Repository Public License
1import Foundation2import PrismCore34/// The object graph for one app: the single artifact the renderer displays, the agent edits,5/// the version system diffs and the publisher packages.6public struct AppBlueprint: Sendable, Hashable, Identifiable {7 public static let currentSchemaVersion = 189 public var schemaVersion: Int10 public var id: String11 public var name: String12 public var summary: String13 public var version: Int14 public var entrypoint: String15 public var permissions: [String]16 public var theme: [String: JSONValue]17 /// Initial app-scope state.18 public var state: [String: JSONValue]19 /// The app icon designed for this app (an `IconSpec`); nil means PRISM draws one from the name.20 public var icon: JSONValue?21 public var objects: [PrismObject]2223 public init(id: String, name: String, entrypoint: String = "", objects: [PrismObject] = []) {24 self.schemaVersion = Self.currentSchemaVersion25 self.id = id; self.name = name; self.summary = ""; self.version = 1; self.entrypoint = entrypoint26 self.permissions = []; self.theme = [:]; self.state = [:]; self.objects = objects27 }2829 public static let fieldNames = [30 "schemaVersion", "id", "name", "summary", "version", "entrypoint", "permissions", "theme", "state", "icon", "objects",31 ]3233 public init(json: JSONValue) throws {34 guard let o = json.objectValue else { throw BlueprintError.malformed("The blueprint must be a JSON object.") }35 guard let v = o["schemaVersion"]?.intValue else { throw BlueprintError.malformed("`schemaVersion` is missing.") }36 guard v == Self.currentSchemaVersion else {37 throw BlueprintError.unsupportedVersion(found: v, supported: Self.currentSchemaVersion)38 }39 guard let id = o["id"]?.stringValue, let name = o["name"]?.stringValue else {40 throw BlueprintError.malformed("The blueprint needs a string `id` and `name`.")41 }42 if let unknown = o.keys.first(where: { !Self.fieldNames.contains($0) }) {43 throw BlueprintError.malformed("Unknown blueprint field `\(unknown)`.")44 }45 guard let objects = o["objects"]?.arrayValue else { throw BlueprintError.malformed("`objects` must be an array.") }46 self.schemaVersion = v47 self.id = id48 self.name = name49 self.summary = o["summary"]?.stringValue ?? ""50 self.version = o["version"]?.intValue ?? 151 self.entrypoint = o["entrypoint"]?.stringValue ?? ""52 self.permissions = (o["permissions"]?.arrayValue ?? []).compactMap(\.stringValue)53 self.theme = o["theme"]?.objectValue ?? [:]54 self.state = o["state"]?.objectValue ?? [:]55 self.icon = o["icon"].flatMap { $0 == .null ? nil : $0 }56 self.objects = try objects.map(PrismObject.init(json:))57 }5859 public var json: JSONValue {60 var o: [String: JSONValue] = [61 "schemaVersion": .int(schemaVersion), "id": .string(id), "name": .string(name), "version": .int(version),62 "entrypoint": .string(entrypoint), "permissions": .array(permissions.map(JSONValue.string)),63 "objects": .array(objects.map(\.json)),64 ]65 if !summary.isEmpty { o["summary"] = .string(summary) }66 if !theme.isEmpty { o["theme"] = .object(theme) }67 if !state.isEmpty { o["state"] = .object(state) }68 if let icon { o["icon"] = icon }69 return .object(o)70 }7172 /// Parse, migrate to the current format, decode.73 public static func load(_ data: Data, migrator: BlueprintMigrator = .standard) throws -> AppBlueprint {74 try AppBlueprint(json: migrator.migrate(JSONValue.parse(data)))75 }7677 public func canonicalData() -> Data { json.canonicalData() }78 public func prettyData() -> Data { Data(json.prettyString().utf8) }79 public var contentHash: String { ContentHash.sha256(json) }8081 // MARK: Lookup8283 public func object(_ id: String) -> PrismObject? { objects.first { $0.id == id } }84 public func index(of id: String) -> Int? { objects.firstIndex { $0.id == id } }85 public var pages: [PrismObject] { objects.filter(\.isPage) }86 public var tables: [PrismObject] { objects.filter(\.isTable) }87 public var queries: [PrismObject] { objects.filter(\.isQuery) }88 public var components: [PrismObject] { objects.filter(\.isComponent) }89 public var scripts: [PrismObject] { objects.filter(\.isScript) }90 public var componentDefinitions: [PrismObject] { objects.filter(\.isComponentDefinition) }9192 public func children(of id: String) -> [PrismObject] {93 (object(id)?.children ?? []).compactMap(object)94 }9596 public func parent(of id: String) -> PrismObject? { objects.first { $0.children.contains(id) } }9798 /// The object and everything below it, depth first. Safe on cyclic graphs.99 public func subtree(_ id: String) -> [PrismObject] {100 var seen = Set<String>(), out: [PrismObject] = []101 func walk(_ id: String) {102 guard seen.insert(id).inserted, let o = object(id) else { return }103 out.append(o)104 o.children.forEach(walk)105 }106 walk(id)107 return out108 }109110 /// Distinct catalog component types used, sorted.111 public var componentTypes: [String] { Array(Set(components.map(\.type))).sorted() }112113 public func uniqueID(_ base: String) -> String {114 let root = PrismID.slug(base, fallback: "obj")115 let existing = Set(objects.map(\.id))116 if !existing.contains(root) { return root }117 var n = 2118 while existing.contains("\(root)_\(n)") { n += 1 }119 return "\(root)_\(n)"120 }121}122123/// Versioned migrations from older blueprint formats (ADR 0002).124public struct BlueprintMigrator: Sendable {125 public typealias Step = @Sendable (JSONValue) throws -> JSONValue126 /// `steps[n]` upgrades a version-`n` document to version `n + 1`.127 public var steps: [Int: Step]128 public var target: Int129130 public init(steps: [Int: Step], target: Int = AppBlueprint.currentSchemaVersion) {131 self.steps = steps; self.target = target132 }133134 /// Version 1 is the first released format, so there is nothing to migrate from yet.135 public static let standard = BlueprintMigrator(steps: [:])136137 public func migrate(_ document: JSONValue) throws -> JSONValue {138 guard var version = document["schemaVersion"]?.intValue else {139 throw BlueprintError.malformed("`schemaVersion` is missing.")140 }141 guard version <= target else { throw BlueprintError.unsupportedVersion(found: version, supported: target) }142 var doc = document143 while version < target {144 guard let step = steps[version] else {145 throw BlueprintError.malformed("No migration from blueprint format \(version) to \(version + 1).")146 }147 doc = try step(doc)148 version += 1149 guard var o = doc.objectValue else { throw BlueprintError.malformed("A migration produced a non-object.") }150 o["schemaVersion"] = .int(version)151 doc = .object(o)152 }153 return doc154 }155}156