Cotton code
223 lines · 11.3 KB · SwiftRaw
// Every definition a database draws — tables, boards, themes — as the CORE// resolved and decoded them (`definitions.catalogue`,// `crates/cotton-ffi/src/phone/catalogue.rs`), read into the view types this// app draws from.//// ONE DECODER OF THE DEFINITION FORMAT (architect, 14 Oct 2026). Phone cut 273// crashed before its first screen: a definition file the core accepted failed// this app's own decoder of the same file. The app no longer reads a// definition file: the core reads them, validates them, says once in// Feedback any stored one it cannot draw, and hands each back as its typed// value serialized.//// A database draws the tables its own definition rows describe and no other// (tools are records only, 21 Oct 2026): no table is drawn from this build.// What the app draws before any database answers is the core's last resort —// this build's boards and themes, no table://   * the app's process asks its core once, right after opening it//     (`receiveLastResort(from:)`), and keeps the boards — a shape this build//     cannot read, or a board it cannot draw, is a refusal the open screen//     says, never a crash;//   * a process with no core of its own (the package's tests) reads//     the same answer from the snapshot beside the resources//     (`Resources/Shipped/catalogue.json`).// A database's own catalogue is cached per database (`DefinitionCatalogues`).// Previews and the package's tests draw a synthetic household that took the// kit (`Resources/Fixtures/catalogue.json`, `fixture(in:)`), never the app.//// THIS FILE IS THE ONE BOUNDARY: no other Swift decodes a table or board// definition (`NoSecondDecoderTests`).import CottonKitimport Foundationimport osextension TableDefinition {    /// Decodes one definition from the format's JSON — only what the core    /// handed over, and only here (and in the tests' fixtures).    static func decode(_ data: Data) throws -> TableDefinition {        try JSONDecoder().decode(TableDefinition.self, from: data)    }}extension BoardDefinition {    /// The board a row describes, or nil for data that is not a board (no id    /// or no parts) — only what the core handed over, and only here.    static func decode(_ data: Data) -> BoardDefinition? {        guard let board = try? JSONDecoder().decode(Self.self, from: data),              !board.id.isEmpty, !board.parts.isEmpty else { return nil }        return board    }    static func decode(_ object: [String: Any]) -> BoardDefinition? {        guard let data = try? JSONSerialization.data(withJSONObject: object) else { return nil }        return decode(data)    }}public struct DefinitionCatalogue: Sendable {    /// Every table the answer carried, by id.    public let tables: [TableDefinition]    /// Every table as the core serialized it, by id — what a screen that    /// edits a definition compares a database's row against.    public let tableRows: [String: Data]    /// Every board by id.    public let boards: [String: BoardDefinition]    /// Every shipped theme's row by id, as `Theme.decode` reads one.    public let themeRows: [String: Data]    /// Each definition the answer carried that this build could not draw,    /// named with why. A last-resort hand-over with any is refused.    public let failures: [String]    static let empty = DefinitionCatalogue(tables: [], tableRows: [:], boards: [:], themeRows: [:], failures: [])    /// A shipped answer this build cannot draw all of.    struct Undrawable: Error, Equatable, CustomStringConvertible {        let failures: [String]        var description: String {            ShellLines.line("definitions", "catalogue.undrawable", ["count": String(failures.count), "failures": failures.joined(separator: "; ")])        }    }    /// The tables of one answer: a table that does not decode is named in    /// `failures` and left out — never a trap.    static func tables(_ raw: RawCatalogue) -> (tables: [TableDefinition], failures: [String]) {        var tables: [TableDefinition] = []        var failures: [String] = []        for (index, data) in raw.tables.enumerated() {            let id = raw.tableIDs[index]            do {                tables.append(try table(data, id: id, in: raw))            } catch {                failures.append("table \(id.isEmpty ? "#\(index)" : id): \(error)")            }        }        return (tables, failures)    }    /// The lines `sayUndrawn` has written in this process.    private static let said = OSAllocatedUnfairLock<Set<String>>(initialState: [])    /// What the reader holds of one answer, said ONCE per process for each    /// database and outcome: how many tables it draws of the rows served, and    /// every row it draws nowhere by id with why — the storage tables kept as    /// rows, the rows the core refused, any table this build could not decode    /// (`failures`) and any imported table the tool catalogue does not name    /// (`unnamed`). A row is never left out silently (tables-dropped, 28 Oct    /// 2026: 35 of Personal's 144 reached the fan as nothing at all).    /// Returns the line, written now or already said.    @discardableResult    static func sayUndrawn(        _ raw: RawCatalogue, drawn: Int, failures: [String], unnamed: [String] = [], database: String    ) -> String {        let line = undrawnLine(raw, drawn: drawn, failures: failures, unnamed: unnamed, database: database)        let fresh = said.withLock { $0.insert(line).inserted }        if fresh {            let wrong = raw.undrawn.contains { $0.kind == .refused } || !failures.isEmpty || !unnamed.isEmpty            if wrong { Log.warn(line) } else { Log.write(line) }        }        return line    }    /// `sayUndrawn`'s line: `definitions: <database> draws 109 of 144 tables served; kept as rows (<why>): a, b; refused: c (<why>); not decoded: …; imported, not in the tool catalogue: …`.    static func undrawnLine(        _ raw: RawCatalogue, drawn: Int, failures: [String], unnamed: [String] = [], database: String    ) -> String {        let served = raw.tables.count + raw.undrawn.count        var parts = [ShellLines.line("definitions", "catalogue.draws", ["database": database.isEmpty ? "personal" : database, "drawn": String(drawn), "served": String(served)])]        let kept = raw.undrawn.filter { $0.kind == .keptAsRows }        for reason in Array(Set(kept.map(\.reason))).sorted() {            parts.append(ShellLines.line("definitions", "catalogue.kept_reason", ["reason": reason]) + " " + kept.filter { $0.reason == reason }.map(\.id).sorted().joined(separator: ", "))        }        let refused = raw.undrawn.filter { $0.kind == .refused }        if !refused.isEmpty {            parts.append("refused: " + refused.map { "\($0.id) (\($0.reason))" }.joined(separator: ", "))        }        if !failures.isEmpty { parts.append(ShellLines.line("definitions", "catalogue.not_decoded") + " " + failures.joined(separator: ", ")) }        if !unnamed.isEmpty { parts.append(ShellLines.line("definitions", "catalogue.not_in_catalogue") + " " + unnamed.sorted().joined(separator: ", ")) }        return parts.joined(separator: "; ")    }    /// No page came with a table: the core resolves every table's page.    struct NoPage: Error, CustomStringConvertible {        var description: String { ShellLines.line("definitions", "catalogue.no_page") }    }    /// One table of an answer, with the page the core resolved for it.    static func table(_ data: Data, id: String, in raw: RawCatalogue) throws -> TableDefinition {        guard let page = raw.pages[id] else { throw NoPage() }        return try TableDefinition.decode(data).drawing(JSONDecoder().decode(DrawnPage.self, from: page)).saying(raw.said[id])    }    /// The board a catalogue's row describes, or nil for data that is not a    /// board (no id or no parts): the caller then draws this build's default.    public static func board(_ drawn: DrawnBoard) -> BoardDefinition? {        BoardDefinition.decode(drawn.definition)    }    /// Read one answer into the view types.    public static func read(_ raw: RawCatalogue) -> DefinitionCatalogue {        var (tables, failures) = tables(raw)        var boards: [String: BoardDefinition] = [:]        for (id, drawn) in raw.boards {            if let board = board(drawn) {                boards[id] = board            } else {                failures.append(ShellLines.line("definitions", "catalogue.not_a_board", ["id": id]))            }        }        tables.sort { $0.id < $1.id }        var tableRows: [String: Data] = [:]        for (id, data) in zip(raw.tableIDs, raw.tables) where !id.isEmpty { tableRows[id] = data }        return DefinitionCatalogue(tables: tables, tableRows: tableRows, boards: boards, themeRows: raw.themes, failures: failures)    }    /// The last-resort snapshot a bundle carries, or nil when it carries none.    static func lastResort(in bundle: Bundle?) throws -> DefinitionCatalogue? {        try read(bundle?.url(forResource: "catalogue", withExtension: "json", subdirectory: "Shipped"))    }    /// The synthetic household's catalogue a bundle carries — the kit as a    /// database that imported it draws it — or nil when it carries none.    /// Previews and the package's tests draw it; a database never does.    public static func fixture(in bundle: Bundle?) throws -> DefinitionCatalogue? {        try read(bundle?.url(forResource: "catalogue", withExtension: "json", subdirectory: "Fixtures"))    }    private static func read(_ url: URL?) throws -> DefinitionCatalogue? {        guard let url else { return nil }        return read(try DefinitionCatalogues.read(FixtureDefinitions.readBundledJSON(url, limit: 8_388_608)))    }    // ── This process's last resort: boards ────────────────────────────────    private static let held = OSAllocatedUnfairLock<[String: BoardDefinition]?>(initialState: nil)    /// The boards this build ships, drawn before a database's catalogue has    /// answered: the last resort this process's core handed over, or — in a    /// process that opened no core — the snapshot in the app's resources.    /// Empty only in a build with no resources at all; it never traps.    public static var shippedBoards: [String: BoardDefinition] {        if let boards = held.withLock({ $0 }) { return boards }        let bundled = (try? lastResort(in: CottonUIResources.bundle))??.boards        return held.withLock { held in            let boards = held ?? bundled ?? [:]            held = boards            return boards        }    }    /// The shipped themes' rows: the core's answer once it has handed one    /// over, else the snapshot's.    public static var shippedThemeRows: [String: Data] { ShippedThemes.rows }    /// Ask the core for its last resort and keep its boards and themes as this    /// process's. Refused — and nothing kept — when the shape is not this    /// build's, the answer is not one, or any board in it cannot be drawn.    public static func receiveLastResort(from core: any CottonCalling) async throws {        let answer = read(try await DefinitionCatalogues.ask(core, shipped: true))        guard answer.failures.isEmpty else { throw Undrawable(failures: answer.failures) }        held.withLock { $0 = answer.boards }        ShippedThemes.receive(answer.themeRows)    }}