SPB Git

Repository Public License

ComponentRegistry.swift 4.4 KB 87 lines swift

1import Foundation2import PrismCore3import PrismObjectModel45/// The searchable, typed, versioned catalog. Content hashes are verified at load (spec §7).6public struct ComponentRegistry: Sendable {7    public struct Rejection: Sendable, Equatable {8        public var type: String9        public var reason: String10    }1112    public private(set) var manifests: [String: ComponentManifest] = [:]13    public private(set) var rejections: [Rejection] = []1415    public init() {}1617    /// Loads manifests and checks each against the expected hash from the lock table.18    /// A manifest whose hash is missing or different is rejected, never half-loaded.19    public init(manifests list: [ComponentManifest], lock: [String: String]) {20        for m in list {21            if manifests[m.type] != nil {22                rejections.append(.init(type: m.type, reason: "The type is declared twice."))23            } else if let expected = lock[m.type], expected == m.contentHash {24                manifests[m.type] = m25            } else if lock[m.type] == nil {26                rejections.append(.init(type: m.type, reason: "No content hash is recorded for this component."))27            } else {28                rejections.append(.init(type: m.type, reason: "The content hash does not match the recorded one."))29            }30        }31    }3233    /// Loads one manifest from JSON bytes with a known hash (for components shipped as files).34    public mutating func load(manifestData: Data, expectedHash: String) throws {35        let json: JSONValue36        do { json = try JSONValue.parse(manifestData) } catch { throw ManifestError("The manifest is not valid JSON.") }37        let manifest = try ComponentManifest(json: json)38        guard manifest.contentHash == expectedHash else {39            throw ManifestError("`\(manifest.type)`: the content hash does not match the recorded one.")40        }41        guard manifests[manifest.type] == nil else { throw ManifestError("`\(manifest.type)` is already registered.") }42        _ = try manifest.fixtureBlueprint()43        manifests[manifest.type] = manifest44    }4546    public func manifest(_ type: String) -> ComponentManifest? { manifests[type] }47    public var all: [ComponentManifest] { manifests.values.sorted { ($0.category, $0.type) < ($1.category, $1.type) } }48    public var count: Int { manifests.count }4950    public struct SearchResult: Sendable, Equatable {51        public var manifest: ComponentManifest52        public var score: Int53    }5455    /// Ranked full-text search over type, name, keywords and summary. An empty query lists a category or everything.56    public func search(_ query: String, category: String? = nil, limit: Int = 12) -> [SearchResult] {57        let terms = query.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).map(String.init)58        var results: [SearchResult] = []59        for m in all where category == nil || m.category == category {60            if terms.isEmpty { results.append(.init(manifest: m, score: 1)); continue }61            let typeWords = m.type.lowercased().split(separator: ".").map(String.init)62            let name = m.name.lowercased(), summary = m.summary.lowercased()63            let keywords = m.keywords.map { $0.lowercased() }64            var score = 065            for t in terms {66                let stem = t.count > 4 && t.hasSuffix("s") ? String(t.dropLast()) : t67                if typeWords.contains(where: { $0 == t || $0 == stem }) { score += 10 }68                if name.split(separator: " ").contains(where: { $0 == t || $0 == stem }) { score += 8 }69                else if name.contains(stem) { score += 4 }70                if keywords.contains(where: { $0 == t || $0 == stem }) { score += 6 }71                else if keywords.contains(where: { $0.contains(stem) }) { score += 3 }72                if summary.contains(stem) { score += 2 }73                if m.category == t { score += 3 }74            }75            if score > 0 { results.append(.init(manifest: m, score: score)) }76        }77        return Array(results.sorted { ($1.score, $0.manifest.type) < ($0.score, $1.manifest.type) }.prefix(max(1, limit)))78    }7980    /// Share of the blueprint's component objects whose type is in the catalog (1 when it uses none).81    public func coverage(of blueprint: AppBlueprint) -> Double {82        let components = blueprint.components83        guard !components.isEmpty else { return 1 }84        return Double(components.filter { manifests[$0.type] != nil }.count) / Double(components.count)85    }86}87
Files main
Menu

Theme