Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 43 lines 1.49 KB
Raw
1 import type { ZodBackend } from '../backend/types';
2 import type { JsonSchema, JsonSchemaObject } from '../types';
3
4 const admitsNull = (branches: JsonSchema[] | undefined): boolean =>
5 Array.isArray(branches) &&
6 branches.some(
7 (schema: JsonSchema) => typeof schema === 'object' && schema !== null && schema.type === 'null'
8 );
9
10 /**
11 * Wraps a parsed property for its place in an object: required properties
12 * stay as parsed, optional ones become optional, and an optional property
13 * with a `default` carries it. A `null` default makes the property nullable
14 * unless its schema already admits `null` through `anyOf`, `oneOf`, or
15 * `nullable`.
16 */
17 export const applyPropertyPresence = <S>(
18 backend: ZodBackend<S>,
19 propJsonSchema: JsonSchema,
20 parsed: S,
21 required: boolean
22 ): S => {
23 if (
24 !required &&
25 propJsonSchema &&
26 typeof propJsonSchema === 'object' &&
27 'default' in propJsonSchema
28 ) {
29 if (propJsonSchema.default === null) {
30 const isNullable =
31 'nullable' in propJsonSchema &&
32 (propJsonSchema as JsonSchemaObject & { nullable?: boolean }).nullable === true;
33
34 if (admitsNull(propJsonSchema.anyOf) || admitsNull(propJsonSchema.oneOf) || isNullable) {
35 return backend.withDefault(backend.optional(parsed), null);
36 }
37 return backend.withDefault(backend.optional(backend.nullable(parsed)), null);
38 }
39 return backend.withDefault(backend.optional(parsed), propJsonSchema.default);
40 }
41
42 return required ? parsed : backend.optional(parsed);
43 };