Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 06:00 UTC
| 1 | import { parseSchema } from './parse-schema'; |
| 2 | import { applyPropertyPresence } from './property-presence'; |
| 3 | import type { ParseContext } from '../context'; |
| 4 | import type { JsonSchemaObject } from '../types'; |
| 5 | import { |
| 6 | createWholeSchemaGuard, |
| 7 | guardSchemaAt, |
| 8 | requiresPermissiveMaterialization, |
| 9 | requiresWholeSchemaValidation, |
| 10 | } from '../whole-schema-validation'; |
| 11 | |
| 12 | /** |
| 13 | * Parses a JSON Schema object and returns the raw shape (property keys mapped to Zod types). |
| 14 | * This is useful when you need ZodRawShape instead of a complete ZodObject. |
| 15 | * |
| 16 | * @param objectSchema - The JSON Schema object to parse |
| 17 | * @param ctx - Parser context for handling nested schemas |
| 18 | * @returns A Zod raw shape object |
| 19 | */ |
| 20 | export function parseObjectShape<S>( |
| 21 | objectSchema: JsonSchemaObject, |
| 22 | ctx: ParseContext<S> |
| 23 | ): Record<string, S> { |
| 24 | if (!objectSchema.properties) { |
| 25 | return {}; |
| 26 | } |
| 27 | |
| 28 | const propertyKeys = Object.keys(objectSchema.properties); |
| 29 | if (propertyKeys.length === 0) { |
| 30 | return {}; |
| 31 | } |
| 32 | |
| 33 | const { backend } = ctx; |
| 34 | const properties: Record<string, S> = {}; |
| 35 | |
| 36 | for (const key of propertyKeys) { |
| 37 | const propJsonSchema = objectSchema.properties[key]; |
| 38 | const propCtx = { |
| 39 | ...ctx, |
| 40 | root: ctx.root ?? objectSchema, |
| 41 | path: [...ctx.path, 'properties', key], |
| 42 | }; |
| 43 | |
| 44 | const parsedProperty = parseSchema(propJsonSchema, propCtx); |
| 45 | // A permissive property (`$ref`, typeless constraints) already carries the |
| 46 | // identical guard from the permissive branch of `selectParser`; attaching |
| 47 | // again would run two full interpretations of the document per parse. A |
| 48 | // `parserOverride` result skips `selectParser`, so with an override in |
| 49 | // play the property keeps its own guard. |
| 50 | const carriesGuard = |
| 51 | ctx.parserOverride === undefined && requiresPermissiveMaterialization(propJsonSchema); |
| 52 | const propZodSchema = |
| 53 | requiresWholeSchemaValidation(propJsonSchema) && !carriesGuard |
| 54 | ? backend.attachGuard( |
| 55 | parsedProperty, |
| 56 | createWholeSchemaGuard(guardSchemaAt(propJsonSchema, propCtx)) |
| 57 | ) |
| 58 | : parsedProperty; |
| 59 | |
| 60 | const required = Array.isArray(objectSchema.required) |
| 61 | ? objectSchema.required.includes(key) |
| 62 | : false; |
| 63 | |
| 64 | properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required); |
| 65 | } |
| 66 | |
| 67 | return properties; |
| 68 | } |