(logger: Logger, jsonSchema: Record<string, any>)
| 2 | import { z } from 'zod' |
| 3 | |
| 4 | function jsonSchemaToZod(logger: Logger, jsonSchema: Record<string, any>): z.ZodTypeAny { |
| 5 | if (!jsonSchema) { |
| 6 | logger.error('Invalid schema: Schema is null or undefined') |
| 7 | throw new Error('Invalid schema: Schema is required') |
| 8 | } |
| 9 | |
| 10 | // Handle non-object schemas (strings, numbers, etc.) |
| 11 | if (typeof jsonSchema !== 'object' || jsonSchema === null) { |
| 12 | logger.warn('Schema is not an object, defaulting to any', { type: typeof jsonSchema }) |
| 13 | return z.any() |
| 14 | } |
| 15 | |
| 16 | // Handle different schema types |
| 17 | if (jsonSchema.type === 'object' && jsonSchema.properties) { |
| 18 | const shape: Record<string, z.ZodTypeAny> = {} |
| 19 | |
| 20 | // Create a zod object for each property |
| 21 | for (const [key, propSchema] of Object.entries(jsonSchema.properties)) { |
| 22 | shape[key] = jsonSchemaToZod(logger, propSchema as Record<string, any>) |
| 23 | |
| 24 | // Add description if available |
| 25 | if ((propSchema as Record<string, any>).description) { |
| 26 | shape[key] = shape[key].describe((propSchema as Record<string, any>).description) |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // Create the base object |
| 31 | let zodObject = z.object(shape) |
| 32 | |
| 33 | // Handle required fields if specified |
| 34 | if (jsonSchema.required && Array.isArray(jsonSchema.required)) { |
| 35 | // For each property that's not in required, make it optional |
| 36 | for (const key of Object.keys(jsonSchema.properties)) { |
| 37 | if (!jsonSchema.required.includes(key)) { |
| 38 | shape[key] = shape[key].optional() |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Recreate the object with the updated shape |
| 43 | zodObject = z.object(shape) |
| 44 | } |
| 45 | |
| 46 | return zodObject |
| 47 | } |
| 48 | if (jsonSchema.type === 'array' && jsonSchema.items) { |
| 49 | const itemSchema = jsonSchemaToZod(logger, jsonSchema.items as Record<string, any>) |
| 50 | let arraySchema = z.array(itemSchema) |
| 51 | |
| 52 | // Add description if available |
| 53 | if (jsonSchema.description) { |
| 54 | arraySchema = arraySchema.describe(jsonSchema.description) |
| 55 | } |
| 56 | |
| 57 | return arraySchema |
| 58 | } |
| 59 | if (jsonSchema.type === 'string') { |
| 60 | let stringSchema = z.string() |
| 61 |
no test coverage detected