added vendors

This commit is contained in:
mickymiek
2018-12-19 15:29:25 +01:00
parent 12e6881669
commit 8ee6bc4b91
2952 changed files with 1124359 additions and 1 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,668 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// THIS FILE IS AUTOMATICALLY GENERATED.
syntax = "proto3";
package openapi.v3;
import "google/protobuf/any.proto";
// This option lets the proto compiler generate Java code inside the package
// name (see below) instead of inside an outer class. It creates a simpler
// developer experience by reducing one-level of name nesting and be
// consistent with most programming languages that don't support outer classes.
option java_multiple_files = true;
// The Java outer classname should be the filename in UpperCamelCase. This
// class is only used to hold proto descriptor, so developers don't need to
// work with it directly.
option java_outer_classname = "OpenAPIProto";
// The Java package name must be proto package name with proper prefix.
option java_package = "org.openapi_v3";
// A reasonable prefix for the Objective-C symbols generated from the package.
// It should at a minimum be 3 characters long, all uppercase, and convention
// is to use an abbreviation of the package name. Something short, but
// hopefully unique enough to not conflict with things that may come along in
// the future. 'GPB' is reserved for the protocol buffer implementation itself.
option objc_class_prefix = "OAS";
message AdditionalPropertiesItem {
oneof oneof {
SchemaOrReference schema_or_reference = 1;
bool boolean = 2;
}
}
message Any {
google.protobuf.Any value = 1;
string yaml = 2;
}
message AnyOrExpression {
oneof oneof {
Any any = 1;
Expression expression = 2;
}
}
message AnysOrExpressions {
repeated NamedAnyOrExpression additional_properties = 1;
}
// A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
message Callback {
repeated NamedPathItem path = 1;
repeated NamedAny specification_extension = 2;
}
message CallbackOrReference {
oneof oneof {
Callback callback = 1;
Reference reference = 2;
}
}
message CallbacksOrReferences {
repeated NamedCallbackOrReference additional_properties = 1;
}
// Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.
message Components {
SchemasOrReferences schemas = 1;
ResponsesOrReferences responses = 2;
ParametersOrReferences parameters = 3;
ExamplesOrReferences examples = 4;
RequestBodiesOrReferences request_bodies = 5;
HeadersOrReferences headers = 6;
SecuritySchemesOrReferences security_schemes = 7;
LinksOrReferences links = 8;
CallbacksOrReferences callbacks = 9;
repeated NamedAny specification_extension = 10;
}
// Contact information for the exposed API.
message Contact {
string name = 1;
string url = 2;
string email = 3;
repeated NamedAny specification_extension = 4;
}
message DefaultType {
oneof oneof {
double number = 1;
bool boolean = 2;
string string = 3;
}
}
// When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. When using the discriminator, _inline_ schemas will not be considered.
message Discriminator {
string property_name = 1;
Strings mapping = 2;
}
message Document {
string openapi = 1;
Info info = 2;
repeated Server servers = 3;
Paths paths = 4;
Components components = 5;
repeated SecurityRequirement security = 6;
repeated Tag tags = 7;
ExternalDocs external_docs = 8;
repeated NamedAny specification_extension = 9;
}
// A single encoding definition applied to a single schema property.
message Encoding {
string content_type = 1;
HeadersOrReferences headers = 2;
string style = 3;
bool explode = 4;
bool allow_reserved = 5;
repeated NamedAny specification_extension = 6;
}
message Encodings {
repeated NamedEncoding additional_properties = 1;
}
message Example {
string summary = 1;
string description = 2;
Any value = 3;
string external_value = 4;
repeated NamedAny specification_extension = 5;
}
message ExampleOrReference {
oneof oneof {
Example example = 1;
Reference reference = 2;
}
}
message ExamplesOrReferences {
repeated NamedExampleOrReference additional_properties = 1;
}
message Expression {
repeated NamedAny additional_properties = 1;
}
// Allows referencing an external resource for extended documentation.
message ExternalDocs {
string description = 1;
string url = 2;
repeated NamedAny specification_extension = 3;
}
// The Header Object follows the structure of the Parameter Object with the following changes: 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. 1. `in` MUST NOT be specified, it is implicitly in `header`. 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, `style`).
message Header {
string description = 1;
bool required = 2;
bool deprecated = 3;
bool allow_empty_value = 4;
string style = 5;
bool explode = 6;
bool allow_reserved = 7;
SchemaOrReference schema = 8;
Any example = 9;
ExamplesOrReferences examples = 10;
MediaTypes content = 11;
repeated NamedAny specification_extension = 12;
}
message HeaderOrReference {
oneof oneof {
Header header = 1;
Reference reference = 2;
}
}
message HeadersOrReferences {
repeated NamedHeaderOrReference additional_properties = 1;
}
// The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.
message Info {
string title = 1;
string description = 2;
string terms_of_service = 3;
Contact contact = 4;
License license = 5;
string version = 6;
repeated NamedAny specification_extension = 7;
}
message ItemsItem {
repeated SchemaOrReference schema_or_reference = 1;
}
// License information for the exposed API.
message License {
string name = 1;
string url = 2;
repeated NamedAny specification_extension = 3;
}
// The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. For computing links, and providing instructions to execute them, a runtime expression is used for accessing values in an operation and using them as parameters while invoking the linked operation.
message Link {
string operation_ref = 1;
string operation_id = 2;
AnysOrExpressions parameters = 3;
AnyOrExpression request_body = 4;
string description = 5;
Server server = 6;
repeated NamedAny specification_extension = 7;
}
message LinkOrReference {
oneof oneof {
Link link = 1;
Reference reference = 2;
}
}
message LinksOrReferences {
repeated NamedLinkOrReference additional_properties = 1;
}
// Each Media Type Object provides schema and examples for the media type identified by its key.
message MediaType {
SchemaOrReference schema = 1;
Any example = 2;
ExamplesOrReferences examples = 3;
Encodings encoding = 4;
repeated NamedAny specification_extension = 5;
}
message MediaTypes {
repeated NamedMediaType additional_properties = 1;
}
// Automatically-generated message used to represent maps of Any as ordered (name,value) pairs.
message NamedAny {
// Map key
string name = 1;
// Mapped value
Any value = 2;
}
// Automatically-generated message used to represent maps of AnyOrExpression as ordered (name,value) pairs.
message NamedAnyOrExpression {
// Map key
string name = 1;
// Mapped value
AnyOrExpression value = 2;
}
// Automatically-generated message used to represent maps of CallbackOrReference as ordered (name,value) pairs.
message NamedCallbackOrReference {
// Map key
string name = 1;
// Mapped value
CallbackOrReference value = 2;
}
// Automatically-generated message used to represent maps of Encoding as ordered (name,value) pairs.
message NamedEncoding {
// Map key
string name = 1;
// Mapped value
Encoding value = 2;
}
// Automatically-generated message used to represent maps of ExampleOrReference as ordered (name,value) pairs.
message NamedExampleOrReference {
// Map key
string name = 1;
// Mapped value
ExampleOrReference value = 2;
}
// Automatically-generated message used to represent maps of HeaderOrReference as ordered (name,value) pairs.
message NamedHeaderOrReference {
// Map key
string name = 1;
// Mapped value
HeaderOrReference value = 2;
}
// Automatically-generated message used to represent maps of LinkOrReference as ordered (name,value) pairs.
message NamedLinkOrReference {
// Map key
string name = 1;
// Mapped value
LinkOrReference value = 2;
}
// Automatically-generated message used to represent maps of MediaType as ordered (name,value) pairs.
message NamedMediaType {
// Map key
string name = 1;
// Mapped value
MediaType value = 2;
}
// Automatically-generated message used to represent maps of ParameterOrReference as ordered (name,value) pairs.
message NamedParameterOrReference {
// Map key
string name = 1;
// Mapped value
ParameterOrReference value = 2;
}
// Automatically-generated message used to represent maps of PathItem as ordered (name,value) pairs.
message NamedPathItem {
// Map key
string name = 1;
// Mapped value
PathItem value = 2;
}
// Automatically-generated message used to represent maps of RequestBodyOrReference as ordered (name,value) pairs.
message NamedRequestBodyOrReference {
// Map key
string name = 1;
// Mapped value
RequestBodyOrReference value = 2;
}
// Automatically-generated message used to represent maps of ResponseOrReference as ordered (name,value) pairs.
message NamedResponseOrReference {
// Map key
string name = 1;
// Mapped value
ResponseOrReference value = 2;
}
// Automatically-generated message used to represent maps of SchemaOrReference as ordered (name,value) pairs.
message NamedSchemaOrReference {
// Map key
string name = 1;
// Mapped value
SchemaOrReference value = 2;
}
// Automatically-generated message used to represent maps of SecuritySchemeOrReference as ordered (name,value) pairs.
message NamedSecuritySchemeOrReference {
// Map key
string name = 1;
// Mapped value
SecuritySchemeOrReference value = 2;
}
// Automatically-generated message used to represent maps of ServerVariable as ordered (name,value) pairs.
message NamedServerVariable {
// Map key
string name = 1;
// Mapped value
ServerVariable value = 2;
}
// Automatically-generated message used to represent maps of string as ordered (name,value) pairs.
message NamedString {
// Map key
string name = 1;
// Mapped value
string value = 2;
}
// Configuration details for a supported OAuth Flow
message OauthFlow {
string authorization_url = 1;
string token_url = 2;
string refresh_url = 3;
Strings scopes = 4;
repeated NamedAny specification_extension = 5;
}
// Allows configuration of the supported OAuth Flows.
message OauthFlows {
OauthFlow implicit = 1;
OauthFlow password = 2;
OauthFlow client_credentials = 3;
OauthFlow authorization_code = 4;
repeated NamedAny specification_extension = 5;
}
message Object {
repeated NamedAny additional_properties = 1;
}
// Describes a single API operation on a path.
message Operation {
repeated string tags = 1;
string summary = 2;
string description = 3;
ExternalDocs external_docs = 4;
string operation_id = 5;
repeated ParameterOrReference parameters = 6;
RequestBodyOrReference request_body = 7;
Responses responses = 8;
CallbacksOrReferences callbacks = 9;
bool deprecated = 10;
repeated SecurityRequirement security = 11;
repeated Server servers = 12;
repeated NamedAny specification_extension = 13;
}
// Describes a single operation parameter. A unique parameter is defined by a combination of a name and location.
message Parameter {
string name = 1;
string in = 2;
string description = 3;
bool required = 4;
bool deprecated = 5;
bool allow_empty_value = 6;
string style = 7;
bool explode = 8;
bool allow_reserved = 9;
SchemaOrReference schema = 10;
Any example = 11;
ExamplesOrReferences examples = 12;
MediaTypes content = 13;
repeated NamedAny specification_extension = 14;
}
message ParameterOrReference {
oneof oneof {
Parameter parameter = 1;
Reference reference = 2;
}
}
message ParametersOrReferences {
repeated NamedParameterOrReference additional_properties = 1;
}
// Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.
message PathItem {
string _ref = 1;
string summary = 2;
string description = 3;
Operation get = 4;
Operation put = 5;
Operation post = 6;
Operation delete = 7;
Operation options = 8;
Operation head = 9;
Operation patch = 10;
Operation trace = 11;
repeated Server servers = 12;
repeated ParameterOrReference parameters = 13;
repeated NamedAny specification_extension = 14;
}
// Holds the relative paths to the individual endpoints and their operations. The path is appended to the URL from the `Server Object` in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.
message Paths {
repeated NamedPathItem path = 1;
repeated NamedAny specification_extension = 2;
}
message Properties {
repeated NamedSchemaOrReference additional_properties = 1;
}
// A simple object to allow referencing other components in the specification, internally and externally. The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules. For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification.
message Reference {
string _ref = 1;
}
message RequestBodiesOrReferences {
repeated NamedRequestBodyOrReference additional_properties = 1;
}
// Describes a single request body.
message RequestBody {
string description = 1;
MediaTypes content = 2;
bool required = 3;
repeated NamedAny specification_extension = 4;
}
message RequestBodyOrReference {
oneof oneof {
RequestBody request_body = 1;
Reference reference = 2;
}
}
// Describes a single response from an API Operation, including design-time, static `links` to operations based on the response.
message Response {
string description = 1;
HeadersOrReferences headers = 2;
MediaTypes content = 3;
LinksOrReferences links = 4;
repeated NamedAny specification_extension = 5;
}
message ResponseOrReference {
oneof oneof {
Response response = 1;
Reference reference = 2;
}
}
// A container for the expected responses of an operation. The container maps a HTTP response code to the expected response. The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. However, documentation is expected to cover a successful operation response and any known errors. The `default` MAY be used as a default response object for all HTTP codes that are not covered individually by the specification. The `Responses Object` MUST contain at least one response code, and it SHOULD be the response for a successful operation call.
message Responses {
ResponseOrReference default = 1;
repeated NamedResponseOrReference response_or_reference = 2;
repeated NamedAny specification_extension = 3;
}
message ResponsesOrReferences {
repeated NamedResponseOrReference additional_properties = 1;
}
// The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is an extended subset of the JSON Schema Specification Wright Draft 00. For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated otherwise, the property definitions follow the JSON Schema.
message Schema {
bool nullable = 1;
Discriminator discriminator = 2;
bool read_only = 3;
bool write_only = 4;
Xml xml = 5;
ExternalDocs external_docs = 6;
Any example = 7;
bool deprecated = 8;
string title = 9;
double multiple_of = 10;
double maximum = 11;
bool exclusive_maximum = 12;
double minimum = 13;
bool exclusive_minimum = 14;
int64 max_length = 15;
int64 min_length = 16;
string pattern = 17;
int64 max_items = 18;
int64 min_items = 19;
bool unique_items = 20;
int64 max_properties = 21;
int64 min_properties = 22;
repeated string required = 23;
repeated Any enum = 24;
string type = 25;
repeated SchemaOrReference all_of = 26;
repeated SchemaOrReference one_of = 27;
repeated SchemaOrReference any_of = 28;
Schema not = 29;
ItemsItem items = 30;
Properties properties = 31;
AdditionalPropertiesItem additional_properties = 32;
DefaultType default = 33;
string description = 34;
string format = 35;
repeated NamedAny specification_extension = 36;
}
message SchemaOrReference {
oneof oneof {
Schema schema = 1;
Reference reference = 2;
}
}
message SchemasOrReferences {
repeated NamedSchemaOrReference additional_properties = 1;
}
// Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a security scheme declared in the Security Schemes under the Components Object. Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. When a list of Security Requirement Objects is defined on the Open API object or Operation Object, only one of Security Requirement Objects in the list needs to be satisfied to authorize the request.
message SecurityRequirement {
}
// Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API key (either as a header or as a query parameter), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect Discovery.
message SecurityScheme {
string type = 1;
string description = 2;
string name = 3;
string in = 4;
string scheme = 5;
string bearer_format = 6;
OauthFlows flows = 7;
string open_id_connect_url = 8;
repeated NamedAny specification_extension = 9;
}
message SecuritySchemeOrReference {
oneof oneof {
SecurityScheme security_scheme = 1;
Reference reference = 2;
}
}
message SecuritySchemesOrReferences {
repeated NamedSecuritySchemeOrReference additional_properties = 1;
}
// An object representing a Server.
message Server {
string url = 1;
string description = 2;
ServerVariables variables = 3;
repeated NamedAny specification_extension = 4;
}
// An object representing a Server Variable for server URL template substitution.
message ServerVariable {
repeated string enum = 1;
string default = 2;
string description = 3;
repeated NamedAny specification_extension = 4;
}
message ServerVariables {
repeated NamedServerVariable additional_properties = 1;
}
// Any property starting with x- is valid.
message SpecificationExtension {
oneof oneof {
double number = 1;
bool boolean = 2;
string string = 3;
}
}
message StringArray {
repeated string value = 1;
}
message Strings {
repeated NamedString additional_properties = 1;
}
// Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag defined in the Operation Object instances.
message Tag {
string name = 1;
string description = 2;
ExternalDocs external_docs = 3;
repeated NamedAny specification_extension = 4;
}
// A metadata object that allows for more fine-tuned XML model definitions. When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. See examples for expected behavior.
message Xml {
string name = 1;
string namespace = 2;
string prefix = 3;
bool attribute = 4;
bool wrapped = 5;
repeated NamedAny specification_extension = 6;
}

View File

@ -0,0 +1,25 @@
# OpenAPI v3 Protocol Buffer Models
This directory contains a Protocol Buffer-language model
and related code for supporting OpenAPI v3.
Gnostic applications and plugins can use OpenAPIv3.proto
to generate Protocol Buffer support code for their preferred
languages.
OpenAPIv3.go is used by Gnostic to read JSON and YAML OpenAPI
descriptions into the Protocol Buffer-based datastructures
generated from OpenAPIv3.proto.
OpenAPIv3.proto and OpenAPIv3.go are generated by the Gnostic
compiler generator, and OpenAPIv3.pb.go is generated by
protoc, the Protocol Buffer compiler, and protoc-gen-go, the
Protocol Buffer Go code generation plugin.
openapi-3.0.json is a preliminary draft JSON schema for OpenAPI 3.0.
It is not the official OpenAPI 3.0 JSON Schema, which at the time
of this commit, does not exist.
The schema-generator directory contains support code which
generates openapi-3.0.json from a draft of the OpenAPI 3.0
specification document (Markdown).

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
# OpenAPI 3.0 Schema Generator
This directory contains a support tool that reads (scrapes) the
Markdown text specification for OpenAPI 3.0 and builds a
corresponding JSON schema.
It also contains "3.0.1.md", a local copy of the OpenAPI specification.
## Disclaimer
This does not generate the official OpenAPI 3.0 JSON Schema, which
at the time of this commit, does not exist.

View File

@ -0,0 +1,859 @@
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// schema-generator is a support tool that generates the OpenAPI v3 JSON schema.
// Yes, it's gross, but the OpenAPI 3.0 spec, which defines REST APIs with a
// rigorous JSON schema, is itself defined with a Markdown file. Ironic?
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/googleapis/gnostic/jsonschema"
)
// convert the first character of a string to lower case
func lowerFirst(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToLower(r)) + s[n:]
}
// Section models a section of the OpenAPI specification text document.
type Section struct {
Level int
Text string
Title string
Children []*Section
}
// ReadSection reads a section of the OpenAPI Specification, recursively dividing it into subsections
func ReadSection(text string, level int) (section *Section) {
titlePattern := regexp.MustCompile("^" + strings.Repeat("#", level) + " .*$")
subtitlePattern := regexp.MustCompile("^" + strings.Repeat("#", level+1) + " .*$")
section = &Section{Level: level, Text: text}
lines := strings.Split(string(text), "\n")
subsection := ""
for i, line := range lines {
if i == 0 && titlePattern.Match([]byte(line)) {
section.Title = line
} else if subtitlePattern.Match([]byte(line)) {
// we've found a subsection title.
// if there's a subsection that we've already been reading, save it
if len(subsection) != 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
// start a new subsection
subsection = line + "\n"
} else {
// add to the subsection we've been reading
subsection += line + "\n"
}
}
// if this section has subsections, save the last one
if len(section.Children) > 0 {
child := ReadSection(subsection, level+1)
section.Children = append(section.Children, child)
}
return
}
// Display recursively displays a section of the specification.
func (s *Section) Display(section string) {
if len(s.Children) == 0 {
//fmt.Printf("%s\n", s.Text)
} else {
for i, child := range s.Children {
var subsection string
if section == "" {
subsection = fmt.Sprintf("%d", i)
} else {
subsection = fmt.Sprintf("%s.%d", section, i)
}
fmt.Printf("%-12s %s\n", subsection, child.NiceTitle())
child.Display(subsection)
}
}
}
// remove a link from a string, leaving only the text that follows it
// if there is no link, just return the string
func stripLink(input string) (output string) {
stringPattern := regexp.MustCompile("^(.*)$")
stringWithLinkPattern := regexp.MustCompile("^<a .*</a>(.*)$")
if matches := stringWithLinkPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else if matches := stringPattern.FindSubmatch([]byte(input)); matches != nil {
return string(matches[1])
} else {
return input
}
}
// NiceTitle returns a nice-to-display title for a section by removing the opening "###" and any links.
func (s *Section) NiceTitle() string {
titlePattern := regexp.MustCompile("^#+ (.*)$")
titleWithLinkPattern := regexp.MustCompile("^#+ <a .*</a>(.*)$")
if matches := titleWithLinkPattern.FindSubmatch([]byte(s.Title)); matches != nil {
return string(matches[1])
} else if matches := titlePattern.FindSubmatch([]byte(s.Title)); matches != nil {
return string(matches[1])
} else {
return ""
}
}
// replace markdown links with their link text (removing the URL part)
func removeMarkdownLinks(input string) (output string) {
markdownLink := regexp.MustCompile("\\[([^\\]\\[]*)\\]\\(([^\\)]*)\\)") // matches [link title](link url)
output = string(markdownLink.ReplaceAll([]byte(input), []byte("$1")))
return
}
// extract the fixed fields from a table in a section
func parseFixedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
// replace escaped bars with "OR", assuming these are used to describe union types
line = strings.Replace(line, " \\| ", " OR ", -1)
// split the table on the remaining bars
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
if fieldName != "Field Name" && fieldName != "---" {
if len(parts) == 3 || len(parts) == 4 {
// this is what we expect
} else {
log.Printf("ERROR: %+v", parts)
}
typeName := parts[1]
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
} else {
// match map[string,<typename>]
mapPattern2 := regexp.MustCompile("^Map\\[string,(.+)\\]$")
if matches := mapPattern2.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
requiredLabel1 := "**Required.** "
requiredLabel2 := "**REQUIRED**."
if strings.Contains(description, requiredLabel1) ||
strings.Contains(description, requiredLabel2) {
// only include required values if their "Validity" is "Any" or if no validity is specified
valid := true
if len(parts) == 4 {
validity := parts[2]
if strings.Contains(validity, "Any") {
valid = true
} else {
valid = false
}
}
if valid {
schemaObject.RequiredFields = append(schemaObject.RequiredFields, fieldName)
}
description = strings.Replace(description, requiredLabel1, "", -1)
description = strings.Replace(description, requiredLabel2, "", -1)
}
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.FixedFields = append(schemaObject.FixedFields, schemaField)
}
}
}
}
// extract the patterned fields from a table in a section
func parsePatternedFields(input string, schemaObject *SchemaObject) {
lines := strings.Split(input, "\n")
for _, line := range lines {
line = strings.Replace(line, " \\| ", " OR ", -1)
parts := strings.Split(line, "|")
if len(parts) > 1 {
fieldName := strings.Trim(stripLink(parts[0]), " ")
fieldName = removeMarkdownLinks(fieldName)
if fieldName == "HTTP Status Code" {
fieldName = "^([0-9X]{3})$"
}
if fieldName != "Field Pattern" && fieldName != "---" {
typeName := parts[1]
typeName = strings.Trim(typeName, " ")
typeName = strings.Replace(typeName, "`", "", -1)
typeName = removeMarkdownLinks(typeName)
typeName = strings.Replace(typeName, " ", "", -1)
typeName = strings.Replace(typeName, "Object", "", -1)
typeName = strings.Replace(typeName, "{expression}", "Expression", -1)
isArray := false
if typeName[0] == '[' && typeName[len(typeName)-1] == ']' {
typeName = typeName[1 : len(typeName)-1]
isArray = true
}
isMap := false
mapPattern := regexp.MustCompile("^Mapstring,\\[(.*)\\]$")
if matches := mapPattern.FindSubmatch([]byte(typeName)); matches != nil {
typeName = string(matches[1])
isMap = true
}
description := strings.Trim(parts[len(parts)-1], " ")
description = removeMarkdownLinks(description)
description = strings.Replace(description, "\n", " ", -1)
schemaField := SchemaObjectField{
Name: fieldName,
Type: typeName,
IsArray: isArray,
IsMap: isMap,
Description: description,
}
schemaObject.PatternedFields = append(schemaObject.PatternedFields, schemaField)
}
}
}
}
// SchemaObjectField describes a field of a schema.
type SchemaObjectField struct {
Name string `json:"name"`
Type string `json:"type"`
IsArray bool `json:"is_array"`
IsMap bool `json:"is_map"`
Description string `json:"description"`
}
// SchemaObject describes a schema.
type SchemaObject struct {
Name string `json:"name"`
ID string `json:"id"`
Description string `json:"description"`
Extendable bool `json:"extendable"`
RequiredFields []string `json:"required"`
FixedFields []SchemaObjectField `json:"fixed"`
PatternedFields []SchemaObjectField `json:"patterned"`
}
// SchemaModel is a collection of schemas.
type SchemaModel struct {
Objects []SchemaObject
}
func (m *SchemaModel) objectWithID(id string) *SchemaObject {
for _, object := range m.Objects {
if object.ID == id {
return &object
}
}
return nil
}
// NewSchemaModel returns a new SchemaModel.
func NewSchemaModel(filename string) (schemaModel *SchemaModel, err error) {
b, err := ioutil.ReadFile("3.0.1.md")
if err != nil {
return nil, err
}
// divide the specification into sections
document := ReadSection(string(b), 1)
document.Display("")
// read object names and their details
specification := document.Children[4] // fragile! the section title is "Specification"
schema := specification.Children[7] // fragile! the section title is "Schema"
anchor := regexp.MustCompile("^#### <a name=\"(.*)Object\"")
schemaObjects := make([]SchemaObject, 0)
for _, section := range schema.Children {
if matches := anchor.FindSubmatch([]byte(section.Title)); matches != nil {
id := string(matches[1])
schemaObject := SchemaObject{
Name: section.NiceTitle(),
ID: id,
RequiredFields: nil,
}
if len(section.Children) > 0 {
description := section.Children[0].Text
description = removeMarkdownLinks(description)
description = strings.Trim(description, " \t\n")
description = strings.Replace(description, "\n", " ", -1)
schemaObject.Description = description
}
// is the object extendable?
if strings.Contains(section.Text, "Specification Extensions") {
schemaObject.Extendable = true
}
// look for fixed fields
for _, child := range section.Children {
if child.NiceTitle() == "Fixed Fields" {
parseFixedFields(child.Text, &schemaObject)
}
}
// look for patterned fields
for _, child := range section.Children {
if child.NiceTitle() == "Patterned Fields" {
parsePatternedFields(child.Text, &schemaObject)
}
}
schemaObjects = append(schemaObjects, schemaObject)
}
}
return &SchemaModel{Objects: schemaObjects}, nil
}
// UnionType represents a union of two types.
type UnionType struct {
Name string
ObjectType1 string
ObjectType2 string
}
var unionTypes map[string]*UnionType
func noteUnionType(typeName, objectType1, objectType2 string) {
if unionTypes == nil {
unionTypes = make(map[string]*UnionType, 0)
}
unionTypes[typeName] = &UnionType{
Name: typeName,
ObjectType1: objectType1,
ObjectType2: objectType2,
}
}
// MapType represents a map of a specified type (with string keys).
type MapType struct {
Name string
ObjectType string
}
var mapTypes map[string]*MapType
func noteMapType(typeName, objectType string) {
if mapTypes == nil {
mapTypes = make(map[string]*MapType, 0)
}
mapTypes[typeName] = &MapType{
Name: typeName,
ObjectType: objectType,
}
}
func definitionNameForType(typeName string) string {
name := typeName
switch typeName {
case "OAuthFlows":
name = "oauthFlows"
case "OAuthFlow":
name = "oauthFlow"
case "XML":
name = "xml"
case "ExternalDocumentation":
name = "externalDocs"
default:
// does the name contain an "OR"
if parts := strings.Split(typeName, "OR"); len(parts) > 1 {
name = lowerFirst(parts[0]) + "Or" + parts[1]
noteUnionType(name, parts[0], parts[1])
} else {
name = lowerFirst(typeName)
}
}
return "#/definitions/" + name
}
func pluralize(name string) string {
if name == "any" {
return "anys"
}
switch name[len(name)-1] {
case 'y':
name = name[0:len(name)-1] + "ies"
case 's':
name = name + "Map"
default:
name = name + "s"
}
return name
}
func definitionNameForMapOfType(typeName string) string {
// pluralize the type name to get the name of an object representing a map of them
var elementTypeName string
var mapTypeName string
if parts := strings.Split(typeName, "OR"); len(parts) > 1 {
elementTypeName = lowerFirst(parts[0]) + "Or" + parts[1]
noteUnionType(elementTypeName, parts[0], parts[1])
mapTypeName = pluralize(lowerFirst(parts[0])) + "Or" + pluralize(parts[1])
} else {
elementTypeName = lowerFirst(typeName)
mapTypeName = pluralize(elementTypeName)
}
noteMapType(mapTypeName, elementTypeName)
return "#/definitions/" + mapTypeName
}
func updateSchemaFieldWithModelField(schemaField *jsonschema.Schema, modelField *SchemaObjectField) {
// fmt.Printf("IN %s:%+v\n", name, schemaField)
// update the attributes of the schema field
if modelField.IsArray {
// is array
itemSchema := &jsonschema.Schema{}
switch modelField.Type {
case "string":
itemSchema.Type = jsonschema.NewStringOrStringArrayWithString("string")
case "boolean":
itemSchema.Type = jsonschema.NewStringOrStringArrayWithString("boolean")
case "primitive":
itemSchema.Ref = stringptr(definitionNameForType("Primitive"))
default:
itemSchema.Ref = stringptr(definitionNameForType(modelField.Type))
}
schemaField.Items = jsonschema.NewSchemaOrSchemaArrayWithSchema(itemSchema)
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("array")
boolValue := true // not sure about this
schemaField.UniqueItems = &boolValue
} else if modelField.IsMap {
schemaField.Ref = stringptr(definitionNameForMapOfType(modelField.Type))
} else {
// is scalar
switch modelField.Type {
case "string":
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("string")
case "boolean":
schemaField.Type = jsonschema.NewStringOrStringArrayWithString("boolean")
case "primitive":
schemaField.Ref = stringptr(definitionNameForType("Primitive"))
default:
schemaField.Ref = stringptr(definitionNameForType(modelField.Type))
}
}
}
func buildSchemaWithModel(modelObject *SchemaObject) (schema *jsonschema.Schema) {
schema = &jsonschema.Schema{}
schema.Type = jsonschema.NewStringOrStringArrayWithString("object")
if modelObject.RequiredFields != nil && len(modelObject.RequiredFields) > 0 {
// copy array
arrayCopy := modelObject.RequiredFields
schema.Required = &arrayCopy
}
schema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(false)
schema.Description = stringptr(modelObject.Description)
// handle fixed fields
if modelObject.FixedFields != nil {
newNamedSchemas := make([]*jsonschema.NamedSchema, 0)
for _, modelField := range modelObject.FixedFields {
schemaField := schema.PropertyWithName(modelField.Name)
if schemaField == nil {
// create and add the schema field
schemaField = &jsonschema.Schema{}
namedSchema := &jsonschema.NamedSchema{Name: modelField.Name, Value: schemaField}
newNamedSchemas = append(newNamedSchemas, namedSchema)
}
updateSchemaFieldWithModelField(schemaField, &modelField)
}
for _, pair := range newNamedSchemas {
if schema.Properties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.Properties = &properties
}
*(schema.Properties) = append(*(schema.Properties), pair)
}
} else {
if schema.Properties != nil {
fmt.Printf("SCHEMA SHOULD NOT HAVE PROPERTIES %s\n", modelObject.ID)
}
}
// handle patterned fields
if modelObject.PatternedFields != nil {
newNamedSchemas := make([]*jsonschema.NamedSchema, 0)
for _, modelField := range modelObject.PatternedFields {
schemaField := schema.PatternPropertyWithName(modelField.Name)
if schemaField == nil {
// create and add the schema field
schemaField = &jsonschema.Schema{}
// Component names should match "^[a-zA-Z0-9\.\-_]+$"
// See https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md#componentsObject
nameRegex := "^[a-zA-Z0-9\\\\.\\\\-_]+$"
if modelObject.Name == "Scopes Object" {
nameRegex = "^"
} else if modelObject.Name == "Headers Object" {
nameRegex = "^[a-zA-Z0-9!#\\-\\$%&'\\*\\+\\\\\\.\\^_`\\|~]+"
}
propertyName := strings.Replace(modelField.Name, "{name}", nameRegex, -1)
// The field name MUST begin with a slash, see https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md#paths-object
// JSON Schema for OpenAPI v2 uses "^/" as regex for paths, see https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/schemas/v2.0/schema.json#L173
propertyName = strings.Replace(propertyName, "/{path}", "^/", -1)
// Replace human-friendly (and regex-confusing) description with a blank pattern
propertyName = strings.Replace(propertyName, "{expression}", "^", -1)
propertyName = strings.Replace(propertyName, "{property}", "^", -1)
namedSchema := &jsonschema.NamedSchema{Name: propertyName, Value: schemaField}
newNamedSchemas = append(newNamedSchemas, namedSchema)
}
updateSchemaFieldWithModelField(schemaField, &modelField)
}
for _, pair := range newNamedSchemas {
if schema.PatternProperties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.PatternProperties = &properties
}
*(schema.PatternProperties) = append(*(schema.PatternProperties), pair)
}
} else {
if schema.PatternProperties != nil && !modelObject.Extendable {
fmt.Printf("SCHEMA SHOULD NOT HAVE PATTERN PROPERTIES %s\n", modelObject.ID)
}
}
if modelObject.Extendable {
schemaField := schema.PatternPropertyWithName("^x-")
if schemaField != nil {
schemaField.Ref = stringptr("#/definitions/specificationExtension")
} else {
schemaField = &jsonschema.Schema{}
schemaField.Ref = stringptr("#/definitions/specificationExtension")
namedSchema := &jsonschema.NamedSchema{Name: "^x-", Value: schemaField}
if schema.PatternProperties == nil {
properties := make([]*jsonschema.NamedSchema, 0)
schema.PatternProperties = &properties
}
*(schema.PatternProperties) = append(*(schema.PatternProperties), namedSchema)
}
} else {
schemaField := schema.PatternPropertyWithName("^x-")
if schemaField != nil {
fmt.Printf("INVALID EXTENSION SUPPORT %s:%s\n", modelObject.ID, "^x-")
}
}
return schema
}
// return a pointer to a copy of a passed-in string
func stringptr(input string) (output *string) {
return &input
}
func int64ptr(input int64) (output *int64) {
return &input
}
func arrayOfSchema() *jsonschema.Schema {
return &jsonschema.Schema{
Type: jsonschema.NewStringOrStringArrayWithString("array"),
MinItems: int64ptr(1),
Items: jsonschema.NewSchemaOrSchemaArrayWithSchema(&jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")}),
}
}
func main() {
// read and parse the text specification into a model structure
model, err := NewSchemaModel("3.0.md")
if err != nil {
panic(err)
}
// write the model as JSON (for debugging)
modelJSON, _ := json.MarshalIndent(model, "", " ")
err = ioutil.WriteFile("model.json", modelJSON, 0644)
if err != nil {
panic(err)
}
// build the top-level schema using the "OAS" model
oasModel := model.objectWithID("oas")
if oasModel == nil {
log.Printf("Unable to find OAS model. Has the source document structure changed?")
os.Exit(-1)
}
schema := buildSchemaWithModel(oasModel)
// manually set a few fields
schema.Title = stringptr("A JSON Schema for OpenAPI 3.0.")
schema.ID = stringptr("http://openapis.org/v3/schema.json#")
schema.Schema = stringptr("http://json-schema.org/draft-04/schema#")
// loop over all models and create the corresponding schema objects
definitions := make([]*jsonschema.NamedSchema, 0)
schema.Definitions = &definitions
for _, modelObject := range model.Objects {
if modelObject.ID == "oas" {
continue
}
definitionSchema := buildSchemaWithModel(&modelObject)
name := modelObject.ID
if name == "externalDocumentation" {
name = "externalDocs"
}
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(name, definitionSchema))
}
// copy the properties of headerObject from parameterObject
headerObject := schema.DefinitionWithName("header")
parameterObject := schema.DefinitionWithName("parameter")
if parameterObject != nil {
newArray := make([]*jsonschema.NamedSchema, 0)
for _, property := range *(parameterObject.Properties) {
// we need to remove a few properties...
if property.Name != "name" && property.Name != "in" {
newArray = append(newArray, property)
}
}
headerObject.Properties = &newArray
// "So a shorthand for copying array arr would be tmp := append([]int{}, arr...)"
ppArray := make([]*jsonschema.NamedSchema, 0)
ppArray = append(ppArray, *(parameterObject.PatternProperties)...)
headerObject.PatternProperties = &ppArray
}
// generate implied union types
unionTypeKeys := make([]string, 0, len(unionTypes))
for key := range unionTypes {
unionTypeKeys = append(unionTypeKeys, key)
}
sort.Strings(unionTypeKeys)
for _, unionTypeKey := range unionTypeKeys {
unionType := unionTypes[unionTypeKey]
objectSchema := schema.DefinitionWithName(unionType.Name)
if objectSchema == nil {
objectSchema = &jsonschema.Schema{}
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Ref: stringptr("#/definitions/" + lowerFirst(unionType.ObjectType1))})
oneOf = append(oneOf, &jsonschema.Schema{Ref: stringptr("#/definitions/" + lowerFirst(unionType.ObjectType2))})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(unionType.Name, objectSchema))
}
}
// generate implied map types
mapTypeKeys := make([]string, 0, len(mapTypes))
for key := range mapTypes {
mapTypeKeys = append(mapTypeKeys, key)
}
sort.Strings(mapTypeKeys)
for _, mapTypeKey := range mapTypeKeys {
mapType := mapTypes[mapTypeKey]
objectSchema := schema.DefinitionWithName(mapType.Name)
if objectSchema == nil {
objectSchema = &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
additionalPropertiesSchema := &jsonschema.Schema{}
if mapType.ObjectType == "string" {
additionalPropertiesSchema.Type = jsonschema.NewStringOrStringArrayWithString("string")
} else {
additionalPropertiesSchema.Ref = stringptr("#/definitions/" + lowerFirst(mapType.ObjectType))
}
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithSchema(additionalPropertiesSchema)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema(mapType.Name, objectSchema))
}
}
// add schema objects for "object", "any", and "expression"
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("object", objectSchema))
}
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("any", objectSchema))
}
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Type = jsonschema.NewStringOrStringArrayWithString("object")
objectSchema.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(true)
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("expression", objectSchema))
}
// add schema objects for "specificationExtension"
if true {
objectSchema := &jsonschema.Schema{}
objectSchema.Description = stringptr("Any property starting with x- is valid.")
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("null")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("number")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("object")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("array")})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("specificationExtension", objectSchema))
}
// add schema objects for "defaultType"
if true {
objectSchema := &jsonschema.Schema{}
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("null")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("array")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("object")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("number")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("defaultType", objectSchema))
}
// add schema objects for "primitive"
if false { // we don't seem to need these for 3.0 RC2
objectSchema := &jsonschema.Schema{}
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("number")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
objectSchema.OneOf = &oneOf
*schema.Definitions = append(*schema.Definitions, jsonschema.NewNamedSchema("primitive", objectSchema))
}
// force a few more things into the "schema" schema
schemaObject := schema.DefinitionWithName("schema")
schemaObject.CopyOfficialSchemaProperties(
[]string{
"title",
"multipleOf",
"maximum",
"exclusiveMaximum",
"minimum",
"exclusiveMinimum",
"maxLength",
"minLength",
"pattern",
"maxItems",
"minItems",
"uniqueItems",
"maxProperties",
"minProperties",
"required",
"enum",
})
schemaObject.AdditionalProperties = jsonschema.NewSchemaOrBooleanWithBoolean(false)
schemaObject.AddProperty("type", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
schemaObject.AddProperty("allOf", arrayOfSchema())
schemaObject.AddProperty("oneOf", arrayOfSchema())
schemaObject.AddProperty("anyOf", arrayOfSchema())
schemaObject.AddProperty("not", &jsonschema.Schema{Ref: stringptr("#/definitions/schema")})
anyOf := make([]*jsonschema.Schema, 0)
anyOf = append(anyOf, &jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")})
anyOf = append(anyOf, arrayOfSchema())
schemaObject.AddProperty("items",
&jsonschema.Schema{AnyOf: &anyOf})
schemaObject.AddProperty("properties", &jsonschema.Schema{
Type: jsonschema.NewStringOrStringArrayWithString("object"),
AdditionalProperties: jsonschema.NewSchemaOrBooleanWithSchema(
&jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")})})
if true { // add additionalProperties schema object
oneOf := make([]*jsonschema.Schema, 0)
oneOf = append(oneOf, &jsonschema.Schema{Ref: stringptr("#/definitions/schemaOrReference")})
oneOf = append(oneOf, &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("boolean")})
schemaObject.AddProperty("additionalProperties", &jsonschema.Schema{OneOf: &oneOf})
}
schemaObject.AddProperty("default", &jsonschema.Schema{Ref: stringptr("#/definitions/defaultType")})
schemaObject.AddProperty("description", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
schemaObject.AddProperty("format", &jsonschema.Schema{Type: jsonschema.NewStringOrStringArrayWithString("string")})
// fix the content object
contentObject := schema.DefinitionWithName("content")
if contentObject != nil {
pairs := make([]*jsonschema.NamedSchema, 0)
contentObject.PatternProperties = &pairs
namedSchema := &jsonschema.NamedSchema{Name: "^", Value: &jsonschema.Schema{Ref: stringptr("#/definitions/mediaType")}}
*(contentObject.PatternProperties) = append(*(contentObject.PatternProperties), namedSchema)
}
// fix the contact object
contactObject := schema.DefinitionWithName("contact")
if contactObject != nil {
emailProperty := contactObject.PropertyWithName("email")
if emailProperty != nil {
emailProperty.Format = stringptr("email");
}
urlProperty := contactObject.PropertyWithName("url")
if urlProperty != nil {
urlProperty.Format = stringptr("uri");
}
}
// write the updated schema
output := schema.JSONString()
err = ioutil.WriteFile("schema.json", []byte(output), 0644)
if err != nil {
panic(err)
}
}