File: parser.rb

package info (click to toggle)
ruby-brandur-json-schema 0.19.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 376 kB
  • sloc: ruby: 3,764; makefile: 6
file content (382 lines) | stat: -rw-r--r-- 13,225 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
require_relative "../json_reference"
require_relative "validator"

module JsonSchema
  class Parser
    ALLOWED_TYPES = %w{any array boolean integer number null object string}
    BOOLEAN = [FalseClass, TrueClass]
    FORMATS = JsonSchema::Validator::DEFAULT_FORMAT_VALIDATORS.keys
    FRIENDLY_TYPES = {
      Array      => "array",
      FalseClass => "boolean",
      Float      => "number",
      Hash       => "object",
      Integer    => "integer",
      NilClass   => "null",
      String     => "string",
      TrueClass  => "boolean",
    }

    attr_accessor :errors

    # Basic parsing of a schema. May return a malformed schema! (Use `#parse!`
    # to raise errors instead).
    def parse(data, parent = nil)
      # while #parse_data is recursed into for many schemas over the same
      # object, the @errors array is an instance-wide accumulator
      @errors = []

      schema = parse_data(data, parent, "#")
      if @errors.count == 0
        schema
      else
        nil
      end
    end

    def parse!(data, parent = nil)
      schema = parse(data, parent)
      if !schema
        raise AggregateError.new(@errors)
      end
      schema
    end

    private

    def build_uri(id, parent_uri)
      # kill any trailing slashes
      if id
        # may look like: http://json-schema.org/draft-04/hyper-schema#
        uri = URI.parse(id)
        # make sure there is no `#` suffix
        uri.fragment = nil
        # if id is defined as absolute, the schema's URI stays absolute
        if uri.absolute? || uri.path[0] == "/"
          uri.to_s.chomp("/")
        # otherwise build it according to the parent's URI
        elsif parent_uri
          # make sure we don't end up with duplicate slashes
          parent_uri = parent_uri.chomp("/")
          parent_uri + "/" + id
        else
          "/"
        end
      # if id is missing, it's defined as its parent schema's URI
      elsif parent_uri
        parent_uri
      else
        "/"
      end
    end

    def parse_additional_items(schema)
      if schema.additional_items
        # an object indicates a schema that will be used to parse any
        # items not listed in `items`
        if schema.additional_items.is_a?(Hash)
          schema.additional_items = parse_data(
            schema.additional_items,
            schema,
            "additionalItems"
          )
        end
        # otherwise, leave as boolean
      end
    end

    def parse_additional_properties(schema)
      if schema.additional_properties
        # an object indicates a schema that will be used to parse any
        # properties not listed in `properties`
        if schema.additional_properties.is_a?(Hash)
          schema.additional_properties = parse_data(
            schema.additional_properties,
            schema,
            "additionalProperties"
          )
        end
        # otherwise, leave as boolean
      end
    end

    def parse_all_of(schema)
      if schema.all_of
        schema.all_of = schema.all_of.each_with_index.
          map { |s, i| parse_data(s, schema, "allOf/#{i}") }
      end
    end

    def parse_any_of(schema)
      if schema.any_of
        schema.any_of = schema.any_of.each_with_index.
          map { |s, i| parse_data(s, schema, "anyOf/#{i}") }
      end
    end

    def parse_one_of(schema)
      if schema.one_of
        schema.one_of = schema.one_of.each_with_index.
          map { |s, i| parse_data(s, schema, "oneOf/#{i}") }
      end
    end

    def parse_data(data, parent, fragment)
      if !data.is_a?(Hash)
        # it would be nice to make this message more specific/nicer (at best it
        # points to the wrong schema)
        message = %{#{data.inspect} is not a valid schema.}
        @errors << SchemaError.new(parent, message, :schema_not_found)
      elsif ref = data["$ref"]
        schema = Schema.new
        schema.fragment = fragment
        schema.parent = parent
        schema.reference = JsonReference::Reference.new(ref)
      else
        schema = parse_schema(data, parent, fragment)
      end

      schema
    end

    def parse_definitions(schema)
      if schema.definitions
        # leave the original data reference intact
        schema.definitions = schema.definitions.dup
        schema.definitions.each do |key, definition|
          subschema = parse_data(definition, schema, "definitions/#{key}")
          schema.definitions[key] = subschema
        end
      end
    end

    def parse_dependencies(schema)
      if schema.dependencies
        # leave the original data reference intact
        schema.dependencies = schema.dependencies.dup
        schema.dependencies.each do |k, s|
          # may be Array, String (simple dependencies), or Hash (schema
          # dependency)
          if s.is_a?(Hash)
            schema.dependencies[k] = parse_data(s, schema, "dependencies")
          elsif s.is_a?(String)
            # just normalize all simple dependencies to arrays
            schema.dependencies[k] = [s]
          end
        end
      end
    end

    def parse_items(schema)
      if schema.items
        # tuple validation: an array of schemas
        if schema.items.is_a?(Array)
          schema.items = schema.items.each_with_index.
            map { |s, i| parse_data(s, schema, "items/#{i}") }
        # list validation: a single schema
        else
          schema.items = parse_data(schema.items, schema, "items")
        end
      end
    end

    def parse_links(schema)
      if schema.links
        schema.links = schema.links.each_with_index.map { |l, i|
          link             = Schema::Link.new
          link.parent      = schema
          link.fragment    = "links/#{i}"

          link.data        = l

          # any parsed schema is automatically expanded
          link.expanded    = true

          link.uri         = nil

          link.description = l["description"]
          link.enc_type    = l["encType"]
          link.href        = l["href"]
          link.method      = l["method"] ? l["method"].downcase.to_sym : nil
          link.rel         = l["rel"]
          link.title       = l["title"]
          link.media_type  = l["mediaType"]

          if l["schema"]
            link.schema = parse_data(l["schema"], schema, "links/#{i}/schema")
          end

          if l["targetSchema"]
            link.target_schema =
              parse_data(l["targetSchema"], schema, "links/#{i}/targetSchema")
          end

          link
        }
      end
    end

    def parse_media(schema)
      if data = schema.media
        schema.media = Schema::Media.new
        schema.media.binary_encoding = data["binaryEncoding"]
        schema.media.type            = data["type"]
      end
    end

    def parse_not(schema)
      if schema.not
        schema.not = parse_data(schema.not, schema, "not")
      end
    end

    def parse_pattern_properties(schema)
      if schema.pattern_properties
        # leave the original data reference intact
        properties = schema.pattern_properties.dup
        properties = properties.map do |k, s|
          [parse_regex(schema, k), parse_data(s, schema, "patternProperties/#{k}")]
        end
        schema.pattern_properties = Hash[*properties.flatten]
      end
    end

    def parse_regex(schema, regex)
      case JsonSchema.configuration.validate_regex_with
      when :'ecma-re-validator'
        message = "Ecma validation deactivated in Debian package"
        #unless EcmaReValidator.valid?(regex)
        #  message = %{#{regex.inspect} is not an ECMA-262 regular expression.}
        #  @errors << SchemaError.new(schema, message, :regex_failed)
        #end
      end
      Regexp.new(regex)
    end

    def parse_properties(schema)
      # leave the original data reference intact
      schema.properties = schema.properties.dup
      if schema.properties && schema.properties.is_a?(Hash)
        schema.properties.each do |key, definition|
          subschema = parse_data(definition, schema, "properties/#{key}")
          schema.properties[key] = subschema
        end
      end
    end

    def parse_schema(data, parent, fragment)
      schema = Schema.new
      schema.fragment = fragment
      schema.parent   = parent

      schema.data        = data
      schema.id          = validate_type(schema, [String], "id")

      # any parsed schema is automatically expanded
      schema.expanded    = true

      # build URI early so we can reference it in errors
      schema.uri         = build_uri(schema.id, parent ? parent.uri : nil)

      schema.title       = validate_type(schema, [String], "title")
      schema.description = validate_type(schema, [String], "description")
      schema.default     = schema.data["default"]

      # validation: any
      schema.all_of        = validate_type(schema, [Array], "allOf") || []
      schema.any_of        = validate_type(schema, [Array], "anyOf") || []
      schema.definitions   = validate_type(schema, [Hash], "definitions") || {}
      schema.enum          = validate_type(schema, [Array], "enum")
      schema.one_of        = validate_type(schema, [Array], "oneOf") || []
      schema.not           = validate_type(schema, [Hash], "not")
      schema.type          = validate_type(schema, [Array, String], "type")
      schema.type          = [schema.type] if schema.type.is_a?(String)
      validate_known_type!(schema)

      # validation: array
      schema.additional_items = validate_type(schema, BOOLEAN + [Hash], "additionalItems")
      schema.items            = validate_type(schema, [Array, Hash], "items")
      schema.max_items        = validate_type(schema, [Integer], "maxItems")
      schema.min_items        = validate_type(schema, [Integer], "minItems")
      schema.unique_items     = validate_type(schema, BOOLEAN, "uniqueItems")

      # validation: number/integer
      schema.max           = validate_type(schema, [Float, Integer], "maximum")
      schema.max_exclusive = validate_type(schema, BOOLEAN, "exclusiveMaximum")
      schema.min           = validate_type(schema, [Float, Integer], "minimum")
      schema.min_exclusive = validate_type(schema, BOOLEAN, "exclusiveMinimum")
      schema.multiple_of   = validate_type(schema, [Float, Integer], "multipleOf")

      # validation: object
      schema.additional_properties =
        validate_type(schema, BOOLEAN + [Hash], "additionalProperties")
      schema.dependencies       = validate_type(schema, [Hash], "dependencies") || {}
      schema.max_properties     = validate_type(schema, [Integer], "maxProperties")
      schema.min_properties     = validate_type(schema, [Integer], "minProperties")
      schema.pattern_properties = validate_type(schema, [Hash], "patternProperties") || {}
      schema.properties         = validate_type(schema, [Hash], "properties") || {}
      schema.required           = validate_type(schema, [Array], "required")
      schema.strict_properties  = validate_type(schema, BOOLEAN, "strictProperties")

      # validation: string
      schema.format     = validate_type(schema, [String], "format")
      schema.max_length = validate_type(schema, [Integer], "maxLength")
      schema.min_length = validate_type(schema, [Integer], "minLength")
      schema.pattern    = validate_type(schema, [String], "pattern")
      schema.pattern    = parse_regex(schema, schema.pattern) if schema.pattern
      validate_format(schema, schema.format) if schema.format

      # hyperschema
      schema.links      = validate_type(schema, [Array], "links")
      schema.media      = validate_type(schema, [Hash], "media")
      schema.path_start = validate_type(schema, [String], "pathStart")
      schema.read_only  = validate_type(schema, BOOLEAN, "readOnly")

      parse_additional_items(schema)
      parse_additional_properties(schema)
      parse_all_of(schema)
      parse_any_of(schema)
      parse_one_of(schema)
      parse_definitions(schema)
      parse_dependencies(schema)
      parse_items(schema)
      parse_links(schema)
      parse_media(schema)
      parse_not(schema)
      parse_pattern_properties(schema)
      parse_properties(schema)

      schema
    end

    def validate_known_type!(schema)
      if schema.type
        if !(bad_types = schema.type - ALLOWED_TYPES).empty?
          message = %{Unknown types: #{bad_types.sort.join(", ")}.}
          @errors << SchemaError.new(schema, message, :unknown_type)
        end
      end
    end

    def validate_type(schema, types, field)
      friendly_types =
        types.map { |t| FRIENDLY_TYPES[t] || t }.sort.uniq.join("/")
      value = schema.data[field]
      if !value.nil? && !types.any? { |t| value.is_a?(t) }
        message = %{#{value.inspect} is not a valid "#{field}", must be a #{friendly_types}.}
        @errors << SchemaError.new(schema, message, :invalid_type)
        nil
      else
        value
      end
    end

    def validate_format(schema, format)
      valid_formats = FORMATS + JsonSchema.configuration.custom_formats.keys
      return if valid_formats.include?(format)

      message = %{#{format.inspect} is not a valid format, must be one of #{valid_formats.join(', ')}.}
      @errors << SchemaError.new(schema, message, :unknown_format)
    end
  end
end