docusaurus-plugin-openapi-docs 1.0.6 → 1.1.2

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 (47) hide show
  1. package/README.md +1 -2
  2. package/lib/markdown/createSchemaDetails.js +325 -132
  3. package/lib/markdown/index.js +1 -0
  4. package/lib/markdown/schema.js +25 -9
  5. package/lib/markdown/utils.d.ts +1 -1
  6. package/lib/markdown/utils.js +4 -1
  7. package/lib/openapi/openapi.d.ts +3 -3
  8. package/lib/openapi/openapi.js +30 -26
  9. package/lib/openapi/types.d.ts +2 -1
  10. package/lib/openapi/utils/loadAndResolveSpec.d.ts +2 -0
  11. package/lib/openapi/utils/{loadAndBundleSpec.js → loadAndResolveSpec.js} +61 -28
  12. package/lib/openapi/utils/services/OpenAPIParser.d.ts +52 -0
  13. package/lib/openapi/utils/services/OpenAPIParser.js +342 -0
  14. package/lib/openapi/utils/services/RedocNormalizedOptions.d.ts +100 -0
  15. package/lib/openapi/utils/services/RedocNormalizedOptions.js +170 -0
  16. package/lib/openapi/utils/types/index.d.ts +2 -0
  17. package/lib/openapi/utils/types/index.js +23 -0
  18. package/lib/openapi/utils/types/open-api.d.ts +305 -0
  19. package/lib/openapi/utils/types/open-api.js +8 -0
  20. package/lib/openapi/utils/utils/JsonPointer.d.ts +51 -0
  21. package/lib/openapi/utils/utils/JsonPointer.js +95 -0
  22. package/lib/openapi/utils/utils/helpers.d.ts +43 -0
  23. package/lib/openapi/utils/utils/helpers.js +230 -0
  24. package/lib/openapi/utils/utils/index.d.ts +3 -0
  25. package/lib/openapi/utils/utils/index.js +25 -0
  26. package/lib/openapi/utils/utils/openapi.d.ts +40 -0
  27. package/lib/openapi/utils/utils/openapi.js +605 -0
  28. package/lib/sidebars/index.js +5 -3
  29. package/package.json +15 -11
  30. package/src/markdown/createSchemaDetails.ts +405 -159
  31. package/src/markdown/index.ts +1 -0
  32. package/src/markdown/schema.ts +28 -8
  33. package/src/markdown/utils.ts +5 -2
  34. package/src/openapi/openapi.ts +42 -38
  35. package/src/openapi/types.ts +2 -1
  36. package/src/openapi/utils/loadAndResolveSpec.ts +123 -0
  37. package/src/openapi/utils/services/OpenAPIParser.ts +433 -0
  38. package/src/openapi/utils/services/RedocNormalizedOptions.ts +330 -0
  39. package/src/openapi/utils/types/index.ts +10 -0
  40. package/src/openapi/utils/types/open-api.ts +303 -0
  41. package/src/openapi/utils/utils/JsonPointer.ts +99 -0
  42. package/src/openapi/utils/utils/helpers.ts +239 -0
  43. package/src/openapi/utils/utils/index.ts +11 -0
  44. package/src/openapi/utils/utils/openapi.ts +771 -0
  45. package/src/sidebars/index.ts +7 -4
  46. package/lib/openapi/utils/loadAndBundleSpec.d.ts +0 -3
  47. package/src/openapi/utils/loadAndBundleSpec.ts +0 -93
@@ -8,22 +8,36 @@
8
8
  import { SchemaObject } from "../openapi/types";
9
9
 
10
10
  function prettyName(schema: SchemaObject, circular?: boolean) {
11
- if (schema.$ref) {
12
- return schema.$ref.replace("#/components/schemas/", "") + circular
13
- ? " (circular)"
14
- : "";
15
- }
16
-
17
11
  if (schema.format) {
18
12
  return schema.format;
19
13
  }
20
14
 
21
15
  if (schema.allOf) {
16
+ if (typeof schema.allOf[0] === "string") {
17
+ // @ts-ignore
18
+ if (schema.allOf[0].includes("circular")) {
19
+ return schema.allOf[0];
20
+ }
21
+ }
22
+ return "object";
23
+ }
24
+
25
+ if (schema.oneOf) {
26
+ return "object";
27
+ }
28
+
29
+ if (schema.anyOf) {
22
30
  return "object";
23
31
  }
24
32
 
25
33
  if (schema.type === "object") {
26
34
  return schema.xml?.name ?? schema.type;
35
+ // return schema.type;
36
+ }
37
+
38
+ if (schema.type === "array") {
39
+ return schema.xml?.name ?? schema.type;
40
+ // return schema.type;
27
41
  }
28
42
 
29
43
  return schema.title ?? schema.type;
@@ -42,8 +56,6 @@ export function getSchemaName(
42
56
 
43
57
  export function getQualifierMessage(schema?: SchemaObject): string | undefined {
44
58
  // TODO:
45
- // - maxItems
46
- // - minItems
47
59
  // - uniqueItems
48
60
  // - maxProperties
49
61
  // - minProperties
@@ -107,6 +119,14 @@ export function getQualifierMessage(schema?: SchemaObject): string | undefined {
107
119
  qualifierGroups.push(`[${schema.enum.map((e) => `\`${e}\``).join(", ")}]`);
108
120
  }
109
121
 
122
+ if (schema.minItems) {
123
+ qualifierGroups.push(`items >= ${schema.minItems}`);
124
+ }
125
+
126
+ if (schema.maxItems) {
127
+ qualifierGroups.push(`items <= ${schema.maxItems}`);
128
+ }
129
+
110
130
  if (qualifierGroups.length === 0) {
111
131
  return undefined;
112
132
  }
@@ -5,7 +5,7 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  * ========================================================================== */
7
7
 
8
- export type Children = string | undefined | (string | undefined)[];
8
+ export type Children = string | undefined | (string | string[] | undefined)[];
9
9
 
10
10
  export type Props = Record<string, any> & { children?: Children };
11
11
 
@@ -33,7 +33,10 @@ export function guard<T>(
33
33
 
34
34
  export function render(children: Children): string {
35
35
  if (Array.isArray(children)) {
36
- return children.filter((c) => c !== undefined).join("");
36
+ const filteredChildren = children.filter((c) => c !== undefined);
37
+ return filteredChildren
38
+ .map((i: any) => (Array.isArray(i) ? i.join("") : i))
39
+ .join("");
37
40
  }
38
41
  return children ?? "";
39
42
  }
@@ -13,7 +13,6 @@ import sdk from "@paloaltonetworks/postman-collection";
13
13
  import Collection from "@paloaltonetworks/postman-collection";
14
14
  import chalk from "chalk";
15
15
  import fs from "fs-extra";
16
- import JsonRefs from "json-refs";
17
16
  import { kebabCase } from "lodash";
18
17
 
19
18
  import { isURL } from "../index";
@@ -26,16 +25,8 @@ import {
26
25
  TagPageMetadata,
27
26
  } from "../types";
28
27
  import { sampleFromSchema } from "./createExample";
29
- import { OpenApiObject, OpenApiObjectWithRef, TagObject } from "./types";
30
- import { loadAndBundleSpec } from "./utils/loadAndBundleSpec";
31
-
32
- /**
33
- * Finds any reference objects in the OpenAPI definition and resolves them to a finalized value.
34
- */
35
- async function resolveRefs(openapiData: OpenApiObjectWithRef) {
36
- const { resolved } = await JsonRefs.resolveRefs(openapiData);
37
- return resolved as OpenApiObject;
38
- }
28
+ import { OpenApiObject, TagObject } from "./types";
29
+ import { loadAndResolveSpec } from "./utils/loadAndResolveSpec";
39
30
 
40
31
  /**
41
32
  * Convenience function for converting raw JSON to a Postman Collection object.
@@ -62,7 +53,8 @@ function jsonToCollection(data: OpenApiObject): Promise<Collection> {
62
53
  async function createPostmanCollection(
63
54
  openapiData: OpenApiObject
64
55
  ): Promise<Collection> {
65
- const data = JSON.parse(JSON.stringify(openapiData)) as OpenApiObject;
56
+ // Create copy of openapiData
57
+ const data = Object.assign({}, openapiData) as OpenApiObject;
66
58
 
67
59
  // Including `servers` breaks postman, so delete all of them.
68
60
  delete data.servers;
@@ -155,7 +147,9 @@ function createItems(
155
147
  operationObject.summary ?? operationObject.operationId ?? "";
156
148
  }
157
149
 
158
- const baseId = kebabCase(title);
150
+ const baseId = operationObject.operationId
151
+ ? kebabCase(operationObject.operationId)
152
+ : kebabCase(operationObject.summary);
159
153
 
160
154
  const servers =
161
155
  operationObject.servers ?? pathObject.servers ?? openapiData.servers;
@@ -243,17 +237,13 @@ function bindCollectionToApiItems(
243
237
  interface OpenApiFiles {
244
238
  source: string;
245
239
  sourceDirName: string;
246
- data: OpenApiObjectWithRef;
240
+ data: OpenApiObject;
247
241
  }
248
242
 
249
243
  export async function readOpenapiFiles(
250
244
  openapiPath: string,
251
245
  options: APIOptions
252
246
  ): Promise<OpenApiFiles[]> {
253
- // TODO: determine if this should be an API option
254
- // Forces the json-schema-ref-parser
255
- const parseJsonRefs = true;
256
-
257
247
  if (!isURL(openapiPath)) {
258
248
  const stat = await fs.lstat(openapiPath);
259
249
  if (stat.isDirectory()) {
@@ -274,10 +264,9 @@ export async function readOpenapiFiles(
274
264
  sources.map(async (source) => {
275
265
  // TODO: make a function for this
276
266
  const fullPath = path.join(openapiPath, source);
277
- const data = (await loadAndBundleSpec(
278
- fullPath,
279
- parseJsonRefs
280
- )) as OpenApiObjectWithRef;
267
+ const data = (await loadAndResolveSpec(
268
+ fullPath
269
+ )) as unknown as OpenApiObject;
281
270
  return {
282
271
  source: fullPath, // This will be aliased in process.
283
272
  sourceDirName: path.dirname(source),
@@ -287,10 +276,9 @@ export async function readOpenapiFiles(
287
276
  );
288
277
  }
289
278
  }
290
- const data = (await loadAndBundleSpec(
291
- openapiPath,
292
- parseJsonRefs
293
- )) as OpenApiObjectWithRef;
279
+ const data = (await loadAndResolveSpec(
280
+ openapiPath
281
+ )) as unknown as OpenApiObject;
294
282
  return [
295
283
  {
296
284
  source: openapiPath, // This will be aliased in process.
@@ -305,30 +293,46 @@ export async function processOpenapiFiles(
305
293
  sidebarOptions: SidebarOptions
306
294
  ): Promise<[ApiMetadata[], TagObject[]]> {
307
295
  const promises = files.map(async (file) => {
308
- const processedFile = await processOpenapiFile(file.data, sidebarOptions);
309
- const itemsObjectsArray = processedFile[0].map((item) => ({
310
- ...item,
311
- }));
312
- const tags = processedFile[1];
313
- return [itemsObjectsArray, tags];
296
+ if (file.data !== undefined) {
297
+ const processedFile = await processOpenapiFile(file.data, sidebarOptions);
298
+ const itemsObjectsArray = processedFile[0].map((item) => ({
299
+ ...item,
300
+ }));
301
+ const tags = processedFile[1];
302
+ return [itemsObjectsArray, tags];
303
+ }
304
+ console.warn(
305
+ chalk.yellow(
306
+ `WARNING: the following OpenAPI spec returned undefined: ${file.source}`
307
+ )
308
+ );
309
+ return [];
314
310
  });
315
311
  const metadata = await Promise.all(promises);
316
312
  const items = metadata
317
313
  .map(function (x) {
318
314
  return x[0];
319
315
  })
320
- .flat();
321
- const tags = metadata.map(function (x) {
322
- return x[1];
323
- });
316
+ .flat()
317
+ .filter(function (x) {
318
+ // Remove undefined items due to transient parsing errors
319
+ return x !== undefined;
320
+ });
321
+ const tags = metadata
322
+ .map(function (x) {
323
+ return x[1];
324
+ })
325
+ .filter(function (x) {
326
+ // Remove undefined tags due to transient parsing errors
327
+ return x !== undefined;
328
+ });
324
329
  return [items as ApiMetadata[], tags as TagObject[]];
325
330
  }
326
331
 
327
332
  export async function processOpenapiFile(
328
- openapiDataWithRefs: OpenApiObjectWithRef,
333
+ openapiData: OpenApiObject,
329
334
  sidebarOptions: SidebarOptions
330
335
  ): Promise<[ApiMetadata[], TagObject[]]> {
331
- const openapiData = await resolveRefs(openapiDataWithRefs);
332
336
  const postmanCollection = await createPostmanCollection(openapiData);
333
337
  const items = createItems(openapiData, sidebarOptions);
334
338
 
@@ -20,6 +20,7 @@ export interface OpenApiObject {
20
20
  security?: SecurityRequirementObject[];
21
21
  tags?: TagObject[];
22
22
  externalDocs?: ExternalDocumentationObject;
23
+ swagger?: string;
23
24
  }
24
25
 
25
26
  export interface OpenApiObjectWithRef {
@@ -325,7 +326,7 @@ export type SchemaObject = Omit<
325
326
  not?: SchemaObject;
326
327
  items?: SchemaObject;
327
328
  properties?: Map<SchemaObject>;
328
- additionalProperties?: boolean | SchemaObject;
329
+ additionalProperties?: Map<SchemaObject>;
329
330
 
330
331
  // OpenAPI additions
331
332
  nullable?: boolean;
@@ -0,0 +1,123 @@
1
+ /* ============================================================================
2
+ * Copyright (c) Palo Alto Networks
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ * ========================================================================== */
7
+
8
+ import $RefParser from "@apidevtools/json-schema-ref-parser";
9
+ import { bundle, Config } from "@redocly/openapi-core";
10
+ import type { Source, Document } from "@redocly/openapi-core";
11
+ import { ResolvedConfig } from "@redocly/openapi-core/lib/config";
12
+ import chalk from "chalk";
13
+ // @ts-ignore
14
+ import { convertObj } from "swagger2openapi";
15
+
16
+ import { OpenApiObject } from "../types";
17
+
18
+ function serializer(replacer: any, cycleReplacer: any) {
19
+ var stack: any = [],
20
+ keys: any = [];
21
+
22
+ if (cycleReplacer === undefined)
23
+ cycleReplacer = function (key: any, value: any) {
24
+ if (stack[0] === value) return "circular()";
25
+ return value.title ? `circular(${value.title})` : "circular()";
26
+ };
27
+
28
+ return function (key: any, value: any) {
29
+ if (stack.length > 0) {
30
+ // @ts-ignore
31
+ var thisPos = stack.indexOf(this);
32
+ // @ts-ignore
33
+ ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
34
+ ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
35
+ // @ts-ignore
36
+ if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value);
37
+ } else stack.push(value);
38
+
39
+ // @ts-ignore
40
+ return replacer === undefined ? value : replacer.call(this, key, value);
41
+ };
42
+ }
43
+
44
+ export function convertSwagger2OpenAPI(spec: object) {
45
+ console.warn(
46
+ "[ReDoc Compatibility mode]: Converting OpenAPI 2.0 to OpenAPI 3.0"
47
+ );
48
+ return new Promise((resolve, reject) =>
49
+ convertObj(
50
+ spec,
51
+ { patch: true, warnOnly: true, text: "{}", anchors: true },
52
+ (err: any, res: any) => {
53
+ // TODO: log any warnings
54
+ if (err) {
55
+ return reject(err);
56
+ }
57
+ resolve(res && res.openapi);
58
+ }
59
+ )
60
+ );
61
+ }
62
+
63
+ async function resolveJsonRefs(specUrlOrObject: object | string) {
64
+ try {
65
+ let schema = await $RefParser.dereference(specUrlOrObject, {
66
+ continueOnError: true,
67
+ resolve: {
68
+ file: true,
69
+ external: true,
70
+ http: {
71
+ timeout: 15000, // 15 sec timeout
72
+ },
73
+ },
74
+ dereference: {
75
+ circular: true,
76
+ },
77
+ });
78
+ return schema as OpenApiObject;
79
+ } catch (err: any) {
80
+ console.error(chalk.yellow(err.errors[0]?.message ?? err));
81
+ return;
82
+ }
83
+ }
84
+
85
+ export async function loadAndResolveSpec(specUrlOrObject: object | string) {
86
+ const config = new Config({} as ResolvedConfig);
87
+ const bundleOpts = {
88
+ config,
89
+ base: process.cwd(),
90
+ } as any;
91
+
92
+ if (typeof specUrlOrObject === "object" && specUrlOrObject !== null) {
93
+ bundleOpts["doc"] = {
94
+ source: { absoluteRef: "" } as Source,
95
+ parsed: specUrlOrObject,
96
+ } as Document;
97
+ } else {
98
+ bundleOpts["ref"] = specUrlOrObject;
99
+ }
100
+
101
+ // Force dereference ?
102
+ // bundleOpts["dereference"] = true;
103
+
104
+ const {
105
+ bundle: { parsed },
106
+ } = await bundle(bundleOpts);
107
+ const resolved = await resolveJsonRefs(parsed);
108
+
109
+ // Force serialization and replace circular $ref pointers
110
+ // @ts-ignore
111
+ const serialized = JSON.stringify(resolved, serializer());
112
+ let decycled;
113
+ try {
114
+ decycled = JSON.parse(serialized);
115
+ } catch (err: any) {
116
+ console.error(chalk.yellow(err));
117
+ }
118
+ return decycled !== undefined && typeof decycled === "object"
119
+ ? decycled.swagger !== undefined
120
+ ? convertSwagger2OpenAPI(decycled)
121
+ : decycled
122
+ : resolved;
123
+ }