import CottonKit import CottonValues import Foundation @testable import CottonUI /// Fixture implementation of #1298's exact CottonCalling envelopes. Packaging /// reads the four shipped JSON files, and the fixture decoder checks the bytes actually /// handed to tools.import rather than pretending a manifest is a package. actor ClassroomPackageCore: CottonCalling { private(set) var catalogReads = 0 private let tool: ToolDefinition private let definitions: [TableDefinition] private let rows: [String: [TableRecord]] private var installed = false private var orphaned = false private let refusal: String? private var imported: Data? /// Whether the last import asked for the package's sample rows. private(set) var withSamples = false static var root: URL { if let root = CottonUIResources.bundle?.resourceURL { return root.appendingPathComponent("Fixtures/classroom") } return SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources/Fixtures/classroom") } init(refusal: String? = nil) throws { let root = Self.root tool = try ToolDefinition.decode(Data(contentsOf: root.appendingPathComponent("manifest.json"))) definitions = try tool.tables.map { try TableDefinition.decode(Data(contentsOf: root.appendingPathComponent("tables/\($0).json"))) } rows = try Dictionary(uniqueKeysWithValues: tool.tables.map { ($0, try JSONDecoder().decode([TableRecord].self, from: Data(contentsOf: root.appendingPathComponent("records/\($0).json")))) }) self.refusal = refusal } static func zip() throws -> Data { let tool = try ToolDefinition.decode(Data(contentsOf: root.appendingPathComponent("manifest.json"))) var files: [(String, Data)] = [("manifest.json", try Data(contentsOf: root.appendingPathComponent("manifest.json"))), ("instructions.md", Data(tool.instructions.utf8))] files += try tool.tables.map { ("tables/\($0).json", try Data(contentsOf: root.appendingPathComponent("tables/\($0).json"))) } return FixtureZip.pack(files) } func recordCount() -> Int { rows.values.reduce(0) { $0 + $1.count } } func callRaw(_ method: String, requestJSON: String) async throws -> String { let args = try JSONDecoder().decode([String: RecordValue].self, from: Data(requestJSON.utf8)) var answer: JSONValue switch method { case "tools.import": if let refusal { return try envelope(.object(["code": .string("tool_package_refused"), "message": .string(refusal)]), ok: false) } guard let encoded = args["bytes"]?.text, let bytes = Data(base64Encoded: encoded) else { throw ActionRefused("bytes is not base64") } let files = try FixtureZip.unpack(bytes) let manifest = try ToolDefinition.decode(try XCTFixtureData(files, "manifest.json")) guard manifest == tool else { throw ActionRefused("Fixture manifest mismatch") } for definition in definitions { let table = try TableDefinition.decode(try XCTFixtureData(files, "tables/\(definition.id).json")) guard table == definition else { throw ActionRefused("Fixture definition mismatch") } } installed = true; orphaned = false; imported = bytes withSamples = args["with_samples"]?.bool ?? false answer = .object(["tool_id": .string(tool.id), "signature": .string("unsigned"), "sample_records": .number(withSamples ? 3 : 0)]) case "tools.list": catalogReads += 1 answer = .object([ "tools": .array(installed ? [.object(["definition": try json(tool), "signature": .string("unsigned")])] : []), "table_definitions": .array((installed || orphaned) ? try definitions.map { .object(["definition": try json($0), "orphaned": .bool(orphaned)]) } : []) ]) case CottonMethod.definitionsCatalogue: // The database's tables: the package's, once it is in, each with a plain page. let tables = (installed || orphaned) ? try definitions.map { try JSONSerialization.jsonObject(with: JSONEncoder().encode($0)) as? [String: Any] ?? [:] } : [] answer = try JSONDecoder().decode(JSONValue.self, from: JSONSerialization.data(withJSONObject: CatalogueAnswers.data(tables: tables))) case "tools.export": guard args["tool_id"]?.text == tool.id, installed, let imported else { throw ActionRefused("there is no tool") } answer = .object(["tool_id": .string(tool.id), "bytes": .string(imported.base64EncodedString())]) case "tools.remove": guard args["tool_id"]?.text == tool.id, installed else { throw ActionRefused("there is no tool") } installed = false; orphaned = true answer = .object(["tool_id": .string(tool.id), "orphaned_tables": .array(tool.tables.map(JSONValue.string))]) case "records.list": let table = args["table"]?.text ?? "" answer = .object(["records": .array(try (rows[table] ?? []).map { .object(["id": .string($0.id), "data": try json($0.values)]) }), "next_page": .null]) default: throw ActionRefused("Unknown fixture method: \(method)") } return try envelope(answer) } private func json(_ value: some Encodable) throws -> JSONValue { try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value)) } private func envelope(_ value: JSONValue, ok: Bool = true) throws -> String { String(decoding: try JSONEncoder().encode(JSONValue.object(["ok": .bool(ok), ok ? "data" : "error": value])), as: UTF8.self) } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} } private func XCTFixtureData(_ files: [String: Data], _ name: String) throws -> Data { guard let data = files[name] else { throw ActionRefused("Fixture zip has no " + name) } return data } /// Portable stored ZIP helper for the test bundle; safety validation belongs /// to Rust, while the fixture checks transport, names and CRCs. private enum FixtureZip { static func crc(_ data: Data) -> UInt32 { var result: UInt32 = 0xffffffff for byte in data { result ^= UInt32(byte) for _ in 0..<8 { result = (result >> 1) ^ (result & 1 == 1 ? 0xedb88320 : 0) } } return result ^ 0xffffffff } static func pack(_ files: [(String, Data)]) -> Data { var body = Data(), directory = Data() for (path, data) in files { let name = Data(path.utf8), offset = body.count, checksum = crc(data) body.le(0x04034b50, 4); body.le(20, 2); body.le(0, 2); body.le(0, 2) body.le(0, 2); body.le(0, 2); body.le(Int(checksum), 4) body.le(data.count, 4); body.le(data.count, 4); body.le(name.count, 2); body.le(0, 2) body.append(name); body.append(data) directory.le(0x02014b50, 4); directory.le(20, 2); directory.le(20, 2) directory.le(0, 2); directory.le(0, 2); directory.le(0, 2); directory.le(0, 2) directory.le(Int(checksum), 4); directory.le(data.count, 4); directory.le(data.count, 4) directory.le(name.count, 2); directory.le(0, 2); directory.le(0, 2) directory.le(0, 2); directory.le(0, 2); directory.le(0, 4); directory.le(offset, 4) directory.append(name) } let offset = body.count body.append(directory) body.le(0x06054b50, 4); body.le(0, 2); body.le(0, 2) body.le(files.count, 2); body.le(files.count, 2) body.le(directory.count, 4); body.le(offset, 4); body.le(0, 2) return body } static func unpack(_ data: Data) throws -> [String: Data] { var offset = 0, files: [String: Data] = [:] func number(_ at: Int, _ width: Int) throws -> Int { guard at >= 0, at + width <= data.count else { throw ActionRefused("Truncated fixture zip") } return (0..> (index * 8))) } } }