SPB Git

Repository Public

JSONValue.swift 6.0 KB 121 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Models/JSONValue.swift3// Description: Loss-free JSON value used for open-ended server payloads (settings, tool inputs/outputs) and lenient decoding helpers.4import Foundation56/// A JSON document kept as-is. Used wherever the server schema is open (tool inputs, settings blobs).7public enum JSONValue: Sendable, Hashable, Codable {8    case null9    case bool(Bool)10    case number(Double)11    case string(String)12    case array([JSONValue])13    case object([String: JSONValue])1415    public init(from decoder: Decoder) throws {16        let c = try decoder.singleValueContainer()17        if c.decodeNil() { self = .null }18        else if let b = try? c.decode(Bool.self) { self = .bool(b) }19        else if let n = try? c.decode(Double.self) { self = .number(n) }20        else if let s = try? c.decode(String.self) { self = .string(s) }21        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }22        else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }23        else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unsupported JSON value") }24    }2526    public func encode(to encoder: Encoder) throws {27        var c = encoder.singleValueContainer()28        switch self {29        case .null: try c.encodeNil()30        case .bool(let b): try c.encode(b)31        case .number(let n):32            if n.rounded() == n, abs(n) < 9_007_199_254_740_992 { try c.encode(Int64(n)) } else { try c.encode(n) }33        case .string(let s): try c.encode(s)34        case .array(let a): try c.encode(a)35        case .object(let o): try c.encode(o)36        }37    }3839    public subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] }; return nil }40    public subscript(index: Int) -> JSONValue? { if case .array(let a) = self, a.indices.contains(index) { return a[index] }; return nil }4142    public var stringValue: String? { if case .string(let s) = self { return s }; return nil }43    public var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }44    public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }45    public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o }; return nil }46    public var isNull: Bool { if case .null = self { return true }; return false }47    /// Numbers also arrive as strings for PostgreSQL `bigint` / `numeric` columns.48    public var doubleValue: Double? {49        switch self {50        case .number(let n): return n51        case .string(let s): return Double(s)52        default: return nil53        }54    }55    public var intValue: Int? { doubleValue.flatMap { $0.isFinite ? Int($0) : nil } }5657    /// Compact or pretty JSON text (sorted keys so that output is stable in tests and exports).58    public func jsonString(pretty: Bool = false) -> String {59        let enc = JSONEncoder()60        enc.outputFormatting = pretty ? [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]61        guard let d = try? enc.encode(self), let s = String(data: d, encoding: .utf8) else { return "null" }62        return s63    }6465    public static func parse(_ data: Data) -> JSONValue? { try? JSONDecoder().decode(JSONValue.self, from: data) }66}6768extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByNilLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {69    public init(stringLiteral value: String) { self = .string(value) }70    public init(booleanLiteral value: Bool) { self = .bool(value) }71    public init(integerLiteral value: Int) { self = .number(Double(value)) }72    public init(floatLiteral value: Double) { self = .number(value) }73    public init(nilLiteral: ()) { self = .null }74    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }75    public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { $1 })) }76}7778extension KeyedDecodingContainer {79    /// Double that may be encoded as a JSON number or as a string (PostgreSQL numeric / bigint).80    func flexDouble(_ key: Key) -> Double? {81        if let v = try? decodeIfPresent(Double.self, forKey: key) { return v }82        if let s = try? decodeIfPresent(String.self, forKey: key) { return Double(s) }83        return nil84    }85    func flexInt(_ key: Key) -> Int? { flexDouble(key).flatMap { $0.isFinite ? Int($0) : nil } }86    func optional<T: Decodable>(_ type: T.Type, _ key: Key) -> T? { (try? decodeIfPresent(type, forKey: key)) ?? nil }87}8889/// Dates sent by the server are ISO 8601 with milliseconds (`2026-11-17T19:01:57.373Z`); date-only values also occur.90public enum ServerDate {91    public static func parse(_ s: String) -> Date? {92        if let d = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) { return d }93        if let d = try? Date(s, strategy: Date.ISO8601FormatStyle()) { return d }94        if s.count == 10, let d = try? Date(s + "T00:00:00Z", strategy: Date.ISO8601FormatStyle()) { return d }95        return nil96    }97    public static func string(_ d: Date) -> String { d.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true)) }98}99100public extension JSONDecoder {101    /// Decoder configured for the chat API.102    static func api() -> JSONDecoder {103        let d = JSONDecoder()104        d.dateDecodingStrategy = .custom { dec in105            let c = try dec.singleValueContainer()106            let s = try c.decode(String.self)107            guard let date = ServerDate.parse(s) else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "Invalid date \(s)") }108            return date109        }110        return d111    }112}113public extension JSONEncoder {114    static func api() -> JSONEncoder {115        let e = JSONEncoder()116        e.dateEncodingStrategy = .custom { date, enc in var c = enc.singleValueContainer(); try c.encode(ServerDate.string(date)) }117        e.outputFormatting = [.withoutEscapingSlashes]118        return e119    }120}121
Files main
Menu

Theme