Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassRegistry/RegistryBuilder.swift8// Module : SPGlassRegistry9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// One item to publish: its metadata and the bytes of its files, already prepared for source mode.44public struct RegistryItemSource: Sendable {45 public var id: String46 public var name: String47 public var kind: String48 public var category: String?49 public var description: String50 public var dependencies: [String]51 public var frameworks: [String]52 public var files: [(path: String, data: Data)]53 public var symbols: [String]54 public var examples: [ManifestExample]55 public var accessibility: [String]56 public var changes: [String]5758 public init(id: String, name: String, kind: String, category: String?, description: String, dependencies: [String], frameworks: [String], files: [(path: String, data: Data)], symbols: [String], examples: [ManifestExample], accessibility: [String], changes: [String]) {59 self.id = id; self.name = name; self.kind = kind; self.category = category; self.description = description60 self.dependencies = dependencies; self.frameworks = frameworks; self.files = files; self.symbols = symbols61 self.examples = examples; self.accessibility = accessibility; self.changes = changes62 }63}6465public struct RegistryThemeSource: Sendable {66 public var id: String67 public var name: String68 public var summary: String69 public var data: Data70 public init(id: String, name: String, summary: String, data: Data) {71 self.id = id; self.name = name; self.summary = summary; self.data = data72 }73}7475public struct RegistryBuildReport: Equatable, Sendable {76 public var written: [String] = []77 public var unchanged: [String] = []78}7980/// Writes a registry tree: one immutable directory per item version, theme files, the index and its signature.81public struct RegistryBuilder {82 public var root: URL83 public var name: String84 public var homepage: String85 public var license: String86 public var version: String87 public var date: String88 public var platforms: [String]89 public var minimumOS: [String: String]90 /// Lets a version directory be rewritten. Only for a version that has never been published.91 public var allowOverwrite: Bool9293 public init(root: URL, name: String, homepage: String, license: String, version: String, date: String, platforms: [String], minimumOS: [String: String], allowOverwrite: Bool = false) {94 self.root = root; self.name = name; self.homepage = homepage; self.license = license95 self.version = version; self.date = date; self.platforms = platforms; self.minimumOS = minimumOS96 self.allowOverwrite = allowOverwrite97 }9899 public func build(items: [RegistryItemSource], themes: [RegistryThemeSource], signingKey: String? = nil) throws -> RegistryBuildReport {100 _ = try SemanticVersion(version)101 var report = RegistryBuildReport()102 let fileManager = FileManager.default103 let known = Set(items.map(\.id))104 guard known.count == items.count else { throw RegistryError.malformed(what: "The item list", detail: "an identifier is used twice.") }105106 // A file belongs to exactly one item.107 var owners: [String: String] = [:]108 for item in items {109 for file in item.files {110 let key = RegistryPath.collisionKey(file.path)111 if let other = owners[key], other != item.id { throw RegistryError.pathCollision("\(other): \(file.path)", "\(item.id): \(file.path)") }112 owners[key] = item.id113 }114 }115 _ = try DependencyGraph.installationOrder(roots: items.map(\.id)) { id throws(RegistryError) -> [String] in116 guard let item = items.first(where: { $0.id == id }) else { throw .unknownItem(id) }117 return item.dependencies118 }119120 var previous: RegistryIndex?121 let indexURL = root.appendingPathComponent(RegistrySchema.indexFileName)122 if let data = try? Data(contentsOf: indexURL) {123 previous = try RegistryJSON.decode(RegistryIndex.self, from: data, what: "The existing index")124 }125126 var entries: [RegistryIndexEntry] = []127 for item in items.sorted(by: { $0.id < $1.id }) {128 let files = item.files.map { ManifestFile(path: $0.path, sha256: RegistryHash.sha256($0.data), bytes: $0.data.count) }.sorted { $0.path < $1.path }129 let manifest = ComponentManifest(130 id: item.id, name: item.name, version: version, description: item.description, kind: item.kind,131 category: item.category, platforms: platforms, minimumOS: minimumOS,132 dependencies: item.dependencies.sorted().map { ManifestDependency(id: $0, version: version) },133 frameworks: item.frameworks, files: files, license: license, symbols: item.symbols,134 examples: item.examples, accessibility: item.accessibility,135 changelog: mergedChangelog(for: item, previous: previous)136 )137 try RegistryValidator.validate(manifest)138 let manifestData = try RegistryJSON.encode(manifest)139 let directory = root.appendingPathComponent(manifest.directory)140 let manifestURL = root.appendingPathComponent(manifest.manifestPath)141142 if let existing = try? Data(contentsOf: manifestURL) {143 // A published version is intact only if its manifest and every one of its files are unchanged.144 let filesIntact = item.files.allSatisfy { file in145 (try? Data(contentsOf: directory.appendingPathComponent("files").appendingPathComponent(file.path))) == file.data146 }147 if existing == manifestData, filesIntact {148 report.unchanged.append(item.id)149 } else if allowOverwrite {150 try fileManager.removeItem(at: directory)151 } else {152 throw RegistryError.immutableVersion(id: item.id, version: version)153 }154 }155 if !fileManager.fileExists(atPath: manifestURL.path) {156 for file in item.files {157 let url = directory.appendingPathComponent("files").appendingPathComponent(file.path)158 try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)159 try file.data.write(to: url, options: .atomic)160 }161 try manifestData.write(to: manifestURL, options: .atomic)162 report.written.append(item.id)163 }164 entries.append(entry(165 id: item.id, name: item.name, kind: item.kind, category: item.category, summary: item.description,166 version: RegistryIndexVersion(version: version, path: manifest.manifestPath, sha256: RegistryHash.sha256(manifestData)),167 previous: previous?.item(item.id)168 ))169 }170171 var themeEntries: [RegistryIndexEntry] = []172 for theme in themes.sorted(by: { $0.id < $1.id }) {173 try RegistryPath.validateIdentifier(theme.id)174 let path = "themes/\(theme.id)/\(version)/theme.json"175 let url = root.appendingPathComponent(path)176 if let existing = try? Data(contentsOf: url), existing != theme.data, !allowOverwrite {177 throw RegistryError.immutableVersion(id: theme.id, version: version)178 }179 try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)180 try theme.data.write(to: url, options: .atomic)181 themeEntries.append(entry(182 id: theme.id, name: theme.name, kind: "theme", category: nil, summary: theme.summary,183 version: RegistryIndexVersion(version: version, path: path, sha256: RegistryHash.sha256(theme.data)),184 previous: previous?.theme(theme.id)185 ))186 }187188 // Items and themes published earlier and absent from this build stay listed.189 for old in previous?.items ?? [] where !entries.contains(where: { $0.id == old.id }) { entries.append(old) }190 for old in previous?.themes ?? [] where !themeEntries.contains(where: { $0.id == old.id }) { themeEntries.append(old) }191192 let index = RegistryIndex(name: name, homepage: homepage, license: license, items: entries.sorted { $0.id < $1.id }, themes: themeEntries.sorted { $0.id < $1.id })193 try RegistryValidator.validate(index)194 let indexData = try RegistryJSON.encode(index)195 try fileManager.createDirectory(at: root, withIntermediateDirectories: true)196 try indexData.write(to: indexURL, options: .atomic)197198 let signatureURL = root.appendingPathComponent(RegistrySchema.signatureFileName)199 if let signingKey {200 let signature = try RegistrySignature.sign(indexData, privateKey: signingKey)201 try Data((signature + "\n").utf8).write(to: signatureURL, options: .atomic)202 } else if fileManager.fileExists(atPath: signatureURL.path) {203 // An index rewritten without a key must not keep a signature that no longer matches it.204 let stale = (try? String(contentsOf: signatureURL, encoding: .utf8)) ?? ""205 if previous == nil || (try? RegistryJSON.encode(previous)) != indexData || stale.isEmpty {206 try fileManager.removeItem(at: signatureURL)207 }208 }209 return report210 }211212 private func entry(id: String, name: String, kind: String, category: String?, summary: String, version new: RegistryIndexVersion, previous: RegistryIndexEntry?) -> RegistryIndexEntry {213 var versions = (previous?.versions ?? []).filter { $0.version != new.version }214 versions.append(new)215 versions.sort { (try? SemanticVersion($0.version)) ?? SemanticVersion(major: 0, minor: 0, patch: 0) < ((try? SemanticVersion($1.version)) ?? SemanticVersion(major: 0, minor: 0, patch: 0)) }216 return RegistryIndexEntry(id: id, name: name, kind: kind, category: category, summary: summary, latest: versions.last?.version ?? new.version, versions: versions)217 }218219 private func mergedChangelog(for item: RegistryItemSource, previous: RegistryIndex?) -> [ManifestChange] {220 var changelog: [ManifestChange] = [ManifestChange(version: version, date: date, changes: item.changes)]221 // The newest published version other than the one being built: building the same version twice222 // must give the same manifest, history included.223 if let path = previous?.item(item.id)?.versions.last(where: { $0.version != version })?.path,224 let data = try? Data(contentsOf: root.appendingPathComponent(path)),225 let old = try? RegistryJSON.decode(ComponentManifest.self, from: data, what: "The previous manifest") {226 changelog.append(contentsOf: old.changelog.filter { $0.version != version })227 }228 return changelog229 }230}231