|
21 | 21 | import * as Arr from "effect/Array" |
22 | 22 | import * as JsonSchema from "effect/JsonSchema" |
23 | 23 | import * as Rec from "effect/Record" |
| 24 | +import * as Schema from "effect/Schema" |
24 | 25 | import * as SchemaRepresentation from "effect/SchemaRepresentation" |
25 | 26 |
|
26 | 27 | type Source = "openapi-3.0" | "openapi-3.1" |
@@ -211,17 +212,48 @@ function makeWithRepresentation() { |
211 | 212 | schemas, |
212 | 213 | definitions |
213 | 214 | } |
| 215 | + const schemasWithExamples: Array<JsonSchema.JsonSchema> = [] |
| 216 | + const preparedSchemas = new WeakMap<JsonSchema.JsonSchema, JsonSchema.JsonSchema>() |
| 217 | + const preparedOutputs = new WeakSet<JsonSchema.JsonSchema>() |
214 | 218 | const importerOptions: SchemaRepresentation.FromJsonSchemaOptions = { |
215 | 219 | patterns: "apply", |
216 | 220 | onEnter(js: JsonSchema.JsonSchema) { |
| 221 | + if (preparedOutputs.has(js)) return js |
| 222 | + const cached = preparedSchemas.get(js) |
| 223 | + if (cached !== undefined) return cached |
| 224 | + |
217 | 225 | const out = { ...js } |
218 | 226 | if (out.type === "object" && out.additionalProperties === undefined) { |
219 | 227 | out.additionalProperties = false |
220 | 228 | } |
221 | | - return options?.onEnter === undefined ? out : options.onEnter(out) |
| 229 | + const transformed = { ...(options?.onEnter === undefined ? out : options.onEnter(out)) } |
| 230 | + preparedSchemas.set(js, transformed) |
| 231 | + preparedOutputs.add(transformed) |
| 232 | + if (Array.isArray(transformed.examples)) { |
| 233 | + schemasWithExamples.push(transformed) |
| 234 | + } |
| 235 | + return transformed |
| 236 | + } |
| 237 | + } |
| 238 | + let rootSchemas = SchemaRepresentation.fromJsonSchemaMultiDocument(document, importerOptions) |
| 239 | + if (Arr.isArrayNonEmpty(schemasWithExamples)) { |
| 240 | + const exampleSchemas = SchemaRepresentation.fromJsonSchemaMultiDocument( |
| 241 | + { ...document, schemas: schemasWithExamples }, |
| 242 | + importerOptions |
| 243 | + ) |
| 244 | + for (let i = 0; i < schemasWithExamples.length; i++) { |
| 245 | + const node = schemasWithExamples[i] |
| 246 | + const examples = node.examples as ReadonlyArray<unknown> |
| 247 | + const validExamples = examples.filter(Schema.is(exampleSchemas[i])) |
| 248 | + if (validExamples.length === examples.length) continue |
| 249 | + if (validExamples.length === 0) { |
| 250 | + delete node.examples |
| 251 | + } else { |
| 252 | + node.examples = validExamples |
| 253 | + } |
222 | 254 | } |
| 255 | + rootSchemas = SchemaRepresentation.fromJsonSchemaMultiDocument(document, importerOptions) |
223 | 256 | } |
224 | | - const rootSchemas = SchemaRepresentation.fromJsonSchemaMultiDocument(document, importerOptions) |
225 | 257 | const codeDocument = SchemaRepresentation.toCodeDocument( |
226 | 258 | SchemaRepresentation.toRepresentations(Arr.map(rootSchemas, (schema) => schema.ast)) |
227 | 259 | ) |
|
0 commit comments