2021-06-09 14:57:36 +03:00
|
|
|
import type { Source, Document } from '@redocly/openapi-core';
|
2022-05-10 14:50:50 +03:00
|
|
|
// eslint-disable-next-line import/no-internal-modules
|
|
|
|
import type { ResolvedConfig } from '@redocly/openapi-core/lib/config';
|
2021-06-09 14:57:36 +03:00
|
|
|
|
|
|
|
// eslint-disable-next-line import/no-internal-modules
|
|
|
|
import { bundle } from '@redocly/openapi-core/lib/bundle';
|
|
|
|
// eslint-disable-next-line import/no-internal-modules
|
|
|
|
import { Config } from '@redocly/openapi-core/lib/config/config';
|
|
|
|
|
2018-07-23 13:22:24 +03:00
|
|
|
/* tslint:disable-next-line:no-implicit-dependencies */
|
2017-11-15 00:40:38 +03:00
|
|
|
import { convertObj } from 'swagger2openapi';
|
|
|
|
import { OpenAPISpec } from '../types';
|
2021-04-08 15:49:15 +03:00
|
|
|
import { IS_BROWSER } from './dom';
|
2017-11-15 00:40:38 +03:00
|
|
|
|
2017-11-19 13:51:59 +03:00
|
|
|
export async function loadAndBundleSpec(specUrlOrObject: object | string): Promise<OpenAPISpec> {
|
2022-05-10 14:50:50 +03:00
|
|
|
const config = new Config({} as ResolvedConfig);
|
2021-04-08 15:49:15 +03:00
|
|
|
const bundleOpts = {
|
|
|
|
config,
|
2021-11-24 17:11:45 +03:00
|
|
|
base: IS_BROWSER ? window.location.href : process.cwd(),
|
|
|
|
};
|
2021-04-08 15:49:15 +03:00
|
|
|
|
|
|
|
if (IS_BROWSER) {
|
|
|
|
config.resolve.http.customFetch = global.fetch;
|
|
|
|
}
|
2017-11-19 13:51:59 +03:00
|
|
|
|
2021-04-08 15:49:15 +03:00
|
|
|
if (typeof specUrlOrObject === 'object' && specUrlOrObject !== null) {
|
|
|
|
bundleOpts['doc'] = {
|
|
|
|
source: { absoluteRef: '' } as Source,
|
2021-11-24 17:11:45 +03:00
|
|
|
parsed: specUrlOrObject,
|
|
|
|
} as Document;
|
2017-11-19 13:51:59 +03:00
|
|
|
} else {
|
2021-04-08 15:49:15 +03:00
|
|
|
bundleOpts['ref'] = specUrlOrObject;
|
2017-11-19 13:51:59 +03:00
|
|
|
}
|
2021-04-08 15:49:15 +03:00
|
|
|
|
2021-11-24 17:11:45 +03:00
|
|
|
const {
|
|
|
|
bundle: { parsed },
|
|
|
|
} = await bundle(bundleOpts);
|
2021-04-08 15:49:15 +03:00
|
|
|
return parsed.swagger !== undefined ? convertSwagger2OpenAPI(parsed) : parsed;
|
2017-11-19 13:51:59 +03:00
|
|
|
}
|
|
|
|
|
2017-11-15 00:40:38 +03:00
|
|
|
export function convertSwagger2OpenAPI(spec: any): Promise<OpenAPISpec> {
|
2017-11-15 17:16:28 +03:00
|
|
|
console.warn('[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0');
|
2017-11-15 00:40:38 +03:00
|
|
|
return new Promise<OpenAPISpec>((resolve, reject) =>
|
2020-07-25 19:06:22 +03:00
|
|
|
convertObj(spec, { patch: true, warnOnly: true, text: '{}', anchors: true }, (err, res) => {
|
2017-11-15 00:40:38 +03:00
|
|
|
// TODO: log any warnings
|
|
|
|
if (err) {
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
resolve(res && (res.openapi as any));
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
}
|