zod
zod copied to clipboard
v4: toJSONSchema `.default()` `.catch()` input values considered non optional
Something tricky to deal with in my library when generating JSON Schema from Zod Types was figuring out whether to generate an input (request) type or a output (response) type. I assume that was the intention of the pipes parameter.
The current required implementation only considers the output type.
https://github.com/colinhacks/zod/blob/2ade678ffc5fbe609d92537f3910f91f15d77725/packages/core/src/util.ts#L538
I considered changing optional
https://github.com/colinhacks/zod/blob/2ade678ffc5fbe609d92537f3910f91f15d77725/packages/core/src/schemas.ts#L1480
to a function instead of a getter which takes an optional output defaulted pipes value but that lead me down a rabbit hole... Keen to help you implement this but I understand that this might require quite a bit of tinkering.
console.log(
JSON.stringify(
z.toJSONSchema(
z.object({
jobId: z.string().default("foo"), // or .catch()
}),
{
reused: "ref",
pipes: "output",
}
),
null,
2
)
);
{
"type": "object",
"properties": {
"jobId": {
"type": "string",
"default": "foo"
}
},
"required": [
"jobId"
]
}
In this scenario jobId should not be marked as required.