-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathMenuBuilder.ts
287 lines (256 loc) · 8.6 KB
/
MenuBuilder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import type { OpenAPISpec, OpenAPIPaths, OpenAPITag, OpenAPISchema } from '../types';
import { isOperationName, JsonPointer, alphabeticallyByProp } from '../utils';
import { MarkdownRenderer } from './MarkdownRenderer';
import { GroupModel, OperationModel } from './models';
import type { OpenAPIParser } from './OpenAPIParser';
import type { RedocNormalizedOptions } from './RedocNormalizedOptions';
import type { ContentItemModel, TagGroup, TagInfo, TagsInfoMap } from './types';
export const GROUP_DEPTH = 0;
export class MenuBuilder {
/**
* Builds page content structure based on tags
*/
static buildStructure(
parser: OpenAPIParser,
options: RedocNormalizedOptions,
): ContentItemModel[] {
const spec = parser.spec;
const items: ContentItemModel[] = [];
const tagsMap = MenuBuilder.getTagsWithOperations(parser, spec);
items.push(...MenuBuilder.addMarkdownItems(spec.info.description || '', undefined, 1, options));
if (spec['x-tagGroups'] && spec['x-tagGroups'].length > 0) {
items.push(
...MenuBuilder.getTagGroupsItems(parser, undefined, spec['x-tagGroups'], tagsMap, options),
);
} else {
items.push(...MenuBuilder.getTagsItems(parser, tagsMap, undefined, undefined, options));
}
return items;
}
/**
* extracts items from markdown description
* @param description - markdown source
*/
static addMarkdownItems(
description: string,
parent: GroupModel | undefined,
initialDepth: number,
options: RedocNormalizedOptions,
): ContentItemModel[] {
const renderer = new MarkdownRenderer(options, parent?.id);
const headings = renderer.extractHeadings(description || '');
if (headings.length && parent && parent.description) {
parent.description = MarkdownRenderer.getTextBeforeHading(
parent.description,
headings[0].name,
);
}
const mapHeadingsDeep = (_parent, items, depth = 1) =>
items.map(heading => {
const group = new GroupModel('section', heading, _parent);
group.depth = depth;
if (heading.items) {
group.items = mapHeadingsDeep(group, heading.items, depth + 1);
}
return group;
});
return mapHeadingsDeep(parent, headings, initialDepth);
}
/**
* Returns array of OperationsGroup items for the tag groups (x-tagGroups vendor extension)
* @param tags value of `x-tagGroups` vendor extension
*/
static getTagGroupsItems(
parser: OpenAPIParser,
parent: GroupModel | undefined,
groups: TagGroup[],
tags: TagsInfoMap,
options: RedocNormalizedOptions,
): GroupModel[] {
const res: GroupModel[] = [];
for (const group of groups) {
const item = new GroupModel('group', group, parent);
item.depth = GROUP_DEPTH;
item.items = MenuBuilder.getTagsItems(parser, tags, item, group, options);
res.push(item);
}
// TODO checkAllTagsUsedInGroups
return res;
}
/**
* Returns array of OperationsGroup items for the tags of the group or for all tags
* @param parser
* @param tagsMap tags info returned from `getTagsWithOperations`
* @param parent parent item
* @param group group which this tag belongs to. if not provided gets all tags
* @param options normalized options
*/
static getTagsItems(
parser: OpenAPIParser,
tagsMap: TagsInfoMap,
parent: GroupModel | undefined,
group: TagGroup | undefined,
options: RedocNormalizedOptions,
): ContentItemModel[] {
let tagNames;
if (group === undefined) {
tagNames = Object.keys(tagsMap); // all tags
} else {
tagNames = group.tags;
}
const tags = tagNames.map(tagName => {
if (!tagsMap[tagName]) {
console.warn(`Non-existing tag "${tagName}" is added to the group "${group!.name}"`);
return null;
}
tagsMap[tagName].used = true;
return tagsMap[tagName];
});
const res: Array<GroupModel | OperationModel> = [];
for (const tag of tags) {
if (!tag) {
continue;
}
const item = new GroupModel('tag', tag, parent);
item.depth = GROUP_DEPTH + 1;
// don't put empty tag into content, instead put its operations
if (tag.name === '') {
const items = [
...MenuBuilder.addMarkdownItems(tag.description || '', item, item.depth + 1, options),
...this.getOperationsItems(parser, undefined, tag, item.depth + 1, options),
];
res.push(...items);
continue;
}
const relatedSchemas = this.getTagRelatedSchema({
parser,
tag,
parent: item,
});
item.items = [
...relatedSchemas,
...MenuBuilder.addMarkdownItems(tag.description || '', item, item.depth + 1, options),
...this.getOperationsItems(parser, item, tag, item.depth + 1, options),
];
res.push(item);
}
if (options.sortTagsAlphabetically) {
res.sort(alphabeticallyByProp<GroupModel | OperationModel>('name'));
}
return res;
}
/**
* Returns array of Operation items for the tag
* @param parser
* @param parent parent OperationsGroup
* @param tag tag info returned from `getTagsWithOperations`
* @param depth items depth
* @param options - normalized options
*/
static getOperationsItems(
parser: OpenAPIParser,
parent: GroupModel | undefined,
tag: TagInfo,
depth: number,
options: RedocNormalizedOptions,
): OperationModel[] {
if (tag.operations.length === 0) {
return [];
}
const res: OperationModel[] = [];
for (const operationInfo of tag.operations) {
const operation = new OperationModel(parser, operationInfo, parent, options);
operation.depth = depth;
res.push(operation);
}
if (options.sortOperationsAlphabetically) {
res.sort(alphabeticallyByProp<OperationModel>('name'));
}
return res;
}
/**
* collects tags and maps each tag to list of operations belonging to this tag
*/
static getTagsWithOperations(parser: OpenAPIParser, spec: OpenAPISpec): TagsInfoMap {
const tags: TagsInfoMap = {};
const webhooks = spec['x-webhooks'] || spec.webhooks;
for (const tag of spec.tags || []) {
tags[tag.name] = { ...tag, operations: [] };
}
if (webhooks) {
getTags(parser, webhooks, true);
}
if (spec.paths) {
getTags(parser, spec.paths);
}
function getTags(parser: OpenAPIParser, paths: OpenAPIPaths, isWebhook?: boolean) {
for (const pathName of Object.keys(paths)) {
const path = paths[pathName];
const operations = Object.keys(path).filter(isOperationName);
for (const operationName of operations) {
const operationInfo = path[operationName];
if (path.$ref) {
const { resolved: resolvedPaths } = parser.deref<OpenAPIPaths>(path as OpenAPIPaths);
getTags(parser, { [pathName]: resolvedPaths }, isWebhook);
continue;
}
let operationTags = operationInfo?.tags;
if (!operationTags || !operationTags.length) {
// empty tag
operationTags = [''];
}
for (const tagName of operationTags) {
let tag = tags[tagName];
if (tag === undefined) {
tag = {
name: tagName,
operations: [],
};
tags[tagName] = tag;
}
if (tag['x-traitTag']) {
continue;
}
tag.operations.push({
...operationInfo,
pathName,
pointer: JsonPointer.compile(['paths', pathName, operationName]),
httpVerb: operationName,
pathParameters: path.parameters || [],
pathServers: path.servers,
isWebhook: !!isWebhook,
});
}
}
}
}
return tags;
}
static getTagRelatedSchema({
parser,
tag,
parent,
}: {
parser: OpenAPIParser;
tag: TagInfo;
parent: GroupModel;
}): GroupModel[] {
return Object.entries(parser.spec.components?.schemas || {})
.map(([schemaName, schema]) => {
const schemaTags = schema['x-tags'];
if (!schemaTags?.includes(tag.name)) return null;
const item = new GroupModel(
'schema',
{
name: schemaName,
'x-displayName': `${(schema as OpenAPISchema).title || schemaName}`,
description: `<SchemaDefinition showWriteOnly={true} schemaRef="#/components/schemas/${schemaName}" />`,
} as OpenAPITag,
parent,
);
item.depth = parent.depth + 1;
return item;
})
.filter(Boolean) as GroupModel[];
}
}