opticore-webapp 1.0.0

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.
Files changed (44) hide show
  1. package/dist/index.cjs +1080 -0
  2. package/dist/index.d.cts +408 -0
  3. package/dist/index.d.ts +408 -0
  4. package/dist/index.js +1038 -0
  5. package/package.json +46 -0
  6. package/src/application/exceptions/messages.exception.ts +67 -0
  7. package/src/application/http/response.http.ts +67 -0
  8. package/src/application/service/core.service.ts +180 -0
  9. package/src/core/config/.gitkeep +0 -0
  10. package/src/core/errors/.gitkeep +0 -0
  11. package/src/core/events/errors/serverListen.event.error.ts +421 -0
  12. package/src/core/events/requestCalls.event.ts +86 -0
  13. package/src/core/handlers/errors/base/stackTraceError.ts +23 -0
  14. package/src/core/handlers/errors/stackTraceAssertionError.ts +13 -0
  15. package/src/core/handlers/errors/stackTraceEvalError.ts +12 -0
  16. package/src/core/handlers/errors/stackTraceGeneralError.ts +13 -0
  17. package/src/core/handlers/errors/stackTraceOpenSSLError.ts +12 -0
  18. package/src/core/handlers/errors/stackTraceRangeError.ts +12 -0
  19. package/src/core/handlers/errors/stackTraceReferenceError.ts +13 -0
  20. package/src/core/handlers/errors/stackTraceSyntaxError.ts +12 -0
  21. package/src/core/handlers/errors/stackTraceSystemError.ts +14 -0
  22. package/src/core/handlers/errors/stackTraceTypeError.ts +13 -0
  23. package/src/core/handlers/errors/stackTraceURIError.ts +13 -0
  24. package/src/core/handlers/eventProcess.handler.ts +106 -0
  25. package/src/core/utils/dateTimeFormatted.utils.ts +6 -0
  26. package/src/core/utils/logMessage.utils.ts +20 -0
  27. package/src/core/utils/modulesLoaded.utils.ts +16 -0
  28. package/src/core/webServer.core.ts +110 -0
  29. package/src/domains/constants/errorName.constant.ts +12 -0
  30. package/src/domains/constants/event.constant.ts +15 -0
  31. package/src/domains/constants/eventNameError.constant.ts +8 -0
  32. package/src/domains/constants/httpStatusCodes.constant.ts +375 -0
  33. package/src/domains/constants/logLevel.constant.ts +6 -0
  34. package/src/domains/env/access.env.ts +23 -0
  35. package/src/domains/interfaces/envVariables.interface.ts +16 -0
  36. package/src/domains/interfaces/kernelModule.interface.ts +6 -0
  37. package/src/domains/interfaces/routeDefinition.interface.ts +6 -0
  38. package/src/domains/types/kernelModule.type.ts +3 -0
  39. package/src/index.ts +20 -0
  40. package/src/infrastructure/events/.gitkeep +0 -0
  41. package/src/infrastructure/handlers/.gitkeep +0 -0
  42. package/src/presentation/middleware/.gitkeep +0 -0
  43. package/tsconfig.json +26 -0
  44. package/tsup.config.ts +11 -0
@@ -0,0 +1,13 @@
1
+ import StackTraceError from "./base/stackTraceError";
2
+ import {errorNameConstant} from "../../utils/constants/errorName.constant";
3
+ import {HttpStatusCodesConstant as status} from "../../../domain/constants/httpStatusCodes.constant";
4
+
5
+
6
+ /**
7
+ * Handling and catch a Node.js error.
8
+ */
9
+ export default class StackTraceURIError extends StackTraceError {
10
+ constructor(message: string) {
11
+ super(message, errorNameConstant.evalError, status.BAD_REQUEST, true);
12
+ }
13
+ }
@@ -0,0 +1,106 @@
1
+ import express, {Express} from "express";
2
+ import process from 'node:process';
3
+ import EventEmitter from "node:events";
4
+ import {eventName, event} from "../../index";
5
+ import {ServerListenEventError} from "@/errors/serverListen.event.error";
6
+
7
+ /**
8
+ *
9
+ */
10
+ export function eventProcessHandler(): void {
11
+ const errorEmitter = new EventEmitter();
12
+ const app: Express = express();
13
+
14
+ /**
15
+ * Listener for error events
16
+ */
17
+ errorEmitter.on(eventName.error, (error: Error): void => {
18
+ ServerListenEventError.listenerError(error);
19
+ });
20
+
21
+ /**
22
+ * Catch uncaught exceptions
23
+ * Process event listeners
24
+ */
25
+ process.on(event.beforeExit, (code: number): void => {
26
+ setTimeout((): void => {
27
+ ServerListenEventError.processBeforeExit(code);
28
+ }, 100);
29
+ });
30
+
31
+ /**
32
+ *
33
+ */
34
+ process.on(event.disconnect, (): void => {
35
+ ServerListenEventError.processDisconnected();
36
+ });
37
+
38
+ /**
39
+ *
40
+ */
41
+ process.on(event.exit, (code: number): void => {
42
+ ServerListenEventError.exited(code);
43
+ });
44
+
45
+ /**
46
+ *
47
+ */
48
+ process.on(event.rejectionHandled, (promise: Promise<any>): void => {
49
+ ServerListenEventError.promiseRejectionHandled(promise);
50
+ });
51
+
52
+ /**
53
+ *
54
+ */
55
+ process.on(event.uncaughtException, (error: any): void => {
56
+ ServerListenEventError.uncaughtException(error);
57
+ });
58
+
59
+ /**
60
+ *
61
+ */
62
+ process.on(event.uncaughtExceptionMonitor, (error: any): void => {
63
+ ServerListenEventError.uncaughtExceptionMonitor(error);
64
+ });
65
+
66
+ /**
67
+ *
68
+ */
69
+ process.on(event.unhandledRejection, (reason: any, promise: Promise<any>): void => {
70
+ ServerListenEventError.unhandledRejection(reason, promise);
71
+ });
72
+
73
+ /**
74
+ *
75
+ */
76
+ process.on(event.warning, (warning: any): void => {
77
+ ServerListenEventError.warning(warning);
78
+ });
79
+ process.on(event.message, (message: any): void => {
80
+ ServerListenEventError.message(message);
81
+ });
82
+
83
+ /**
84
+ *
85
+ */
86
+ process.on(event.multipleResolves, (type: string, promise: Promise<any>, reason: any): void => {
87
+ ServerListenEventError.multipleResolves(type, promise, reason);
88
+ });
89
+
90
+ /**
91
+ * Handle specific signals
92
+ */
93
+ process.on(event.sigint, (): void => {
94
+ ServerListenEventError.processInterrupted();
95
+ });
96
+ process.on(event.sigterm, (signal: any): void => {
97
+ ServerListenEventError.sigtermSignalReceived(signal);
98
+ });
99
+
100
+ /**
101
+ * Express error-handling middleware
102
+ */
103
+ app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction): void => {
104
+ ServerListenEventError.expressErrorHandlingMiddleware(errorEmitter, err, req, res, next);
105
+ });
106
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Give time like: 6-8-2024 4:30:29
3
+ */
4
+
5
+
6
+ export const dateTimeFormattedUtils: string = `${(new Date().getMonth())}-${(new Date().getDate())}-${(new Date().getFullYear())} ${(new Date().getHours())}:${(new Date().getMinutes())}:${(new Date().getSeconds())}`;
@@ -0,0 +1,20 @@
1
+ import colors from "ansi-colors";
2
+ import {dateTimeFormattedUtils} from "./dateTimeFormatted.utils";
3
+
4
+ export class LogMessageUtils {
5
+ static success(title: string, action: string, contentAction: string): void {
6
+ console.log(`${colors.green(`✔`)} ${colors.bgGreen(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgGreen(`${colors.white(` Success `)}`)} [ ${action} ] ${contentAction} - [ Status ] ${colors.bgGreen(`${colors.white(` 200 `)}`)}`);
7
+ }
8
+ static warning(title: string, action: string, contentAction: string): void {
9
+ console.warn(`${colors.yellow(`⚠️`)} ${colors.bgYellow(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgYellow(`${colors.white(` Warning `)}`)} ${contentAction}`);
10
+ }
11
+ static info(title: string, action: string, contentAction: string): void {
12
+ console.info(`${colors.cyan(`ⓘ`)} ${colors.bgCyan(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} ${dateTimeFormattedUtils} | ${colors.bgCyan(`${colors.white(` Info `)}`)} ${contentAction}`);
13
+ }
14
+ static error(title: string, errorType: any, stackTrace: any, messageContent: any, httpCodeValue: number): void {
15
+ console.error(`${colors.red(`✘`)} ${colors.bgRed(` ${colors.bold(`${colors.white(`${title}`)}`)} `)} | ${dateTimeFormattedUtils} | [ ${colors.red(`${colors.bold(` ${errorType} `)}`)} ] | [ ${colors.bold(`stack trace`)} ] ${colors.red(`${stackTrace}`)} - ${colors.red(`${messageContent}`)} - [ ${colors.red(`${colors.bold(` HttpCode `)}`)} ] ${colors.red(`${colors.bold(` ${httpCodeValue} `)}`)} `);
16
+ }
17
+ static requestError(title: string, errorName: string, errorMessage: string, errorCode: number): void {
18
+ console.error(`[ ${colors.red(`${title}`)} ] ${dateTimeFormattedUtils} | ${colors.bgRed(`${colors.white(` ERROR `)}`)} ${colors.red(`[ ${errorName} ]`)} ${colors.red(`${errorMessage}`)} - [ Status ] ${colors.bgRed(`${colors.white(` ${errorCode} `)}`)}`);
19
+ }
20
+ }
@@ -0,0 +1,16 @@
1
+ import colors from "ansi-colors";
2
+ import express from "express";
3
+ import {dateTimeFormattedUtils} from "./dateTimeFormatted.utils";
4
+ import {LogMessageUtils} from "@webApp/core/utils/logMessage.utils";
5
+
6
+
7
+ export function modulesLoadedUtils(allAppRoutes: express.Router[], dbConChecker: () => void): void {
8
+ LogMessageUtils.success("Kernel", "load kernel", "Modules app have been successfully loaded");
9
+ console.log(`${colors.whiteBright(` content`)} ${colors.green('Kernel :')} ${colors.cyan(`${colors.bold(`server side`)}`)} has been loaded successfully ${colors.green(`✔`)}`);
10
+ allAppRoutes
11
+ ? console.log(`${colors.whiteBright(` content`)} ${colors.green('Kernel :')} ${colors.cyan(`${colors.bold(`Routers service`)} `)} has been loaded successfully ${colors.green(`✔`)}`)
12
+ : console.log(`${colors.red(`✘`)} ${colors.bgRed(` ${colors.bold(`${colors.white(` Register routes `)}`)} `)} | ${dateTimeFormattedUtils} | [ ${colors.red(`${colors.bold(` fail `)}`)} ] | [ ${colors.bold(` loading `)} ] - ${colors.red(` routers `)} - The route register failed to load `);
13
+ typeof dbConChecker == "function"
14
+ ? console.log(`${colors.whiteBright(` content`)} ${colors.green('Kernel :')} ${colors.cyan(`${colors.bold(`database checker connection`)}`)} has been loaded successfully ${colors.green(`✔`)}`)
15
+ : "";
16
+ }
@@ -0,0 +1,110 @@
1
+ import {Server as serverWebApp} from "http";
2
+ import {IncomingMessage, ServerResponse} from "node:http";
3
+ import express, {Express} from "express";
4
+ import corsOrigin, {CorsOptions} from "cors";
5
+ import {IRouteDefinition} from "@webApp/domains/interfaces/routeDefinition.interface";
6
+ import {KernelModuleType} from "@webApp/domains/types/kernelModule.type";
7
+ import {getEnvVariable} from "@webApp/domains/env/access.env";
8
+ import {HttpStatusCodesConstant as status} from "@webApp/domains/constants/httpStatusCodes.constant";
9
+ import StackTraceError from "@webApp/core/handlers/errors/base/stackTraceError";
10
+ import {eventProcessHandler} from "@webApp/core/handlers/eventProcess.handler";
11
+ import {requestCallsEvent} from "@webApp/core/events/requestCalls.event";
12
+ import {CEventNameError as eventName} from "@webApp/domains/constants/eventNameError.constant";
13
+ import {ServerListenEventError as eventErrorOnListeningServer} from "@webApp/core/events/errors/serverListen.event.error";
14
+ import {CoreService} from "@webApp/application/service/core.service";
15
+ import {dateTimeFormattedUtils as currentDate} from "@webApp/core/utils/dateTimeFormatted.utils";
16
+
17
+
18
+ export class WebServerCore {
19
+ private serverUtility: CoreService = new CoreService();
20
+ private expressApp: Express = express();
21
+ private readonly routerExpressApp: express.Application;
22
+ private readonly port: number;
23
+ private readonly host: string;
24
+
25
+ constructor(app: express.Application, corsOriginOptions?: Partial<CorsOptions>) {
26
+ this.port = Number(getEnvVariable.appPort);
27
+ this.host = getEnvVariable.appHost;
28
+ this.routerExpressApp = app;
29
+
30
+ this.expressApp.use(express.json());
31
+ this.expressApp.use(express.raw());
32
+ this.expressApp.use(express.text());
33
+ this.expressApp.use(express.urlencoded({ extended: true }));
34
+ this.expressApp.use(corsOrigin(corsOriginOptions));
35
+
36
+ this.stackTraceErrorHandling();
37
+ }
38
+
39
+ public onStartServer(routers: { featureRoute: IRouteDefinition[] }[]) {
40
+ return this.expressApp.listen(
41
+ this.port,
42
+ this.host,
43
+ (): void => {
44
+ try {
45
+ if (this.host === "" && this.port === 0) {
46
+ eventErrorOnListeningServer.hostPortUndefined();
47
+ } else if (this.host === "") {
48
+ eventErrorOnListeningServer.hostUndefined();
49
+ } else if (this.port === 0) {
50
+ eventErrorOnListeningServer.portUndefined();
51
+ } else {
52
+ this.registerRoutes(routers);
53
+ }
54
+ } catch (err: any) {
55
+ this.traceError(err.message, "Error", status.NOT_ACCEPTABLE);
56
+ }
57
+ }
58
+ );
59
+ }
60
+
61
+ public onListeningOnServerEvent(serverWeb: serverWebApp, kernelModule: KernelModuleType): void {
62
+ serverWeb.on(eventName.error, (err: Error): void => {
63
+ eventErrorOnListeningServer.onEventError(err);
64
+ }).on(eventName.close, (): void => {
65
+ eventErrorOnListeningServer.serverClosing();
66
+ }).on(eventName.drop, (): void => {
67
+ eventErrorOnListeningServer.dropNewConnection();
68
+ }).on(eventName.listening, (): void => {
69
+ this.infoWebApp();
70
+ this.serverUtility.coreListenerEventLoaderModuleService(kernelModule);
71
+ });
72
+ }
73
+
74
+ public onRequestOnServerEvent(serverWeb: serverWebApp): void {
75
+ serverWeb.on(eventName.request, (req: IncomingMessage, res: ServerResponse): void => {
76
+ requestCallsEvent(req, res, this.host, this.port, currentDate);
77
+ });
78
+ }
79
+
80
+ public kernelModules(registerRouter: { featureRoute: IRouteDefinition[] }[],
81
+ dbConnection: () => void): KernelModuleType {
82
+ return [registerRouter, dbConnection] as KernelModuleType
83
+ }
84
+
85
+ private registerRoutes(allFeatureRoutes: { featureRoute: IRouteDefinition[] }[]): void {
86
+ allFeatureRoutes.map((router: {featureRoute: IRouteDefinition[]} ): void => {
87
+ router.featureRoute.map((route: IRouteDefinition): void => {
88
+ this.expressApp.use(route.path, route.handler);
89
+ });
90
+ });
91
+ }
92
+ private stackTraceErrorHandling(): void {
93
+ eventProcessHandler();
94
+ }
95
+ private infoWebApp(): void {
96
+ this.serverUtility.infoServer(
97
+ this.serverUtility.getVersions().nodeVersion,
98
+ this.serverUtility.getProjectInfo().startingTime,
99
+ getEnvVariable.appHost,
100
+ Number(getEnvVariable.appPort),
101
+ this.serverUtility.getUsageMemory().rss,
102
+ this.serverUtility.getUsageMemory().heapUsed,
103
+ this.serverUtility.getUsageMemory().user,
104
+ this.serverUtility.getUsageMemory().system
105
+ );
106
+ }
107
+ private traceError(props: string, name: string, status: number): StackTraceError {
108
+ return new StackTraceError(props, name, status, true);
109
+ }
110
+ }
@@ -0,0 +1,12 @@
1
+ export const CErrorName = {
2
+ evalError: "EvalError",
3
+ syntaxError: "SyntaxError",
4
+ rangeError: "RangeError",
5
+ referenceError: "ReferenceError",
6
+ typeError: "TypeError",
7
+ uriError: "URIError",
8
+ systemError: "SystemError",
9
+ assertionError: "AssertionError",
10
+ openSSLError: "OpenSSLError",
11
+ generalError: "GeneralError"
12
+ }
@@ -0,0 +1,15 @@
1
+ export const CEvent = {
2
+ beforeExit: "beforeExit",
3
+ disconnect: "disconnect",
4
+ exit: "exit",
5
+ rejectionHandled: "rejectionHandled",
6
+ uncaughtException: "uncaughtException",
7
+ uncaughtExceptionMonitor: "uncaughtExceptionMonitor",
8
+ unhandledRejection: "unhandledRejection",
9
+ warning: "warning",
10
+ message: "message",
11
+ multipleResolves: "multipleResolves",
12
+ worker: "worker",
13
+ sigint: "SIGINT",
14
+ sigterm: "SIGTERM"
15
+ }
@@ -0,0 +1,8 @@
1
+ export const CEventNameError = {
2
+ error: "error",
3
+ listening: "listening",
4
+ close: "close",
5
+ connection: "connection",
6
+ drop: "drop",
7
+ request: "request"
8
+ }