Cotton code
47 lines · 2.6 KB · SwiftRaw
import CottonKitimport Foundation/// A `definitions.catalogue` answer for a scripted core, built from what a/// test means to say about one database: the theme it wears. Every other part/// is empty — the tests that use this read the theme only.enum CatalogueAnswers {    /// The catalogue envelope wearing the theme in `themeEnvelope` (a    /// `{"ok":true,"data":{definition, drawn, passed_over?}}` the old    /// `definitions.theme` answered); a refusal passes through as it is.    static func wearing(_ themeEnvelope: String) -> String {        guard let envelope = (try? JSONSerialization.jsonObject(with: Data(themeEnvelope.utf8))) as? [String: Any],            envelope["ok"] as? Bool == true, let theme = envelope["data"]        else { return themeEnvelope }        let catalogue: [String: Any] = [            "shape": DefinitionCatalogues.shape, "tables": [], "pages": [:], "boards": [:], "theme": theme, "themes": [:],            "kept_as_rows": [], "refused": [],        ]        let data = (try? JSONSerialization.data(withJSONObject: ["ok": true, "data": catalogue])) ?? Data()        return String(decoding: data, as: UTF8.self)    }    /// The catalogue's data alone (a `ScriptedCore.Reply.ok`), wearing the    /// theme `themeData` (`{definition, drawn, passed_over?}`).    static func data(wearing themeData: String) -> String {        let envelope = wearing(#"{"ok":true,"data":"# + themeData + "}")        guard let object = (try? JSONSerialization.jsonObject(with: Data(envelope.utf8))) as? [String: Any],            let data = object["data"], let json = try? JSONSerialization.data(withJSONObject: data)        else { return "{}" }        return String(decoding: json, as: UTF8.self)    }    /// A plain page, for a test table the core would resolve no differently:    /// no hand, no lists, no acts.    static var plainPage: [String: Any] { [        "parts": ["shape": "sheet", "head": ["facts": []], "links": [], "lists": [], "acts": ["more": []]],        "page_parts": ["title", "facts", "grid", "content", "sections"],    ] }    /// A catalogue's data carrying `tables` (their JSON), each with `plainPage`.    static func data(tables: [[String: Any]]) -> [String: Any] {        let pages = Dictionary(tables.compactMap { table in (table["id"] as? String).map { ($0, plainPage as Any) } }) { $1 }        return ["shape": DefinitionCatalogues.shape, "tables": tables, "pages": pages, "boards": [:] as [String: Any],                "theme": ["definition": [:] as [String: Any]], "themes": [:] as [String: Any],                "kept_as_rows": [] as [Any], "refused": [] as [Any]]    }}