SPB Git

Repository Public

JSONValue.swift 4.3 KB 91 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatCore/Sources/JSONValue.swift3// Description: A Sendable, Codable JSON value used for tool schemas, tool arguments and wire payloads.4import Foundation56public 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 { self = .object(try c.decode([String: JSONValue].self)) }22    }2324    public func encode(to encoder: Encoder) throws {25        var c = encoder.singleValueContainer()26        switch self {27        case .null: try c.encodeNil()28        case .bool(let b): try c.encode(b)29        case .number(let n):30            if n.rounded() == n, abs(n) < 9e15 { try c.encode(Int64(n)) } else { try c.encode(n) }31        case .string(let s): try c.encode(s)32        case .array(let a): try c.encode(a)33        case .object(let o): try c.encode(o)34        }35    }3637    public var stringValue: String? { if case .string(let s) = self { s } else { nil } }38    public var numberValue: Double? { if case .number(let n) = self { n } else { nil } }39    public var intValue: Int? { numberValue.map { Int($0) } }40    public var boolValue: Bool? { if case .bool(let b) = self { b } else { nil } }41    public var arrayValue: [JSONValue]? { if case .array(let a) = self { a } else { nil } }42    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { o } else { nil } }43    public subscript(key: String) -> JSONValue? { objectValue?[key] }4445    /// Converts to Foundation / plain Sendable values (for chat templates and JSONSerialization).46    public var anyValue: any Sendable {47        switch self {48        case .null: NSNull()49        case .bool(let b): b50        case .number(let n): n.rounded() == n && abs(n) < 9e15 ? Int(n) as any Sendable : n51        case .string(let s): s52        case .array(let a): a.map(\.anyValue)53        case .object(let o): o.mapValues(\.anyValue)54        }55    }5657    public init(any value: Any) {58        switch value {59        case let v as JSONValue: self = v60        case let b as Bool where type(of: value) == type(of: true) || CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID(): self = .bool(b)61        case let n as NSNumber: self = .number(n.doubleValue)62        case let s as String: self = .string(s)63        case let a as [Any]: self = .array(a.map { JSONValue(any: $0) })64        case let o as [String: Any]: self = .object(o.mapValues { JSONValue(any: $0) })65        default: self = .null66        }67    }6869    public static func parse(_ text: String) -> JSONValue? {70        guard let data = text.data(using: .utf8) else { return nil }71        return try? JSONDecoder().decode(JSONValue.self, from: data)72    }7374    public func serialized(pretty: Bool = false) -> String {75        let enc = JSONEncoder()76        enc.outputFormatting = pretty ? [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]77        return (try? enc.encode(self)).flatMap { String(data: $0, encoding: .utf8) } ?? "null"78    }79}8081extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral,82                     ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral {83    public init(stringLiteral value: String) { self = .string(value) }84    public init(booleanLiteral value: Bool) { self = .bool(value) }85    public init(integerLiteral value: Int) { self = .number(Double(value)) }86    public init(floatLiteral value: Double) { self = .number(value) }87    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }88    public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { $1 })) }89    public init(nilLiteral: ()) { self = .null }90}91
Files main
Menu

Theme