-
Notifications
You must be signed in to change notification settings - Fork 114
/
index.ts
202 lines (178 loc) · 5.61 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import fs from 'fs';
import path from 'path';
import type {
LoadContext,
Plugin,
OptionValidationContext,
} from '@docusaurus/types';
import { normalizeUrl } from '@docusaurus/utils';
import { loadAndBundleSpec } from 'redoc';
import type { OpenAPISpec } from 'redoc/typings/types';
import {
formatProblems,
getTotals,
bundle,
stringifyYaml,
Document,
NormalizedProblem,
} from '@redocly/openapi-core';
import {
PluginOptionSchema,
PluginOptions,
PluginOptionsWithDefault,
PluginDirectUsageOptions,
DEFAULT_OPTIONS,
} from './options';
import type { SpecProps, ApiDocProps } from './types/common';
import { loadSpecWithConfig } from './loadSpec';
import { loadRedoclyConfig } from './loadRedoclyConfig';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const version = require('../package.json').version;
export { PluginOptions, PluginDirectUsageOptions, loadRedoclyConfig };
export default function redocPlugin(
context: LoadContext,
opts: PluginOptions,
): Plugin<{
converted: OpenAPISpec;
bundle?: Record<string, unknown>;
}> {
const { baseUrl } = context.siteConfig;
const options: PluginOptionsWithDefault = { ...DEFAULT_OPTIONS, ...opts };
const { debug, spec, url: downloadUrl, config, themeId } = options;
let url = downloadUrl;
const isSpecFile = fs.existsSync(spec);
const fileName = path.join(
'redocusaurus',
`${options.id || 'api-spec'}.yaml`,
);
let filesToWatch: string[] = isSpecFile ? [path.resolve(spec)] : [];
if (debug) {
console.error('[REDOCUSAURUS_PLUGIN] Opts Input:', opts);
console.error('[REDOCUSAURUS_PLUGIN] Options:', options);
}
return {
name: 'docusaurus-plugin-redoc',
async loadContent() {
const redoclyConfig = await loadRedoclyConfig(config);
if (redoclyConfig.configFile) {
filesToWatch.push(redoclyConfig.configFile);
}
let bundledSpec: Document, problems: NormalizedProblem[];
if (!isSpecFile) {
// If spec is a remote url then add it as download url also as a default
url = url || spec;
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] bundling spec from url', spec);
}
({ bundle: bundledSpec, problems } = await loadSpecWithConfig(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
spec!,
redoclyConfig,
));
} else {
// If local file
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] reading file: ', spec);
}
const fileBundle = await bundle({
ref: spec,
config: redoclyConfig,
});
({ bundle: bundledSpec, problems } = fileBundle);
filesToWatch = [path.resolve(spec), ...fileBundle.fileDependencies];
}
if (problems?.length) {
console.error('[REDOCUSAURUS_PLUGIN] errors while bundling spec', spec);
formatProblems(problems, {
totals: getTotals(problems),
version,
});
}
if (debug) {
console.log('[REDOCUSAURUS_PLUGIN] File Bundled');
}
// Pass again to loader to convert swagger to openapi
const converted = await loadAndBundleSpec(bundledSpec.parsed);
// If download url is not provided then use bundled yaml as a static file (see `postBuild`)
url = url || fileName;
return {
converted,
bundle: bundledSpec.parsed,
};
},
async contentLoaded({ content, actions }) {
const { createData, addRoute, setGlobalData } = actions;
if (!content?.converted) {
throw new Error(`[Redocusaurus] Spec could not be parsed: ${spec}`);
}
const data: SpecProps = {
url,
themeId,
isSpecFile,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
spec: content.converted as any,
};
setGlobalData(data);
if (options.route) {
const routePath = options.route.startsWith('/')
? options.route.slice(1)
: options.route;
const specProps = await createData(
`redocApiSpecV1.2-${options.id || '1'}.json`,
JSON.stringify(data),
);
const layoutProps = await createData(
`redocApiLayoutV1-${options.id || '1'}.json`,
JSON.stringify(options.layout),
);
const modules: Record<keyof ApiDocProps, string> = {
specProps,
layoutProps,
};
const routeOptions = {
modules,
component: '@theme/ApiDoc',
exact: true,
path: normalizeUrl([baseUrl, routePath]),
};
if (debug) {
console.error('[REDOCUSAURUS_PLUGIN] Route:', routeOptions);
}
addRoute(routeOptions);
}
},
async postBuild({ content }) {
if (!isSpecFile || downloadUrl) {
return;
}
// Create a static file from bundled spec
const staticFile = path.join(context.outDir, fileName);
const dir = path.dirname(staticFile);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
if (debug) {
console.error(
'[REDOCUSAURUS_PLUGIN] creating static bundle copy for download',
staticFile,
);
}
// create bundled url
const bundledYaml = stringifyYaml(content.bundle || content.converted);
fs.writeFileSync(staticFile, bundledYaml);
},
getPathsToWatch() {
return filesToWatch;
},
};
}
export function validateOptions({
options,
validate,
}: OptionValidationContext<
typeof PluginOptionSchema,
PluginOptions
>): PluginOptions {
const validatedOptions = validate(PluginOptionSchema, options);
return validatedOptions;
}