opticore-webapp 1.0.69 → 1.0.70

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.
package/dist/index.cjs CHANGED
@@ -39,107 +39,25 @@ module.exports = __toCommonJS(index_exports);
39
39
  var path2 = __toESM(require("path"), 1);
40
40
  var import_node_process3 = __toESM(require("process"), 1);
41
41
  var import_cors = __toESM(require("cors"), 1);
42
- var import_express = __toESM(require("express"), 1);
43
- var import_chokidar = __toESM(require("chokidar"), 1);
44
42
  var import_opticore_catch_exception_error3 = require("opticore-catch-exception-error");
43
+ var import_opticore_express2 = require("opticore-express");
45
44
  var import_opticore_env_access2 = require("opticore-env-access");
46
- var import_opticore_request_call_event = require("opticore-request-call-event");
47
- var import_opticore_dependency_inject2 = require("opticore-dependency-inject");
48
45
  var import_opticore_http_response3 = require("opticore-http-response");
49
46
  var import_opticore_translator2 = require("opticore-translator");
47
+ var import_opticore_request_call_event = require("opticore-request-call-event");
50
48
 
51
49
  // src/core/handlers/eventProcess.handler.ts
52
50
  var import_node_process = __toESM(require("process"), 1);
53
51
  var import_node_events = __toESM(require("events"), 1);
52
+ var import_opticore_express = require("opticore-express");
54
53
  var import_opticore_catch_exception_error = require("opticore-catch-exception-error");
55
-
56
- // src/utils/isTransformError.utils.ts
57
- var isTransformErrorUtils = (error) => {
58
- return error?.name === "TransformError" || error?.message?.includes("Transform failed") || error?.message?.includes("esbuild");
59
- };
60
-
61
- // src/core/handlers/eventProcess.handler.ts
62
- function eventProcessHandler(localeLanguage, expressApp) {
54
+ function eventProcessHandler(localeLanguage) {
63
55
  const errorEmitter = new import_node_events.default();
56
+ const app = (0, import_opticore_express.express)();
64
57
  const serverListenEvent = new import_opticore_catch_exception_error.ServerListenEventError(localeLanguage);
65
- console.log("[Server] Setting up error event handlers...");
66
58
  errorEmitter.on(import_opticore_catch_exception_error.CEventNameError.error, (error) => {
67
- console.error("[Server] EventEmitter error caught:", error.message);
68
- if (isTransformErrorUtils(error)) {
69
- handleTransformError(error);
70
- }
71
59
  serverListenEvent.listenerError(error);
72
60
  });
73
- function handleTransformError(error) {
74
- console.error("[Server] ============================================");
75
- console.error("[Server] TRANSFORM ERROR DETECTED");
76
- console.error("[Server] ============================================");
77
- console.error("[Server] Message:", error.message);
78
- console.error("[Server] Stack:", error.stack);
79
- if (error.errors && Array.isArray(error.errors)) {
80
- error.errors.forEach((err, index) => {
81
- console.error(`[Server] Error ${index + 1}:`, err.text);
82
- if (err.location) {
83
- console.error(`[Server] File: ${err.location.file}`);
84
- console.error(`[Server] Line: ${err.location.line}, Column: ${err.location.column}`);
85
- }
86
- });
87
- }
88
- const fileMatch = error.message.match(/([^:]+\.ts):(\d+):(\d+):/);
89
- if (fileMatch) {
90
- console.error("[Server] Problem file:", fileMatch[1]);
91
- console.error("[Server] Line:", fileMatch[2], "Column:", fileMatch[3]);
92
- }
93
- const errorDetailMatch = error.message.match(/ERROR: (.+)$/m);
94
- if (errorDetailMatch) {
95
- console.error("[Server] Error detail:", errorDetailMatch[1]);
96
- }
97
- console.error("[Server] ============================================");
98
- if (import_node_process.default.send) {
99
- import_node_process.default.send({
100
- type: "TRANSFORM_ERROR",
101
- error: error.message,
102
- stack: error.stack,
103
- errorName: error.name,
104
- details: error.errors,
105
- timestamp: Date.now()
106
- });
107
- }
108
- }
109
- import_node_process.default.on(import_opticore_catch_exception_error.CEvent.uncaughtException, (error) => {
110
- console.error("[Server] UNCAUGHT EXCEPTION:", error.message);
111
- console.error("[Server] Stack:", error.stack);
112
- if (isTransformErrorUtils(error)) {
113
- errorEmitter.emit("transformError", error);
114
- }
115
- serverListenEvent.uncaughtException(error);
116
- if (import_node_process.default.send) {
117
- const messageType = isTransformErrorUtils(error) ? "TRANSFORM_ERROR" : "HOT_RELOAD_ERROR";
118
- import_node_process.default.send({
119
- type: messageType,
120
- error: error.message,
121
- stack: error.stack,
122
- errorName: error.name,
123
- timestamp: Date.now()
124
- });
125
- }
126
- });
127
- import_node_process.default.on(import_opticore_catch_exception_error.CEvent.unhandledRejection, (reason, promise) => {
128
- console.error("[Server] UNHANDLED REJECTION:", reason);
129
- if (isTransformErrorUtils(reason)) {
130
- errorEmitter.emit("transformError", reason);
131
- }
132
- serverListenEvent.unhandledRejection(reason, promise);
133
- if (import_node_process.default.send) {
134
- const messageType = isTransformErrorUtils(reason) ? "TRANSFORM_ERROR" : "HOT_RELOAD_ERROR";
135
- import_node_process.default.send({
136
- type: messageType,
137
- error: reason?.message || String(reason),
138
- errorName: reason?.name,
139
- timestamp: Date.now()
140
- });
141
- }
142
- });
143
61
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.beforeExit, (code) => {
144
62
  setTimeout(() => {
145
63
  serverListenEvent.processBeforeExit(code);
@@ -154,20 +72,20 @@ function eventProcessHandler(localeLanguage, expressApp) {
154
72
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.rejectionHandled, (promise) => {
155
73
  serverListenEvent.promiseRejectionHandled(promise);
156
74
  });
75
+ import_node_process.default.on(import_opticore_catch_exception_error.CEvent.uncaughtException, (error) => {
76
+ serverListenEvent.uncaughtException(error);
77
+ });
157
78
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.uncaughtExceptionMonitor, (error) => {
158
- console.error("[Server] UNCAUGHT EXCEPTION MONITOR:", error.message);
159
- if (isTransformErrorUtils(error)) {
160
- errorEmitter.emit("transformError", error);
161
- }
162
79
  serverListenEvent.uncaughtExceptionMonitor(error);
163
80
  });
81
+ import_node_process.default.on(import_opticore_catch_exception_error.CEvent.unhandledRejection, (reason, promise) => {
82
+ serverListenEvent.unhandledRejection(reason, promise);
83
+ });
164
84
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.warning, (warning) => {
165
85
  serverListenEvent.warning(warning);
166
86
  });
167
87
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.message, (message) => {
168
- if (message.type !== "HOT_RELOAD_REQUEST" && message.type !== "SERVER_READY") {
169
- serverListenEvent.message(message);
170
- }
88
+ serverListenEvent.message(message);
171
89
  });
172
90
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.multipleResolves, (type, promise, reason) => {
173
91
  serverListenEvent.multipleResolves(type, promise, reason);
@@ -178,15 +96,9 @@ function eventProcessHandler(localeLanguage, expressApp) {
178
96
  import_node_process.default.on(import_opticore_catch_exception_error.CEvent.sigterm, (signal) => {
179
97
  serverListenEvent.sigtermSignalReceived(signal);
180
98
  });
181
- expressApp.use((err, req, res, next) => {
182
- console.error("[Server] Express error middleware triggered:", err.message);
183
- console.error("[Server] Request URL:", req.url);
184
- console.error("[Server] Request method:", req.method);
185
- errorEmitter.emit(import_opticore_catch_exception_error.CEventNameError.error, err);
99
+ app.use((err, req, res, next) => {
186
100
  serverListenEvent.expressErrorHandlingMiddleware(errorEmitter, err, req, res, next);
187
101
  });
188
- console.log("[Server] Error event handlers configured successfully");
189
- return errorEmitter;
190
102
  }
191
103
 
192
104
  // src/application/service/core.service.ts
@@ -237,21 +149,6 @@ var dependenciesContainerProvider = (localLang) => {
237
149
  return new import_opticore_dependency_inject.SContainer(localLang, dependencies);
238
150
  };
239
151
 
240
- // src/application/service/core.service.ts
241
- var import_opticore_logger2 = require("opticore-logger");
242
-
243
- // src/application/service/logger.service.ts
244
- var SLogger = (localLang) => {
245
- return {
246
- get serverLog() {
247
- return dependenciesContainerProvider(localLang).resolve("OpticoreLogger");
248
- },
249
- get logger() {
250
- return dependenciesContainerProvider(localLang).resolve("LoggerCore");
251
- }
252
- };
253
- };
254
-
255
152
  // src/application/service/core.service.ts
256
153
  var CoreService = class {
257
154
  localLanguage;
@@ -259,9 +156,9 @@ var CoreService = class {
259
156
  serverLog;
260
157
  logger;
261
158
  constructor(localLang, environmentPath) {
159
+ this.loadTranslationFiles();
262
160
  this.environmentPath = environmentPath;
263
161
  this.localLanguage = localLang;
264
- loaderTranslationFile(this.localLanguage);
265
162
  this.serverLog = dependenciesContainerProvider(localLang).resolve("OpticoreLogger");
266
163
  this.logger = dependenciesContainerProvider(localLang).resolve("LoggerCore");
267
164
  }
@@ -275,6 +172,41 @@ var CoreService = class {
275
172
  formatMemoryUsage(data) {
276
173
  return `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
277
174
  }
175
+ loadTranslationFiles() {
176
+ loaderTranslationFile(this.localLanguage);
177
+ }
178
+ /**
179
+ *
180
+ * @param filePath
181
+ * @private
182
+ *
183
+ * Return void
184
+ */
185
+ getEnvFileLoading(filePath) {
186
+ this.loadTranslationFiles();
187
+ try {
188
+ const fullPath = path.resolve(import_node_process2.default.cwd(), filePath);
189
+ if (fs.existsSync(fullPath)) {
190
+ const env = fs.readFileSync(fullPath, "utf-8");
191
+ const lines = env.split("\n");
192
+ lines.forEach((line) => {
193
+ const match = line.match(/^([^#=]+)=([^#]+)$/);
194
+ if (match) {
195
+ const key = match[1].trim();
196
+ import_node_process2.default.env[key] = match[2].trim();
197
+ }
198
+ });
199
+ }
200
+ } catch (err) {
201
+ this.logger.error({
202
+ message: err.message,
203
+ title: import_opticore_translator.TranslationLoader.t("EnvFileLoading", this.localLanguage),
204
+ errorType: err.code,
205
+ stackTrace: err.stack,
206
+ httpCodeValue: import_opticore_http_response.HttpStatusCode.INTERNAL_SERVER_ERROR
207
+ });
208
+ }
209
+ }
278
210
  /**
279
211
  * Returns an Object containing a node version, openssl, and v0
280
212
  */
@@ -299,7 +231,7 @@ var CoreService = class {
299
231
  * and Memory usage system
300
232
  */
301
233
  getUsageMemory() {
302
- loaderTranslationFile(this.localLanguage);
234
+ this.loadTranslationFiles();
303
235
  const memoryData = import_node_process2.default.memoryUsage();
304
236
  const data = {
305
237
  [import_opticore_translator.TranslationLoader.t("totalMemoryAllocated", this.localLanguage)]: this.formatMemoryUsage(memoryData.rss),
@@ -331,37 +263,6 @@ var CoreService = class {
331
263
  "startingTime": `${executionTime.toFixed(5)} ms`
332
264
  };
333
265
  }
334
- /**
335
- *
336
- * @param filePath
337
- * @private
338
- *
339
- * Return void
340
- */
341
- getEnvFileLoading(filePath) {
342
- try {
343
- const fullPath = path.resolve(import_node_process2.default.cwd(), filePath);
344
- if (fs.existsSync(fullPath)) {
345
- const env = fs.readFileSync(fullPath, "utf-8");
346
- const lines = env.split("\n");
347
- lines.forEach((line) => {
348
- const match = line.match(/^([^#=]+)=([^#]+)$/);
349
- if (match) {
350
- const key = match[1].trim();
351
- import_node_process2.default.env[key] = match[2].trim();
352
- }
353
- });
354
- }
355
- } catch (err) {
356
- this.logger.error({
357
- message: err.message,
358
- title: import_opticore_translator.TranslationLoader.t("EnvFileLoading", this.localLanguage),
359
- errorType: err.code,
360
- stackTrace: err.stack,
361
- httpCodeValue: import_opticore_http_response.HttpStatusCode.INTERNAL_SERVER_ERROR
362
- });
363
- }
364
- }
365
266
  /**
366
267
  *
367
268
  * @param development
@@ -370,14 +271,15 @@ var CoreService = class {
370
271
  * Return string
371
272
  */
372
273
  getServerRunningMode(development, production) {
274
+ this.loadTranslationFiles();
373
275
  try {
374
- loaderTranslationFile(this.localLanguage);
375
276
  this.getEnvFileLoading(".env");
376
- const env = (0, import_opticore_env_access.getEnvironnementValue)(path.join(envPath));
377
- const isDevelopment = env.devEnv === development && env.prodEnv === "";
277
+ const env = (0, import_opticore_env_access.getEnvironmentValue)(path.join(envPath));
278
+ const isDevelopment = env.devEnv === development;
279
+ const isProd = env.prodEnv === production;
378
280
  if (isDevelopment) {
379
281
  return `${import_opticore_translator.TranslationLoader.t("serverRunning", this.localLanguage)} ${import_ansi_colors.default.bgBlue(`${import_ansi_colors.default.bold(`${development}`)}`)} mode`;
380
- } else if (!isDevelopment) {
282
+ } else if (isProd) {
381
283
  return `${import_opticore_translator.TranslationLoader.t("serverRunning", this.localLanguage)} ${import_ansi_colors.default.bgBlue(`${import_ansi_colors.default.bold(`${production}`)}`)} mode`;
382
284
  } else {
383
285
  return `${import_opticore_translator.TranslationLoader.t("serverRunning", this.localLanguage)} ${import_ansi_colors.default.bgBlue(`${import_ansi_colors.default.bold(`${development}`)}`)} mode`;
@@ -393,9 +295,9 @@ var CoreService = class {
393
295
  }
394
296
  }
395
297
  infoServer(host, port) {
298
+ this.loadTranslationFiles();
396
299
  try {
397
- loaderTranslationFile(this.localLanguage);
398
- const getEnvironment = (0, import_opticore_env_access.getEnvironnementValue)(this.environmentPath);
300
+ const getEnvironment = (0, import_opticore_env_access.getEnvironmentValue)(this.environmentPath);
399
301
  const msg5 = getEnvironment.protocolTransfert === "" ? import_ansi_colors.default.underline(`http://${host}:${port}`) : import_ansi_colors.default.underline(`${getEnvironment.protocolTransfert}://${host}:${port}`);
400
302
  const messages = [
401
303
  import_opticore_translator.TranslationLoader.t("webServerListening", this.localLanguage),
@@ -416,12 +318,11 @@ var CoreService = class {
416
318
  });
417
319
  console.log(border);
418
320
  console.log("\n");
419
- const logCore = new import_opticore_logger2.LoggerCore();
420
- logCore.success({
321
+ this.logger.success({
421
322
  title: import_opticore_translator.TranslationLoader.t("serverRunningTitle", this.localLanguage),
422
323
  message: import_opticore_translator.TranslationLoader.t("serverRunningAt", this.localLanguage, { server: msg5 })
423
324
  });
424
- SLogger(this.localLanguage).serverLog.serverLog({
325
+ this.serverLog.serverLog({
425
326
  timestamp: (/* @__PURE__ */ new Date()).toString(),
426
327
  level: "SERVER",
427
328
  title: import_opticore_translator.TranslationLoader.t("serverRunningTitle", this.localLanguage),
@@ -429,7 +330,7 @@ var CoreService = class {
429
330
  message: import_opticore_translator.TranslationLoader.t("serverRunningAt", this.localLanguage, { server: msg5 })
430
331
  });
431
332
  } catch (err) {
432
- SLogger(this.localLanguage).logger.error({
333
+ this.logger.error({
433
334
  message: err.message,
434
335
  title: import_opticore_translator.TranslationLoader.t("server", this.localLanguage),
435
336
  errorType: err.code,
@@ -445,6 +346,20 @@ var dateTimeFormattedUtils = `${(/* @__PURE__ */ new Date()).getMonth()}-${(/* @
445
346
 
446
347
  // src/application/service/serverStartError.service.ts
447
348
  var import_opticore_catch_exception_error2 = require("opticore-catch-exception-error");
349
+
350
+ // src/application/service/logger.service.ts
351
+ var SLogger = (localLang) => {
352
+ return {
353
+ get serverLog() {
354
+ return dependenciesContainerProvider(localLang).resolve("OpticoreLogger");
355
+ },
356
+ get logger() {
357
+ return dependenciesContainerProvider(localLang).resolve("LoggerCore");
358
+ }
359
+ };
360
+ };
361
+
362
+ // src/application/service/serverStartError.service.ts
448
363
  var import_opticore_http_response2 = require("opticore-http-response");
449
364
  var SServerStartError = (err, environmentPath) => {
450
365
  if (err.name) {
@@ -477,390 +392,108 @@ var SServerStartError = (err, environmentPath) => {
477
392
  };
478
393
 
479
394
  // src/core/webServer.core.ts
395
+ var import_opticore_dependency_inject2 = require("opticore-dependency-inject");
480
396
  var WebServerCore = class {
481
397
  serverUtility;
482
- expressApp;
398
+ expressApp = (0, import_opticore_express2.express)();
483
399
  localLanguage;
484
400
  loggerConfig;
485
- getEnvironment;
401
+ routerExpressApp;
402
+ getEnvironmentValue;
486
403
  environmentPath;
487
404
  serverListenEvent;
488
- // Existing properties
489
- currentRoutes = [];
490
- currentDependencies = [];
491
- server = void 0;
492
- errorEmitter;
493
- serverStatus = "STARTING";
494
- serverStartTime = /* @__PURE__ */ new Date();
495
- // HMR properties
496
- fileWatcher = null;
497
- hmrRestartPending = false;
498
- hmrDebounceTimeout = null;
499
- hmrRestartCount = 0;
500
- lastHmrRestartTime = 0;
501
- /**
502
- * Creates a new WebServerCore instance.
503
- *
504
- * @constructor
505
- * @param {WebServerConstructorInterface} paramsConstructor - Configuration parameters
506
- *
507
- * @param {express.Application} paramsConstructor.app - Express application instance
508
- * @param {LoggerCore} paramsConstructor.loggerConfig - Logger configuration
509
- * @param {string} paramsConstructor.environmentPath - Path to environment file
510
- * @param {string} paramsConstructor.localLanguage - Default language for translations
511
- * @param {CorsOptions} paramsConstructor.corsOriginOptions - CORS configuration
512
- *
513
- * @returns {WebServerCore} New WebServerCore instance
514
- *
515
- * @throws {Error} If environment file cannot be loaded
516
- *
517
- * @example
518
- * ```typescript
519
- * const server = new WebServerCore({
520
- * app: express(),
521
- * loggerConfig: new LoggerCore(config),
522
- * environmentPath: ".env",
523
- * localLanguage: "fr",
524
- * corsOriginOptions: { origin: "http://localhost:3000" }
525
- * });
526
- * ```
527
- */
405
+ dependenciesRegistered = false;
528
406
  constructor(paramsConstructor) {
529
- this.getEnvironment = (0, import_opticore_env_access2.getEnvironmentValue)(paramsConstructor.environmentPath);
407
+ this.loadTranslationFiles();
408
+ this.stackTraceErrorHandling();
409
+ this.getEnvironmentValue = (0, import_opticore_env_access2.getEnvironmentValue)(paramsConstructor.environmentPath);
410
+ this.routerExpressApp = paramsConstructor.app;
530
411
  this.loggerConfig = paramsConstructor.loggerConfig;
531
412
  this.localLanguage = paramsConstructor.localLanguage;
532
413
  this.environmentPath = paramsConstructor.environmentPath;
533
- this.expressApp = (0, import_express.default)();
534
- this.serverListenEvent = new import_opticore_catch_exception_error3.ServerListenEventError(paramsConstructor.localLanguage);
535
- this.expressApp.use(import_express.default.json());
536
- this.expressApp.use(import_express.default.raw());
537
- this.expressApp.use(import_express.default.text());
538
- this.expressApp.use(import_express.default.urlencoded({ extended: true }));
414
+ this.expressApp.use(import_opticore_express2.express.json());
415
+ this.expressApp.use(import_opticore_express2.express.raw());
416
+ this.expressApp.use(import_opticore_express2.express.text());
417
+ this.expressApp.use(import_opticore_express2.express.urlencoded({ extended: true }));
539
418
  this.expressApp.use((0, import_cors.default)(paramsConstructor.corsOriginOptions));
419
+ this.serverListenEvent = new import_opticore_catch_exception_error3.ServerListenEventError(paramsConstructor.localLanguage);
540
420
  this.serverUtility = new CoreService(paramsConstructor.localLanguage, paramsConstructor.environmentPath);
541
- this.serverStatus = "STARTING";
542
- this.serverStartTime = /* @__PURE__ */ new Date();
543
- this.setupProcessEventListeners();
544
421
  }
545
- /**
546
- * Starts the HTTP server and initializes all components including HMR if enabled.
547
- *
548
- * @method onStartServer
549
- * @public
550
- *
551
- * @param {TFeatureRoutes[]} routers - Array of feature routes to register
552
- * @param {(env: IEnvVariables) => void} [databaseCallback] - Optional database connection callback
553
- * @param {TDependency[]} [dependenciesProvider] - Optional dependency injection providers
554
- *
555
- * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
556
- *
557
- * @throws {ServerListenEventError} If port/host configuration is invalid
558
- * @throws {Error} If server initialization fails
559
- *
560
- * @fires WebServerCore#startHttpServer - When server successfully starts
561
- * @fires WebServerCore#startHMR - When HMR is started (if enabled)
562
- * @fires WebServerCore#serverError - When server fails to start
563
- *
564
- * @example
565
- * ```typescript
566
- * const server = app.onStartServer(
567
- * routes,
568
- * (env) => connectToDatabase(env),
569
- * dependencies
570
- * );
571
- *
572
- * if (server) {
573
- * console.log("Server started successfully");
574
- * }
575
- * ```
576
- */
577
- onStartServer(routers, databaseCallback, dependenciesProvider) {
422
+ registerDependencies(dependencies2) {
578
423
  try {
579
- loaderTranslationFile(this.localLanguage);
580
- this.currentRoutes = routers;
581
- this.currentDependencies = dependenciesProvider || [];
582
- this.serverStartTime = /* @__PURE__ */ new Date();
583
- this.serverStatus = "STARTING";
584
- if (!this.validateServerParameters()) {
585
- return void 0;
586
- }
587
- const server = this.startHttpServer(databaseCallback);
588
- if (this.getEnvironment.hmrEnabled) {
589
- this.startHMR();
424
+ if (dependencies2 && dependencies2.length > 0) {
425
+ dependencies2.forEach((dependency) => {
426
+ return new import_opticore_dependency_inject2.SContainer(this.localLanguage).register(dependency.key, dependency.factory, dependency.scope);
427
+ });
428
+ } else {
429
+ SLogger(this.environmentPath).logger.info({
430
+ message: import_opticore_translator2.TranslationLoader.t("NO_REGISTER_DEPENDENCIES", this.localLanguage),
431
+ title: import_opticore_translator2.TranslationLoader.t("REGISTER_DEPENDENCIES", this.localLanguage)
432
+ });
590
433
  }
591
- return server;
592
- } catch (error) {
593
- this.handleStartupError(error);
434
+ } catch (err) {
435
+ SLogger(this.environmentPath).logger.error({
436
+ message: err.message,
437
+ title: "Register Dependencies",
438
+ errorType: err.code,
439
+ stackTrace: err.stack,
440
+ httpCodeValue: import_opticore_http_response3.HttpStatusCode.INTERNAL_SERVER_ERROR
441
+ });
594
442
  }
595
443
  }
596
- /**
597
- * Validates server configuration parameters.
598
- *
599
- * @method validateServerParameters
600
- * @private
601
- *
602
- * @returns {boolean} True if all parameters are valid, false otherwise
603
- *
604
- * @remarks
605
- * Validates:
606
- * - Port number is valid and positive
607
- * - Host is not empty
608
- * - Local language is specified
609
- * - HMR configuration (if enabled)
610
- */
611
- validateServerParameters() {
612
- loaderTranslationFile(this.localLanguage);
613
- const port = Number(this.getEnvironment.appPort);
614
- if (isNaN(port) || port <= 0) {
444
+ onStartServer(routers, databaseCallback, dependenciesProvider) {
445
+ this.loadTranslationFiles();
446
+ if (this.getEnvironmentValue.appPort === "" && Number(this.getEnvironmentValue.appPort) === 0) {
447
+ this.serverListenEvent.hostPortUndefined(Number(this.getEnvironmentValue.appPort));
448
+ } else if (this.getEnvironmentValue.appHost === "") {
449
+ this.serverListenEvent.hostUndefined(this.getEnvironmentValue.appHost);
450
+ } else if (Number(this.getEnvironmentValue.appPort) === 0) {
615
451
  this.serverListenEvent.portUndefined();
616
- return false;
617
- }
618
- if (!this.getEnvironment.appHost || this.getEnvironment.appHost.trim() === "") {
619
- this.serverListenEvent.hostUndefined(this.getEnvironment.appHost);
620
- return false;
621
- }
622
- if (!this.localLanguage || this.localLanguage.trim() === "") {
623
- SLogger(this.localLanguage).logger.error({
452
+ } else if (this.localLanguage === "") {
453
+ SLogger(this.environmentPath).logger.error({
624
454
  message: import_opticore_translator2.TranslationLoader.t("noDefaultLocalLang", this.localLanguage),
625
455
  title: import_opticore_translator2.TranslationLoader.t("noLocalLang", this.localLanguage),
626
456
  errorType: import_opticore_translator2.TranslationLoader.t("localLangMissing", this.localLanguage),
627
457
  stackTrace: void 0,
628
458
  httpCodeValue: import_opticore_http_response3.HttpStatusCode.NOT_FOUND
629
459
  });
630
- return false;
631
- }
632
- if (this.getEnvironment.hmrEnabled) {
633
- if (!this.getEnvironment.hmrWatchPatterns || this.getEnvironment.hmrWatchPatterns.length === 0) {
634
- SLogger(this.localLanguage).logger.warn({
635
- title: import_opticore_translator2.TranslationLoader.t("HMR_CONFIG_WARNING", this.localLanguage),
636
- message: "HMR enabled but no watch patterns defined"
637
- });
638
- }
639
- }
640
- return true;
641
- }
642
- /**
643
- * Starts the HTTP server and sets up event listeners.
644
- *
645
- * @method startHttpServer
646
- * @private
647
- *
648
- * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
649
- *
650
- * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
651
- *
652
- * @throws {Error} If server fails to start
653
- */
654
- startHttpServer(databaseCallback) {
655
- try {
656
- loaderTranslationFile(this.localLanguage);
657
- const port = Number(this.getEnvironment.appPort);
658
- const host = this.getEnvironment.appHost;
659
- this.server = this.expressApp.listen(port, host, () => {
660
- try {
661
- this.configureServerComponents(databaseCallback);
662
- this.serverStatus = "READY";
663
- SLogger(this.localLanguage).logger.info({
664
- title: import_opticore_translator2.TranslationLoader.t("SERVER_RUNNING_TITLE", this.localLanguage),
665
- message: import_opticore_translator2.TranslationLoader.t("SERVER_RUNNING_AT", this.localLanguage, {
666
- server: `${host}:${port}`,
667
- hmrEnabled: this.getEnvironment.hmrEnabled ? "with HMR" : "without HMR"
668
- })
669
- });
670
- } catch (err) {
671
- this.handleServerConfigurationError(err);
672
- }
673
- });
674
- this.setupServerEventListeners();
675
- return this.server;
676
- } catch (error) {
677
- this.serverListenEvent.onEventError(
678
- new Error(import_opticore_translator2.TranslationLoader.t(
679
- "HTTP_SERVER_FAILED",
680
- this.localLanguage,
681
- { errorMessage: error.message }
682
- ))
683
- );
684
- }
685
- }
686
- /**
687
- * Configures server components (database, dependencies, routes, etc.).
688
- *
689
- * @method configureServerComponents
690
- * @private
691
- *
692
- * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
693
- *
694
- * @returns {void}
695
- *
696
- * @throws {Error} If component configuration fails
697
- */
698
- configureServerComponents(databaseCallback) {
699
- try {
700
- loaderTranslationFile(this.localLanguage);
701
- if (databaseCallback && typeof databaseCallback === "function") {
702
- try {
703
- databaseCallback(this.getEnvironment);
704
- } catch (dbError) {
705
- this.serverListenEvent.listenerError(
706
- new Error(import_opticore_translator2.TranslationLoader.t("DB_CON_FAILED", this.localLanguage, { dbErrorMessage: dbError.message }))
707
- );
460
+ } else {
461
+ return this.expressApp.listen(
462
+ Number(this.getEnvironmentValue.appPort),
463
+ () => {
464
+ this.loadTranslationFiles();
465
+ try {
466
+ databaseCallback(this.getEnvironmentValue);
467
+ new import_opticore_dependency_inject2.SContainer(this.localLanguage, dependenciesProvider);
468
+ this.expressApp.use(import_opticore_express2.express.static(path2.join(import_node_process3.default.cwd(), "public/template")));
469
+ this.registerRoutes(routers);
470
+ } catch (err) {
471
+ SServerStartError(err, this.environmentPath);
472
+ }
708
473
  }
709
- }
710
- try {
711
- new import_opticore_dependency_inject2.SContainer(this.localLanguage, this.currentDependencies);
712
- } catch (depError) {
713
- this.serverListenEvent.listenerError(
714
- new Error(import_opticore_translator2.TranslationLoader.t("DEPENDENCY_INJECTION_FAILED", this.localLanguage, { depErrorMessage: depError.message }))
715
- );
716
- }
717
- this.expressApp.use(import_express.default.static(path2.join(import_node_process3.default.cwd(), "public/template")));
718
- this.registerRoutes(this.currentRoutes);
719
- this.setupErrorHandling();
720
- this.infoWebApp();
721
- } catch (error) {
722
- this.serverListenEvent.listenerError(
723
- new Error(import_opticore_translator2.TranslationLoader.t("SERVER_COMPONENT_CONFIG_FAILED", this.localLanguage, { errorMessage: error.message }))
724
474
  );
725
- throw error;
726
- }
727
- }
728
- /**
729
- * Handles server configuration errors.
730
- *
731
- * @method handleServerConfigurationError
732
- * @private
733
- *
734
- * @param {any} err - The error that occurred
735
- *
736
- * @returns {void}
737
- */
738
- handleServerConfigurationError(err) {
739
- loaderTranslationFile(this.localLanguage);
740
- this.serverStatus = "ERROR";
741
- this.serverListenEvent.onEventError(err);
742
- try {
743
- SServerStartError(err, this.environmentPath);
744
- } catch (startError) {
745
- this.serverListenEvent.listenerError(startError);
746
475
  }
747
476
  }
748
- /**
749
- * Handles general startup errors.
750
- *
751
- * @method handleStartupError
752
- * @private
753
- *
754
- * @param {any} error - The startup error
755
- *
756
- * @returns {void}
757
- */
758
- handleStartupError(error) {
759
- loaderTranslationFile(this.localLanguage);
760
- this.serverStatus = "ERROR";
761
- this.serverListenEvent.listenerError(error);
762
- SLogger(this.localLanguage).logger.error({
763
- title: import_opticore_translator2.TranslationLoader.t("GLOBAL_STARTUP_ERROR", this.localLanguage),
764
- message: error.message,
765
- errorType: error.name || "StartupError",
766
- stackTrace: error.stack,
767
- httpCodeValue: import_opticore_http_response3.HttpStatusCode.INTERNAL_SERVER_ERROR
768
- });
769
- }
770
- /**
771
- * Sets up Node.js process event listeners.
772
- *
773
- * @method setupProcessEventListeners
774
- * @private
775
- *
776
- * @returns {void}
777
- *
778
- * @remarks
779
- * Listens for:
780
- * - Process exit events
781
- * - Uncaught exceptions
782
- * - Unhandled rejections
783
- * - System signals (SIGINT, SIGTERM)
784
- */
785
- setupProcessEventListeners() {
786
- loaderTranslationFile(this.localLanguage);
787
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.beforeExit, (code) => {
788
- this.serverListenEvent.processBeforeExit(code);
789
- });
790
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.disconnect, () => {
791
- this.serverListenEvent.processDisconnected();
792
- });
793
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.exit, (code) => {
794
- this.serverListenEvent.exited(code);
795
- });
796
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.message, (message) => {
797
- this.serverListenEvent.message(message);
798
- });
799
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.multipleResolves, (type, promise, reason) => {
800
- this.serverListenEvent.multipleResolves(type, promise, reason);
801
- });
802
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.rejectionHandled, (promise) => {
803
- this.serverListenEvent.promiseRejectionHandled(promise);
804
- });
805
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.uncaughtException, (error) => {
806
- this.serverListenEvent.uncaughtException(error);
807
- });
808
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.uncaughtExceptionMonitor, (error) => {
809
- this.serverListenEvent.uncaughtExceptionMonitor(error);
810
- });
811
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.unhandledRejection, (reason, promise) => {
812
- this.serverListenEvent.unhandledRejection(reason, promise);
813
- });
814
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.warning, (warning) => {
815
- this.serverListenEvent.warning(warning);
816
- });
817
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.sigint, () => {
818
- this.serverListenEvent.processInterrupted();
819
- });
820
- import_node_process3.default.on(import_opticore_catch_exception_error3.CEvent.sigterm, (signal) => {
821
- this.serverListenEvent.sigtermSignalReceived(signal);
822
- });
823
- }
824
- /**
825
- * Sets up HTTP server event listeners.
826
- *
827
- * @method setupServerEventListeners
828
- * @private
829
- *
830
- * @returns {void}
831
- *
832
- * @remarks
833
- * Configures listeners for:
834
- * - Server errors
835
- * - Connection closing
836
- * - Connection dropping
837
- * - HTTP requests (for logging)
838
- *
839
- * @listens Server#error - Server error events
840
- * @listens Server#close - Server closing events
841
- * @listens Server#drop - Connection drop events
842
- * @listens Server#request - HTTP request events
843
- */
844
- setupServerEventListeners() {
845
- loaderTranslationFile(this.localLanguage);
846
- if (!this.server) {
847
- return;
848
- }
849
- this.server.on(import_opticore_catch_exception_error3.CEventNameError.error, (err) => {
477
+ onListeningOnServerEvent(serverWeb) {
478
+ this.loadTranslationFiles();
479
+ serverWeb.on(import_opticore_catch_exception_error3.CEventNameError.error, (err) => {
850
480
  this.serverListenEvent.onEventError(err);
851
- });
852
- this.server.on(import_opticore_catch_exception_error3.CEventNameError.close, () => {
481
+ }).on(import_opticore_catch_exception_error3.CEventNameError.close, () => {
853
482
  this.serverListenEvent.serverClosing();
854
- });
855
- this.server.on(import_opticore_catch_exception_error3.CEventNameError.drop, () => {
483
+ }).on(import_opticore_catch_exception_error3.CEventNameError.drop, () => {
856
484
  this.serverListenEvent.dropNewConnection();
485
+ }).on(import_opticore_catch_exception_error3.CEventNameError.listening, () => {
486
+ this.infoWebApp();
857
487
  });
858
- this.server.on(import_opticore_catch_exception_error3.CEventNameError.request, (req, res) => {
488
+ }
489
+ onRequestOnServerEvent(serverWeb) {
490
+ this.loadTranslationFiles();
491
+ serverWeb.on(import_opticore_catch_exception_error3.CEventNameError.request, (req, res) => {
859
492
  (0, import_opticore_request_call_event.requestCallsEvent)(
860
493
  req,
861
494
  res,
862
- this.getEnvironment.appHost,
863
- Number(this.getEnvironment.appPort),
495
+ this.getEnvironmentValue.appHost,
496
+ Number(this.getEnvironmentValue.appPort),
864
497
  dateTimeFormattedUtils,
865
498
  this.environmentPath,
866
499
  this.localLanguage
@@ -868,623 +501,41 @@ var WebServerCore = class {
868
501
  });
869
502
  }
870
503
  /**
871
- * Sets up error handling middleware and event emitters.
872
504
  *
873
- * @method setupErrorHandling
874
505
  * @private
875
- *
876
- * @returns {void}
877
506
  */
878
- setupErrorHandling() {
507
+ loadTranslationFiles() {
879
508
  loaderTranslationFile(this.localLanguage);
880
- SLogger(this.localLanguage).logger.info({
881
- title: import_opticore_translator2.TranslationLoader.t("SETTING_UP", this.localLanguage),
882
- message: import_opticore_translator2.TranslationLoader.t("SETTING_UP_ERROR", this.localLanguage)
883
- });
884
- this.errorEmitter = eventProcessHandler(this.localLanguage, this.expressApp);
885
- if (this.errorEmitter) {
886
- this.expressApp.use((err, req, res, next) => {
887
- this.serverListenEvent.expressErrorHandlingMiddleware(
888
- this.errorEmitter,
889
- err,
890
- req,
891
- res,
892
- next
893
- );
894
- });
895
- this.errorEmitter.on("transformError", (error) => {
896
- this.serverListenEvent.listenerError(error);
897
- });
898
- this.errorEmitter.on("error", (error) => {
899
- this.serverListenEvent.listenerError(error);
900
- });
901
- this.errorEmitter.on("hotReload", (data) => {
902
- SLogger(this.localLanguage).logger.info({
903
- title: import_opticore_translator2.TranslationLoader.t("HOT_RELOAD_EVENT", this.localLanguage),
904
- message: `Hot reload triggered for ${data.file}`
905
- });
906
- });
907
- }
908
- SLogger(this.localLanguage).logger.info({
909
- title: import_opticore_translator2.TranslationLoader.t("ERROR_HANDLING", this.localLanguage),
910
- message: import_opticore_translator2.TranslationLoader.t("ERROR_HANDLING_CONFIGURED", this.localLanguage)
911
- });
912
509
  }
913
510
  /**
914
- * Registers routes with the Express application.
915
511
  *
916
- * @method registerRoutes
512
+ * @param allFeatureRoutes
917
513
  * @private
918
- *
919
- * @param {any[]} allFeatureRoutes - Array of feature routes to register
920
- *
921
- * @returns {void}
922
514
  */
923
515
  registerRoutes(allFeatureRoutes) {
924
- allFeatureRoutes.forEach((router) => {
925
- if (router.routes) {
926
- router.routes.forEach((route) => {
927
- this.expressApp.use(route.path, route.handler);
928
- });
929
- }
930
- });
931
- }
932
- /**
933
- * Displays server information.
934
- *
935
- * @method infoWebApp
936
- * @private
937
- *
938
- * @returns {void}
939
- */
940
- infoWebApp() {
941
- loaderTranslationFile(this.localLanguage);
942
- this.serverUtility.infoServer(
943
- this.getEnvironment.appHost,
944
- Number(this.getEnvironment.appPort)
945
- );
946
- }
947
- /**
948
- * Starts the Hot Module Replacement (HMR) file watching system.
949
- *
950
- * @method startHMR
951
- * @private
952
- *
953
- * @returns {void}
954
- *
955
- * @remarks
956
- * Configures file watcher based on environment variables:
957
- * - HMR_ENABLED: Enable/disable HMR
958
- * - HMR_WATCH_PATTERNS: Files to watch
959
- * - HMR_IGNORE_PATTERNS: Files to ignore
960
- *
961
- * @throws {Error} If HMR configuration is invalid
962
- */
963
- startHMR() {
964
- try {
965
- loaderTranslationFile(this.localLanguage);
966
- const hmrConfig = this.getEnvironment;
967
- if (!hmrConfig.hmrEnabled) {
968
- SLogger(this.localLanguage).logger.info({
969
- title: import_opticore_translator2.TranslationLoader.t("HMR_DISABLED", this.localLanguage),
970
- message: "HMR is disabled in configuration"
971
- });
972
- return;
973
- }
974
- if (!hmrConfig.hmrWatchPatterns || hmrConfig.hmrWatchPatterns.length === 0) {
975
- SLogger(this.localLanguage).logger.error({
976
- title: import_opticore_translator2.TranslationLoader.t("HMR_WATCH_PATTERNS_MISSING", this.localLanguage),
977
- message: "No watch patterns defined for HMR",
978
- errorType: "HMR Configuration Error",
979
- httpCodeValue: import_opticore_http_response3.HttpStatusCode.BAD_REQUEST
980
- });
981
- return;
982
- }
983
- const watchPatterns = hmrConfig.hmrWatchPatterns;
984
- const ignorePatterns = hmrConfig.hmrIgnorePatterns || [
985
- "node_modules/**",
986
- "dist/**",
987
- "build/**",
988
- "*.log",
989
- ".git/**"
990
- ];
991
- const allPatterns = [
992
- ...watchPatterns,
993
- ...ignorePatterns.map((pattern) => `!${pattern}`)
994
- ];
995
- this.fileWatcher = import_chokidar.default.watch(allPatterns, {
996
- ignored: /(^|[/\\])\../,
997
- persistent: true,
998
- ignoreInitial: true,
999
- awaitWriteFinish: {
1000
- stabilityThreshold: 300,
1001
- pollInterval: 100
1002
- },
1003
- cwd: import_node_process3.default.cwd(),
1004
- depth: 10
1005
- });
1006
- this.fileWatcher.on("ready", () => this.onHMRWatcherReady(watchPatterns, ignorePatterns)).on("change", (filePath) => this.handleFileChange(filePath)).on("add", (filePath) => this.handleFileChange(filePath, "added")).on("unlink", (filePath) => this.handleFileChange(filePath, "deleted")).on("error", (error) => this.onHMRWatcherError(error));
1007
- this.hmrRestartCount = 0;
1008
- this.lastHmrRestartTime = Date.now();
1009
- SLogger(this.localLanguage).logger.info({
1010
- title: import_opticore_translator2.TranslationLoader.t("HMR_STARTED", this.localLanguage),
1011
- message: import_opticore_translator2.TranslationLoader.t("HMR_MONITORING_STARTED", this.localLanguage)
1012
- });
1013
- } catch (error) {
1014
- SLogger(this.localLanguage).logger.error({
1015
- title: import_opticore_translator2.TranslationLoader.t("HMR_START_FAILED", this.localLanguage),
1016
- message: error.message,
1017
- errorType: "HMR Error",
1018
- stackTrace: error.stack
1019
- });
1020
- }
1021
- }
1022
- /**
1023
- * Handles file change events with debouncing.
1024
- *
1025
- * @method handleFileChange
1026
- * @private
1027
- *
1028
- * @param {string} filePath - Path of the changed file
1029
- * @param {string} [action="modified"] - Type of file change (modified/added/deleted)
1030
- *
1031
- * @returns {void}
1032
- *
1033
- * @remarks
1034
- * Uses debouncing to prevent multiple rapid reloads.
1035
- * Debounce time configurable via HMR_DEBOUNCE_MS environment variable.
1036
- */
1037
- handleFileChange(filePath, action = "modified") {
1038
- const debounceMs = this.getEnvironment.hmrDebounceMs || 500;
1039
- if (this.hmrDebounceTimeout) {
1040
- clearTimeout(this.hmrDebounceTimeout);
1041
- }
1042
- this.hmrDebounceTimeout = setTimeout(async () => {
1043
- await this.triggerHotReload(filePath, action);
1044
- }, debounceMs);
1045
- SLogger(this.localLanguage).logger.info({
1046
- title: import_opticore_translator2.TranslationLoader.t("FILE_CHANGE_DETECTED", this.localLanguage),
1047
- message: `File ${action}: ${filePath}`
1048
- });
1049
- }
1050
- /**
1051
- * Triggers a hot reload operation.
1052
- *
1053
- * @method triggerHotReload
1054
- * @private
1055
- *
1056
- * @param {string} filePath - Path of the changed file
1057
- * @param {string} action - Type of file change
1058
- *
1059
- * @returns {Promise<void>}
1060
- *
1061
- * @remarks
1062
- * - Checks if reload is already in progress
1063
- * - Validates restart limits
1064
- * - Performs appropriate reload actions based on file type
1065
- * - Emits hotReload event
1066
- */
1067
- async triggerHotReload(filePath, action) {
1068
- if (this.hmrRestartPending) {
1069
- return;
1070
- }
1071
- if (!this.canProceedWithHMRRestart()) {
1072
- return;
1073
- }
1074
- this.hmrRestartPending = true;
1075
- this.hmrRestartCount++;
1076
- this.lastHmrRestartTime = Date.now();
1077
- try {
1078
- loaderTranslationFile(this.localLanguage);
1079
- SLogger(this.localLanguage).logger.info({
1080
- title: import_opticore_translator2.TranslationLoader.t("HOT_RELOAD_STARTING", this.localLanguage),
1081
- message: import_opticore_translator2.TranslationLoader.t("RELOADING_APPLICATION", this.localLanguage, {
1082
- file: filePath,
1083
- action
1084
- })
1085
- });
1086
- if (this.errorEmitter) {
1087
- this.errorEmitter.emit("hotReload", {
1088
- file: filePath,
1089
- action,
1090
- timestamp: /* @__PURE__ */ new Date(),
1091
- restartCount: this.hmrRestartCount
1092
- });
1093
- }
1094
- await this.performHotReloadActions(filePath);
1095
- SLogger(this.localLanguage).logger.success({
1096
- title: import_opticore_translator2.TranslationLoader.t("HOT_RELOAD_COMPLETE", this.localLanguage),
1097
- message: import_opticore_translator2.TranslationLoader.t("APPLICATION_RELOADED", this.localLanguage, {
1098
- file: filePath,
1099
- restartCount: this.hmrRestartCount,
1100
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1101
- })
1102
- });
1103
- } catch (error) {
1104
- SLogger(this.localLanguage).logger.error({
1105
- title: import_opticore_translator2.TranslationLoader.t("HOT_RELOAD_FAILED", this.localLanguage),
1106
- message: error.message,
1107
- errorType: "HotReloadError",
1108
- stackTrace: error.stack,
1109
- httpCodeValue: import_opticore_http_response3.HttpStatusCode.INTERNAL_SERVER_ERROR
1110
- });
1111
- } finally {
1112
- this.hmrRestartPending = false;
1113
- }
1114
- }
1115
- /**
1116
- * Performs appropriate hot reload actions based on file type.
1117
- *
1118
- * @method performHotReloadActions
1119
- * @private
1120
- *
1121
- * @param {string} filePath - Path of the changed file
1122
- *
1123
- * @returns {Promise<void>}
1124
- *
1125
- * @remarks
1126
- * Different actions for different file types:
1127
- * - .json/.env: Reload translations
1128
- * - routes/controller files: Reload routes
1129
- * - config/.env files: Reload dependencies
1130
- */
1131
- async performHotReloadActions(filePath) {
1132
- if (filePath.includes(".json") || filePath.endsWith(".env")) {
1133
- loaderTranslationFile(this.localLanguage);
1134
- }
1135
- if (filePath.includes("routes") || filePath.includes("controller")) {
1136
- await this.reloadRoutes();
1137
- }
1138
- if (filePath.includes("config") || filePath.includes(".env")) {
1139
- await this.reloadDependencies();
1140
- }
1141
- }
1142
- /**
1143
- * Reloads routes dynamically.
1144
- *
1145
- * @method reloadRoutes
1146
- * @private
1147
- *
1148
- * @returns {Promise<void>}
1149
- *
1150
- * @throws {Error} If route reloading fails
1151
- *
1152
- * @remarks
1153
- * This method should be implemented based on your architecture.
1154
- * It should reload route modules from the filesystem.
1155
- */
1156
- async reloadRoutes() {
1157
- try {
1158
- SLogger(this.localLanguage).logger.info({
1159
- title: import_opticore_translator2.TranslationLoader.t("ROUTES_RELOADED", this.localLanguage),
1160
- message: "Routes dynamically reloaded"
1161
- });
1162
- } catch (error) {
1163
- throw new Error(`Route reload failed: ${error.message}`);
1164
- }
1165
- }
1166
- /**
1167
- * Reloads dependencies dynamically.
1168
- *
1169
- * @method reloadDependencies
1170
- * @private
1171
- *
1172
- * @returns {Promise<void>}
1173
- *
1174
- * @throws {Error} If dependency reloading fails
1175
- */
1176
- async reloadDependencies() {
1177
- try {
1178
- if (this.currentDependencies.length > 0) {
1179
- new import_opticore_dependency_inject2.SContainer(this.localLanguage, this.currentDependencies);
1180
- SLogger(this.localLanguage).logger.info({
1181
- title: import_opticore_translator2.TranslationLoader.t("DEPENDENCIES_RELOADED", this.localLanguage),
1182
- message: "Dependencies reloaded"
1183
- });
1184
- }
1185
- } catch (error) {
1186
- throw new Error(`Dependency reload failed: ${error.message}`);
1187
- }
1188
- }
1189
- /**
1190
- * Checks if HMR restart can proceed based on configuration limits.
1191
- *
1192
- * @method canProceedWithHMRRestart
1193
- * @private
1194
- *
1195
- * @returns {boolean} True if restart can proceed, false otherwise
1196
- *
1197
- * @remarks
1198
- * Checks:
1199
- * - Auto-restart enabled/disabled
1200
- * - Maximum restarts per minute limit
1201
- */
1202
- canProceedWithHMRRestart() {
1203
- const hmrConfig = this.getEnvironment;
1204
- if (!hmrConfig.hmrAutoRestarts) {
1205
- SLogger(this.localLanguage).logger.warn({
1206
- title: import_opticore_translator2.TranslationLoader.t("HMR_AUTO_RESTART_DISABLED", this.localLanguage),
1207
- message: "HMR auto-restart disabled"
1208
- });
1209
- return false;
1210
- }
1211
- const maxRestarts = hmrConfig.hmrMaxRestarts || 5;
1212
- const now = Date.now();
1213
- const oneMinuteAgo = now - 6e4;
1214
- if (this.lastHmrRestartTime < oneMinuteAgo) {
1215
- this.hmrRestartCount = 0;
1216
- }
1217
- if (this.hmrRestartCount >= maxRestarts) {
1218
- const nextReset = Math.ceil((this.lastHmrRestartTime + 6e4 - now) / 1e3);
1219
- SLogger(this.localLanguage).logger.error({
1220
- title: import_opticore_translator2.TranslationLoader.t("HMR_RESTART_LIMIT_EXCEEDED", this.localLanguage),
1221
- message: import_opticore_translator2.TranslationLoader.t("HMR_RESTART_LIMIT_MESSAGE", this.localLanguage, {
1222
- max: maxRestarts,
1223
- nextReset
1224
- })
516
+ allFeatureRoutes.map((router) => {
517
+ router.routes.map((route) => {
518
+ this.expressApp.use(route.path, route.handler);
1225
519
  });
1226
- return false;
1227
- }
1228
- return true;
1229
- }
1230
- /**
1231
- * Called when the HMR watcher is ready.
1232
- *
1233
- * @method onHMRWatcherReady
1234
- * @private
1235
- *
1236
- * @param {string[]} watchPatterns - Patterns being watched
1237
- * @param {string[]} ignorePatterns - Patterns being ignored
1238
- *
1239
- * @returns {void}
1240
- */
1241
- onHMRWatcherReady(watchPatterns, ignorePatterns) {
1242
- SLogger(this.localLanguage).logger.info({
1243
- title: import_opticore_translator2.TranslationLoader.t("HMR_WATCHER_READY", this.localLanguage),
1244
- message: import_opticore_translator2.TranslationLoader.t("HMR_WATCHING_DETAILS", this.localLanguage, {
1245
- watchCount: watchPatterns,
1246
- ignoreCount: ignorePatterns
1247
- })
1248
- });
1249
- }
1250
- /**
1251
- * Handles HMR watcher errors.
1252
- *
1253
- * @method onHMRWatcherError
1254
- * @private
1255
- *
1256
- * @param {Error} error - The watcher error
1257
- *
1258
- * @returns {void}
1259
- */
1260
- onHMRWatcherError(error) {
1261
- SLogger(this.localLanguage).logger.error({
1262
- title: import_opticore_translator2.TranslationLoader.t("HMR_WATCHER_ERROR", this.localLanguage),
1263
- message: error.message,
1264
- errorType: "FileWatcherError",
1265
- stackTrace: error.stack
1266
- });
1267
- }
1268
- /**
1269
- * Stops the HMR system.
1270
- *
1271
- * @method stopHMR
1272
- * @private
1273
- *
1274
- * @returns {void}
1275
- */
1276
- stopHMR() {
1277
- if (this.fileWatcher) {
1278
- this.fileWatcher.close();
1279
- this.fileWatcher = null;
1280
- }
1281
- if (this.hmrDebounceTimeout) {
1282
- clearTimeout(this.hmrDebounceTimeout);
1283
- this.hmrDebounceTimeout = null;
1284
- }
1285
- SLogger(this.localLanguage).logger.info({
1286
- title: import_opticore_translator2.TranslationLoader.t("HMR_STOPPED", this.localLanguage),
1287
- message: import_opticore_translator2.TranslationLoader.t("HMR_MONITORING_STOPPED", this.localLanguage)
1288
520
  });
1289
521
  }
1290
522
  /**
1291
- * Stops the server and HMR system cleanly.
1292
- *
1293
- * @method onStopServer
1294
- * @public
1295
- *
1296
- * @returns {void}
1297
- */
1298
- onStopServer() {
1299
- this.stopHMR();
1300
- if (this.server) {
1301
- this.server.close(() => {
1302
- SLogger(this.localLanguage).logger.info({
1303
- title: import_opticore_translator2.TranslationLoader.t("SERVER_STOPPED", this.localLanguage),
1304
- message: "Server stopped cleanly"
1305
- });
1306
- });
1307
- this.serverStatus = "STOPPED";
1308
- }
1309
- }
1310
- /**
1311
- * Gets the current server state information.
1312
- *
1313
- * @method getServerState
1314
- * @public
1315
- *
1316
- * @returns {IServerStateInfo} Server state information object
1317
- *
1318
- * @remarks
1319
- * Includes:
1320
- * - Status, host, port
1321
- * - Route and dependency counts
1322
- * - Uptime and memory usage
1323
- * - HMR configuration and statistics
1324
- */
1325
- getServerState() {
1326
- const now = /* @__PURE__ */ new Date();
1327
- const uptime = this.serverStartTime ? now.getTime() - this.serverStartTime.getTime() : 0;
1328
- return {
1329
- status: this.serverStatus,
1330
- isRunning: this.server !== void 0 && this.serverStatus === "READY",
1331
- host: this.getEnvironment.appHost,
1332
- port: Number(this.getEnvironment.appPort),
1333
- language: this.localLanguage,
1334
- routesCount: this.currentRoutes.length,
1335
- dependenciesCount: this.currentDependencies.length,
1336
- startTime: this.serverStartTime,
1337
- currentTime: now,
1338
- uptime,
1339
- uptimeFormatted: this.formatUptime(uptime),
1340
- memoryUsage: import_node_process3.default.memoryUsage(),
1341
- pid: import_node_process3.default.pid,
1342
- platform: import_node_process3.default.platform,
1343
- nodeVersion: import_node_process3.default.version,
1344
- cwd: import_node_process3.default.cwd(),
1345
- hmrEnabled: this.getEnvironment.hmrEnabled,
1346
- hmrWatchingFiles: this.getEnvironment.hmrWatchPatterns?.length || 0,
1347
- hmrRestartCount: this.hmrRestartCount
1348
- };
1349
- }
1350
- /**
1351
- * Gets the current server status.
1352
- *
1353
- * @method getServerStatus
1354
- * @public
1355
- *
1356
- * @returns {TServerStatus} Current server status
1357
- */
1358
- getServerStatus() {
1359
- return this.serverStatus;
1360
- }
1361
- /**
1362
- * Gets detailed server statistics.
1363
- *
1364
- * @method getServerStats
1365
- * @public
1366
- *
1367
- * @returns {IServerStats} Server statistics object
1368
- *
1369
- * @remarks
1370
- * Includes:
1371
- * - Performance metrics (CPU, memory)
1372
- * - Uptime information
1373
- * - HMR statistics
1374
- */
1375
- getServerStats() {
1376
- const uptime = this.serverStartTime ? Date.now() - this.serverStartTime.getTime() : 0;
1377
- const memory = import_node_process3.default.memoryUsage();
1378
- return {
1379
- status: this.serverStatus,
1380
- uptime: this.formatUptime(uptime),
1381
- memory: {
1382
- rss: this.formatBytes(memory.rss),
1383
- heapTotal: this.formatBytes(memory.heapTotal),
1384
- heapUsed: this.formatBytes(memory.heapUsed),
1385
- external: this.formatBytes(memory.external)
1386
- },
1387
- performance: {
1388
- cpuUsage: import_node_process3.default.cpuUsage(),
1389
- resourceUsage: import_node_process3.default.resourceUsage?.()
1390
- },
1391
- hmrStats: {
1392
- enabled: this.getEnvironment.hmrEnabled,
1393
- restartCount: this.hmrRestartCount,
1394
- lastRestartTime: this.lastHmrRestartTime,
1395
- watchingFiles: this.getEnvironment.hmrWatchPatterns?.length || 0
1396
- }
1397
- };
1398
- }
1399
- /**
1400
- * Formats milliseconds into a human-readable uptime string.
1401
523
  *
1402
- * @method formatUptime
1403
524
  * @private
1404
- *
1405
- * @param {number} ms - Milliseconds to format
1406
- *
1407
- * @returns {string} Formatted uptime string
1408
- *
1409
- * @example
1410
- * formatUptime(3661000) // returns "1h 1m 1s"
1411
525
  */
1412
- formatUptime(ms) {
1413
- const seconds = Math.floor(ms / 1e3);
1414
- const minutes = Math.floor(seconds / 60);
1415
- const hours = Math.floor(minutes / 60);
1416
- const days = Math.floor(hours / 24);
1417
- if (days > 0) {
1418
- return `${days}d ${hours % 24}h ${minutes % 60}m`;
1419
- } else if (hours > 0) {
1420
- return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
1421
- } else if (minutes > 0) {
1422
- return `${minutes}m ${seconds % 60}s`;
1423
- } else {
1424
- return `${seconds}s`;
1425
- }
526
+ stackTraceErrorHandling() {
527
+ return eventProcessHandler(this.localLanguage);
1426
528
  }
1427
529
  /**
1428
- * Formats bytes into a human-readable size string.
1429
530
  *
1430
- * @method formatBytes
1431
531
  * @private
1432
- *
1433
- * @param {number} bytes - Bytes to format
1434
- *
1435
- * @returns {string} Formatted size string
1436
- *
1437
- * @example
1438
- * formatBytes(1048576) // returns "1.00 MB"
1439
- */
1440
- formatBytes(bytes) {
1441
- const units = ["B", "KB", "MB", "GB", "TB"];
1442
- let value = bytes;
1443
- let unitIndex = 0;
1444
- while (value >= 1024 && unitIndex < units.length - 1) {
1445
- value /= 1024;
1446
- unitIndex++;
1447
- }
1448
- return `${value.toFixed(2)} ${units[unitIndex]}`;
1449
- }
1450
- /**
1451
- * Checks if HMR is currently active.
1452
- *
1453
- * @method isHMRActive
1454
- * @public
1455
- *
1456
- * @returns {boolean} True if HMR is enabled and watching files, false otherwise
1457
- */
1458
- isHMRActive() {
1459
- return this.getEnvironment.hmrEnabled && this.fileWatcher !== null;
1460
- }
1461
- /**
1462
- * Gets detailed HMR information and status.
1463
- *
1464
- * @method getHMRInfo
1465
- * @public
1466
- *
1467
- * @returns {any} HMR information object
1468
- *
1469
- * @remarks
1470
- * Includes:
1471
- * - Configuration settings from .env
1472
- * - Current restart count
1473
- * - Watcher status
1474
532
  */
1475
- getHMRInfo() {
1476
- return {
1477
- enabled: this.getEnvironment.hmrEnabled,
1478
- watchPatterns: this.getEnvironment.hmrWatchPatterns,
1479
- ignorePatterns: this.getEnvironment.hmrIgnorePatterns,
1480
- debounceMs: this.getEnvironment.hmrDebounceMs,
1481
- maxRestarts: this.getEnvironment.hmrMaxRestarts,
1482
- autoRestart: this.getEnvironment.hmrAutoRestarts,
1483
- currentRestartCount: this.hmrRestartCount,
1484
- lastRestartTime: this.lastHmrRestartTime,
1485
- isWatching: this.fileWatcher !== null,
1486
- isRestartPending: this.hmrRestartPending
1487
- };
533
+ infoWebApp() {
534
+ this.loadTranslationFiles();
535
+ this.serverUtility.infoServer(
536
+ this.getEnvironmentValue.appHost,
537
+ Number(this.getEnvironmentValue.appPort)
538
+ );
1488
539
  }
1489
540
  };
1490
541
  // Annotate the CommonJS export names for ESM import in node: