Marcel van Lohuizen | 47d9870 | 2020-01-17 21:51:39 +0100 | [diff] [blame] | 1 | // Copyright 2020 CUE Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package jsonschema implements the JSON schema standard. |
| 16 | // |
| 17 | // Mapping and Linking |
| 18 | // |
| 19 | // JSON Schema are often defined in a single file. CUE, on the other hand |
| 20 | // idomatically defines schema as a definition. |
| 21 | // |
| 22 | // CUE: |
| 23 | // $schema: which schema is used for validation. |
| 24 | // $id: which validation does this schema provide. |
| 25 | // |
| 26 | // Foo: _ @jsonschema(sc) |
| 27 | // @source(https://...) // What schema is used to validate. |
| 28 | // |
| 29 | // NOTE: JSON Schema is a draft standard and may undergo backwards incompatible |
| 30 | // changes. |
| 31 | package jsonschema |
| 32 | |
| 33 | import ( |
| 34 | "cuelang.org/go/cue" |
| 35 | "cuelang.org/go/cue/ast" |
| 36 | ) |
| 37 | |
| 38 | // Extract converts JSON Schema data into an equivalent CUE representation. |
| 39 | // |
| 40 | // The generated CUE schema is guaranteed to deem valid any value that is |
| 41 | // a valid instance of the source JSON schema. |
| 42 | func Extract(data *cue.Instance, cfg *Config) (*ast.File, error) { |
| 43 | d := &decoder{ |
| 44 | cfg: cfg, |
| 45 | imports: map[string]*ast.Ident{}, |
| 46 | } |
| 47 | e := d.decode(data) |
| 48 | if d.errs != nil { |
| 49 | return nil, d.errs |
| 50 | } |
| 51 | return e, nil |
| 52 | } |
| 53 | |
| 54 | // A Config configures a JSON Schema encoding or decoding. |
| 55 | type Config struct { |
| 56 | ID string // URL of the original source, corresponding to the $id field. |
| 57 | |
| 58 | // TODO: configurability to make it compatible with OpenAPI, such as |
| 59 | // - locations of definitions: #/components/schemas, for instance. |
| 60 | // - selection and definition of formats |
| 61 | // - documentation hooks. |
| 62 | |
| 63 | _ struct{} // prohibit casting from different type. |
| 64 | } |