import type { ZodTypeAny } from 'zod'; import { toToolParameters } from '../../utils/zodToJson.js'; type Node = Record; const isNode = (value: unknown): value is Node => value !== null && typeof value === 'object' && !Array.isArray(value); // Visit *schema nodes*, never property maps, enum data or examples. function children(node: Node, visit: (node: Node, hint: string) => Node, hint: string): Node { const out = { ...node }; if (isNode(node.properties)) out.properties = Object.fromEntries( Object.entries(node.properties).map(([key, value]) => [key, isNode(value) ? visit(value, key) : value]), ); if (isNode(node.items)) out.items = visit(node.items, hint + 'Item'); for (const key of ['allOf', 'anyOf', 'oneOf']) { const entries = node[key]; if (Array.isArray(entries)) out[key] = entries.map((item, i) => isNode(item) ? visit(item, hint + i) : item); } return out; } /** Local pointers are rooted inside *each tool's own parameters document*. * This is a size projection only: no field, constraint, alias or description * is dropped. Tools that never repeat a large subtree stay untouched. */ export function browserParameters(schema: ZodTypeAny): object { const root = toToolParameters(schema) as Node; const counts = new Map(); function count(node: Node, hint: string): Node { if (node.properties || node.items) { const key = JSON.stringify(node); if (key.length > 100) counts.set(key, (counts.get(key) ?? 0) + 1); } children(node, count, hint); return node; } count(root, 'input'); const names = new Map(); const defs: Record = {}; function compact(node: Node, hint: string): Node { const key = JSON.stringify(node); if ((counts.get(key) ?? 0) < 2) return children(node, compact, hint); let name = names.get(key); if (!name) { name = hint.replace(/[^A-Za-z0-9_]/g, '') || 'entry'; while (Object.hasOwn(defs, name)) name += '_'; names.set(key, name); defs[name] = {}; defs[name] = children(node, compact, hint); } return { $ref: '#/$defs/' + name }; } const result = children(root, compact, 'input'); return Object.keys(defs).length ? { ...result, $defs: defs } : result; }