Documentation
¶
Overview ¶
Package schema validates JSON values against JSON Schema drafts 2020-12 and 7 without code generation: Compile builds a schema once into closures, and the builders return plain JSON Schema objects.
Index ¶
- type AnnotationOption
- type ArrayOption
- type BytesOption
- type Check
- type CoercingValidator
- type CompileOptions
- type Draft
- type FormatCheck
- type JsonSchema
- type LengthOption
- type NumberOption
- type Object
- type ObjectOption
- type ParseResult
- type Properties
- type Property
- type Schema
- func Arr(items Schema, options ...ArrayOption) Schema
- func Bool(options ...AnnotationOption) Schema
- func Bytes(options ...BytesOption) Schema
- func Int(options ...NumberOption) Schema
- func Lit(value any, options ...AnnotationOption) Schema
- func Map(value Schema, options ...AnnotationOption) Schema
- func Nul(options ...AnnotationOption) Schema
- func Nullable(schema Schema, options ...AnnotationOption) Schema
- func Num(options ...NumberOption) Schema
- func Obj(properties Properties, options ...ObjectOption) Schema
- func OneOf(values []any, options ...AnnotationOption) Schema
- func Str(options ...StrOption) Schema
- func Tuple(items []Schema, options ...AnnotationOption) Schema
- func Union(schemas []Schema, options ...AnnotationOption) Schema
- func Unknown(options ...AnnotationOption) Schema
- type StrOption
- type UnresolvedRefs
- type ValidationError
- type Validator
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AnnotationOption ¶
type AnnotationOption interface {
StrOption
NumberOption
ArrayOption
BytesOption
ObjectOption
// contains filtered or unexported methods
}
AnnotationOption is an option every builder accepts: it describes the schema and never changes what it accepts. It satisfies every builder's option type.
func Default ¶
func Default(value any) AnnotationOption
Default sets `default`, an annotation for tools and forms: validation never inserts it.
type ArrayOption ¶
type ArrayOption interface {
// contains filtered or unexported methods
}
ArrayOption is an option of Arr.
func UniqueItems ¶
func UniqueItems(unique bool) ArrayOption
UniqueItems sets `uniqueItems` of an array.
type BytesOption ¶
type BytesOption interface {
// contains filtered or unexported methods
}
BytesOption is an option of Bytes.
type CoercingValidator ¶
type CoercingValidator struct {
*Validator
// contains filtered or unexported fields
}
CoercingValidator is a Validator that also coerces loosely typed input towards the schema. It is safe for concurrent use.
func CompileCoercing ¶
func CompileCoercing(schema JsonSchema, options CompileOptions) (*CoercingValidator, error)
CompileCoercing compiles schema into a CoercingValidator: a Validator that also coerces and parses loosely typed input (Pi's `compile(schema, { coerce: true })`). It fails where Compile does.
func (*CoercingValidator) Coerce ¶
func (v *CoercingValidator) Coerce(value any) (any, error)
Coerce returns value coerced towards the schema: numeric strings to numbers, "true" to true, a single value to a one-item array, an optional null dropped, the first union branch the value converts to (the README lists every rule). Only the changed paths are copied; value comes back itself when nothing changes, and is never modified. Values that cannot be coerced stay as they are. The rules are built on the first call. The error is the one Pi's `coerce` throws: a pattern of the schema that is not a regular expression, or a dynamic reference that cannot be compiled, in a part of the schema the check never compiled.
func (*CoercingValidator) Parse ¶
func (v *CoercingValidator) Parse(value any) (ParseResult, error)
Parse coerces value, then checks it: the coerced value when it is valid, else its errors.
type CompileOptions ¶
type CompileOptions struct {
// Draft is the draft whose semantics apply: Draft202012 (default, also for "") or Draft7.
Draft Draft
// Formats maps a format name to its check. Without it `format` is an annotation, as draft 2020-12 specifies. The standard formats are in package formats.
Formats map[string]FormatCheck
// Schemas holds schema documents by URI, for `$ref`s to other documents.
Schemas map[string]JsonSchema
// UnresolvedRefs is what a `$ref` that names nothing (a missing definition, a document not in Schemas) does: UnresolvedRefsThrow (default, also for "") makes Compile fail; UnresolvedRefsReject compiles it as `false`, so only values at that place fail, with the error "unresolved reference".
UnresolvedRefs UnresolvedRefs
}
CompileOptions are the options of Compile.
type FormatCheck ¶
FormatCheck reports whether value has the format.
type JsonSchema ¶
type JsonSchema = any
JsonSchema is a JSON Schema: a bool, an *Object or a map[string]any. Schemas come from tool definitions, MCP servers and other untrusted sources, so Compile reads every keyword defensively instead of trusting a static shape.
type LengthOption ¶
type LengthOption interface {
StrOption
BytesOption
}
LengthOption is an option of Str and Bytes.
func MaxLength ¶
func MaxLength(n int) LengthOption
MaxLength sets `maxLength` of a string, in code points, or of bytes, in bytes.
func MinLength ¶
func MinLength(n int) LengthOption
MinLength sets `minLength` of a string, in code points, or of bytes, in bytes.
type NumberOption ¶
type NumberOption interface {
// contains filtered or unexported methods
}
NumberOption is an option of Num and Int.
func ExclusiveMaximum ¶
func ExclusiveMaximum(n float64) NumberOption
ExclusiveMaximum sets `exclusiveMaximum` of a number.
func ExclusiveMinimum ¶
func ExclusiveMinimum(n float64) NumberOption
ExclusiveMinimum sets `exclusiveMinimum` of a number.
type Object ¶
Object is a JSON object that keeps JavaScript's property order (own keys: array-index keys ascending, then insertion order).
type ObjectOption ¶
type ObjectOption interface {
// contains filtered or unexported methods
}
ObjectOption is an option of Obj.
func Open ¶
func Open() ObjectOption
Open lets an Obj schema allow properties it does not declare, as tool schemas from other systems often do.
type ParseResult ¶
type ParseResult struct {
OK bool
Value any
Errors []ValidationError
}
ParseResult is the result of CoercingValidator.Parse: the coerced Value when OK, else the Errors of the coerced value.
type Properties ¶
type Properties []Property
Properties are the properties of Obj in declaration order. The `properties` and `required` of the schema, and so the order of its errors, follow JavaScript's own-key order: array-index names first in ascending order, then the others in declaration order. A name declared twice keeps its first position and its last declaration.
type Property ¶
Property is a property of Obj.
type Schema ¶
type Schema = *Object
Schema is a JSON Schema object returned by a builder.
func Arr ¶
func Arr(items Schema, options ...ArrayOption) Schema
Arr is an array of items, with optional length bounds and unique items.
func Bytes ¶
func Bytes(options ...BytesOption) Schema
Bytes is a []byte with optional length bounds (an extension of JSON Schema for values that never pass through JSON).
func Lit ¶
func Lit(value any, options ...AnnotationOption) Schema
Lit is exactly value (a string, number, boolean or nil).
func Map ¶
func Map(value Schema, options ...AnnotationOption) Schema
Map is an object with string keys and values of value (a record).
func Nullable ¶
func Nullable(schema Schema, options ...AnnotationOption) Schema
Nullable is schema or null.
func Obj ¶
func Obj(properties Properties, options ...ObjectOption) Schema
Obj is a closed object: the given properties (required unless Opt) and no others. The Open option allows other properties, as tool schemas from other systems often do.
func OneOf ¶
func OneOf(values []any, options ...AnnotationOption) Schema
OneOf is one of the given values.
func Tuple ¶
func Tuple(items []Schema, options ...AnnotationOption) Schema
Tuple is a fixed-length array whose items match items in order.
func Union ¶
func Union(schemas []Schema, options ...AnnotationOption) Schema
Union is any of the given schemas. A union of objects tagged by a Lit property (`{ kind: Lit("text"), ... }`) is checked by the tag: only the branch it selects runs, and its errors are the ones reported.
type StrOption ¶
type StrOption interface {
// contains filtered or unexported methods
}
StrOption is an option of Str.
type UnresolvedRefs ¶
type UnresolvedRefs string
UnresolvedRefs selects what a `$ref` that names nothing does.
const ( // UnresolvedRefsThrow makes Compile fail. UnresolvedRefsThrow UnresolvedRefs = "throw" // UnresolvedRefsReject compiles the reference as `false`. UnresolvedRefsReject UnresolvedRefs = "reject" )
type ValidationError ¶
ValidationError is one failure of a value: where it is (a JSON Pointer, "" for the value itself), the failing keyword and a message.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator is a compiled schema. It is safe for concurrent use.
A validator whose schema has a bookended `$dynamicRef` tracks the dynamic scope in state that a check mutates, and compiles the dynamic targets on first use, so its checks run one at a time.
func Compile ¶
func Compile(schema JsonSchema, options CompileOptions) (*Validator, error)
Compile compiles schema into a Validator. It fails if the schema is malformed or a `$ref` names nothing (register other documents with options.Schemas). The schema is read, never modified.
func (*Validator) Check ¶
Check reports whether value is valid. The error is the one a `$dynamicRef` target that is malformed or names nothing raises when a check first reaches it, as that compile error does upstream; every other validator never fails.
func (*Validator) Errors ¶
func (v *Validator) Errors(value any) ([]ValidationError, error)
Errors explains why value is invalid: one error per failing keyword, none when it is valid. The explanation is built on the first failure and kept, so a validator whose values always pass never pays for it. The error is the one the explanation raises where Pi's `errors` throws: a subschema that is neither an object nor a boolean, or a reference that names nothing, in a part of the schema the check never compiled.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package formats holds the format checks of JSON Schema 2020-12, for the schema package's formats option.
|
Package formats holds the format checks of JSON Schema 2020-12, for the schema package's formats option. |
|
internal/idna
Package idna validates hostnames and internationalized hostnames with Pi's own IDNA checks (RFC 5890, 5891, 5892, 5893).
|
Package idna validates hostnames and internationalized hostnames with Pi's own IDNA checks (RFC 5890, 5891, 5892, 5893). |
|
internal
|
|
|
ecmaregex
Package ecmaregex runs ECMAScript regular expressions: the engine behind `new RegExp(source, "u")` and `new RegExp(source)` for patterns without the d, g, v and y flags, which is what packages/schema/src/shared.ts (sharedRegex) and packages/schema/src/formats/typebox/regex.ts construct.
|
Package ecmaregex runs ECMAScript regular expressions: the engine behind `new RegExp(source, "u")` and `new RegExp(source)` for patterns without the d, g, v and y flags, which is what packages/schema/src/shared.ts (sharedRegex) and packages/schema/src/formats/typebox/regex.ts construct. |