-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgenApiSchema.ts
351 lines (313 loc) · 12.3 KB
/
genApiSchema.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import { ZodFileSchema, getContext, logSuccess } from '@rnv/core';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { z } from 'zod';
import path from 'path';
import fs from 'fs';
const { zodConfigFileApp, zodConfigFileProject, zodConfigFileTemplate, zodConfigFilePlugin, zodConfigFileIntegration } =
ZodFileSchema;
export const generateSchema = async () => {
_generateSchemaFile({
schema: zodConfigFileProject,
schemaId: 'rnv.project',
sideBarTitle: 'renative.json (Project Config)',
});
_generateSchemaFile({ schema: zodConfigFileApp, schemaId: 'rnv.app', sideBarTitle: 'renative.json (App Config)' });
// _generateSchemaFile({ schema: RootLocalSchema, schemaId: 'rnv.local' });
// _generateSchemaFile({ schema: RootEngineSchema, schemaId: 'rnv.engine' });
// _generateSchemaFile({ schema: RootGlobalSchema, schemaId: 'rnv.global' });
// _generateSchemaFile({ schema: RootPluginsSchema, schemaId: 'rnv.plugins' });
_generateSchemaFile({
schema: zodConfigFileTemplate,
schemaId: 'rnv.template',
sideBarTitle: 'renative.template.json (Template Config)',
});
// _generateSchemaFile({ schema: RootPrivateSchema, schemaId: 'rnv.private' });
_generateSchemaFile({ schema: zodConfigFilePlugin, schemaId: 'rnv.plugin', sideBarTitle: 'renative.plugin.json' });
// _generateSchemaFile({ schema: RootTemplatesSchema, schemaId: 'rnv.templates' });
_generateSchemaFile({
schema: zodConfigFileIntegration,
schemaId: 'rnv.integration',
sideBarTitle: 'renative.integration.json',
});
// add _category_ file
const categoryContent = `label: "Config Descriptors"`;
const ctx = getContext();
const destFolder = path.join(ctx.paths.project.dir, `docs/api/schemas`);
const destPath = path.join(destFolder, `_category_.yml`);
fs.writeFileSync(destPath, categoryContent);
logSuccess('Sucessfully exported all schemas');
};
const _generateSchemaFile = (opts: { schema: z.ZodObject<any>; schemaId: string; sideBarTitle: string }) => {
const { schema, schemaId, sideBarTitle } = opts;
const ctx = getContext();
const jsonSchema: any = zodToJsonSchema(schema);
jsonSchema['$schema'] = 'http://json-schema.org/draft-04/schema#';
const resolvedSchema = resolveRefsInSchema({ ...jsonSchema });
const destFolder = path.join(ctx.paths.project.dir, `docs/api/schemas`);
if (!fs.existsSync(destFolder)) {
fs.mkdirSync(destFolder, { recursive: true });
}
const destPath = path.join(destFolder, `${schemaId}.md`);
fs.writeFileSync(destPath, generate(resolvedSchema, schemaId, sideBarTitle));
};
const generateElementTitle = (
hashtags: string,
elementName: string | undefined,
elementType: string,
isRequired: boolean,
isEnum: boolean,
example: string
) => {
const tooManyHashtags = hashtags.length > 6;
const text = [tooManyHashtags ? '' : hashtags];
if (elementName) {
if (tooManyHashtags) {
text.push('**`' + elementName + '`**');
} else {
text.push(' `' + elementName + '`');
}
}
if (elementType || isRequired) {
text.push(' (');
if (elementType) {
text.push(elementType);
}
if (isEnum) {
text.push(', enum');
}
if (isRequired) {
text.push(', required');
}
text.push(')');
}
if (example) {
text.push(' eg: `' + example + '`');
}
return text.join('');
};
const generatePropertyRestrictions = (schema: unknown) => {
const generate = generateSinglePropertyRestriction(schema);
return [
generate('minimum', 'Minimum'),
generate('maximum', 'Maximum'),
generate('pattern', 'Regex pattern'),
generate('minItems', 'Minimum items'),
generate('uniqueItems', 'Unique items'),
]
.filter((text) => {
return text;
})
.join('\n');
};
const generateSinglePropertyRestriction = (schema) => {
return (key: string, text: string) => {
if (schema[key]) {
return '* ' + text + ': `' + schema[key] + '`';
} else {
return null;
}
};
};
const generateSchemaSectionText = (
hashtags: string,
name: string | undefined,
isRequired: boolean,
schema: any,
subSchemas: any
) => {
const schemaType = getActualType(schema, subSchemas);
let text: string[] = [
generateElementTitle(hashtags, name, schemaType, isRequired, schema.enum, schema.example),
schema.description,
];
if (schemaType === 'object') {
if (schema.properties) {
text.push('Properties of the' + (name ? ' `' + name + '`' : '') + ' object:');
generatePropertySection(hashtags, schema, subSchemas).forEach((section) => {
text = text.concat(section);
});
}
if (schema.additionalProperties.properties) {
text.push('Properties of the' + (name ? ' `' + name + '`' : '') + ' object:');
generatePropertySection(hashtags, schema.additionalProperties, subSchemas).forEach((section) => {
text = text.concat(section);
});
}
} else if (schemaType === 'array') {
let itemsType = schema.items && schema.items.type;
if (!itemsType && schema.items['$ref']) {
itemsType = getActualType(schema.items, subSchemas);
}
if (itemsType && name) {
text.push('The object is an array with all elements of the type `' + itemsType + '`.');
} else if (itemsType) {
text.push('The schema defines an array with all elements of the type `' + itemsType + '`.');
} else {
let validationItems = [];
if (schema.items.allOf) {
text.push('The elements of the array must match *all* of the following properties:');
validationItems = schema.items.allOf;
} else if (schema.items.anyOf) {
text.push('The elements of the array must match *at least one* of the following properties:');
validationItems = schema.items.anyOf;
} else if (schema.items.oneOf) {
text.push('The elements of the array must match *exactly one* of the following properties:');
validationItems = schema.items.oneOf;
} else if (schema.items.not) {
text.push('The elements of the array must *not* match the following properties:');
validationItems = schema.items.not;
}
if (validationItems.length > 0) {
validationItems.forEach((item: any) => {
text = text.concat(generateSchemaSectionText(hashtags, item.title || '', false, item, subSchemas));
});
}
}
if (itemsType === 'object') {
text.push('The array object has the following properties:');
generatePropertySection(hashtags, schema.items, subSchemas).forEach((section) => {
text = text.concat(section);
});
}
} else if (schema.oneOf) {
text.push('The object must be one of the following types:');
text.push(
schema.oneOf
.map((oneOf) => {
return '* `' + subSchemas[oneOf['$ref']] + '`';
})
.join('\n')
);
}
if (schema.enum) {
text.push('This element must be one of the following enum values:');
text.push(
schema.enum
.map((enumItem) => {
return '* `' + enumItem + '`';
})
.join('\n')
);
}
if (schema.default !== undefined) {
if (schema.default === null || ['boolean', 'number', 'string'].indexOf(typeof schema.default) !== -1) {
text.push('Default: `' + JSON.stringify(schema.default) + '`');
} else {
text.push('Default:');
text.push('```\n' + JSON.stringify(schema.default, null, 2) + '\n```');
}
}
const restrictions = generatePropertyRestrictions(schema);
if (restrictions) {
text.push('*Constraints:*');
text.push(restrictions);
}
return text;
};
const generatePropertySection = (hashtags: string, schema: any, subSchemas: unknown) => {
if (schema.properties) {
return Object.keys(schema.properties).map((propertyKey) => {
const propertyIsRequired = schema.required && schema.required.indexOf(propertyKey) >= 0;
return generateSchemaSectionText(
hashtags + '#',
propertyKey,
propertyIsRequired,
schema.properties[propertyKey],
subSchemas
);
});
} else if (schema.oneOf) {
const oneOfList = schema.oneOf
.map((innerSchema: unknown) => {
return '* `' + getActualType(innerSchema, subSchemas) + '`';
})
.join('\n');
return ['This property must be one of the following types:', oneOfList];
} else {
return [];
}
};
const getActualType = (schema: any, subSchemas: any) => {
if (schema.type) {
return schema.type;
} else if (schema['$ref'] && subSchemas[schema['$ref']]) {
return subSchemas[schema['$ref']];
} else {
return undefined;
}
};
const generate = (schema: any, id: string, sidebarLabel: string) => {
const subSchemaTypes = Object.keys(schema.definitions || {}).reduce((map, subSchemaTypeName) => {
map['#/definitions/' + subSchemaTypeName] = subSchemaTypeName;
return map;
}, {});
const header = `---
id: ${id}
title: ${id} Schema
sidebar_label: ${sidebarLabel}
---
`;
let text: string[] = [header, `# ${id} Schema Definition`];
let hashtags = '#';
if (schema.title) {
hashtags += '#';
text.push(hashtags + ' ' + schema.title);
}
if (schema.type === 'object') {
if (schema.description) {
text.push(schema.description);
}
text.push('The schema defines the following properties:');
generatePropertySection(hashtags, schema, subSchemaTypes).forEach((section) => {
text = text.concat(section);
});
} else {
text = text.concat(generateSchemaSectionText('#' + hashtags, undefined, false, schema, subSchemaTypes));
}
return text
.filter((line) => {
return !!line;
})
.join('\n\n');
};
const resolveRefsInSchema = (schema: any): any => {
const resolveJsonRefs = (schema: any, ref: string): any => {
const pointer = ref.replace(/^#\//, '').split('/');
return pointer.reduce((acc, key) => acc && acc[key], schema);
};
const resolveRefs = (currentSchema: any, depth = 0): any => {
if (currentSchema.$ref) {
const resolvedSchema = resolveJsonRefs(schema, currentSchema.$ref);
return resolveRefs(resolvedSchema, depth);
}
if (currentSchema.type === 'object' && currentSchema.properties) {
const newProperties = {};
Object.keys(currentSchema.properties).forEach((key) => {
newProperties[key] = resolveRefs(currentSchema.properties[key], depth);
});
return { ...currentSchema, properties: newProperties };
}
if (currentSchema.additionalProperties && typeof currentSchema.additionalProperties === 'object') {
const resolvedAdditionalProperties = resolveRefs(currentSchema.additionalProperties, depth);
return { ...currentSchema, additionalProperties: resolvedAdditionalProperties };
}
if (currentSchema.type === 'array' && currentSchema.items) {
if (depth > 0) {
return currentSchema;
}
// depth <= recursion limit for `items` field to avoid circular refs (children)
const resolvedItems = resolveRefs(currentSchema.items, depth + 1);
return { ...currentSchema, items: resolvedItems };
}
if (Array.isArray(currentSchema.anyOf)) {
return {
...currentSchema,
anyOf: currentSchema.anyOf.map((subSchema: any) => {
return resolveRefs(subSchema, depth);
}),
};
}
return currentSchema;
};
return resolveRefs(schema);
};