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
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "opticore-webapp",
3
+ "version": "1.0.0",
4
+ "description": "wep server",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "type": "module",
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1",
11
+ "build": "tsup"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/guyzoum77/opticore-webApp.git"
16
+ },
17
+ "keywords": [
18
+ "opticore"
19
+ ],
20
+ "author": "Guy-serge Kouacou",
21
+ "license": "MIT",
22
+ "bugs": {
23
+ "url": "https://github.com/guyzoum77/opticore-webApp/issues"
24
+ },
25
+ "homepage": "https://github.com/guyzoum77/opticore-webApp#readme",
26
+ "dependencies": {
27
+ "ansi-colors": "^4.1.3",
28
+ "cors": "^2.8.5",
29
+ "dotenv": "^16.4.7",
30
+ "express": "^4.21.0",
31
+ "express-rate-limit": "^5.5.1",
32
+ "express-session": "^1.0.0",
33
+ "express-useragent": "^1.0.15",
34
+ "gradient-string": "^2.0.2",
35
+ "opticore-logger": "^1.0.1",
36
+ "opticore-router": "^1.0.7",
37
+ "opticore-validator": "^1.0.3",
38
+ "typescript": "^5.4.5"
39
+ },
40
+ "devDependencies": {
41
+ "@types/cors": "^2.8.17",
42
+ "@types/express": "^4.17.21",
43
+ "@types/gradient-string": "^1.1.6",
44
+ "tsup": "^8.3.5"
45
+ }
46
+ }
@@ -0,0 +1,67 @@
1
+ import colors from "ansi-colors";
2
+
3
+ export const messageException = {
4
+ dbConnection: "DataBase connection",
5
+ dbConnectionClosed: "MySQL connection is closed",
6
+ mysqlErrorCon: "MysqlError connection",
7
+ mySQLError: "MysqlError",
8
+ mySqlCloseConnection: "MySql close connection",
9
+ verifyExistingKey: "Verify Existing Key",
10
+ invalidRequest: "Invalid request",
11
+ tokenNotProvided: "No token provided.",
12
+ ExpiresToken: "Expires Token. You're not authorize",
13
+ privateKeyNotExist: "A private key doesn't exist.",
14
+ publicKeyNotExist: "A public key doesn't exist.",
15
+ errorNamePublicKeyNotExist: "No public key",
16
+ errorAuthorPublicKeyNotExist: "PublicKey not existing",
17
+ errorDecryption: "Error decryption with private key",
18
+ rsaKeyNotFound: "RSA key provided is not found.",
19
+ notVerifyingRSAKey: "Not verify RSA Key",
20
+ errorNameNotVerifyingRSAKey: "Error Verify RSA Key",
21
+ errorEncryptionPublicKey: "Error encryption with public key",
22
+ errorEncryptionPrivateKey: "Error encryption with private key",
23
+ errorNameRsaVerifyExistingKey: "Verify existing key",
24
+ signatureRSAKeyFailed: "Signature verification failed.",
25
+ encryptionWithPrivateKeyFailed: "Encryption With PrivateKey",
26
+ encryptionFailed: "Encryption failed",
27
+ decryptionWithPublicKeyFailed: "Decryption With PublicKey",
28
+ decryptionFailed: "Decryption failed",
29
+ verifyRSAKey: "Verify RSA Keys",
30
+ verifyRSAKeyFailed: "Verify RSA Keys Failed",
31
+ notVerifying: "Verification failed",
32
+ signatureRSAKeysError: "Signature RSA Keys Error",
33
+ encryptionWithPublicKey: "Encryption error",
34
+ errorDecryptionWithPrivateKey: "Error Decryption With PrivateKey",
35
+ verifyPublicRSAKey: "Verify Public RSA Key",
36
+ PostgresDBConnectionChecker: "PostgresDB Connection Checker",
37
+ PostgresConnection: "connection",
38
+ MongoDBConnectionChecker: "MongoDB Connection Checker",
39
+ MongoConnection: "connection",
40
+ mongoDBAuthentication: "authentication",
41
+ mongoDBConnection: "MongoDB connection",
42
+ mongoDBAuthenticationFailed: "failed",
43
+ mongoDBUnableParsingUrl: "unable to parse",
44
+ mongoDBConnectionUrl: "url",
45
+ mongoDBServerSelection: "MongoServer selection error",
46
+ mongoDBServer: "MongoServer",
47
+ mongoDBConnectionError: "connection error",
48
+ mongoDBError: "error",
49
+ loadedModules: "Loading core modules",
50
+ loadedModulesError: "Required core modules are not loaded properly",
51
+ dbConnexionSuccess: "The database connection was successful 🚀",
52
+ mongoConnectionSuccess: "Connection to database is successfully.",
53
+ PostgresConnectionSuccess: "Connection to database is successfully.",
54
+ verifyExistingKeyError: "The provided key is not found",
55
+ webServer: "Web server",
56
+ listening: "listening",
57
+ webHost: "host",
58
+ badHost: "bad host",
59
+ hostNotFound: "not found",
60
+ errorHostUrl: "The host and port are not define, please define them in .env",
61
+ badPort: "bad port",
62
+ errorPort: "The port is not correct. Please define a right port with number port.",
63
+ errorHost: "The host can't be empty or blank. Please define a string host in .env",
64
+ accessDeniedToDBCon: (user: string, password: string): string => `Access denied for user ${user}. Database credentials in .env file are User: ${user} and Password: ${password}. '${user}''${password}'@'localhost'. Try to set user and password in .env file`,
65
+ unknownDB: (database: string): string => `Database ${database} is unknown. Please try to use Database CLI to create your database, or do it manually in your Database Management System`,
66
+ errorDBHost: (host: string): string => `A database host ${host} does not allow connection. Please either set the host like this: ${colors.bgRed(`${colors.white(`localhost`)}`)} in your .env file`
67
+ }
@@ -0,0 +1,67 @@
1
+ import express from "express";
2
+ import {ValidationResultInterface} from "opticore-validator";
3
+
4
+ export class ResponseHttp {
5
+ /**
6
+ *
7
+ * @param res
8
+ * @param status
9
+ * @param message
10
+ * @param apiVersion
11
+ */
12
+ static error(res: express.Response,
13
+ status: number,
14
+ message: string | ValidationResultInterface,
15
+ apiVersion: any): express.Response<any, Record<string, any>> {
16
+ return res.status(status).json({
17
+ errorMessage: message,
18
+ responseStatus: status,
19
+ version: apiVersion
20
+ });
21
+ }
22
+
23
+ /**
24
+ *
25
+ * @param res
26
+ * @param status
27
+ * @param context
28
+ * @param successMessage
29
+ * @param apiVersion
30
+ */
31
+ static success(res: express.Response,
32
+ status: number,
33
+ context: string,
34
+ successMessage: string,
35
+ apiVersion: any): express.Response<any, Record<string, any>> {
36
+ return res.status(200).json({
37
+ "@context": context,
38
+ message: successMessage,
39
+ responseStatus: status,
40
+ version: apiVersion
41
+ });
42
+ }
43
+
44
+ /**
45
+ *
46
+ * @param res
47
+ * @param status
48
+ * @param context
49
+ * @param successMessage
50
+ * @param data
51
+ * @param apiVersion
52
+ */
53
+ static successWithData (res: express.Response,
54
+ status: number,
55
+ context: string,
56
+ successMessage: string,
57
+ data: any,
58
+ apiVersion: any): express.Response<any, Record<string, any>> {
59
+ return res.status(200).json({
60
+ "@context": context,
61
+ message: successMessage,
62
+ dataResponse: data,
63
+ responseStatus: status,
64
+ version: apiVersion
65
+ });
66
+ }
67
+ }
@@ -0,0 +1,180 @@
1
+ import process from "node:process";
2
+ import chalk from 'chalk';
3
+ import * as path from "path";
4
+ import * as fs from "fs";
5
+ import colors from "ansi-colors";
6
+ import {KernelModuleType} from "@webApp/domains/types/kernelModule.type";
7
+ import express from "express";
8
+ import StackTraceError from "@webApp/core/handlers/errors/base/stackTraceError";
9
+ import {modulesLoadedUtils as loadedModules} from "@webApp/core/utils/modulesLoaded.utils";
10
+ import {messageException as msg} from "@webApp/application/exceptions/messages.exception";
11
+ import {HttpStatusCodesConstant as status} from "@webApp/domains/constants/httpStatusCodes.constant";
12
+
13
+
14
+ export class CoreService {
15
+
16
+ /**
17
+ *
18
+ * @param data
19
+ * @private
20
+ * Return a string converted in MegaBytes
21
+ */
22
+ private formatMemoryUsage(data: any): string {
23
+ return `${Math.round(data / 1024 / 1024 * 100) / 100} MB`;
24
+ }
25
+
26
+ /**
27
+ * Returns an Object containing a node version, openssl, and v0
28
+ */
29
+ public getVersions() {
30
+ const { node, openssl, v8 }: NodeJS.ProcessVersions = process.versions;
31
+ const data = {
32
+ "node version" : node,
33
+ "openssl": openssl,
34
+ "v8": v8
35
+ };
36
+
37
+ return {
38
+ "nodeVersion" : data["node version"],
39
+ "openssl": data.openssl,
40
+ "v8": data.v8
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Return an Object containing a Resident Set Size - total memory allocated for the process execution
46
+ * Total size of the allocated heap
47
+ * Actual memory used during the execution
48
+ * Memory usage user
49
+ * and Memory usage system
50
+ */
51
+ public getUsageMemory() {
52
+ const memoryData: NodeJS.MemoryUsage = process.memoryUsage();
53
+ const data = {
54
+ "Resident Set Size - total memory allocated for the process execution": this.formatMemoryUsage(memoryData.rss),
55
+ "Total size of the allocated heap": this.formatMemoryUsage(memoryData.heapTotal),
56
+ "Actual memory used during the execution": this.formatMemoryUsage(memoryData.heapUsed),
57
+ "V8 external memory": this.formatMemoryUsage(memoryData.external),
58
+ "Memory usage user": this.formatMemoryUsage(process.cpuUsage().user),
59
+ "Memory usage system": this.formatMemoryUsage(process.cpuUsage().system),
60
+ }
61
+
62
+ return {
63
+ "rss": data["Resident Set Size - total memory allocated for the process execution"],
64
+ "heapTotal": data["Total size of the allocated heap"],
65
+ "heapUsed": data["Actual memory used during the execution"],
66
+ "external": data["V8 external memory"],
67
+ "user": data["Memory usage user"],
68
+ "system": data["Memory usage system"]
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Return an Object containing a project path and running server time
74
+ */
75
+ public getProjectInfo() {
76
+ const startTime:[number, number] = process.hrtime();
77
+ const endTime:[number, number] = process.hrtime(startTime);
78
+ const executionTime: number = (endTime[0] * 1e9 + endTime[1]) / 1e6; // Convertir en millisecondes
79
+ return {
80
+ "projectPath": path.join(process.cwd()),
81
+ "startingTime": `${executionTime.toFixed(5)} ms`
82
+ }
83
+ }
84
+
85
+ /**
86
+ *
87
+ * @param filePath
88
+ * @private
89
+ */
90
+ private getEnvFileLoading(filePath: string): void {
91
+ const fullPath: string = path.resolve(process.cwd(), filePath);
92
+ if (fs.existsSync(fullPath)) {
93
+ const env: string = fs.readFileSync(fullPath, 'utf-8');
94
+ const lines: string[] = env.split('\n');
95
+
96
+ lines.forEach((line: string): void => {
97
+ const match: RegExpMatchArray | null = line.match(/^([^#=]+)=([^#]+)$/);
98
+ if (match) {
99
+ const key: string = match[1].trim();
100
+ process.env[key] = match[2].trim();
101
+ }
102
+ });
103
+ }
104
+ }
105
+
106
+ /**
107
+ *
108
+ * @param development
109
+ * @param production
110
+ */
111
+ public getServerRunningMode(development: string, production: string, ): string {
112
+ /**
113
+ * Load environment variables from the .env file
114
+ */
115
+ this.getEnvFileLoading('.env');
116
+
117
+ const isDevelopment: boolean = process.env.NODE_ENV === 'development';
118
+ if (isDevelopment) {
119
+ return `The server is running in ${colors.bgBlue(`${colors.bold(`${development}`)}`)} mode`;
120
+ } else {
121
+ return `The server is running in ${colors.bgBlue(`${colors.bold(`${production}`)}`)} mode`;
122
+ }
123
+ }
124
+
125
+ public infoServer(nodeVersion: string, startingTime: any, host: string, port: number, rss: string, heapUsed: string, user: string, system: string): void {
126
+ // Padding length
127
+ const paddingLength = 52;
128
+
129
+ // Creating padded messages
130
+ const msg0: string = ' '.padEnd(paddingLength, ' ');
131
+ const msg1: string = ' [OK] Web server listening';
132
+ const msg2Value: string = `${colors.bgBlue(`${colors.bold(`${nodeVersion}`)}`)}`;
133
+ const msg2: string = ` The Web server is using Node.js version`;
134
+ const msg3Value: string = `${colors.bgBlue(`${colors.bold(`${startingTime}`)}`)}`;
135
+ const msg3: string = ` Startup time:`;
136
+ const msg4: string = ` ${this.getServerRunningMode('development', 'production')}`;
137
+ const msg5: string = ` ${colors.underline(`http://${host}:${port}`)}`;
138
+
139
+ // display the message
140
+ console.log(chalk.bgGreen.white(msg0.padEnd(paddingLength, ' ')));
141
+ console.log(chalk.bgGreen.white(msg1.padEnd(paddingLength, ' ')));
142
+ console.log(chalk.bgGreen.white(msg2, msg2Value.padEnd(30.5, ' ')));
143
+ console.log(chalk.bgGreen.white(msg3, msg3Value.padEnd(56, ' ')));
144
+ console.log(chalk.bgGreen.white(msg4.padEnd(71, ' ')));
145
+ console.log(chalk.bgGreen.white(msg5.padEnd(61, ' ')));
146
+ console.log(chalk.bgGreen.white(msg0.padEnd(paddingLength, ' ')));
147
+ console.log(``);
148
+ console.log(`${(`Resident Set Size - total memory allocated for the process execution :`)} ${colors.cyan(`${colors.bold(`${rss}`)}`)}`);
149
+ console.log(`${(`Actual memory used during the execution :`)} ${colors.cyan(`${colors.bold(`${heapUsed}`)}`)}`);
150
+ console.log(`${(`Memory usage by user :`)} ${colors.cyan(`${colors.bold(`${user}`)}`)}`);
151
+ console.log(`${(`Memory usage by system :`)} ${colors.cyan(`${colors.bold(`${system}`)}`)}`);
152
+ console.log(``);
153
+ }
154
+
155
+ public coreListenerEventLoaderModuleService<T extends KernelModuleType>(kernelModule: T) {
156
+ let router: express.Router[] = [];
157
+ let dbCon: (() => void) | undefined;
158
+
159
+ kernelModule.forEach((module): void => {
160
+ if (Array.isArray(module)) {
161
+ router = module as express.Router[];
162
+ } else if (typeof module === "function") {
163
+ dbCon = module as () => void;
164
+ }
165
+ });
166
+
167
+ if (router && dbCon) {
168
+ loadedModules(router, dbCon);
169
+ ((): void => { dbCon(); })();
170
+ } else {
171
+ const stackTrace: StackTraceError = new StackTraceError(
172
+ msg.loadedModulesError,
173
+ msg.loadedModules,
174
+ status.NOT_ACCEPTABLE,
175
+ true
176
+ );
177
+ throw new Error(stackTrace.message);
178
+ }
179
+ }
180
+ }
File without changes
File without changes