Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQJSONBacked.swift3// Description: The forward-compatibility mechanism of the sync models: a typed view over the raw JSON object.4import Foundation56/// A typed view over a JSON object.7///8/// The value **is** its JSON (`raw`); typed properties read and write keys of it. Consequences, by construction:9/// - keys this version does not know (at any depth) survive decode → edit → encode untouched (CONTRACT §1.1:10/// "unknown keys are preserved");11/// - an explicit `null` stays a `null`, an omitted key stays omitted (the server stores the client's own JSON);12/// - a field of an unexpected type reads as absent instead of failing the whole object;13/// - two values are equal exactly when their JSON is equal.14///15/// Setting an optional property to `nil` removes the key ("optional fields may be omitted").16public protocol VQJSONBacked: VQJSONDecodable, Hashable, Codable {17 var raw: VQJSONObject { get set }18 init(raw: VQJSONObject)19}2021public extension VQJSONBacked {22 init(json: VQJSON) { self.init(raw: json.objectValue ?? [:]) }23 var json: VQJSON { .object(raw) }2425 init(from decoder: Decoder) throws { self.init(json: try VQJSON(from: decoder)) }26 func encode(to encoder: Encoder) throws { try json.encode(to: encoder) }2728 /// Keys present in the JSON that this type has no typed property for.29 func unknownKeys(known: Set<String>) -> [String] { raw.keys.filter { !known.contains($0) }.sorted() }3031 // MARK: typed accessors used by the models3233 func string(_ key: String) -> String? { raw[key]?.stringValue }34 func double(_ key: String) -> Double? { raw[key]?.doubleValue }35 func int(_ key: String) -> Int? { raw[key]?.intValue }36 func bool(_ key: String) -> Bool? { raw[key]?.boolValue }37 func strings(_ key: String) -> [String] { raw[key]?.arrayValue?.compactMap(\.stringValue) ?? [] }38 func doubles(_ key: String) -> [Double] { raw[key]?.arrayValue?.compactMap(\.doubleValue) ?? [] }39 func date(_ key: String) -> Date? { double(key).map { Date(timeIntervalSince1970: $0 / 1000) } }40 func items<T: VQJSONBacked>(_ key: String, as type: T.Type = T.self) -> [T] {41 raw[key]?.arrayValue?.compactMap { $0.objectValue.map(T.init(raw:)) } ?? []42 }43 func item<T: VQJSONBacked>(_ key: String, as type: T.Type = T.self) -> T? { raw[key]?.objectValue.map(T.init(raw:)) }4445 mutating func set(_ key: String, _ value: String?) { raw[key] = value.map(VQJSON.string) }46 mutating func set(_ key: String, _ value: Double?) { raw[key] = value.map(VQJSON.number) }47 mutating func set(_ key: String, _ value: Int?) { raw[key] = value.map { VQJSON.number(Double($0)) } }48 mutating func set(_ key: String, _ value: Bool?) { raw[key] = value.map(VQJSON.bool) }49 mutating func set(_ key: String, _ value: [String]?) { raw[key] = value.map { VQJSON($0) } }50 mutating func set(_ key: String, _ value: [Double]?) { raw[key] = value.map { VQJSON($0) } }51 mutating func set(_ key: String, date value: Date?) { raw[key] = value.map { VQJSON.number(($0.timeIntervalSince1970 * 1000).rounded()) } }52 mutating func set<T: VQJSONBacked>(_ key: String, items value: [T]?) { raw[key] = value.map { .array($0.map(\.json)) } }53 mutating func set<T: VQJSONBacked>(_ key: String, item value: T?) { raw[key] = value.map(\.json) }54 mutating func set(_ key: String, json value: VQJSON?) { raw[key] = value }55}5657/// The `data` of a synced object of one kind (CONTRACT §1.1).58public protocol VQSyncData: VQJSONBacked {59 static var kind: VQObjectKind { get }60 /// Client-side check of the fields the contract marks required; the server stays the authority (400 naming the field).61 func validationIssues() -> [String]62}6364public extension VQSyncData {65 func validationIssues() -> [String] { [] }66}6768/// The object kinds of the store. A struct, not an enum: kinds added by a later backend flow through the sync engine69/// untouched (they are replicated as raw JSON).70public struct VQObjectKind: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible, ExpressibleByStringLiteral {71 public let rawValue: String72 public init(rawValue: String) { self.rawValue = rawValue }73 public init(_ rawValue: String) { self.rawValue = rawValue }74 public init(stringLiteral value: String) { self.rawValue = value }75 public var description: String { rawValue }7677 public static let watchlist: VQObjectKind = "watchlist"78 public static let portfolio: VQObjectKind = "portfolio"79 public static let workspace: VQObjectKind = "workspace"80 public static let chart: VQObjectKind = "chart"81 public static let project: VQObjectKind = "project"82 public static let note: VQObjectKind = "note"83 /// Written by the server only (PUT → 403).84 public static let review: VQObjectKind = "review"85 public static let preference: VQObjectKind = "preference"8687 public static let known: [VQObjectKind] = [.watchlist, .portfolio, .workspace, .chart, .project, .note, .review, .preference]88 /// Kinds whose replaced revisions the server archives (last 30).89 public static let versioned: Set<VQObjectKind> = [.project, .note, .chart, .workspace, .portfolio]90 public var isServerOnly: Bool { self == .review }91}9293public enum VQObjectID {94 /// `[A-Za-z0-9_-]{1,64}`95 public static func isValid(_ id: String) -> Bool {96 !id.isEmpty && id.utf8.count <= 64 && id.utf8.allSatisfy { ($0 >= 48 && $0 <= 57) || ($0 >= 65 && $0 <= 90) || ($0 >= 97 && $0 <= 122) || $0 == 95 || $0 == 45 }97 }98 /// A new client-generated id (lower-case UUID).99 public static func make() -> String { UUID().uuidString.lowercased() }100 /// The portfolio the agent reasons about, and the single preference object.101 public static let mainPortfolio = "main"102 public static let defaultPreference = "default"103}104