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 186 lines 6.58 KB
Raw
1 import { z } from 'zod';
2
3 const ObjectSchema = z.record(z.string(), z.unknown());
4 const Schema = z
5 .object({
6 $ref: z.string().optional(),
7 deprecated: z.boolean().optional(),
8 properties: z.record(z.string(), z.unknown()).optional(),
9 required: z.array(z.string()).optional(),
10 })
11 .loose();
12
13 // These are payloads, not schemas. In particular, a payload may legitimately
14 // contain properties named "deprecated" or "properties".
15 const PAYLOAD_KEYS = new Set(['default', 'example', 'examples', 'enum', 'const']);
16 const SCHEMA_MAPS = new Set([
17 'properties',
18 'patternProperties',
19 '$defs',
20 'definitions',
21 'dependentSchemas',
22 ]);
23 const SCHEMA_LISTS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
24 const SCHEMA_CHILDREN = new Set([
25 'items',
26 'additionalProperties',
27 'contains',
28 'not',
29 'if',
30 'then',
31 'else',
32 'propertyNames',
33 'unevaluatedProperties',
34 ]);
35
36 /** Filter only the playground copy; keep the reference and published contract intact. */
37 export function hideDeprecatedFields<T extends object>(input: T): T {
38 const document = structuredClone(input);
39 function object(value: unknown) {
40 const parsed = ObjectSchema.safeParse(value);
41 if (!parsed.success) return undefined;
42 return parsed.data;
43 }
44
45 function resolvePointer(ref: string): unknown {
46 if (!ref.startsWith('#/')) return undefined;
47 let value: unknown = input;
48 for (const part of ref.slice(2).split('/')) {
49 value = object(value)?.[decodeURIComponent(part).replace(/~1/g, '/').replace(/~0/g, '~')];
50 }
51 return value;
52 }
53
54 function resolve(value: unknown, seen = new Set<string>()): z.infer<typeof Schema> | undefined {
55 const parsed = Schema.safeParse(value);
56 if (!parsed.success) return undefined;
57 const schema = parsed.data;
58 if (!schema.$ref || seen.has(schema.$ref)) return schema;
59 seen.add(schema.$ref);
60 return { ...resolve(resolvePointer(schema.$ref), seen), ...schema };
61 }
62
63 function schemaVariants(value: unknown, seen = new Set<unknown>()): z.infer<typeof Schema>[] {
64 if (seen.has(value)) return [];
65 seen.add(value);
66 const schema = resolve(value);
67 if (!schema) return [];
68 return [
69 schema,
70 ...['allOf', 'anyOf', 'oneOf'].flatMap(key => {
71 const variants = schema[key];
72 return Array.isArray(variants) ? variants.flatMap(item => schemaVariants(item, seen)) : [];
73 }),
74 ];
75 }
76
77 function properties(value: unknown) {
78 const result = new Map<string, unknown[]>();
79 for (const schema of schemaVariants(value)) {
80 for (const [name, child] of Object.entries(schema.properties ?? {})) {
81 result.set(name, [...(result.get(name) ?? []), child]);
82 }
83 }
84 return result;
85 }
86
87 const allDeprecated = (schemas: unknown[]) =>
88 schemas.every(schema => resolve(schema)?.deprecated === true);
89
90 // Inspect the original schemas, which still contain the deprecation flags.
91 // If a union also defines a current field with this name, preserve its value.
92 function cleanValue(value: unknown, rawSchema: unknown): unknown {
93 if (Array.isArray(value)) {
94 const items = schemaVariants(rawSchema)
95 .map(schema => schema.items)
96 .filter(item => item !== undefined);
97 return value.map(item => cleanValue(item, { allOf: items }));
98 }
99 const record = object(value);
100 if (!record) return value;
101 for (const [name, children] of properties(rawSchema)) {
102 if (allDeprecated(children)) delete record[name];
103 else if (Object.hasOwn(record, name))
104 record[name] = cleanValue(record[name], { allOf: children });
105 }
106 return record;
107 }
108
109 function filterSchema(value: unknown): unknown {
110 const parsed = Schema.safeParse(value);
111 if (!parsed.success) return value; // Boolean schemas are valid in OpenAPI 3.1.
112 const schema = parsed.data;
113 if (schema.properties) {
114 const hidden = new Set(
115 Object.entries(schema.properties)
116 .filter(([, child]) => resolve(child)?.deprecated === true)
117 .map(([name]) => name)
118 );
119 schema.properties = Object.fromEntries(
120 Object.entries(schema.properties)
121 .filter(([name]) => !hidden.has(name))
122 .map(([name, child]) => [name, filterSchema(child)])
123 );
124 }
125 if (schema.required) {
126 const fields = properties(value);
127 schema.required = schema.required.filter(name => {
128 const definitions = fields.get(name);
129 return !definitions || !allDeprecated(definitions);
130 });
131 }
132 for (const [key, child] of Object.entries(schema)) {
133 if (key === 'default' || key === 'example') schema[key] = cleanValue(child, value);
134 else if (key === 'examples' && Array.isArray(child))
135 schema[key] = child.map(item => cleanValue(item, value));
136 else if (key !== 'properties' && SCHEMA_MAPS.has(key)) {
137 const map = object(child);
138 if (map)
139 schema[key] = Object.fromEntries(
140 Object.entries(map).map(([name, item]) => [name, filterSchema(item)])
141 );
142 } else if (SCHEMA_LISTS.has(key) && Array.isArray(child))
143 schema[key] = child.map(filterSchema);
144 else if (SCHEMA_CHILDREN.has(key)) schema[key] = filterSchema(child);
145 }
146 return schema;
147 }
148
149 function walk(value: unknown, key = ''): unknown {
150 if (Array.isArray(value)) return value.map(item => walk(item));
151 const record = object(value);
152 if (!record) return value;
153 for (const [name, child] of Object.entries(record)) {
154 if (name === 'schema') record[name] = filterSchema(child);
155 else if (key === 'components' && name === 'schemas') {
156 const schemas = object(child);
157 if (schemas)
158 record[name] = Object.fromEntries(
159 Object.entries(schemas).map(([id, schema]) => [id, filterSchema(schema)])
160 );
161 } else if (!PAYLOAD_KEYS.has(name) && !name.startsWith('x-'))
162 record[name] = walk(child, name);
163 }
164 if (record.schema) {
165 if (Object.hasOwn(record, 'example'))
166 record.example = cleanValue(record.example, object(value)?.schema);
167 const examples = object(record.examples);
168 if (examples) {
169 record.examples = Object.fromEntries(
170 Object.entries(examples).map(([name, entry]) => {
171 const example = resolve(entry);
172 if (example && Object.hasOwn(example, 'value')) {
173 example.value = cleanValue(example.value, object(value)?.schema);
174 delete example.$ref; // Inline this usage so shared examples remain unchanged.
175 }
176 return [name, example ?? entry];
177 })
178 );
179 }
180 }
181 return record;
182 }
183
184 Object.assign(document, walk(document));
185 return document;
186 }