arktype icon indicating copy to clipboard operation
arktype copied to clipboard

feat: Add JSON Schema to ArkType conversion

Open TizzySaurus opened this issue 1 year ago • 0 comments

Closes #729.

What

This PR adds @ark/jsonschema, which is a library enabling users to convert a valid JSON Schema schema into an ArkType type.

API

Below is a basic sample-use of @ark/jsonschema:

import { parseJsonSchema } from "@ark/jsonschema"

const type = parseJsonSchema({type: "string"})
// ^? 
// NB: `type` is correctly inferred as `Type<string>`, and can now be used as-per any other ArkType type

Remaining Work Before Merging

  • For some reason the innerParseJsonSchema const is giving a type error Type "string" is not assignable to type "never". It seems my explicit type definition is somehow wrong 🤷

  • For some reason parseJsonSchema({type: "array", items: {type: "string"}}) raises TypeError: this.Schema1Apply is not a function despite working against an earlier ArkType version (probably a bug in ArkType that I've not yet delved into to properly give details).

  • Similar to above, const t = parseJsonSchema({oneOf: [{type: "string"}, {type: "number"}]}) raises TypeError: this.CompositionKeywords1Apply is not a function: image

  • Tests are only partially implemented.

    • I wasn't entirely confident on what should/shouldn't be tested, and where things should/shouldn't be tested, so am waiting on feedback for this before finishing the tests.
      • For example, I have tests for {type: "string", "maxLength": 5} and {type: "string", "pattern": "es"}, but not {type: "string", "maxLength": 5, "pattern": "es"}. Is it worth having tests for the various "permutations"? I think this is perhaps overly excessive?
    • All test files also give this linting errors stating it can't find the @ark/jsonschema package: image
  • Haven't yet properly filled out ark/jsonschema/CHANGELOG.md.

  • Constraints are correctly inferred, but should ideally be displayed more "prettily" (see below image): image

  • I'd like to get custom type-errors working again, however the current problem is that calling parseJsonSchema with an invalid JSON Schema always results in a excessively deep and possibly infinite error, making this [seemingly] impossible. image

Known Limitations (things I didn't implement from JSON Schema spec)

  • No support for JSON Schema dependencies keyword on objects.
  • No support for JSON Schema if/else/then.
    • Sort of not required, since you can write the same (admittedly more verbosely) by combining any/oneOf/allOf/not.
  • multipleOf on numbers only supports integer divisors, due to ArkType only supporting integer divisors.

TizzySaurus avatar Oct 02 '24 15:10 TizzySaurus