Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Models/JSONValue.swift4// Description: Untyped JSON value (tool inputs/outputs, settings) and lenient decoding helpers for the backend's payloads.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112/// A JSON value whose shape is not known at compile time (tool inputs and outputs, per-message settings).13enum JSONValue: Codable, Hashable, Sendable {14 case null15 case bool(Bool)16 case number(Double)17 case string(String)18 case array([JSONValue])19 case object([String: JSONValue])2021 init(from decoder: Decoder) throws {22 let c = try decoder.singleValueContainer()23 if c.decodeNil() { self = .null }24 else if let b = try? c.decode(Bool.self) { self = .bool(b) }25 else if let n = try? c.decode(Double.self) { self = .number(n) }26 else if let s = try? c.decode(String.self) { self = .string(s) }27 else if let a = try? c.decode([JSONValue].self) { self = .array(a) }28 else if let o = try? c.decode([String: JSONValue].self) { self = .object(o) }29 else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unsupported JSON value") }30 }3132 func encode(to encoder: Encoder) throws {33 var c = encoder.singleValueContainer()34 switch self {35 case .null: try c.encodeNil()36 case .bool(let b): try c.encode(b)37 case .number(let n):38 // whole numbers are written without a fractional part (the backend validates some fields as integers)39 if n.rounded() == n, abs(n) < 9e15 { try c.encode(Int64(n)) } else { try c.encode(n) }40 case .string(let s): try c.encode(s)41 case .array(let a): try c.encode(a)42 case .object(let o): try c.encode(o)43 }44 }4546 subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] } else { return nil } }47 var stringValue: String? { if case .string(let s) = self { return s } else { return nil } }48 var doubleValue: Double? {49 switch self { case .number(let n): return n; case .string(let s): return Double(s); default: return nil }50 }51 var intValue: Int? { doubleValue.map { Int($0) } }52 var boolValue: Bool? { if case .bool(let b) = self { return b } else { return nil } }53 var arrayValue: [JSONValue]? { if case .array(let a) = self { return a } else { return nil } }54 var objectValue: [String: JSONValue]? { if case .object(let o) = self { return o } else { return nil } }55 var isNull: Bool { if case .null = self { return true } else { return false } }5657 /// Compact, human-readable rendering used by the tool-call inspector.58 func prettyPrinted(limit: Int = 6000) -> String {59 if case .string(let s) = self { return String(s.prefix(limit)) }60 let enc = JSONEncoder(); enc.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]61 guard let d = try? enc.encode(self), let s = String(data: d, encoding: .utf8) else { return "" }62 return s.count > limit ? String(s.prefix(limit)) + "\n…" : s63 }64}6566extension KeyedDecodingContainer {67 /// PostgreSQL `numeric` / `bigint` columns reach the client either as JSON numbers or as strings: accept both.68 func flexDouble(_ key: Key) -> Double? {69 if let d = try? decodeIfPresent(Double.self, forKey: key) { return d }70 if let s = try? decodeIfPresent(String.self, forKey: key) { return Double(s) }71 return nil72 }73 func flexInt(_ key: Key) -> Int? {74 if let i = try? decodeIfPresent(Int.self, forKey: key) { return i }75 if let d = flexDouble(key) { return Int(d) }76 return nil77 }78 func flexString(_ key: Key) -> String? { (try? decodeIfPresent(String.self, forKey: key)) ?? nil }79 func flexBool(_ key: Key) -> Bool? { (try? decodeIfPresent(Bool.self, forKey: key)) ?? nil }80 func flexDate(_ key: Key) -> Date? {81 guard let s = flexString(key) else { return nil }82 return ISO8601.parse(s)83 }84}8586/// ISO-8601 timestamps as produced by the backend (`2026-11-17T19:02:01.090Z`), with or without fractional seconds.87enum ISO8601 {88 static func parse(_ s: String) -> Date? {89 if let d = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) { return d }90 if let d = try? Date(s, strategy: Date.ISO8601FormatStyle()) { return d }91 return nil92 }93 /// Milliseconds are rounded, then nudged past the binary representation, so a parsed date is written back identically.94 static func string(_ d: Date) -> String {95 let ms = (d.timeIntervalSince1970 * 1000).rounded() / 100096 return Date(timeIntervalSince1970: ms + 0.00002).formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true))97 }98}99