diff --git a/src/contracts/inputSchemaPresentation.ts b/src/contracts/inputSchemaPresentation.ts index cc97088075..b25c534790 100644 --- a/src/contracts/inputSchemaPresentation.ts +++ b/src/contracts/inputSchemaPresentation.ts @@ -180,6 +180,79 @@ const isBooleanSchema = (schema: unknown): boolean => isObject(schema) && (schema.type === "boolean" || isBooleanLiteralSchema(schema)); +const isObjectKeyword = (key: string) => schemaMaps.has(key); +const isArrayKeyword = (key: string) => schemaArrays.has(key); +const isChildKeyword = (key: string) => schemaChildren.has(key); + +/** + * Remove every instance default below a schema, not only the one this keyword + * carries, keeping the entries at `kept`. A nested default belongs to the group + * that declares it: outside that group a client that fills it would send an + * object a strict sibling refuses. A default a reference still targets stays + * caller data; dropping it would leave that reference dangling. + */ +const omitNestedDefaults = ( + schema: unknown, + kept: ReadonlySet = new Set(), + path: readonly string[] = [], +): unknown => { + if (Array.isArray(schema)) + return schema.map((child, index) => + omitNestedDefaults(child, kept, [...path, String(index)]), + ); + if (!isObject(schema)) return schema; + return Object.fromEntries( + Object.entries(schema).flatMap(([key, value]) => { + const childPath = [...path, key]; + if (kept.has(JSON.stringify(childPath))) return [[key, value]]; + if (key === "default") return []; + return [ + [ + key, + isObjectKeyword(key) && isObject(value) + ? Object.fromEntries( + Object.entries(value).map(([name, child]) => [ + name, + omitNestedDefaults(child, kept, [...childPath, name]), + ]), + ) + : isArrayKeyword(key) && Array.isArray(value) + ? value.map((child, index) => + omitNestedDefaults(child, kept, [ + ...childPath, + String(index), + ]), + ) + : isChildKeyword(key) + ? Array.isArray(value) + ? value.map((child, index) => + omitNestedDefaults(child, kept, [ + ...childPath, + String(index), + ]), + ) + : omitNestedDefaults(value, kept, childPath) + : value, + ], + ]; + }), + ); +}; + +/** Every path into a `default` that a reference inside `schema` targets. */ +const referencedDefaultPaths = ( + schema: Readonly>, +): ReadonlySet => { + const kept = new Set(); + for (const { target } of new JsonSchemaReferences(schema).references()) { + if (target.kind !== "target") continue; + const defaultAt = target.path.indexOf("default"); + if (defaultAt < 0) continue; + kept.add(JSON.stringify(target.path.slice(0, defaultAt + 1))); + } + return kept; +}; + const preserveSharedDefault = ( schema: Record, branches: readonly unknown[], @@ -599,14 +672,19 @@ const flattenRootObjectUnion = ( const required = sharedRequiredProperties(branches); // A default lifted out of an input group can make a client send a field // rejected by another strict group. Keep it only when every group owns the - // property and supplies the same default. + // property and supplies the same default. A property some group omits takes + // its nested defaults too: filling only the inner property would otherwise + // still send an object that sibling group refuses. A default the nested + // property carries inside a group that does accept the parent stays, so + // callers keep that guidance. for (const [name, schemas] of variants) { - const defaults = branches.map((branch) => { - const property = isObject(branch.properties) - ? branch.properties[name] - : undefined; - return isObject(property) ? property.default : undefined; - }); + const properties = branches.map((branch) => + isObject(branch.properties) ? branch.properties[name] : undefined, + ); + const ownedByEveryGroup = properties.every(isObject); + const defaults = properties.map((property) => + isObject(property) ? property.default : undefined, + ); if ( defaults.every( (value) => value !== undefined && isDeepStrictEqual(value, defaults[0]), @@ -615,11 +693,16 @@ const flattenRootObjectUnion = ( continue; const withoutDefaults: unknown[] = []; for (const schema of schemas) { - let withoutDefault = schema; - if (isObject(schema) && Object.hasOwn(schema, "default")) { - const { default: _default, ...rest } = schema; - withoutDefault = rest; - } + const withoutDefault = ownedByEveryGroup + ? isObject(schema) && Object.hasOwn(schema, "default") + ? Object.fromEntries( + Object.entries(schema).filter(([key]) => key !== "default"), + ) + : schema + : omitNestedDefaults( + schema, + isObject(schema) ? referencedDefaultPaths(schema) : new Set(), + ); if ( !withoutDefaults.some((known) => isDeepStrictEqual(known, withoutDefault), diff --git a/src/contracts/toolInputReferences.test.ts b/src/contracts/toolInputReferences.test.ts index 712465b3ee..3edd34111b 100644 --- a/src/contracts/toolInputReferences.test.ts +++ b/src/contracts/toolInputReferences.test.ts @@ -831,3 +831,116 @@ it.each(["$ref", "$dynamicRef"])( expect(advertised(value)).toBe(canonical(value)); }, ); + +describe("root union default presentation", () => { + it.each(["draft-2020-12", "draft-07"] as const)( + "omits a nested default the other root group would refuse in %s", + (target) => { + const normalization = z + .strictObject({ rules: z.array(z.string()).default([]) }) + .default({ rules: [] }); + const schema = z.union([ + z.strictObject({ before: z.string(), after: z.string() }), + z.strictObject({ + before_scenario: z.string(), + after_scenario: z.string(), + normalization, + }), + ]); + const canonical = z.toJSONSchema(schema, { io: "input", target }); + const advertised = presentInputJsonSchema( + canonical, + (property) => property, + ); + const defaults: string[] = []; + const collect = (value: unknown, path: readonly string[]): void => { + if (Array.isArray(value)) { + value.forEach((child, index) => + collect(child, [...path, String(index)]), + ); + return; + } + if (typeof value !== "object" || value === null) return; + if (Object.hasOwn(value, "default")) defaults.push(path.join(".")); + for (const [key, child] of Object.entries(value)) + collect(child, [...path, key]); + }; + collect(advertised, []); + // `normalization` belongs to the scenario group only. Leaving its + // `rules` default behind made a client that fills nested defaults send + // an object the strict passive group rejects. + expect(defaults).toEqual([]); + const ajv = + target === "draft-2020-12" + ? new Ajv2020({ strict: false }) + : new Ajv({ strict: false }); + expect( + ajv.compile(advertised)({ before: "first", after: "second" }), + ).toBe(true); + expect( + schema.safeParse({ + before: "first", + after: "second", + normalization: { rules: [] }, + }).success, + ).toBe(false); + }, + ); + + it.each(["draft-2020-12", "draft-07"] as const)( + "keeps a nested default a reference inside its resource targets in %s", + (target) => { + const schema = z.union([ + z.strictObject({ before: z.string(), after: z.string() }), + z.strictObject({ + before_scenario: z.string(), + after_scenario: z.string(), + normalization: z + .object({ rules: z.array(z.string()).optional() }) + .default({ rules: [] }), + }), + ]); + const canonical = z.toJSONSchema(schema, { io: "input", target }) as { + anyOf: { + properties: Record>; + required: string[]; + additionalProperties: boolean; + }[]; + }; + // A nested resource keeps the group, so the union still flattens. Its + // sibling reference points into the default the flattening would drop. + const scenario = canonical.anyOf[1] as NonNullable< + (typeof canonical.anyOf)[1] + >; + const normalization = scenario.properties.normalization as Record< + string, + unknown + >; + canonical.anyOf[1] = { + ...scenario, + properties: { + ...scenario.properties, + normalization: { + $id: "https://example.test/normalization", + ...normalization, + properties: { + ...(normalization.properties as Record), + alias: { $ref: "#/default/rules" }, + }, + }, + }, + }; + const advertised = presentInputJsonSchema( + canonical, + (property) => property, + ); + expect(advertised).not.toHaveProperty("anyOf"); + const ajv = + target === "draft-2020-12" + ? new Ajv2020({ strict: false }) + : new Ajv({ strict: false }); + const validate = ajv.compile(advertised); + expect(validate({ before: "first", after: "second" })).toBe(true); + }, + ); +});