import Foundation struct CRDTProjection: Decodable, Sendable { var children: [CRDTNode] var canUndo: Bool var canRedo: Bool } struct CRDTNode: Decodable, Identifiable, Sendable { let id: String let type: String var attrs: [String: String]? var children: [CRDTNode]? var runs: [CRDTRun]? var plainText: String { runs?.map(\.insert).joined() ?? children?.map(\.plainText).joined() ?? "" } } struct CRDTRun: Decodable, Sendable { var insert: String var marks: [String: JSONValue]? } indirect enum JSONValue: Codable, Sendable, Equatable { case object([String: JSONValue]), array([JSONValue]), string(String), number(Double), bool(Bool), null init(from decoder: any Decoder) throws { let c = try decoder.singleValueContainer() if c.decodeNil() { self = .null } else if let v = try? c.decode(Bool.self) { self = .bool(v) } else if let v = try? c.decode(String.self) { self = .string(v) } else if let v = try? c.decode(Double.self) { self = .number(v) } else if let v = try? c.decode([String: JSONValue].self) { self = .object(v) } else { self = .array(try c.decode([JSONValue].self)) } } func encode(to encoder: any Encoder) throws { var c = encoder.singleValueContainer() switch self { case .object(let v): try c.encode(v) case .array(let v): try c.encode(v) case .string(let v): try c.encode(v) case .number(let v): try c.encode(v) case .bool(let v): try c.encode(v) case .null: try c.encodeNil() } } }