@meghjs/core 0.5.4 → 0.5.5

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 (95) hide show
  1. package/README.md +32 -12
  2. package/dist/common/exceptions/http-exceptions.d.ts +1 -50
  3. package/dist/common/exceptions/http-exceptions.js +15 -80
  4. package/dist/common/exceptions/http-exceptions.js.map +1 -1
  5. package/dist/common/utils/compiled-validation.d.ts +43 -0
  6. package/dist/common/utils/compiled-validation.js +298 -0
  7. package/dist/common/utils/compiled-validation.js.map +1 -0
  8. package/dist/common/utils/object-utils.d.ts +4 -0
  9. package/dist/common/utils/object-utils.js +44 -7
  10. package/dist/common/utils/object-utils.js.map +1 -1
  11. package/dist/common/utils/path-utils.d.ts +7 -0
  12. package/dist/common/utils/path-utils.js +15 -0
  13. package/dist/common/utils/path-utils.js.map +1 -1
  14. package/dist/config/environment-variables.d.ts +2 -0
  15. package/dist/config/environment-variables.js +23 -12
  16. package/dist/config/environment-variables.js.map +1 -1
  17. package/dist/core/application.d.ts +89 -6
  18. package/dist/core/application.js +149 -72
  19. package/dist/core/application.js.map +1 -1
  20. package/dist/core/interfaces.d.ts +48 -1
  21. package/dist/core/router.d.ts +59 -5
  22. package/dist/core/router.js +233 -109
  23. package/dist/core/router.js.map +1 -1
  24. package/dist/core/testing.js +2 -12
  25. package/dist/core/testing.js.map +1 -1
  26. package/dist/core/types.d.ts +6 -0
  27. package/dist/errors/error-handler.d.ts +56 -0
  28. package/dist/errors/error-handler.js +206 -0
  29. package/dist/errors/error-handler.js.map +1 -0
  30. package/dist/errors/exception-filter.d.ts +96 -0
  31. package/dist/errors/exception-filter.js +68 -0
  32. package/dist/errors/exception-filter.js.map +1 -0
  33. package/dist/errors/http-exceptions.d.ts +413 -0
  34. package/dist/errors/http-exceptions.js +155 -0
  35. package/dist/errors/http-exceptions.js.map +1 -0
  36. package/dist/errors/index.d.ts +4 -0
  37. package/dist/errors/index.js +24 -0
  38. package/dist/errors/index.js.map +1 -0
  39. package/dist/events/event-subscriber.js +14 -3
  40. package/dist/events/event-subscriber.js.map +1 -1
  41. package/dist/events/socket-dispatcher.d.ts +1 -1
  42. package/dist/events/socket-dispatcher.js +1 -1
  43. package/dist/events/socket-dispatcher.js.map +1 -1
  44. package/dist/http/params.js +3 -1
  45. package/dist/http/params.js.map +1 -1
  46. package/dist/index.d.ts +2 -1
  47. package/dist/index.js +4 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/observability/health.d.ts +45 -0
  50. package/dist/observability/health.js +74 -0
  51. package/dist/observability/health.js.map +1 -0
  52. package/dist/observability/index.d.ts +3 -0
  53. package/dist/observability/index.js +5 -0
  54. package/dist/observability/index.js.map +1 -1
  55. package/dist/observability/logger.js +8 -1
  56. package/dist/observability/logger.js.map +1 -1
  57. package/dist/observability/request-context.d.ts +29 -0
  58. package/dist/observability/request-context.js +54 -0
  59. package/dist/observability/request-context.js.map +1 -0
  60. package/dist/openapi/swagger-schema.js +21 -2
  61. package/dist/openapi/swagger-schema.js.map +1 -1
  62. package/dist/orm/connect.d.ts +2 -0
  63. package/dist/orm/connect.js +6 -1
  64. package/dist/orm/connect.js.map +1 -1
  65. package/dist/orm/plugin.js +2 -0
  66. package/dist/orm/plugin.js.map +1 -1
  67. package/dist/plugins/plugin.d.ts +3 -0
  68. package/dist/plugins/plugin.js.map +1 -1
  69. package/dist/plugins/registry.js +1 -0
  70. package/dist/plugins/registry.js.map +1 -1
  71. package/dist/validator/compat.d.ts +5 -0
  72. package/dist/validator/compat.js +42 -0
  73. package/dist/validator/compat.js.map +1 -0
  74. package/dist/validator/compiler.d.ts +20 -0
  75. package/dist/validator/compiler.js +219 -0
  76. package/dist/validator/compiler.js.map +1 -0
  77. package/dist/validator/decorators.d.ts +81 -0
  78. package/dist/validator/decorators.js +377 -0
  79. package/dist/validator/decorators.js.map +1 -0
  80. package/dist/validator/index.d.ts +16 -0
  81. package/dist/validator/index.js +36 -0
  82. package/dist/validator/index.js.map +1 -0
  83. package/dist/validator/is-email.d.ts +25 -0
  84. package/dist/validator/is-email.js +204 -0
  85. package/dist/validator/is-email.js.map +1 -0
  86. package/dist/validator/messages.d.ts +20 -0
  87. package/dist/validator/messages.js +186 -0
  88. package/dist/validator/messages.js.map +1 -0
  89. package/dist/validator/metadata.d.ts +118 -0
  90. package/dist/validator/metadata.js +153 -0
  91. package/dist/validator/metadata.js.map +1 -0
  92. package/dist/validator/transform.d.ts +29 -0
  93. package/dist/validator/transform.js +210 -0
  94. package/dist/validator/transform.js.map +1 -0
  95. package/package.json +8 -3
package/README.md CHANGED
@@ -58,7 +58,9 @@ Megh is a TypeScript-first web framework built on top of [Fastify](https://fasti
58
58
  - 🎯 **Decorator-based routing** — define controllers and routes with TypeScript decorators
59
59
  - 💉 **Dependency injection** — `MeghContainer`, `@Injectable` and `Token`, on Megh's own container (no third-party DI library)
60
60
  - 📄 **OpenAPI / Swagger** — automatic docs with Swagger UI or [Scalar](https://scalar.com)
61
- - ✅ **Validation** — request DTOs validated and whitelisted via [class-validator](https://github.com/typestack/class-validator)
61
+ - ✅ **Validation** — request DTOs validated and whitelisted, with Megh's own compiled decorators or [class-validator](https://github.com/typestack/class-validator)
62
+ - 🚨 **Error handling** — HTTP exceptions and pluggable exception filters
63
+ - ❤️ **Health checks & request IDs** — `/health` and `/ready` probes, an `x-request-id` on every response and log line
62
64
  - 🔑 **Authentication** — pluggable handler that populates `request.user`
63
65
  - 🔒 **Authorization** — deny-by-default `@Authorized` routes
64
66
  - 📁 **File uploads** — multipart support with safe, confined storage
@@ -289,6 +291,11 @@ Error responses have the shape `{ code, status: "Error", message, data? }`.
289
291
  Outside development, 5xx responses hide the message and data and return
290
292
  `"Internal Server Error"`.
291
293
 
294
+ To change how errors are turned into responses, register exception filters
295
+ with `@Catch`, `@UseFilters` or `app.useExceptionFilters()`, or replace the
296
+ handler with `app.useErrorHandler()`. See
297
+ [Error Handling](https://meghjs.github.io/core-concept/error-handling).
298
+
292
299
  ---
293
300
 
294
301
  ### Middleware
@@ -329,12 +336,16 @@ class UserController {
329
336
  Requests pass through these stages in order:
330
337
 
331
338
  1. Global middlewares (`useMiddlewares`)
332
- 2. Authentication
333
- 3. Class `@Authorized`, then method `@Authorized`
334
- 4. Class `@UseMiddleware`, then method `@UseMiddleware`
335
- 5. Parameter validation
339
+ 2. Class `@UseMiddleware`, then method `@UseMiddleware`
340
+ 3. Authentication (sets `request.user`)
341
+ 4. Class `@Authorized`, then method `@Authorized`
342
+ 5. Parameter and DTO validation
336
343
  6. Handler
337
344
 
345
+ Middleware runs before authentication, so it can reject a request early but
346
+ cannot read `request.user`. Inline routes follow the same order. (Before
347
+ 0.5.5, `@UseMiddleware` ran after `@Authorized`.)
348
+
338
349
  ---
339
350
 
340
351
  ### Authentication
@@ -439,10 +450,15 @@ under that name makes `app.run()` fail.
439
450
 
440
451
  ### Validation
441
452
 
442
- Validation is powered by `class-validator`. Decorate your DTOs and Megh validates `@Body()` and `@Query()` automatically:
453
+ Decorate your DTOs and Megh validates `@Body()` and `@Query()` automatically.
454
+ The decorators come from `@meghjs/core`, with the same names, options and
455
+ messages as `class-validator`, and each DTO is compiled once into a single
456
+ function, so validation is several times faster. DTOs written with
457
+ `class-validator` keep working; switching is a change of import. See
458
+ [Validation](https://meghjs.github.io/core-concept/validation).
443
459
 
444
460
  ```typescript
445
- import { IsString, IsNotEmpty, IsEmail, IsInt, Min, Max, IsOptional } from 'class-validator';
461
+ import { IsString, IsNotEmpty, IsEmail, IsInt, Min, Max, IsOptional } from '@meghjs/core';
446
462
 
447
463
  class CreateUserDto {
448
464
  @IsString()
@@ -1200,8 +1216,12 @@ dispatches jobs without Redis.
1200
1216
  - Set `NODE_ENV=production`. Unset also counts as production, but be explicit.
1201
1217
  Production mode hides 5xx details, writes JSON logs, and makes
1202
1218
  `app.isDevelopment()` false.
1203
- - `app.run(port)` defaults to port 4000. It handles `SIGTERM`/`SIGINT` by
1204
- stopping the scheduler and closing registered workers before exiting.
1219
+ - `app.run(port)` defaults to port 4000 and listens on `HOST` or `0.0.0.0`
1220
+ (`app.run(port, { host })` to change it). It handles `SIGTERM`/`SIGINT` by
1221
+ stopping the scheduler, closing registered workers and the cache, and gives
1222
+ up after `shutdownTimeout`.
1223
+ - Add `app.useHealth()` for `/health` and `/ready` probes. See
1224
+ [Health Checks](https://meghjs.github.io/advanced/health).
1205
1225
  - Register an authorizer if you use `@Authorized`; without one those routes
1206
1226
  return 403.
1207
1227
 
@@ -1235,13 +1255,13 @@ These are regressions or gaps in 0.3.0 that are expected to be fixed in a patch
1235
1255
  under dependency injection.** Add `constructor() { super(); }`.
1236
1256
  - **Status codes from `Results.Created`, `Results.NoContent`,
1237
1257
  `Results.NotFound`, `HttpResponse.Created` and `@HttpCode` are not applied.**
1238
- The response is 200. Throw `HttpExceptions` to send error statuses.
1258
+ The response is 200. Throw `HttpExceptions` to send error statuses. Fixed in 0.5.5.
1239
1259
  - **`@Body()`/`@Query()` DTOs are missing from the generated OpenAPI document.**
1240
1260
  Validation still runs. Describe them with `@OpenApi({ requestBody, query })`
1241
1261
  for now.
1242
- - **`@All()` crashes `app.run()`.**
1262
+ - **`@All()` crashes `app.run()`.** Fixed in 0.5.5.
1243
1263
  - **Upload policy violations return 500**, not 400 or 413.
1244
- - **`app.run()` has no `host` option.** The server binds to localhost.
1264
+ - **`app.run()` has no `host` option.** The server binds to localhost. Fixed in 0.5.5.
1245
1265
 
1246
1266
  ---
1247
1267
 
@@ -1,50 +1 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
- export declare abstract class BaseHttpException extends Error {
8
- code: number;
9
- name: string;
10
- payload: any;
11
- constructor(message: any);
12
- isCustomException(): boolean;
13
- }
14
- export declare class BadRequestException extends BaseHttpException {
15
- name: string;
16
- code: number;
17
- constructor(message: any);
18
- }
19
- export declare class ValidationErrorException extends BadRequestException {
20
- name: string;
21
- }
22
- export declare class InternalErrorException extends BaseHttpException {
23
- name: string;
24
- code: number;
25
- constructor(message?: any);
26
- }
27
- export declare class NotFoundException extends BaseHttpException {
28
- name: string;
29
- code: number;
30
- constructor(message: any);
31
- }
32
- export declare class UnauthorizedException extends BaseHttpException {
33
- name: string;
34
- code: number;
35
- constructor(message: any);
36
- }
37
- export declare class ForbiddenException extends BaseHttpException {
38
- name: string;
39
- code: number;
40
- constructor(message: any);
41
- }
42
- export type HttpExceptionTypes = NotFoundException | BadRequestException | UnauthorizedException | InternalErrorException | ForbiddenException;
43
- export declare const HttpExceptions: {
44
- notFound: (message?: any) => NotFoundException;
45
- validationError: (message?: any) => ValidationErrorException;
46
- badRequest: (message?: any) => BadRequestException;
47
- unauthorized: (message?: any) => UnauthorizedException;
48
- forbidden: (message?: any) => ForbiddenException;
49
- internalError: (message?: any) => InternalErrorException;
50
- };
1
+ export * from "../../errors/http-exceptions";
@@ -1,84 +1,19 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpExceptions = exports.ForbiddenException = exports.UnauthorizedException = exports.NotFoundException = exports.InternalErrorException = exports.ValidationErrorException = exports.BadRequestException = exports.BaseHttpException = void 0;
4
- /**
5
- * @copyright 2024
6
- * @author Tareq Hossain
7
- * @email xtrinsic96@gmail.com
8
- * @url https://github.com/xtareq
9
- */
10
- class BaseHttpException extends Error {
11
- code = 500;
12
- name = "HttpException";
13
- payload;
14
- constructor(message) {
15
- const stringMessage = typeof message === "string" ? message : JSON.stringify(message);
16
- super(stringMessage);
17
- this.payload = typeof message === "string" ? { message } : message;
18
- }
19
- isCustomException() {
20
- return true;
21
- }
22
- }
23
- exports.BaseHttpException = BaseHttpException;
24
- class BadRequestException extends BaseHttpException {
25
- name = "BadRequest";
26
- code = 400;
27
- constructor(message) {
28
- super(message);
29
- }
30
- }
31
- exports.BadRequestException = BadRequestException;
32
- class ValidationErrorException extends BadRequestException {
33
- name = "ValidationError";
34
- }
35
- exports.ValidationErrorException = ValidationErrorException;
36
- class InternalErrorException extends BaseHttpException {
37
- name = "InternalError";
38
- code = 500;
39
- constructor(message = "Something going wrong") {
40
- super(message);
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
41
7
  }
42
- }
43
- exports.InternalErrorException = InternalErrorException;
44
- class NotFoundException extends BaseHttpException {
45
- name = "NotFound";
46
- code = 404;
47
- constructor(message) {
48
- super(message);
49
- }
50
- }
51
- exports.NotFoundException = NotFoundException;
52
- class UnauthorizedException extends BaseHttpException {
53
- name = "Unauthorized";
54
- code = 401;
55
- constructor(message) {
56
- super(message);
57
- }
58
- }
59
- exports.UnauthorizedException = UnauthorizedException;
60
- class ForbiddenException extends BaseHttpException {
61
- name = "Forbidden";
62
- code = 403;
63
- constructor(message) {
64
- super(message);
65
- }
66
- }
67
- exports.ForbiddenException = ForbiddenException;
68
- // export type HttpExceptions = {
69
- // NotFound: (message: any) => NotFoundException,
70
- // ValidationError: (message: any) =>ValidationErrorException,
71
- // BadRequest: (message: any) => BadRequestException,
72
- // Unauthorized: (message: any) => UnauthorizedException,
73
- // Forbidden: (message: any) => ForbiddenException,
74
- // InternalError: (message: any) => InternalErrorException
75
- // }
76
- exports.HttpExceptions = {
77
- notFound: (message = "") => new NotFoundException(message),
78
- validationError: (message = "") => new ValidationErrorException(message),
79
- badRequest: (message = "") => new BadRequestException(message),
80
- unauthorized: (message = "") => new UnauthorizedException(message),
81
- forbidden: (message = "") => new ForbiddenException(message),
82
- internalError: (message = "") => new InternalErrorException(message),
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
83
15
  };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ // Moved to `src/errors`. Re-exported so existing imports keep working.
18
+ __exportStar(require("../../errors/http-exceptions"), exports);
84
19
  //# sourceMappingURL=http-exceptions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"http-exceptions.js","sourceRoot":"","sources":["../../../src/common/exceptions/http-exceptions.ts"],"names":[],"mappings":";;;AAEA;;;;;GAKG;AACH,MAAsB,iBAAkB,SAAQ,KAAK;IACnD,IAAI,GAAW,GAAG,CAAC;IACnB,IAAI,GAAW,eAAe,CAAC;IAC/B,OAAO,CAAM;IACb,YAAY,OAAY;QACtB,MAAM,aAAa,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QACtF,KAAK,CAAC,aAAa,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;IACrE,CAAC;IACD,iBAAiB;QACf,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAZD,8CAYC;AAED,MAAa,mBAAoB,SAAQ,iBAAiB;IACxD,IAAI,GAAW,YAAY,CAAC;IAC5B,IAAI,GAAW,GAAG,CAAC;IAEnB,YAAY,OAAY;QACtB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAPD,kDAOC;AAED,MAAa,wBAAyB,SAAQ,mBAAmB;IAC/D,IAAI,GAAW,iBAAiB,CAAC;CAClC;AAFD,4DAEC;AAED,MAAa,sBAAuB,SAAQ,iBAAiB;IAC3D,IAAI,GAAW,eAAe,CAAC;IAC/B,IAAI,GAAW,GAAG,CAAC;IAEnB,YAAY,UAAe,uBAAuB;QAChD,KAAK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AAsB,CAAC,OAAO,CAAC;CAC1E,CAAC"}
1
+ {"version":3,"file":"http-exceptions.js","sourceRoot":"","sources":["../../../src/common/exceptions/http-exceptions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uEAAuE;AACvE,+DAA6C"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ *
7
+ * Experimental: compiled request DTO validation.
8
+ *
9
+ * `transformAndValidate` runs `plainToInstance` and then class-validator's
10
+ * `validate()` on every request. Both re-read decorator metadata, allocate a
11
+ * `ValidationError` per property and go through promises even when every
12
+ * constraint is synchronous.
13
+ *
14
+ * `compileValidator` reads the same metadata once per DTO class and returns a
15
+ * synchronous function that does the same work: it builds the instance the way
16
+ * `plainToInstance` does, then calls the same constraint objects in the same
17
+ * order with the same options (`whitelist` + `forbidNonWhitelisted`). Messages
18
+ * are built only when a constraint fails, with class-validator's own message
19
+ * functions and token replacement. The result is the same `{ value, errors }`
20
+ * that `transformAndValidate` returns.
21
+ *
22
+ * Only DTOs whose behaviour can be reproduced exactly are compiled. Anything
23
+ * else returns `undefined` from `compileValidator`, and the caller keeps using
24
+ * `transformAndValidate`:
25
+ * - class-transformer metadata on the class (`@Type`, `@Transform`,
26
+ * `@Expose`, `@Exclude`)
27
+ * - nested or promise validation (`@ValidateNested`, `@ValidatePromise`)
28
+ * - constraints declared `async`
29
+ * - a class with no applicable validation metadata
30
+ * At request time the compiled function returns `undefined` (meaning "use the
31
+ * slow path for this request") if a constraint returns a promise anyway, or the
32
+ * payload holds an object the plain-copy rules don't cover.
33
+ */
34
+ import { Constructor } from "./common-utils";
35
+ import type { RequestValidationResult } from "./validation-utils";
36
+ /** A compiled validator. `undefined` means: validate this payload the slow way. */
37
+ export type CompiledValidator<T = any> = (value: unknown) => RequestValidationResult<T> | undefined;
38
+ /**
39
+ * Compile a validator for the DTO class `target`, or return `undefined` when
40
+ * the class uses something the compiled path does not reproduce exactly.
41
+ * Results are cached per class.
42
+ */
43
+ export declare function compileValidator<T extends object>(target: Constructor<T>): CompiledValidator<T> | undefined;
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compileValidator = compileValidator;
4
+ const schema_properties_1 = require("../../openapi/schema-properties");
5
+ const messages_1 = require("../../validator/messages");
6
+ const IS_DEFINED = "isDefined";
7
+ const CUSTOM_VALIDATION = "customValidation";
8
+ const CONDITIONAL_VALIDATION = "conditionalValidation";
9
+ const WHITELIST = "whitelistValidation";
10
+ /** Thrown inside a run to abandon the fast path for that payload. */
11
+ const BAIL = Symbol("megh:compiled-validation:bail");
12
+ const plans = new WeakMap();
13
+ let warnedUnavailable = false;
14
+ /**
15
+ * Compile a validator for the DTO class `target`, or return `undefined` when
16
+ * the class uses something the compiled path does not reproduce exactly.
17
+ * Results are cached per class.
18
+ */
19
+ function compileValidator(target) {
20
+ if (typeof target !== "function")
21
+ return undefined;
22
+ const cached = plans.get(target);
23
+ if (cached !== undefined)
24
+ return cached ?? undefined;
25
+ let compiled = null;
26
+ try {
27
+ const plan = buildPlan(target);
28
+ compiled = plan ? createRunner(plan) : null;
29
+ }
30
+ catch (error) {
31
+ if (!warnedUnavailable) {
32
+ warnedUnavailable = true;
33
+ console.warn("[Megh] compiled validation is unavailable, using class-validator:", error?.message ?? error);
34
+ }
35
+ compiled = null;
36
+ }
37
+ plans.set(target, compiled);
38
+ return compiled ?? undefined;
39
+ }
40
+ // ---------------------------------------------------------------------------
41
+ // Plan
42
+ // ---------------------------------------------------------------------------
43
+ function buildPlan(target) {
44
+ if (hasTransformerMetadata(target))
45
+ return undefined;
46
+ const { getMetadataStorage } = require("class-validator");
47
+ const storage = getMetadataStorage();
48
+ // Same arguments `validate(instance, options)` uses: no schema, no groups,
49
+ // `always` and `strictGroups` off.
50
+ const metadatas = storage.getTargetValidationMetadatas(target, undefined, false, false, undefined);
51
+ // class-validator answers "unknownValue" for a class without metadata.
52
+ if (metadatas.length === 0)
53
+ return undefined;
54
+ const grouped = storage.groupByPropertyName(metadatas);
55
+ const allowed = new Set();
56
+ const properties = [];
57
+ for (const name of Object.keys(grouped)) {
58
+ const group = grouped[name];
59
+ if (group.length > 0)
60
+ allowed.add(name);
61
+ const plan = {
62
+ name,
63
+ conditions: [],
64
+ defined: [],
65
+ checks: [],
66
+ };
67
+ for (const metadata of group) {
68
+ switch (metadata.type) {
69
+ case WHITELIST:
70
+ break;
71
+ case CONDITIONAL_VALIDATION:
72
+ plan.conditions.push(metadata.constraints[0]);
73
+ break;
74
+ case IS_DEFINED:
75
+ case CUSTOM_VALIDATION: {
76
+ const constraints = storage.getTargetValidatorConstraints(metadata.constraintCls);
77
+ const list = metadata.type === IS_DEFINED ? plan.defined : plan.checks;
78
+ for (const constraint of constraints) {
79
+ if (constraint.async)
80
+ return undefined;
81
+ list.push({ metadata, constraint, each: !!metadata.each });
82
+ }
83
+ break;
84
+ }
85
+ default:
86
+ // nestedValidation, promiseValidation or an unknown type.
87
+ return undefined;
88
+ }
89
+ }
90
+ properties.push(plan);
91
+ }
92
+ return {
93
+ target,
94
+ allowed,
95
+ properties,
96
+ readonlyKeys: readonlyKeysOf(target.prototype),
97
+ };
98
+ }
99
+ /** Any class-transformer decorator on the class or its ancestors. */
100
+ function hasTransformerMetadata(target) {
101
+ const storage = (0, schema_properties_1.getTransformerStorage)();
102
+ if (!storage)
103
+ return false;
104
+ const maps = [
105
+ storage._typeMetadatas,
106
+ storage._transformMetadatas,
107
+ storage._exposeMetadatas,
108
+ storage._excludeMetadatas,
109
+ ];
110
+ let current = target;
111
+ while (typeof current === "function" && current !== Function.prototype) {
112
+ for (const map of maps) {
113
+ const entry = map instanceof Map ? map.get(current) : undefined;
114
+ if (entry instanceof Map ? entry.size > 0 : entry !== undefined) {
115
+ return true;
116
+ }
117
+ }
118
+ current = Object.getPrototypeOf(current);
119
+ }
120
+ return false;
121
+ }
122
+ /**
123
+ * Keys `plainToInstance` never assigns on an instance of this class: any own
124
+ * property of the prototype without a setter (getters, methods). Inherited
125
+ * methods are caught per instance by the `instanceof Function` check.
126
+ */
127
+ function readonlyKeysOf(prototype) {
128
+ const keys = new Set();
129
+ if (!prototype)
130
+ return keys;
131
+ for (const key of Object.getOwnPropertyNames(prototype)) {
132
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, key);
133
+ if (descriptor && !descriptor.set)
134
+ keys.add(key);
135
+ }
136
+ return keys;
137
+ }
138
+ // ---------------------------------------------------------------------------
139
+ // Run
140
+ // ---------------------------------------------------------------------------
141
+ function createRunner(plan) {
142
+ const targetName = plan.target.name;
143
+ return (value) => {
144
+ if (value !== null &&
145
+ value !== undefined &&
146
+ (typeof value !== "object" || Array.isArray(value))) {
147
+ return {
148
+ value: value,
149
+ errors: [
150
+ { path: "", constraints: { isObject: "payload must be an object" } },
151
+ ],
152
+ };
153
+ }
154
+ try {
155
+ const instance = toInstance(plan, (value ?? {}));
156
+ const errors = [];
157
+ // whitelist + forbidNonWhitelisted
158
+ for (const key of Object.keys(instance)) {
159
+ if (!plan.allowed.has(key)) {
160
+ errors.push({
161
+ path: key,
162
+ constraints: { [WHITELIST]: `property ${key} should not exist` },
163
+ });
164
+ }
165
+ }
166
+ for (const property of plan.properties) {
167
+ const propertyValue = instance[property.name];
168
+ // Every condition is called, as `conditionalValidations` does.
169
+ let canValidate = true;
170
+ for (const condition of property.conditions) {
171
+ if (!condition(instance, propertyValue))
172
+ canValidate = false;
173
+ }
174
+ if (!canValidate)
175
+ continue;
176
+ let constraints;
177
+ for (const check of property.defined) {
178
+ constraints = runCheck(check, instance, propertyValue, targetName, constraints);
179
+ }
180
+ for (const check of property.checks) {
181
+ constraints = runCheck(check, instance, propertyValue, targetName, constraints);
182
+ }
183
+ if (constraints)
184
+ errors.push({ path: property.name, constraints });
185
+ }
186
+ return { value: instance, errors: errors.length > 0 ? errors : null };
187
+ }
188
+ catch (error) {
189
+ if (error === BAIL)
190
+ return undefined;
191
+ throw error;
192
+ }
193
+ };
194
+ }
195
+ function runCheck(check, object, value, targetName, constraints) {
196
+ const { metadata, constraint } = check;
197
+ const args = {
198
+ targetName,
199
+ property: metadata.propertyName,
200
+ object,
201
+ value,
202
+ constraints: metadata.constraints,
203
+ };
204
+ let valid;
205
+ if (!check.each ||
206
+ !(Array.isArray(value) || value instanceof Set || value instanceof Map)) {
207
+ const result = constraint.instance.validate(value, args);
208
+ if (isThenable(result))
209
+ throw BAIL;
210
+ valid = !!result;
211
+ }
212
+ else {
213
+ const items = value instanceof Map ? Array.from(value.values()) : Array.from(value);
214
+ valid = true;
215
+ for (const item of items) {
216
+ const result = constraint.instance.validate(item, args);
217
+ if (isThenable(result))
218
+ throw BAIL;
219
+ if (!result)
220
+ valid = false;
221
+ }
222
+ }
223
+ if (valid)
224
+ return constraints;
225
+ const type = constraint.name ? constraint.name : metadata.type;
226
+ const out = constraints ?? {};
227
+ out[type] = createMessage(metadata, constraint, args);
228
+ return out;
229
+ }
230
+ /** `ValidationExecutor.createValidationError`, message part. */
231
+ function createMessage(metadata, constraint, args) {
232
+ let message = metadata.message || "";
233
+ if (!metadata.message &&
234
+ constraint &&
235
+ constraint.instance.defaultMessage instanceof Function) {
236
+ message = constraint.instance.defaultMessage(args);
237
+ }
238
+ return (0, messages_1.replaceMessageSpecialTokens)(message, args);
239
+ }
240
+ function isThenable(value) {
241
+ return (value !== null &&
242
+ (typeof value === "object" || typeof value === "function") &&
243
+ typeof value.then === "function");
244
+ }
245
+ // ---------------------------------------------------------------------------
246
+ // plainToInstance, for a class without class-transformer metadata
247
+ // ---------------------------------------------------------------------------
248
+ /**
249
+ * `plainToInstance(target, plain)` with default options: a new instance, then
250
+ * every key of `plain` copied onto it, skipping `__proto__`, `constructor`,
251
+ * read-only accessors and methods. Nested values are copied the same way.
252
+ */
253
+ function toInstance(plan, plain) {
254
+ const instance = new plan.target();
255
+ for (const key of Object.keys(plain)) {
256
+ if (key === "__proto__" || key === "constructor")
257
+ continue;
258
+ if (plan.readonlyKeys.has(key) || instance[key] instanceof Function)
259
+ continue;
260
+ instance[key] = copyPlain(plain[key]);
261
+ }
262
+ return instance;
263
+ }
264
+ const objectPrototypeKeys = new Set(Object.getOwnPropertyNames(Object.prototype));
265
+ function copyPlain(value) {
266
+ if (value === null || typeof value !== "object") {
267
+ // Functions are copied by reference too; JSON never contains them.
268
+ return value;
269
+ }
270
+ if (Array.isArray(value)) {
271
+ const out = new Array(value.length);
272
+ for (let i = 0; i < value.length; i++)
273
+ out[i] = copyPlain(value[i]);
274
+ return out;
275
+ }
276
+ if (value instanceof Date)
277
+ return new Date(value.valueOf());
278
+ const proto = Object.getPrototypeOf(value);
279
+ // Plain objects only (incl. null-prototype objects from query parsing).
280
+ // Sets, Maps, Buffers, promises and class instances take the slow path.
281
+ if (proto !== Object.prototype && proto !== null)
282
+ throw BAIL;
283
+ // An own `constructor` key makes plainToInstance guess a type from it (and
284
+ // throw for `{"constructor": 1}`); leave that to the slow path.
285
+ if (Object.prototype.hasOwnProperty.call(value, "constructor"))
286
+ throw BAIL;
287
+ const out = {};
288
+ for (const key of Object.keys(value)) {
289
+ if (key === "__proto__" || key === "constructor")
290
+ continue;
291
+ // `{}` inherits these; plainToInstance skips them.
292
+ if (objectPrototypeKeys.has(key))
293
+ continue;
294
+ out[key] = copyPlain(value[key]);
295
+ }
296
+ return out;
297
+ }
298
+ //# sourceMappingURL=compiled-validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiled-validation.js","sourceRoot":"","sources":["../../../src/common/utils/compiled-validation.ts"],"names":[],"mappings":";;AAuFA,4CAsBC;AA3ED,uEAAwE;AACxE,uDAAuE;AAWvE,MAAM,UAAU,GAAG,WAAW,CAAC;AAC/B,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AAC7C,MAAM,sBAAsB,GAAG,uBAAuB,CAAC;AACvD,MAAM,SAAS,GAAG,qBAAqB,CAAC;AAExC,qEAAqE;AACrE,MAAM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G,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC3C,wEAAwE;IACxE,wEAAwE;IACxE,IAAI,KAAK,KAAK,MAAM,CAAC,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,MAAM,IAAI,CAAC;IAC7D,2EAA2E;IAC3E,gEAAgE;IAChE,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC;QAAE,MAAM,IAAI,CAAC;IAE3E,MAAM,GAAG,GAAwB,EAAE,CAAC;IACpC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACrC,IAAI,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,aAAa;YAAE,SAAS;QAC3D,mDAAmD;QACnD,IAAI,mBAAmB,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,SAAS;QAC3C,GAAG,CAAC,GAAG,CAAC,GAAG,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;IACnC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,6 +1,10 @@
1
1
  import { Constructor } from "./common-utils";
2
2
  export declare function pick<T extends object>(obj: T, paths: string[]): Partial<T>;
3
3
  export declare function exclude<T extends object>(obj: T | T[], paths: string[]): Partial<T> | Partial<T>[];
4
+ /**
5
+ * Cast a raw path or query value. With a scalar type hint, only that type is
6
+ * produced; without one, numbers, booleans, dates and JSON are inferred.
7
+ */
4
8
  export declare function autoCast(value: any, typeHint?: any, schema?: any): any;
5
9
  /**
6
10
  * Deeply normalizes query strings into nested JS objects.