gcornut / valibot-json-schema

Converter from Valibot schemas to JSON schema
https://www.npmjs.com/package/@gcornut/valibot-json-schema
MIT License
38 stars 3 forks source link

Supporting transform schemas #71

Open dmsynge opened 1 week ago

dmsynge commented 1 week ago

Hi there! First of all, thanks for this excellent library!

I've got some schema that include transforms. At the moment, trying to generate a JSON Schema on a Valibot object that contains a transform results in an error: "Unsupported valibot validation transform for schema object".

Valibot seems able to infer input and output types of transforms with no issues, so I'm guessing it wouldn't be impossible to implement JSON schema generation.

One issue would be deciding whether the generate based on the input or output. For example, if you're generating an OpenAPI specification, it might make sense to use the transform input on requestBody, but the transform output for response content. So it would probably need a new option.

I don't think this is super urgent (I haven't explored fully, but I reckon it shouldn't be too difficult to work around it with customSchemaConversion or customValidationConversion options. But I expect others will run into this problem, too.

Anyway, let me know if this is something you've given any thought to -- and thanks again for the library :)

gcornut commented 1 week ago

Valibot schema transforms output can be inferred in the TS type system but this lib works in JS, at runtime. There is no way to access TS types data in JS directly.

There are some CLI utils that can convert TS types to JSON schema: example here. But you can't convert all of valibot in TS types (array size contraint, regexp literal, etc.). It's bit more heavy, you need to parse TS from source code and resolve all types (almost a full TS compilation process).

dmsynge commented 1 week ago

Thanks for the reply! Sorry, I did not mean that you could or should generate the schema from the valibot inferred types.

I only meant that the fact that valibot can infer input and output types of transformed schema (compared to Zod with ZodEffects types, etc) means that this might not be too difficult.

To be honest, I haven't yet looked at the internals of either valibot or valibot-json-schema to get a sense of how difficult it might be to implement, but if I have time over the next couple of weeks I will do so and submit a PR.