docusaurus-plugin-openapi-docs 0.0.0-1000

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 (163) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +361 -0
  3. package/lib/index.d.ts +9 -0
  4. package/lib/index.js +709 -0
  5. package/lib/markdown/createArrayBracket.d.ts +2 -0
  6. package/lib/markdown/createArrayBracket.js +36 -0
  7. package/lib/markdown/createAuthentication.d.ts +2 -0
  8. package/lib/markdown/createAuthentication.js +171 -0
  9. package/lib/markdown/createAuthorization.d.ts +1 -0
  10. package/lib/markdown/createAuthorization.js +15 -0
  11. package/lib/markdown/createCallbackMethodEndpoint.d.ts +1 -0
  12. package/lib/markdown/createCallbackMethodEndpoint.js +20 -0
  13. package/lib/markdown/createCallbacks.d.ts +6 -0
  14. package/lib/markdown/createCallbacks.js +77 -0
  15. package/lib/markdown/createContactInfo.d.ts +2 -0
  16. package/lib/markdown/createContactInfo.js +39 -0
  17. package/lib/markdown/createDeprecationNotice.d.ts +6 -0
  18. package/lib/markdown/createDeprecationNotice.js +20 -0
  19. package/lib/markdown/createDescription.d.ts +1 -0
  20. package/lib/markdown/createDescription.js +13 -0
  21. package/lib/markdown/createDetails.d.ts +2 -0
  22. package/lib/markdown/createDetails.js +17 -0
  23. package/lib/markdown/createDetailsSummary.d.ts +2 -0
  24. package/lib/markdown/createDetailsSummary.js +17 -0
  25. package/lib/markdown/createDownload.d.ts +1 -0
  26. package/lib/markdown/createDownload.js +16 -0
  27. package/lib/markdown/createHeading.d.ts +1 -0
  28. package/lib/markdown/createHeading.js +20 -0
  29. package/lib/markdown/createLicense.d.ts +2 -0
  30. package/lib/markdown/createLicense.js +32 -0
  31. package/lib/markdown/createLogo.d.ts +2 -0
  32. package/lib/markdown/createLogo.js +18 -0
  33. package/lib/markdown/createMethodEndpoint.d.ts +1 -0
  34. package/lib/markdown/createMethodEndpoint.js +20 -0
  35. package/lib/markdown/createParamsDetails.d.ts +6 -0
  36. package/lib/markdown/createParamsDetails.js +18 -0
  37. package/lib/markdown/createRequestBodyDetails.d.ts +13 -0
  38. package/lib/markdown/createRequestBodyDetails.js +13 -0
  39. package/lib/markdown/createRequestHeader.d.ts +1 -0
  40. package/lib/markdown/createRequestHeader.js +21 -0
  41. package/lib/markdown/createRequestSchema.d.ts +14 -0
  42. package/lib/markdown/createRequestSchema.js +20 -0
  43. package/lib/markdown/createResponseSchema.d.ts +14 -0
  44. package/lib/markdown/createResponseSchema.js +20 -0
  45. package/lib/markdown/createSchema.d.ts +9 -0
  46. package/lib/markdown/createSchema.js +668 -0
  47. package/lib/markdown/createSchema.test.d.ts +1 -0
  48. package/lib/markdown/createSchema.test.js +913 -0
  49. package/lib/markdown/createStatusCodes.d.ts +9 -0
  50. package/lib/markdown/createStatusCodes.js +63 -0
  51. package/lib/markdown/createTermsOfService.d.ts +1 -0
  52. package/lib/markdown/createTermsOfService.js +31 -0
  53. package/lib/markdown/createVendorExtensions.d.ts +1 -0
  54. package/lib/markdown/createVendorExtensions.js +24 -0
  55. package/lib/markdown/createVersionBadge.d.ts +1 -0
  56. package/lib/markdown/createVersionBadge.js +19 -0
  57. package/lib/markdown/index.d.ts +5 -0
  58. package/lib/markdown/index.js +92 -0
  59. package/lib/markdown/schema.d.ts +3 -0
  60. package/lib/markdown/schema.js +154 -0
  61. package/lib/markdown/schema.test.d.ts +1 -0
  62. package/lib/markdown/schema.test.js +181 -0
  63. package/lib/markdown/utils.d.ts +20 -0
  64. package/lib/markdown/utils.js +68 -0
  65. package/lib/openapi/createRequestExample.d.ts +2 -0
  66. package/lib/openapi/createRequestExample.js +191 -0
  67. package/lib/openapi/createResponseExample.d.ts +2 -0
  68. package/lib/openapi/createResponseExample.js +192 -0
  69. package/lib/openapi/index.d.ts +1 -0
  70. package/lib/openapi/index.js +12 -0
  71. package/lib/openapi/openapi.d.ts +12 -0
  72. package/lib/openapi/openapi.js +544 -0
  73. package/lib/openapi/openapi.test.d.ts +1 -0
  74. package/lib/openapi/openapi.test.js +33 -0
  75. package/lib/openapi/types.d.ts +354 -0
  76. package/lib/openapi/types.js +8 -0
  77. package/lib/openapi/utils/loadAndResolveSpec.d.ts +2 -0
  78. package/lib/openapi/utils/loadAndResolveSpec.js +153 -0
  79. package/lib/openapi/utils/services/OpenAPIParser.d.ts +52 -0
  80. package/lib/openapi/utils/services/OpenAPIParser.js +343 -0
  81. package/lib/openapi/utils/services/RedocNormalizedOptions.d.ts +100 -0
  82. package/lib/openapi/utils/services/RedocNormalizedOptions.js +170 -0
  83. package/lib/openapi/utils/types/index.d.ts +2 -0
  84. package/lib/openapi/utils/types/index.js +23 -0
  85. package/lib/openapi/utils/types/open-api.d.ts +305 -0
  86. package/lib/openapi/utils/types/open-api.js +8 -0
  87. package/lib/openapi/utils/types.d.ts +306 -0
  88. package/lib/openapi/utils/types.js +8 -0
  89. package/lib/openapi/utils/utils/JsonPointer.d.ts +51 -0
  90. package/lib/openapi/utils/utils/JsonPointer.js +95 -0
  91. package/lib/openapi/utils/utils/helpers.d.ts +43 -0
  92. package/lib/openapi/utils/utils/helpers.js +230 -0
  93. package/lib/openapi/utils/utils/index.d.ts +3 -0
  94. package/lib/openapi/utils/utils/index.js +25 -0
  95. package/lib/openapi/utils/utils/openapi.d.ts +40 -0
  96. package/lib/openapi/utils/utils/openapi.js +605 -0
  97. package/lib/options.d.ts +2 -0
  98. package/lib/options.js +69 -0
  99. package/lib/sidebars/index.d.ts +4 -0
  100. package/lib/sidebars/index.js +226 -0
  101. package/lib/sidebars/utils.d.ts +2 -0
  102. package/lib/sidebars/utils.js +30 -0
  103. package/lib/types.d.ts +135 -0
  104. package/lib/types.js +8 -0
  105. package/package.json +69 -0
  106. package/src/index.ts +945 -0
  107. package/src/markdown/__snapshots__/createSchema.test.ts.snap +1605 -0
  108. package/src/markdown/createArrayBracket.ts +35 -0
  109. package/src/markdown/createAuthentication.ts +201 -0
  110. package/src/markdown/createAuthorization.ts +13 -0
  111. package/src/markdown/createCallbackMethodEndpoint.ts +19 -0
  112. package/src/markdown/createCallbacks.ts +101 -0
  113. package/src/markdown/createContactInfo.ts +41 -0
  114. package/src/markdown/createDeprecationNotice.ts +31 -0
  115. package/src/markdown/createDescription.ts +12 -0
  116. package/src/markdown/createDetails.ts +16 -0
  117. package/src/markdown/createDetailsSummary.ts +16 -0
  118. package/src/markdown/createDownload.ts +15 -0
  119. package/src/markdown/createHeading.ts +23 -0
  120. package/src/markdown/createLicense.ts +34 -0
  121. package/src/markdown/createLogo.ts +21 -0
  122. package/src/markdown/createMethodEndpoint.ts +19 -0
  123. package/src/markdown/createParamsDetails.ts +22 -0
  124. package/src/markdown/createRequestBodyDetails.ts +24 -0
  125. package/src/markdown/createRequestHeader.ts +24 -0
  126. package/src/markdown/createRequestSchema.ts +32 -0
  127. package/src/markdown/createResponseSchema.ts +32 -0
  128. package/src/markdown/createSchema.test.ts +1075 -0
  129. package/src/markdown/createSchema.ts +862 -0
  130. package/src/markdown/createStatusCodes.ts +63 -0
  131. package/src/markdown/createTermsOfService.ts +30 -0
  132. package/src/markdown/createVendorExtensions.ts +22 -0
  133. package/src/markdown/createVersionBadge.ts +22 -0
  134. package/src/markdown/index.ts +144 -0
  135. package/src/markdown/schema.test.ts +208 -0
  136. package/src/markdown/schema.ts +185 -0
  137. package/src/markdown/utils.ts +89 -0
  138. package/src/openapi/__fixtures__/examples/openapi.yaml +49 -0
  139. package/src/openapi/createRequestExample.ts +235 -0
  140. package/src/openapi/createResponseExample.ts +238 -0
  141. package/src/openapi/index.ts +8 -0
  142. package/src/openapi/openapi.test.ts +40 -0
  143. package/src/openapi/openapi.ts +697 -0
  144. package/src/openapi/types.ts +455 -0
  145. package/src/openapi/utils/loadAndResolveSpec.ts +171 -0
  146. package/src/openapi/utils/services/OpenAPIParser.ts +434 -0
  147. package/src/openapi/utils/services/RedocNormalizedOptions.ts +330 -0
  148. package/src/openapi/utils/types/index.ts +10 -0
  149. package/src/openapi/utils/types/open-api.ts +303 -0
  150. package/src/openapi/utils/types.ts +303 -0
  151. package/src/openapi/utils/utils/JsonPointer.ts +99 -0
  152. package/src/openapi/utils/utils/helpers.ts +239 -0
  153. package/src/openapi/utils/utils/index.ts +11 -0
  154. package/src/openapi/utils/utils/openapi.ts +771 -0
  155. package/src/openapi-to-postmanv2.d.ts +10 -0
  156. package/src/options.ts +77 -0
  157. package/src/plugin-content-docs-types.d.ts +42 -0
  158. package/src/plugin-openapi.d.ts +87 -0
  159. package/src/postman-collection.d.ts +10 -0
  160. package/src/sidebars/index.ts +322 -0
  161. package/src/sidebars/utils.ts +29 -0
  162. package/src/types.ts +176 -0
  163. package/tsconfig.json +7 -0
package/lib/index.js ADDED
@@ -0,0 +1,709 @@
1
+ "use strict";
2
+ /* ============================================================================
3
+ * Copyright (c) Palo Alto Networks
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ * ========================================================================== */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.isURL = isURL;
13
+ exports.getDocsPluginConfig = getDocsPluginConfig;
14
+ exports.default = pluginOpenAPIDocs;
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const path_1 = __importDefault(require("path"));
17
+ const zlib_1 = __importDefault(require("zlib"));
18
+ const utils_1 = require("@docusaurus/utils");
19
+ const chalk_1 = __importDefault(require("chalk"));
20
+ const json5_1 = __importDefault(require("json5"));
21
+ const mustache_1 = require("mustache");
22
+ const markdown_1 = require("./markdown");
23
+ const openapi_1 = require("./openapi");
24
+ const options_1 = require("./options");
25
+ const sidebars_1 = __importDefault(require("./sidebars"));
26
+ function isURL(str) {
27
+ return /^(https?:)\/\//m.test(str);
28
+ }
29
+ function getDocsPluginConfig(presetsPlugins, plugin, pluginId) {
30
+ // eslint-disable-next-line array-callback-return
31
+ const filteredConfig = presetsPlugins.filter((data) => {
32
+ // Search presets
33
+ if (Array.isArray(data)) {
34
+ if (typeof data[0] === "string" && data[0].endsWith(pluginId)) {
35
+ return data[1];
36
+ }
37
+ // Search plugin-content-docs instances
38
+ if (typeof data[0] === "string" && data[0] === plugin) {
39
+ const configPluginId = data[1].id ? data[1].id : "default";
40
+ if (configPluginId === pluginId) {
41
+ return data[1];
42
+ }
43
+ }
44
+ }
45
+ })[0];
46
+ if (filteredConfig) {
47
+ // Search presets, e.g. "classic"
48
+ if (filteredConfig[0].endsWith(pluginId)) {
49
+ return filteredConfig[1].docs;
50
+ }
51
+ // Search plugin-content-docs instances
52
+ if (filteredConfig[0] === plugin) {
53
+ const configPluginId = filteredConfig[1].id
54
+ ? filteredConfig[1].id
55
+ : "default";
56
+ if (configPluginId === pluginId) {
57
+ return filteredConfig[1];
58
+ }
59
+ }
60
+ }
61
+ return;
62
+ }
63
+ function getPluginConfig(plugins, pluginId) {
64
+ return plugins.filter((data) => data[1].id === pluginId)[0][1];
65
+ }
66
+ function getPluginInstances(plugins) {
67
+ return plugins.filter((data) => data[0] === "docusaurus-plugin-openapi-docs");
68
+ }
69
+ function pluginOpenAPIDocs(context, options) {
70
+ const { config, docsPlugin = "@docusaurus/plugin-content-docs", docsPluginId, } = options;
71
+ const { siteDir, siteConfig } = context;
72
+ // Get routeBasePath and path from plugin-content-docs or preset
73
+ const presets = siteConfig.presets;
74
+ const plugins = siteConfig.plugins;
75
+ const presetsPlugins = presets.concat(plugins);
76
+ let docData = getDocsPluginConfig(presetsPlugins, docsPlugin, docsPluginId);
77
+ let docRouteBasePath = docData ? docData.routeBasePath : undefined;
78
+ let docPath = docData ? (docData.path ? docData.path : "docs") : undefined;
79
+ async function generateApiDocs(options, pluginId) {
80
+ var _a, _b, _c, _d;
81
+ let { specPath, outputDir, template, infoTemplate, tagTemplate, schemaTemplate, markdownGenerators, downloadUrl, sidebarOptions, disableCompression, } = options;
82
+ // Remove trailing slash before proceeding
83
+ outputDir = outputDir.replace(/\/$/, "");
84
+ // Override docPath if pluginId provided
85
+ if (pluginId) {
86
+ docData = getDocsPluginConfig(presetsPlugins, docsPlugin, pluginId);
87
+ docRouteBasePath = docData ? docData.routeBasePath : undefined;
88
+ docPath = docData ? (docData.path ? docData.path : "docs") : undefined;
89
+ }
90
+ const contentPath = isURL(specPath)
91
+ ? specPath
92
+ : path_1.default.resolve(siteDir, specPath);
93
+ try {
94
+ const openapiFiles = await (0, openapi_1.readOpenapiFiles)(contentPath);
95
+ const [loadedApi, tags, tagGroups] = await (0, openapi_1.processOpenapiFiles)(openapiFiles, options, sidebarOptions);
96
+ if (!fs_1.default.existsSync(outputDir)) {
97
+ try {
98
+ fs_1.default.mkdirSync(outputDir, { recursive: true });
99
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}"`));
100
+ }
101
+ catch (err) {
102
+ console.error(chalk_1.default.red(`Failed to create "${outputDir}"`), chalk_1.default.yellow(err));
103
+ }
104
+ }
105
+ // TODO: figure out better way to set default
106
+ if (Object.keys(sidebarOptions !== null && sidebarOptions !== void 0 ? sidebarOptions : {}).length > 0) {
107
+ const sidebarSlice = (0, sidebars_1.default)(sidebarOptions, options, loadedApi, tags, docPath, tagGroups);
108
+ let sidebarSliceTemplate = `import type { SidebarsConfig } from "@docusaurus/plugin-content-docs";\n\n`;
109
+ sidebarSliceTemplate += `const sidebar: SidebarsConfig = {{{slice}}};\n\n`;
110
+ sidebarSliceTemplate += `export default sidebar.apisidebar;\n`;
111
+ const view = (0, mustache_1.render)(sidebarSliceTemplate, {
112
+ slice: json5_1.default.stringify({ apisidebar: sidebarSlice }, { space: 2, quote: '"' }),
113
+ });
114
+ if (!fs_1.default.existsSync(`${outputDir}/sidebar.ts`)) {
115
+ try {
116
+ fs_1.default.writeFileSync(`${outputDir}/sidebar.ts`, view, "utf8");
117
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/sidebar.ts"`));
118
+ }
119
+ catch (err) {
120
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/sidebar.ts"`), chalk_1.default.yellow(err));
121
+ }
122
+ }
123
+ }
124
+ const mdTemplate = template
125
+ ? fs_1.default.readFileSync(template).toString()
126
+ : `---
127
+ id: {{{id}}}
128
+ title: "{{{title}}}"
129
+ description: "{{{frontMatter.description}}}"
130
+ {{^api}}
131
+ sidebar_label: Introduction
132
+ {{/api}}
133
+ {{#api}}
134
+ sidebar_label: "{{{title}}}"
135
+ {{/api}}
136
+ {{^api}}
137
+ sidebar_position: 0
138
+ {{/api}}
139
+ hide_title: true
140
+ {{#api}}
141
+ hide_table_of_contents: true
142
+ {{/api}}
143
+ {{#json}}
144
+ api: {{{json}}}
145
+ {{/json}}
146
+ {{#api.method}}
147
+ sidebar_class_name: "{{{api.method}}} api-method"
148
+ {{/api.method}}
149
+ {{#infoPath}}
150
+ info_path: {{{infoPath}}}
151
+ {{/infoPath}}
152
+ custom_edit_url: null
153
+ {{#frontMatter.proxy}}
154
+ proxy: {{{frontMatter.proxy}}}
155
+ {{/frontMatter.proxy}}
156
+ {{#frontMatter.hide_send_button}}
157
+ hide_send_button: true
158
+ {{/frontMatter.hide_send_button}}
159
+ {{#frontMatter.show_extensions}}
160
+ show_extensions: true
161
+ {{/frontMatter.show_extensions}}
162
+ ---
163
+
164
+ {{{markdown}}}
165
+ `;
166
+ const infoMdTemplate = infoTemplate
167
+ ? fs_1.default.readFileSync(infoTemplate).toString()
168
+ : `---
169
+ id: {{{id}}}
170
+ title: "{{{title}}}"
171
+ description: "{{{frontMatter.description}}}"
172
+ sidebar_label: "{{{title}}}"
173
+ hide_title: true
174
+ custom_edit_url: null
175
+ ---
176
+
177
+ {{{markdown}}}
178
+
179
+ \`\`\`mdx-code-block
180
+ import DocCardList from '@theme/DocCardList';
181
+ import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
182
+
183
+ <DocCardList items={useCurrentSidebarCategory().items}/>
184
+ \`\`\`
185
+ `;
186
+ const tagMdTemplate = tagTemplate
187
+ ? fs_1.default.readFileSync(tagTemplate).toString()
188
+ : `---
189
+ id: {{{id}}}
190
+ title: "{{{frontMatter.description}}}"
191
+ description: "{{{frontMatter.description}}}"
192
+ custom_edit_url: null
193
+ ---
194
+
195
+ {{{markdown}}}
196
+
197
+ \`\`\`mdx-code-block
198
+ import DocCardList from '@theme/DocCardList';
199
+ import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
200
+
201
+ <DocCardList items={useCurrentSidebarCategory().items}/>
202
+ \`\`\`
203
+ `;
204
+ const schemaMdTemplate = schemaTemplate
205
+ ? fs_1.default.readFileSync(schemaTemplate).toString()
206
+ : `---
207
+ id: {{{id}}}
208
+ title: "{{{title}}}"
209
+ description: "{{{frontMatter.description}}}"
210
+ sidebar_label: "{{{title}}}"
211
+ hide_title: true
212
+ {{#schema}}
213
+ hide_table_of_contents: true
214
+ {{/schema}}
215
+ schema: true
216
+ sample: {{{frontMatter.sample}}}
217
+ custom_edit_url: null
218
+ ---
219
+
220
+ {{{markdown}}}
221
+ `;
222
+ const apiPageGenerator = (_a = markdownGenerators === null || markdownGenerators === void 0 ? void 0 : markdownGenerators.createApiPageMD) !== null && _a !== void 0 ? _a : markdown_1.createApiPageMD;
223
+ const infoPageGenerator = (_b = markdownGenerators === null || markdownGenerators === void 0 ? void 0 : markdownGenerators.createInfoPageMD) !== null && _b !== void 0 ? _b : markdown_1.createInfoPageMD;
224
+ const tagPageGenerator = (_c = markdownGenerators === null || markdownGenerators === void 0 ? void 0 : markdownGenerators.createTagPageMD) !== null && _c !== void 0 ? _c : markdown_1.createTagPageMD;
225
+ const schemaPageGenerator = (_d = markdownGenerators === null || markdownGenerators === void 0 ? void 0 : markdownGenerators.createSchemaPageMD) !== null && _d !== void 0 ? _d : markdown_1.createSchemaPageMD;
226
+ const pageGeneratorByType = {
227
+ api: apiPageGenerator,
228
+ info: infoPageGenerator,
229
+ tag: tagPageGenerator,
230
+ schema: schemaPageGenerator,
231
+ };
232
+ loadedApi.map(async (item) => {
233
+ if (downloadUrl) {
234
+ item.downloadUrl = downloadUrl;
235
+ }
236
+ const markdown = pageGeneratorByType[item.type](item);
237
+ item.markdown = markdown;
238
+ if (item.type === "api") {
239
+ // opportunity to compress JSON
240
+ // const serialize = (o: any) => {
241
+ // return zlib.deflateSync(JSON.stringify(o)).toString("base64");
242
+ // };
243
+ // const deserialize = (s: any) => {
244
+ // return zlib.inflateSync(Buffer.from(s, "base64")).toString();
245
+ // };
246
+ disableCompression === true
247
+ ? (item.json = JSON.stringify(item.api))
248
+ : (item.json = zlib_1.default
249
+ .deflateSync(JSON.stringify(item.api))
250
+ .toString("base64"));
251
+ let infoBasePath = `${outputDir}/${item.infoId}`;
252
+ if (docRouteBasePath) {
253
+ infoBasePath = `${docRouteBasePath}/${outputDir
254
+ .split(docPath)[1]
255
+ .replace(/^\/+/g, "")}/${item.infoId}`.replace(/^\/+/g, "");
256
+ }
257
+ if (item.infoId)
258
+ item.infoPath = infoBasePath;
259
+ }
260
+ const view = (0, mustache_1.render)(mdTemplate, item);
261
+ const utils = (0, mustache_1.render)(infoMdTemplate, item);
262
+ // eslint-disable-next-line testing-library/render-result-naming-convention
263
+ const tagUtils = (0, mustache_1.render)(tagMdTemplate, item);
264
+ if (item.type === "api") {
265
+ if (!fs_1.default.existsSync(`${outputDir}/${item.id}.api.mdx`)) {
266
+ try {
267
+ // kebabCase(arg) returns 0-length string when arg is undefined
268
+ if (item.id.length === 0) {
269
+ throw Error("Operation must have summary or operationId defined");
270
+ }
271
+ fs_1.default.writeFileSync(`${outputDir}/${item.id}.api.mdx`, view, "utf8");
272
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/${item.id}.api.mdx"`));
273
+ }
274
+ catch (err) {
275
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/${item.id}.api.mdx"`), chalk_1.default.yellow(err));
276
+ }
277
+ }
278
+ }
279
+ if (item.type === "info") {
280
+ if (!fs_1.default.existsSync(`${outputDir}/${item.id}.info.mdx`)) {
281
+ try {
282
+ fs_1.default.writeFileSync(`${outputDir}/${item.id}.info.mdx`, utils, "utf8");
283
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/${item.id}.info.mdx"`));
284
+ }
285
+ catch (err) {
286
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/${item.id}.info.mdx"`), chalk_1.default.yellow(err));
287
+ }
288
+ }
289
+ }
290
+ if (item.type === "tag") {
291
+ if (!fs_1.default.existsSync(`${outputDir}/${item.id}.tag.mdx`)) {
292
+ try {
293
+ fs_1.default.writeFileSync(`${outputDir}/${item.id}.tag.mdx`, tagUtils, "utf8");
294
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/${item.id}.tag.mdx"`));
295
+ }
296
+ catch (err) {
297
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/${item.id}.tag.mdx"`), chalk_1.default.yellow(err));
298
+ }
299
+ }
300
+ }
301
+ if (item.type === "schema") {
302
+ if (!fs_1.default.existsSync(`${outputDir}/schemas/${item.id}.schema.mdx`)) {
303
+ if (!fs_1.default.existsSync(`${outputDir}/schemas`)) {
304
+ try {
305
+ fs_1.default.mkdirSync(`${outputDir}/schemas`, { recursive: true });
306
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/schemas"`));
307
+ }
308
+ catch (err) {
309
+ console.error(chalk_1.default.red(`Failed to create "${outputDir}/schemas"`), chalk_1.default.yellow(err));
310
+ }
311
+ }
312
+ try {
313
+ // kebabCase(arg) returns 0-length string when arg is undefined
314
+ if (item.id.length === 0) {
315
+ throw Error("Schema must have title defined");
316
+ }
317
+ // eslint-disable-next-line testing-library/render-result-naming-convention
318
+ const schemaView = (0, mustache_1.render)(schemaMdTemplate, item);
319
+ fs_1.default.writeFileSync(`${outputDir}/schemas/${item.id}.schema.mdx`, schemaView, "utf8");
320
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/${item.id}.schema.mdx"`));
321
+ }
322
+ catch (err) {
323
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/${item.id}.schema.mdx"`), chalk_1.default.yellow(err));
324
+ }
325
+ }
326
+ }
327
+ return;
328
+ });
329
+ return;
330
+ }
331
+ catch (e) {
332
+ console.error(chalk_1.default.red(`Loading of api failed for "${contentPath}"`));
333
+ throw e;
334
+ }
335
+ }
336
+ async function cleanApiDocs(options) {
337
+ const { outputDir } = options;
338
+ const apiDir = (0, utils_1.posixPath)(path_1.default.join(siteDir, outputDir));
339
+ const apiMdxFiles = await (0, utils_1.Globby)(["*.api.mdx", "*.info.mdx", "*.tag.mdx"], {
340
+ cwd: path_1.default.resolve(apiDir),
341
+ deep: 1,
342
+ });
343
+ const sidebarFile = await (0, utils_1.Globby)(["sidebar.js", "sidebar.ts"], {
344
+ cwd: path_1.default.resolve(apiDir),
345
+ deep: 1,
346
+ });
347
+ apiMdxFiles.map((mdx) => fs_1.default.unlink(`${apiDir}/${mdx}`, (err) => {
348
+ if (err) {
349
+ console.error(chalk_1.default.red(`Cleanup failed for "${apiDir}/${mdx}"`), chalk_1.default.yellow(err));
350
+ }
351
+ else {
352
+ console.log(chalk_1.default.green(`Cleanup succeeded for "${apiDir}/${mdx}"`));
353
+ }
354
+ }));
355
+ try {
356
+ fs_1.default.rmSync(`${apiDir}/schemas`, { recursive: true });
357
+ console.log(chalk_1.default.green(`Cleanup succeeded for "${apiDir}/schemas"`));
358
+ }
359
+ catch (err) {
360
+ if (err.code !== "ENOENT") {
361
+ console.error(chalk_1.default.red(`Cleanup failed for "${apiDir}/schemas"`), chalk_1.default.yellow(err));
362
+ }
363
+ }
364
+ sidebarFile.map((sidebar) => fs_1.default.unlink(`${apiDir}/${sidebar}`, (err) => {
365
+ if (err) {
366
+ console.error(chalk_1.default.red(`Cleanup failed for "${apiDir}/${sidebar}"`), chalk_1.default.yellow(err));
367
+ }
368
+ else {
369
+ console.log(chalk_1.default.green(`Cleanup succeeded for "${apiDir}/${sidebar}"`));
370
+ }
371
+ }));
372
+ }
373
+ async function generateVersions(versions, outputDir) {
374
+ let versionsArray = [];
375
+ for (const [version, metadata] of Object.entries(versions)) {
376
+ versionsArray.push({
377
+ version: version,
378
+ label: metadata.label,
379
+ baseUrl: metadata.baseUrl,
380
+ downloadUrl: metadata.downloadUrl,
381
+ });
382
+ }
383
+ if (!fs_1.default.existsSync(outputDir)) {
384
+ try {
385
+ fs_1.default.mkdirSync(outputDir, { recursive: true });
386
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}"`));
387
+ }
388
+ catch (err) {
389
+ console.error(chalk_1.default.red(`Failed to create "${outputDir}"`), chalk_1.default.yellow(err));
390
+ }
391
+ }
392
+ const versionsJson = JSON.stringify(versionsArray, null, 2);
393
+ try {
394
+ fs_1.default.writeFileSync(`${outputDir}/versions.json`, versionsJson + "\n", "utf8");
395
+ console.log(chalk_1.default.green(`Successfully created "${outputDir}/versions.json"`));
396
+ }
397
+ catch (err) {
398
+ console.error(chalk_1.default.red(`Failed to write "${outputDir}/versions.json"`), chalk_1.default.yellow(err));
399
+ }
400
+ }
401
+ async function cleanVersions(outputDir) {
402
+ if (fs_1.default.existsSync(`${outputDir}/versions.json`)) {
403
+ fs_1.default.unlink(`${outputDir}/versions.json`, (err) => {
404
+ if (err) {
405
+ console.error(chalk_1.default.red(`Cleanup failed for "${outputDir}/versions.json"`), chalk_1.default.yellow(err));
406
+ }
407
+ else {
408
+ console.log(chalk_1.default.green(`Cleanup succeeded for "${outputDir}/versions.json"`));
409
+ }
410
+ });
411
+ }
412
+ }
413
+ async function generateAllVersions(options, pluginId) {
414
+ const parentOptions = Object.assign({}, options);
415
+ const { versions } = parentOptions;
416
+ if (versions != null && Object.keys(versions).length > 0) {
417
+ const version = parentOptions.version;
418
+ const label = parentOptions.label;
419
+ const baseUrl = parentOptions.baseUrl;
420
+ let parentVersion = {};
421
+ parentVersion[version] = { label: label, baseUrl: baseUrl };
422
+ const mergedVersions = Object.assign(parentVersion, versions);
423
+ // Prepare for merge
424
+ delete parentOptions.versions;
425
+ delete parentOptions.version;
426
+ delete parentOptions.label;
427
+ delete parentOptions.baseUrl;
428
+ delete parentOptions.downloadUrl;
429
+ await generateVersions(mergedVersions, parentOptions.outputDir);
430
+ Object.keys(versions).forEach(async (key) => {
431
+ if (key === "all") {
432
+ console.error(chalk_1.default.red("Can't use id 'all' for OpenAPI docs versions configuration key."));
433
+ }
434
+ const versionOptions = versions[key];
435
+ const mergedOptions = {
436
+ ...parentOptions,
437
+ ...versionOptions,
438
+ };
439
+ await generateApiDocs(mergedOptions, pluginId);
440
+ });
441
+ }
442
+ }
443
+ async function cleanAllVersions(options) {
444
+ const parentOptions = Object.assign({}, options);
445
+ const { versions } = parentOptions;
446
+ delete parentOptions.versions;
447
+ if (versions != null && Object.keys(versions).length > 0) {
448
+ await cleanVersions(parentOptions.outputDir);
449
+ Object.keys(versions).forEach(async (key) => {
450
+ const versionOptions = versions[key];
451
+ const mergedOptions = {
452
+ ...parentOptions,
453
+ ...versionOptions,
454
+ };
455
+ await cleanApiDocs(mergedOptions);
456
+ });
457
+ }
458
+ }
459
+ return {
460
+ name: `docusaurus-plugin-openapi-docs`,
461
+ extendCli(cli) {
462
+ cli
463
+ .command(`gen-api-docs`)
464
+ .description(`Generates OpenAPI docs in MDX file format and sidebar.ts (if enabled).`)
465
+ .usage("<id>")
466
+ .arguments("<id>")
467
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
468
+ .option("--all-versions", "Generate all versions.")
469
+ .action(async (id, instance) => {
470
+ var _a;
471
+ const options = instance.opts();
472
+ const pluginId = options.pluginId;
473
+ const allVersions = options.allVersions;
474
+ const pluginInstances = getPluginInstances(plugins);
475
+ let targetConfig;
476
+ let targetDocsPluginId;
477
+ if (pluginId) {
478
+ try {
479
+ const pluginConfig = getPluginConfig(plugins, pluginId);
480
+ targetConfig = (_a = pluginConfig.config) !== null && _a !== void 0 ? _a : {};
481
+ targetDocsPluginId = pluginConfig.docsPluginId;
482
+ }
483
+ catch {
484
+ console.error(chalk_1.default.red(`OpenAPI docs plugin ID '${pluginId}' not found.`));
485
+ return;
486
+ }
487
+ }
488
+ else {
489
+ if (pluginInstances.length > 1) {
490
+ console.error(chalk_1.default.red("OpenAPI docs plugin ID must be specified when more than one plugin instance exists."));
491
+ return;
492
+ }
493
+ targetConfig = config;
494
+ }
495
+ if (id === "all") {
496
+ if (targetConfig[id]) {
497
+ console.error(chalk_1.default.red("Can't use id 'all' for OpenAPI docs configuration key."));
498
+ }
499
+ else {
500
+ Object.keys(targetConfig).forEach(async function (key) {
501
+ await generateApiDocs(targetConfig[key], targetDocsPluginId);
502
+ if (allVersions) {
503
+ await generateAllVersions(targetConfig[key], targetDocsPluginId);
504
+ }
505
+ });
506
+ }
507
+ }
508
+ else if (!targetConfig[id]) {
509
+ console.error(chalk_1.default.red(`ID '${id}' does not exist in OpenAPI docs config.`));
510
+ }
511
+ else {
512
+ await generateApiDocs(targetConfig[id], targetDocsPluginId);
513
+ if (allVersions) {
514
+ await generateAllVersions(targetConfig[id], targetDocsPluginId);
515
+ }
516
+ }
517
+ });
518
+ cli
519
+ .command(`gen-api-docs:version`)
520
+ .description(`Generates versioned OpenAPI docs in MDX file format, versions.js and sidebar.ts (if enabled).`)
521
+ .usage("<id:version>")
522
+ .arguments("<id:version>")
523
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
524
+ .action(async (id, instance) => {
525
+ var _a;
526
+ const options = instance.opts();
527
+ const pluginId = options.pluginId;
528
+ const pluginInstances = getPluginInstances(plugins);
529
+ let targetConfig;
530
+ let targetDocsPluginId;
531
+ if (pluginId) {
532
+ try {
533
+ const pluginConfig = getPluginConfig(plugins, pluginId);
534
+ targetConfig = (_a = pluginConfig.config) !== null && _a !== void 0 ? _a : {};
535
+ targetDocsPluginId = pluginConfig.docsPluginId;
536
+ }
537
+ catch {
538
+ console.error(chalk_1.default.red(`OpenAPI docs plugin ID '${pluginId}' not found.`));
539
+ return;
540
+ }
541
+ }
542
+ else {
543
+ if (pluginInstances.length > 1) {
544
+ console.error(chalk_1.default.red("OpenAPI docs plugin ID must be specified when more than one plugin instance exists."));
545
+ return;
546
+ }
547
+ targetConfig = config;
548
+ }
549
+ const [parentId, versionId] = id.split(":");
550
+ const parentConfig = Object.assign({}, targetConfig[parentId]);
551
+ const version = parentConfig.version;
552
+ const label = parentConfig.label;
553
+ const baseUrl = parentConfig.baseUrl;
554
+ let parentVersion = {};
555
+ parentVersion[version] = { label: label, baseUrl: baseUrl };
556
+ const { versions } = targetConfig[parentId];
557
+ const mergedVersions = Object.assign(parentVersion, versions);
558
+ // Prepare for merge
559
+ delete parentConfig.versions;
560
+ delete parentConfig.version;
561
+ delete parentConfig.label;
562
+ delete parentConfig.baseUrl;
563
+ delete parentConfig.downloadUrl;
564
+ // TODO: handle when no versions are defined by version command is passed
565
+ if (versionId === "all") {
566
+ if (versions[id]) {
567
+ console.error(chalk_1.default.red("Can't use id 'all' for OpenAPI docs versions configuration key."));
568
+ }
569
+ else {
570
+ await generateVersions(mergedVersions, parentConfig.outputDir);
571
+ Object.keys(versions).forEach(async (key) => {
572
+ const versionConfig = versions[key];
573
+ const mergedConfig = {
574
+ ...parentConfig,
575
+ ...versionConfig,
576
+ };
577
+ await generateApiDocs(mergedConfig, targetDocsPluginId);
578
+ });
579
+ }
580
+ }
581
+ else if (!versions[versionId]) {
582
+ console.error(chalk_1.default.red(`Version ID '${versionId}' does not exist in OpenAPI docs versions config.`));
583
+ }
584
+ else {
585
+ const versionConfig = versions[versionId];
586
+ const mergedConfig = {
587
+ ...parentConfig,
588
+ ...versionConfig,
589
+ };
590
+ await generateVersions(mergedVersions, parentConfig.outputDir);
591
+ await generateApiDocs(mergedConfig, targetDocsPluginId);
592
+ }
593
+ });
594
+ cli
595
+ .command(`clean-api-docs`)
596
+ .description(`Clears the generated OpenAPI docs MDX files and sidebar.ts (if enabled).`)
597
+ .usage("<id>")
598
+ .arguments("<id>")
599
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
600
+ .option("--all-versions", "Clean all versions.")
601
+ .action(async (id, instance) => {
602
+ var _a;
603
+ const options = instance.opts();
604
+ const pluginId = options.pluginId;
605
+ const allVersions = options.allVersions;
606
+ const pluginInstances = getPluginInstances(plugins);
607
+ let targetConfig;
608
+ if (pluginId) {
609
+ try {
610
+ const pluginConfig = getPluginConfig(plugins, pluginId);
611
+ targetConfig = (_a = pluginConfig.config) !== null && _a !== void 0 ? _a : {};
612
+ }
613
+ catch {
614
+ console.error(chalk_1.default.red(`OpenAPI docs plugin ID '${pluginId}' not found.`));
615
+ return;
616
+ }
617
+ }
618
+ else {
619
+ if (pluginInstances.length > 1) {
620
+ console.error(chalk_1.default.red("OpenAPI docs plugin ID must be specified when more than one plugin instance exists."));
621
+ return;
622
+ }
623
+ targetConfig = config;
624
+ }
625
+ if (id === "all") {
626
+ if (targetConfig[id]) {
627
+ console.error(chalk_1.default.red("Can't use id 'all' for OpenAPI docs configuration key."));
628
+ }
629
+ else {
630
+ Object.keys(targetConfig).forEach(async function (key) {
631
+ await cleanApiDocs(targetConfig[key]);
632
+ if (allVersions) {
633
+ await cleanAllVersions(targetConfig[key]);
634
+ }
635
+ });
636
+ }
637
+ }
638
+ else {
639
+ await cleanApiDocs(targetConfig[id]);
640
+ if (allVersions) {
641
+ await cleanAllVersions(targetConfig[id]);
642
+ }
643
+ }
644
+ });
645
+ cli
646
+ .command(`clean-api-docs:version`)
647
+ .description(`Clears the versioned, generated OpenAPI docs MDX files, versions.json and sidebar.ts (if enabled).`)
648
+ .usage("<id:version>")
649
+ .arguments("<id:version>")
650
+ .option("-p, --plugin-id <plugin>", "OpenAPI docs plugin ID.")
651
+ .action(async (id, instance) => {
652
+ var _a;
653
+ const options = instance.opts();
654
+ const pluginId = options.pluginId;
655
+ const pluginInstances = getPluginInstances(plugins);
656
+ let targetConfig;
657
+ if (pluginId) {
658
+ try {
659
+ const pluginConfig = getPluginConfig(plugins, pluginId);
660
+ targetConfig = (_a = pluginConfig.config) !== null && _a !== void 0 ? _a : {};
661
+ }
662
+ catch {
663
+ console.error(chalk_1.default.red(`OpenAPI docs plugin ID '${pluginId}' not found.`));
664
+ return;
665
+ }
666
+ }
667
+ else {
668
+ if (pluginInstances.length > 1) {
669
+ console.error(chalk_1.default.red("OpenAPI docs plugin ID must be specified when more than one plugin instance exists."));
670
+ return;
671
+ }
672
+ targetConfig = config;
673
+ }
674
+ const [parentId, versionId] = id.split(":");
675
+ const { versions } = targetConfig[parentId];
676
+ const parentConfig = Object.assign({}, targetConfig[parentId]);
677
+ delete parentConfig.versions;
678
+ if (versionId === "all") {
679
+ if (versions[id]) {
680
+ chalk_1.default.red("Can't use id 'all' for OpenAPI docs versions configuration key.");
681
+ }
682
+ else {
683
+ await cleanVersions(parentConfig.outputDir);
684
+ Object.keys(versions).forEach(async (key) => {
685
+ const versionConfig = versions[key];
686
+ const mergedConfig = {
687
+ ...parentConfig,
688
+ ...versionConfig,
689
+ };
690
+ await cleanApiDocs(mergedConfig);
691
+ });
692
+ }
693
+ }
694
+ else {
695
+ const versionConfig = versions[versionId];
696
+ const mergedConfig = {
697
+ ...parentConfig,
698
+ ...versionConfig,
699
+ };
700
+ await cleanApiDocs(mergedConfig);
701
+ }
702
+ });
703
+ },
704
+ };
705
+ }
706
+ pluginOpenAPIDocs.validateOptions = ({ options, validate }) => {
707
+ const validatedOptions = validate(options_1.OptionsSchema, options);
708
+ return validatedOptions;
709
+ };