SPB Git

Repository Public License

JSONSchema.swift 11.2 KB 193 lines swift

1import Foundation2import ProviderKit34/// One reason a value (or a schema) was rejected. `path` is a JSON path such as `$.fields[2].name`.5public struct SchemaIssue: Sendable, Hashable, CustomStringConvertible {6    public var path: String7    public var message: String89    public init(path: String, message: String) { self.path = path; self.message = message }10    public var description: String { "\(path): \(message)" }11}1213/// A deliberately small JSON Schema validator for tool arguments.14///15/// Supported keywords: `type` (object, string, integer, number, boolean, array), `description`, `properties`,16/// `required`, `additionalProperties` (must be `false` on every object), `enum`, `minimum`, `maximum`, `minLength`,17/// `maxLength`, `items`, `minItems`, `maxItems`. A schema using anything else is itself invalid, and validation18/// against an invalid schema always fails: an unsupported constraint is never silently ignored.19public enum SchemaValidator {20    public static let supportedKeywords: Set<String> = [21        "type", "description", "properties", "required", "additionalProperties", "enum", "minimum", "maximum",22        "minLength", "maxLength", "items", "minItems", "maxItems",23    ]24    public static let supportedTypes: Set<String> = ["object", "string", "integer", "number", "boolean", "array"]25    static let maxDepth = 1226    static let maxIssues = 122728    private static let applicability: [String: Set<String>] = [29        "properties": ["object"], "required": ["object"], "additionalProperties": ["object"],30        "minLength": ["string"], "maxLength": ["string"],31        "minimum": ["integer", "number"], "maximum": ["integer", "number"],32        "items": ["array"], "minItems": ["array"], "maxItems": ["array"],33        "enum": ["string", "integer", "number"],34    ]3536    /// Problems with the schema itself. Empty when every keyword is supported and well formed.37    public static func schemaIssues(_ schema: JSONValue) -> [SchemaIssue] {38        var issues: [SchemaIssue] = []39        check(schema: schema, path: "$", depth: 0, into: &issues)40        return issues41    }4243    /// Problems with `value`. Empty means the value is acceptable.44    public static func validate(_ value: JSONValue, against schema: JSONValue) -> [SchemaIssue] {45        let broken = schemaIssues(schema)46        if !broken.isEmpty {47            return broken.prefix(maxIssues).map { SchemaIssue(path: $0.path, message: "unsupported schema: \($0.message)") }48        }49        var issues: [SchemaIssue] = []50        validate(value, schema: schema, path: "$", depth: 0, into: &issues)51        return Array(issues.prefix(maxIssues))52    }5354    // MARK: Schema well-formedness5556    private static func check(schema: JSONValue, path: String, depth: Int, into issues: inout [SchemaIssue]) {57        guard issues.count < maxIssues else { return }58        guard depth <= maxDepth else { issues.append(SchemaIssue(path: path, message: "schema nested too deeply")); return }59        guard let fields = schema.objectValue else { issues.append(SchemaIssue(path: path, message: "a schema must be an object")); return }60        for key in fields.keys.sorted() where !supportedKeywords.contains(key) {61            issues.append(SchemaIssue(path: path, message: "keyword “\(key)” is not supported"))62        }63        guard let type = fields["type"]?.stringValue, supportedTypes.contains(type) else {64            issues.append(SchemaIssue(path: path, message: "“type” must be one of \(supportedTypes.sorted().joined(separator: ", "))"))65            return66        }67        for (keyword, types) in applicability where fields[keyword] != nil && !types.contains(type) {68            issues.append(SchemaIssue(path: path, message: "“\(keyword)” does not apply to type \(type)"))69        }70        if let description = fields["description"], description.stringValue == nil {71            issues.append(SchemaIssue(path: path, message: "“description” must be a string"))72        }73        switch type {74        case "object":75            // Closed objects only: a tool never accepts a property it did not declare.76            if fields["additionalProperties"] != .bool(false) {77                issues.append(SchemaIssue(path: path, message: "“additionalProperties” must be false"))78            }79            var names = Set<String>()80            if let properties = fields["properties"] {81                guard let map = properties.objectValue else {82                    issues.append(SchemaIssue(path: path, message: "“properties” must be an object")); return83                }84                names = Set(map.keys)85                for key in map.keys.sorted() { check(schema: map[key] ?? .null, path: "\(path).\(key)", depth: depth + 1, into: &issues) }86            }87            if let required = fields["required"] {88                guard let list = required.arrayValue, list.allSatisfy({ $0.stringValue != nil }) else {89                    issues.append(SchemaIssue(path: path, message: "“required” must be an array of strings")); return90                }91                for name in list.compactMap(\.stringValue) where !names.contains(name) {92                    issues.append(SchemaIssue(path: path, message: "required property “\(name)” is not declared"))93                }94            }95        case "string":96            for keyword in ["minLength", "maxLength"] {97                if let bound = fields[keyword], (bound.intValue ?? -1) < 0 {98                    issues.append(SchemaIssue(path: path, message: "“\(keyword)” must be a non-negative integer"))99                }100            }101            if let options = fields["enum"], !(options.arrayValue.map { !$0.isEmpty && $0.allSatisfy { $0.stringValue != nil } } ?? false) {102                issues.append(SchemaIssue(path: path, message: "“enum” must be a non-empty array of strings"))103            }104        case "integer", "number":105            for keyword in ["minimum", "maximum"] {106                if let bound = fields[keyword], numeric(bound) == nil {107                    issues.append(SchemaIssue(path: path, message: "“\(keyword)” must be a number"))108                }109            }110            if let options = fields["enum"], !(options.arrayValue.map { !$0.isEmpty && $0.allSatisfy { numeric($0) != nil } } ?? false) {111                issues.append(SchemaIssue(path: path, message: "“enum” must be a non-empty array of numbers"))112            }113        case "array":114            guard let items = fields["items"] else {115                issues.append(SchemaIssue(path: path, message: "an array needs “items”")); return116            }117            for keyword in ["minItems", "maxItems"] {118                if let bound = fields[keyword], (bound.intValue ?? -1) < 0 {119                    issues.append(SchemaIssue(path: path, message: "“\(keyword)” must be a non-negative integer"))120                }121            }122            check(schema: items, path: "\(path)[]", depth: depth + 1, into: &issues)123        default: break124        }125    }126127    /// A JSON number only: `JSONValue.doubleValue` also accepts numeric strings, which a schema must not.128    private static func numeric(_ value: JSONValue) -> Double? {129        if case .number(let number) = value, number.isFinite { return number }130        return nil131    }132133    // MARK: Value validation134135    private static func validate(_ value: JSONValue, schema: JSONValue, path: String, depth: Int, into issues: inout [SchemaIssue]) {136        guard issues.count < maxIssues, let fields = schema.objectValue, let type = fields["type"]?.stringValue else { return }137        guard depth <= maxDepth else { issues.append(SchemaIssue(path: path, message: "value nested too deeply")); return }138        switch type {139        case "object":140            guard let object = value.objectValue else { issues.append(SchemaIssue(path: path, message: "expected an object")); return }141            let properties = fields["properties"]?.objectValue ?? [:]142            for key in object.keys.sorted() where properties[key] == nil {143                issues.append(SchemaIssue(path: path, message: "unknown property “\(AgentText.singleLine(key, limit: 40))”"))144            }145            for name in (fields["required"]?.arrayValue ?? []).compactMap(\.stringValue) where object[name] == nil {146                issues.append(SchemaIssue(path: path, message: "missing required property “\(name)”"))147            }148            for key in properties.keys.sorted() {149                if let child = object[key], let childSchema = properties[key] {150                    validate(child, schema: childSchema, path: "\(path).\(key)", depth: depth + 1, into: &issues)151                }152            }153        case "string":154            guard let text = value.stringValue else { issues.append(SchemaIssue(path: path, message: "expected a string")); return }155            if let max = fields["maxLength"]?.intValue, text.count > max {156                issues.append(SchemaIssue(path: path, message: "longer than \(max) characters"))157            }158            if let min = fields["minLength"]?.intValue, text.count < min {159                issues.append(SchemaIssue(path: path, message: "shorter than \(min) characters"))160            }161            if let options = fields["enum"]?.arrayValue, !options.contains(value) {162                issues.append(SchemaIssue(path: path, message: "must be one of \(options.compactMap(\.stringValue).joined(separator: ", "))"))163            }164        case "integer", "number":165            guard let number = numeric(value) else {166                issues.append(SchemaIssue(path: path, message: "expected \(type == "integer" ? "an integer" : "a number")")); return167            }168            if type == "integer", value.intValue == nil { issues.append(SchemaIssue(path: path, message: "expected an integer")); return }169            if let min = fields["minimum"].flatMap(numeric), number < min { issues.append(SchemaIssue(path: path, message: "below the minimum \(format(min))")) }170            if let max = fields["maximum"].flatMap(numeric), number > max { issues.append(SchemaIssue(path: path, message: "above the maximum \(format(max))")) }171            if let options = fields["enum"]?.arrayValue, !options.contains(where: { numeric($0) == number }) {172                issues.append(SchemaIssue(path: path, message: "not one of the allowed values"))173            }174        case "boolean":175            if value.boolValue == nil { issues.append(SchemaIssue(path: path, message: "expected a boolean")) }176        case "array":177            guard let items = value.arrayValue else { issues.append(SchemaIssue(path: path, message: "expected an array")); return }178            if let max = fields["maxItems"]?.intValue, items.count > max { issues.append(SchemaIssue(path: path, message: "more than \(max) items")); return }179            if let min = fields["minItems"]?.intValue, items.count < min { issues.append(SchemaIssue(path: path, message: "fewer than \(min) items")) }180            if let itemSchema = fields["items"] {181                for (index, item) in items.enumerated() {182                    validate(item, schema: itemSchema, path: "\(path)[\(index)]", depth: depth + 1, into: &issues)183                }184            }185        default: break186        }187    }188189    private static func format(_ number: Double) -> String {190        number == number.rounded() && abs(number) < 1e15 ? String(Int(number)) : String(number)191    }192}193
Files main
Menu

Theme