@jpmorganchase/elemental 7.0.1 → 8.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.
package/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isHttpOperation, isHttpWebhookOperation, isHttpService, HttpMethodColors, DeprecatedBadge, ParsedDocs, TryItWithRequestSamples, Docs, ResponsiveSidebarLayout, ElementsOptionsProvider, SidebarLayout, Logo, TableOfContents, PoweredByLink, slugify, withRouter, withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider, useResponsiveLayout, useParsedValue, useBundleRefsIntoDocument, NonIdealState, InlineRefResolverProvider } from '@jpmorganchase/elemental-core';
1
+ import { isHttpOperation, isHttpWebhookOperation, isHttpService, resolveUrl, HttpMethodColors, DeprecatedBadge, ParsedDocs, TryItWithRequestSamples, Docs, resolveRelativeLink, ResponsiveSidebarLayout, ElementsOptionsProvider, SidebarLayout, Logo, TableOfContents, PoweredByLink, slugify, withRouter, withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider, useResponsiveLayout, useParsedValue, useBundleRefsIntoDocument, NonIdealState, InlineRefResolverProvider } from '@jpmorganchase/elemental-core';
2
2
  import { Box, Flex, Icon, Tabs, TabList, Tab, TabPanels, TabPanel, Heading } from '@stoplight/mosaic';
3
3
  import { NodeType } from '@stoplight/types';
4
4
  import cn from 'classnames';
@@ -6,7 +6,7 @@ import * as React from 'react';
6
6
  import defaults from 'lodash/defaults.js';
7
7
  import flow from 'lodash/flow.js';
8
8
  import { useQuery } from 'react-query';
9
- import { useLocation, Redirect, Link } from 'react-router-dom';
9
+ import { useLocation, Navigate, Link } from 'react-router-dom';
10
10
  import { safeStringify } from '@stoplight/yaml';
11
11
  import saver from 'file-saver';
12
12
  import { OPERATION_CONFIG, WEBHOOK_CONFIG } from '@stoplight/http-spec/oas';
@@ -17,648 +17,685 @@ import get from 'lodash/get.js';
17
17
  import isObject from 'lodash/isObject.js';
18
18
  import last from 'lodash/last.js';
19
19
 
20
- function computeTagGroups(serviceNode, nodeType) {
21
- const groupsByTagId = {};
22
- const ungrouped = [];
23
- const lowerCaseServiceTags = serviceNode.tags.map(tn => tn.toLowerCase());
24
- const groupableNodes = serviceNode.children.filter(n => n.type === nodeType);
25
- for (const node of groupableNodes) {
26
- const tagName = node.tags[0];
27
- if (tagName) {
28
- const tagId = tagName.toLowerCase();
29
- if (groupsByTagId[tagId]) {
30
- groupsByTagId[tagId].items.push(node);
31
- }
32
- else {
33
- const serviceTagIndex = lowerCaseServiceTags.findIndex(tn => tn === tagId);
34
- const serviceTagName = serviceNode.tags[serviceTagIndex];
35
- groupsByTagId[tagId] = {
36
- title: serviceTagName || tagName,
37
- items: [node],
38
- };
39
- }
40
- }
41
- else {
42
- ungrouped.push(node);
43
- }
44
- }
45
- const orderedTagGroups = Object.entries(groupsByTagId)
46
- .sort(([g1], [g2]) => {
47
- const g1LC = g1.toLowerCase();
48
- const g2LC = g2.toLowerCase();
49
- const g1Idx = lowerCaseServiceTags.findIndex(tn => tn === g1LC);
50
- const g2Idx = lowerCaseServiceTags.findIndex(tn => tn === g2LC);
51
- if (g1Idx < 0 && g2Idx < 0)
52
- return 0;
53
- if (g1Idx < 0)
54
- return 1;
55
- if (g2Idx < 0)
56
- return -1;
57
- return g1Idx - g2Idx;
58
- })
59
- .map(([, tagGroup]) => tagGroup);
60
- return { groups: orderedTagGroups, ungrouped };
61
- }
62
- const defaultComputerAPITreeConfig = {
63
- hideSchemas: false,
64
- hideInternal: false,
65
- };
66
- const computeAPITree = (serviceNode, config = {}) => {
67
- const mergedConfig = defaults(config, defaultComputerAPITreeConfig);
68
- const tree = [];
69
- tree.push({
70
- id: '/',
71
- slug: '/',
72
- title: 'Overview',
73
- type: 'overview',
74
- meta: '',
75
- });
76
- const hasOperationNodes = serviceNode.children.some(node => node.type === NodeType.HttpOperation);
77
- if (hasOperationNodes) {
78
- tree.push({
79
- title: 'Endpoints',
80
- });
81
- const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.HttpOperation);
82
- addTagGroupsToTree(groups, ungrouped, tree, NodeType.HttpOperation, mergedConfig.hideInternal);
83
- }
84
- const hasWebhookNodes = serviceNode.children.some(node => node.type === NodeType.HttpWebhook);
85
- if (hasWebhookNodes) {
86
- tree.push({
87
- title: 'Webhooks',
88
- });
89
- const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.HttpWebhook);
90
- addTagGroupsToTree(groups, ungrouped, tree, NodeType.HttpWebhook, mergedConfig.hideInternal);
91
- }
92
- let schemaNodes = serviceNode.children.filter(node => node.type === NodeType.Model);
93
- if (mergedConfig.hideInternal) {
94
- schemaNodes = schemaNodes.filter(n => !isInternal(n));
95
- }
96
- if (!mergedConfig.hideSchemas && schemaNodes.length) {
97
- tree.push({
98
- title: 'Schemas',
99
- });
100
- const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.Model);
101
- addTagGroupsToTree(groups, ungrouped, tree, NodeType.Model, mergedConfig.hideInternal);
102
- }
103
- return tree;
104
- };
105
- const findFirstNodeSlug = (tree) => {
106
- for (const item of tree) {
107
- if ('slug' in item) {
108
- return item.slug;
109
- }
110
- if ('items' in item) {
111
- const slug = findFirstNodeSlug(item.items);
112
- if (slug) {
113
- return slug;
114
- }
115
- }
116
- }
117
- return;
118
- };
119
- const isInternal = (node) => {
120
- const data = node.data;
121
- if (isHttpOperation(data) || isHttpWebhookOperation(data)) {
122
- return !!data.internal;
123
- }
124
- if (isHttpService(data)) {
125
- return false;
126
- }
127
- return !!data['x-internal'];
128
- };
129
- const addTagGroupsToTree = (groups, ungrouped, tree, itemsType, hideInternal) => {
130
- ungrouped.forEach(node => {
131
- if (hideInternal && isInternal(node)) {
132
- return;
133
- }
134
- tree.push({
135
- id: node.uri,
136
- slug: node.uri,
137
- title: node.name,
138
- type: node.type,
139
- meta: isHttpOperation(node.data) || isHttpWebhookOperation(node.data) ? node.data.method : '',
140
- });
141
- });
142
- groups.forEach(group => {
143
- const items = group.items.flatMap(node => {
144
- if (hideInternal && isInternal(node)) {
145
- return [];
146
- }
147
- return {
148
- id: node.uri,
149
- slug: node.uri,
150
- title: node.name,
151
- type: node.type,
152
- meta: isHttpOperation(node.data) || isHttpWebhookOperation(node.data) ? node.data.method : '',
153
- };
154
- });
155
- if (items.length > 0) {
156
- tree.push({
157
- title: group.title,
158
- items,
159
- itemsType,
160
- });
161
- }
162
- });
20
+ function computeTagGroups(serviceNode, nodeType) {
21
+ const groupsByTagId = {};
22
+ const ungrouped = [];
23
+ const lowerCaseServiceTags = serviceNode.tags.map(tn => tn.toLowerCase());
24
+ const groupableNodes = serviceNode.children.filter(n => n.type === nodeType);
25
+ for (const node of groupableNodes) {
26
+ for (const tagName of node.tags) {
27
+ const tagId = tagName.toLowerCase();
28
+ if (groupsByTagId[tagId]) {
29
+ groupsByTagId[tagId].items.push(node);
30
+ }
31
+ else {
32
+ const serviceTagIndex = lowerCaseServiceTags.findIndex(tn => tn === tagId);
33
+ const serviceTagName = serviceNode.tags[serviceTagIndex];
34
+ groupsByTagId[tagId] = {
35
+ title: serviceTagName || tagName,
36
+ items: [node],
37
+ };
38
+ }
39
+ }
40
+ if (node.tags.length === 0) {
41
+ ungrouped.push(node);
42
+ }
43
+ }
44
+ const orderedTagGroups = Object.entries(groupsByTagId)
45
+ .sort(([g1], [g2]) => {
46
+ const g1LC = g1.toLowerCase();
47
+ const g2LC = g2.toLowerCase();
48
+ const g1Idx = lowerCaseServiceTags.findIndex(tn => tn === g1LC);
49
+ const g2Idx = lowerCaseServiceTags.findIndex(tn => tn === g2LC);
50
+ if (g1Idx < 0 && g2Idx < 0)
51
+ return 0;
52
+ if (g1Idx < 0)
53
+ return 1;
54
+ if (g2Idx < 0)
55
+ return -1;
56
+ return g1Idx - g2Idx;
57
+ })
58
+ .map(([, tagGroup]) => tagGroup);
59
+ return { groups: orderedTagGroups, ungrouped };
60
+ }
61
+ const defaultComputerAPITreeConfig = {
62
+ hideSchemas: false,
63
+ hideInternal: false,
64
+ };
65
+ const computeAPITree = (serviceNode, config = {}) => {
66
+ const mergedConfig = defaults(config, defaultComputerAPITreeConfig);
67
+ const tree = [];
68
+ tree.push({
69
+ id: '/',
70
+ slug: '/',
71
+ title: 'Overview',
72
+ type: 'overview',
73
+ meta: '',
74
+ });
75
+ const hasOperationNodes = serviceNode.children.some(node => node.type === NodeType.HttpOperation);
76
+ if (hasOperationNodes) {
77
+ tree.push({
78
+ title: 'Endpoints',
79
+ });
80
+ const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.HttpOperation);
81
+ addTagGroupsToTree(groups, ungrouped, tree, NodeType.HttpOperation, mergedConfig.hideInternal);
82
+ }
83
+ const hasWebhookNodes = serviceNode.children.some(node => node.type === NodeType.HttpWebhook);
84
+ if (hasWebhookNodes) {
85
+ tree.push({
86
+ title: 'Webhooks',
87
+ });
88
+ const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.HttpWebhook);
89
+ addTagGroupsToTree(groups, ungrouped, tree, NodeType.HttpWebhook, mergedConfig.hideInternal);
90
+ }
91
+ let schemaNodes = serviceNode.children.filter(node => node.type === NodeType.Model);
92
+ if (mergedConfig.hideInternal) {
93
+ schemaNodes = schemaNodes.filter(n => !isInternal(n));
94
+ }
95
+ if (!mergedConfig.hideSchemas && schemaNodes.length) {
96
+ tree.push({
97
+ title: 'Schemas',
98
+ });
99
+ const { groups, ungrouped } = computeTagGroups(serviceNode, NodeType.Model);
100
+ addTagGroupsToTree(groups, ungrouped, tree, NodeType.Model, mergedConfig.hideInternal);
101
+ }
102
+ return tree;
103
+ };
104
+ const findFirstNodeSlug = (tree) => {
105
+ for (const item of tree) {
106
+ if ('slug' in item) {
107
+ return item.slug;
108
+ }
109
+ if ('items' in item) {
110
+ const slug = findFirstNodeSlug(item.items);
111
+ if (slug) {
112
+ return slug;
113
+ }
114
+ }
115
+ }
116
+ return;
117
+ };
118
+ const isInternal = (node) => {
119
+ const data = node.data;
120
+ if (isHttpOperation(data) || isHttpWebhookOperation(data)) {
121
+ return !!data.internal;
122
+ }
123
+ if (isHttpService(data)) {
124
+ return false;
125
+ }
126
+ return !!data['x-internal'];
127
+ };
128
+ const addTagGroupsToTree = (groups, ungrouped, tree, itemsType, hideInternal) => {
129
+ ungrouped.forEach(node => {
130
+ if (hideInternal && isInternal(node)) {
131
+ return;
132
+ }
133
+ tree.push({
134
+ id: node.uri,
135
+ slug: node.uri,
136
+ title: node.name,
137
+ type: node.type,
138
+ meta: isHttpOperation(node.data) || isHttpWebhookOperation(node.data) ? node.data.method : '',
139
+ });
140
+ });
141
+ groups.forEach(group => {
142
+ const items = group.items.flatMap(node => {
143
+ if (hideInternal && isInternal(node)) {
144
+ return [];
145
+ }
146
+ return {
147
+ id: node.uri,
148
+ slug: node.uri,
149
+ title: node.name,
150
+ type: node.type,
151
+ meta: isHttpOperation(node.data) || isHttpWebhookOperation(node.data) ? node.data.method : '',
152
+ };
153
+ });
154
+ if (items.length > 0) {
155
+ tree.push({
156
+ title: group.title,
157
+ items,
158
+ itemsType,
159
+ });
160
+ }
161
+ });
162
+ };
163
+ const resolveRelativePath = (currentPath, basePath, outerRouter) => {
164
+ if (!outerRouter || !basePath || basePath === '/') {
165
+ return currentPath;
166
+ }
167
+ const baseUrl = resolveUrl(basePath);
168
+ const currentUrl = resolveUrl(currentPath);
169
+ return baseUrl && currentUrl && baseUrl !== currentUrl ? currentUrl.replace(baseUrl, '') : '/';
163
170
  };
164
171
 
165
- const itemUriMatchesPathname = (itemUri, pathname) => itemUri === pathname;
166
- const TryItContext = React.createContext({
167
- hideTryIt: false,
168
- tryItCredentialsPolicy: 'omit',
169
- });
170
- TryItContext.displayName = 'TryItContext';
171
- const LocationContext = React.createContext({
172
- location: {
173
- hash: '',
174
- key: '',
175
- pathname: '',
176
- search: '',
177
- state: '',
178
- },
179
- });
180
- LocationContext.displayName = 'LocationContext';
181
- const APIWithStackedLayout = ({ serviceNode, hideTryIt, hideExport, hideInlineExamples, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, showPoweredByLink = true, location, tryItOutDefaultServer, }) => {
182
- const { groups: operationGroups } = computeTagGroups(serviceNode, NodeType.HttpOperation);
183
- const { groups: webhookGroups } = computeTagGroups(serviceNode, NodeType.HttpWebhook);
184
- return (React.createElement(LocationContext.Provider, { value: { location } },
185
- React.createElement(TryItContext.Provider, { value: {
186
- hideTryIt,
187
- tryItCredentialsPolicy,
188
- corsProxy: tryItCorsProxy,
189
- hideInlineExamples,
190
- tryItOutDefaultServer,
191
- } },
192
- React.createElement(Flex, { w: "full", flexDirection: "col", m: "auto", className: "sl-max-w-4xl" },
193
- React.createElement(Box, { w: "full", borderB: true },
194
- React.createElement(Docs, { className: "sl-mx-auto", nodeData: serviceNode.data, nodeTitle: serviceNode.name, nodeType: NodeType.HttpService, location: location, layoutOptions: { showPoweredByLink, hideExport }, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer })),
195
- operationGroups.length > 0 && webhookGroups.length > 0 ? React.createElement(Heading, { size: 2 }, "Endpoints") : null,
196
- operationGroups.map(group => (React.createElement(Group, { key: group.title, group: group }))),
197
- webhookGroups.length > 0 ? React.createElement(Heading, { size: 2 }, "Webhooks") : null,
198
- webhookGroups.map(group => (React.createElement(Group, { key: group.title, group: group })))))));
199
- };
200
- APIWithStackedLayout.displayName = 'APIWithStackedLayout';
201
- const Group = React.memo(({ group }) => {
202
- const [isExpanded, setIsExpanded] = React.useState(false);
203
- const { location: { pathname }, } = React.useContext(LocationContext);
204
- const onClick = React.useCallback(() => setIsExpanded(!isExpanded), [isExpanded]);
205
- const shouldExpand = React.useMemo(() => {
206
- return group.items.some(item => itemUriMatchesPathname(item.uri, pathname));
207
- }, [group, pathname]);
208
- React.useEffect(() => {
209
- if (shouldExpand) {
210
- setIsExpanded(true);
211
- }
212
- }, [shouldExpand]);
213
- return (React.createElement(Box, null,
214
- React.createElement(Flex, { onClick: onClick, mx: "auto", justifyContent: "between", alignItems: "center", borderB: true, px: 2, py: 4, cursor: "pointer", color: { default: 'current', hover: 'muted' } },
215
- React.createElement(Box, { fontSize: "lg", fontWeight: "medium" }, group.title),
216
- React.createElement(Icon, { className: "sl-mr-2", icon: isExpanded ? 'chevron-down' : 'chevron-right', size: "sm" })),
217
- React.createElement(Collapse, { isOpen: isExpanded }, group.items.map(item => {
218
- return React.createElement(Item, { key: item.uri, item: item });
219
- }))));
220
- });
221
- Group.displayName = 'Group';
222
- const Item = React.memo(({ item }) => {
223
- const { location } = React.useContext(LocationContext);
224
- const { pathname } = location;
225
- const [isExpanded, setIsExpanded] = React.useState(false);
226
- const scrollRef = React.useRef(null);
227
- const color = HttpMethodColors[item.data.method] || 'gray';
228
- const isDeprecated = !!item.data.deprecated;
229
- const { hideTryIt, hideInlineExamples, tryItCredentialsPolicy, corsProxy, tryItOutDefaultServer } = React.useContext(TryItContext);
230
- const onClick = React.useCallback(() => {
231
- setIsExpanded(!isExpanded);
232
- if (window && window.location) {
233
- window.history.pushState(null, '', `#${item.uri}`);
234
- }
235
- }, [isExpanded, item]);
236
- React.useEffect(() => {
237
- if (itemUriMatchesPathname(item.uri, pathname)) {
238
- setIsExpanded(true);
239
- if (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) {
240
- scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current.scrollIntoView();
241
- }
242
- }
243
- }, [pathname, item]);
244
- return (React.createElement(Box, { ref: scrollRef, w: "full", my: 2, border: true, borderColor: { default: isExpanded ? 'light' : 'transparent', hover: 'light' }, bg: { default: isExpanded ? 'code' : 'transparent', hover: 'code' } },
245
- React.createElement(Flex, { mx: "auto", alignItems: "center", cursor: "pointer", fontSize: "lg", p: 2, onClick: onClick, color: "current" },
246
- React.createElement(Box, { w: 24, textTransform: "uppercase", textAlign: "center", fontWeight: "semibold", border: true, rounded: true, px: 2, bg: "canvas", className: cn(`sl-mr-5 sl-text-base`, `sl-text-${color}`, `sl-border-${color}`) }, item.data.method || 'UNKNOWN'),
247
- React.createElement(Box, { flex: 1, fontWeight: "medium", wordBreak: "all" }, item.type === NodeType.HttpOperation ? item.data.path : item.name),
248
- isDeprecated && React.createElement(DeprecatedBadge, null)),
249
- React.createElement(Collapse, { isOpen: isExpanded },
250
- React.createElement(Box, { flex: 1, p: 2, fontWeight: "medium", mx: "auto", fontSize: "xl" }, item.name),
251
- hideTryIt ? (React.createElement(Box, { as: ParsedDocs, layoutOptions: { noHeading: true, hideTryItPanel: true }, node: item, p: 4 })) : (React.createElement(Tabs, { appearance: "line" },
252
- React.createElement(TabList, null,
253
- React.createElement(Tab, null, "Docs"),
254
- React.createElement(Tab, null, "TryIt")),
255
- React.createElement(TabPanels, null,
256
- React.createElement(TabPanel, null,
257
- React.createElement(ParsedDocs, { className: "sl-px-4", node: item, location: location, layoutOptions: { noHeading: true, hideTryItPanel: true } })),
258
- React.createElement(TabPanel, null,
259
- React.createElement(TryItWithRequestSamples, { httpOperation: item.data, hideInlineExamples: hideInlineExamples, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItOutDefaultServer: tryItOutDefaultServer, corsProxy: corsProxy }))))))));
260
- });
261
- Item.displayName = 'Item';
262
- const Collapse = ({ isOpen, children }) => {
263
- if (!isOpen)
264
- return null;
265
- return React.createElement(Box, null, children);
266
- };
172
+ const itemUriMatchesPathname = (itemUri, pathname) => itemUri === pathname;
173
+ const TryItContext = React.createContext({
174
+ hideTryIt: false,
175
+ hideTryItPanel: false,
176
+ hideSamples: false,
177
+ tryItCredentialsPolicy: 'omit',
178
+ });
179
+ TryItContext.displayName = 'TryItContext';
180
+ const LocationContext = React.createContext({
181
+ location: {
182
+ hash: '',
183
+ key: '',
184
+ pathname: '',
185
+ search: '',
186
+ state: '',
187
+ },
188
+ });
189
+ LocationContext.displayName = 'LocationContext';
190
+ const APIWithStackedLayout = ({ serviceNode, hideTryItPanel, hideTryIt, hideSamples, hideExport, hideSecurityInfo, hideServerInfo, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, showPoweredByLink = true, location, hideInlineExamples, tryItOutDefaultServer, }) => {
191
+ const { groups: operationGroups } = computeTagGroups(serviceNode, NodeType.HttpOperation);
192
+ const { groups: webhookGroups } = computeTagGroups(serviceNode, NodeType.HttpWebhook);
193
+ return (React.createElement(LocationContext.Provider, { value: { location } },
194
+ React.createElement(TryItContext.Provider, { value: {
195
+ hideTryItPanel,
196
+ hideTryIt,
197
+ hideSamples,
198
+ tryItCredentialsPolicy,
199
+ corsProxy: tryItCorsProxy,
200
+ hideInlineExamples,
201
+ tryItOutDefaultServer,
202
+ } },
203
+ React.createElement(Flex, { w: "full", flexDirection: "col", m: "auto", className: "sl-max-w-4xl" },
204
+ React.createElement(Box, { w: "full", borderB: true },
205
+ React.createElement(Docs, { className: "sl-mx-auto", nodeData: serviceNode.data, nodeTitle: serviceNode.name, nodeType: NodeType.HttpService, location: location, layoutOptions: { showPoweredByLink, hideExport, hideSecurityInfo, hideServerInfo }, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer })),
206
+ operationGroups.length > 0 && webhookGroups.length > 0 ? React.createElement(Heading, { size: 2 }, "Endpoints") : null,
207
+ operationGroups.map(group => (React.createElement(Group, { key: group.title, group: group }))),
208
+ webhookGroups.length > 0 ? React.createElement(Heading, { size: 2 }, "Webhooks") : null,
209
+ webhookGroups.map(group => (React.createElement(Group, { key: group.title, group: group })))))));
210
+ };
211
+ APIWithStackedLayout.displayName = 'APIWithStackedLayout';
212
+ const Group = React.memo(({ group }) => {
213
+ const [isExpanded, setIsExpanded] = React.useState(false);
214
+ const { location: { pathname }, } = React.useContext(LocationContext);
215
+ const onClick = React.useCallback(() => setIsExpanded(!isExpanded), [isExpanded]);
216
+ const shouldExpand = React.useMemo(() => {
217
+ return group.items.some(item => itemUriMatchesPathname(item.uri, pathname));
218
+ }, [group, pathname]);
219
+ React.useEffect(() => {
220
+ if (shouldExpand) {
221
+ setIsExpanded(true);
222
+ }
223
+ }, [shouldExpand]);
224
+ return (React.createElement(Box, null,
225
+ React.createElement(Flex, { onClick: onClick, mx: "auto", justifyContent: "between", alignItems: "center", borderB: true, px: 2, py: 4, cursor: "pointer", color: { default: 'current', hover: 'muted' } },
226
+ React.createElement(Box, { fontSize: "lg", fontWeight: "medium" }, group.title),
227
+ React.createElement(Icon, { className: "sl-mr-2", icon: isExpanded ? 'chevron-down' : 'chevron-right', size: "sm" })),
228
+ React.createElement(Collapse, { isOpen: isExpanded }, group.items.map(item => {
229
+ return React.createElement(Item, { key: item.uri, item: item });
230
+ }))));
231
+ });
232
+ Group.displayName = 'Group';
233
+ const Item = React.memo(({ item }) => {
234
+ const { location } = React.useContext(LocationContext);
235
+ const { pathname } = location;
236
+ const [isExpanded, setIsExpanded] = React.useState(false);
237
+ const scrollRef = React.useRef(null);
238
+ const color = HttpMethodColors[item.data.method] || 'gray';
239
+ const isDeprecated = !!item.data.deprecated;
240
+ const { hideTryIt, hideSamples, hideTryItPanel, tryItCredentialsPolicy, corsProxy, hideInlineExamples, tryItOutDefaultServer, } = React.useContext(TryItContext);
241
+ const onClick = React.useCallback(() => {
242
+ setIsExpanded(!isExpanded);
243
+ if (window && window.location) {
244
+ window.history.pushState(null, '', `#${item.uri}`);
245
+ }
246
+ }, [isExpanded, item]);
247
+ React.useEffect(() => {
248
+ if (itemUriMatchesPathname(item.uri, pathname)) {
249
+ setIsExpanded(true);
250
+ if (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current) {
251
+ scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current.scrollIntoView();
252
+ }
253
+ }
254
+ }, [pathname, item]);
255
+ return (React.createElement(Box, { ref: scrollRef, w: "full", my: 2, border: true, borderColor: { default: isExpanded ? 'light' : 'transparent', hover: 'light' }, bg: { default: isExpanded ? 'code' : 'transparent', hover: 'code' } },
256
+ React.createElement(Flex, { mx: "auto", alignItems: "center", cursor: "pointer", fontSize: "lg", p: 2, onClick: onClick, color: "current" },
257
+ React.createElement(Box, { w: 24, textTransform: "uppercase", textAlign: "center", fontWeight: "semibold", border: true, rounded: true, px: 2, bg: "canvas", className: cn(`sl-mr-5 sl-text-base`, `sl-text-${color}`, `sl-border-${color}`) }, item.data.method || 'UNKNOWN'),
258
+ React.createElement(Box, { flex: 1, fontWeight: "medium", wordBreak: "all" }, item.type === NodeType.HttpOperation ? item.data.path : item.name),
259
+ isDeprecated && React.createElement(DeprecatedBadge, null)),
260
+ React.createElement(Collapse, { isOpen: isExpanded },
261
+ React.createElement(Box, { flex: 1, p: 2, fontWeight: "medium", mx: "auto", fontSize: "xl" }, item.name),
262
+ hideTryItPanel ? (React.createElement(Box, { as: ParsedDocs, layoutOptions: { noHeading: true, hideTryItPanel: true, hideSamples, hideTryIt }, node: item, p: 4 })) : (React.createElement(Tabs, { appearance: "line" },
263
+ React.createElement(TabList, null,
264
+ React.createElement(Tab, null, "Docs"),
265
+ React.createElement(Tab, null, "TryIt")),
266
+ React.createElement(TabPanels, null,
267
+ React.createElement(TabPanel, null,
268
+ React.createElement(ParsedDocs, { className: "sl-px-4", node: item, location: location, layoutOptions: { noHeading: true, hideTryItPanel: false, hideSamples, hideTryIt, hideInlineExamples: hideInlineExamples }, tryItOutDefaultServer: tryItOutDefaultServer })),
269
+ React.createElement(TabPanel, null,
270
+ React.createElement(TryItWithRequestSamples, { httpOperation: item.data, hideInlineExamples: hideInlineExamples, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItOutDefaultServer: tryItOutDefaultServer, corsProxy: corsProxy, hideSamples: hideSamples, hideTryIt: hideTryIt }))))))));
271
+ });
272
+ Item.displayName = 'Item';
273
+ const Collapse = ({ isOpen, children }) => {
274
+ if (!isOpen)
275
+ return null;
276
+ return React.createElement(Box, null, children);
277
+ };
267
278
  Collapse.displayName = 'Collapse';
268
279
 
269
- const APIWithResponsiveSidebarLayout = ({ serviceNode, logo, hideTryIt, compact, hideSchemas, hideInternal, hideExport, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, }) => {
270
- const container = React.useRef(null);
271
- const tree = React.useMemo(() => computeAPITree(serviceNode, { hideSchemas, hideInternal }), [serviceNode, hideSchemas, hideInternal]);
272
- const location = useLocation();
273
- const { pathname } = location;
274
- const isRootPath = !pathname || pathname === '/';
275
- const node = isRootPath ? serviceNode : serviceNode.children.find(child => child.uri === pathname);
276
- const layoutOptions = React.useMemo(() => ({ hideTryIt: hideTryIt, compact: compact, hideExport: hideExport || (node === null || node === void 0 ? void 0 : node.type) !== NodeType.HttpService }), [hideTryIt, hideExport, node, compact]);
277
- if (!node) {
278
- const firstSlug = findFirstNodeSlug(tree);
279
- if (firstSlug) {
280
- return React.createElement(Redirect, { to: firstSlug });
281
- }
282
- }
283
- if (hideInternal && node && isInternal(node)) {
284
- return React.createElement(Redirect, { to: "/" });
285
- }
286
- const handleTocClick = () => {
287
- if (container.current) {
288
- container.current.scrollIntoView();
289
- }
290
- };
291
- return (React.createElement(ResponsiveSidebarLayout, { onTocClick: handleTocClick, tree: tree, logo: logo !== null && logo !== void 0 ? logo : serviceNode.data.logo, ref: container, name: serviceNode.name }, node && (React.createElement(ElementsOptionsProvider, { renderExtensionAddon: renderExtensionAddon },
292
- React.createElement(ParsedDocs, { key: pathname, uri: pathname, node: node, nodeTitle: node.name, layoutOptions: layoutOptions, location: location, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon })))));
280
+ const APIWithResponsiveSidebarLayout = ({ serviceNode, logo, hideTryItPanel, hideTryIt, hideSamples, compact, hideSchemas, hideInternal, hideExport, hideInlineExamples = false, hideServerInfo, hideSecurityInfo, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, basePath = '/', outerRouter = false, tryItOutDefaultServer, useCustomNav }) => {
281
+ const container = React.useRef(null);
282
+ const tree = React.useMemo(() => {
283
+ if (!useCustomNav)
284
+ return computeAPITree(serviceNode, { hideSchemas, hideInternal });
285
+ else
286
+ return [];
287
+ }, [serviceNode, hideSchemas, hideInternal, useCustomNav]);
288
+ const location = useLocation();
289
+ const { pathname: currentPath } = location;
290
+ const relativePath = resolveRelativePath(currentPath, basePath, outerRouter);
291
+ const isRootPath = relativePath === '/';
292
+ const node = isRootPath ? serviceNode : serviceNode.children.find(child => child.uri === relativePath);
293
+ React.useEffect(() => {
294
+ }, [currentPath]);
295
+ const layoutOptions = React.useMemo(() => ({
296
+ hideTryIt: hideTryIt,
297
+ hideTryItPanel,
298
+ hideSamples,
299
+ hideSecurityInfo: hideSecurityInfo,
300
+ hideServerInfo: hideServerInfo,
301
+ compact: compact,
302
+ hideExport: hideExport || (node === null || node === void 0 ? void 0 : node.type) !== NodeType.HttpService,
303
+ hideInlineExamples
304
+ }), [hideTryIt, hideSecurityInfo, hideServerInfo, compact, hideExport, hideTryItPanel, hideSamples, node === null || node === void 0 ? void 0 : node.type, hideInlineExamples]);
305
+ if (!node) {
306
+ const firstSlug = findFirstNodeSlug(tree);
307
+ if (firstSlug) {
308
+ return React.createElement(Navigate, { to: resolveRelativeLink(firstSlug), replace: true });
309
+ }
310
+ }
311
+ if (hideInternal && node && isInternal(node)) {
312
+ return React.createElement(Navigate, { to: ".", replace: true });
313
+ }
314
+ const handleTocClick = () => {
315
+ if (container.current) {
316
+ container.current.scrollIntoView();
317
+ }
318
+ };
319
+ return (React.createElement(ResponsiveSidebarLayout, { onTocClick: handleTocClick, tree: tree, logo: logo !== null && logo !== void 0 ? logo : serviceNode.data.logo, ref: container, name: serviceNode.name, renderSideBar: !useCustomNav }, node && (React.createElement(ElementsOptionsProvider, { renderExtensionAddon: renderExtensionAddon },
320
+ React.createElement(ParsedDocs, { key: relativePath, uri: relativePath, node: node, nodeTitle: node.name, layoutOptions: layoutOptions, location: location, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer })))));
293
321
  };
294
322
 
295
- const APIWithSidebarLayout = ({ serviceNode, logo, hideTryIt, hideSchemas, hideInternal, hideExport, hideInlineExamples = false, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, tryItOutDefaultServer, useCustomNav, layout, }) => {
296
- const container = React.useRef(null);
297
- const tree = React.useMemo(() => {
298
- if (!useCustomNav)
299
- return computeAPITree(serviceNode, { hideSchemas, hideInternal });
300
- else
301
- return [];
302
- }, [serviceNode, hideSchemas, hideInternal, useCustomNav]);
303
- const location = useLocation();
304
- const { pathname } = location;
305
- const isRootPath = !pathname || pathname === '/';
306
- const node = isRootPath ? serviceNode : serviceNode.children.find(child => child.uri === pathname);
307
- React.useEffect(() => {
308
- }, [pathname]);
309
- const layoutOptions = React.useMemo(() => ({ hideTryIt: hideTryIt, hideInlineExamples, hideExport: hideExport || (node === null || node === void 0 ? void 0 : node.type) !== NodeType.HttpService }), [hideTryIt, hideExport, node, hideInlineExamples]);
310
- if (!node) {
311
- const firstSlug = findFirstNodeSlug(tree);
312
- if (firstSlug) {
313
- return React.createElement(Redirect, { to: firstSlug });
314
- }
315
- }
316
- if (hideInternal && node && isInternal(node)) {
317
- return React.createElement(Redirect, { to: "/" });
318
- }
319
- const sidebar = (React.createElement(Sidebar, { serviceNode: serviceNode, logo: logo, container: container, pathname: pathname, tree: tree }));
320
- return (React.createElement(SidebarLayout, { ref: container, sidebar: sidebar, renderSideBar: !useCustomNav, layout: layout }, node && (React.createElement(ElementsOptionsProvider, { renderExtensionAddon: renderExtensionAddon },
321
- React.createElement(ParsedDocs, { key: pathname, uri: pathname, node: node, nodeTitle: node.name, layoutOptions: layoutOptions, location: location, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer })))));
322
- };
323
- const Sidebar = ({ serviceNode, logo, container, pathname, tree }) => {
324
- const handleTocClick = () => {
325
- if (container.current) {
326
- container.current.scrollIntoView();
327
- }
328
- };
329
- return (React.createElement(React.Fragment, null,
330
- React.createElement(Flex, { ml: 4, mb: 5, alignItems: "center" },
331
- logo ? (React.createElement(Logo, { logo: { url: logo, altText: 'logo' } })) : (serviceNode.data.logo && React.createElement(Logo, { logo: serviceNode.data.logo })),
332
- React.createElement(Heading, { size: 4 }, serviceNode.name)),
333
- React.createElement(Flex, { flexGrow: true, flexShrink: true, overflowY: "auto", direction: "col" },
334
- React.createElement(TableOfContents, { tree: tree, activeId: pathname, Link: Link, onLinkClick: handleTocClick })),
335
- React.createElement(PoweredByLink, { source: serviceNode.name, pathname: pathname, packageType: "elements" })));
336
- };
323
+ const APIWithSidebarLayout = ({ serviceNode, logo, hideTryItPanel, hideTryIt, hideSamples, hideSchemas, hideSecurityInfo, hideServerInfo, hideInternal, hideExport, hideInlineExamples = false, exportProps, tryItCredentialsPolicy, tryItCorsProxy, renderExtensionAddon, basePath = '/', outerRouter = false, tryItOutDefaultServer, useCustomNav, layout, }) => {
324
+ const container = React.useRef(null);
325
+ const tree = React.useMemo(() => {
326
+ if (!useCustomNav)
327
+ return computeAPITree(serviceNode, { hideSchemas, hideInternal });
328
+ else
329
+ return [];
330
+ }, [serviceNode, hideSchemas, hideInternal, useCustomNav]);
331
+ const location = useLocation();
332
+ const { pathname: currentPath } = location;
333
+ const relativePath = resolveRelativePath(currentPath, basePath, outerRouter);
334
+ const isRootPath = relativePath === '/';
335
+ const node = isRootPath ? serviceNode : serviceNode.children.find(child => child.uri === relativePath);
336
+ React.useEffect(() => {
337
+ }, [currentPath]);
338
+ const layoutOptions = React.useMemo(() => ({
339
+ hideTryIt: hideTryIt,
340
+ hideTryItPanel,
341
+ hideSamples,
342
+ hideServerInfo: hideServerInfo,
343
+ hideSecurityInfo: hideSecurityInfo,
344
+ hideExport: hideExport || (node === null || node === void 0 ? void 0 : node.type) !== NodeType.HttpService,
345
+ hideInlineExamples
346
+ }), [hideTryIt, hideServerInfo, hideSecurityInfo, hideExport, hideTryItPanel, hideSamples, node === null || node === void 0 ? void 0 : node.type, hideInlineExamples]);
347
+ if (!node) {
348
+ const firstSlug = findFirstNodeSlug(tree);
349
+ if (firstSlug) {
350
+ return React.createElement(Navigate, { to: resolveRelativeLink(firstSlug), replace: true });
351
+ }
352
+ }
353
+ if (hideInternal && node && isInternal(node)) {
354
+ return React.createElement(Navigate, { to: ".", replace: true });
355
+ }
356
+ const sidebar = (React.createElement(Sidebar, { serviceNode: serviceNode, logo: logo, container: container, pathname: relativePath, tree: tree }));
357
+ return (React.createElement(SidebarLayout, { ref: container, sidebar: sidebar, renderSideBar: !useCustomNav, layout: layout }, node && (React.createElement(ElementsOptionsProvider, { renderExtensionAddon: renderExtensionAddon },
358
+ React.createElement(ParsedDocs, { key: relativePath, uri: relativePath, node: node, nodeTitle: node.name, layoutOptions: layoutOptions, location: location, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer })))));
359
+ };
360
+ const Sidebar = ({ serviceNode, logo, container, pathname, tree }) => {
361
+ const handleTocClick = () => {
362
+ if (container.current) {
363
+ container.current.scrollIntoView();
364
+ }
365
+ };
366
+ return (React.createElement(React.Fragment, null,
367
+ React.createElement(Flex, { ml: 4, mb: 5, alignItems: "center" },
368
+ logo ? (React.createElement(Logo, { logo: { url: logo, altText: 'logo' } })) : (serviceNode.data.logo && React.createElement(Logo, { logo: serviceNode.data.logo })),
369
+ React.createElement(Heading, { size: 4 }, serviceNode.name)),
370
+ React.createElement(Flex, { flexGrow: true, flexShrink: true, overflowY: "auto", direction: "col" },
371
+ React.createElement(TableOfContents, { tree: tree, activeId: pathname, Link: Link, onLinkClick: handleTocClick })),
372
+ React.createElement(PoweredByLink, { source: serviceNode.name, pathname: pathname, packageType: "elements" })));
373
+ };
337
374
  Sidebar.displayName = 'Sidebar';
338
375
 
339
- var NodeTypes;
340
- (function (NodeTypes) {
341
- NodeTypes["Paths"] = "paths";
342
- NodeTypes["Path"] = "path";
343
- NodeTypes["Operation"] = "operation";
344
- NodeTypes["Webhooks"] = "webhooks";
345
- NodeTypes["Webhook"] = "webhook";
346
- NodeTypes["Components"] = "components";
347
- NodeTypes["Models"] = "models";
348
- NodeTypes["Model"] = "model";
376
+ var NodeTypes;
377
+ (function (NodeTypes) {
378
+ NodeTypes["Paths"] = "paths";
379
+ NodeTypes["Path"] = "path";
380
+ NodeTypes["Operation"] = "operation";
381
+ NodeTypes["Webhooks"] = "webhooks";
382
+ NodeTypes["Webhook"] = "webhook";
383
+ NodeTypes["Components"] = "components";
384
+ NodeTypes["Models"] = "models";
385
+ NodeTypes["Model"] = "model";
349
386
  })(NodeTypes || (NodeTypes = {}));
350
387
 
351
- const oas2SourceMap = [
352
- {
353
- match: 'paths',
354
- type: NodeTypes.Paths,
355
- children: [
356
- {
357
- notMatch: '^x-',
358
- type: NodeTypes.Path,
359
- children: [
360
- {
361
- match: 'get|post|put|delete|options|head|patch|trace',
362
- type: NodeTypes.Operation,
363
- },
364
- ],
365
- },
366
- ],
367
- },
368
- {
369
- match: 'definitions',
370
- type: NodeTypes.Models,
371
- children: [
372
- {
373
- notMatch: '^x-',
374
- type: NodeTypes.Model,
375
- },
376
- ],
377
- },
388
+ const oas2SourceMap = [
389
+ {
390
+ match: 'paths',
391
+ type: NodeTypes.Paths,
392
+ children: [
393
+ {
394
+ notMatch: '^x-',
395
+ type: NodeTypes.Path,
396
+ children: [
397
+ {
398
+ match: 'get|post|put|delete|options|head|patch|trace',
399
+ type: NodeTypes.Operation,
400
+ },
401
+ ],
402
+ },
403
+ ],
404
+ },
405
+ {
406
+ match: 'definitions',
407
+ type: NodeTypes.Models,
408
+ children: [
409
+ {
410
+ notMatch: '^x-',
411
+ type: NodeTypes.Model,
412
+ },
413
+ ],
414
+ },
378
415
  ];
379
416
 
380
- const oas3SourceMap = [
381
- {
382
- match: 'paths',
383
- type: NodeTypes.Paths,
384
- children: [
385
- {
386
- notMatch: '^x-',
387
- type: NodeTypes.Path,
388
- children: [
389
- {
390
- match: 'get|post|put|delete|options|head|patch|trace',
391
- type: NodeTypes.Operation,
392
- },
393
- ],
394
- },
395
- ],
396
- },
397
- {
398
- match: 'webhooks',
399
- type: NodeTypes.Webhooks,
400
- children: [
401
- {
402
- notMatch: '^x-',
403
- type: NodeTypes.Webhook,
404
- children: [
405
- {
406
- match: 'get|post|put|delete|options|head|patch|trace',
407
- type: NodeTypes.Webhook,
408
- },
409
- ],
410
- },
411
- ],
412
- },
413
- {
414
- match: 'components',
415
- type: NodeTypes.Components,
416
- children: [
417
- {
418
- match: 'schemas',
419
- type: NodeTypes.Models,
420
- children: [
421
- {
422
- notMatch: '^x-',
423
- type: NodeTypes.Model,
424
- },
425
- ],
426
- },
427
- ],
428
- },
417
+ const oas3SourceMap = [
418
+ {
419
+ match: 'paths',
420
+ type: NodeTypes.Paths,
421
+ children: [
422
+ {
423
+ notMatch: '^x-',
424
+ type: NodeTypes.Path,
425
+ children: [
426
+ {
427
+ match: 'get|post|put|delete|options|head|patch|trace',
428
+ type: NodeTypes.Operation,
429
+ },
430
+ ],
431
+ },
432
+ ],
433
+ },
434
+ {
435
+ match: 'webhooks',
436
+ type: NodeTypes.Webhooks,
437
+ children: [
438
+ {
439
+ notMatch: '^x-',
440
+ type: NodeTypes.Webhook,
441
+ children: [
442
+ {
443
+ match: 'get|post|put|delete|options|head|patch|trace',
444
+ type: NodeTypes.Webhook,
445
+ },
446
+ ],
447
+ },
448
+ ],
449
+ },
450
+ {
451
+ match: 'components',
452
+ type: NodeTypes.Components,
453
+ children: [
454
+ {
455
+ match: 'schemas',
456
+ type: NodeTypes.Models,
457
+ children: [
458
+ {
459
+ notMatch: '^x-',
460
+ type: NodeTypes.Model,
461
+ },
462
+ ],
463
+ },
464
+ ],
465
+ },
429
466
  ];
430
467
 
431
- const isOas2 = (parsed) => isObject(parsed) &&
432
- 'swagger' in parsed &&
433
- Number.parseInt(String(parsed.swagger)) === 2;
434
- const isOas3 = (parsed) => isObject(parsed) &&
435
- 'openapi' in parsed &&
436
- Number.parseFloat(String(parsed.openapi)) >= 3;
437
- const isOas31 = (parsed) => isObject(parsed) &&
438
- 'openapi' in parsed &&
439
- Number.parseFloat(String(parsed.openapi)) === 3.1;
440
- const OAS_MODEL_REGEXP = /((definitions|components)\/?(schemas)?)\//;
441
- function transformOasToServiceNode(apiDescriptionDocument) {
442
- if (isOas31(apiDescriptionDocument)) {
443
- return computeServiceNode(Object.assign(Object.assign({}, apiDescriptionDocument), { jsonSchemaDialect: 'http://json-schema.org/draft-07/schema#' }), oas3SourceMap, transformOas3Service, transformOas3Operation);
444
- }
445
- if (isOas3(apiDescriptionDocument)) {
446
- return computeServiceNode(apiDescriptionDocument, oas3SourceMap, transformOas3Service, transformOas3Operation);
447
- }
448
- else if (isOas2(apiDescriptionDocument)) {
449
- return computeServiceNode(apiDescriptionDocument, oas2SourceMap, transformOas2Service, transformOas2Operation);
450
- }
451
- return null;
452
- }
453
- function computeServiceNode(document, map, transformService, transformOperation) {
454
- var _a;
455
- const serviceDocument = transformService({ document });
456
- const serviceNode = {
457
- type: NodeType.HttpService,
458
- uri: '/',
459
- name: serviceDocument.name,
460
- data: serviceDocument,
461
- tags: ((_a = serviceDocument.tags) === null || _a === void 0 ? void 0 : _a.map(tag => tag.name)) || [],
462
- children: computeChildNodes(document, document, map, transformOperation),
463
- };
464
- return serviceNode;
465
- }
466
- function computeChildNodes(document, data, map, transformer, parentUri = '') {
467
- var _a, _b;
468
- const nodes = [];
469
- if (!isObject(data))
470
- return nodes;
471
- for (const key of Object.keys(data)) {
472
- const sanitizedKey = encodePointerFragment(key);
473
- const match = findMapMatch(sanitizedKey, map);
474
- if (match) {
475
- const uri = `${parentUri}/${sanitizedKey}`;
476
- const jsonPath = pointerToPath(`#${uri}`);
477
- if (match.type === NodeTypes.Operation && jsonPath.length === 3) {
478
- const path = String(jsonPath[1]);
479
- const method = String(jsonPath[2]);
480
- const operationDocument = transformer({
481
- document,
482
- name: path,
483
- method,
484
- config: OPERATION_CONFIG,
485
- });
486
- let parsedUri;
487
- const encodedPath = String(encodePointerFragment(path));
488
- if (operationDocument.iid) {
489
- parsedUri = `/operations/${operationDocument.iid}`;
490
- }
491
- else {
492
- parsedUri = uri.replace(encodedPath, slugify(path));
493
- }
494
- nodes.push({
495
- type: NodeType.HttpOperation,
496
- uri: parsedUri,
497
- data: operationDocument,
498
- name: operationDocument.summary || operationDocument.iid || operationDocument.path,
499
- tags: ((_a = operationDocument.tags) === null || _a === void 0 ? void 0 : _a.map(tag => tag.name)) || [],
500
- });
501
- }
502
- else if (match.type === NodeTypes.Webhook && jsonPath.length === 3) {
503
- const name = String(jsonPath[1]);
504
- const method = String(jsonPath[2]);
505
- const webhookDocument = transformer({
506
- document,
507
- name,
508
- method,
509
- config: WEBHOOK_CONFIG,
510
- });
511
- let parsedUri;
512
- const encodedPath = String(encodePointerFragment(name));
513
- if (webhookDocument.iid) {
514
- parsedUri = `/webhooks/${webhookDocument.iid}`;
515
- }
516
- else {
517
- parsedUri = uri.replace(encodedPath, slugify(name));
518
- }
519
- nodes.push({
520
- type: NodeType.HttpWebhook,
521
- uri: parsedUri,
522
- data: webhookDocument,
523
- name: webhookDocument.summary || webhookDocument.name,
524
- tags: ((_b = webhookDocument.tags) === null || _b === void 0 ? void 0 : _b.map(tag => tag.name)) || [],
525
- });
526
- }
527
- else if (match.type === NodeTypes.Model) {
528
- const schemaDocument = get(document, jsonPath);
529
- const parsedUri = uri.replace(OAS_MODEL_REGEXP, 'schemas/');
530
- nodes.push({
531
- type: NodeType.Model,
532
- uri: parsedUri,
533
- data: schemaDocument,
534
- name: schemaDocument.title || last(uri.split('/')) || '',
535
- tags: schemaDocument['x-tags'] || [],
536
- });
537
- }
538
- if (match.children) {
539
- nodes.push(...computeChildNodes(document, data[key], match.children, transformer, uri));
540
- }
541
- }
542
- }
543
- return nodes;
544
- }
545
- function findMapMatch(key, map) {
546
- var _a;
547
- if (typeof key === 'number')
548
- return;
549
- for (const entry of map) {
550
- const escapedKey = key.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
551
- if (!!((_a = entry.match) === null || _a === void 0 ? void 0 : _a.match(escapedKey)) || (entry.notMatch !== void 0 && !entry.notMatch.match(escapedKey))) {
552
- return entry;
553
- }
554
- }
555
- }
556
- function isJson(value) {
557
- try {
558
- JSON.parse(value);
559
- }
560
- catch (e) {
561
- return false;
562
- }
563
- return true;
468
+ const isOas2 = (parsed) => isObject(parsed) &&
469
+ 'swagger' in parsed &&
470
+ Number.parseInt(String(parsed.swagger)) === 2;
471
+ const isOas3 = (parsed) => isObject(parsed) &&
472
+ 'openapi' in parsed &&
473
+ Number.parseFloat(String(parsed.openapi)) >= 3;
474
+ const isOas31 = (parsed) => isObject(parsed) &&
475
+ 'openapi' in parsed &&
476
+ Number.parseFloat(String(parsed.openapi)) === 3.1;
477
+ const OAS_MODEL_REGEXP = /((definitions|components)\/?(schemas)?)\//;
478
+ function transformOasToServiceNode(apiDescriptionDocument) {
479
+ if (isOas31(apiDescriptionDocument)) {
480
+ return computeServiceNode(Object.assign(Object.assign({}, apiDescriptionDocument), { jsonSchemaDialect: 'http://json-schema.org/draft-07/schema#' }), oas3SourceMap, transformOas3Service, transformOas3Operation);
481
+ }
482
+ if (isOas3(apiDescriptionDocument)) {
483
+ return computeServiceNode(apiDescriptionDocument, oas3SourceMap, transformOas3Service, transformOas3Operation);
484
+ }
485
+ else if (isOas2(apiDescriptionDocument)) {
486
+ return computeServiceNode(apiDescriptionDocument, oas2SourceMap, transformOas2Service, transformOas2Operation);
487
+ }
488
+ return null;
489
+ }
490
+ function computeServiceNode(document, map, transformService, transformOperation) {
491
+ var _a;
492
+ const serviceDocument = transformService({ document });
493
+ const serviceNode = {
494
+ type: NodeType.HttpService,
495
+ uri: '/',
496
+ name: serviceDocument.name,
497
+ data: serviceDocument,
498
+ tags: ((_a = serviceDocument.tags) === null || _a === void 0 ? void 0 : _a.map(tag => tag.name)) || [],
499
+ children: computeChildNodes(document, document, map, transformOperation),
500
+ };
501
+ return serviceNode;
502
+ }
503
+ function computeChildNodes(document, data, map, transformer, parentUri = '') {
504
+ var _a, _b;
505
+ const nodes = [];
506
+ if (!isObject(data))
507
+ return nodes;
508
+ for (const [key, value] of Object.entries(data)) {
509
+ const sanitizedKey = encodePointerFragment(key);
510
+ const match = findMapMatch(sanitizedKey, map);
511
+ if (match) {
512
+ const uri = `${parentUri}/${sanitizedKey}`;
513
+ const jsonPath = pointerToPath(`#${uri}`);
514
+ if (match.type === NodeTypes.Operation && jsonPath.length === 3) {
515
+ const path = String(jsonPath[1]);
516
+ const method = String(jsonPath[2]);
517
+ const operationDocument = transformer({
518
+ document,
519
+ name: path,
520
+ method,
521
+ config: OPERATION_CONFIG,
522
+ });
523
+ let parsedUri;
524
+ const encodedPath = String(encodePointerFragment(path));
525
+ if (operationDocument.iid) {
526
+ parsedUri = `/operations/${operationDocument.iid}`;
527
+ }
528
+ else {
529
+ parsedUri = uri.replace(encodedPath, slugify(path));
530
+ }
531
+ nodes.push({
532
+ type: NodeType.HttpOperation,
533
+ uri: parsedUri,
534
+ data: operationDocument,
535
+ name: operationDocument.summary || operationDocument.iid || operationDocument.path,
536
+ tags: ((_a = operationDocument.tags) === null || _a === void 0 ? void 0 : _a.map(tag => tag.name)) || [],
537
+ });
538
+ }
539
+ else if (match.type === NodeTypes.Webhook && jsonPath.length === 3) {
540
+ const name = String(jsonPath[1]);
541
+ const method = String(jsonPath[2]);
542
+ const webhookDocument = transformer({
543
+ document,
544
+ name,
545
+ method,
546
+ config: WEBHOOK_CONFIG,
547
+ });
548
+ let parsedUri;
549
+ const encodedPath = String(encodePointerFragment(name));
550
+ if (webhookDocument.iid) {
551
+ parsedUri = `/webhooks/${webhookDocument.iid}`;
552
+ }
553
+ else {
554
+ parsedUri = uri.replace(encodedPath, slugify(name));
555
+ }
556
+ nodes.push({
557
+ type: NodeType.HttpWebhook,
558
+ uri: parsedUri,
559
+ data: webhookDocument,
560
+ name: webhookDocument.summary || webhookDocument.name,
561
+ tags: ((_b = webhookDocument.tags) === null || _b === void 0 ? void 0 : _b.map(tag => tag.name)) || [],
562
+ });
563
+ }
564
+ else if (match.type === NodeTypes.Model) {
565
+ const schemaDocument = get(document, jsonPath);
566
+ const parsedUri = uri.replace(OAS_MODEL_REGEXP, 'schemas/');
567
+ nodes.push({
568
+ type: NodeType.Model,
569
+ uri: parsedUri,
570
+ data: schemaDocument,
571
+ name: schemaDocument.title || last(uri.split('/')) || '',
572
+ tags: schemaDocument['x-tags'] || [],
573
+ });
574
+ }
575
+ if (match.children) {
576
+ nodes.push(...computeChildNodes(document, value, match.children, transformer, uri));
577
+ }
578
+ }
579
+ }
580
+ return nodes;
581
+ }
582
+ function findMapMatch(key, map) {
583
+ var _a;
584
+ if (typeof key === 'number')
585
+ return;
586
+ for (const entry of map) {
587
+ const escapedKey = key.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
588
+ if (!!((_a = entry.match) === null || _a === void 0 ? void 0 : _a.match(escapedKey)) || (entry.notMatch !== void 0 && !entry.notMatch.match(escapedKey))) {
589
+ return entry;
590
+ }
591
+ }
592
+ }
593
+ function isJson(value) {
594
+ try {
595
+ JSON.parse(value);
596
+ }
597
+ catch (e) {
598
+ return false;
599
+ }
600
+ return true;
564
601
  }
565
602
 
566
- function useExportDocumentProps({ originalDocument, bundledDocument, }) {
567
- const isJsonDocument = typeof originalDocument === 'object' || (!!originalDocument && isJson(originalDocument));
568
- const exportDocument = React.useCallback((document) => {
569
- const type = isJsonDocument ? 'json' : 'yaml';
570
- const blob = new Blob([document], {
571
- type: `application/${type}`,
572
- });
573
- saver.saveAs(blob, `document.${type}`);
574
- }, [isJsonDocument]);
575
- const exportOriginalDocument = React.useCallback(() => {
576
- const stringifiedDocument = typeof originalDocument === 'object' ? JSON.stringify(originalDocument, null, 2) : originalDocument || '';
577
- exportDocument(stringifiedDocument);
578
- }, [originalDocument, exportDocument]);
579
- const exportBundledDocument = React.useCallback(() => {
580
- const stringifiedDocument = isJsonDocument
581
- ? JSON.stringify(bundledDocument, null, 2)
582
- : safeStringify(bundledDocument);
583
- exportDocument(stringifiedDocument);
584
- }, [bundledDocument, isJsonDocument, exportDocument]);
585
- return {
586
- original: {
587
- onPress: exportOriginalDocument,
588
- },
589
- bundled: {
590
- onPress: exportBundledDocument,
591
- },
592
- };
603
+ function useExportDocumentProps({ originalDocument, bundledDocument, }) {
604
+ const isJsonDocument = typeof originalDocument === 'object' || (!!originalDocument && isJson(originalDocument));
605
+ const exportDocument = React.useCallback((document) => {
606
+ const type = isJsonDocument ? 'json' : 'yaml';
607
+ const blob = new Blob([document], {
608
+ type: `application/${type}`,
609
+ });
610
+ saver.saveAs(blob, `document.${type}`);
611
+ }, [isJsonDocument]);
612
+ const exportOriginalDocument = React.useCallback(() => {
613
+ const stringifiedDocument = typeof originalDocument === 'object' ? JSON.stringify(originalDocument, null, 2) : originalDocument || '';
614
+ exportDocument(stringifiedDocument);
615
+ }, [originalDocument, exportDocument]);
616
+ const exportBundledDocument = React.useCallback(() => {
617
+ const stringifiedDocument = isJsonDocument
618
+ ? JSON.stringify(bundledDocument, null, 2)
619
+ : safeStringify(bundledDocument);
620
+ exportDocument(stringifiedDocument);
621
+ }, [bundledDocument, isJsonDocument, exportDocument]);
622
+ return {
623
+ original: {
624
+ onPress: exportOriginalDocument,
625
+ },
626
+ bundled: {
627
+ onPress: exportBundledDocument,
628
+ },
629
+ };
593
630
  }
594
631
 
595
- const propsAreWithDocument = (props) => {
596
- return props.hasOwnProperty('apiDescriptionDocument');
597
- };
598
- const APIImpl = props => {
599
- const { layout = 'sidebar', apiDescriptionUrl = '', logo, hideTryIt, hideSchemas, hideInternal, hideExport, hideInlineExamples, tryItCredentialsPolicy, tryItCorsProxy, maxRefDepth, renderExtensionAddon, tryItOutDefaultServer, useCustomNav, } = props;
600
- const location = useLocation();
601
- const apiDescriptionDocument = propsAreWithDocument(props) ? props.apiDescriptionDocument : undefined;
602
- const { isResponsiveLayoutEnabled } = useResponsiveLayout();
603
- const { data: fetchedDocument, error } = useQuery([apiDescriptionUrl], () => fetch(apiDescriptionUrl).then(res => {
604
- if (res.ok) {
605
- return res.text();
606
- }
607
- throw new Error(`Unable to load description document, status code: ${res.status}`);
608
- }), {
609
- enabled: apiDescriptionUrl !== '' && !apiDescriptionDocument,
610
- });
611
- const document = apiDescriptionDocument || fetchedDocument || '';
612
- const parsedDocument = useParsedValue(document);
613
- const bundledDocument = useBundleRefsIntoDocument(parsedDocument, { baseUrl: apiDescriptionUrl });
614
- const serviceNode = React.useMemo(() => transformOasToServiceNode(bundledDocument), [bundledDocument]);
615
- const exportProps = useExportDocumentProps({ originalDocument: document, bundledDocument });
616
- if (error) {
617
- return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen" },
618
- React.createElement(NonIdealState, { title: "Document could not be loaded", description: "The API description document could not be fetched. This could indicate connectivity problems, or issues with the server hosting the spec.", icon: "exclamation-triangle" })));
619
- }
620
- if (!bundledDocument) {
621
- return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen", color: "light" },
622
- React.createElement(Box, { as: Icon, icon: ['fal', 'circle-notch'], size: "3x", spin: true })));
623
- }
624
- if (!serviceNode) {
625
- return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen" },
626
- React.createElement(NonIdealState, { title: "Failed to parse OpenAPI file", description: "Please make sure your OpenAPI file is valid and try again" })));
627
- }
628
- return (React.createElement(InlineRefResolverProvider, { document: parsedDocument, maxRefDepth: maxRefDepth },
629
- layout === 'stacked' && (React.createElement(APIWithStackedLayout, { serviceNode: serviceNode, hideTryIt: hideTryIt, hideExport: hideExport, hideInlineExamples: hideInlineExamples, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, location: location, tryItOutDefaultServer: tryItOutDefaultServer })),
630
- layout === 'sidebar' && (React.createElement(APIWithSidebarLayout, { logo: logo, serviceNode: serviceNode, hideTryIt: hideTryIt, hideSchemas: hideSchemas, hideInternal: hideInternal, hideExport: hideExport, hideInlineExamples: hideInlineExamples, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, tryItOutDefaultServer: tryItOutDefaultServer, useCustomNav: useCustomNav, layout: layout })),
631
- layout === 'responsive' && (React.createElement(APIWithResponsiveSidebarLayout, { logo: logo, serviceNode: serviceNode, hideTryIt: hideTryIt, hideSchemas: hideSchemas, hideInternal: hideInternal, hideExport: hideExport, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, compact: isResponsiveLayoutEnabled }))));
632
- };
632
+ const propsAreWithDocument = (props) => {
633
+ return props.hasOwnProperty('apiDescriptionDocument');
634
+ };
635
+ const APIImpl = props => {
636
+ const { layout = 'sidebar', apiDescriptionUrl = '', logo, hideTryItPanel, hideTryIt, hideSamples, hideSecurityInfo, hideServerInfo, hideSchemas, hideInternal, hideExport, hideInlineExamples, tryItCredentialsPolicy, tryItCorsProxy, maxRefDepth, renderExtensionAddon, basePath, outerRouter = false, tryItOutDefaultServer, useCustomNav, } = props;
637
+ const location = useLocation();
638
+ const apiDescriptionDocument = propsAreWithDocument(props) ? props.apiDescriptionDocument : undefined;
639
+ const { isResponsiveLayoutEnabled } = useResponsiveLayout();
640
+ const { data: fetchedDocument, error } = useQuery([apiDescriptionUrl], () => fetch(apiDescriptionUrl).then(res => {
641
+ if (res.ok) {
642
+ return res.text();
643
+ }
644
+ throw new Error(`Unable to load description document, status code: ${res.status}`);
645
+ }), {
646
+ enabled: apiDescriptionUrl !== '' && !apiDescriptionDocument,
647
+ });
648
+ const document = apiDescriptionDocument || fetchedDocument || '';
649
+ const parsedDocument = useParsedValue(document);
650
+ const bundledDocument = useBundleRefsIntoDocument(parsedDocument, { baseUrl: apiDescriptionUrl });
651
+ const serviceNode = React.useMemo(() => transformOasToServiceNode(bundledDocument), [bundledDocument]);
652
+ const exportProps = useExportDocumentProps({ originalDocument: document, bundledDocument });
653
+ if (error) {
654
+ return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen" },
655
+ React.createElement(NonIdealState, { title: "Document could not be loaded", description: "The API description document could not be fetched. This could indicate connectivity problems, or issues with the server hosting the spec.", icon: "exclamation-triangle" })));
656
+ }
657
+ if (!bundledDocument) {
658
+ return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen", color: "light" },
659
+ React.createElement(Box, { as: Icon, icon: ['fal', 'circle-notch'], size: "3x", spin: true })));
660
+ }
661
+ if (!serviceNode) {
662
+ return (React.createElement(Flex, { justify: "center", alignItems: "center", w: "full", minH: "screen" },
663
+ React.createElement(NonIdealState, { title: "Failed to parse OpenAPI file", description: "Please make sure your OpenAPI file is valid and try again" })));
664
+ }
665
+ return (React.createElement(InlineRefResolverProvider, { document: parsedDocument, maxRefDepth: maxRefDepth },
666
+ layout === 'stacked' && (React.createElement(APIWithStackedLayout, { serviceNode: serviceNode, hideTryIt: hideTryIt, hideSamples: hideSamples, hideTryItPanel: hideTryItPanel, hideSecurityInfo: hideSecurityInfo, hideServerInfo: hideServerInfo, hideExport: hideExport, hideInlineExamples: hideInlineExamples, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, location: location, tryItOutDefaultServer: tryItOutDefaultServer })),
667
+ layout === 'sidebar' && (React.createElement(APIWithSidebarLayout, { logo: logo, serviceNode: serviceNode, hideTryItPanel: hideTryItPanel, hideTryIt: hideTryIt, hideSamples: hideSamples, hideSecurityInfo: hideSecurityInfo, hideServerInfo: hideServerInfo, hideSchemas: hideSchemas, hideInternal: hideInternal, hideExport: hideExport, hideInlineExamples: hideInlineExamples, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, basePath: basePath, outerRouter: outerRouter, tryItOutDefaultServer: tryItOutDefaultServer, useCustomNav: useCustomNav, layout: layout })),
668
+ layout === 'responsive' && (React.createElement(APIWithResponsiveSidebarLayout, { logo: logo, serviceNode: serviceNode, hideTryItPanel: hideTryItPanel, hideTryIt: hideTryIt, hideSamples: hideSamples, hideSecurityInfo: hideSecurityInfo, hideServerInfo: hideServerInfo, hideSchemas: hideSchemas, hideInternal: hideInternal, hideExport: hideExport, hideInlineExamples: hideInlineExamples, exportProps: exportProps, tryItCredentialsPolicy: tryItCredentialsPolicy, tryItCorsProxy: tryItCorsProxy, renderExtensionAddon: renderExtensionAddon, compact: isResponsiveLayoutEnabled, basePath: basePath, outerRouter: outerRouter, tryItOutDefaultServer: tryItOutDefaultServer, useCustomNav: useCustomNav }))));
669
+ };
633
670
  const API = flow(withRouter, withStyles, withPersistenceBoundary, withMosaicProvider, withQueryClientProvider)(APIImpl);
634
671
 
635
- const useGetOasNavTree = (apiDescriptionDocument) => {
636
- const parsedDocument = useParsedValue(apiDescriptionDocument);
637
- const bundledDocument = useBundleRefsIntoDocument(parsedDocument);
638
- if (!bundledDocument)
639
- return [];
640
- const groupSchemas = (tree) => {
641
- const targetTitle = 'Schemas';
642
- const newTree = tree.reduce((accumulator, currentObject) => {
643
- var _a;
644
- if (currentObject.title === targetTitle) {
645
- accumulator.matchedObject = currentObject;
646
- }
647
- else if ((_a = currentObject.id) === null || _a === void 0 ? void 0 : _a.includes(targetTitle.toLowerCase())) {
648
- accumulator.matchedObject.items = accumulator.matchedObject.items || [];
649
- accumulator.matchedObject.items.push(currentObject);
650
- }
651
- else {
652
- accumulator.others = accumulator.others || [];
653
- accumulator.others.push(currentObject);
654
- }
655
- return accumulator;
656
- }, {});
657
- const navTree = [...newTree.others, newTree.matchedObject];
658
- return navTree;
659
- };
660
- const apiTree = computeAPITree(transformOasToServiceNode(bundledDocument));
661
- return groupSchemas(apiTree);
672
+ const useGetOasNavTree = (apiDescriptionDocument) => {
673
+ const parsedDocument = useParsedValue(apiDescriptionDocument);
674
+ const bundledDocument = useBundleRefsIntoDocument(parsedDocument);
675
+ if (!bundledDocument)
676
+ return [];
677
+ const groupSchemas = (tree) => {
678
+ const targetTitle = 'Schemas';
679
+ const newTree = tree.reduce((accumulator, currentObject) => {
680
+ var _a;
681
+ if (currentObject.title === targetTitle) {
682
+ accumulator.matchedObject = currentObject;
683
+ }
684
+ else if ((_a = currentObject.id) === null || _a === void 0 ? void 0 : _a.includes(targetTitle.toLowerCase())) {
685
+ accumulator.matchedObject.items = accumulator.matchedObject.items || [];
686
+ accumulator.matchedObject.items.push(currentObject);
687
+ }
688
+ else {
689
+ accumulator.others = accumulator.others || [];
690
+ accumulator.others.push(currentObject);
691
+ }
692
+ return accumulator;
693
+ }, {});
694
+ const navTree = [...newTree.others, newTree.matchedObject];
695
+ return navTree;
696
+ };
697
+ const apiTree = computeAPITree(transformOasToServiceNode(bundledDocument));
698
+ return groupSchemas(apiTree);
662
699
  };
663
700
 
664
701
  export { API, APIWithStackedLayout, transformOasToServiceNode, useExportDocumentProps, useGetOasNavTree };