@gitbook/react-openapi 0.7.1 → 1.0.1

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 (118) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/InteractiveSection.d.ts +4 -8
  3. package/dist/InteractiveSection.jsx +60 -0
  4. package/dist/Markdown.d.ts +1 -2
  5. package/dist/Markdown.jsx +5 -0
  6. package/dist/OpenAPICodeSample.d.ts +2 -4
  7. package/dist/OpenAPICodeSample.jsx +141 -0
  8. package/dist/OpenAPIDisclosure.d.ts +12 -0
  9. package/dist/OpenAPIDisclosure.jsx +32 -0
  10. package/dist/OpenAPIDisclosureGroup.d.ts +19 -0
  11. package/dist/OpenAPIDisclosureGroup.jsx +81 -0
  12. package/dist/OpenAPIOperation.d.ts +2 -4
  13. package/dist/OpenAPIOperation.jsx +51 -0
  14. package/dist/OpenAPIOperationContext.d.ts +16 -0
  15. package/dist/OpenAPIOperationContext.jsx +26 -0
  16. package/dist/OpenAPIPath.d.ts +8 -0
  17. package/dist/OpenAPIPath.jsx +54 -0
  18. package/dist/OpenAPIRequestBody.d.ts +4 -5
  19. package/dist/OpenAPIRequestBody.jsx +22 -0
  20. package/dist/OpenAPIResponse.d.ts +4 -4
  21. package/dist/OpenAPIResponse.jsx +39 -0
  22. package/dist/OpenAPIResponseExample.d.ts +2 -4
  23. package/dist/OpenAPIResponseExample.jsx +108 -0
  24. package/dist/OpenAPIResponses.d.ts +3 -4
  25. package/dist/OpenAPIResponses.jsx +35 -0
  26. package/dist/OpenAPISchema.d.ts +11 -8
  27. package/dist/OpenAPISchema.jsx +285 -0
  28. package/dist/OpenAPISchemaName.d.ts +12 -0
  29. package/dist/OpenAPISchemaName.jsx +15 -0
  30. package/dist/OpenAPISecurities.d.ts +2 -4
  31. package/dist/OpenAPISecurities.jsx +55 -0
  32. package/dist/OpenAPIServerURL.d.ts +2 -3
  33. package/dist/OpenAPIServerURL.jsx +67 -0
  34. package/dist/OpenAPIServerURLVariable.d.ts +2 -3
  35. package/dist/OpenAPIServerURLVariable.jsx +8 -0
  36. package/dist/OpenAPISpec.d.ts +3 -4
  37. package/dist/OpenAPISpec.jsx +91 -0
  38. package/dist/OpenAPITabs.d.ts +26 -0
  39. package/dist/OpenAPITabs.jsx +103 -0
  40. package/dist/ScalarApiButton.d.ts +3 -3
  41. package/dist/ScalarApiButton.jsx +51 -0
  42. package/dist/code-samples.d.ts +4 -0
  43. package/dist/code-samples.js +103 -38
  44. package/dist/generateSchemaExample.d.ts +2 -2
  45. package/dist/generateSchemaExample.js +29 -102
  46. package/dist/index.d.ts +3 -2
  47. package/dist/index.js +2 -1
  48. package/dist/resolveOpenAPIOperation.d.ts +11 -0
  49. package/dist/resolveOpenAPIOperation.js +194 -0
  50. package/dist/stringifyOpenAPI.d.ts +4 -0
  51. package/dist/stringifyOpenAPI.js +6 -0
  52. package/dist/tsconfig.build.tsbuildinfo +1 -0
  53. package/dist/types.d.ts +11 -12
  54. package/dist/useSyncedTabsGlobalState.d.ts +1 -0
  55. package/dist/useSyncedTabsGlobalState.js +16 -0
  56. package/dist/utils.d.ts +6 -2
  57. package/dist/utils.js +13 -6
  58. package/package.json +12 -10
  59. package/src/InteractiveSection.tsx +90 -86
  60. package/src/Markdown.tsx +2 -3
  61. package/src/OpenAPICodeSample.tsx +43 -31
  62. package/src/OpenAPIDisclosure.tsx +50 -0
  63. package/src/OpenAPIDisclosureGroup.tsx +136 -0
  64. package/src/OpenAPIOperation.tsx +36 -42
  65. package/src/OpenAPIOperationContext.tsx +45 -0
  66. package/src/OpenAPIPath.tsx +65 -0
  67. package/src/OpenAPIRequestBody.tsx +10 -17
  68. package/src/OpenAPIResponse.tsx +27 -45
  69. package/src/OpenAPIResponseExample.tsx +89 -31
  70. package/src/OpenAPIResponses.tsx +48 -17
  71. package/src/OpenAPISchema.test.ts +1 -1
  72. package/src/OpenAPISchema.tsx +129 -108
  73. package/src/OpenAPISchemaName.tsx +27 -0
  74. package/src/OpenAPISecurities.tsx +45 -24
  75. package/src/OpenAPIServerURL.tsx +17 -10
  76. package/src/OpenAPIServerURLVariable.tsx +2 -4
  77. package/src/OpenAPISpec.tsx +58 -58
  78. package/src/OpenAPITabs.tsx +153 -0
  79. package/src/ScalarApiButton.tsx +84 -7
  80. package/src/code-samples.test.ts +51 -0
  81. package/src/code-samples.ts +95 -31
  82. package/src/generateSchemaExample.ts +26 -153
  83. package/src/index.ts +3 -2
  84. package/src/resolveOpenAPIOperation.test.ts +177 -0
  85. package/src/resolveOpenAPIOperation.ts +164 -0
  86. package/src/stringifyOpenAPI.ts +6 -0
  87. package/src/types.ts +17 -10
  88. package/src/useSyncedTabsGlobalState.ts +23 -0
  89. package/src/utils.ts +14 -7
  90. package/dist/InteractiveSection.js +0 -47
  91. package/dist/Markdown.js +0 -6
  92. package/dist/OpenAPICodeSample.js +0 -110
  93. package/dist/OpenAPIOperation.js +0 -38
  94. package/dist/OpenAPIRequestBody.js +0 -18
  95. package/dist/OpenAPIResponse.js +0 -32
  96. package/dist/OpenAPIResponseExample.js +0 -54
  97. package/dist/OpenAPIResponses.js +0 -18
  98. package/dist/OpenAPISchema.js +0 -235
  99. package/dist/OpenAPISchema.test.d.ts +0 -1
  100. package/dist/OpenAPISchema.test.js +0 -91
  101. package/dist/OpenAPISecurities.js +0 -42
  102. package/dist/OpenAPIServerURL.js +0 -51
  103. package/dist/OpenAPIServerURLVariable.js +0 -10
  104. package/dist/OpenAPISpec.js +0 -70
  105. package/dist/ScalarApiButton.js +0 -14
  106. package/dist/fetchOpenAPIOperation.d.ts +0 -72
  107. package/dist/fetchOpenAPIOperation.js +0 -124
  108. package/dist/fetchOpenAPIOperation.test.d.ts +0 -1
  109. package/dist/fetchOpenAPIOperation.test.js +0 -152
  110. package/dist/resolveOpenAPIPath.d.ts +0 -7
  111. package/dist/resolveOpenAPIPath.js +0 -112
  112. package/dist/resolveOpenAPIPath.test.d.ts +0 -1
  113. package/dist/resolveOpenAPIPath.test.js +0 -39
  114. package/dist/tsconfig.tsbuildinfo +0 -1
  115. package/src/fetchOpenAPIOperation.test.ts +0 -185
  116. package/src/fetchOpenAPIOperation.ts +0 -230
  117. package/src/resolveOpenAPIPath.test.ts +0 -60
  118. package/src/resolveOpenAPIPath.ts +0 -145
@@ -1,42 +0,0 @@
1
- import * as React from 'react';
2
- import { InteractiveSection } from './InteractiveSection';
3
- import { Markdown } from './Markdown';
4
- /**
5
- * Present securities authorization that can be used for this operation.
6
- */
7
- export function OpenAPISecurities(props) {
8
- const { securities, context } = props;
9
- if (securities.length === 0) {
10
- return null;
11
- }
12
- return (React.createElement(InteractiveSection, { header: "Authorization", className: "openapi-securities", toggeable: true, defaultOpened: false, toggleCloseIcon: context.icons.chevronDown, toggleOpenIcon: context.icons.chevronRight, tabs: securities.map(([key, security]) => {
13
- return {
14
- key: key,
15
- label: key,
16
- body: (React.createElement(React.Fragment, null,
17
- React.createElement("p", { className: "openapi-securities-label" }, getLabelForType(security)),
18
- security.description ? (React.createElement(Markdown, { source: security.description, className: "openapi-securities-description" })) : null)),
19
- };
20
- }) }));
21
- }
22
- function getLabelForType(security) {
23
- switch (security.type) {
24
- case 'apiKey':
25
- return 'API Key';
26
- case 'http':
27
- if (security.scheme === 'basic') {
28
- return 'Basic Auth';
29
- }
30
- if (security.scheme == 'bearer') {
31
- return `Bearer Token ${security.bearerFormat ? `(${security.bearerFormat})` : ''}`;
32
- }
33
- return 'HTTP';
34
- case 'oauth2':
35
- return 'OAuth2';
36
- case 'openIdConnect':
37
- return 'OpenID Connect';
38
- default:
39
- // @ts-ignore
40
- return security.type;
41
- }
42
- }
@@ -1,51 +0,0 @@
1
- import * as React from 'react';
2
- import { OpenAPIServerURLVariable } from './OpenAPIServerURLVariable';
3
- /**
4
- * Show the url of the server with variables replaced by their default values.
5
- */
6
- export function OpenAPIServerURL(props) {
7
- const { servers } = props;
8
- const server = servers[0];
9
- const parts = parseServerURL(server?.url ?? '');
10
- return (React.createElement("span", null, parts.map((part, i) => {
11
- if (part.kind === 'text') {
12
- return React.createElement("span", { key: i }, part.text);
13
- }
14
- else {
15
- if (!server.variables?.[part.name]) {
16
- return React.createElement("span", { key: i }, `{${part.name}}`);
17
- }
18
- return (React.createElement(OpenAPIServerURLVariable, { key: i, name: part.name, variable: server.variables[part.name] }));
19
- }
20
- })));
21
- }
22
- /**
23
- * Get the default URL for the server.
24
- */
25
- export function getServersURL(servers) {
26
- const server = servers[0];
27
- const parts = parseServerURL(server?.url ?? '');
28
- return parts
29
- .map((part) => {
30
- if (part.kind === 'text') {
31
- return part.text;
32
- }
33
- else {
34
- return server.variables?.[part.name]?.default ?? `{${part.name}}`;
35
- }
36
- })
37
- .join('');
38
- }
39
- function parseServerURL(url) {
40
- const parts = url.split(/{([^}]+)}/g);
41
- const result = [];
42
- for (let i = 0; i < parts.length; i++) {
43
- if (i % 2 === 0) {
44
- result.push({ kind: 'text', text: parts[i] });
45
- }
46
- else {
47
- result.push({ kind: 'variable', name: parts[i] });
48
- }
49
- }
50
- return result;
51
- }
@@ -1,10 +0,0 @@
1
- 'use client';
2
- import * as React from 'react';
3
- import classNames from 'classnames';
4
- /**
5
- * Interactive component to show the value of a server variable and let the user change it.
6
- */
7
- export function OpenAPIServerURLVariable(props) {
8
- const { variable } = props;
9
- return React.createElement("span", { className: classNames('openapi-url-var') }, variable.default);
10
- }
@@ -1,70 +0,0 @@
1
- 'use client';
2
- import * as React from 'react';
3
- import { fromJSON } from './fetchOpenAPIOperation';
4
- import { InteractiveSection } from './InteractiveSection';
5
- import { OpenAPIRequestBody } from './OpenAPIRequestBody';
6
- import { OpenAPIResponses } from './OpenAPIResponses';
7
- import { OpenAPISchemaProperties } from './OpenAPISchema';
8
- import { OpenAPISecurities } from './OpenAPISecurities';
9
- import { noReference } from './utils';
10
- /**
11
- * Client component to render the spec for the request and response.
12
- *
13
- * We use a client component as rendering recursive JSON schema in the server is expensive
14
- * (the entire schema is rendered at once, while the client component only renders the visible part)
15
- */
16
- export function OpenAPISpec(props) {
17
- const { rawData, context } = props;
18
- const parsedData = fromJSON(rawData);
19
- const { operation, securities } = parsedData;
20
- const parameterGroups = groupParameters((operation.parameters || []).map(noReference));
21
- return (React.createElement(React.Fragment, null,
22
- securities.length > 0 ? (React.createElement(OpenAPISecurities, { securities: securities, context: context })) : null,
23
- parameterGroups.map((group) => (React.createElement(InteractiveSection, { key: group.key, className: "openapi-parameters", toggeable: true, toggleOpenIcon: context.icons.chevronRight, toggleCloseIcon: context.icons.chevronDown, header: group.label, defaultOpened: group.key === 'path' || context.defaultInteractiveOpened },
24
- React.createElement(OpenAPISchemaProperties, { properties: group.parameters.map((parameter) => ({
25
- propertyName: parameter.name,
26
- schema: {
27
- // Description of the parameter is defined at the parameter level
28
- // we use display it if the schema doesn't override it
29
- description: parameter.description,
30
- example: parameter.example,
31
- ...(noReference(parameter.schema) ?? {}),
32
- },
33
- required: parameter.required,
34
- })), context: context })))),
35
- operation.requestBody ? (React.createElement(OpenAPIRequestBody, { requestBody: noReference(operation.requestBody), context: context })) : null,
36
- operation.responses ? (React.createElement(OpenAPIResponses, { responses: noReference(operation.responses), context: context })) : null));
37
- }
38
- function groupParameters(parameters) {
39
- const sorted = ['path', 'query', 'header'];
40
- const groups = [];
41
- parameters.forEach((parameter) => {
42
- const key = parameter.in;
43
- const label = getParameterGroupName(parameter.in);
44
- const group = groups.find((group) => group.key === key);
45
- if (group) {
46
- group.parameters.push(parameter);
47
- }
48
- else {
49
- groups.push({
50
- key,
51
- label,
52
- parameters: [parameter],
53
- });
54
- }
55
- });
56
- groups.sort((a, b) => sorted.indexOf(a.key) - sorted.indexOf(b.key));
57
- return groups;
58
- }
59
- function getParameterGroupName(paramIn) {
60
- switch (paramIn) {
61
- case 'path':
62
- return 'Path parameters';
63
- case 'query':
64
- return 'Query parameters';
65
- case 'header':
66
- return 'Header parameters';
67
- default:
68
- return paramIn;
69
- }
70
- }
@@ -1,14 +0,0 @@
1
- 'use client';
2
- import { useApiClientModal } from '@scalar/api-client-react';
3
- import React from 'react';
4
- /**
5
- * Button which launches the Scalar API Client
6
- */
7
- export function ScalarApiButton({ method, path }) {
8
- const client = useApiClientModal();
9
- return (React.createElement("div", { className: "scalar scalar-activate" },
10
- React.createElement("button", { className: "scalar-activate-button", onClick: () => client?.open({ method, path }) },
11
- React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "10", height: "12", fill: "none" },
12
- React.createElement("path", { stroke: "currentColor", strokeWidth: "1.5", d: "M1 10.05V1.43c0-.2.2-.31.37-.22l7.26 4.08c.17.1.17.33.01.43l-7.26 4.54a.25.25 0 0 1-.38-.21Z" })),
13
- "Test it")));
14
- }
@@ -1,72 +0,0 @@
1
- import { toJSON, fromJSON } from 'flatted';
2
- import { OpenAPIV3 } from 'openapi-types';
3
- import { OpenAPIFetcher } from './types';
4
- export interface OpenAPIOperationData extends OpenAPICustomSpecProperties {
5
- path: string;
6
- method: string;
7
- /** Servers to be used for this operation */
8
- servers: OpenAPIV3.ServerObject[];
9
- /** Spec of the operation */
10
- operation: OpenAPIV3.OperationObject & OpenAPICustomOperationProperties;
11
- /** Securities that should be used for this operation */
12
- securities: [string, OpenAPIV3.SecuritySchemeObject][];
13
- }
14
- /**
15
- * Custom properties that can be defined at the entire spec level.
16
- */
17
- export interface OpenAPICustomSpecProperties {
18
- /**
19
- * If `true`, code samples will not be displayed.
20
- * This option can be used to hide code samples for the entire spec.
21
- */
22
- 'x-codeSamples'?: boolean;
23
- /**
24
- * If `true`, the "Try it" button will not be displayed.
25
- * This option can be used to hide code samples for the entire spec.
26
- */
27
- 'x-hideTryItPanel'?: boolean;
28
- }
29
- /**
30
- * Custom properties that can be defined at the operation level.
31
- * These properties are not part of the OpenAPI spec.
32
- */
33
- export interface OpenAPICustomOperationProperties {
34
- 'x-code-samples'?: OpenAPICustomCodeSample[];
35
- 'x-codeSamples'?: OpenAPICustomCodeSample[] | false;
36
- 'x-custom-examples'?: OpenAPICustomCodeSample[];
37
- /**
38
- * If `true`, the "Try it" button will not be displayed.
39
- * https://redocly.com/docs/api-reference-docs/specification-extensions/x-hidetryitpanel/
40
- */
41
- 'x-hideTryItPanel'?: boolean;
42
- }
43
- /**
44
- * Custom code samples that can be defined at the operation level.
45
- * It follows the spec defined by Redocly.
46
- * https://redocly.com/docs/api-reference-docs/specification-extensions/x-code-samples/
47
- */
48
- export interface OpenAPICustomCodeSample {
49
- lang: string;
50
- label: string;
51
- source: string;
52
- }
53
- export { toJSON, fromJSON };
54
- /**
55
- * Resolve an OpenAPI operation in a file and compile it to a more usable format.
56
- */
57
- export declare function fetchOpenAPIOperation(input: {
58
- url: string;
59
- path: string;
60
- method: string;
61
- }, rawFetcher: OpenAPIFetcher): Promise<OpenAPIOperationData | null>;
62
- /**
63
- * Parse a raw string into an OpenAPI document.
64
- * It will also convert Swagger 2.0 to OpenAPI 3.0.
65
- * It can throw an `OpenAPIFetchError` if the document is invalid.
66
- */
67
- export declare function parseOpenAPIV3(url: string, text: string): Promise<OpenAPIV3.Document>;
68
- export declare class OpenAPIFetchError extends Error {
69
- readonly url: string;
70
- name: string;
71
- constructor(message: string, url: string);
72
- }
@@ -1,124 +0,0 @@
1
- import { toJSON, fromJSON } from 'flatted';
2
- import YAML from 'yaml';
3
- import swagger2openapi from 'swagger2openapi';
4
- import { resolveOpenAPIPath } from './resolveOpenAPIPath';
5
- export { toJSON, fromJSON };
6
- /**
7
- * Resolve an OpenAPI operation in a file and compile it to a more usable format.
8
- */
9
- export async function fetchOpenAPIOperation(input, rawFetcher) {
10
- const fetcher = cacheFetcher(rawFetcher);
11
- let operation = await resolveOpenAPIPath(input.url, ['paths', input.path, input.method], fetcher);
12
- if (!operation) {
13
- return null;
14
- }
15
- const specData = await fetcher.fetch(input.url);
16
- // Resolve common parameters
17
- const commonParameters = await resolveOpenAPIPath(input.url, ['paths', input.path, 'parameters'], fetcher);
18
- if (commonParameters) {
19
- operation = {
20
- ...operation,
21
- parameters: [...commonParameters, ...(operation.parameters ?? [])],
22
- };
23
- }
24
- // Resolve servers
25
- const servers = await resolveOpenAPIPath(input.url, ['servers'], fetcher);
26
- // Resolve securities
27
- const securities = [];
28
- for (const security of operation.security ?? []) {
29
- const securityKey = Object.keys(security)[0];
30
- const securityScheme = await resolveOpenAPIPath(input.url, ['components', 'securitySchemes', securityKey], fetcher);
31
- if (securityScheme) {
32
- securities.push([securityKey, securityScheme]);
33
- }
34
- }
35
- return {
36
- servers: servers ?? [],
37
- operation,
38
- method: input.method,
39
- path: input.path,
40
- securities,
41
- 'x-codeSamples': typeof specData['x-codeSamples'] === 'boolean' ? specData['x-codeSamples'] : undefined,
42
- 'x-hideTryItPanel': typeof specData['x-hideTryItPanel'] === 'boolean'
43
- ? specData['x-hideTryItPanel']
44
- : undefined,
45
- };
46
- }
47
- function cacheFetcher(fetcher) {
48
- const cache = new Map();
49
- return {
50
- async fetch(url) {
51
- if (cache.has(url)) {
52
- return cache.get(url);
53
- }
54
- const promise = fetcher.fetch(url);
55
- cache.set(url, promise);
56
- return promise;
57
- },
58
- parseMarkdown: fetcher.parseMarkdown,
59
- };
60
- }
61
- /**
62
- * Parse a raw string into an OpenAPI document.
63
- * It will also convert Swagger 2.0 to OpenAPI 3.0.
64
- * It can throw an `OpenAPIFetchError` if the document is invalid.
65
- */
66
- export async function parseOpenAPIV3(url, text) {
67
- // Parse the JSON or YAML
68
- let data;
69
- // Try with JSON
70
- try {
71
- data = JSON.parse(text);
72
- }
73
- catch (jsonError) {
74
- try {
75
- // Try with YAML
76
- data = YAML.parse(text);
77
- }
78
- catch (yamlError) {
79
- if (yamlError instanceof Error && yamlError.name.startsWith('YAML')) {
80
- throw new OpenAPIFetchError('Failed to parse YAML: ' + yamlError.message, url);
81
- }
82
- else {
83
- throw yamlError;
84
- }
85
- }
86
- }
87
- // Convert Swagger 2.0 to OpenAPI 3.0
88
- // @ts-ignore
89
- if (data && data.swagger) {
90
- try {
91
- // Convert Swagger 2.0 to OpenAPI 3.0
92
- // @ts-ignore
93
- const result = (await swagger2openapi.convertObj(data, {
94
- resolve: false,
95
- resolveInternal: false,
96
- laxDefaults: true,
97
- laxurls: true,
98
- lint: false,
99
- prevalidate: false,
100
- anchors: true,
101
- patch: true,
102
- }));
103
- data = result.openapi;
104
- }
105
- catch (error) {
106
- if (error.name === 'S2OError') {
107
- throw new OpenAPIFetchError('Failed to convert Swagger 2.0 to OpenAPI 3.0: ' + error.message, url);
108
- }
109
- else {
110
- throw error;
111
- }
112
- }
113
- }
114
- // @ts-ignore
115
- return data;
116
- }
117
- export class OpenAPIFetchError extends Error {
118
- url;
119
- name = 'OpenAPIFetchError';
120
- constructor(message, url) {
121
- super(message);
122
- this.url = url;
123
- }
124
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,152 +0,0 @@
1
- import { it, expect } from 'bun:test';
2
- import { fetchOpenAPIOperation, parseOpenAPIV3 } from './fetchOpenAPIOperation';
3
- const fetcher = {
4
- fetch: async (url) => {
5
- const response = await fetch(url);
6
- return parseOpenAPIV3(url, await response.text());
7
- },
8
- };
9
- it('should resolve refs', async () => {
10
- const resolved = await fetchOpenAPIOperation({
11
- url: 'https://petstore3.swagger.io/api/v3/openapi.json',
12
- method: 'put',
13
- path: '/pet',
14
- }, fetcher);
15
- expect(resolved).toMatchObject({
16
- servers: [
17
- {
18
- url: '/api/v3',
19
- },
20
- ],
21
- operation: {
22
- tags: ['pet'],
23
- summary: 'Update an existing pet',
24
- description: 'Update an existing pet by Id',
25
- requestBody: {
26
- content: {
27
- 'application/json': {
28
- schema: {
29
- type: 'object',
30
- required: ['name', 'photoUrls'],
31
- },
32
- },
33
- },
34
- },
35
- },
36
- });
37
- });
38
- it('should support yaml', async () => {
39
- const resolved = await fetchOpenAPIOperation({
40
- url: 'https://petstore3.swagger.io/api/v3/openapi.yaml',
41
- method: 'put',
42
- path: '/pet',
43
- }, fetcher);
44
- expect(resolved).toMatchObject({
45
- servers: [
46
- {
47
- url: '/api/v3',
48
- },
49
- ],
50
- operation: {
51
- tags: ['pet'],
52
- summary: 'Update an existing pet',
53
- description: 'Update an existing pet by Id',
54
- requestBody: {
55
- content: {
56
- 'application/json': {
57
- schema: {
58
- type: 'object',
59
- required: ['name', 'photoUrls'],
60
- },
61
- },
62
- },
63
- },
64
- },
65
- });
66
- });
67
- it('should resolve circular refs', async () => {
68
- const resolved = await fetchOpenAPIOperation({
69
- url: 'https://api.gitbook.com/openapi.json',
70
- method: 'post',
71
- path: '/search/ask',
72
- }, fetcher);
73
- expect(resolved).toMatchObject({
74
- servers: [
75
- {
76
- url: '{host}/v1',
77
- },
78
- ],
79
- operation: {
80
- operationId: 'askQuery',
81
- },
82
- });
83
- });
84
- it('should resolve to null if the method is not supported', async () => {
85
- const resolved = await fetchOpenAPIOperation({
86
- url: 'https://petstore3.swagger.io/api/v3/openapi.json',
87
- method: 'dontexist',
88
- path: '/pet',
89
- }, fetcher);
90
- expect(resolved).toBe(null);
91
- });
92
- it('should parse Swagger 2.0', async () => {
93
- const resolved = await fetchOpenAPIOperation({
94
- url: 'https://petstore.swagger.io/v2/swagger.json',
95
- method: 'put',
96
- path: '/pet',
97
- }, fetcher);
98
- expect(resolved).toMatchObject({
99
- servers: [
100
- {
101
- url: 'https://petstore.swagger.io/v2',
102
- },
103
- {
104
- url: 'http://petstore.swagger.io/v2',
105
- },
106
- ],
107
- operation: {
108
- tags: ['pet'],
109
- summary: 'Update an existing pet',
110
- description: '',
111
- requestBody: {
112
- content: {
113
- 'application/json': {
114
- schema: {
115
- type: 'object',
116
- required: ['name', 'photoUrls'],
117
- },
118
- },
119
- },
120
- },
121
- },
122
- });
123
- });
124
- it('should resolve a ref with whitespace', async () => {
125
- const resolved = await fetchOpenAPIOperation({
126
- url: ' https://petstore3.swagger.io/api/v3/openapi.json',
127
- method: 'put',
128
- path: '/pet',
129
- }, fetcher);
130
- expect(resolved).toMatchObject({
131
- servers: [
132
- {
133
- url: '/api/v3',
134
- },
135
- ],
136
- operation: {
137
- tags: ['pet'],
138
- summary: 'Update an existing pet',
139
- description: 'Update an existing pet by Id',
140
- requestBody: {
141
- content: {
142
- 'application/json': {
143
- schema: {
144
- type: 'object',
145
- required: ['name', 'photoUrls'],
146
- },
147
- },
148
- },
149
- },
150
- },
151
- });
152
- });
@@ -1,7 +0,0 @@
1
- import { OpenAPIFetcher } from './types';
2
- export declare const SYMBOL_REF_RESOLVED = "__$refResolved";
3
- /**
4
- * Resolve a path in a OpenAPI file.
5
- * It resolves any reference needed to resolve the path, ignoring other references outside the path.
6
- */
7
- export declare function resolveOpenAPIPath<T>(url: string, dataPath: string[], fetcher: OpenAPIFetcher): Promise<T | undefined>;
@@ -1,112 +0,0 @@
1
- const SYMBOL_MARKDOWN_PARSED = '__$markdownParsed';
2
- export const SYMBOL_REF_RESOLVED = '__$refResolved';
3
- /**
4
- * Resolve a path in a OpenAPI file.
5
- * It resolves any reference needed to resolve the path, ignoring other references outside the path.
6
- */
7
- export async function resolveOpenAPIPath(url, dataPath, fetcher) {
8
- const data = await fetcher.fetch(url);
9
- let value = data;
10
- if (!value) {
11
- return undefined;
12
- }
13
- const lastKey = dataPath[dataPath.length - 1];
14
- dataPath = dataPath.slice(0, -1);
15
- for (const part of dataPath) {
16
- // @ts-ignore
17
- if (isRef(value[part])) {
18
- await transformAll(url, value, part, fetcher);
19
- }
20
- // @ts-ignore
21
- value = value[part];
22
- // If any part along the path is undefined, return undefined.
23
- if (typeof value !== 'object' || value === null) {
24
- return undefined;
25
- }
26
- }
27
- await transformAll(url, value, lastKey, fetcher);
28
- // @ts-expect-error
29
- return value[lastKey];
30
- }
31
- /**
32
- * Recursively process a part of the OpenAPI spec to resolve all references.
33
- */
34
- async function transformAll(url, data, key, fetcher) {
35
- const value = data[key];
36
- if (typeof value === 'string' &&
37
- key === 'description' &&
38
- fetcher.parseMarkdown &&
39
- !data[SYMBOL_MARKDOWN_PARSED]) {
40
- // Parse markdown
41
- data[SYMBOL_MARKDOWN_PARSED] = true;
42
- data[key] = await fetcher.parseMarkdown(value);
43
- }
44
- else if (typeof value === 'string' ||
45
- typeof value === 'number' ||
46
- typeof value === 'boolean' ||
47
- value === null) {
48
- // Primitives
49
- }
50
- else if (typeof value === 'object' && value !== null && SYMBOL_REF_RESOLVED in value) {
51
- // Ref was already resolved
52
- }
53
- else if (isRef(value)) {
54
- const ref = value.$ref;
55
- // Delete the ref to avoid infinite loop with circular references
56
- // @ts-ignore
57
- delete value.$ref;
58
- data[key] = await resolveReference(url, ref, fetcher);
59
- if (data[key]) {
60
- data[key][SYMBOL_REF_RESOLVED] = extractRefName(ref);
61
- }
62
- }
63
- else if (Array.isArray(value)) {
64
- // Recursively resolve all references in the array
65
- await Promise.all(value.map((item, index) => transformAll(url, value, index, fetcher)));
66
- }
67
- else if (typeof value === 'object' && value !== null) {
68
- // Recursively resolve all references in the object
69
- const keys = Object.keys(value);
70
- for (const key of keys) {
71
- await transformAll(url, value, key, fetcher);
72
- }
73
- }
74
- }
75
- async function resolveReference(origin, ref, fetcher) {
76
- const parsed = parseReference(origin, ref);
77
- return resolveOpenAPIPath(parsed.url, parsed.dataPath, fetcher);
78
- }
79
- function parseReference(origin, ref) {
80
- if (!ref) {
81
- return {
82
- url: origin,
83
- dataPath: [],
84
- };
85
- }
86
- if (ref.startsWith('#')) {
87
- // Local references
88
- const dataPath = ref.split('/').filter(Boolean).slice(1);
89
- return {
90
- url: origin,
91
- dataPath,
92
- };
93
- }
94
- // Absolute references
95
- const url = new URL(ref, origin);
96
- if (url.hash) {
97
- const hash = url.hash;
98
- url.hash = '';
99
- return parseReference(url.toString(), hash);
100
- }
101
- return {
102
- url: url.toString(),
103
- dataPath: [],
104
- };
105
- }
106
- function extractRefName(ref) {
107
- const parts = ref.split('/');
108
- return parts[parts.length - 1];
109
- }
110
- function isRef(ref) {
111
- return typeof ref === 'object' && ref !== null && '$ref' in ref && ref.$ref;
112
- }
@@ -1 +0,0 @@
1
- export {};