(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams)
| 627 | /** |
| 628 | * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */ |
| 629 | export function fromJSONSchema(schema: JSONSchema.JSONSchema | boolean, params?: FromJSONSchemaParams): ZodType { |
| 630 | // Handle boolean schemas |
| 631 | if (typeof schema === "boolean") { |
| 632 | return schema ? z.any() : z.never(); |
| 633 | } |
| 634 | |
| 635 | // Normalize input via a JSON round-trip. This guarantees the converter |
| 636 | // walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, |
| 637 | // getter/Proxy-based properties are materialized into static values, and |
| 638 | // class instances collapse to plain objects. |
| 639 | let normalized: JSONSchema.JSONSchema; |
| 640 | try { |
| 641 | normalized = JSON.parse(JSON.stringify(schema)); |
| 642 | } catch { |
| 643 | throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas"); |
| 644 | } |
| 645 | |
| 646 | const version = detectVersion(normalized, params?.defaultTarget); |
| 647 | const defs = (normalized.$defs || normalized.definitions || {}) as Record<string, JSONSchema.JSONSchema>; |
| 648 | |
| 649 | const ctx: ConversionContext = { |
| 650 | version, |
| 651 | defs, |
| 652 | refs: new Map(), |
| 653 | processing: new Set(), |
| 654 | rootSchema: normalized, |
| 655 | registry: params?.registry ?? globalRegistry, |
| 656 | }; |
| 657 | |
| 658 | return convertSchema(normalized, ctx); |
| 659 | } |
no test coverage detected