const schemaMaps = new Set([ "$defs", "definitions", "properties", "patternProperties", "dependentSchemas", "dependencies", ]); const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]); const schemaChildren = new Set([ "items", "additionalItems", "contains", "additionalProperties", "unevaluatedProperties", "unevaluatedItems", "propertyNames", "not", "if", "then", "else", ]); const isObject = (value: unknown): value is Readonly> => typeof value === "object" && value !== null && !Array.isArray(value); const resolveReference = ( root: Readonly>, reference: string, ): unknown => { if (!reference.startsWith("#/")) return undefined; let value: unknown = root; for (const token of reference.slice(2).split("/")) { const key = token.replaceAll("~1", "/").replaceAll("~0", "~"); if (!isObject(value) || !Object.hasOwn(value, key)) return undefined; value = value[key]; } return value; }; const referencedDescription = ( root: Readonly>, schema: Readonly>, ): string | undefined => { let value: unknown = schema; const active = new Set(); while (isObject(value)) { if (typeof value.description === "string") return value.description; if (typeof value.$ref !== "string" || active.has(value.$ref)) return undefined; active.add(value.$ref); value = resolveReference(root, value.$ref); } return undefined; }; const describeSchema = ( schema: unknown, root: Readonly>, describeProperty: (property: string) => string, ): unknown => { if (!isObject(schema)) return schema; return Object.fromEntries( Object.entries(schema).map(([key, value]) => { if (schemaMaps.has(key) && isObject(value)) return [ key, Object.fromEntries( Object.entries(value).map(([name, child]) => { const described = describeSchema(child, root, describeProperty); return [ name, key === "properties" && isObject(described) ? { ...described, description: referencedDescription(root, described) ?? describeProperty(name), } : described, ]; }), ), ]; if (schemaArrays.has(key) && Array.isArray(value)) return [ key, value.map((child) => describeSchema(child, root, describeProperty)), ]; if (schemaChildren.has(key)) return [ key, Array.isArray(value) ? value.map((child) => describeSchema(child, root, describeProperty), ) : describeSchema(value, root, describeProperty), ]; // Annotation values and literal const/enum data are not schemas. return [key, value]; }), ); }; /** Describe canonical input fields without changing structural constraints. */ export const presentInputJsonSchema = ( root: Record, describeProperty: (property: string) => string, ): Record => { const described = describeSchema(root, root, describeProperty); return isObject(described) ? described : root; };