-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONSchemaResource.swift
364 lines (338 loc) · 12 KB
/
JSONSchemaResource.swift
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
//
// JSONSchemaResource.swift
// DynamicJSON
//
// Created by Matthias Zenger on 25/03/2024.
// Copyright © 2024 Matthias Zenger. 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.
//
import Foundation
///
/// Implementation of JSON Schema resources. These are containers for managing JSON schema.
/// Each resource encapsulates one schema. It manages various indices to look up nested schema
/// as well as anchor definitions. Since schema might be nested, each schema also has an
/// optional `outer` link to its enclosing schema.
///
public class JSONSchemaResource: CustomStringConvertible, CustomDebugStringConvertible {
public let schema: JSONSchema
private var distance: Int = .max
public private(set) weak var outer: JSONSchemaResource? = nil
public private(set) var nested: [JSONLocation : JSONSchemaResource]?
public private(set) var anchors: [String : Anchor]?
public private(set) var selfAnchor: String? = nil
public private(set) var dynamicSelfAnchor: String? = nil
/// Anchors are either static and dynamic. They are stored in resolved form, i.e.
/// referring directly to the corresponding `JSONSchemaResource` object.
public enum Anchor {
case `static`(JSONSchemaResource)
case `dynamic`(JSONSchemaResource)
public var isStatic: Bool {
switch self {
case .static(_):
return true
case .dynamic(_):
return false
}
}
public var resource: JSONSchemaResource {
switch self {
case .static(let resource):
return resource
case .dynamic(let resource):
return resource
}
}
}
/// Collection of errors raised by functionality provided by `JSONSchemaResource`.
public enum Error: LocalizedError, CustomStringConvertible {
case rootSchemaRequiresAbsoluteId
case schemaWithoutId(JSONSchema)
case illegalUriFragment(String)
public var description: String {
switch self {
case .rootSchemaRequiresAbsoluteId:
return "root schema objects require absolute URI as $id"
case .schemaWithoutId(let schema):
if let title = schema.title {
return "schema \"\(title)\" does not provide an $id"
} else {
return "schema does not provide an $id"
}
case .illegalUriFragment(let fragment):
return "illegal URI fragment '\(fragment)'"
}
}
public var errorDescription: String? {
return self.description
}
public var failureReason: String? {
switch self {
case .rootSchemaRequiresAbsoluteId, .schemaWithoutId(_):
return "schema error"
case .illegalUriFragment(_):
return "URI error"
}
}
}
/// Used to initialize nested schema resources.
internal init(nested: JSONSchema, outer: JSONSchemaResource? = nil) {
self.schema = nested
if nested.isBoolean {
self.nested = nil
self.anchors = nil
} else {
self.nested = [:]
self.anchors = [:]
}
self.outer = outer
}
/// Initializes root schema resources, scans the whole document and sets up lookup
/// tables for nested schema and anchors. This constructor forces schema `root` to have
/// an id, i.e. it will generate one if not available.
public convenience init(root: JSONSchema) throws {
switch root {
case .boolean(_):
self.init(nested: root)
return
case .descriptor(var descriptor, let json):
if descriptor.id == nil {
descriptor.id = JSONSchemaIdentifier(string: UUID().uuidString)
}
self.init(nested: .descriptor(descriptor, json))
}
let schemaObjects = self.schema.schemaObjects
for (location, schema) in schemaObjects where location != .root {
let resource = JSONSchemaResource(nested: schema)
for (nestedloc, nestedsub) in self.nested! {
if let relativeloc = location.relative(to: nestedloc) {
nestedsub.nest(resource, at: relativeloc)
} else if let relativeloc = nestedloc.relative(to: location) {
resource.nest(nestedsub, at: relativeloc)
}
}
self.nested![location] = resource
}
for resource in self.nested!.values {
if resource.outer == nil {
resource.outer = self
}
if case .descriptor(let descriptor, _) = resource.schema {
if let anchor = descriptor.anchor {
if descriptor.id != nil {
resource.selfAnchor = anchor
} else if let outer = resource.outer, !outer.schema.isBoolean {
outer.anchors![anchor] = .static(resource)
}
}
if let anchor = descriptor.dynamicAnchor {
if descriptor.id != nil {
resource.dynamicSelfAnchor = anchor
} else if let outer = resource.outer, !outer.schema.isBoolean {
outer.anchors![anchor] = .dynamic(resource)
}
}
}
}
if case .descriptor(let descriptor, _) = self.schema, descriptor.id != nil {
if let anchor = descriptor.anchor {
self.selfAnchor = anchor
}
if let anchor = descriptor.dynamicAnchor {
self.dynamicSelfAnchor = anchor
}
}
}
/// Initializes a schema resource from a `Data` value. The given schema
/// identifier `id` is only used if the schema does not define one itself.
public convenience init(data: Data, id: JSONSchemaIdentifier? = nil) throws {
try self.init(root: JSONSchema(data: data, id: id))
}
/// Initializes a schema resource from a string representation. The given schema
/// identifier `id` is only used if the schema does not define one itself.
public convenience init(string: String, id: JSONSchemaIdentifier? = nil) throws {
try self.init(root: JSONSchema(string: string, id: id))
}
/// Initializes a schema resource from a URL for the given default JSON schema identifier.
/// The given schema identifier `id` is only used if the schema does not define one itself.
public convenience init(url: URL, id: JSONSchemaIdentifier? = nil) throws {
try self.init(root: JSONSchema(url: url, id: id))
}
/// Returns true if this is an anonymous schema resource
public var isAnonymous: Bool {
return self.schema.id == nil
}
/// Returns true if this is a root schema resource, i.e. it does not have an outer resource.
public var isRoot: Bool {
return self.schema.id != nil && self.outer == nil
}
/// Returns the id of this schema resource
public var id: JSONSchemaIdentifier? {
return self.schema.id
}
public var nonAnonymousResource: JSONSchemaResource {
var res: JSONSchemaResource? = self
while res?.isAnonymous ?? false {
res = res?.outer
}
return res ?? self
}
/// Returns a resource map for all internal, nested schema resources.
public var resources: [JSONSchemaIdentifier : JSONSchemaResource] {
guard let nested else {
return [:]
}
var res: [JSONSchemaIdentifier : JSONSchemaResource] = [:]
for nested in nested.values {
if let nestedId = nested.id {
res[nestedId] = nested
}
}
if let id {
res[id] = self
}
return res
}
/// Returns all nested schema resources.
public var nestedResources: [JSONSchemaResource] {
return [JSONSchemaResource]((self.nested ?? [:]).values)
}
/// Resolves the given anchor for this schema resource.
public func resolve(anchor: String?) throws -> Anchor? {
if self.isAnonymous, let outer = self.outer {
return try outer.resolve(anchor: anchor)
}
guard let anchor else {
return .static(self)
}
if anchor.isEmpty {
return .static(self)
} else if let anchors = self.anchors, let subschema = anchors[anchor] {
return subschema
} else if self.selfAnchor == anchor {
return .static(self)
} else if self.dynamicSelfAnchor == anchor {
return .dynamic(self)
}
return nil
}
/// Resolves the given JSON reference for this schema resource
public func resolve(ref: JSONReference & JSONLocationConvertible) throws -> Anchor? {
if self.isAnonymous, let outer = self.outer {
return try outer.resolve(ref: ref)
}
if ref.isRoot {
return .static(self)
} else if let nested = self.nested {
let locations = ref.locations()
// Find via known keywords
for location in locations {
if let subschema = nested[location] {
return .static(subschema)
}
}
// Find via unknown keywords
if case .descriptor(_, let json) = self.schema,
let target = ref.get(from: json),
let targetSchema: JSONSchema = try? target.coerce() {
return .static(JSONSchemaResource(nested: targetSchema, outer: self))
}
}
return nil
}
/// Resolves a fragment relative to this schema resource.
public func resolve(fragment: String?) throws -> Anchor {
if self.isAnonymous, let outer = self.outer {
return try outer.resolve(fragment: fragment)
}
guard let fragment else {
return .static(self)
}
if fragment.isEmpty {
return .static(self)
} else if fragment.starts(with: "/") {
if let nested = self.nested {
// Resolve as JSON pointer reference
let pointer = try JSONPointer(fragment)
let locations = pointer.locations()
// Find via known keywords
for location in locations {
if let subschema = nested[location] {
return .static(subschema)
}
}
// Find via unknown keywords
if case .descriptor(_, let json) = self.schema,
let target = pointer.get(from: json),
let targetSchema: JSONSchema = try? target.coerce() {
return .static(JSONSchemaResource(nested: targetSchema, outer: self))
}
}
} else if let anchors = self.anchors, let subschema = anchors[fragment] {
return subschema
} else if self.selfAnchor == fragment {
return .static(self)
} else if self.dynamicSelfAnchor == fragment {
return .dynamic(self)
}
throw Error.illegalUriFragment(fragment)
}
/// Nests a subschema under this schema at `location`.
private func nest(_ subschema: JSONSchemaResource, at location: JSONLocation) {
guard !self.isAnonymous else {
return
}
self.nested?[location] = subschema
let distance = location.segmentCount
if !self.isAnonymous && distance < subschema.distance {
subschema.outer = self
subschema.distance = distance
}
}
public var description: String {
if let id = self.id {
return "resource(\(id))"
} else {
return "resource(<anon>)"
}
}
public var debugDescription: String {
var res: String = "JSON SCHEMA RESOURCE FOR\n" + self.schema.debugDescription + "\n"
if let outer = self.outer {
res += "OUTER (distance = \(self.distance)\n" + outer.schema.debugDescription + "\n"
}
if let nested = self.nested {
res += "NESTED\n"
for (key, value) in nested {
res += " \(key) -> \(value.description)\n"
}
}
if let anchors = self.anchors {
res += "ANCHORS\n"
for (key, value) in anchors {
if value.isStatic {
res += " static \(key) -> \(value.resource.description)\n"
} else {
res += " dynamic \(key) -> \(value.resource.description)\n"
}
}
}
if let selfAnchor = self.selfAnchor {
res += "SELF ANCHOR = '\(selfAnchor)'\n"
}
if let selfAnchor = self.dynamicSelfAnchor {
res += "DYNAMIC SELF ANCHOR = '\(selfAnchor)'\n"
}
return res
}
}