Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Support/JSONValue.swift3// Description: A lossless JSON value for payloads whose shape is owned by the server or by a data provider (tool results, statement rows).4import Foundation56public enum JSONValue: Sendable, Equatable, 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: "not a 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): 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 subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] } else { return nil } }38 public subscript(index: Int) -> JSONValue? { if case .array(let a) = self, a.indices.contains(index) { return a[index] } else { return nil } }3940 public var stringValue: String? { if case .string(let s) = self { return s } else { return nil } }41 public var boolValue: Bool? { if case .bool(let b) = self { return b } else { return nil } }42 public var arrayValue: [JSONValue]? { if case .array(let a) = self { return a } else { return nil } }43 public var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o } else { return nil } }44 /// A number, or a string that holds one (providers send both).45 public var doubleValue: Double? {46 switch self {47 case .number(let n): return n48 case .string(let s): return Double(s)49 default: return nil50 }51 }52 public var intValue: Int? { doubleValue.flatMap { $0.isFinite ? Int($0) : nil } }53 public var isNull: Bool { self == .null }5455 public static func parse(_ data: Data) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: data) }56 public func data(pretty: Bool = false) -> Data {57 let e = JSONEncoder(); e.outputFormatting = pretty ? [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]58 return (try? e.encode(self)) ?? Data("null".utf8)59 }60}6162extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral {63 public init(stringLiteral value: String) { self = .string(value) }64 public init(booleanLiteral value: Bool) { self = .bool(value) }65 public init(integerLiteral value: Int) { self = .number(Double(value)) }66 public init(floatLiteral value: Double) { self = .number(value) }67 public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }68 public init(dictionaryLiteral elements: (String, JSONValue)...) { self = .object(Dictionary(elements, uniquingKeysWith: { $1 })) }69 public init(nilLiteral: ()) { self = .null }70}7172public extension Data {73 init?(base64URLEncoded s: String) {74 var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")75 while t.count % 4 != 0 { t.append("=") }76 self.init(base64Encoded: t)77 }78 func base64URLEncodedString() -> String {79 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")80 }81}82