schema

    Download zip
    Author
    Version
    0.6.0
    License
    Zlib
    Last updated
    4 hours ago
    Downloads
    14

    No dependencies

    #Omochice/schema

    A typed schema DSL in which one definition yields both a JSON Schema and a decoder to a MoonBit value, so the schema a program advertises and the validation it performs cannot drift apart.

    #What is supported

    A schema is built from the combinators below.

    • Scalars: string, not_blank, literal, choice, iso_date, integer (Int32), integer64 (Int64), number, and boolean.
    • Containers: array, nullable, and record, whose members are required, optional, and optional_or handles read back through Values::get.
    • Variants: union for alternatives, and keyed and by_key for objects whose shape depends on a key they carry.
    • Refinements on any schema: describe, map, refine, allow_one, require_one, and require_any.
    • Schema::to_json_schema emits JSON Schema draft 2020-12, and Schema::parse decodes a value, raising SchemaError with the path of the offending member.

    #What is not supported

    The limits below follow from the design, which builds a schema by hand rather than from a type.

    • No derivation from a struct; every object is a record of listed members.
    • No JSON Schema keywords beyond those the combinators emit, other than what refine adds through keywords.
    • No validation of a JSON Schema itself; the module only produces one.

    #Usage

    The definition below decodes an object into a pair, filling in the default of a member that is absent, and advertises the matching schema. The block is a test, so moon test keeps it true.

    ///|
    test "one definition decodes a value and advertises its schema" {
    let name = @schema.required("name", @schema.not_blank())
    let limit = @schema.optional_or("limit", @schema.integer(min=1), 25)
    let query : @schema.Schema[(String, Int32)] = @schema.record(
    [name.as_member(), limit.as_member()],
    v => (v.get(name), v.get(limit)),
    )
    assert_eq(query.parse({ "name": "alice" }), ("alice", 25))
    inspect(
    query.to_json_schema().stringify(),
    content=(
    #|{"type":"object","properties":{"name":{"type":"string","pattern":"\\S"},"limit":{"type":"integer","minimum":1,"default":25}},"required":["name"],"additionalProperties":false}
    ),
    )
    }

    A value that fails the schema raises SchemaError, whose message names the member.

    #Omochice/schema

    A typed schema DSL in which one definition yields both a JSON Schema and a decoder to a MoonBit value, so the schema a program advertises and the validation it performs cannot drift apart.

    #What is supported

    A schema is built from the combinators below.

    • Scalars: string, not_blank, literal, choice, iso_date, integer (Int32), integer64 (Int64), number, and boolean.
    • Containers: array, nullable, and record, whose members are required, optional, and optional_or handles read back through Values::get.
    • Variants: union for alternatives, and keyed and by_key for objects whose shape depends on a key they carry.
    • Refinements on any schema: describe, map, refine, allow_one, require_one, and require_any.
    • Schema::to_json_schema emits JSON Schema draft 2020-12, and Schema::parse decodes a value, raising SchemaError with the path of the offending member.

    #What is not supported

    The limits below follow from the design, which builds a schema by hand rather than from a type.

    • No derivation from a struct; every object is a record of listed members.
    • No JSON Schema keywords beyond those the combinators emit, other than what refine adds through keywords.
    • No validation of a JSON Schema itself; the module only produces one.

    #Usage

    The definition below decodes an object into a pair, filling in the default of a member that is absent, and advertises the matching schema. The block is a test, so moon test keeps it true.

    ///|
    test "one definition decodes a value and advertises its schema" {
    let name = @schema.required("name", @schema.not_blank())
    let limit = @schema.optional_or("limit", @schema.integer(min=1), 25)
    let query : @schema.Schema[(String, Int32)] = @schema.record(
    [name.as_member(), limit.as_member()],
    v => (v.get(name), v.get(limit)),
    )
    assert_eq(query.parse({ "name": "alice" }), ("alice", 25))
    inspect(
    query.to_json_schema().stringify(),
    content=(
    #|{"type":"object","properties":{"name":{"type":"string","pattern":"\\S"},"limit":{"type":"integer","minimum":1,"default":25}},"required":["name"],"additionalProperties":false}
    ),
    )
    }

    A value that fails the schema raises SchemaError, whose message names the member.

    SchemaError

    pub(all) suberror SchemaError {
    Invalid(path~ : Array[String], message~ : String)
    Many(Array[SchemaError])
    }

    A validation failure. Invalid is one failed value; Many groups the failures reported together, such as several unknown keys.
    impl Show for SchemaError

    SchemaError::message

    fn SchemaError::message(self : SchemaError) -> String

    The failures of the error joined into one line.

    SchemaError::messages

    fn SchemaError::messages(self : SchemaError) -> Array[String]

    Every failed value of the error as a.b.c: message, or just message when the failure is at the root. Duplicates are dropped.

    SchemaError::output

    fn SchemaError::output(self : SchemaError, logger : &Logger) -> Unit

    SchemaError::to_string

    fn SchemaError::to_string(self : SchemaError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    Field

    type Field[T]

    A named member of an object whose parsed value is a T. It is declared once and then both listed in record and read from Values, so a value is always fetched by the name that produced it.

    Field::as_member

    fn[T] Field::as_member(self : Field[T]) -> Member

    Erases the value type so the field can be listed in record.

    Member

    type Member

    A Field with its value type erased so members of different types fit in one list.

    Schema

    pub(all) struct Schema[T] {
    json : () ->
    Json

    decode : (
    Json
    , Array[String]) -> T raise SchemaError
    }

    A JSON Schema paired with the parser that produces a T from a value satisfying it, so the advertised schema and the validation cannot drift.

    Schema::allow_one

    fn[T] Schema::allow_one(self : Schema[T], members : Array[Member]) -> Schema[T]

    Rejects an object that carries more than one of members, advertised as oneOf with an alternative for carrying none. A member counts as given when its key is present, as for required.

    Schema::describe

    fn[T] Schema::describe(self : Schema[T], text : String) -> Schema[T]

    Adds a description to the emitted schema.

    Schema::map

    fn[A, B] Schema::map(self : Schema[A], f : (A) -> B) -> Schema[B]

    Converts the parsed value; the emitted schema is unchanged.

    Schema::parse

    fn[T] Schema::parse(self : Schema[T], input :
    Json
    ) -> T raise SchemaError

    Parses input, raising SchemaError with the path of the offending value.

    Schema::refine

    fn[T] Schema::refine(self : Schema[T], check : (T) -> Bool, message : String, keywords? : Array[(String,
    Json
    )]) -> Schema[T]

    Rejects values for which check is false with message. keywords are added to the emitted schema so the advertised schema states the same constraint, e.g. a pattern that MoonBit cannot evaluate itself. A keyword the schema already carries with another value is kept beside the new one under allOf, since check is enforced on top of the earlier constraint rather than instead of it.

    Schema::require_any

    fn[T] Schema::require_any(self : Schema[T], members : Array[Member]) -> Schema[T]

    Rejects an object that carries none of members, advertised as anyOf. A member counts as given when its key is present, as for required.

    Schema::require_one

    fn[T] Schema::require_one(self : Schema[T], members : Array[Member]) -> Schema[T]

    Rejects an object that carries none or more than one of members, advertised as oneOf. A member counts as given when its key is present, as for required.

    Schema::to_json_schema

    fn[T] Schema::to_json_schema(self : Schema[T]) ->
    Json

    The JSON Schema (draft 2020-12) of the values the schema accepts.

    Values

    type Values

    The members of an object being parsed, read by Field handle.

    Values::get

    fn[T] Values::get(self : Values, field : Field[T]) -> T raise SchemaError

    The value of field, which must have been listed in record; raises SchemaError otherwise, because the schema never validated it.

    array

    fn[T] array(item : Schema[T], min_items? : Int) -> Schema[Array[T]]

    An array whose items all satisfy item.

    boolean

    fn boolean() -> Schema[Bool]

    A boolean.

    by_key

    fn[T] by_key(alternatives : Array[(String, Schema[T])], otherwise? : Schema[T]) -> Schema[T]

    Accepts an object by the first listed alternative whose key it carries, and anything else by otherwise. Unlike union, a failure reports only that alternative's errors.

    choice

    fn[T] choice(options : Array[(String, T)]) -> Schema[T]

    One of the listed names, parsed to the value paired with it.

    integer

    fn integer(min? : Int, max? : Int) -> Schema[Int]

    An integer, optionally bounded (inclusive).

    integer64

    fn integer64(min? : Int64, max? : Int64) -> Schema[Int64]

    An integer beyond the range of integer, such as a byte count, optionally bounded (inclusive).

    iso_date

    fn iso_date() -> Schema[String]

    A YYYY-MM-DD string naming a real calendar date, returned unchanged.

    keyed

    fn[T] keyed(entries : Array[(String, Schema[T])]) -> Schema[T]

    An object of exactly one key, naming an action, whose value is parsed by that action's schema. The top level stays a plain object because the Anthropic Messages API rejects anyOf, oneOf and allOf there.

    Aborts when an action is named twice.

    literal

    fn literal(value : String) -> Schema[String]

    Exactly the string value.

    not_blank

    fn not_blank(min_length? : Int, max_length? : Int) -> Schema[String]

    A string containing at least one non-whitespace character, optionally bounded in length (in characters) like string.

    nullable

    fn[T] nullable(inner : Schema[T]) -> Schema[T?]

    Accepts null as None, otherwise whatever inner accepts.

    number

    fn number(min? : Double, max? : Double) -> Schema[Double]

    A number, optionally bounded (inclusive).

    optional

    fn[T] optional(name : String, schema : Schema[T]) -> Field[T?]

    A member that may be absent, in which case its value is None.

    optional_or

    fn[T :
    ToJson
    ] optional_or(name : String, schema : Schema[T], default : T) -> Field[T]

    A member that may be absent, in which case its value is default. The default is advertised as the default keyword.

    record

    fn[T] record(members : Array[Member], build : (Values) -> T raise SchemaError) -> Schema[T]

    An object of exactly the listed members. Keys that no member names are rejected, every member is validated before build runs, and the failures of all of them are reported together.

    required

    fn[T] required(name : String, schema : Schema[T]) -> Field[T]

    A member that must be present.

    string

    fn string(min_length? : Int, max_length? : Int) -> Schema[String]

    A string, optionally bounded in length (in characters).

    union

    fn[T] union(alternatives : Array[Schema[T]]) -> Schema[T]

    Accepts what the first matching alternative accepts, emitted as anyOf. When no alternative matches, failures inside an object are reported by field; otherwise the alternatives' messages are listed.