|
| 1 | +/* eslint-disable camelcase */ |
| 2 | +import { ParseResultElement } from '@swagger-api/apidom-core'; |
| 3 | +import { ParserError, Parser } from '@swagger-api/apidom-reference/configuration/empty'; |
| 4 | +import { |
| 5 | + mediaTypes, |
| 6 | + OpenApi3_1Element, |
| 7 | + OpenAPIMediaTypes, |
| 8 | +} from '@swagger-api/apidom-ns-openapi-3-1'; |
| 9 | + |
| 10 | +// eslint-disable-next-line camelcase |
| 11 | +const OpenApiJson3_1Parser = Parser.compose(Parser, { |
| 12 | + props: { |
| 13 | + name: 'openapi-json-3-1-swagger-client', |
| 14 | + fileExtensions: ['.json'], |
| 15 | + mediaTypes: new OpenAPIMediaTypes( |
| 16 | + ...mediaTypes.filterByFormat('generic'), |
| 17 | + ...mediaTypes.filterByFormat('json') |
| 18 | + ), |
| 19 | + detectionRegExp: /"openapi"\s*:\s*"(?<version_json>3\.1\.(?:[1-9]\d*|0))"/, |
| 20 | + }, |
| 21 | + methods: { |
| 22 | + async canParse(file) { |
| 23 | + const hasSupportedFileExtension = |
| 24 | + this.fileExtensions.length === 0 ? true : this.fileExtensions.includes(file.extension); |
| 25 | + const hasSupportedMediaType = this.mediaTypes.includes(file.mediaType); |
| 26 | + |
| 27 | + if (!hasSupportedFileExtension) return false; |
| 28 | + if (hasSupportedMediaType) return true; |
| 29 | + if (!hasSupportedMediaType) { |
| 30 | + try { |
| 31 | + const source = file.toString(); |
| 32 | + JSON.parse(source); |
| 33 | + return this.detectionRegExp.test(source); |
| 34 | + } catch (error) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + return false; |
| 39 | + }, |
| 40 | + async parse(file) { |
| 41 | + if (this.sourceMap) { |
| 42 | + // eslint-disable-next-line no-console |
| 43 | + console.warn( |
| 44 | + "openapi-json-3-1-swagger-client parser plugin doesn't support sourceMaps option" |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + const source = file.toString(); |
| 49 | + |
| 50 | + try { |
| 51 | + const pojo = JSON.parse(source); |
| 52 | + const element = OpenApi3_1Element.refract(pojo, this.refractorOpts); |
| 53 | + const parseResultElement = new ParseResultElement(); |
| 54 | + |
| 55 | + element.classes.push('result'); |
| 56 | + parseResultElement.push(element); |
| 57 | + return parseResultElement; |
| 58 | + } catch (error) { |
| 59 | + throw new ParserError(`Error parsing "${file.uri}"`, error); |
| 60 | + } |
| 61 | + }, |
| 62 | + }, |
| 63 | +}); |
| 64 | + |
| 65 | +export default OpenApiJson3_1Parser; |
| 66 | +/* eslint-enable camelcase */ |
0 commit comments