@devlearning/swagger-generator 1.1.9 → 1.1.10

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.
@@ -1,12 +1,46 @@
1
1
  import fetch, { RequestInit } from 'node-fetch';
2
2
  import { Swagger } from "./models/swagger/swagger.js";
3
+ import { logger } from './utils/logger.js';
4
+ import { SwaggerValidator } from './utils/swagger-validator.js';
3
5
 
4
6
  const settings: RequestInit = { method: "Get" };
5
7
 
6
8
  export class SwaggerDownloader {
7
- async download(swaggerJsonUrl: URL) {
8
- let response = await fetch(swaggerJsonUrl, settings);
9
- let json = await response.json();
10
- return <Swagger>json;
9
+ async download(swaggerJsonUrl: URL): Promise<Swagger> {
10
+ try {
11
+ logger.progress(`Downloading Swagger from: ${swaggerJsonUrl}`);
12
+
13
+ const response = await fetch(swaggerJsonUrl, settings);
14
+
15
+ if (!response.ok) {
16
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
17
+ }
18
+
19
+ const json = await response.json();
20
+
21
+ // Validate the downloaded swagger document
22
+ if (!SwaggerValidator.isValidSwaggerDocument(json)) {
23
+ throw new Error('Downloaded document is not a valid Swagger/OpenAPI specification');
24
+ }
25
+
26
+ // Normalize openapi field to openApi (camelCase) if needed
27
+ const jsonAny = json as any;
28
+ if (jsonAny.openapi && !jsonAny.openApi) {
29
+ jsonAny.openApi = jsonAny.openapi;
30
+ }
31
+ if (jsonAny.swagger && !jsonAny.openApi) {
32
+ jsonAny.openApi = jsonAny.swagger;
33
+ }
34
+
35
+ const swagger = jsonAny as Swagger;
36
+ SwaggerValidator.validate(swagger);
37
+
38
+ logger.success(`Swagger document downloaded successfully`);
39
+ return swagger;
40
+
41
+ } catch (error) {
42
+ logger.error(`Failed to download Swagger from ${swaggerJsonUrl}`, error);
43
+ throw error;
44
+ }
11
45
  }
12
46
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Centralized logging utility for the Swagger Generator
3
+ * Provides consistent logging with levels and formatting
4
+ */
5
+
6
+ export enum LogLevel {
7
+ DEBUG = 0,
8
+ INFO = 1,
9
+ WARN = 2,
10
+ ERROR = 3,
11
+ SILENT = 4,
12
+ }
13
+
14
+ export class Logger {
15
+ private static instance: Logger;
16
+ private logLevel: LogLevel = LogLevel.INFO;
17
+
18
+ private constructor() {}
19
+
20
+ static getInstance(): Logger {
21
+ if (!Logger.instance) {
22
+ Logger.instance = new Logger();
23
+ }
24
+ return Logger.instance;
25
+ }
26
+
27
+ setLogLevel(level: LogLevel) {
28
+ this.logLevel = level;
29
+ }
30
+
31
+ debug(message: string, ...args: any[]) {
32
+ if (this.logLevel <= LogLevel.DEBUG) {
33
+ console.debug(`[DEBUG] ${message}`, ...args);
34
+ }
35
+ }
36
+
37
+ info(message: string, ...args: any[]) {
38
+ if (this.logLevel <= LogLevel.INFO) {
39
+ console.info(`[INFO] ${message}`, ...args);
40
+ }
41
+ }
42
+
43
+ warn(message: string, ...args: any[]) {
44
+ if (this.logLevel <= LogLevel.WARN) {
45
+ console.warn(`[WARN] ${message}`, ...args);
46
+ }
47
+ }
48
+
49
+ error(message: string, error?: any) {
50
+ if (this.logLevel <= LogLevel.ERROR) {
51
+ if (error) {
52
+ console.error(`[ERROR] ${message}`, error);
53
+ } else {
54
+ console.error(`[ERROR] ${message}`);
55
+ }
56
+ }
57
+ }
58
+
59
+ success(message: string) {
60
+ if (this.logLevel <= LogLevel.INFO) {
61
+ console.info(`✓ ${message}`);
62
+ }
63
+ }
64
+
65
+ progress(message: string) {
66
+ if (this.logLevel <= LogLevel.INFO) {
67
+ console.info(`→ ${message}`);
68
+ }
69
+ }
70
+ }
71
+
72
+ // Export singleton instance
73
+ export const logger = Logger.getInstance();
@@ -0,0 +1,89 @@
1
+ import { Swagger } from '../models/swagger/swagger.js';
2
+ import { logger } from './logger.js';
3
+
4
+ /**
5
+ * Validates Swagger/OpenAPI specification
6
+ * Ensures the document has required fields before processing
7
+ */
8
+ export class SwaggerValidator {
9
+
10
+ /**
11
+ * Validates a Swagger document structure
12
+ * @param swagger - The Swagger document to validate
13
+ * @throws Error if validation fails
14
+ */
15
+ static validate(swagger: any): void {
16
+ const errors: string[] = [];
17
+
18
+ // Check required top-level fields (support both openapi and openApi)
19
+ const version = swagger.openapi || swagger.swagger || swagger.openApi;
20
+ if (!version) {
21
+ errors.push('Missing openapi/swagger version field');
22
+ }
23
+
24
+ if (!swagger.paths || Object.keys(swagger.paths).length === 0) {
25
+ errors.push('Missing or empty paths object');
26
+ }
27
+
28
+ if (!swagger.info) {
29
+ errors.push('Missing info object');
30
+ } else {
31
+ if (!swagger.info.title) {
32
+ errors.push('Missing info.title');
33
+ }
34
+ if (!swagger.info.version) {
35
+ errors.push('Missing info.version');
36
+ }
37
+ }
38
+
39
+ // Check components
40
+ if (!swagger.components && !swagger.definitions) {
41
+ logger.warn('No components/definitions found - model generation may be limited');
42
+ }
43
+
44
+ // Validate paths structure
45
+ if (swagger.paths) {
46
+ for (const [path, methods] of Object.entries(swagger.paths)) {
47
+ if (!methods || typeof methods !== 'object') {
48
+ errors.push(`Invalid path definition for: ${path}`);
49
+ continue;
50
+ }
51
+
52
+ const validMethods = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head'];
53
+ const pathMethods = Object.keys(methods);
54
+
55
+ if (pathMethods.length === 0) {
56
+ errors.push(`No HTTP methods defined for path: ${path}`);
57
+ }
58
+
59
+ for (const method of pathMethods) {
60
+ if (!validMethods.includes(method.toLowerCase())) {
61
+ logger.warn(`Unexpected HTTP method '${method}' in path: ${path}`);
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ // If there are errors, throw
68
+ if (errors.length > 0) {
69
+ const errorMessage = `Swagger validation failed:\n${errors.map(e => ` - ${e}`).join('\n')}`;
70
+ logger.error(errorMessage);
71
+ throw new Error(errorMessage);
72
+ }
73
+
74
+ logger.success('Swagger document validation passed');
75
+ }
76
+
77
+ /**
78
+ * Checks if the Swagger document is likely valid without throwing
79
+ * @param obj - Object to check
80
+ * @returns true if it looks like a valid Swagger document
81
+ */
82
+ static isValidSwaggerDocument(obj: any): obj is Swagger {
83
+ return obj &&
84
+ typeof obj === 'object' &&
85
+ (obj.openApi || obj.openapi || obj.swagger) &&
86
+ obj.paths &&
87
+ typeof obj.paths === 'object';
88
+ }
89
+ }