opticore-webapp 1.0.67 → 1.0.69

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.d.cts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { Server } from 'http';
2
+ import { IEnvVariables } from 'opticore-env-access';
2
3
  import { TDependency } from 'opticore-dependency-inject';
4
+ import { TFeatureRoutes } from 'opticore-router';
3
5
  import { express } from 'opticore-express';
4
6
  import { LoggerCore } from 'opticore-logger';
5
7
  import { CorsOptions } from 'cors';
6
- import { TFeatureRoutes } from 'opticore-router';
7
8
 
8
9
  interface WebServerConstructorInterface {
9
10
  app: express.Application;
@@ -13,20 +14,75 @@ interface WebServerConstructorInterface {
13
14
  corsOriginOptions?: Partial<CorsOptions>;
14
15
  }
15
16
 
17
+ type TServerStatus = "READY" | "RELOADING" | "BLOCKED" | "ERROR" | "STARTING" | "STOPPING" | "STOPPED";
18
+
19
+ interface IServerStateInfo {
20
+ status: TServerStatus;
21
+ isRunning: boolean;
22
+ host: string;
23
+ port: number;
24
+ language: string;
25
+ routesCount: number;
26
+ dependenciesCount: number;
27
+ startTime?: Date;
28
+ currentTime?: Date;
29
+ uptime?: number;
30
+ uptimeFormatted?: string;
31
+ memoryUsage?: NodeJS.MemoryUsage;
32
+ pid?: number;
33
+ platform?: string;
34
+ nodeVersion?: string;
35
+ cwd?: string;
36
+ hmrEnabled: boolean;
37
+ hmrWatchingFiles: number;
38
+ hmrRestartCount: number;
39
+ }
40
+
41
+ interface IServerStats {
42
+ status: TServerStatus;
43
+ uptime: string;
44
+ memory: {
45
+ rss: string;
46
+ heapTotal: string;
47
+ heapUsed: string;
48
+ external: string;
49
+ };
50
+ performance: {
51
+ cpuUsage: NodeJS.CpuUsage;
52
+ resourceUsage?: NodeJS.ResourceUsage;
53
+ };
54
+ hmrStats: {
55
+ enabled: boolean;
56
+ restartCount: number;
57
+ lastRestartTime: number;
58
+ watchingFiles: number;
59
+ };
60
+ }
61
+
16
62
  /**
17
- * WebServerCore - Architecture Serveur-Autorité
63
+ * Main server class that handles HTTP server initialization, routing,
64
+ * error handling, file watching with hot reload capabilities, and HMR.
65
+ *
66
+ * @class WebServerCore
18
67
  *
19
- * Le serveur gère strictement ses états :
20
- * - READY : Prêt à recevoir des demandes de hot reload
21
- * - RELOADING : En cours de hot reload
22
- * - BLOCKED : Bloqué par une erreur, refuse les nouveaux reloads
68
+ * @example
69
+ * ```typescript
70
+ * const app = new WebServerCore({
71
+ * app: express(),
72
+ * loggerConfig: loggerConfig,
73
+ * environmentPath: ".env",
74
+ * localLanguage: "fr",
75
+ * corsOriginOptions: corsConfig
76
+ * });
77
+ *
78
+ * app.onStartServer(routes, databaseCallback, dependencies);
79
+ * ```
23
80
  */
24
81
  declare class WebServerCore {
25
82
  private serverUtility;
26
- private expressApp;
83
+ private readonly expressApp;
27
84
  private readonly localLanguage;
28
85
  private readonly loggerConfig;
29
- private readonly routerExpressApp;
30
86
  private readonly getEnvironment;
31
87
  private readonly environmentPath;
32
88
  private serverListenEvent;
@@ -34,50 +90,445 @@ declare class WebServerCore {
34
90
  private currentDependencies;
35
91
  private server;
36
92
  private errorEmitter;
37
- private serverState;
38
- private lastError;
39
- private hotReloadAttempts;
40
- private hotReloadSuccesses;
41
- private hotReloadFailures;
93
+ private serverStatus;
94
+ private serverStartTime;
95
+ private fileWatcher;
96
+ private hmrRestartPending;
97
+ private hmrDebounceTimeout;
98
+ private hmrRestartCount;
99
+ private lastHmrRestartTime;
100
+ /**
101
+ * Creates a new WebServerCore instance.
102
+ *
103
+ * @constructor
104
+ * @param {WebServerConstructorInterface} paramsConstructor - Configuration parameters
105
+ *
106
+ * @param {express.Application} paramsConstructor.app - Express application instance
107
+ * @param {LoggerCore} paramsConstructor.loggerConfig - Logger configuration
108
+ * @param {string} paramsConstructor.environmentPath - Path to environment file
109
+ * @param {string} paramsConstructor.localLanguage - Default language for translations
110
+ * @param {CorsOptions} paramsConstructor.corsOriginOptions - CORS configuration
111
+ *
112
+ * @returns {WebServerCore} New WebServerCore instance
113
+ *
114
+ * @throws {Error} If environment file cannot be loaded
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const server = new WebServerCore({
119
+ * app: express(),
120
+ * loggerConfig: new LoggerCore(config),
121
+ * environmentPath: ".env",
122
+ * localLanguage: "fr",
123
+ * corsOriginOptions: { origin: "http://localhost:3000" }
124
+ * });
125
+ * ```
126
+ */
42
127
  constructor(paramsConstructor: WebServerConstructorInterface);
43
- onStartServer(routers: TFeatureRoutes[], databaseCallback?: (env: any) => void, dependenciesProvider?: TDependency[]): Server | undefined;
44
128
  /**
45
- * ✅✅✅ Configuration de la gestion d'erreurs
129
+ * Starts the HTTP server and initializes all components including HMR if enabled.
130
+ *
131
+ * @method onStartServer
132
+ * @public
133
+ *
134
+ * @param {TFeatureRoutes[]} routers - Array of feature routes to register
135
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Optional database connection callback
136
+ * @param {TDependency[]} [dependenciesProvider] - Optional dependency injection providers
137
+ *
138
+ * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
139
+ *
140
+ * @throws {ServerListenEventError} If port/host configuration is invalid
141
+ * @throws {Error} If server initialization fails
142
+ *
143
+ * @fires WebServerCore#startHttpServer - When server successfully starts
144
+ * @fires WebServerCore#startHMR - When HMR is started (if enabled)
145
+ * @fires WebServerCore#serverError - When server fails to start
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * const server = app.onStartServer(
150
+ * routes,
151
+ * (env) => connectToDatabase(env),
152
+ * dependencies
153
+ * );
154
+ *
155
+ * if (server) {
156
+ * console.log("Server started successfully");
157
+ * }
158
+ * ```
46
159
  */
47
- private setupErrorHandling;
48
- private setupServerEvents;
49
- private notifyServerReady;
50
- private setupSignalHandlers;
51
- private setupIPCHandlers;
160
+ onStartServer(routers: TFeatureRoutes[], databaseCallback?: (env: IEnvVariables) => void, dependenciesProvider?: TDependency[]): Server | undefined;
52
161
  /**
53
- * ✅✅✅ HOT RELOAD avec gestion d'état stricte
162
+ * Validates server configuration parameters.
163
+ *
164
+ * @method validateServerParameters
165
+ * @private
166
+ *
167
+ * @returns {boolean} True if all parameters are valid, false otherwise
168
+ *
169
+ * @remarks
170
+ * Validates:
171
+ * - Port number is valid and positive
172
+ * - Host is not empty
173
+ * - Local language is specified
174
+ * - HMR configuration (if enabled)
54
175
  */
55
- private performTrueHotReload;
176
+ private validateServerParameters;
56
177
  /**
57
- * Nettoie le cache des modules applicatifs
178
+ * Starts the HTTP server and sets up event listeners.
179
+ *
180
+ * @method startHttpServer
181
+ * @private
182
+ *
183
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
184
+ *
185
+ * @returns {serverWebApp | undefined} HTTP server instance or undefined if startup fails
186
+ *
187
+ * @throws {Error} If server fails to start
58
188
  */
59
- private clearApplicationModulesCache;
60
- private reloadConfigurations;
61
- private reloadDependencies;
189
+ private startHttpServer;
190
+ /**
191
+ * Configures server components (database, dependencies, routes, etc.).
192
+ *
193
+ * @method configureServerComponents
194
+ * @private
195
+ *
196
+ * @param {(env: IEnvVariables) => void} [databaseCallback] - Database connection callback
197
+ *
198
+ * @returns {void}
199
+ *
200
+ * @throws {Error} If component configuration fails
201
+ */
202
+ private configureServerComponents;
62
203
  /**
63
- * ✅✅✅ Notifier le watcher : SUCCÈS
204
+ * Handles server configuration errors.
205
+ *
206
+ * @method handleServerConfigurationError
207
+ * @private
208
+ *
209
+ * @param {any} err - The error that occurred
210
+ *
211
+ * @returns {void}
64
212
  */
65
- private notifyWatcherReloadSuccess;
213
+ private handleServerConfigurationError;
66
214
  /**
67
- * ✅✅✅ Notifier le watcher : BLOQUÉ PAR ERREUR TRANSFORM
215
+ * Handles general startup errors.
216
+ *
217
+ * @method handleStartupError
218
+ * @private
219
+ *
220
+ * @param {any} error - The startup error
221
+ *
222
+ * @returns {void}
68
223
  */
69
- private notifyWatcherBlockedByError;
224
+ private handleStartupError;
70
225
  /**
71
- * ✅✅✅ Notifier le watcher : ERREUR GÉNÉRIQUE
226
+ * Sets up Node.js process event listeners.
227
+ *
228
+ * @method setupProcessEventListeners
229
+ * @private
230
+ *
231
+ * @returns {void}
232
+ *
233
+ * @remarks
234
+ * Listens for:
235
+ * - Process exit events
236
+ * - Uncaught exceptions
237
+ * - Unhandled rejections
238
+ * - System signals (SIGINT, SIGTERM)
72
239
  */
73
- private notifyWatcherReloadError;
240
+ private setupProcessEventListeners;
74
241
  /**
75
- * ✅✅✅ Parser les détails d'une TransformError
242
+ * Sets up HTTP server event listeners.
243
+ *
244
+ * @method setupServerEventListeners
245
+ * @private
246
+ *
247
+ * @returns {void}
248
+ *
249
+ * @remarks
250
+ * Configures listeners for:
251
+ * - Server errors
252
+ * - Connection closing
253
+ * - Connection dropping
254
+ * - HTTP requests (for logging)
255
+ *
256
+ * @listens Server#error - Server error events
257
+ * @listens Server#close - Server closing events
258
+ * @listens Server#drop - Connection drop events
259
+ * @listens Server#request - HTTP request events
260
+ */
261
+ private setupServerEventListeners;
262
+ /**
263
+ * Sets up error handling middleware and event emitters.
264
+ *
265
+ * @method setupErrorHandling
266
+ * @private
267
+ *
268
+ * @returns {void}
269
+ */
270
+ private setupErrorHandling;
271
+ /**
272
+ * Registers routes with the Express application.
273
+ *
274
+ * @method registerRoutes
275
+ * @private
276
+ *
277
+ * @param {any[]} allFeatureRoutes - Array of feature routes to register
278
+ *
279
+ * @returns {void}
76
280
  */
77
- private parseTransformError;
78
281
  private registerRoutes;
282
+ /**
283
+ * Displays server information.
284
+ *
285
+ * @method infoWebApp
286
+ * @private
287
+ *
288
+ * @returns {void}
289
+ */
79
290
  private infoWebApp;
80
- private shutdown;
291
+ /**
292
+ * Starts the Hot Module Replacement (HMR) file watching system.
293
+ *
294
+ * @method startHMR
295
+ * @private
296
+ *
297
+ * @returns {void}
298
+ *
299
+ * @remarks
300
+ * Configures file watcher based on environment variables:
301
+ * - HMR_ENABLED: Enable/disable HMR
302
+ * - HMR_WATCH_PATTERNS: Files to watch
303
+ * - HMR_IGNORE_PATTERNS: Files to ignore
304
+ *
305
+ * @throws {Error} If HMR configuration is invalid
306
+ */
307
+ private startHMR;
308
+ /**
309
+ * Handles file change events with debouncing.
310
+ *
311
+ * @method handleFileChange
312
+ * @private
313
+ *
314
+ * @param {string} filePath - Path of the changed file
315
+ * @param {string} [action="modified"] - Type of file change (modified/added/deleted)
316
+ *
317
+ * @returns {void}
318
+ *
319
+ * @remarks
320
+ * Uses debouncing to prevent multiple rapid reloads.
321
+ * Debounce time configurable via HMR_DEBOUNCE_MS environment variable.
322
+ */
323
+ private handleFileChange;
324
+ /**
325
+ * Triggers a hot reload operation.
326
+ *
327
+ * @method triggerHotReload
328
+ * @private
329
+ *
330
+ * @param {string} filePath - Path of the changed file
331
+ * @param {string} action - Type of file change
332
+ *
333
+ * @returns {Promise<void>}
334
+ *
335
+ * @remarks
336
+ * - Checks if reload is already in progress
337
+ * - Validates restart limits
338
+ * - Performs appropriate reload actions based on file type
339
+ * - Emits hotReload event
340
+ */
341
+ private triggerHotReload;
342
+ /**
343
+ * Performs appropriate hot reload actions based on file type.
344
+ *
345
+ * @method performHotReloadActions
346
+ * @private
347
+ *
348
+ * @param {string} filePath - Path of the changed file
349
+ *
350
+ * @returns {Promise<void>}
351
+ *
352
+ * @remarks
353
+ * Different actions for different file types:
354
+ * - .json/.env: Reload translations
355
+ * - routes/controller files: Reload routes
356
+ * - config/.env files: Reload dependencies
357
+ */
358
+ private performHotReloadActions;
359
+ /**
360
+ * Reloads routes dynamically.
361
+ *
362
+ * @method reloadRoutes
363
+ * @private
364
+ *
365
+ * @returns {Promise<void>}
366
+ *
367
+ * @throws {Error} If route reloading fails
368
+ *
369
+ * @remarks
370
+ * This method should be implemented based on your architecture.
371
+ * It should reload route modules from the filesystem.
372
+ */
373
+ private reloadRoutes;
374
+ /**
375
+ * Reloads dependencies dynamically.
376
+ *
377
+ * @method reloadDependencies
378
+ * @private
379
+ *
380
+ * @returns {Promise<void>}
381
+ *
382
+ * @throws {Error} If dependency reloading fails
383
+ */
384
+ private reloadDependencies;
385
+ /**
386
+ * Checks if HMR restart can proceed based on configuration limits.
387
+ *
388
+ * @method canProceedWithHMRRestart
389
+ * @private
390
+ *
391
+ * @returns {boolean} True if restart can proceed, false otherwise
392
+ *
393
+ * @remarks
394
+ * Checks:
395
+ * - Auto-restart enabled/disabled
396
+ * - Maximum restarts per minute limit
397
+ */
398
+ private canProceedWithHMRRestart;
399
+ /**
400
+ * Called when the HMR watcher is ready.
401
+ *
402
+ * @method onHMRWatcherReady
403
+ * @private
404
+ *
405
+ * @param {string[]} watchPatterns - Patterns being watched
406
+ * @param {string[]} ignorePatterns - Patterns being ignored
407
+ *
408
+ * @returns {void}
409
+ */
410
+ private onHMRWatcherReady;
411
+ /**
412
+ * Handles HMR watcher errors.
413
+ *
414
+ * @method onHMRWatcherError
415
+ * @private
416
+ *
417
+ * @param {Error} error - The watcher error
418
+ *
419
+ * @returns {void}
420
+ */
421
+ private onHMRWatcherError;
422
+ /**
423
+ * Stops the HMR system.
424
+ *
425
+ * @method stopHMR
426
+ * @private
427
+ *
428
+ * @returns {void}
429
+ */
430
+ private stopHMR;
431
+ /**
432
+ * Stops the server and HMR system cleanly.
433
+ *
434
+ * @method onStopServer
435
+ * @public
436
+ *
437
+ * @returns {void}
438
+ */
439
+ onStopServer(): void;
440
+ /**
441
+ * Gets the current server state information.
442
+ *
443
+ * @method getServerState
444
+ * @public
445
+ *
446
+ * @returns {IServerStateInfo} Server state information object
447
+ *
448
+ * @remarks
449
+ * Includes:
450
+ * - Status, host, port
451
+ * - Route and dependency counts
452
+ * - Uptime and memory usage
453
+ * - HMR configuration and statistics
454
+ */
455
+ getServerState(): IServerStateInfo;
456
+ /**
457
+ * Gets the current server status.
458
+ *
459
+ * @method getServerStatus
460
+ * @public
461
+ *
462
+ * @returns {TServerStatus} Current server status
463
+ */
464
+ getServerStatus(): TServerStatus;
465
+ /**
466
+ * Gets detailed server statistics.
467
+ *
468
+ * @method getServerStats
469
+ * @public
470
+ *
471
+ * @returns {IServerStats} Server statistics object
472
+ *
473
+ * @remarks
474
+ * Includes:
475
+ * - Performance metrics (CPU, memory)
476
+ * - Uptime information
477
+ * - HMR statistics
478
+ */
479
+ getServerStats(): IServerStats;
480
+ /**
481
+ * Formats milliseconds into a human-readable uptime string.
482
+ *
483
+ * @method formatUptime
484
+ * @private
485
+ *
486
+ * @param {number} ms - Milliseconds to format
487
+ *
488
+ * @returns {string} Formatted uptime string
489
+ *
490
+ * @example
491
+ * formatUptime(3661000) // returns "1h 1m 1s"
492
+ */
493
+ private formatUptime;
494
+ /**
495
+ * Formats bytes into a human-readable size string.
496
+ *
497
+ * @method formatBytes
498
+ * @private
499
+ *
500
+ * @param {number} bytes - Bytes to format
501
+ *
502
+ * @returns {string} Formatted size string
503
+ *
504
+ * @example
505
+ * formatBytes(1048576) // returns "1.00 MB"
506
+ */
507
+ private formatBytes;
508
+ /**
509
+ * Checks if HMR is currently active.
510
+ *
511
+ * @method isHMRActive
512
+ * @public
513
+ *
514
+ * @returns {boolean} True if HMR is enabled and watching files, false otherwise
515
+ */
516
+ isHMRActive(): boolean;
517
+ /**
518
+ * Gets detailed HMR information and status.
519
+ *
520
+ * @method getHMRInfo
521
+ * @public
522
+ *
523
+ * @returns {any} HMR information object
524
+ *
525
+ * @remarks
526
+ * Includes:
527
+ * - Configuration settings from .env
528
+ * - Current restart count
529
+ * - Watcher status
530
+ */
531
+ getHMRInfo(): any;
81
532
  }
82
533
 
83
534
  declare const envPath: string;