fix(contracts): drop nested defaults from a root union sibling (#10254)

* fix(contracts): drop nested defaults from a root union sibling

Flattening a union of strict object groups lifts each group's properties
into one object. A default the scenario group carried inside
normalization.rules survived that lift even though the passive group
declares no normalization, so a client that fills nested defaults sent
{normalization: {rules: []}} and the runtime parser refused the call
with "Unrecognized key: normalization".

Remove defaults below a property that any group omits, not just the one
on the property itself. A property every group owns keeps its own
nested guidance.

* fix(contracts): keep a nested default a reference still targets

Dropping the nested default of a property a sibling group omits also removed defaults that references point into. A resource whose validation $ref targets its own default was advertised with that reference intact but its target gone, so the advertised schema no longer compiled in AJV or client projection.

Collect the paths into a default that references inside the branch target and keep those entries while stripping the rest. Other nested defaults are still removed, so the strict sibling group keeps refusing the object.

* test(contracts): type the root union default regression fixture

The fixture spread the canonical branch through a widened cast, so the repository typecheck rejected the spread and indexed access. Narrow the branch shape and guard the optional schema before collecting its referenced defaults.

---------

Co-authored-by: 2SinceJuly <202121119+2SinceJuly@users.noreply.github.com>
This commit is contained in:
2SinceJulyand2SinceJuly authored and GitHub committed 2026-11-12 19:27:58 -05:00
1 parent 9d32836d37
commit 7559e06740
2 files changed
+208 -12

No files matched your search

+95 -12
View File
@@ -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<string> = 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<Record<string, unknown>>,
): ReadonlySet<string> => {
const kept = new Set<string>();
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<string, unknown>,
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),
+113
View File
@@ -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<string, Record<string, unknown>>;
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<string, unknown>),
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);
},
);
});