@heliosjs/middlewares 10.0.5 → 10.0.7

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/catch.d.ts CHANGED
@@ -1,29 +1,32 @@
1
1
  import type { ErrorHandler } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to register a global or controller-level error handler.
3
+ * Registers an error handler on a controller class or a single route method. It
4
+ * fires when a guard, pipe, middleware, handler, or interceptor throws.
4
5
  *
5
- * This decorator accepts an error handling callback function which will be invoked
6
- * whenever an error occurs within the decorated target's scope (e.g., controller or service).
7
- * It attaches the handler as metadata on the target class, allowing the framework to
8
- * retrieve and execute the error handler appropriately during runtime.
6
+ * Handlers run newest-first (method-level before controller-level). The first one
7
+ * that **returns a non-Error value** stops the chain and that value becomes the
8
+ * response body; a handler that returns an `Error` or re-throws passes control to
9
+ * the next handler, and if none resolves the error it propagates to the adapter's
10
+ * default error response.
9
11
  *
10
- * @param {ErrorHandler} handler - The error callback function to handle errors.
12
+ * Declaring `@Catch` also opts the route into handling the "self-resolving" error
13
+ * codes (`FORBIDDEN`, `NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `UNAUTHORIZED`) that
14
+ * otherwise bypass error handlers.
11
15
  *
12
- * @returns {Function} A class decorator function that defines the error handler metadata.
16
+ * @param handler - `(error, req, res) => unknown`. `error` is the thrown value
17
+ * (often a `HeliosError` subclass with `.code` / `.status`). Return a value to
18
+ * answer the request, or return/throw an `Error` to defer. May be async. Why:
19
+ * map domain errors to response shapes in one place.
20
+ *
21
+ * @returns A class or method decorator.
13
22
  *
14
23
  * @example
15
- * // Register a global error handler for a controller
16
- * @Catch(async (error, context) => {
17
- * console.error('Error caught:', error);
18
- * // Custom error handling logic
24
+ * ```ts
25
+ * @Catch((err, req, res) => {
26
+ * if (err instanceof NotFoundError) return { error: 'not found', path: req.path };
27
+ * throw err; // let the framework handle everything else
19
28
  * })
20
- * class MyController {
21
- * // ...
22
- * }
23
- *
24
- * @remarks
25
- * The metadata key used for storing the error handler is defined by `CATCH`.
26
- * This metadata is accessible via Reflect API and used internally by the framework
27
- * to invoke the registered error handler when errors occur.
29
+ * class MyController {}
30
+ * ```
28
31
  */
29
- export declare function Catch(handler: ErrorHandler): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
32
+ export declare function Catch(handler: ErrorHandler): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/catch.js CHANGED
@@ -3,36 +3,39 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Catch = Catch;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register a global or controller-level error handler.
6
+ * Registers an error handler on a controller class or a single route method. It
7
+ * fires when a guard, pipe, middleware, handler, or interceptor throws.
7
8
  *
8
- * This decorator accepts an error handling callback function which will be invoked
9
- * whenever an error occurs within the decorated target's scope (e.g., controller or service).
10
- * It attaches the handler as metadata on the target class, allowing the framework to
11
- * retrieve and execute the error handler appropriately during runtime.
9
+ * Handlers run newest-first (method-level before controller-level). The first one
10
+ * that **returns a non-Error value** stops the chain and that value becomes the
11
+ * response body; a handler that returns an `Error` or re-throws passes control to
12
+ * the next handler, and if none resolves the error it propagates to the adapter's
13
+ * default error response.
12
14
  *
13
- * @param {ErrorHandler} handler - The error callback function to handle errors.
15
+ * Declaring `@Catch` also opts the route into handling the "self-resolving" error
16
+ * codes (`FORBIDDEN`, `NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `UNAUTHORIZED`) that
17
+ * otherwise bypass error handlers.
14
18
  *
15
- * @returns {Function} A class decorator function that defines the error handler metadata.
19
+ * @param handler - `(error, req, res) => unknown`. `error` is the thrown value
20
+ * (often a `HeliosError` subclass with `.code` / `.status`). Return a value to
21
+ * answer the request, or return/throw an `Error` to defer. May be async. Why:
22
+ * map domain errors to response shapes in one place.
23
+ *
24
+ * @returns A class or method decorator.
16
25
  *
17
26
  * @example
18
- * // Register a global error handler for a controller
19
- * @Catch(async (error, context) => {
20
- * console.error('Error caught:', error);
21
- * // Custom error handling logic
27
+ * ```ts
28
+ * @Catch((err, req, res) => {
29
+ * if (err instanceof NotFoundError) return { error: 'not found', path: req.path };
30
+ * throw err; // let the framework handle everything else
22
31
  * })
23
- * class MyController {
24
- * // ...
25
- * }
26
- *
27
- * @remarks
28
- * The metadata key used for storing the error handler is defined by `CATCH`.
29
- * This metadata is accessible via Reflect API and used internally by the framework
30
- * to invoke the registered error handler when errors occur.
32
+ * class MyController {}
33
+ * ```
31
34
  */
32
35
  function Catch(handler) {
33
- return function (target, propertyKey, descriptor) {
36
+ return function (target, propertyKey, _descriptor) {
34
37
  const data = [{ errorHandler: handler }];
35
- if (descriptor) {
38
+ if (propertyKey) {
36
39
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
37
40
  }
38
41
  else {
package/dist/catch.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"catch.js","sourceRoot":"","sources":["../src/catch.ts"],"names":[],"mappings":";;AA6BA,sBAUC;AAtCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,SAAgB,KAAK,CAAC,OAAqB;IACzC,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"catch.js","sourceRoot":"","sources":["../src/catch.ts"],"names":[],"mappings":";;AAgCA,sBAUC;AAzCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,SAAgB,KAAK,CAAC,OAAqB;IACzC,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;QAEzC,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/cors.d.ts CHANGED
@@ -1,37 +1,42 @@
1
1
  import type { CORSConfig } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to configure Cross-Origin Resource Sharing (CORS) settings for HTTP controllers or methods.
3
+ * Configures Cross-Origin Resource Sharing for a controller class or a single
4
+ * route method. On a preflight (`OPTIONS`) request the response is answered
5
+ * directly with the negotiated CORS headers and `optionsSuccessStatus`; on a
6
+ * real request a disallowed origin is rejected with HTTP 403.
4
7
  *
5
- * This decorator allows you to specify CORS policies such as allowed origins, HTTP methods, and
6
- * the status code to return for successful OPTIONS requests. It can be applied at the class level
7
- * to affect all endpoints within a controller or at the method level to customize CORS for specific endpoints.
8
+ * Unspecified keys fall back to: `origin: '*'`, `optionsSuccessStatus: 204`,
9
+ * `methods:` every HTTP method Helios knows.
8
10
  *
9
- * When applied, the decorator defines metadata on the target (class prototype or method) which can be
10
- * later retrieved by the framework to enforce CORS policies during request handling.
11
+ * @param config - CORS options (all optional):
12
+ * - `origin` `string`, `string[]`, or `(origin) => boolean`. `'*'` allows
13
+ * any origin; a list allows exact matches; a function decides per request.
14
+ * Why: the allow-list is the core of the policy.
15
+ * - `methods` — allowed methods for `Access-Control-Allow-Methods`, e.g.
16
+ * `['GET', 'POST']`. Why: advertise only what the route group supports.
17
+ * - `allowedHeaders` — value for `Access-Control-Allow-Headers` (request
18
+ * headers the browser may send). Why: without this, custom headers like
19
+ * `Authorization` are blocked on cross-origin calls.
20
+ * - `exposedHeaders` — response headers JS may read
21
+ * (`Access-Control-Expose-Headers`). Why: e.g. expose `X-Total-Count`.
22
+ * - `credentials` — when `true`, sets `Access-Control-Allow-Credentials: true`
23
+ * so cookies / `Authorization` are sent. Why: required for cookie auth;
24
+ * cannot be combined with `origin: '*'` per the spec.
25
+ * - `maxAge` — seconds a browser may cache the preflight result. Why: fewer
26
+ * `OPTIONS` round-trips.
27
+ * - `optionsSuccessStatus` — status for a successful preflight (default `204`;
28
+ * use `200` for legacy browsers that choke on 204).
11
29
  *
12
- * @param {CORSConfig} [config={}] - Configuration object for CORS settings.
13
- * @param {string|string[]} [config.origin='*'] - Specifies the allowed origin(s) for CORS requests. Defaults to '*'.
14
- * @param {number} [config.optionsSuccessStatus=204] - HTTP status code to return for successful OPTIONS requests.
15
- * @param {string[]} [config.methods=Object.keys(HTTP_METHODS)] - Array of allowed HTTP methods for CORS.
16
- *
17
- * @returns {Function} A decorator function that applies the CORS configuration metadata.
18
- *
19
- * @example
20
- * // Apply CORS with default settings to all endpoints in a controller
21
- * @Cors()
22
- * class MyController {
23
- * // ...
24
- * }
30
+ * @returns A class or method decorator.
25
31
  *
26
32
  * @example
27
- * // Apply CORS with custom settings to a specific method
28
- * @Cors({ origin: 'https://example.com', methods: ['GET', 'POST'] })
29
- * async myMethod() {
30
- * // ...
31
- * }
32
- *
33
- * @remarks
34
- * The metadata key used for storing the CORS configuration is defined by `CORS_METADATA`.
35
- * This metadata is accessible via Reflect API and used internally by the framework to enforce CORS.
33
+ * ```ts
34
+ * @Cors({
35
+ * origin: ['https://app.example.com'],
36
+ * methods: ['GET', 'POST'],
37
+ * credentials: true,
38
+ * })
39
+ * class ApiController {}
40
+ * ```
36
41
  */
37
- export declare function Cors(config?: CORSConfig): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
42
+ export declare function Cors(config?: CORSConfig): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/cors.js CHANGED
@@ -4,42 +4,47 @@ exports.Cors = Cors;
4
4
  const types_1 = require("@heliosjs/core/types");
5
5
  const utils_1 = require("@heliosjs/core/utils");
6
6
  /**
7
- * Decorator to configure Cross-Origin Resource Sharing (CORS) settings for HTTP controllers or methods.
7
+ * Configures Cross-Origin Resource Sharing for a controller class or a single
8
+ * route method. On a preflight (`OPTIONS`) request the response is answered
9
+ * directly with the negotiated CORS headers and `optionsSuccessStatus`; on a
10
+ * real request a disallowed origin is rejected with HTTP 403.
8
11
  *
9
- * This decorator allows you to specify CORS policies such as allowed origins, HTTP methods, and
10
- * the status code to return for successful OPTIONS requests. It can be applied at the class level
11
- * to affect all endpoints within a controller or at the method level to customize CORS for specific endpoints.
12
+ * Unspecified keys fall back to: `origin: '*'`, `optionsSuccessStatus: 204`,
13
+ * `methods:` every HTTP method Helios knows.
12
14
  *
13
- * When applied, the decorator defines metadata on the target (class prototype or method) which can be
14
- * later retrieved by the framework to enforce CORS policies during request handling.
15
+ * @param config - CORS options (all optional):
16
+ * - `origin` `string`, `string[]`, or `(origin) => boolean`. `'*'` allows
17
+ * any origin; a list allows exact matches; a function decides per request.
18
+ * Why: the allow-list is the core of the policy.
19
+ * - `methods` — allowed methods for `Access-Control-Allow-Methods`, e.g.
20
+ * `['GET', 'POST']`. Why: advertise only what the route group supports.
21
+ * - `allowedHeaders` — value for `Access-Control-Allow-Headers` (request
22
+ * headers the browser may send). Why: without this, custom headers like
23
+ * `Authorization` are blocked on cross-origin calls.
24
+ * - `exposedHeaders` — response headers JS may read
25
+ * (`Access-Control-Expose-Headers`). Why: e.g. expose `X-Total-Count`.
26
+ * - `credentials` — when `true`, sets `Access-Control-Allow-Credentials: true`
27
+ * so cookies / `Authorization` are sent. Why: required for cookie auth;
28
+ * cannot be combined with `origin: '*'` per the spec.
29
+ * - `maxAge` — seconds a browser may cache the preflight result. Why: fewer
30
+ * `OPTIONS` round-trips.
31
+ * - `optionsSuccessStatus` — status for a successful preflight (default `204`;
32
+ * use `200` for legacy browsers that choke on 204).
15
33
  *
16
- * @param {CORSConfig} [config={}] - Configuration object for CORS settings.
17
- * @param {string|string[]} [config.origin='*'] - Specifies the allowed origin(s) for CORS requests. Defaults to '*'.
18
- * @param {number} [config.optionsSuccessStatus=204] - HTTP status code to return for successful OPTIONS requests.
19
- * @param {string[]} [config.methods=Object.keys(HTTP_METHODS)] - Array of allowed HTTP methods for CORS.
20
- *
21
- * @returns {Function} A decorator function that applies the CORS configuration metadata.
22
- *
23
- * @example
24
- * // Apply CORS with default settings to all endpoints in a controller
25
- * @Cors()
26
- * class MyController {
27
- * // ...
28
- * }
34
+ * @returns A class or method decorator.
29
35
  *
30
36
  * @example
31
- * // Apply CORS with custom settings to a specific method
32
- * @Cors({ origin: 'https://example.com', methods: ['GET', 'POST'] })
33
- * async myMethod() {
34
- * // ...
35
- * }
36
- *
37
- * @remarks
38
- * The metadata key used for storing the CORS configuration is defined by `CORS_METADATA`.
39
- * This metadata is accessible via Reflect API and used internally by the framework to enforce CORS.
37
+ * ```ts
38
+ * @Cors({
39
+ * origin: ['https://app.example.com'],
40
+ * methods: ['GET', 'POST'],
41
+ * credentials: true,
42
+ * })
43
+ * class ApiController {}
44
+ * ```
40
45
  */
41
46
  function Cors(config = {}) {
42
- return function (target, propertyKey, descriptor) {
47
+ return function (target, propertyKey, _descriptor) {
43
48
  const defaultConfig = {
44
49
  origin: '*',
45
50
  optionsSuccessStatus: 204,
@@ -47,7 +52,7 @@ function Cors(config = {}) {
47
52
  };
48
53
  const finalConfig = { ...defaultConfig, ...config };
49
54
  const data = [{ cors: finalConfig }];
50
- if (descriptor) {
55
+ if (propertyKey) {
51
56
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
52
57
  }
53
58
  else {
package/dist/cors.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cors.js","sourceRoot":"","sources":["../src/cors.ts"],"names":[],"mappings":";;AAsCA,oBAkBC;AAvDD,gDAAoD;AACpD,gD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YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/guard.d.ts CHANGED
@@ -1,45 +1,42 @@
1
1
  import type { GuardFunction, GuardInstance } from '@heliosjs/core/types';
2
2
  import { type GuardClass } from '@heliosjs/core/types';
3
3
  /**
4
- * Decorator to register a guard.
5
- *
6
- * Guards are used to control access to a controller by validating
7
- * incoming requests before they reach route handlers. If a guard
8
- * returns `false`, the request is blocked.
9
- *
10
- * @param guard - A guard class or function used to determine whether
11
- * the request is allowed to proceed.
12
- *
13
- * @returns A class decorator that attaches guard metadata to the target.
14
- *
15
- * @example
16
- * // Using function guard
17
- * @GuardClass((req, res) => {
18
- * return !!req.headers.authorization;
19
- * })
20
- * class MyController {}
4
+ * Registers a guard on a controller class or a single route method. Guards run
5
+ * before pipes, middlewares, and the handler; use them for authentication and
6
+ * authorization checks.
7
+ *
8
+ * A guard grants access by returning `true` and denies by returning `false` or a
9
+ * `string`. On denial the request is rejected with `ForbiddenError` (HTTP 403);
10
+ * a returned string becomes the error message (falling back to
11
+ * `guard.message`, then `"Forbidden"`). Guards may be async.
12
+ *
13
+ * @param guard - One of:
14
+ * - a **function** `(req, res) => boolean | string | Promise<boolean | string>`;
15
+ * - a **class** with a `canActivate(req, res)` method (instantiated per request,
16
+ * may expose a `message` property for the denial text);
17
+ * - an already-constructed **instance** with `canActivate` (and optional
18
+ * `message`).
19
+ * Why: pick the lightest form — a closure for simple checks, a class when the
20
+ * guard needs its own dependencies.
21
+ *
22
+ * @returns A class or method decorator.
21
23
  *
22
24
  * @example
23
- * // Using class-based guard
24
- * class AuthGuard {
25
- * canActivate(req: Request, res: Response) {
26
- * return !!req.headers.authorization;
25
+ * ```ts
26
+ * @Guard((req) => !!req.getHeader('authorization') || 'Missing token')
27
+ * class SecureController {}
28
+ *
29
+ * class RoleGuard {
30
+ * message = 'Admins only';
31
+ * canActivate(req: Request) {
32
+ * return req.getState('role') === 'admin';
27
33
  * }
28
34
  * }
29
35
  *
30
- * @GuardClass(AuthGuard)
31
- * class MyController {}
32
- *
33
- * @remarks
34
- * Guards are executed before controller methods.
35
- * They can be used for:
36
- * - authentication
37
- * - authorization
38
- * - request validation
39
- *
40
- * If any guard returns `false`, the request handling is stopped.
41
- *
42
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and used
43
- * internally by the framework during request processing.
36
+ * class AdminController {
37
+ * @Guard(RoleGuard)
38
+ * deleteEverything() {}
39
+ * }
40
+ * ```
44
41
  */
45
- export declare function Guard(guard: GuardClass | GuardFunction | GuardInstance): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
42
+ export declare function Guard(guard: GuardClass | GuardFunction | GuardInstance): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/guard.js CHANGED
@@ -3,51 +3,48 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Guard = Guard;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register a guard.
7
- *
8
- * Guards are used to control access to a controller by validating
9
- * incoming requests before they reach route handlers. If a guard
10
- * returns `false`, the request is blocked.
11
- *
12
- * @param guard - A guard class or function used to determine whether
13
- * the request is allowed to proceed.
14
- *
15
- * @returns A class decorator that attaches guard metadata to the target.
16
- *
17
- * @example
18
- * // Using function guard
19
- * @GuardClass((req, res) => {
20
- * return !!req.headers.authorization;
21
- * })
22
- * class MyController {}
6
+ * Registers a guard on a controller class or a single route method. Guards run
7
+ * before pipes, middlewares, and the handler; use them for authentication and
8
+ * authorization checks.
9
+ *
10
+ * A guard grants access by returning `true` and denies by returning `false` or a
11
+ * `string`. On denial the request is rejected with `ForbiddenError` (HTTP 403);
12
+ * a returned string becomes the error message (falling back to
13
+ * `guard.message`, then `"Forbidden"`). Guards may be async.
14
+ *
15
+ * @param guard - One of:
16
+ * - a **function** `(req, res) => boolean | string | Promise<boolean | string>`;
17
+ * - a **class** with a `canActivate(req, res)` method (instantiated per request,
18
+ * may expose a `message` property for the denial text);
19
+ * - an already-constructed **instance** with `canActivate` (and optional
20
+ * `message`).
21
+ * Why: pick the lightest form — a closure for simple checks, a class when the
22
+ * guard needs its own dependencies.
23
+ *
24
+ * @returns A class or method decorator.
23
25
  *
24
26
  * @example
25
- * // Using class-based guard
26
- * class AuthGuard {
27
- * canActivate(req: Request, res: Response) {
28
- * return !!req.headers.authorization;
27
+ * ```ts
28
+ * @Guard((req) => !!req.getHeader('authorization') || 'Missing token')
29
+ * class SecureController {}
30
+ *
31
+ * class RoleGuard {
32
+ * message = 'Admins only';
33
+ * canActivate(req: Request) {
34
+ * return req.getState('role') === 'admin';
29
35
  * }
30
36
  * }
31
37
  *
32
- * @GuardClass(AuthGuard)
33
- * class MyController {}
34
- *
35
- * @remarks
36
- * Guards are executed before controller methods.
37
- * They can be used for:
38
- * - authentication
39
- * - authorization
40
- * - request validation
41
- *
42
- * If any guard returns `false`, the request handling is stopped.
43
- *
44
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and used
45
- * internally by the framework during request processing.
38
+ * class AdminController {
39
+ * @Guard(RoleGuard)
40
+ * deleteEverything() {}
41
+ * }
42
+ * ```
46
43
  */
47
44
  function Guard(guard) {
48
- return function (target, propertyKey, descriptor) {
45
+ return function (target, propertyKey, _descriptor) {
49
46
  const data = [{ guard: guard }];
50
- if (descriptor) {
47
+ if (propertyKey) {
51
48
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
52
49
  }
53
50
  else {
package/dist/guard.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":";;AA6CA,sBAUC;AArDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,SAAgB,KAAK,CAAC,KAAiD;IACrE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAEhC,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":";;AA0CA,sBAUC;AAlDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,SAAgB,KAAK,CAAC,KAAiD;IACrE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QAEhC,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -2,37 +2,33 @@ import type { InterceptorCB } from '@heliosjs/core/types';
2
2
  /**
3
3
  * Decorator to register an interceptor at the controller or method level.
4
4
  *
5
- * Interceptors are functions that wrap the execution of a route handler.
6
- * They can run logic before after the handler is executed, allowing
7
- * you to modify responses, or handle cross-cutting concerns.
5
+ * An interceptor runs *after* the route handler. It receives the value the
6
+ * handler returned and whatever it returns becomes the new response payload,
7
+ * so it is the place for response shaping, wrapping, or caching.
8
8
  *
9
- * @param handler - Interceptor callback function.
9
+ * Signature: `(data, req, res) => newData` (may be async). Interceptors run
10
+ * regardless of whether the handler returned a value, including `undefined`.
11
+ *
12
+ * @param interceptor - `(data, req, res) => newData` callback.
10
13
  *
11
14
  * @returns A decorator that attaches interceptor metadata to the target
12
15
  * (either a class or a method).
13
16
  *
14
17
  * @example
15
- * // Logging interceptor
16
- * @Intercept(async (ctx, next) => {
17
- * console.log('Before');
18
- * const result = await next();
19
- * console.log('After');
20
- * return result;
21
- * })
18
+ * // Wrap every response body
19
+ * @Intercept((data) => ({ data, timestamp: Date.now() }))
22
20
  * class MyController {}
23
21
  *
24
22
  * @example
25
23
  * // Method-level interceptor
26
24
  * class MyController {
27
- * @Intercept(async (ctx, next) => {
28
- * return next();
29
- * })
25
+ * @Intercept(async (data, req) => ({ ...data, path: req.path }))
30
26
  * getData() {}
31
27
  * }
32
28
  *
33
29
  * @remarks
34
- * - Interceptors can modify the result returned by the handler.
35
- * - They are executed in the order they are applied.
30
+ * - Interceptors replace the result returned by the handler.
31
+ * - Multiple interceptors run in reverse order (the one nearest the handler first).
36
32
  * - Can be used for:
37
33
  * - logging
38
34
  * - response transformation
@@ -42,4 +38,4 @@ import type { InterceptorCB } from '@heliosjs/core/types';
42
38
  * Metadata is stored using the MIDDLEWARES_CONFIG key and
43
39
  * used internally by the framework during request processing.
44
40
  */
45
- export declare function Intercept(interceptor: InterceptorCB): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
41
+ export declare function Intercept(interceptor: InterceptorCB): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
@@ -5,37 +5,33 @@ const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
6
  * Decorator to register an interceptor at the controller or method level.
7
7
  *
8
- * Interceptors are functions that wrap the execution of a route handler.
9
- * They can run logic before after the handler is executed, allowing
10
- * you to modify responses, or handle cross-cutting concerns.
8
+ * An interceptor runs *after* the route handler. It receives the value the
9
+ * handler returned and whatever it returns becomes the new response payload,
10
+ * so it is the place for response shaping, wrapping, or caching.
11
11
  *
12
- * @param handler - Interceptor callback function.
12
+ * Signature: `(data, req, res) => newData` (may be async). Interceptors run
13
+ * regardless of whether the handler returned a value, including `undefined`.
14
+ *
15
+ * @param interceptor - `(data, req, res) => newData` callback.
13
16
  *
14
17
  * @returns A decorator that attaches interceptor metadata to the target
15
18
  * (either a class or a method).
16
19
  *
17
20
  * @example
18
- * // Logging interceptor
19
- * @Intercept(async (ctx, next) => {
20
- * console.log('Before');
21
- * const result = await next();
22
- * console.log('After');
23
- * return result;
24
- * })
21
+ * // Wrap every response body
22
+ * @Intercept((data) => ({ data, timestamp: Date.now() }))
25
23
  * class MyController {}
26
24
  *
27
25
  * @example
28
26
  * // Method-level interceptor
29
27
  * class MyController {
30
- * @Intercept(async (ctx, next) => {
31
- * return next();
32
- * })
28
+ * @Intercept(async (data, req) => ({ ...data, path: req.path }))
33
29
  * getData() {}
34
30
  * }
35
31
  *
36
32
  * @remarks
37
- * - Interceptors can modify the result returned by the handler.
38
- * - They are executed in the order they are applied.
33
+ * - Interceptors replace the result returned by the handler.
34
+ * - Multiple interceptors run in reverse order (the one nearest the handler first).
39
35
  * - Can be used for:
40
36
  * - logging
41
37
  * - response transformation
@@ -46,9 +42,9 @@ const utils_1 = require("@heliosjs/core/utils");
46
42
  * used internally by the framework during request processing.
47
43
  */
48
44
  function Intercept(interceptor) {
49
- return function (target, propertyKey, descriptor) {
45
+ return function (target, propertyKey, _descriptor) {
50
46
  const data = [{ interceptor }];
51
- if (descriptor) {
47
+ if (propertyKey) {
52
48
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
53
49
  }
54
50
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":";;AA6CA,8BAUC;AAtDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,SAAgB,SAAS,CAAC,WAA0B;IAClD,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QAE/B,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":";;AAyCA,8BAUC;AAlDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,SAAgB,SAAS,CAAC,WAA0B;IAClD,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QAE/B,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/pipe.d.ts CHANGED
@@ -1,31 +1,34 @@
1
1
  import { type Pipe } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to register a data transformation pipe.
3
+ * Registers a transformation pipe on a controller class or a single route method.
4
+ * Pipes run after guards and before middlewares; each supplied function replaces
5
+ * the matching part of the request with its return value, so the handler and its
6
+ * `@Body()` / `@QueryParam()` decorators see the transformed data.
4
7
  *
5
- * Pipes are used to transform incoming request data before it reaches
6
- * the route handler. They can be applied at the controller level and
7
- * modify parts of the request such as body, query, params, or headers.
8
+ * Use pipes for normalization and coercion (trim, lowercase, `Number(...)`,
9
+ * defaults). For schema validation prefer a DTO on the param decorator or
10
+ * `@Sanitize`.
8
11
  *
9
- * @param config - Configuration object containing transformation functions
10
- * for different parts of the request.
12
+ * @param pipe - An object with any of these keys, each a
13
+ * `(value, request) => value` transformer:
14
+ * - `body` — `(body, req) => body`. Why: reshape or clean the parsed body.
15
+ * - `query` — `(query, req) => query`, where query is
16
+ * `Record<string, string | string[]>`. Why: coerce query strings to the
17
+ * types the handler expects.
18
+ * - `params` — `(params, req) => params`, `Record<string, string>`. Why:
19
+ * normalize path segments (case, padding).
20
+ * - `headers` — `(headers, req) => headers`. Why: canonicalize header values.
21
+ * Omitted keys leave that part untouched.
11
22
  *
12
- * @returns A class decorator that attaches pipe metadata to the target.
23
+ * @returns A class or method decorator.
13
24
  *
14
25
  * @example
26
+ * ```ts
15
27
  * @Pipe({
16
- * body: (body) => ({ ...body, name: body.name.trim() }),
17
- * query: (query) => ({ ...query, page: Number(query.page) }),
28
+ * body: (body) => ({ ...body, name: body.name?.trim() }),
29
+ * query: (query) => ({ ...query, page: Number(query.page ?? 1) }),
18
30
  * })
19
31
  * class MyController {}
20
- *
21
- * @remarks
22
- * Each function in the pipe receives raw data and must return the transformed value.
23
- * Pipes are executed before controller methods and can be used for:
24
- * - data normalization
25
- * - type casting
26
- * - sanitization
27
- *
28
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and later used
29
- * by the framework during request processing.
32
+ * ```
30
33
  */
31
- export declare function Pipe(pipe: Pipe): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
34
+ export declare function Pipe(pipe: Pipe): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/pipe.js CHANGED
@@ -3,38 +3,41 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Pipe = Pipe;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register a data transformation pipe.
6
+ * Registers a transformation pipe on a controller class or a single route method.
7
+ * Pipes run after guards and before middlewares; each supplied function replaces
8
+ * the matching part of the request with its return value, so the handler and its
9
+ * `@Body()` / `@QueryParam()` decorators see the transformed data.
7
10
  *
8
- * Pipes are used to transform incoming request data before it reaches
9
- * the route handler. They can be applied at the controller level and
10
- * modify parts of the request such as body, query, params, or headers.
11
+ * Use pipes for normalization and coercion (trim, lowercase, `Number(...)`,
12
+ * defaults). For schema validation prefer a DTO on the param decorator or
13
+ * `@Sanitize`.
11
14
  *
12
- * @param config - Configuration object containing transformation functions
13
- * for different parts of the request.
15
+ * @param pipe - An object with any of these keys, each a
16
+ * `(value, request) => value` transformer:
17
+ * - `body` — `(body, req) => body`. Why: reshape or clean the parsed body.
18
+ * - `query` — `(query, req) => query`, where query is
19
+ * `Record<string, string | string[]>`. Why: coerce query strings to the
20
+ * types the handler expects.
21
+ * - `params` — `(params, req) => params`, `Record<string, string>`. Why:
22
+ * normalize path segments (case, padding).
23
+ * - `headers` — `(headers, req) => headers`. Why: canonicalize header values.
24
+ * Omitted keys leave that part untouched.
14
25
  *
15
- * @returns A class decorator that attaches pipe metadata to the target.
26
+ * @returns A class or method decorator.
16
27
  *
17
28
  * @example
29
+ * ```ts
18
30
  * @Pipe({
19
- * body: (body) => ({ ...body, name: body.name.trim() }),
20
- * query: (query) => ({ ...query, page: Number(query.page) }),
31
+ * body: (body) => ({ ...body, name: body.name?.trim() }),
32
+ * query: (query) => ({ ...query, page: Number(query.page ?? 1) }),
21
33
  * })
22
34
  * class MyController {}
23
- *
24
- * @remarks
25
- * Each function in the pipe receives raw data and must return the transformed value.
26
- * Pipes are executed before controller methods and can be used for:
27
- * - data normalization
28
- * - type casting
29
- * - sanitization
30
- *
31
- * Metadata is stored under the CONTROLLER_CONFIGURATION key and later used
32
- * by the framework during request processing.
35
+ * ```
33
36
  */
34
37
  function Pipe(pipe) {
35
- return function (target, propertyKey, descriptor) {
38
+ return function (target, propertyKey, _descriptor) {
36
39
  const data = [{ pipe }];
37
- if (descriptor) {
40
+ if (propertyKey) {
38
41
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
39
42
  }
40
43
  else {
package/dist/pipe.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"pipe.js","sourceRoot":"","sources":["../src/pipe.ts"],"names":[],"mappings":";;AA+BA,oBAUC;AAxCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,SAAgB,IAAI,CAAC,IAAU;IAC7B,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAExB,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"pipe.js","sourceRoot":"","sources":["../src/pipe.ts"],"names":[],"mappings":";;AAkCA,oBAUC;AA3CD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,SAAgB,IAAI,CAAC,IAAU;IAC7B,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAExB,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/roles.d.ts CHANGED
@@ -26,5 +26,5 @@ export declare function createRolesGuard(required: string[], options: RolesOptio
26
26
  * @example
27
27
  * @Roles(['admin', 'editor'], { mode: 'all' }) // ALL
28
28
  */
29
- export declare function Roles(...args: (RolesArg | RolesOptions)[]): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
29
+ export declare function Roles(...args: (RolesArg | RolesOptions)[]): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
30
30
  export {};
package/dist/roles.js CHANGED
@@ -59,9 +59,9 @@ function createRolesGuard(required, options) {
59
59
  function Roles(...args) {
60
60
  const { roles, options } = normalizeArgs(args);
61
61
  const guard = createRolesGuard(roles, options);
62
- return function (target, propertyKey, descriptor) {
62
+ return function (target, propertyKey, _descriptor) {
63
63
  const data = [{ guard }];
64
- if (descriptor) {
64
+ if (propertyKey) {
65
65
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
66
66
  }
67
67
  else {
package/dist/roles.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"roles.js","sourceRoot":"","sources":["../src/roles.ts"],"names":[],"mappings":";;AAYA,gCAQC;AAED,sCAsBC;AAED,4CAoBC;AAiBD,sBAaC;AA/FD,gDAAmG;AAWnG,SAAgB,UAAU,CACxB,QAAkB,EAClB,SAAmB,EACnB,IAAc;IAEd,OAAO,IAAI,KAAK,KAAK;QACnB,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QACpD,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,SAAgB,aAAa,CAC3B,IAAiC;IAEjC,IAAI,OAAO,GAAiB,EAAE,CAAC;IAC/B,IAAI,QAAQ,GAAG,IAAI,CAAC;IAEpB,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACnC,MAAM,SAAS,GACb,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,CAAC,KAAK,C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AAC,CAAC;QAEtE,OAAO,UAAU,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;IAChE,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,KAAK,CAAC,GAAG,IAAiC;IACxD,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,aAAa,CAAC,IAAI,CAAC,CAAC;IAC/C,MAAM,KAAK,GAAG,gBAAgB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAE/C,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,IAAI,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEzB,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -1,40 +1,36 @@
1
1
  import type { SanitizerConfig } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to apply sanitization configurations to a controller or method.
3
+ * Runs a Joi schema over one part of the request on a controller class or a
4
+ * single route method. Sanitizers run first in the pipeline (before guards), so
5
+ * every later stage sees the cleaned/validated data.
4
6
  *
5
- * This decorator accepts one or more sanitization configuration objects which define
6
- * how incoming request data should be sanitized before processing. It can be applied
7
- * at the class level to apply sanitization globally to all methods or at the method level
8
- * for fine-grained control.
7
+ * Depending on `action` a config either validates (throws on mismatch),
8
+ * sanitizes (coerces/strips and writes the result back onto the request), or
9
+ * both. The `SANITIZER` helper from `@heliosjs/core` provides ready-made Joi
10
+ * builders (`SANITIZER.string.email()`, `SANITIZER.xss()`, …).
9
11
  *
10
- * The sanitization configurations are stored as metadata on the target or method,
11
- * which can be retrieved by the framework to perform the actual sanitization during
12
- * request handling.
12
+ * @param config - One `SanitizerConfig`, or an array applied in order. Each has:
13
+ * - `schema` (**required**) a `Joi.Schema` to run.
14
+ * - `type` (**required**) — which request part to target, one of
15
+ * `'body'`, `'query'`, `'params'`, `'headers'`.
16
+ * - `action` — `'validate'` (reject on error), `'sanitize'` (transform in
17
+ * place), or `'both'`. Default `'both'`.
18
+ * - `options` — Joi `ValidationOptions` passed through.
19
+ * - `stripUnknown` — drop keys not in the schema.
20
+ * Why an array: apply different schemas to different request parts on the same
21
+ * route.
13
22
  *
14
- * @param {SanitizerConfig | SanitizerConfig[]} sanitizeConfig - A single or array of sanitization configuration objects.
15
- *
16
- * @returns {Function} A decorator function that applies the sanitization metadata.
17
- *
18
- * @example
19
- * // Apply sanitization to all methods in a controller
20
- * @Sanitize({ trim: true, escape: true })
21
- * class MyController {
22
- * // ...
23
- * }
23
+ * @returns A class or method decorator.
24
24
  *
25
25
  * @example
26
- * // Apply multiple sanitization rules to a specific method
27
- * @Sanitize([
28
- * { trim: true },
29
- * { escape: true }
30
- * ])
31
- * async myMethod() {
32
- * // ...
33
- * }
34
- *
35
- * @remarks
36
- * The metadata key used for storing the sanitization configurations is defined by `SANITIZE`.
37
- * This metadata is accessible via Reflect API and used internally by the framework
38
- * to apply sanitization logic.
26
+ * ```ts
27
+ * @Sanitize({
28
+ * type: 'body',
29
+ * action: 'both',
30
+ * schema: Joi.object({ email: SANITIZER.string.email(), bio: SANITIZER.xss() }),
31
+ * stripUnknown: true,
32
+ * })
33
+ * class ProfileController {}
34
+ * ```
39
35
  */
40
- export declare function Sanitize(config: SanitizerConfig | SanitizerConfig[]): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => void;
36
+ export declare function Sanitize(config: SanitizerConfig | SanitizerConfig[]): (target: any, propertyKey?: string, _descriptor?: PropertyDescriptor) => void;
package/dist/sanitize.js CHANGED
@@ -3,48 +3,44 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Sanitize = Sanitize;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to apply sanitization configurations to a controller or method.
6
+ * Runs a Joi schema over one part of the request on a controller class or a
7
+ * single route method. Sanitizers run first in the pipeline (before guards), so
8
+ * every later stage sees the cleaned/validated data.
7
9
  *
8
- * This decorator accepts one or more sanitization configuration objects which define
9
- * how incoming request data should be sanitized before processing. It can be applied
10
- * at the class level to apply sanitization globally to all methods or at the method level
11
- * for fine-grained control.
10
+ * Depending on `action` a config either validates (throws on mismatch),
11
+ * sanitizes (coerces/strips and writes the result back onto the request), or
12
+ * both. The `SANITIZER` helper from `@heliosjs/core` provides ready-made Joi
13
+ * builders (`SANITIZER.string.email()`, `SANITIZER.xss()`, …).
12
14
  *
13
- * The sanitization configurations are stored as metadata on the target or method,
14
- * which can be retrieved by the framework to perform the actual sanitization during
15
- * request handling.
15
+ * @param config - One `SanitizerConfig`, or an array applied in order. Each has:
16
+ * - `schema` (**required**) a `Joi.Schema` to run.
17
+ * - `type` (**required**) — which request part to target, one of
18
+ * `'body'`, `'query'`, `'params'`, `'headers'`.
19
+ * - `action` — `'validate'` (reject on error), `'sanitize'` (transform in
20
+ * place), or `'both'`. Default `'both'`.
21
+ * - `options` — Joi `ValidationOptions` passed through.
22
+ * - `stripUnknown` — drop keys not in the schema.
23
+ * Why an array: apply different schemas to different request parts on the same
24
+ * route.
16
25
  *
17
- * @param {SanitizerConfig | SanitizerConfig[]} sanitizeConfig - A single or array of sanitization configuration objects.
18
- *
19
- * @returns {Function} A decorator function that applies the sanitization metadata.
20
- *
21
- * @example
22
- * // Apply sanitization to all methods in a controller
23
- * @Sanitize({ trim: true, escape: true })
24
- * class MyController {
25
- * // ...
26
- * }
26
+ * @returns A class or method decorator.
27
27
  *
28
28
  * @example
29
- * // Apply multiple sanitization rules to a specific method
30
- * @Sanitize([
31
- * { trim: true },
32
- * { escape: true }
33
- * ])
34
- * async myMethod() {
35
- * // ...
36
- * }
37
- *
38
- * @remarks
39
- * The metadata key used for storing the sanitization configurations is defined by `SANITIZE`.
40
- * This metadata is accessible via Reflect API and used internally by the framework
41
- * to apply sanitization logic.
29
+ * ```ts
30
+ * @Sanitize({
31
+ * type: 'body',
32
+ * action: 'both',
33
+ * schema: Joi.object({ email: SANITIZER.string.email(), bio: SANITIZER.xss() }),
34
+ * stripUnknown: true,
35
+ * })
36
+ * class ProfileController {}
37
+ * ```
42
38
  */
43
39
  function Sanitize(config) {
44
- return function (target, propertyKey, descriptor) {
40
+ return function (target, propertyKey, _descriptor) {
45
41
  const sanitizers = Array.isArray(config) ? config : [config];
46
42
  const data = sanitizers.map(sanitizer => ({ sanitizer }));
47
- if (descriptor) {
43
+ if (propertyKey) {
48
44
  (0, utils_1.defineMiddlewaresMeta)(data, target, propertyKey);
49
45
  }
50
46
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"sanitize.js","sourceRoot":"","sources":["../src/sanitize.ts"],"names":[],"mappings":";;AAwCA,4BAWC;AAlDD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,SAAgB,QAAQ,CAAC,MAA2C;IAClE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;QAE1D,IAAI,UAAU,EAAE,CAAC;YACf,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"sanitize.js","sourceRoot":"","sources":["../src/sanitize.ts"],"names":[],"mappings":";;AAoCA,4BAWC;AA9CD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,SAAgB,QAAQ,CAAC,MAA2C;IAClE,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,WAAgC;QAClF,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAC7D,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;QAE1D,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/status.d.ts CHANGED
@@ -1,35 +1,25 @@
1
1
  /**
2
- * Decorator to set the HTTP status code for the response.
2
+ * Sets the HTTP status code for successful responses from a controller class or a
3
+ * single route method. Method-level wins over class-level. Without it a
4
+ * successful handler responds `200` (or the code you set via `res.status`).
3
5
  *
4
- * This decorator can be applied at the method level to specify the HTTP status code
5
- * that should be returned when the method's response is sent. It can also be applied
6
- * at the class level to set a default status code for all methods within the class.
6
+ * This only affects the success path errors still carry the status of the
7
+ * thrown `HeliosError`, and an explicit `res.redirect()` keeps its own code.
7
8
  *
8
- * The status code is stored as metadata on the target or method, which can be retrieved
9
- * by the framework to set the HTTP response status accordingly.
9
+ * @param status - The HTTP status code to send, e.g. `201` for a create, `202`
10
+ * for an accepted async job, `204` for an empty body. Why: express REST
11
+ * semantics without touching the `Response` object.
10
12
  *
11
- * @param {number} status - The HTTP status code to set for the response.
12
- *
13
- * @returns {Function} A decorator function that applies the status code metadata.
13
+ * @returns A class or method decorator.
14
14
  *
15
15
  * @example
16
- * // Set status code 201 for a specific method
17
- * @Status(201)
18
- * async createResource() {
19
- * // ...
16
+ * ```ts
17
+ * class UserController {
18
+ * @Post('/')
19
+ * @Status(201)
20
+ * create(@Body() dto: CreateUserDto) {}
20
21
  * }
21
- *
22
- * @example
23
- * // Set default status code 204 for all methods in a controller
24
- * @Status(204)
25
- * class MyController {
26
- * // ...
27
- * }
28
- *
29
- * @remarks
30
- * The metadata key used for storing the status code is defined by `OK_METADATA_KEY`.
31
- * This metadata is accessible via Reflect API and used internally by the framework
32
- * to set the HTTP response status.
22
+ * ```
33
23
  */
34
24
  export declare function Status(status: number): (target: any, propertyKey?: string) => void;
35
25
  /**
package/dist/status.js CHANGED
@@ -4,43 +4,36 @@ exports.Ok204 = exports.Ok201 = exports.Ok200 = void 0;
4
4
  exports.Status = Status;
5
5
  const utils_1 = require("@heliosjs/core/utils");
6
6
  /**
7
- * Decorator to set the HTTP status code for the response.
7
+ * Sets the HTTP status code for successful responses from a controller class or a
8
+ * single route method. Method-level wins over class-level. Without it a
9
+ * successful handler responds `200` (or the code you set via `res.status`).
8
10
  *
9
- * This decorator can be applied at the method level to specify the HTTP status code
10
- * that should be returned when the method's response is sent. It can also be applied
11
- * at the class level to set a default status code for all methods within the class.
11
+ * This only affects the success path errors still carry the status of the
12
+ * thrown `HeliosError`, and an explicit `res.redirect()` keeps its own code.
12
13
  *
13
- * The status code is stored as metadata on the target or method, which can be retrieved
14
- * by the framework to set the HTTP response status accordingly.
14
+ * @param status - The HTTP status code to send, e.g. `201` for a create, `202`
15
+ * for an accepted async job, `204` for an empty body. Why: express REST
16
+ * semantics without touching the `Response` object.
15
17
  *
16
- * @param {number} status - The HTTP status code to set for the response.
17
- *
18
- * @returns {Function} A decorator function that applies the status code metadata.
19
- *
20
- * @example
21
- * // Set status code 201 for a specific method
22
- * @Status(201)
23
- * async createResource() {
24
- * // ...
25
- * }
18
+ * @returns A class or method decorator.
26
19
  *
27
20
  * @example
28
- * // Set default status code 204 for all methods in a controller
29
- * @Status(204)
30
- * class MyController {
31
- * // ...
21
+ * ```ts
22
+ * class UserController {
23
+ * @Post('/')
24
+ * @Status(201)
25
+ * create(@Body() dto: CreateUserDto) {}
32
26
  * }
33
- *
34
- * @remarks
35
- * The metadata key used for storing the status code is defined by `OK_METADATA_KEY`.
36
- * This metadata is accessible via Reflect API and used internally by the framework
37
- * to set the HTTP response status.
27
+ * ```
38
28
  */
39
29
  function Status(status) {
40
30
  return function (target, propertyKey) {
41
31
  if (propertyKey) {
42
32
  (0, utils_1.defineMiddlewaresMeta)([{ status }], target, propertyKey);
43
33
  }
34
+ else {
35
+ (0, utils_1.defineMiddlewaresMeta)([{ status }], target);
36
+ }
44
37
  };
45
38
  }
46
39
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"status.js","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":";;;AAkCA,wBAMC;AAxCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,SAAgB,MAAM,CAAC,MAAc;IACnC,OAAO,UAAU,MAAW,EAAE,WAAoB;QAChD,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QAC3D,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB;AAEvC;;;;;;;GAOG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB;AAEvC;;;;;;;;GAQG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB"}
1
+ {"version":3,"file":"status.js","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":";;;AAwBA,wBAQC;AAhCD,gDAA6D;AAC7D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,MAAM,CAAC,MAAc;IACnC,OAAO,UAAU,MAAW,EAAE,WAAoB;QAChD,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QAC3D,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB;AAEvC;;;;;;;GAOG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB;AAEvC;;;;;;;;GAQG;AACI,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAA1B,QAAA,KAAK,SAAqB"}
package/dist/use.d.ts CHANGED
@@ -1,46 +1,27 @@
1
1
  import type { MiddlewareCB } from '@heliosjs/core/types';
2
2
  /**
3
- * Decorator to register middleware(s) at the controller or method level.
3
+ * Registers one or more middlewares on a controller class or a single route
4
+ * method. Middlewares run before the handler, in declaration order, after guards
5
+ * and pipes in the request pipeline. Calling `next(err)` with an error aborts the
6
+ * request; not calling `next` still proceeds (the pipeline advances once the
7
+ * middleware resolves).
4
8
  *
5
- * Middlewares are functions executed before the route handler.
6
- * They can be used to:
7
- * - modify request/response
8
- * - perform logging
9
- * - handle authentication/authorization
10
- * - short-circuit request handling
9
+ * Applied to a class, the middleware covers every route in it (and its child
10
+ * controllers); applied to a method, only that route.
11
11
  *
12
- * @param middleware - A single middleware function or an array of middleware functions.
12
+ * @param middleware - A middleware callback `(req, res, next) => void | Promise<void>`,
13
+ * or an array of them applied in order. Why: attach auth, logging, request
14
+ * shaping, or short-circuit logic without hand-wiring it into each handler.
13
15
  *
14
- * @returns A decorator that attaches middleware metadata to the target
15
- * (either a class or a method).
16
+ * @returns A class or method decorator.
16
17
  *
17
18
  * @example
18
- * // Single middleware
19
- * @Use((req, res, next) => {
20
- * console.log('Request received');
21
- * next();
22
- * })
23
- * class MyController {}
24
- *
25
- * @example
26
- * // Multiple middlewares
27
- * @Use([
28
- * authMiddleware,
29
- * loggingMiddleware,
30
- * ])
31
- * class MyController {}
32
- *
33
- * @example
34
- * // Method-level middleware
19
+ * ```ts
20
+ * @Use([authMiddleware, loggingMiddleware])
35
21
  * class MyController {
36
- * @Use(authMiddleware)
22
+ * @Use(rateLimitMiddleware)
37
23
  * getData() {}
38
24
  * }
39
- *
40
- * @remarks
41
- * - Middlewares are executed in the order they are defined.
42
- * - Can be applied at both class and method levels.
43
- * - Metadata is stored using the MIDDLEWARES_CONFIG key and used
44
- * internally by the framework during request handling.
25
+ * ```
45
26
  */
46
27
  export declare function Use(middleware: MiddlewareCB | MiddlewareCB[]): (target: any, propertyKey?: string, descriptor?: PropertyDescriptor) => any;
package/dist/use.js CHANGED
@@ -3,48 +3,29 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Use = Use;
4
4
  const utils_1 = require("@heliosjs/core/utils");
5
5
  /**
6
- * Decorator to register middleware(s) at the controller or method level.
6
+ * Registers one or more middlewares on a controller class or a single route
7
+ * method. Middlewares run before the handler, in declaration order, after guards
8
+ * and pipes in the request pipeline. Calling `next(err)` with an error aborts the
9
+ * request; not calling `next` still proceeds (the pipeline advances once the
10
+ * middleware resolves).
7
11
  *
8
- * Middlewares are functions executed before the route handler.
9
- * They can be used to:
10
- * - modify request/response
11
- * - perform logging
12
- * - handle authentication/authorization
13
- * - short-circuit request handling
12
+ * Applied to a class, the middleware covers every route in it (and its child
13
+ * controllers); applied to a method, only that route.
14
14
  *
15
- * @param middleware - A single middleware function or an array of middleware functions.
15
+ * @param middleware - A middleware callback `(req, res, next) => void | Promise<void>`,
16
+ * or an array of them applied in order. Why: attach auth, logging, request
17
+ * shaping, or short-circuit logic without hand-wiring it into each handler.
16
18
  *
17
- * @returns A decorator that attaches middleware metadata to the target
18
- * (either a class or a method).
19
+ * @returns A class or method decorator.
19
20
  *
20
21
  * @example
21
- * // Single middleware
22
- * @Use((req, res, next) => {
23
- * console.log('Request received');
24
- * next();
25
- * })
26
- * class MyController {}
27
- *
28
- * @example
29
- * // Multiple middlewares
30
- * @Use([
31
- * authMiddleware,
32
- * loggingMiddleware,
33
- * ])
34
- * class MyController {}
35
- *
36
- * @example
37
- * // Method-level middleware
22
+ * ```ts
23
+ * @Use([authMiddleware, loggingMiddleware])
38
24
  * class MyController {
39
- * @Use(authMiddleware)
25
+ * @Use(rateLimitMiddleware)
40
26
  * getData() {}
41
27
  * }
42
- *
43
- * @remarks
44
- * - Middlewares are executed in the order they are defined.
45
- * - Can be applied at both class and method levels.
46
- * - Metadata is stored using the MIDDLEWARES_CONFIG key and used
47
- * internally by the framework during request handling.
28
+ * ```
48
29
  */
49
30
  function Use(middleware) {
50
31
  return function (target, propertyKey, descriptor) {
package/dist/use.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"use.js","sourceRoot":"","sources":["../src/use.ts"],"names":[],"mappings":";;AA+CA,kBAcC;AA5DD,gDAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,SAAgB,GAAG,CAAC,UAAyC;IAC3D,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;QAE1E,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;QAE/D,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"use.js","sourceRoot":"","sources":["../src/use.ts"],"names":[],"mappings":";;AA4BA,kBAcC;AAzCD,gDAA6D;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,SAAgB,GAAG,CAAC,UAAyC;IAC3D,OAAO,UAAU,MAAW,EAAE,WAAoB,EAAE,UAA+B;QACjF,MAAM,WAAW,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;QAE1E,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC;QAE/D,IAAI,WAAW,EAAE,CAAC;YAChB,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAA,6BAAqB,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heliosjs/middlewares",
3
- "version": "10.0.5",
3
+ "version": "10.0.7",
4
4
  "description": "Middlewares for @heliosjs",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "reflect-metadata": "^0.2.2"
31
31
  },
32
32
  "peerDependencies": {
33
- "@heliosjs/core": "^3.2.8",
33
+ "@heliosjs/core": "^3.2.10",
34
34
  "@types/node": ">=20.0.0",
35
35
  "reflect-metadata": "^0.2.2",
36
36
  "typescript": ">=5.0.0"