@expressots/core 2.15.0 → 2.16.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.
package/lib/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
 
2
2
 
3
+ ## [2.16.0](https://github.com/expressots/expressots/compare/2.15.0...2.16.0) (2024-08-08)
4
+
5
+
6
+ ### Features
7
+
8
+ * add stack trace option on defaultErrorHandler middleware ([c9005ed](https://github.com/expressots/expressots/commit/c9005ed4e28bd76f7622f1bd006d90b18e8b0cf6))
9
+ * add urlEncodedParser default middleware ([ec44767](https://github.com/expressots/expressots/commit/ec44767e41d8a1a208bb2be1120bb13a97942b20))
10
+ * bump release-it from 17.5.0 to 17.6.0 ([bbdc3c8](https://github.com/expressots/expressots/commit/bbdc3c8ad692775f96f26ba3da952f38441aa58e))
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * remove express dependency and middlewares.spec ([b538cce](https://github.com/expressots/expressots/commit/b538cce0a9b61e43988d3190973dd79993da833b))
16
+
17
+
18
+ ### Code Refactoring
19
+
20
+ * adjust command dev, build, prod ([c819625](https://github.com/expressots/expressots/commit/c819625327a3e9632d418eed0e26af7fa80dcdcc))
21
+ * remove opinionated template example ([bca45ac](https://github.com/expressots/expressots/commit/bca45ac19e4415452e6194468d54a6f34ec5c5d7))
22
+
23
+
24
+ ### Tests
25
+
26
+ * ignore middleware service, utils ([6c3e6f7](https://github.com/expressots/expressots/commit/6c3e6f7af7c656ec15e5a5ced23af05eef8a0872))
27
+ * ignore spec on coverage & better comments in app-factory ([698053d](https://github.com/expressots/expressots/commit/698053deeb538fdfdff6ed4a75fd616052df4f58))
28
+
3
29
  ## [2.15.0](https://github.com/expressots/expressots/compare/2.14.1...2.15.0) (2024-07-17)
4
30
 
5
31
 
@@ -18,8 +18,8 @@ function isWebServerConstructor(input) {
18
18
  class AppFactory {
19
19
  /**
20
20
  * Create an instance of a web server.
21
- * @param container - InversifyJS container to resolve dependencies.
22
- * @param webServerType - Constructor of a class that implements IWebServer, or array of middlewares.
21
+ * @param container - Dependency injection container.
22
+ * @param webServerType - Constructor of a class that implements IWebServer.
23
23
  * @returns A promise that resolves to an instance of IWebServer.
24
24
  */
25
25
  static async create(container, webServerType) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const app_error_1 = require("./app-error");
4
4
  const status_code_1 = require("./status-code");
5
+ const utils_1 = require("./utils");
5
6
  /**
6
7
  * errorHandler is a custom Express error-handling middleware function.
7
8
  * It logs the error, sets the status code, and sends a JSON response containing the status code and error message.
@@ -9,20 +10,30 @@ const status_code_1 = require("./status-code");
9
10
  * @param req - The Express request object.
10
11
  * @param res - The Express response object.
11
12
  * @param next - The Express next function for passing control to the next middleware function.
13
+ * @param showStackTrace - A boolean value indicating whether to show the stack trace in the response.
12
14
  */
13
15
  function defaultErrorHandler(error, req, res,
14
16
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
15
- next) {
16
- if (error instanceof app_error_1.AppError) {
17
- res
18
- .status(error.statusCode)
19
- .json({ statusCode: error.statusCode, error: error.message });
17
+ next, showStackTrace = false) {
18
+ try {
19
+ if (error instanceof app_error_1.AppError) {
20
+ res.status(error.statusCode).json({
21
+ statusCode: error.statusCode,
22
+ error: error.message,
23
+ });
24
+ }
25
+ else {
26
+ res.status(status_code_1.StatusCode.InternalServerError).json({
27
+ statusCode: status_code_1.StatusCode.InternalServerError,
28
+ error: "An unexpected error occurred.",
29
+ });
30
+ }
31
+ if (showStackTrace && error.stack) {
32
+ (0, utils_1.beautifyStackTrace)(error.stack);
33
+ }
20
34
  }
21
- else {
22
- res.status(status_code_1.StatusCode.InternalServerError).json({
23
- statusCode: status_code_1.StatusCode.InternalServerError,
24
- error: "An unexpected error occurred.",
25
- });
35
+ catch (error) {
36
+ next(error);
26
37
  }
27
38
  }
28
39
  exports.default = defaultErrorHandler;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.beautifyStackTrace = beautifyStackTrace;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ function beautifyStackTrace(stack) {
9
+ if (!stack)
10
+ return;
11
+ const lines = stack.split("\n");
12
+ const errorMessage = lines.shift()?.trim();
13
+ const maxOriginLength = "[External Library]".length;
14
+ const stackLines = lines
15
+ .filter((line) => line.trim().startsWith("at"))
16
+ .map((line) => line.trim())
17
+ .map((line) => {
18
+ const isExternalLib = line.includes("node_modules");
19
+ const filePathMatch = line.match(/\((.*):(\d+):(\d+)\)/);
20
+ const filePath = filePathMatch
21
+ ? `${filePathMatch[1]}:${filePathMatch[2]}:${filePathMatch[3]}`
22
+ : "";
23
+ const stackMessage = line.replace(/\(.*\)/, "").trim();
24
+ return {
25
+ origin: isExternalLib
26
+ ? chalk_1.default.gray("[External Library]").padEnd(maxOriginLength)
27
+ : chalk_1.default.gray("[Application] ").padEnd(maxOriginLength),
28
+ stackMessage: chalk_1.default.green(stackMessage),
29
+ filePath: chalk_1.default.white(filePath),
30
+ };
31
+ });
32
+ if (stackLines.length > 0) {
33
+ console.log(chalk_1.default.red.bold(`Error Originated From: ${chalk_1.default.bold.white(stackLines[0]?.filePath || "unknown")}`));
34
+ }
35
+ console.log(chalk_1.default.red.bold(errorMessage));
36
+ console.log(chalk_1.default.blue.bold("\nStack Trace:\n"));
37
+ stackLines.forEach(({ origin, stackMessage, filePath }) => {
38
+ console.log(`${origin} | ${stackMessage} | ${filePath}`);
39
+ });
40
+ return "";
41
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -25,6 +25,7 @@ class MiddlewareResolver {
25
25
  rateLimit: "express-rate-limit",
26
26
  multer: "multer",
27
27
  session: "express-session",
28
+ urlencoded: "urlencodedParser",
28
29
  // Add other middlewares
29
30
  };
30
31
  this.logger = new logger_provider_1.Logger();
@@ -93,6 +93,24 @@ let Middleware = class Middleware {
93
93
  return false;
94
94
  });
95
95
  }
96
+ /**
97
+ * Adds a URL Encoded Parser middleware to the middleware collection.
98
+ * The URL Encoded Parser is responsible for parsing the URL-encoded data in the incoming request bodies.
99
+ *
100
+ * @param options - Optional configuration options for the URL Encoded Parser.
101
+ */
102
+ addUrlEncodedParser(options) {
103
+ const middlewareExist = this.middlewareExists("urlencodedParser");
104
+ if (middlewareExist) {
105
+ this.logger.warn(`[urlencodedParser] already exists. Skipping...`, "configure-service");
106
+ }
107
+ else {
108
+ this.middlewarePipeline.push({
109
+ timestamp: new Date(),
110
+ middleware: express_1.default.urlencoded(options),
111
+ });
112
+ }
113
+ }
96
114
  addRateLimiter(options) {
97
115
  const middleware = (0, middleware_resolver_1.middlewareResolver)("rateLimit", options);
98
116
  const middlewareExist = this.middlewareExists("rateLimit");
@@ -257,11 +275,16 @@ let Middleware = class Middleware {
257
275
  /**
258
276
  * Configures the error handling middleware for the application.
259
277
  *
260
- * @param errorHandling - The Express error handler function that takes care of processing errors and formulating the response.
278
+ * @param options - The object containing the configuration options for the error handler middleware.
279
+ * @param errorHandler - The Express error handler function that takes care of processing errors and formulating the response.
280
+ * @param showStackTrace - A boolean value indicating whether to show the stack trace in the response.
261
281
  */
262
- setErrorHandler(errorHandling) {
282
+ setErrorHandler(options = {}) {
283
+ const { errorHandler: errorHandling, showStackTrace } = options;
263
284
  if (!errorHandling) {
264
- this.errorHandler = error_handler_middleware_1.default;
285
+ this.errorHandler = (error, req, res, next) => {
286
+ (0, error_handler_middleware_1.default)(error, req, res, next, showStackTrace);
287
+ };
265
288
  }
266
289
  else {
267
290
  this.errorHandler = errorHandling;
@@ -10,8 +10,8 @@ declare class AppFactory {
10
10
  private static logger;
11
11
  /**
12
12
  * Create an instance of a web server.
13
- * @param container - InversifyJS container to resolve dependencies.
14
- * @param webServerType - Constructor of a class that implements IWebServer, or array of middlewares.
13
+ * @param container - Dependency injection container.
14
+ * @param webServerType - Constructor of a class that implements IWebServer.
15
15
  * @returns A promise that resolves to an instance of IWebServer.
16
16
  */
17
17
  static create<T extends IWebServer>(container: Container, webServerType: IWebServerConstructor<T>): Promise<IWebServerPublic>;
@@ -6,6 +6,7 @@ import { NextFunction, Request, Response } from "express";
6
6
  * @param req - The Express request object.
7
7
  * @param res - The Express response object.
8
8
  * @param next - The Express next function for passing control to the next middleware function.
9
+ * @param showStackTrace - A boolean value indicating whether to show the stack trace in the response.
9
10
  */
10
- declare function defaultErrorHandler(error: Error, req: Request, res: Response, next: NextFunction): void;
11
+ declare function defaultErrorHandler(error: Error, req: Request, res: Response, next: NextFunction, showStackTrace?: boolean): void;
11
12
  export default defaultErrorHandler;
@@ -0,0 +1 @@
1
+ export declare function beautifyStackTrace(stack: string): string;
@@ -1,4 +1,4 @@
1
- export { IMiddleware, Middleware, ExpressHandler, ExpressoMiddleware, MiddlewareOptions, } from "./middleware-service";
1
+ export { IMiddleware, Middleware, ExpressHandler, ExpressoMiddleware, MiddlewareOptions, ErrorHandlerOptions, } from "./middleware-service";
2
2
  export { OptionsJson } from "./interfaces/body-parser.interface";
3
3
  export { CorsOptions } from "./interfaces/cors.interface";
4
4
  export { CompressionOptions } from "./interfaces/compression.interface";
@@ -10,4 +10,5 @@ export { CookieParserOptions } from "./interfaces/cookie-parser.interface";
10
10
  export { ServeFaviconOptions } from "./interfaces/serve-favicon.interface";
11
11
  export { RateLimitOptions } from "./interfaces/express-rate-limit.interface";
12
12
  export { multer } from "./interfaces/multer.interface";
13
+ export { OptionsUrlencoded } from "./interfaces/url-encoded.interface";
13
14
  export * as IMorgan from "./interfaces/morgan.interface";
@@ -0,0 +1,37 @@
1
+ import * as http from "http";
2
+ interface Options {
3
+ /** When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true. */
4
+ inflate?: boolean | undefined;
5
+ /**
6
+ * Controls the maximum request body size. If this is a number,
7
+ * then the value specifies the number of bytes; if it is a string,
8
+ * the value is passed to the bytes library for parsing. Defaults to '100kb'.
9
+ */
10
+ limit?: number | string | undefined;
11
+ /**
12
+ * The type option is used to determine what media type the middleware will parse
13
+ */
14
+ type?: string | Array<string> | ((req: http.IncomingMessage) => any) | undefined;
15
+ /**
16
+ * The verify option, if supplied, is called as verify(req, res, buf, encoding),
17
+ * where buf is a Buffer of the raw request body and encoding is the encoding of the request.
18
+ */
19
+ verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void;
20
+ }
21
+ /**
22
+ * These are the options available to urlencodedParser.
23
+ */
24
+ export interface OptionsUrlencoded extends Options {
25
+ /**
26
+ * The extended option allows to choose between parsing the URL-encoded data
27
+ * with the querystring library (when `false`) or the qs library (when `true`).
28
+ */
29
+ extended?: boolean | undefined;
30
+ /**
31
+ * The parameterLimit option controls the maximum number of parameters
32
+ * that are allowed in the URL-encoded data. If a request contains more parameters than this value,
33
+ * a 413 will be returned to the client. Defaults to 1000.
34
+ */
35
+ parameterLimit?: number | undefined;
36
+ }
37
+ export {};
@@ -11,6 +11,7 @@ import { RateLimitOptions } from "./interfaces/express-rate-limit.interface";
11
11
  import { OptionsHelmet } from "./interfaces/helmet.interface";
12
12
  import { multer } from "./interfaces/multer.interface";
13
13
  import { SessionOptions } from "./interfaces/express-session.interface";
14
+ import { OptionsUrlencoded } from "./interfaces/url-encoded.interface";
14
15
  /**
15
16
  * ExpressHandler Type
16
17
  *
@@ -66,11 +67,29 @@ interface MiddlewarePipeline {
66
67
  timestamp: Date;
67
68
  middleware: ExpressHandler | MiddlewareConfig | IExpressoMiddleware;
68
69
  }
70
+ /**
71
+ * ErrorHandlerOptions Interface
72
+ *
73
+ * The ErrorHandlerOptions interface specifies the configuration options for the error handler middleware.
74
+ * @param errorHandler: An Express error handler function that takes care of processing errors and formulating the response.
75
+ * @param showStackTrace: A boolean value indicating whether to include the stack trace in the error response. The default value is false.
76
+ */
77
+ export interface ErrorHandlerOptions {
78
+ errorHandler?: ExpressHandler;
79
+ showStackTrace?: boolean;
80
+ }
69
81
  /**
70
82
  * Interface for configuring and managing middlewares in the application.
71
83
  * Provides methods to be added automatically in the application without the need to import packages.
72
84
  */
73
85
  interface IMiddleware {
86
+ /**
87
+ * Adds a URL Encoded Parser middleware to the middleware collection.
88
+ * The URL Encoded Parser is responsible for parsing the URL-encoded data in the incoming request bodies.
89
+ *
90
+ * @param options - Optional configuration options for the URL Encoded Parser.
91
+ */
92
+ addUrlEncodedParser(options?: OptionsUrlencoded): void;
74
93
  /**
75
94
  * Adds a Rate Limit middleware to the middleware collection.
76
95
  * The rate limiter is responsible for adding dynamic rate limit and request throttling to the application.
@@ -135,9 +154,11 @@ interface IMiddleware {
135
154
  /**
136
155
  * Configures the error handling middleware for the application.
137
156
  *
138
- * @param errorHandling - The Express error handler function that takes care of processing errors and formulating the response.
157
+ * @param options - The object containing the configuration options for the error handler middleware.
158
+ * @param errorHandler - The Express error handler function that takes care of processing errors and formulating the response.
159
+ * @param showStackTrace - A boolean value indicating whether to show the stack trace in the response.
139
160
  */
140
- setErrorHandler(errorHandling?: ExpressHandler): void;
161
+ setErrorHandler(options?: ErrorHandlerOptions): void;
141
162
  /**
142
163
  * Adds a middleware to serve static files from the specified root directory.
143
164
  * Allows the application to serve files like images, CSS, JavaScript, etc.
@@ -225,6 +246,13 @@ declare class Middleware implements IMiddleware {
225
246
  * @returns A boolean value indicating whether the middleware exists or not.
226
247
  */
227
248
  private middlewareExists;
249
+ /**
250
+ * Adds a URL Encoded Parser middleware to the middleware collection.
251
+ * The URL Encoded Parser is responsible for parsing the URL-encoded data in the incoming request bodies.
252
+ *
253
+ * @param options - Optional configuration options for the URL Encoded Parser.
254
+ */
255
+ addUrlEncodedParser(options?: OptionsUrlencoded): void;
228
256
  addRateLimiter(options?: RateLimitOptions): void;
229
257
  /**
230
258
  * Adds a Body Parser middleware to the middleware collection using the given options.
@@ -290,9 +318,11 @@ declare class Middleware implements IMiddleware {
290
318
  /**
291
319
  * Configures the error handling middleware for the application.
292
320
  *
293
- * @param errorHandling - The Express error handler function that takes care of processing errors and formulating the response.
321
+ * @param options - The object containing the configuration options for the error handler middleware.
322
+ * @param errorHandler - The Express error handler function that takes care of processing errors and formulating the response.
323
+ * @param showStackTrace - A boolean value indicating whether to show the stack trace in the response.
294
324
  */
295
- setErrorHandler(errorHandling?: ExpressHandler): void;
325
+ setErrorHandler(options?: ErrorHandlerOptions): void;
296
326
  /**
297
327
  * Adds a middleware to serve static files from the specified root directory.
298
328
  * Allows the application to serve files like images, CSS, JavaScript, etc.
package/lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/core",
3
- "version": "2.15.0",
3
+ "version": "2.16.0",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@core)",
5
5
  "author": "Richard Zampieri",
6
6
  "main": "./lib/cjs/index.js",
@@ -87,7 +87,7 @@
87
87
  "eslint-config-prettier": "9.1.0",
88
88
  "husky": "9.0.11",
89
89
  "prettier": "3.3.3",
90
- "release-it": "17.5.0",
90
+ "release-it": "17.6.0",
91
91
  "typescript": "5.5.3",
92
92
  "vite": "5.3.3",
93
93
  "vite-tsconfig-paths": "4.3.2",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@expressots/core",
3
- "version": "2.15.0",
3
+ "version": "2.16.0",
4
4
  "description": "Expressots - modern, fast, lightweight nodejs web framework (@core)",
5
5
  "author": "Richard Zampieri",
6
6
  "main": "./lib/cjs/index.js",
@@ -87,7 +87,7 @@
87
87
  "eslint-config-prettier": "9.1.0",
88
88
  "husky": "9.0.11",
89
89
  "prettier": "3.3.3",
90
- "release-it": "17.5.0",
90
+ "release-it": "17.6.0",
91
91
  "typescript": "5.5.3",
92
92
  "vite": "5.3.3",
93
93
  "vite-tsconfig-paths": "4.3.2",