@devries-cameron20 / composio Mirror · read-only
Fork 0

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

next
ts 259 lines 8.34 KB
Raw
1 import { parseAllOf } from './parse-all-of';
2 import { parseAnyOf } from './parse-any-of';
3 import { parseOneOf } from './parse-one-of';
4 import { parseSchema } from './parse-schema';
5 import { applyPropertyPresence } from './property-presence';
6 import type { ParseContext } from '../context';
7 import type { JsonSchemaObject } from '../types';
8 import { compilePattern } from '../utils/compile-pattern';
9 import { its } from '../utils/its';
10
11 /**
12 * Build the static part of an object parser, or `undefined` when the schema
13 * declares no named properties.
14 *
15 * A property-less object (`properties` absent or `{}`) deliberately returns
16 * `undefined` so the caller can apply the open-object policy. This supersedes
17 * an earlier `z.object({})` fallback that was kept "or else this will break
18 * openai responses": collapsing `{ type: "object" }` to a strict empty object
19 * is the defect it was masking, and the OpenAI provider suite is part of this
20 * package's verification precisely so the claim stays checked.
21 */
22 function parseObjectProperties<S>(
23 objectSchema: JsonSchemaObject & { type?: 'object' },
24 ctx: ParseContext<S>
25 ): Record<string, S> | undefined {
26 if (!objectSchema.properties) {
27 return undefined;
28 }
29
30 const propertyKeys = Object.keys(objectSchema.properties);
31 if (propertyKeys.length === 0) {
32 return undefined;
33 }
34
35 const { backend } = ctx;
36 const properties: Record<string, S> = {};
37
38 for (const key of propertyKeys) {
39 const propJsonSchema = objectSchema.properties[key];
40
41 const propZodSchema = parseSchema(propJsonSchema, {
42 ...ctx,
43 path: [...ctx.path, 'properties', key],
44 });
45
46 const required = Array.isArray(objectSchema.required)
47 ? objectSchema.required.includes(key)
48 : false;
49
50 properties[key] = applyPropertyPresence(backend, propJsonSchema, propZodSchema, required);
51 }
52
53 return properties;
54 }
55
56 /**
57 * Object parser for schemas carrying `patternProperties`.
58 *
59 * Every key is routed to exactly the schemas that apply to it — each matching
60 * pattern, and `additionalProperties` only when no pattern and no named
61 * property claims the key. A catch-all union would instead let a key sneak past
62 * its own pattern by satisfying an unrelated one.
63 */
64 function parseDynamicKeyObject<S>(
65 normalizedSchema: JsonSchemaObject & { type?: 'object' },
66 shape: Record<string, S> | undefined,
67 additionalProperties: S | undefined,
68 ctx: ParseContext<S>
69 ): S {
70 const { backend } = ctx;
71 const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(
72 ([pattern, schema]) => ({
73 regex: compilePattern('patternProperties', pattern, ctx),
74 parser: parseSchema(schema, {
75 ...ctx,
76 path: [...ctx.path, 'patternProperties', pattern],
77 }),
78 })
79 );
80
81 const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
82 const rejectsUnmatched =
83 (additionalProperties !== undefined && backend.isNever(additionalProperties)) ||
84 (additionalProperties === undefined && declaredKeys.size > 0);
85 const validatesUnmatched =
86 additionalProperties !== undefined &&
87 !backend.isNever(additionalProperties) &&
88 normalizedSchema.additionalProperties !== true;
89
90 const base = backend.object(shape ?? {}, { kind: 'loose' });
91
92 return backend.rewrite<Record<string, unknown>>(base, (value, issues) => {
93 const result: Record<string, unknown> = { ...value };
94 const unrecognizedKeys: string[] = [];
95
96 for (const key of Object.keys(value)) {
97 const matching = patterns.filter(({ regex }) => regex.test(key));
98
99 for (const { parser } of matching) {
100 const parsed = backend.run(parser, value[key]);
101 if (!parsed.success) {
102 issues.custom(`Invalid input: key "${key}" must match its patternProperties schema`, {
103 path: [key],
104 params: { issues: parsed.failure.issues },
105 });
106 } else if (!declaredKeys.has(key)) {
107 result[key] = parsed.data;
108 }
109 }
110
111 if (matching.length > 0 || declaredKeys.has(key)) {
112 continue;
113 }
114
115 if (rejectsUnmatched) {
116 unrecognizedKeys.push(key);
117 } else if (validatesUnmatched) {
118 const parsed = backend.run(additionalProperties!, value[key]);
119 if (!parsed.success) {
120 issues.custom(`Invalid input: key "${key}" must match the additionalProperties schema`, {
121 path: [key],
122 params: { issues: parsed.failure.issues },
123 });
124 } else {
125 result[key] = parsed.data;
126 }
127 }
128 }
129
130 if (unrecognizedKeys.length > 0) {
131 issues.unrecognizedKeys(
132 unrecognizedKeys,
133 `Unrecognized key(s) in object: ${unrecognizedKeys.map(key => `'${key}'`).join(', ')}`
134 );
135 }
136
137 return result;
138 });
139 }
140
141 export function parseObject<S>(
142 objectSchema: JsonSchemaObject & { type?: 'object' },
143 ctx: ParseContext<S>
144 ): S {
145 const { backend } = ctx;
146 const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
147
148 // Ensure type is set to 'object' if not already
149 const normalizedSchema =
150 objectSchema.type === 'object' ? objectSchema : { ...objectSchema, type: 'object' as const };
151
152 const shape = parseObjectProperties(normalizedSchema, ctx);
153
154 const additionalProperties =
155 normalizedSchema.additionalProperties !== undefined
156 ? parseSchema(normalizedSchema.additionalProperties, {
157 ...ctx,
158 path: [...ctx.path, 'additionalProperties'],
159 })
160 : undefined;
161
162 // Track if additionalProperties was explicitly set to true
163 const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
164
165 let output: S;
166 if (hasPatternProperties) {
167 output = parseDynamicKeyObject(normalizedSchema, shape, additionalProperties, ctx);
168 } else if (shape) {
169 if (additionalProperties) {
170 if (backend.isNever(additionalProperties)) {
171 output = backend.object(shape, { kind: 'strict' });
172 } else if (isAdditionalPropertiesTrue) {
173 // When additionalProperties was explicitly true, use passthrough
174 output = backend.object(shape, { kind: 'loose' });
175 } else {
176 output = backend.object(shape, { kind: 'catchall', schema: additionalProperties });
177 }
178 } else {
179 // Named properties with an omitted `additionalProperties` stay strict for
180 // tool inputs, even though JSON Schema itself would allow unknown keys.
181 output = backend.object(shape, { kind: 'strict' });
182 }
183 } else {
184 if (additionalProperties) {
185 if (backend.isNever(additionalProperties)) {
186 // When additionalProperties is false, create strict empty object
187 output = backend.object({}, { kind: 'strict' });
188 } else if (isAdditionalPropertiesTrue) {
189 // When additionalProperties was explicitly true, use empty object with passthrough
190 output = backend.object({}, { kind: 'loose' });
191 } else {
192 output = backend.record(additionalProperties);
193 }
194 } else {
195 // A property-less object with no `additionalProperties` keyword is open:
196 // arbitrary content is accepted and preserved verbatim.
197 output = backend.object({}, { kind: 'loose' });
198 }
199 }
200
201 if (its.an.anyOf(objectSchema)) {
202 output = backend.intersection(
203 output,
204 parseAnyOf(
205 {
206 ...objectSchema,
207 anyOf: objectSchema.anyOf.map(x =>
208 typeof x === 'object' &&
209 !x.type &&
210 (x.properties ?? x.additionalProperties ?? x.patternProperties)
211 ? { ...x, type: 'object' }
212 : x
213 ),
214 },
215 ctx
216 )
217 );
218 }
219
220 if (its.a.oneOf(objectSchema)) {
221 output = backend.intersection(
222 output,
223 parseOneOf(
224 {
225 ...objectSchema,
226 oneOf: objectSchema.oneOf.map(x =>
227 typeof x === 'object' &&
228 !x.type &&
229 (x.properties ?? x.additionalProperties ?? x.patternProperties)
230 ? { ...x, type: 'object' }
231 : x
232 ),
233 },
234 ctx
235 )
236 );
237 }
238
239 if (its.an.allOf(objectSchema)) {
240 output = backend.intersection(
241 output,
242 parseAllOf(
243 {
244 ...objectSchema,
245 allOf: objectSchema.allOf.map(x =>
246 typeof x === 'object' &&
247 !x.type &&
248 (x.properties ?? x.additionalProperties ?? x.patternProperties)
249 ? { ...x, type: 'object' }
250 : x
251 ),
252 },
253 ctx
254 )
255 );
256 }
257
258 return output;
259 }