@nestia/sdk 2.4.7 → 2.5.0-dev.20240129

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 (40) hide show
  1. package/lib/generates/internal/E2eFileProgrammer.js +44 -46
  2. package/lib/generates/internal/E2eFileProgrammer.js.map +1 -1
  3. package/lib/generates/internal/SdkDtoGenerator.js +2 -1
  4. package/lib/generates/internal/SdkDtoGenerator.js.map +1 -1
  5. package/lib/generates/internal/SdkFileProgrammer.js +16 -10
  6. package/lib/generates/internal/SdkFileProgrammer.js.map +1 -1
  7. package/lib/generates/internal/SdkFunctionProgrammer.d.ts +6 -1
  8. package/lib/generates/internal/SdkFunctionProgrammer.js +73 -323
  9. package/lib/generates/internal/SdkFunctionProgrammer.js.map +1 -1
  10. package/lib/generates/internal/SdkNamespaceProgrammer.d.ts +11 -0
  11. package/lib/generates/internal/SdkNamespaceProgrammer.js +175 -0
  12. package/lib/generates/internal/SdkNamespaceProgrammer.js.map +1 -0
  13. package/lib/generates/internal/SdkRouteProgrammer.d.ts +7 -0
  14. package/lib/generates/internal/SdkRouteProgrammer.js +55 -0
  15. package/lib/generates/internal/SdkRouteProgrammer.js.map +1 -0
  16. package/lib/generates/internal/SdkSimulationProgrammer.d.ts +7 -1
  17. package/lib/generates/internal/SdkSimulationProgrammer.js +98 -88
  18. package/lib/generates/internal/SdkSimulationProgrammer.js.map +1 -1
  19. package/lib/utils/FormatUtil.d.ts +6 -0
  20. package/lib/utils/FormatUtil.js +36 -0
  21. package/lib/utils/FormatUtil.js.map +1 -0
  22. package/lib/utils/ImportDictionary.d.ts +2 -0
  23. package/lib/utils/ImportDictionary.js +45 -0
  24. package/lib/utils/ImportDictionary.js.map +1 -1
  25. package/package.json +6 -3
  26. package/src/analyses/ConfigAnalyzer.ts +147 -147
  27. package/src/analyses/ControllerAnalyzer.ts +390 -390
  28. package/src/analyses/PathAnalyzer.ts +110 -110
  29. package/src/analyses/ReflectAnalyzer.ts +464 -464
  30. package/src/generates/SwaggerGenerator.ts +376 -376
  31. package/src/generates/internal/E2eFileProgrammer.ts +148 -73
  32. package/src/generates/internal/SdkDtoGenerator.ts +6 -1
  33. package/src/generates/internal/SdkFileProgrammer.ts +40 -13
  34. package/src/generates/internal/SdkFunctionProgrammer.ts +176 -475
  35. package/src/generates/internal/SdkNamespaceProgrammer.ts +495 -0
  36. package/src/generates/internal/SdkRouteProgrammer.ts +82 -0
  37. package/src/generates/internal/SdkSimulationProgrammer.ts +359 -133
  38. package/src/generates/internal/SwaggerSchemaGenerator.ts +444 -444
  39. package/src/utils/FormatUtil.ts +30 -0
  40. package/src/utils/ImportDictionary.ts +72 -0
@@ -1,376 +1,376 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import { Singleton } from "tstl/thread/Singleton";
4
- import ts from "typescript";
5
- import typia, { IJsonApplication, IJsonComponents } from "typia";
6
- import { MetadataCollection } from "typia/lib/factories/MetadataCollection";
7
- import { JsonApplicationProgrammer } from "typia/lib/programmers/json/JsonApplicationProgrammer";
8
-
9
- import { INestiaConfig } from "../INestiaConfig";
10
- import { IRoute } from "../structures/IRoute";
11
- import { ISwagger } from "../structures/ISwagger";
12
- import { ISwaggerError } from "../structures/ISwaggerError";
13
- import { ISwaggerInfo } from "../structures/ISwaggerInfo";
14
- import { ISwaggerLazyProperty } from "../structures/ISwaggerLazyProperty";
15
- import { ISwaggerLazySchema } from "../structures/ISwaggerLazySchema";
16
- import { ISwaggerRoute } from "../structures/ISwaggerRoute";
17
- import { ISwaggerSecurityScheme } from "../structures/ISwaggerSecurityScheme";
18
- import { FileRetriever } from "../utils/FileRetriever";
19
- import { MapUtil } from "../utils/MapUtil";
20
- import { SwaggerSchemaGenerator } from "./internal/SwaggerSchemaGenerator";
21
-
22
- export namespace SwaggerGenerator {
23
- export interface IProps {
24
- config: INestiaConfig.ISwaggerConfig;
25
- checker: ts.TypeChecker;
26
- collection: MetadataCollection;
27
- lazySchemas: Array<ISwaggerLazySchema>;
28
- lazyProperties: Array<ISwaggerLazyProperty>;
29
- errors: ISwaggerError[];
30
- }
31
-
32
- export const generate =
33
- (checker: ts.TypeChecker) =>
34
- (config: INestiaConfig.ISwaggerConfig) =>
35
- async (routeList: IRoute[]): Promise<void> => {
36
- console.log("Generating Swagger Documents");
37
-
38
- // VALIDATE SECURITY
39
- validate_security(config)(routeList);
40
-
41
- // PREPARE ASSETS
42
- const parsed: path.ParsedPath = path.parse(config.output);
43
- const directory: string = path.dirname(parsed.dir);
44
- if (fs.existsSync(directory) === false)
45
- try {
46
- await fs.promises.mkdir(directory);
47
- } catch {}
48
- if (fs.existsSync(directory) === false)
49
- throw new Error(
50
- `Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
51
- );
52
-
53
- const location: string = !!parsed.ext
54
- ? path.resolve(config.output)
55
- : path.join(path.resolve(config.output), "swagger.json");
56
-
57
- const collection: MetadataCollection = new MetadataCollection({
58
- replace: MetadataCollection.replace,
59
- });
60
-
61
- // CONSTRUCT SWAGGER DOCUMENTS
62
- const errors: ISwaggerError[] = [];
63
- const lazySchemas: Array<ISwaggerLazySchema> = [];
64
- const lazyProperties: Array<ISwaggerLazyProperty> = [];
65
- const swagger: ISwagger = await initialize(config);
66
- const pathDict: Map<string, Record<string, ISwaggerRoute>> = new Map();
67
-
68
- for (const route of routeList) {
69
- if (route.jsDocTags.find((tag) => tag.name === "internal")) continue;
70
-
71
- const path: Record<string, ISwaggerRoute> = MapUtil.take(
72
- pathDict,
73
- get_path(route.path, route.parameters),
74
- () => ({}),
75
- );
76
- path[route.method.toLowerCase()] = generate_route({
77
- config,
78
- checker,
79
- collection,
80
- lazySchemas,
81
- lazyProperties,
82
- errors,
83
- })(route);
84
- }
85
- swagger.paths = {};
86
- for (const [path, routes] of pathDict) swagger.paths[path] = routes;
87
-
88
- // FILL JSON-SCHEMAS
89
- const application: IJsonApplication = JsonApplicationProgrammer.write({
90
- purpose: "swagger",
91
- })(lazySchemas.map(({ metadata }) => metadata));
92
- swagger.components = {
93
- ...(swagger.components ?? {}),
94
- ...(application.components ?? {}),
95
- };
96
- lazySchemas.forEach(({ schema }, index) => {
97
- Object.assign(schema, application.schemas[index]!);
98
- });
99
- for (const p of lazyProperties)
100
- Object.assign(
101
- p.schema,
102
- (
103
- application.components.schemas?.[
104
- p.object
105
- ] as IJsonComponents.IObject
106
- )?.properties[p.property],
107
- );
108
-
109
- // CONFIGURE SECURITY
110
- if (config.security) fill_security(config.security, swagger);
111
-
112
- // REPORT ERRORS
113
- if (errors.length) {
114
- for (const e of errors)
115
- console.error(
116
- `${path.relative(e.route.location, process.cwd())}:${
117
- e.route.symbol.class
118
- }.${e.route.symbol.function}:${
119
- e.from
120
- } - error TS(@nestia/sdk): invalid type detected.\n\n` +
121
- e.messages.map((m) => ` - ${m}`).join("\n"),
122
- "\n\n",
123
- );
124
- throw new TypeError("Invalid type detected");
125
- }
126
-
127
- // DO GENERATE
128
- await fs.promises.writeFile(
129
- location,
130
- !config.beautify
131
- ? JSON.stringify(swagger)
132
- : JSON.stringify(
133
- swagger,
134
- null,
135
- typeof config.beautify === "number" ? config.beautify : 2,
136
- ),
137
- "utf8",
138
- );
139
- };
140
-
141
- const validate_security =
142
- (config: INestiaConfig.ISwaggerConfig) =>
143
- (routeList: IRoute[]): void | never => {
144
- const securityMap: Map<
145
- string,
146
- { scheme: ISwaggerSecurityScheme; scopes: Set<string> }
147
- > = new Map();
148
- for (const [key, value] of Object.entries(config.security ?? {}))
149
- securityMap.set(key, {
150
- scheme: emend_security(value),
151
- scopes:
152
- value.type === "oauth2"
153
- ? new Set([
154
- ...Object.keys(value.flows.authorizationCode?.scopes ?? {}),
155
- ...Object.keys(value.flows.implicit?.scopes ?? {}),
156
- ...Object.keys(value.flows.password?.scopes ?? {}),
157
- ...Object.keys(value.flows.clientCredentials?.scopes ?? {}),
158
- ])
159
- : new Set(),
160
- });
161
-
162
- const validate =
163
- (reporter: (str: string) => void) =>
164
- (key: string, scopes: string[]) => {
165
- const security = securityMap.get(key);
166
- if (security === undefined)
167
- return reporter(`target security scheme "${key}" does not exists.`);
168
- else if (scopes.length === 0) return;
169
- else if (security.scheme.type !== "oauth2")
170
- return reporter(
171
- `target security scheme "${key}" is not "oauth2" type, but you've configured the scopes.`,
172
- );
173
- for (const s of scopes)
174
- if (security.scopes.has(s) === false)
175
- reporter(
176
- `target security scheme "${key}" does not have a specific scope "${s}".`,
177
- );
178
- };
179
-
180
- const violations: string[] = [];
181
- for (const route of routeList)
182
- for (const record of route.security)
183
- for (const [key, scopes] of Object.entries(record))
184
- validate((str) =>
185
- violations.push(
186
- ` - ${str} (${route.symbol} at "${route.location}")`,
187
- ),
188
- )(key, scopes);
189
-
190
- if (violations.length)
191
- throw new Error(
192
- `Error on NestiaApplication.swagger(): invalid security specification. Check your "nestia.config.ts" file's "swagger.security" property, or each controller methods.\n` +
193
- `\n` +
194
- `List of violations:\n` +
195
- violations.join("\n"),
196
- );
197
- };
198
-
199
- /* ---------------------------------------------------------
200
- INITIALIZERS
201
- --------------------------------------------------------- */
202
- const initialize = async (
203
- config: INestiaConfig.ISwaggerConfig,
204
- ): Promise<ISwagger> => {
205
- const pack = new Singleton(
206
- async (): Promise<Partial<ISwaggerInfo> | null> => {
207
- const location: string | null = await FileRetriever.file(
208
- "package.json",
209
- )(process.cwd());
210
- if (location === null) return null;
211
-
212
- try {
213
- const content: string = await fs.promises.readFile(location, "utf8");
214
- const data = typia.json.assertParse<{
215
- name?: string;
216
- version?: string;
217
- description?: string;
218
- license?:
219
- | string
220
- | {
221
- type: string;
222
- /**
223
- * @format uri
224
- */
225
- url: string;
226
- };
227
- }>(content);
228
- return {
229
- title: data.name,
230
- version: data.version,
231
- description: data.description,
232
- license: data.license
233
- ? typeof data.license === "string"
234
- ? { name: data.license }
235
- : typeof data.license === "object"
236
- ? {
237
- name: data.license.type,
238
- url: data.license.url,
239
- }
240
- : undefined
241
- : undefined,
242
- };
243
- } catch {
244
- return null;
245
- }
246
- },
247
- );
248
-
249
- return {
250
- openapi: "3.0.1",
251
- servers: config.servers ?? [
252
- {
253
- url: "https://github.com/samchon/nestia",
254
- description: "insert your server url",
255
- },
256
- ],
257
- info: {
258
- ...(config.info ?? {}),
259
- version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
260
- title:
261
- config.info?.title ??
262
- (await pack.get())?.title ??
263
- "Swagger Documents",
264
- description:
265
- config.info?.description ??
266
- (await pack.get())?.description ??
267
- "Generated by nestia - https://github.com/samchon/nestia",
268
- license: config.info?.license ?? (await pack.get())?.license,
269
- },
270
- paths: {},
271
- components: {},
272
- };
273
- };
274
-
275
- function get_path(path: string, parameters: IRoute.IParameter[]): string {
276
- const filtered: IRoute.IParameter[] = parameters.filter(
277
- (param) => param.category === "param" && !!param.field,
278
- );
279
- for (const param of filtered)
280
- path = path.replace(`:${param.field}`, `{${param.field}}`);
281
- return path;
282
- }
283
-
284
- const generate_route =
285
- (props: IProps) =>
286
- (route: IRoute): ISwaggerRoute => {
287
- const body = route.parameters.find((param) => param.category === "body");
288
- const getJsDocTexts = (name: string) =>
289
- route.jsDocTags
290
- .filter(
291
- (tag) =>
292
- tag.name === name &&
293
- tag.text &&
294
- tag.text.find(
295
- (elem) => elem.kind === "text" && elem.text.length,
296
- ) !== undefined,
297
- )
298
- .map((tag) => tag.text!.find((elem) => elem.kind === "text")!.text);
299
-
300
- const description: string | undefined = route.description?.length
301
- ? route.description
302
- : undefined;
303
- const summary: string | undefined = (() => {
304
- if (description === undefined) return undefined;
305
-
306
- const [explicit] = getJsDocTexts("summary");
307
- if (explicit?.length) return explicit;
308
-
309
- const index: number = description.indexOf(".");
310
- if (index <= 0) return undefined;
311
-
312
- const content: string = description.substring(0, index).trim();
313
- return content.length ? content : undefined;
314
- })();
315
- const deprecated = route.jsDocTags.find(
316
- (tag) => tag.name === "deprecated",
317
- );
318
-
319
- return {
320
- deprecated: deprecated ? true : undefined,
321
- tags: [...route.swaggerTags, ...new Set([...getJsDocTexts("tag")])],
322
- operationId:
323
- route.operationId ??
324
- props.config.operationId?.({
325
- class: route.symbol.class,
326
- function: route.symbol.function,
327
- method: route.method as "GET",
328
- path: route.path,
329
- }),
330
- parameters: route.parameters
331
- .filter((param) => param.category !== "body")
332
- .map((param) => SwaggerSchemaGenerator.parameter(props)(route)(param))
333
- .flat(),
334
- requestBody: body
335
- ? SwaggerSchemaGenerator.body(props)(route)(body)
336
- : undefined,
337
- responses: SwaggerSchemaGenerator.response(props)(route),
338
- summary,
339
- description,
340
- security: route.security.length ? route.security : undefined,
341
- ...(props.config.additional === true
342
- ? {
343
- "x-nestia-namespace": [
344
- ...route.path
345
- .split("/")
346
- .filter((str) => str.length && str[0] !== ":"),
347
- route.name,
348
- ].join("."),
349
- "x-nestia-jsDocTags": route.jsDocTags,
350
- "x-nestia-method": route.method,
351
- }
352
- : {}),
353
- };
354
- };
355
-
356
- function fill_security(
357
- security: Required<INestiaConfig.ISwaggerConfig>["security"],
358
- swagger: ISwagger,
359
- ): void {
360
- swagger.components.securitySchemes = {};
361
- for (const [key, value] of Object.entries(security))
362
- swagger.components.securitySchemes[key] = emend_security(value);
363
- }
364
-
365
- function emend_security(
366
- input: ISwaggerSecurityScheme,
367
- ): ISwaggerSecurityScheme {
368
- if (input.type === "apiKey")
369
- return {
370
- ...input,
371
- in: input.in ?? "header",
372
- name: input.name ?? "Authorization",
373
- };
374
- return input;
375
- }
376
- }
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { Singleton } from "tstl/thread/Singleton";
4
+ import ts from "typescript";
5
+ import typia, { IJsonApplication, IJsonComponents } from "typia";
6
+ import { MetadataCollection } from "typia/lib/factories/MetadataCollection";
7
+ import { JsonApplicationProgrammer } from "typia/lib/programmers/json/JsonApplicationProgrammer";
8
+
9
+ import { INestiaConfig } from "../INestiaConfig";
10
+ import { IRoute } from "../structures/IRoute";
11
+ import { ISwagger } from "../structures/ISwagger";
12
+ import { ISwaggerError } from "../structures/ISwaggerError";
13
+ import { ISwaggerInfo } from "../structures/ISwaggerInfo";
14
+ import { ISwaggerLazyProperty } from "../structures/ISwaggerLazyProperty";
15
+ import { ISwaggerLazySchema } from "../structures/ISwaggerLazySchema";
16
+ import { ISwaggerRoute } from "../structures/ISwaggerRoute";
17
+ import { ISwaggerSecurityScheme } from "../structures/ISwaggerSecurityScheme";
18
+ import { FileRetriever } from "../utils/FileRetriever";
19
+ import { MapUtil } from "../utils/MapUtil";
20
+ import { SwaggerSchemaGenerator } from "./internal/SwaggerSchemaGenerator";
21
+
22
+ export namespace SwaggerGenerator {
23
+ export interface IProps {
24
+ config: INestiaConfig.ISwaggerConfig;
25
+ checker: ts.TypeChecker;
26
+ collection: MetadataCollection;
27
+ lazySchemas: Array<ISwaggerLazySchema>;
28
+ lazyProperties: Array<ISwaggerLazyProperty>;
29
+ errors: ISwaggerError[];
30
+ }
31
+
32
+ export const generate =
33
+ (checker: ts.TypeChecker) =>
34
+ (config: INestiaConfig.ISwaggerConfig) =>
35
+ async (routeList: IRoute[]): Promise<void> => {
36
+ console.log("Generating Swagger Documents");
37
+
38
+ // VALIDATE SECURITY
39
+ validate_security(config)(routeList);
40
+
41
+ // PREPARE ASSETS
42
+ const parsed: path.ParsedPath = path.parse(config.output);
43
+ const directory: string = path.dirname(parsed.dir);
44
+ if (fs.existsSync(directory) === false)
45
+ try {
46
+ await fs.promises.mkdir(directory);
47
+ } catch {}
48
+ if (fs.existsSync(directory) === false)
49
+ throw new Error(
50
+ `Error on NestiaApplication.swagger(): failed to create output directory: ${directory}`,
51
+ );
52
+
53
+ const location: string = !!parsed.ext
54
+ ? path.resolve(config.output)
55
+ : path.join(path.resolve(config.output), "swagger.json");
56
+
57
+ const collection: MetadataCollection = new MetadataCollection({
58
+ replace: MetadataCollection.replace,
59
+ });
60
+
61
+ // CONSTRUCT SWAGGER DOCUMENTS
62
+ const errors: ISwaggerError[] = [];
63
+ const lazySchemas: Array<ISwaggerLazySchema> = [];
64
+ const lazyProperties: Array<ISwaggerLazyProperty> = [];
65
+ const swagger: ISwagger = await initialize(config);
66
+ const pathDict: Map<string, Record<string, ISwaggerRoute>> = new Map();
67
+
68
+ for (const route of routeList) {
69
+ if (route.jsDocTags.find((tag) => tag.name === "internal")) continue;
70
+
71
+ const path: Record<string, ISwaggerRoute> = MapUtil.take(
72
+ pathDict,
73
+ get_path(route.path, route.parameters),
74
+ () => ({}),
75
+ );
76
+ path[route.method.toLowerCase()] = generate_route({
77
+ config,
78
+ checker,
79
+ collection,
80
+ lazySchemas,
81
+ lazyProperties,
82
+ errors,
83
+ })(route);
84
+ }
85
+ swagger.paths = {};
86
+ for (const [path, routes] of pathDict) swagger.paths[path] = routes;
87
+
88
+ // FILL JSON-SCHEMAS
89
+ const application: IJsonApplication = JsonApplicationProgrammer.write({
90
+ purpose: "swagger",
91
+ })(lazySchemas.map(({ metadata }) => metadata));
92
+ swagger.components = {
93
+ ...(swagger.components ?? {}),
94
+ ...(application.components ?? {}),
95
+ };
96
+ lazySchemas.forEach(({ schema }, index) => {
97
+ Object.assign(schema, application.schemas[index]!);
98
+ });
99
+ for (const p of lazyProperties)
100
+ Object.assign(
101
+ p.schema,
102
+ (
103
+ application.components.schemas?.[
104
+ p.object
105
+ ] as IJsonComponents.IObject
106
+ )?.properties[p.property],
107
+ );
108
+
109
+ // CONFIGURE SECURITY
110
+ if (config.security) fill_security(config.security, swagger);
111
+
112
+ // REPORT ERRORS
113
+ if (errors.length) {
114
+ for (const e of errors)
115
+ console.error(
116
+ `${path.relative(e.route.location, process.cwd())}:${
117
+ e.route.symbol.class
118
+ }.${e.route.symbol.function}:${
119
+ e.from
120
+ } - error TS(@nestia/sdk): invalid type detected.\n\n` +
121
+ e.messages.map((m) => ` - ${m}`).join("\n"),
122
+ "\n\n",
123
+ );
124
+ throw new TypeError("Invalid type detected");
125
+ }
126
+
127
+ // DO GENERATE
128
+ await fs.promises.writeFile(
129
+ location,
130
+ !config.beautify
131
+ ? JSON.stringify(swagger)
132
+ : JSON.stringify(
133
+ swagger,
134
+ null,
135
+ typeof config.beautify === "number" ? config.beautify : 2,
136
+ ),
137
+ "utf8",
138
+ );
139
+ };
140
+
141
+ const validate_security =
142
+ (config: INestiaConfig.ISwaggerConfig) =>
143
+ (routeList: IRoute[]): void | never => {
144
+ const securityMap: Map<
145
+ string,
146
+ { scheme: ISwaggerSecurityScheme; scopes: Set<string> }
147
+ > = new Map();
148
+ for (const [key, value] of Object.entries(config.security ?? {}))
149
+ securityMap.set(key, {
150
+ scheme: emend_security(value),
151
+ scopes:
152
+ value.type === "oauth2"
153
+ ? new Set([
154
+ ...Object.keys(value.flows.authorizationCode?.scopes ?? {}),
155
+ ...Object.keys(value.flows.implicit?.scopes ?? {}),
156
+ ...Object.keys(value.flows.password?.scopes ?? {}),
157
+ ...Object.keys(value.flows.clientCredentials?.scopes ?? {}),
158
+ ])
159
+ : new Set(),
160
+ });
161
+
162
+ const validate =
163
+ (reporter: (str: string) => void) =>
164
+ (key: string, scopes: string[]) => {
165
+ const security = securityMap.get(key);
166
+ if (security === undefined)
167
+ return reporter(`target security scheme "${key}" does not exists.`);
168
+ else if (scopes.length === 0) return;
169
+ else if (security.scheme.type !== "oauth2")
170
+ return reporter(
171
+ `target security scheme "${key}" is not "oauth2" type, but you've configured the scopes.`,
172
+ );
173
+ for (const s of scopes)
174
+ if (security.scopes.has(s) === false)
175
+ reporter(
176
+ `target security scheme "${key}" does not have a specific scope "${s}".`,
177
+ );
178
+ };
179
+
180
+ const violations: string[] = [];
181
+ for (const route of routeList)
182
+ for (const record of route.security)
183
+ for (const [key, scopes] of Object.entries(record))
184
+ validate((str) =>
185
+ violations.push(
186
+ ` - ${str} (${route.symbol} at "${route.location}")`,
187
+ ),
188
+ )(key, scopes);
189
+
190
+ if (violations.length)
191
+ throw new Error(
192
+ `Error on NestiaApplication.swagger(): invalid security specification. Check your "nestia.config.ts" file's "swagger.security" property, or each controller methods.\n` +
193
+ `\n` +
194
+ `List of violations:\n` +
195
+ violations.join("\n"),
196
+ );
197
+ };
198
+
199
+ /* ---------------------------------------------------------
200
+ INITIALIZERS
201
+ --------------------------------------------------------- */
202
+ const initialize = async (
203
+ config: INestiaConfig.ISwaggerConfig,
204
+ ): Promise<ISwagger> => {
205
+ const pack = new Singleton(
206
+ async (): Promise<Partial<ISwaggerInfo> | null> => {
207
+ const location: string | null = await FileRetriever.file(
208
+ "package.json",
209
+ )(process.cwd());
210
+ if (location === null) return null;
211
+
212
+ try {
213
+ const content: string = await fs.promises.readFile(location, "utf8");
214
+ const data = typia.json.assertParse<{
215
+ name?: string;
216
+ version?: string;
217
+ description?: string;
218
+ license?:
219
+ | string
220
+ | {
221
+ type: string;
222
+ /**
223
+ * @format uri
224
+ */
225
+ url: string;
226
+ };
227
+ }>(content);
228
+ return {
229
+ title: data.name,
230
+ version: data.version,
231
+ description: data.description,
232
+ license: data.license
233
+ ? typeof data.license === "string"
234
+ ? { name: data.license }
235
+ : typeof data.license === "object"
236
+ ? {
237
+ name: data.license.type,
238
+ url: data.license.url,
239
+ }
240
+ : undefined
241
+ : undefined,
242
+ };
243
+ } catch {
244
+ return null;
245
+ }
246
+ },
247
+ );
248
+
249
+ return {
250
+ openapi: "3.0.1",
251
+ servers: config.servers ?? [
252
+ {
253
+ url: "https://github.com/samchon/nestia",
254
+ description: "insert your server url",
255
+ },
256
+ ],
257
+ info: {
258
+ ...(config.info ?? {}),
259
+ version: config.info?.version ?? (await pack.get())?.version ?? "0.1.0",
260
+ title:
261
+ config.info?.title ??
262
+ (await pack.get())?.title ??
263
+ "Swagger Documents",
264
+ description:
265
+ config.info?.description ??
266
+ (await pack.get())?.description ??
267
+ "Generated by nestia - https://github.com/samchon/nestia",
268
+ license: config.info?.license ?? (await pack.get())?.license,
269
+ },
270
+ paths: {},
271
+ components: {},
272
+ };
273
+ };
274
+
275
+ function get_path(path: string, parameters: IRoute.IParameter[]): string {
276
+ const filtered: IRoute.IParameter[] = parameters.filter(
277
+ (param) => param.category === "param" && !!param.field,
278
+ );
279
+ for (const param of filtered)
280
+ path = path.replace(`:${param.field}`, `{${param.field}}`);
281
+ return path;
282
+ }
283
+
284
+ const generate_route =
285
+ (props: IProps) =>
286
+ (route: IRoute): ISwaggerRoute => {
287
+ const body = route.parameters.find((param) => param.category === "body");
288
+ const getJsDocTexts = (name: string) =>
289
+ route.jsDocTags
290
+ .filter(
291
+ (tag) =>
292
+ tag.name === name &&
293
+ tag.text &&
294
+ tag.text.find(
295
+ (elem) => elem.kind === "text" && elem.text.length,
296
+ ) !== undefined,
297
+ )
298
+ .map((tag) => tag.text!.find((elem) => elem.kind === "text")!.text);
299
+
300
+ const description: string | undefined = route.description?.length
301
+ ? route.description
302
+ : undefined;
303
+ const summary: string | undefined = (() => {
304
+ if (description === undefined) return undefined;
305
+
306
+ const [explicit] = getJsDocTexts("summary");
307
+ if (explicit?.length) return explicit;
308
+
309
+ const index: number = description.indexOf(".");
310
+ if (index <= 0) return undefined;
311
+
312
+ const content: string = description.substring(0, index).trim();
313
+ return content.length ? content : undefined;
314
+ })();
315
+ const deprecated = route.jsDocTags.find(
316
+ (tag) => tag.name === "deprecated",
317
+ );
318
+
319
+ return {
320
+ deprecated: deprecated ? true : undefined,
321
+ tags: [...route.swaggerTags, ...new Set([...getJsDocTexts("tag")])],
322
+ operationId:
323
+ route.operationId ??
324
+ props.config.operationId?.({
325
+ class: route.symbol.class,
326
+ function: route.symbol.function,
327
+ method: route.method as "GET",
328
+ path: route.path,
329
+ }),
330
+ parameters: route.parameters
331
+ .filter((param) => param.category !== "body")
332
+ .map((param) => SwaggerSchemaGenerator.parameter(props)(route)(param))
333
+ .flat(),
334
+ requestBody: body
335
+ ? SwaggerSchemaGenerator.body(props)(route)(body)
336
+ : undefined,
337
+ responses: SwaggerSchemaGenerator.response(props)(route),
338
+ summary,
339
+ description,
340
+ security: route.security.length ? route.security : undefined,
341
+ ...(props.config.additional === true
342
+ ? {
343
+ "x-nestia-namespace": [
344
+ ...route.path
345
+ .split("/")
346
+ .filter((str) => str.length && str[0] !== ":"),
347
+ route.name,
348
+ ].join("."),
349
+ "x-nestia-jsDocTags": route.jsDocTags,
350
+ "x-nestia-method": route.method,
351
+ }
352
+ : {}),
353
+ };
354
+ };
355
+
356
+ function fill_security(
357
+ security: Required<INestiaConfig.ISwaggerConfig>["security"],
358
+ swagger: ISwagger,
359
+ ): void {
360
+ swagger.components.securitySchemes = {};
361
+ for (const [key, value] of Object.entries(security))
362
+ swagger.components.securitySchemes[key] = emend_security(value);
363
+ }
364
+
365
+ function emend_security(
366
+ input: ISwaggerSecurityScheme,
367
+ ): ISwaggerSecurityScheme {
368
+ if (input.type === "apiKey")
369
+ return {
370
+ ...input,
371
+ in: input.in ?? "header",
372
+ name: input.name ?? "Authorization",
373
+ };
374
+ return input;
375
+ }
376
+ }