SPB Git

Repository Public

JSONValue.swift 4.2 KB 91 lines swift

1import Foundation2import OpenAPIRuntime34/// A JSON value. Used for the free-form parts of the contract (WebAuthn payloads, action parameters,5/// JSON Schemas, results, settings) so that the rest of the code never handles `Any`.6public enum JSONValue: Sendable, Hashable, Codable {7    case null8    case bool(Bool)9    case number(Double)10    case string(String)11    case array([JSONValue])12    case object([String: JSONValue])1314    public init(from decoder: Decoder) throws {15        let c = try decoder.singleValueContainer()16        if c.decodeNil() { self = .null }17        else if let b = try? c.decode(Bool.self) { self = .bool(b) }18        else if let n = try? c.decode(Double.self) { self = .number(n) }19        else if let s = try? c.decode(String.self) { self = .string(s) }20        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }21        else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }22        else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unsupported JSON value") }23    }2425    public func encode(to encoder: Encoder) throws {26        var c = encoder.singleValueContainer()27        switch self {28        case .null: try c.encodeNil()29        case .bool(let b): try c.encode(b)30        case .number(let n):31            if n.rounded() == n, abs(n) < 9_007_199_254_740_992 { try c.encode(Int64(n)) } else { try c.encode(n) }32        case .string(let s): try c.encode(s)33        case .array(let a): try c.encode(a)34        case .object(let o): try c.encode(o)35        }36    }3738    public subscript(key: String) -> JSONValue? {39        if case .object(let o) = self { return o[key] }40        return nil41    }42    public var stringValue: String? { if case .string(let s) = self { return s }; return nil }43    public var doubleValue: Double? { if case .number(let n) = self { return n }; return nil }44    public var intValue: Int? { if case .number(let n) = self, n.rounded() == n { return Int(n) }; return nil }45    public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }46    public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }47    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }4849    /// Compact, human-readable rendering (sorted keys) for read-only display.50    public func prettyPrinted() -> String {51        let enc = JSONEncoder()52        enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]53        guard let d = try? enc.encode(self), let s = String(data: d, encoding: .utf8) else { return "" }54        return s55    }5657    public static func parse(_ data: Data) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: data) }58    public func data() throws -> Data { try JSONEncoder().encode(self) }59}6061extension JSONValue {62    /// Bridges through JSON text: the generated containers are Codable, which keeps this independent of their internals.63    public init<T: Encodable>(encoding value: T) throws {64        self = try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value))65    }66    public func decode<T: Decodable>(_ type: T.Type) throws -> T {67        try JSONDecoder().decode(T.self, from: JSONEncoder().encode(self))68    }69    public init(_ container: OpenAPIObjectContainer) {70        self = (try? JSONValue(encoding: container)) ?? .object([:])71    }72    public init(_ container: OpenAPIValueContainer) {73        self = (try? JSONValue(encoding: container)) ?? .null74    }75    public func objectContainer() throws -> OpenAPIObjectContainer { try decode(OpenAPIObjectContainer.self) }76    public func valueContainer() throws -> OpenAPIValueContainer { try decode(OpenAPIValueContainer.self) }77}7879/// base64url without padding, as used by WebAuthn JSON.80public enum Base64URL {81    public static func encode(_ data: Data) -> String {82        data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")83            .replacingOccurrences(of: "=", with: "")84    }85    public static func decode(_ string: String) -> Data? {86        var s = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")87        while s.count % 4 != 0 { s.append("=") }88        return Data(base64Encoded: s)89    }90}91
Files main
Menu

Theme