@celljs/openapi 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +87 -2
  2. package/cell.yml +14 -0
  3. package/esm/common/annotation.d.ts +60 -0
  4. package/esm/common/annotation.js +73 -0
  5. package/esm/common/annotation.js.map +1 -0
  6. package/esm/common/constants.d.ts +11 -0
  7. package/esm/common/constants.js +12 -0
  8. package/esm/common/constants.js.map +1 -0
  9. package/esm/common/index.d.ts +3 -0
  10. package/esm/common/index.js +4 -0
  11. package/esm/common/index.js.map +1 -0
  12. package/esm/common/openapi-protocol.d.ts +143 -0
  13. package/esm/common/openapi-protocol.js +2 -0
  14. package/esm/common/openapi-protocol.js.map +1 -0
  15. package/esm/node/index.d.ts +6 -0
  16. package/esm/node/index.js +7 -0
  17. package/esm/node/index.js.map +1 -0
  18. package/esm/node/module.d.ts +3 -0
  19. package/esm/node/module.js +4 -0
  20. package/esm/node/module.js.map +1 -0
  21. package/esm/node/openapi-document-provider.d.ts +39 -0
  22. package/esm/node/openapi-document-provider.js +310 -0
  23. package/esm/node/openapi-document-provider.js.map +1 -0
  24. package/esm/node/openapi-middleware.d.ts +17 -0
  25. package/esm/node/openapi-middleware.js +76 -0
  26. package/esm/node/openapi-middleware.js.map +1 -0
  27. package/esm/node/openapi-node-protocol.d.ts +7 -0
  28. package/esm/node/openapi-node-protocol.js +4 -0
  29. package/esm/node/openapi-node-protocol.js.map +1 -0
  30. package/esm/node/openapi-path-util.d.ts +10 -0
  31. package/esm/node/openapi-path-util.js +84 -0
  32. package/esm/node/openapi-path-util.js.map +1 -0
  33. package/esm/node/schema-builder.d.ts +39 -0
  34. package/esm/node/schema-builder.js +271 -0
  35. package/esm/node/schema-builder.js.map +1 -0
  36. package/esm/node/swagger-ui.d.ts +10 -0
  37. package/esm/node/swagger-ui.js +31 -0
  38. package/esm/node/swagger-ui.js.map +1 -0
  39. package/esm/package.json +3 -0
  40. package/lib/common/annotation.d.ts +61 -0
  41. package/lib/common/annotation.d.ts.map +1 -0
  42. package/lib/common/annotation.js +86 -0
  43. package/lib/common/annotation.js.map +1 -0
  44. package/lib/common/constants.d.ts +12 -0
  45. package/lib/common/constants.d.ts.map +1 -0
  46. package/lib/common/constants.js +15 -0
  47. package/lib/common/constants.js.map +1 -0
  48. package/lib/common/index.d.ts +4 -0
  49. package/lib/common/index.d.ts.map +1 -0
  50. package/lib/common/index.js +20 -0
  51. package/lib/common/index.js.map +1 -0
  52. package/lib/common/openapi-protocol.d.ts +144 -0
  53. package/lib/common/openapi-protocol.d.ts.map +1 -0
  54. package/lib/common/openapi-protocol.js +3 -0
  55. package/lib/common/openapi-protocol.js.map +1 -0
  56. package/lib/node/index.d.ts +7 -0
  57. package/lib/node/index.d.ts.map +1 -0
  58. package/lib/node/index.js +23 -0
  59. package/lib/node/index.js.map +1 -0
  60. package/lib/node/module.d.ts +4 -0
  61. package/lib/node/module.d.ts.map +1 -0
  62. package/lib/node/module.js +6 -0
  63. package/lib/node/module.js.map +1 -0
  64. package/lib/node/openapi-document-provider.d.ts +40 -0
  65. package/lib/node/openapi-document-provider.d.ts.map +1 -0
  66. package/lib/node/openapi-document-provider.js +313 -0
  67. package/lib/node/openapi-document-provider.js.map +1 -0
  68. package/lib/node/openapi-middleware.d.ts +18 -0
  69. package/lib/node/openapi-middleware.d.ts.map +1 -0
  70. package/lib/node/openapi-middleware.js +79 -0
  71. package/lib/node/openapi-middleware.js.map +1 -0
  72. package/lib/node/openapi-node-protocol.d.ts +8 -0
  73. package/lib/node/openapi-node-protocol.d.ts.map +1 -0
  74. package/lib/node/openapi-node-protocol.js +7 -0
  75. package/lib/node/openapi-node-protocol.js.map +1 -0
  76. package/lib/node/openapi-path-util.d.ts +11 -0
  77. package/lib/node/openapi-path-util.d.ts.map +1 -0
  78. package/lib/node/openapi-path-util.js +87 -0
  79. package/lib/node/openapi-path-util.js.map +1 -0
  80. package/lib/node/openapi.spec.d.ts +30 -0
  81. package/lib/node/openapi.spec.d.ts.map +1 -0
  82. package/lib/node/openapi.spec.js +268 -0
  83. package/lib/node/openapi.spec.js.map +1 -0
  84. package/lib/node/schema-builder.d.ts +40 -0
  85. package/lib/node/schema-builder.d.ts.map +1 -0
  86. package/lib/node/schema-builder.js +275 -0
  87. package/lib/node/schema-builder.js.map +1 -0
  88. package/lib/node/schema-builder.spec.d.ts +2 -0
  89. package/lib/node/schema-builder.spec.d.ts.map +1 -0
  90. package/lib/node/schema-builder.spec.js +143 -0
  91. package/lib/node/schema-builder.spec.js.map +1 -0
  92. package/lib/node/swagger-ui.d.ts +11 -0
  93. package/lib/node/swagger-ui.d.ts.map +1 -0
  94. package/lib/node/swagger-ui.js +34 -0
  95. package/lib/node/swagger-ui.js.map +1 -0
  96. package/lib/package.spec.d.ts +2 -0
  97. package/lib/package.spec.d.ts.map +1 -0
  98. package/lib/package.spec.js +7 -0
  99. package/lib/package.spec.js.map +1 -0
  100. package/package.json +77 -4
  101. package/src/common/annotation.ts +130 -0
  102. package/src/common/constants.ts +12 -0
  103. package/src/common/index.ts +3 -0
  104. package/src/common/openapi-protocol.ts +154 -0
  105. package/src/node/index.ts +6 -0
  106. package/src/node/module.ts +4 -0
  107. package/src/node/openapi-document-provider.ts +334 -0
  108. package/src/node/openapi-middleware.ts +59 -0
  109. package/src/node/openapi-node-protocol.ts +11 -0
  110. package/src/node/openapi-path-util.ts +75 -0
  111. package/src/node/openapi.spec.ts +219 -0
  112. package/src/node/schema-builder.spec.ts +124 -0
  113. package/src/node/schema-builder.ts +282 -0
  114. package/src/node/swagger-ui.ts +38 -0
  115. package/src/package.spec.ts +5 -0
@@ -0,0 +1,59 @@
1
+ import { Autowired, Component, Value } from '@celljs/core';
2
+ import { HttpHeaders, MediaType } from '@celljs/http';
3
+ import { PathResolver } from '@celljs/web';
4
+ import { type Context, Middleware, NotFoundError, RequestMatcher } from '@celljs/web/lib/node';
5
+ import type { OpenApiOptions } from '../common';
6
+ import { OPENAPI_MIDDLEWARE_PRIORITY, OpenApiDocumentProvider } from './openapi-node-protocol';
7
+ import { SwaggerUiUtil } from './swagger-ui';
8
+
9
+ /**
10
+ * Serves the document (`cell.openapi.url`) and the Swagger UI page (`cell.openapi.ui.url`) for GET requests
11
+ * that no controller answered, so it costs nothing to the other requests.
12
+ */
13
+ @Component(Middleware)
14
+ export class OpenApiMiddleware implements Middleware {
15
+ @Autowired(OpenApiDocumentProvider)
16
+ protected readonly documentProvider: OpenApiDocumentProvider;
17
+
18
+ @Autowired(RequestMatcher)
19
+ protected readonly requestMatcher: RequestMatcher;
20
+
21
+ @Autowired(PathResolver)
22
+ protected readonly pathResolver: PathResolver;
23
+
24
+ @Value('cell.openapi')
25
+ protected readonly options: OpenApiOptions;
26
+
27
+ readonly priority = OPENAPI_MIDDLEWARE_PRIORITY;
28
+
29
+ async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
30
+ try {
31
+ await next();
32
+ } catch (error) {
33
+ if (error instanceof NotFoundError && !ctx.response.writableEnded && this.options?.enabled !== false && (await this.serve(ctx))) {
34
+ return;
35
+ }
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ protected async serve({ response }: Context): Promise<boolean> {
41
+ const url = await this.pathResolver.resolve(this.options.url);
42
+ if (await this.requestMatcher.match(url, 'GET')) {
43
+ const document = await this.documentProvider.provide();
44
+ response.statusCode = 200;
45
+ response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8);
46
+ response.body = JSON.stringify(document);
47
+ return true;
48
+ }
49
+ const { ui } = this.options;
50
+ if (ui?.enabled !== false && ui?.url && (await this.requestMatcher.match(await this.pathResolver.resolve(ui.url), 'GET'))) {
51
+ const document = await this.documentProvider.provide();
52
+ response.statusCode = 200;
53
+ response.setHeader(HttpHeaders.CONTENT_TYPE, `${MediaType.TEXT_HTML};charset=UTF-8`);
54
+ response.body = SwaggerUiUtil.render({ title: document.info.title, url, cdn: ui.cdn });
55
+ return true;
56
+ }
57
+ return false;
58
+ }
59
+ }
@@ -0,0 +1,11 @@
1
+ import { HEALTH_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
2
+ import type { OpenApiDocument } from '../common';
3
+
4
+ export const OpenApiDocumentProvider = Symbol('OpenApiDocumentProvider');
5
+
6
+ export const OPENAPI_MIDDLEWARE_PRIORITY = HEALTH_MIDDLEWARE_PRIORITY;
7
+
8
+ export interface OpenApiDocumentProvider {
9
+ /** The document of the controllers of the application; built on the first call. */
10
+ provide(): Promise<OpenApiDocument>;
11
+ }
@@ -0,0 +1,75 @@
1
+ const NAME = /^[a-zA-Z0-9]+/;
2
+
3
+ /** Turns Cell route patterns (`/users/:id`, `/users(/:id)`, `/files/*`) into OpenAPI paths. */
4
+ export namespace OpenApiPathUtil {
5
+ /** One pattern per combination of its optional parts: `/users(/:id)` gives `/users` and `/users/:id`. */
6
+ export function expand(pattern: string): string[] {
7
+ const start = indexOfUnescaped(pattern, '(');
8
+ if (start === -1) {
9
+ return [pattern];
10
+ }
11
+ let depth = 0;
12
+ let end = -1;
13
+ for (let i = start; i < pattern.length; i++) {
14
+ if (pattern[i] === '\\') {
15
+ i++;
16
+ } else if (pattern[i] === '(') {
17
+ depth++;
18
+ } else if (pattern[i] === ')' && --depth === 0) {
19
+ end = i;
20
+ break;
21
+ }
22
+ }
23
+ if (end === -1) {
24
+ return [pattern];
25
+ }
26
+ const prefix = pattern.slice(0, start);
27
+ const inner = expand(pattern.slice(start + 1, end));
28
+ const result: string[] = [];
29
+ for (const rest of expand(pattern.slice(end + 1))) {
30
+ result.push(prefix + rest);
31
+ for (const part of inner) {
32
+ result.push(prefix + part + rest);
33
+ }
34
+ }
35
+ return result;
36
+ }
37
+
38
+ /** `/users/:id` → `/users/{id}`; `*` is the parameter `_` (as in the values the route matcher gives). */
39
+ export function convert(pattern: string): { path: string; names: string[] } {
40
+ let path = '';
41
+ const names: string[] = [];
42
+ for (let i = 0; i < pattern.length; i++) {
43
+ const c = pattern[i];
44
+ if (c === '\\') {
45
+ path += pattern[++i] ?? '';
46
+ } else if (c === ':') {
47
+ const name = NAME.exec(pattern.slice(i + 1))?.[0];
48
+ if (!name) {
49
+ path += c;
50
+ continue;
51
+ }
52
+ path += `{${name}}`;
53
+ names.push(name);
54
+ i += name.length;
55
+ } else if (c === '*') {
56
+ path += '{_}';
57
+ names.push('_');
58
+ } else {
59
+ path += c;
60
+ }
61
+ }
62
+ return { path, names: [...new Set(names)] };
63
+ }
64
+
65
+ function indexOfUnescaped(text: string, char: string): number {
66
+ for (let i = 0; i < text.length; i++) {
67
+ if (text[i] === '\\') {
68
+ i++;
69
+ } else if (text[i] === char) {
70
+ return i;
71
+ }
72
+ }
73
+ return -1;
74
+ }
75
+ }
@@ -0,0 +1,219 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
2
+ import type { Server } from 'node:http';
3
+ import type { AddressInfo } from 'node:net';
4
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
5
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
6
+ import { Container } from '@celljs/core/lib/common/container/container';
7
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
8
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
9
+ import { currentThis } from '@celljs/core/lib/common/utils';
10
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
11
+ import { Body, Controller, Delete, Get, Header, Param, Post, Query, Text } from '@celljs/mvc/lib/node';
12
+ import mvcNodeModule from '@celljs/mvc/lib/node/module';
13
+ import webCommonModule from '@celljs/web/lib/common/module';
14
+ import { HttpServerUtil } from '@celljs/web/lib/node';
15
+ import webNodeModule from '@celljs/web/lib/node/module';
16
+ import { IsInt, IsOptional, IsString, Min } from 'class-validator';
17
+ import { ApiBearerAuth, ApiExclude, ApiOperation, ApiProperty, ApiQuery, ApiResponse, ApiTags, type OpenApiDocument } from '../common';
18
+ import openapiNodeModule from './module';
19
+
20
+ class Pet {
21
+ @ApiProperty({ example: 1 })
22
+ id: number;
23
+
24
+ @IsString()
25
+ name: string;
26
+ }
27
+
28
+ class CreatePet {
29
+ @IsString()
30
+ name: string;
31
+
32
+ @IsInt()
33
+ @Min(0)
34
+ @IsOptional()
35
+ age?: number;
36
+ }
37
+
38
+ class PetFilter {
39
+ @IsString()
40
+ @IsOptional()
41
+ name?: string;
42
+
43
+ @IsInt()
44
+ limit: number;
45
+ }
46
+
47
+ @Controller('pets')
48
+ @ApiTags('Pets')
49
+ export class PetController {
50
+ @Get()
51
+ @ApiOperation({ summary: 'List pets' })
52
+ @ApiResponse({ status: 200, type: [Pet] })
53
+ list(@Query() filter: PetFilter) {
54
+ return [{ id: 1, name: String(filter.name ?? 'cat') }];
55
+ }
56
+
57
+ @Get(':id')
58
+ @ApiResponse({ type: Pet })
59
+ @ApiResponse({ status: 404, description: 'No such pet' })
60
+ get(@Param('id') id: number, @Header('x-trace') trace: string) {
61
+ return { id, name: trace };
62
+ }
63
+
64
+ @Post()
65
+ @ApiBearerAuth()
66
+ create(@Body() pet: CreatePet): Pet {
67
+ return { id: 2, name: pet.name };
68
+ }
69
+
70
+ @Delete('trash(/:id)')
71
+ @ApiQuery({ name: 'force', type: Boolean, description: 'Skip the trash' })
72
+ remove(@Param('id') id: string) {
73
+ return id;
74
+ }
75
+
76
+ @Get('internal')
77
+ @ApiExclude()
78
+ internal() {
79
+ return 'hidden';
80
+ }
81
+ }
82
+
83
+ @Controller()
84
+ export class HomeController {
85
+ @Get('hello')
86
+ @Text()
87
+ hello(): string {
88
+ return 'hello';
89
+ }
90
+ }
91
+
92
+ const CONFIG = {
93
+ cell: {
94
+ name: 'Cell Framework',
95
+ annotation: { Component: { proxy: false } },
96
+ aop: { enabled: true },
97
+ logger: { level: 'error' },
98
+ tenant: { enabled: false },
99
+ session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' },
100
+ server: { path: '/', port: 3000, host: '127.0.0.1', endpoint: 'http://localhost:3000' },
101
+ trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' },
102
+ health: { url: '/health', method: 'GET' },
103
+ web: { route: { cacheSize: 500 } },
104
+ cookies: { keys: ['abcdef'] },
105
+ mvc: { path: '/*', defaultViewName: 'json', baseFileDir: 'assets' },
106
+ client: { config: {} },
107
+ openapi: {
108
+ enabled: true,
109
+ url: '/openapi.json',
110
+ ui: { enabled: true, url: '/api-docs', cdn: 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5' },
111
+ document: { openapi: '3.0.3', info: { title: 'Pet Store', version: '2.0.0' }, servers: [{ url: 'http://localhost:3000' }] },
112
+ },
113
+ },
114
+ };
115
+
116
+ /** The document and the UI through real HTTP requests, as express-adapter serves them. */
117
+ describe('openapi', () => {
118
+ let server: Server;
119
+ let base: string;
120
+ let document: OpenApiDocument;
121
+
122
+ beforeAll(async () => {
123
+ currentThis.cellProps = structuredClone(CONFIG);
124
+ const container = new Container(coreCommonStatic, coreNodeStatic, webCommonModule, webNodeModule, mvcNodeModule, openapiNodeModule, autoBind());
125
+ ContainerProvider.set(container);
126
+ await container.get<Application>(Application).start();
127
+ server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
128
+ await new Promise<void>(r => server.listen(0, '127.0.0.1', r));
129
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
130
+ const res = await fetch(`${base}/openapi.json`);
131
+ expect(res.status).toBe(200);
132
+ expect(res.headers.get('content-type')).toContain('application/json');
133
+ document = await res.json();
134
+ });
135
+
136
+ afterAll(() => new Promise<void>(r => server.close(() => r())));
137
+
138
+ it('merges cell.openapi.document', () => {
139
+ expect(document.openapi).toBe('3.0.3');
140
+ expect(document.info).toEqual({ title: 'Pet Store', version: '2.0.0' });
141
+ expect(document.servers).toEqual([{ url: 'http://localhost:3000' }]);
142
+ });
143
+
144
+ it('lists the routes, without the excluded ones', () => {
145
+ expect(Object.keys(document.paths)).toEqual(['/hello', '/pets', '/pets/trash', '/pets/trash/{id}', '/pets/{id}']);
146
+ expect(Object.keys(document.paths['/pets'])).toEqual(['get', 'post']);
147
+ });
148
+
149
+ it('expands a class of @Query() into query parameters', () => {
150
+ const list = document.paths['/pets'].get;
151
+ expect(list.tags).toEqual(['Pets']);
152
+ expect(list.summary).toBe('List pets');
153
+ expect(list.operationId).toBe('PetController_list');
154
+ expect(list.parameters).toEqual([
155
+ { name: 'name', in: 'query', schema: { type: 'string' } },
156
+ { name: 'limit', in: 'query', required: true, schema: { type: 'integer' } },
157
+ ]);
158
+ expect(list.responses['200'].content?.['application/json'].schema).toEqual({ type: 'array', items: { $ref: '#/components/schemas/Pet' } });
159
+ });
160
+
161
+ it('documents path and header parameters and declared responses', () => {
162
+ const get = document.paths['/pets/{id}'].get;
163
+ expect(get.parameters).toEqual([
164
+ { name: 'id', in: 'path', required: true, schema: { type: 'number' } },
165
+ { name: 'x-trace', in: 'header', schema: { type: 'string' } },
166
+ ]);
167
+ expect(get.responses).toEqual({
168
+ 200: { description: 'OK', content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet' } } } },
169
+ 404: { description: 'No such pet' },
170
+ });
171
+ });
172
+
173
+ it('takes the body from @Body() and the response from the return type', () => {
174
+ const create = document.paths['/pets'].post;
175
+ expect(create.requestBody).toEqual({ required: true, content: { 'application/json': { schema: { $ref: '#/components/schemas/CreatePet' } } } });
176
+ expect(create.responses['200'].content?.['application/json'].schema).toEqual({ $ref: '#/components/schemas/Pet' });
177
+ expect(create.security).toEqual([{ bearer: [] }]);
178
+ expect(document.components?.securitySchemes).toEqual({ bearer: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } });
179
+ expect(document.components?.schemas?.CreatePet).toEqual({
180
+ type: 'object',
181
+ properties: { name: { type: 'string' }, age: { type: 'integer', minimum: 0 } },
182
+ required: ['name'],
183
+ });
184
+ expect(document.components?.schemas?.Pet).toEqual({
185
+ type: 'object',
186
+ properties: { name: { type: 'string' }, id: { type: 'number', example: 1 } },
187
+ required: ['name', 'id'],
188
+ });
189
+ });
190
+
191
+ it('splits optional parts into paths with unique operation ids', () => {
192
+ const without = document.paths['/pets/trash'].delete;
193
+ const withId = document.paths['/pets/trash/{id}'].delete;
194
+ expect(without.parameters).toEqual([{ name: 'force', in: 'query', description: 'Skip the trash', schema: { type: 'boolean' } }]);
195
+ expect(withId.parameters?.[0]).toEqual({ name: 'id', in: 'path', required: true, schema: { type: 'string' } });
196
+ expect(new Set([without.operationId, withId.operationId]).size).toBe(2);
197
+ });
198
+
199
+ it('uses the content type of the view', () => {
200
+ expect(document.paths['/hello'].get.tags).toEqual(['Home']);
201
+ expect(document.paths['/hello'].get.responses['200'].content).toEqual({ 'text/plain': { schema: { type: 'string' } } });
202
+ });
203
+
204
+ it('serves Swagger UI pointing at the document', async () => {
205
+ const res = await fetch(`${base}/api-docs`);
206
+ expect(res.status).toBe(200);
207
+ expect(res.headers.get('content-type')).toContain('text/html');
208
+ const html = await res.text();
209
+ expect(html).toContain('<title>Pet Store</title>');
210
+ expect(html).toContain('url: "/openapi.json"');
211
+ expect(html).toContain('https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js');
212
+ });
213
+
214
+ it('leaves the other requests alone', async () => {
215
+ expect(await (await fetch(`${base}/hello`)).text()).toBe('hello');
216
+ expect((await fetch(`${base}/missing`)).status).toBe(404);
217
+ expect((await fetch(`${base}/openapi.json`, { method: 'POST' })).status).toBe(404);
218
+ });
219
+ });
@@ -0,0 +1,124 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { IsEmail, IsEnum, IsInt, IsOptional, IsString, Length, Max, Min, ValidateNested } from 'class-validator';
3
+ import { ApiProperty, ApiPropertyOptional } from '../common';
4
+ import { OpenApiPathUtil } from './openapi-path-util';
5
+ import { EnumUtil, SchemaBuilder } from './schema-builder';
6
+ import { SwaggerUiUtil } from './swagger-ui';
7
+
8
+ enum Role {
9
+ Admin = 'admin',
10
+ Member = 'member',
11
+ }
12
+ enum Level {
13
+ Low,
14
+ High,
15
+ }
16
+
17
+ class Address {
18
+ @IsString()
19
+ city: string;
20
+ }
21
+
22
+ class CreateUser {
23
+ @IsString()
24
+ @Length(2, 20)
25
+ name: string;
26
+
27
+ @IsInt()
28
+ @Min(0)
29
+ @Max(150)
30
+ @IsOptional()
31
+ age?: number;
32
+
33
+ @IsEmail()
34
+ email: string;
35
+
36
+ @IsEnum(Role)
37
+ role: Role;
38
+
39
+ @ValidateNested()
40
+ address: Address;
41
+
42
+ @ApiProperty({ type: [String], description: 'Labels' })
43
+ tags: string[];
44
+
45
+ @ApiPropertyOptional({ example: 'hi' })
46
+ note?: string;
47
+ }
48
+
49
+ class Node {
50
+ @ApiProperty()
51
+ name: string;
52
+
53
+ @ApiProperty({ type: [Node] })
54
+ children: Node[];
55
+ }
56
+
57
+ describe('OpenApiPathUtil', () => {
58
+ it('expands optional parts', () => {
59
+ expect(OpenApiPathUtil.expand('/users(/:id)')).toEqual(['/users', '/users/:id']);
60
+ expect(OpenApiPathUtil.expand('/a(/:b(/:c))')).toEqual(['/a', '/a/:b', '/a/:b/:c']);
61
+ expect(OpenApiPathUtil.expand('/plain')).toEqual(['/plain']);
62
+ });
63
+
64
+ it('converts parameters and wildcards', () => {
65
+ expect(OpenApiPathUtil.convert('/users/:id/posts/:postId')).toEqual({ path: '/users/{id}/posts/{postId}', names: ['id', 'postId'] });
66
+ expect(OpenApiPathUtil.convert('/files/*')).toEqual({ path: '/files/{_}', names: ['_'] });
67
+ expect(OpenApiPathUtil.convert('/a\\*b')).toEqual({ path: '/a*b', names: [] });
68
+ });
69
+ });
70
+
71
+ describe('SchemaBuilder', () => {
72
+ it('reads class-validator and @ApiProperty metadata', () => {
73
+ const builder = new SchemaBuilder();
74
+ expect(builder.resolve(CreateUser)).toEqual({ $ref: '#/components/schemas/CreateUser' });
75
+ expect(builder.schemas.CreateUser).toEqual({
76
+ type: 'object',
77
+ properties: {
78
+ name: { type: 'string', minLength: 2, maxLength: 20 },
79
+ age: { type: 'integer', minimum: 0, maximum: 150 },
80
+ email: { type: 'string', format: 'email' },
81
+ role: { type: 'string', enum: ['admin', 'member'] },
82
+ address: { $ref: '#/components/schemas/Address' },
83
+ tags: { type: 'array', items: { type: 'string' }, description: 'Labels' },
84
+ note: { type: 'string', example: 'hi' },
85
+ },
86
+ required: ['name', 'email', 'role', 'address', 'tags'],
87
+ });
88
+ expect(builder.schemas.Address).toEqual({ type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });
89
+ });
90
+
91
+ it('handles recursive classes and primitives', () => {
92
+ const builder = new SchemaBuilder();
93
+ builder.resolve(Node);
94
+ expect(builder.schemas.Node.properties?.children).toEqual({ type: 'array', items: { $ref: '#/components/schemas/Node' } });
95
+ expect(builder.resolve(Date)).toEqual({ type: 'string', format: 'date-time' });
96
+ expect(builder.resolve(Promise)).toBeUndefined();
97
+ expect(builder.resolve('integer')).toEqual({ type: 'integer' });
98
+ expect(builder.fromOptions({ enum: Level }, { type: 'object' })).toEqual({ type: 'integer', enum: [0, 1] });
99
+ });
100
+
101
+ it('gives classes with the same name different schema names', () => {
102
+ const builder = new SchemaBuilder();
103
+ const A = class Item {};
104
+ const B = class Item {};
105
+ expect(builder.resolve(A)).toEqual({ $ref: '#/components/schemas/Item' });
106
+ expect(builder.resolve(B)).toEqual({ $ref: '#/components/schemas/Item2' });
107
+ });
108
+ });
109
+
110
+ describe('EnumUtil', () => {
111
+ it('drops the reverse entries of numeric enums', () => {
112
+ expect(EnumUtil.values(Level)).toEqual([0, 1]);
113
+ expect(EnumUtil.values(Role)).toEqual(['admin', 'member']);
114
+ });
115
+ });
116
+
117
+ describe('SwaggerUiUtil', () => {
118
+ it('escapes what it puts in the page', () => {
119
+ const html = SwaggerUiUtil.render({ title: '<x>', url: '/a</script>', cdn: 'https://cdn.example/ui/' });
120
+ expect(html).toContain('<title>&#60;x&#62;</title>');
121
+ expect(html).toContain('"/a\\u003c/script>"');
122
+ expect(html).toContain('href="https://cdn.example/ui/swagger-ui.css"');
123
+ });
124
+ });