@meghjs/core 0.5.2 → 0.5.4

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 (63) hide show
  1. package/README.md +37 -24
  2. package/dist/collection/pagination.d.ts +9 -0
  3. package/dist/collection/pagination.js +11 -1
  4. package/dist/collection/pagination.js.map +1 -1
  5. package/dist/core/application.js +24 -2
  6. package/dist/core/application.js.map +1 -1
  7. package/dist/core/router.js +43 -12
  8. package/dist/core/router.js.map +1 -1
  9. package/dist/openapi/branding.d.ts +1 -1
  10. package/dist/openapi/branding.js.map +1 -1
  11. package/dist/openapi/index.d.ts +1 -0
  12. package/dist/openapi/index.js +4 -0
  13. package/dist/openapi/index.js.map +1 -1
  14. package/dist/openapi/openapi.d.ts +122 -21
  15. package/dist/openapi/openapi.js.map +1 -1
  16. package/dist/openapi/query-params.d.ts +36 -0
  17. package/dist/openapi/query-params.js +96 -0
  18. package/dist/openapi/query-params.js.map +1 -0
  19. package/dist/openapi/responses.d.ts +89 -0
  20. package/dist/openapi/responses.js +275 -0
  21. package/dist/openapi/responses.js.map +1 -0
  22. package/dist/openapi/swagger-schema.d.ts +5 -0
  23. package/dist/openapi/swagger-schema.js +5 -0
  24. package/dist/openapi/swagger-schema.js.map +1 -1
  25. package/dist/orm/connect.d.ts +12 -1
  26. package/dist/orm/connect.js +72 -1
  27. package/dist/orm/connect.js.map +1 -1
  28. package/dist/orm/connection.d.ts +7 -0
  29. package/dist/orm/connection.js +27 -3
  30. package/dist/orm/connection.js.map +1 -1
  31. package/dist/orm/core.d.ts +2 -0
  32. package/dist/orm/core.js +3 -1
  33. package/dist/orm/core.js.map +1 -1
  34. package/dist/orm/db.js +9 -1
  35. package/dist/orm/db.js.map +1 -1
  36. package/dist/orm/decorators.d.ts +4 -4
  37. package/dist/orm/decorators.js +3 -3
  38. package/dist/orm/decorators.js.map +1 -1
  39. package/dist/orm/factories.d.ts +59 -0
  40. package/dist/orm/factories.js +145 -0
  41. package/dist/orm/factories.js.map +1 -0
  42. package/dist/orm/index.d.ts +3 -0
  43. package/dist/orm/index.js +16 -1
  44. package/dist/orm/index.js.map +1 -1
  45. package/dist/orm/migrations.d.ts +6 -0
  46. package/dist/orm/migrations.js +1 -0
  47. package/dist/orm/migrations.js.map +1 -1
  48. package/dist/orm/model.d.ts +2 -8
  49. package/dist/orm/model.js.map +1 -1
  50. package/dist/orm/openapi.d.ts +8 -0
  51. package/dist/orm/openapi.js +75 -0
  52. package/dist/orm/openapi.js.map +1 -0
  53. package/dist/orm/schema.d.ts +2 -0
  54. package/dist/orm/schema.js +21 -0
  55. package/dist/orm/schema.js.map +1 -1
  56. package/dist/orm/seeders.d.ts +66 -0
  57. package/dist/orm/seeders.js +173 -0
  58. package/dist/orm/seeders.js.map +1 -0
  59. package/dist/orm/state.d.ts +2 -2
  60. package/dist/orm/state.js +13 -3
  61. package/dist/orm/state.js.map +1 -1
  62. package/dist/orm/types.d.ts +39 -15
  63. package/package.json +29 -5
@@ -1,3 +1,4 @@
1
+ import type { PaginatedType } from "./responses";
1
2
  export interface InfoObject {
2
3
  title: string;
3
4
  description?: string;
@@ -27,30 +28,125 @@ export interface ServerVariableObject {
27
28
  default: string;
28
29
  description?: string;
29
30
  }
31
+ /** Swagger UI's top-bar logo. */
32
+ export interface SwaggerUiLogo {
33
+ /** Media type, e.g. `"image/svg+xml"` or `"image/png"`. */
34
+ type: string;
35
+ content: string | Buffer;
36
+ /** Link the logo opens. */
37
+ href?: string;
38
+ target?: "_blank" | "_parent" | "_self" | "_top";
39
+ }
40
+ /** A file Swagger UI's page loads: a stylesheet, script or favicon. */
41
+ export interface SwaggerUiThemeFile {
42
+ filename: string;
43
+ content: string | Buffer;
44
+ }
45
+ export interface SwaggerUiFavicon extends SwaggerUiThemeFile {
46
+ /** e.g. `"icon"`. */
47
+ rel: string;
48
+ /** e.g. `"32x32"`. */
49
+ sizes: string;
50
+ /** e.g. `"image/png"`. */
51
+ type: string;
52
+ }
53
+ /** Swagger UI's page: its title, extra stylesheets and scripts, and favicons. */
54
+ export interface SwaggerUiTheme {
55
+ /** The browser tab's title. */
56
+ title?: string;
57
+ css?: SwaggerUiThemeFile[];
58
+ js?: SwaggerUiThemeFile[];
59
+ favicon?: SwaggerUiFavicon[];
60
+ }
61
+ /** Swagger UI settings (https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/). */
62
+ export interface SwaggerUiConfig {
63
+ /** Which operations start expanded. Megh defaults to `"full"`. */
64
+ docExpansion?: "list" | "full" | "none";
65
+ /** Link to each operation from the URL. Megh defaults to `false`. */
66
+ deepLinking?: boolean;
67
+ /** Keep the "Authorize" credentials across page reloads. */
68
+ persistAuthorization?: boolean;
69
+ /** Show how long each "Try it out" request took. */
70
+ displayRequestDuration?: boolean;
71
+ /** Show a box that filters operations by tag. */
72
+ filter?: boolean | string;
73
+ /** Open every operation in "Try it out" mode. */
74
+ tryItOutEnabled?: boolean;
75
+ /** How deep schemas start expanded in the models list; `-1` hides it. */
76
+ defaultModelsExpandDepth?: number;
77
+ defaultModelExpandDepth?: number;
78
+ /** Order of operations within a tag. */
79
+ operationsSorter?: "alpha" | "method";
80
+ tagsSorter?: "alpha";
81
+ /** Any other Swagger UI setting. */
82
+ [setting: string]: unknown;
83
+ }
84
+ /** Scalar settings (https://github.com/scalar/scalar/blob/main/documentation/configuration.md). */
85
+ export interface ScalarConfig {
86
+ /** Color theme, e.g. `"default"`, `"purple"`, `"moon"`, `"kepler"`. */
87
+ theme?: string;
88
+ layout?: "modern" | "classic";
89
+ darkMode?: boolean;
90
+ hideModels?: boolean;
91
+ /** Hide the "Download OpenAPI document" button. */
92
+ hideDownloadButton?: boolean;
93
+ /** Extra CSS for the page. */
94
+ customCss?: string;
95
+ /** Any other Scalar setting. */
96
+ [setting: string]: unknown;
97
+ }
98
+ /**
99
+ * How `@Authorized` routes are secured, for the "Authorize" button:
100
+ * `"bearer"` (a JWT in `Authorization: Bearer …`), `"apiKey"` (an
101
+ * `X-API-Key` header), or any OpenAPI security scheme. Each `@Authorized`
102
+ * route is marked with it.
103
+ */
104
+ export type OpenApiAuth = "bearer" | "apiKey" | SecuritySchemeObject;
105
+ /**
106
+ * Options for `app.useOpenApi()`: the document's details and the docs page.
107
+ *
108
+ * ```ts
109
+ * app.useOpenApi({
110
+ * info: { title: 'Shop API', version: '1.0.0' },
111
+ * routePrefix: '/docs',
112
+ * auth: 'bearer',
113
+ * });
114
+ * ```
115
+ */
30
116
  export type OpenApiUiOptions = {
31
- /**
32
- * Swagger UI top-bar logo, e.g. `{ type: "image/svg+xml", content, href? }`.
33
- * Defaults to the Megh logo; `null` shows Swagger UI's own logo.
34
- */
35
- logo?: any;
36
- /**
37
- * Swagger UI theme (`title`, `css`, `js`, `favicon`). Defaults to the Megh
38
- * favicon; any key given here replaces the default.
39
- */
40
- theme?: any;
41
- provider?: "default" | "scalar";
42
- ui?: "default" | "scalar";
43
- openapi?: string;
44
- uiConfig?: any;
45
- configuration?: any;
46
- routePrefix?: string;
117
+ /** The API's title, version and description. Defaults to `{ title: "API", version: "1.0.0" }`. */
47
118
  info?: InfoObject;
119
+ /** Where the docs page is served. Defaults to `/swagger`; the document is at `<routePrefix>/json`. */
120
+ routePrefix?: string;
121
+ /** The docs page: Swagger UI (`"default"`) or Scalar (`"scalar"`, needs `@scalar/fastify-api-reference`). */
122
+ provider?: "default" | "scalar";
123
+ /** Marks every `@Authorized` route with this security scheme. See {@link OpenApiAuth}. */
124
+ auth?: OpenApiAuth;
125
+ /** Base URLs the API is served from, e.g. `[{ url: "https://api.example.com" }]`. */
48
126
  servers?: ServerObject[];
49
- paths?: PathsObject<any>;
50
- components?: ComponentsObject;
51
- security?: SecurityRequirementObject[];
127
+ /** Descriptions of the tags (one per controller, named after it without `Controller`). */
52
128
  tags?: TagObject[];
53
- externalDocs?: any;
129
+ /** Security requirement for every operation. Prefer `auth`, which applies to `@Authorized` routes only. */
130
+ security?: SecurityRequirementObject[];
131
+ /** Extra component schemas, responses, security schemes, … merged into the generated ones. */
132
+ components?: ComponentsObject;
133
+ externalDocs?: ExternalDocumentationObject;
134
+ /** Swagger UI settings. With `provider: "scalar"`, Scalar settings (or use `scalar`). */
135
+ uiConfig?: SwaggerUiConfig;
136
+ /** Scalar settings, with `provider: "scalar"`. */
137
+ scalar?: ScalarConfig;
138
+ /** Swagger UI's top-bar logo. Defaults to the Megh logo; `null` shows Swagger UI's own. */
139
+ logo?: SwaggerUiLogo | null;
140
+ /** Swagger UI's page title, CSS, scripts and favicon. Defaults to the Megh favicon. */
141
+ theme?: SwaggerUiTheme;
142
+ /** OpenAPI version of the document. Defaults to `"3.0.3"`. */
143
+ openapi?: string;
144
+ /** Extra paths documented as given, e.g. for routes outside Megh. */
145
+ paths?: PathsObject<any>;
146
+ /** @deprecated Use `provider`. */
147
+ ui?: "default" | "scalar";
148
+ /** @deprecated Use `scalar`. */
149
+ configuration?: ScalarConfig;
54
150
  };
55
151
  export interface PathsObject<T extends {} = {}, P extends {} = {}> {
56
152
  [pattern: string]: (PathItemObject<T> & P) | undefined;
@@ -395,8 +491,13 @@ export type ResponseBodyOptions = {
395
491
  [media: string]: MediaTypeObject;
396
492
  };
397
493
  } & Partial<BaseSchemaObject>;
494
+ /**
495
+ * Responses keyed by status code. A DTO or model class, `[Class]` or
496
+ * `Paginated(Class)` is documented only; a JSON schema (`ResponseBodyOptions`)
497
+ * also becomes Fastify's response schema, which serializes the reply.
498
+ */
398
499
  export type ResponsesOptions = {
399
- [statusCode: number]: ResponseBodyOptions | ResponseObject;
500
+ [statusCode: number]: ResponseBodyOptions | ResponseObject | SchemaClass | readonly [SchemaClass] | PaginatedType;
400
501
  };
401
502
  export type OpenApiOptions = {
402
503
  exclude?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.js","sourceRoot":"","sources":["../../src/openapi/openapi.ts"],"names":[],"mappings":";;AA8cA,kEAuBC;AACD,sCAIC;AACD,0BAmBC;AA9fD;;;;;GAKG;AACH,2DAA6D;AA4D7D,IAAK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;AACD,SAAgB,aAAa;IAC3B,OAAO,UAAU,MAAM;QACrB,OAAO,CAAC,cAAc,CAAC,gBAAgB,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;IACzD,CAAC,CAAC;AACJ,CAAC;AACD,SAAgB,OAAO,CACrB,OAAuB;IAEvB,OAAO,UACL,MAAyB,EACzB,WAA6B,EAC7B,UAA+B;QAE/B,IAAI,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,WAAW,EAAE,CAAC;YACjD,OAAO,CAAC,cAAc,CAAC,oBAAoB,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAChE,CAAC;aAAM,IAAI,UAAU,EAAE,CAAC;YACtB,0EAA0E;YAC1E,OAAO,CAAC,cAAc,CAAC,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,WAAY,CAAC,CAAC;QACzE,CAAC;aAAM,IAAI,WAAW,EAAE,CAAC;YACvB,OAAO,CAAC,cAAc,CAAC,kBAAkB,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;YACzE,IAAI,OAAO,WAAW,KAAK,QAAQ;gBACjC,IAAA,0CAAsB,EAAC,MAAM,EAAE,WAAW,CAAC,CAAC;QAChD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @copyright 2024
3
+ * @author Tareq Hossain
4
+ * @email xtrinsic96@gmail.com
5
+ * @url https://github.com/xtareq
6
+ *
7
+ * Internal: documenting `@Query()` parameters as OpenAPI query parameters.
8
+ *
9
+ * Megh validates query DTOs itself, so routes get no Fastify `querystring`
10
+ * schema (that would add a second validator with different errors). The
11
+ * parameters ride on the route schema under {@link QUERY_PARAMS_EXTENSION}
12
+ * and {@link applyQueryParamExtensions} moves them into place once the
13
+ * document is generated.
14
+ */
15
+ import type { ParameterObject } from "./openapi";
16
+ export declare const QUERY_PARAMS_EXTENSION = "x-megh-query-parameters";
17
+ type QueryMeta = {
18
+ index: number;
19
+ key: string;
20
+ required?: boolean;
21
+ dataType?: unknown;
22
+ validatorClass?: boolean;
23
+ };
24
+ /**
25
+ * Query parameters for a route's `@Query()` metadata: a whole-query DTO
26
+ * (`@Query() q: Dto`) becomes one parameter per property, `@Query('key')`
27
+ * one parameter.
28
+ */
29
+ export declare function buildQueryParameters(query: QueryMeta[]): ParameterObject[];
30
+ /**
31
+ * `@fastify/swagger` `transformObject` hook: add every route's
32
+ * {@link QUERY_PARAMS_EXTENSION} to the operation's `parameters`. A query
33
+ * parameter already documented (e.g. through `@OpenApi({ query })`) wins.
34
+ */
35
+ export declare function applyQueryParamExtensions<T = any>(document: T): T;
36
+ export {};
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QUERY_PARAMS_EXTENSION = void 0;
4
+ exports.buildQueryParameters = buildQueryParameters;
5
+ exports.applyQueryParamExtensions = applyQueryParamExtensions;
6
+ const swagger_schema_1 = require("./swagger-schema");
7
+ exports.QUERY_PARAMS_EXTENSION = "x-megh-query-parameters";
8
+ const PRIMITIVES = new Set(["string", "number", "integer", "boolean"]);
9
+ function isClass(value) {
10
+ return typeof value === "function" && !!value.prototype;
11
+ }
12
+ /** A property schema as a Parameter Object; `description`/`example` move up a level. */
13
+ function toParameter(name, schema, required) {
14
+ const { description, example, ...rest } = schema ?? {};
15
+ const param = { name, in: "query", required, schema: rest };
16
+ if (description !== undefined)
17
+ param.description = description;
18
+ if (example !== undefined)
19
+ param.example = example;
20
+ return param;
21
+ }
22
+ /**
23
+ * Query parameters for a route's `@Query()` metadata: a whole-query DTO
24
+ * (`@Query() q: Dto`) becomes one parameter per property, `@Query('key')`
25
+ * one parameter.
26
+ */
27
+ function buildQueryParameters(query) {
28
+ const out = [];
29
+ const seen = new Set();
30
+ const add = (p) => {
31
+ if (seen.has(p.name))
32
+ return;
33
+ seen.add(p.name);
34
+ out.push(p);
35
+ };
36
+ // Parameter decorators run last to first; list them in signature order.
37
+ const ordered = [...query].sort((a, b) => a.index - b.index);
38
+ for (const q of ordered) {
39
+ const type = q.dataType;
40
+ if (q.key === "all") {
41
+ if (!q.validatorClass || !isClass(type))
42
+ continue;
43
+ const schema = (0, swagger_schema_1.generateClassSchema)(type, { inline: true });
44
+ const required = schema.required ?? [];
45
+ for (const [name, prop] of Object.entries(schema.properties ?? {}))
46
+ add(toParameter(name, prop, required.includes(name)));
47
+ continue;
48
+ }
49
+ let schema;
50
+ if (typeof type === "string" && PRIMITIVES.has(type))
51
+ schema = { type };
52
+ else if (type === "array")
53
+ schema = { type: "array", items: { type: "string" } };
54
+ else if (q.validatorClass && isClass(type))
55
+ schema = (0, swagger_schema_1.generateClassSchema)(type, { inline: true });
56
+ else
57
+ schema = { type: "string" };
58
+ const param = toParameter(q.key, schema, q.required ?? true);
59
+ if (schema.type === "object") {
60
+ param.style = "deepObject";
61
+ param.explode = true;
62
+ }
63
+ add(param);
64
+ }
65
+ return out;
66
+ }
67
+ /**
68
+ * `@fastify/swagger` `transformObject` hook: add every route's
69
+ * {@link QUERY_PARAMS_EXTENSION} to the operation's `parameters`. A query
70
+ * parameter already documented (e.g. through `@OpenApi({ query })`) wins.
71
+ */
72
+ function applyQueryParamExtensions(document) {
73
+ const paths = document?.paths;
74
+ if (!paths || typeof paths !== "object")
75
+ return document;
76
+ for (const pathItem of Object.values(paths)) {
77
+ if (!pathItem || typeof pathItem !== "object")
78
+ continue;
79
+ for (const operation of Object.values(pathItem)) {
80
+ if (!operation || typeof operation !== "object")
81
+ continue;
82
+ const ext = operation[exports.QUERY_PARAMS_EXTENSION];
83
+ if (!ext)
84
+ continue;
85
+ delete operation[exports.QUERY_PARAMS_EXTENSION];
86
+ const params = (operation.parameters ??= []);
87
+ const documented = new Set(params.filter((p) => p?.in === "query").map((p) => p.name));
88
+ for (const p of ext) {
89
+ if (!documented.has(p.name))
90
+ params.push(structuredClone(p));
91
+ }
92
+ }
93
+ }
94
+ return document;
95
+ }
96
+ //# sourceMappingURL=query-params.js.map
@@ -0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C,EAAE,EAAE,KAAK,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAC3D,CAAC;YACF,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC;gBACpB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;oBAAE,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Documented responses: what each route returns, from `@ApiResponse()` and
3
+ * what the controller tells us (a validated DTO can fail with 400, an
4
+ * `@Authorized` route with 401 and 403).
5
+ *
6
+ * Like request bodies (see request-body.ts), these are documentation only.
7
+ * A Fastify `response` schema would also serialize the reply, dropping every
8
+ * field it doesn't list (loaded relations, `withCount` counts, …), so the
9
+ * Responses Object rides on the route schema under {@link RESPONSES_EXTENSION}
10
+ * and {@link applyResponseExtensions} moves it into the document.
11
+ */
12
+ import { PAGINATED_ITEM as PAGINATED } from "../collection/pagination";
13
+ import type { ReferenceObject, ResponseObject, SchemaClass, SchemaObject } from "./openapi";
14
+ export declare const RESPONSES_EXTENSION = "x-megh-responses";
15
+ /** Marks an operation that needs authorization, for the `auth` option. */
16
+ export declare const AUTHORIZED_EXTENSION = "x-megh-authorized";
17
+ /** `{ data: T[], meta }`, as `paginate()` returns. Build it with {@link Paginated}. */
18
+ export interface PaginatedType {
19
+ readonly [PAGINATED]: SchemaClass;
20
+ }
21
+ /**
22
+ * What a response body is: a DTO or model class, `[Class]` for an array,
23
+ * `Paginated(Class)` for a page, or a JSON schema.
24
+ */
25
+ export type ResponseType = SchemaClass | readonly [SchemaClass] | PaginatedType | SchemaObject | ReferenceObject;
26
+ export interface ApiResponseOptions {
27
+ /** The body. Leave it out for an empty body; errors default to the error shape. */
28
+ type?: ResponseType;
29
+ /** Defaults to a description of the status code. */
30
+ description?: string;
31
+ /** Defaults to `application/json`. */
32
+ contentType?: string;
33
+ example?: unknown;
34
+ }
35
+ interface DeclaredResponse extends ApiResponseOptions {
36
+ status: number;
37
+ }
38
+ /**
39
+ * Document a response of a route (on a method) or of every route in a
40
+ * controller (on the class). Stack it for several status codes:
41
+ *
42
+ * ```ts
43
+ * @Get('/:id')
44
+ * @ApiResponse(200, User)
45
+ * @ApiResponse(404)
46
+ * show(@Param('id') id: number) { … }
47
+ * ```
48
+ *
49
+ * The type may be a DTO or MeghORM model class, `[User]` for an array,
50
+ * `Paginated(User)` for a page, or a JSON schema. It's documentation only:
51
+ * what the handler returns is sent unchanged.
52
+ */
53
+ export declare function ApiResponse(status: number, type?: ResponseType | ApiResponseOptions, description?: string): MethodDecorator & ClassDecorator;
54
+ /** `@ApiResponse()`s on a controller class and one of its methods. */
55
+ export declare function declaredResponses(controller: Function, method: string): DeclaredResponse[];
56
+ /** Whether `value` is something a response can be documented with (a class, `[Class]` or `Paginated()`). */
57
+ export declare function isResponseType(value: unknown): boolean;
58
+ /**
59
+ * Something that can describe a class as a JSON schema, e.g. the ORM for its
60
+ * models. Returns `undefined` for classes it doesn't know.
61
+ */
62
+ export type SchemaProvider = (cls: SchemaClass) => SchemaObject | undefined;
63
+ /** Describe classes the DTO reader doesn't (MeghORM registers its models). */
64
+ export declare function registerSchemaProvider(provider: SchemaProvider): void;
65
+ export interface RouteResponses {
66
+ responses: Record<string, ResponseObject>;
67
+ /** Component schemas the responses refer to, keyed by name. */
68
+ schemas: Record<string, any>;
69
+ }
70
+ /**
71
+ * The Responses Object for a route: its `@ApiResponse()`s, plus the errors
72
+ * its controller can produce that aren't declared already.
73
+ */
74
+ export declare function buildResponses(route: {
75
+ declared: DeclaredResponse[];
76
+ /** The route validates a `@Body()` or `@Query()` DTO. */
77
+ validates: boolean;
78
+ /** `@Authorized` applies to the route. */
79
+ authorized: boolean;
80
+ }): RouteResponses | undefined;
81
+ /**
82
+ * Move each operation's {@link RESPONSES_EXTENSION} into its `responses`,
83
+ * add the schemas they use, and apply `security` to authorized operations.
84
+ */
85
+ export declare function applyResponseExtensions<T = any>(document: T, security?: {
86
+ requirement: Record<string, string[]>;
87
+ scheme: [string, any];
88
+ }): T;
89
+ export {};
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AUTHORIZED_EXTENSION = exports.RESPONSES_EXTENSION = void 0;
4
+ exports.ApiResponse = ApiResponse;
5
+ exports.declaredResponses = declaredResponses;
6
+ exports.isResponseType = isResponseType;
7
+ exports.registerSchemaProvider = registerSchemaProvider;
8
+ exports.buildResponses = buildResponses;
9
+ exports.applyResponseExtensions = applyResponseExtensions;
10
+ /**
11
+ * Documented responses: what each route returns, from `@ApiResponse()` and
12
+ * what the controller tells us (a validated DTO can fail with 400, an
13
+ * `@Authorized` route with 401 and 403).
14
+ *
15
+ * Like request bodies (see request-body.ts), these are documentation only.
16
+ * A Fastify `response` schema would also serialize the reply, dropping every
17
+ * field it doesn't list (loaded relations, `withCount` counts, …), so the
18
+ * Responses Object rides on the route schema under {@link RESPONSES_EXTENSION}
19
+ * and {@link applyResponseExtensions} moves it into the document.
20
+ */
21
+ const pagination_1 = require("../collection/pagination");
22
+ const swagger_schema_1 = require("./swagger-schema");
23
+ exports.RESPONSES_EXTENSION = "x-megh-responses";
24
+ /** Marks an operation that needs authorization, for the `auth` option. */
25
+ exports.AUTHORIZED_EXTENSION = "x-megh-authorized";
26
+ const RESPONSES_META = "openapi:responses";
27
+ const SCHEMAS = "#/components/schemas/";
28
+ /**
29
+ * Document a response of a route (on a method) or of every route in a
30
+ * controller (on the class). Stack it for several status codes:
31
+ *
32
+ * ```ts
33
+ * @Get('/:id')
34
+ * @ApiResponse(200, User)
35
+ * @ApiResponse(404)
36
+ * show(@Param('id') id: number) { … }
37
+ * ```
38
+ *
39
+ * The type may be a DTO or MeghORM model class, `[User]` for an array,
40
+ * `Paginated(User)` for a page, or a JSON schema. It's documentation only:
41
+ * what the handler returns is sent unchanged.
42
+ */
43
+ function ApiResponse(status, type, description) {
44
+ const entry = isOptions(type)
45
+ ? { status, ...type }
46
+ : { status, type, description };
47
+ return (target, propertyKey) => {
48
+ const args = propertyKey === undefined ? [target] : [target, propertyKey];
49
+ const list = Reflect.getOwnMetadata(RESPONSES_META, ...args) ?? [];
50
+ Reflect.defineMetadata(RESPONSES_META, [...list, entry], ...args);
51
+ };
52
+ }
53
+ /** `@ApiResponse()`s on a controller class and one of its methods. */
54
+ function declaredResponses(controller, method) {
55
+ const get = (...args) => Reflect.getMetadata(RESPONSES_META, ...args) ?? [];
56
+ return [...get(controller), ...get(controller.prototype, method)];
57
+ }
58
+ function isOptions(value) {
59
+ if (!value || typeof value !== "object" || Array.isArray(value))
60
+ return false;
61
+ if (pagination_1.PAGINATED_ITEM in value || "$ref" in value)
62
+ return false;
63
+ // A JSON schema has schema keywords; options have only these keys.
64
+ const keys = Object.keys(value);
65
+ return (keys.length > 0 &&
66
+ keys.every((k) => ["type", "description", "contentType", "example"].includes(k)) &&
67
+ typeof value.type !== "string");
68
+ }
69
+ const isClass = (value) => typeof value === "function" && !!value.prototype;
70
+ /** Whether `value` is something a response can be documented with (a class, `[Class]` or `Paginated()`). */
71
+ function isResponseType(value) {
72
+ return (isClass(value) ||
73
+ (Array.isArray(value) && value.length === 1 && isClass(value[0])) ||
74
+ (!!value && typeof value === "object" && pagination_1.PAGINATED_ITEM in value));
75
+ }
76
+ const STATUS_TEXT = {
77
+ 200: "OK",
78
+ 201: "Created",
79
+ 202: "Accepted",
80
+ 204: "No Content",
81
+ 400: "Bad Request",
82
+ 401: "Unauthorized",
83
+ 403: "Forbidden",
84
+ 404: "Not Found",
85
+ 409: "Conflict",
86
+ 422: "Unprocessable Entity",
87
+ 429: "Too Many Requests",
88
+ 500: "Internal Server Error",
89
+ };
90
+ const ERROR_SCHEMA = {
91
+ type: "object",
92
+ description: "Megh's error response.",
93
+ properties: {
94
+ code: { type: "integer", example: 404 },
95
+ status: { type: "string", example: "Error" },
96
+ message: { type: "string", example: "Not Found" },
97
+ data: { description: "Details, when the error carries any." },
98
+ },
99
+ required: ["code", "status", "message"],
100
+ };
101
+ const VALIDATION_ERROR_SCHEMA = {
102
+ type: "object",
103
+ description: "A request that failed DTO validation.",
104
+ properties: {
105
+ code: { type: "integer", example: 400 },
106
+ status: { type: "string", example: "Error" },
107
+ message: { type: "string", example: "email must be an email" },
108
+ errors: {
109
+ type: "array",
110
+ items: {
111
+ type: "object",
112
+ properties: {
113
+ path: { type: "string", example: "email" },
114
+ constraints: {
115
+ type: "object",
116
+ additionalProperties: { type: "string" },
117
+ example: { isEmail: "email must be an email" },
118
+ },
119
+ },
120
+ },
121
+ },
122
+ },
123
+ required: ["code", "status", "message"],
124
+ };
125
+ const PAGINATION_META_SCHEMA = {
126
+ type: "object",
127
+ properties: {
128
+ total: { type: "integer", description: "Items across all pages." },
129
+ page: { type: "integer", description: "Current 1-based page." },
130
+ perPage: { type: "integer", description: "Items per page." },
131
+ lastPage: {
132
+ type: "integer",
133
+ description: "Last page number (at least 1).",
134
+ },
135
+ next: {
136
+ type: "integer",
137
+ nullable: true,
138
+ description: "Next page, or null on the last page.",
139
+ },
140
+ prev: {
141
+ type: "integer",
142
+ nullable: true,
143
+ description: "Previous page, or null on the first page.",
144
+ },
145
+ },
146
+ required: ["total", "page", "perPage", "lastPage", "next", "prev"],
147
+ };
148
+ const schemaProviders = [];
149
+ /** Describe classes the DTO reader doesn't (MeghORM registers its models). */
150
+ function registerSchemaProvider(provider) {
151
+ if (!schemaProviders.includes(provider))
152
+ schemaProviders.push(provider);
153
+ }
154
+ function providedSchema(cls) {
155
+ for (const provider of schemaProviders) {
156
+ const schema = provider(cls);
157
+ if (schema)
158
+ return schema;
159
+ }
160
+ return undefined;
161
+ }
162
+ /** A `$ref` to `cls`'s schema, collecting it (and what it references) into `schemas`. */
163
+ function schemaRef(cls, schemas) {
164
+ const name = cls.name;
165
+ if (!(name in schemas)) {
166
+ schemas[name] = { type: "object" }; // placeholder for cycles
167
+ schemas[name] =
168
+ providedSchema(cls) ?? (0, swagger_schema_1.generateClassSchema)(cls, { components: schemas });
169
+ }
170
+ return { $ref: `${SCHEMAS}${name}` };
171
+ }
172
+ function bodySchema(type, schemas) {
173
+ if (isClass(type))
174
+ return schemaRef(type, schemas);
175
+ if (Array.isArray(type))
176
+ return { type: "array", items: schemaRef(type[0], schemas) };
177
+ if (type && typeof type === "object" && pagination_1.PAGINATED_ITEM in type) {
178
+ const item = type[pagination_1.PAGINATED_ITEM];
179
+ schemas.PaginationMeta ??= PAGINATION_META_SCHEMA;
180
+ return {
181
+ type: "object",
182
+ properties: {
183
+ data: { type: "array", items: schemaRef(item, schemas) },
184
+ meta: { $ref: `${SCHEMAS}PaginationMeta` },
185
+ },
186
+ required: ["data", "meta"],
187
+ };
188
+ }
189
+ return type;
190
+ }
191
+ function response(entry, schemas) {
192
+ const description = entry.description ?? STATUS_TEXT[entry.status] ?? `Status ${entry.status}`;
193
+ let type = entry.type;
194
+ if (type === undefined && entry.status >= 400) {
195
+ schemas.ErrorResponse ??= ERROR_SCHEMA;
196
+ type = { $ref: `${SCHEMAS}ErrorResponse` };
197
+ }
198
+ if (type === undefined)
199
+ return { description };
200
+ const media = { schema: bodySchema(type, schemas) };
201
+ if (entry.example !== undefined)
202
+ media.example = entry.example;
203
+ return {
204
+ description,
205
+ content: { [entry.contentType ?? "application/json"]: media },
206
+ };
207
+ }
208
+ /**
209
+ * The Responses Object for a route: its `@ApiResponse()`s, plus the errors
210
+ * its controller can produce that aren't declared already.
211
+ */
212
+ function buildResponses(route) {
213
+ const schemas = {};
214
+ const responses = {};
215
+ for (const entry of route.declared)
216
+ responses[String(entry.status)] = response(entry, schemas);
217
+ if (route.validates && !responses["400"]) {
218
+ schemas.ValidationErrorResponse ??= VALIDATION_ERROR_SCHEMA;
219
+ responses["400"] = response({
220
+ status: 400,
221
+ description: "Validation failed",
222
+ type: { $ref: `${SCHEMAS}ValidationErrorResponse` },
223
+ }, schemas);
224
+ }
225
+ if (route.authorized) {
226
+ responses["401"] ??= response({ status: 401, description: "Missing or invalid credentials" }, schemas);
227
+ responses["403"] ??= response({ status: 403, description: "Not allowed to do this" }, schemas);
228
+ }
229
+ return Object.keys(responses).length ? { responses, schemas } : undefined;
230
+ }
231
+ /**
232
+ * Move each operation's {@link RESPONSES_EXTENSION} into its `responses`,
233
+ * add the schemas they use, and apply `security` to authorized operations.
234
+ */
235
+ function applyResponseExtensions(document, security) {
236
+ const doc = document;
237
+ const schemas = {};
238
+ for (const item of Object.values(doc?.paths ?? {})) {
239
+ for (const operation of Object.values(item ?? {})) {
240
+ if (!operation || typeof operation !== "object")
241
+ continue;
242
+ const extension = operation[exports.RESPONSES_EXTENSION];
243
+ delete operation[exports.RESPONSES_EXTENSION];
244
+ const authorized = operation[exports.AUTHORIZED_EXTENSION] === true;
245
+ delete operation[exports.AUTHORIZED_EXTENSION];
246
+ if (authorized && security && !operation.security)
247
+ operation.security = [security.requirement];
248
+ if (!extension)
249
+ continue;
250
+ const existing = operation.responses ?? {};
251
+ const declaresSuccess = Object.keys(extension.responses).some((s) => s.startsWith("2"));
252
+ // @fastify/swagger adds a bare "200: Default Response"; a documented success replaces it.
253
+ if (declaresSuccess &&
254
+ existing["200"]?.description === "Default Response" &&
255
+ !existing["200"].content) {
256
+ delete existing["200"];
257
+ }
258
+ operation.responses = { ...existing, ...extension.responses };
259
+ Object.assign(schemas, extension.schemas);
260
+ }
261
+ }
262
+ if (Object.keys(schemas).length || security) {
263
+ doc.components ??= {};
264
+ if (Object.keys(schemas).length)
265
+ doc.components.schemas = { ...schemas, ...doc.components.schemas };
266
+ if (security) {
267
+ doc.components.securitySchemes = {
268
+ [security.scheme[0]]: security.scheme[1],
269
+ ...doc.components.securitySchemes,
270
+ };
271
+ }
272
+ }
273
+ return document;
274
+ }
275
+ //# sourceMappingURL=responses.js.map