-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathexampleGeneration.ts
More file actions
253 lines (218 loc) · 7.89 KB
/
Copy pathexampleGeneration.ts
File metadata and controls
253 lines (218 loc) · 7.89 KB
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
import { isPlainObject, safeStringify } from '@stoplight/json';
import * as Sampler from '@stoplight/json-schema-sampler';
import { IMediaTypeContent, INodeExample, INodeExternalExample } from '@stoplight/types';
import { JSONSchema7, JSONSchema7Object, JSONSchema7Type } from 'json-schema';
import React from 'react';
import { useDocument } from '../../context/InlineRefResolver';
type Example = {
label: string;
data: string;
};
export type GenerateExampleFromMediaTypeContentOptions = Sampler.Options;
export const useGenerateExampleFromMediaTypeContent = (
mediaTypeContent: IMediaTypeContent | undefined,
chosenExampleIndex?: number,
{ skipReadOnly, skipWriteOnly, skipNonRequired, ticks }: GenerateExampleFromMediaTypeContentOptions = {},
) => {
const document = useDocument();
return React.useMemo(
() =>
generateExampleFromMediaTypeContent(mediaTypeContent, document, chosenExampleIndex, {
skipNonRequired,
skipWriteOnly,
skipReadOnly,
ticks: ticks || 6000,
}),
[mediaTypeContent, document, chosenExampleIndex, skipNonRequired, skipWriteOnly, skipReadOnly, ticks],
);
};
export const generateExampleFromMediaTypeContent = (
mediaTypeContent: IMediaTypeContent | undefined,
document: any,
chosenExampleIndex = 0,
options?: GenerateExampleFromMediaTypeContentOptions,
) => {
const textRequestBodySchema = mediaTypeContent?.schema;
const textRequestBodyExamples = mediaTypeContent?.examples;
try {
if (textRequestBodyExamples?.length) {
return (
safeStringify(
textRequestBodyExamples?.[chosenExampleIndex]['value' as keyof (INodeExample | INodeExternalExample)],
undefined,
2,
) ?? ''
);
} else if (textRequestBodySchema) {
const generated = Sampler.sample(textRequestBodySchema, options, document);
return generated !== null ? safeStringify(generated, undefined, 2) ?? '' : '';
}
} catch (e) {
console.warn(e);
return `Example cannot be created for this schema\n${e}`;
}
return '';
};
export const generateExamplesFromJsonSchema = (schema: JSONSchema7 & { 'x-examples'?: JSONSchema7Type }): Example[] => {
const examples: Example[] = [];
const hasResolvedProperties = (schemaToCheck: JSONSchema7): boolean => {
// Case 1: Direct object with properties
if (schemaToCheck.properties && Object.keys(schemaToCheck.properties).length > 0) {
return true;
}
// Case 2: Check inside allOf, oneOf, anyOf recursively
const composedArray = schemaToCheck.allOf || schemaToCheck.oneOf || schemaToCheck.anyOf;
if (Array.isArray(composedArray)) {
return composedArray.some(sub => {
if (typeof sub !== 'object' || sub === null) return false;
return hasResolvedProperties(sub as JSONSchema7);
});
}
return false;
};
const hasNoResolvedProperties = (schemaToCheck: JSONSchema7): boolean => {
return !hasResolvedProperties(schemaToCheck);
};
const isHasNoResolvedProperties = hasNoResolvedProperties(schema);
if (Array.isArray(schema?.examples)) {
if (isHasNoResolvedProperties) {
schema.examples.forEach((example, index) => {
examples.push({
data: '{}',
label: index === 0 ? 'default' : `example-${index}`,
});
});
} else {
let res = filterExamplesBySchema(schema, schema.examples);
res.forEach((example, index) => {
examples.push({
data: safeStringify(example, undefined, 2) ?? '',
label: index === 0 ? 'default' : `example-${index}`,
});
});
}
} else if (isPlainObject(schema?.['x-examples'])) {
for (const [label, example] of Object.entries(schema['x-examples'])) {
if (isPlainObject(example)) {
const val = example.hasOwnProperty('value') && Object.keys(example).length === 1 ? example.value : example;
examples.push({
label,
data: safeStringify(val, undefined, 2) ?? '',
});
}
}
}
if (examples.length) {
return examples;
}
try {
const generated = Sampler.sample(schema, {
maxSampleDepth: 4,
ticks: 6000,
});
return generated !== null
? [
{
label: 'default',
data: safeStringify(generated, undefined, 2) ?? '',
},
]
: [{ label: 'default', data: '' }];
} catch (e) {
return [{ label: '', data: `Example cannot be created for this schema\n${e}` }];
}
};
export const exceedsSize = (example: string, size: number = 500) => {
return example.split(/\r\n|\r|\n/).length > size;
};
/**
* Filters examples to only include properties that exist in the schema.
* Handles nested objects, arrays, allOf, oneOf, anyOf, and additionalProperties.
* Only removes a property from the example at the exact path where it was removed from the schema.
*
* @param schema - The JSON Schema (possibly with masked/hidden properties)
* @param examples - Array of raw JSON values (e.g. schema.examples)
* @returns New array of filtered objects matching the schema structure
*/
export const filterExamplesBySchema = (
schema: JSONSchema7 & { 'x-examples'?: JSONSchema7Type },
examples: JSONSchema7Type[],
): JSONSchema7Type[] => {
return examples.map(example => {
try {
return filterValueBySchema(example, schema);
} catch {
return example;
}
});
};
const collectSchemaPropertyNames = (schema: JSONSchema7): Set<string> => {
const keys = new Set<string>();
if (schema.properties) {
for (const key of Object.keys(schema.properties)) {
keys.add(key);
}
}
const composedSchemas = [
...(Array.isArray(schema.allOf) ? schema.allOf : []),
...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
];
for (const sub of composedSchemas) {
if (typeof sub === 'object' && sub !== null) {
for (const key of collectSchemaPropertyNames(sub as JSONSchema7)) {
keys.add(key);
}
}
}
return keys;
};
const findPropertySchema = (schema: JSONSchema7, propertyName: string): JSONSchema7 | undefined => {
if (schema.properties?.[propertyName]) {
const prop = schema.properties[propertyName];
return typeof prop === 'boolean' ? undefined : prop;
}
const composedSchemas = [
...(Array.isArray(schema.allOf) ? schema.allOf : []),
...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
];
for (const sub of composedSchemas) {
if (typeof sub === 'object' && sub !== null) {
const found = findPropertySchema(sub as JSONSchema7, propertyName);
if (found) return found;
}
}
return undefined;
};
const filterValueBySchema = (value: JSONSchema7Type, schema: JSONSchema7): JSONSchema7Type => {
if (value === null || value === undefined) return value;
// Handle arrays
if (Array.isArray(value)) {
const itemSchema =
schema.items && typeof schema.items !== 'boolean' && !Array.isArray(schema.items)
? (schema.items as JSONSchema7)
: undefined;
return itemSchema ? value.map(item => filterValueBySchema(item, itemSchema)) : value;
}
// Handle objects
if (isPlainObject(value)) {
const allowedKeys = collectSchemaPropertyNames(schema);
const hasStructure = allowedKeys.size > 0;
const hasAdditionalProperties = schema.additionalProperties;
if (!hasStructure && !hasAdditionalProperties) return value as JSONSchema7Object;
const result: JSONSchema7Object = {};
for (const [key, val] of Object.entries(value as JSONSchema7Object)) {
if (allowedKeys.has(key)) {
const propSchema = findPropertySchema(schema, key);
result[key] = propSchema ? filterValueBySchema(val as JSONSchema7Type, propSchema) : val;
} else if (hasAdditionalProperties) {
result[key] = val;
}
// else: property was masked/removed from schema — omit it
}
return result;
}
// Primitives
return value;
};