SPB Git

Repository Public License

ExportAndHistory.swift 7.0 KB 138 lines swift

1import Foundation2import PrismCore3import PrismDataRuntime4import PrismObjectModel56extension ProjectStore {7    public static let exportFormat = "prism.project"8    public static let exportVersion = 1910    /// A single documented JSON file (`.prismproject`): project, blueprint, saved versions and table rows.11    /// It never contains settings, secrets or the audit log.12    public func exportProject(_ projectID: String) throws -> Data {13        let record = try project(projectID)14        guard let current = try loadBlueprint(projectID)?.blueprint else { throw StoreError("This project has no app to export yet.") }15        var versions: [JSONValue] = []16        for s in try snapshots(projectID).prefix(50) {17            guard let bp = try? blueprint(of: s) else { continue }18            versions.append(["label": .string(s.label), "created": .double(s.createdAt.timeIntervalSince1970), "blueprint": bp.json])19        }20        var tables: [String: JSONValue] = [:]21        if FileManager.default.fileExists(atPath: dataURL(projectID).path) {22            let data = try AppDataStore(url: dataURL(projectID), blueprint: current)23            defer { data.close() }24            for t in current.tables { tables[t.id] = .array(try data.run(DataQuery(table: t.id)).map(JSONValue.object)) }25        }26        let doc: JSONValue = [27            "format": .string(Self.exportFormat), "formatVersion": .int(Self.exportVersion),28            "project": ["name": .string(record.name), "prompt": .string(record.prompt), "created": .double(record.createdAt.timeIntervalSince1970)],29            "blueprint": current.json, "versions": .array(versions), "data": .object(tables),30        ]31        return Data(doc.prettyString().utf8)32    }3334    /// Imports an exported project as a new project. Everything in the file is treated as untrusted data.35    @discardableResult36    public func importProject(_ data: Data, validate: (AppBlueprint) -> [ValidationIssue]) throws -> ProjectRecord {37        guard data.count <= 200 * 1024 * 1024 else { throw StoreError("The file is too large to be a PRISM project.") }38        let doc: JSONValue39        do { doc = try JSONValue.parse(data) } catch { throw StoreError("This is not a PRISM project file.") }40        guard doc["format"]?.stringValue == Self.exportFormat else { throw StoreError("This is not a PRISM project file.") }41        guard let version = doc["formatVersion"]?.intValue, version <= Self.exportVersion else {42            throw StoreError("This project file was made by a newer version of PRISM.")43        }44        guard let bpJSON = doc["blueprint"] else { throw StoreError("The project file contains no app.") }45        let blueprint: AppBlueprint46        do { blueprint = try AppBlueprint(json: BlueprintMigrator.standard.migrate(bpJSON)) }47        catch { throw StoreError("The app in this file cannot be read: \(error.localizedDescription)") }48        let errors = validate(blueprint).errors49        guard errors.isEmpty else { throw StoreError("The app in this file is not valid: \(errors[0].message)") }5051        let record = try createProject(name: doc["project"]?["name"]?.stringValue ?? blueprint.name, prompt: doc["project"]?["prompt"]?.stringValue ?? "")52        do {53            for v in (doc["versions"]?.arrayValue ?? []).reversed() {54                guard let json = v["blueprint"], let old = try? AppBlueprint(json: json), old.contentHash != blueprint.contentHash,55                      validate(old).errors.isEmpty else { continue }56                try save(old, for: record.id, label: String((v["label"]?.stringValue ?? "Imported version").prefix(120)))57            }58            try save(blueprint, for: record.id, label: "Imported")59            let store = try AppDataStore(url: dataURL(record.id), blueprint: blueprint)60            defer { store.close() }61            for (table, rows) in doc["data"]?.objectValue ?? [:] where blueprint.object(table)?.isTable == true {62                // Seed rows are replaced by the file's rows; unknown columns are dropped; bad rows fail the import.63                try store.deleteAll(from: table)64                let schema = try store.schema(table)65                let clean = (rows.arrayValue ?? []).compactMap(\.objectValue).map { row in row.filter { schema.column($0.key) != nil } }66                try store.insertAll(into: table, rows: clean)67            }68        } catch {69            try? deleteProject(record.id)70            throw StoreError("The project could not be imported: \(error.localizedDescription)")71        }72        audit(record.id, "project.import", "Imported project", ["objects": .int(blueprint.objects.count)])73        return try project(record.id)74    }7576    /// Copies the whole library (metadata, blueprints, app data) to a folder; returns the folder.77    public func backup(to destination: URL) throws -> URL {78        let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-")79        let target = destination.appendingPathComponent("PRISM-backup-\(stamp)", isDirectory: true)80        try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)81        for p in projects() {82            guard let data = try? exportProject(p.id) else { continue }83            try AtomicFile.write(data, to: target.appendingPathComponent("\(PrismID.slug(p.name))-\(p.id).prismproject"))84        }85        return target86    }87}8889/// In-memory undo/redo over blueprint values. Each edit pushes the previous value; nothing is ever mutated in place.90public struct EditHistory: Sendable {91    public private(set) var current: AppBlueprint92    private var past: [(AppBlueprint, String)] = []93    private var future: [(AppBlueprint, String)] = []94    public var limit = 1009596    public init(_ blueprint: AppBlueprint) { current = blueprint }9798    public var canUndo: Bool { !past.isEmpty }99    public var canRedo: Bool { !future.isEmpty }100    public var undoLabel: String? { past.last?.1 }101    public var redoLabel: String? { future.last?.1 }102103    public mutating func apply(_ next: AppBlueprint, label: String) {104        guard next != current else { return }105        past.append((current, label))106        if past.count > limit { past.removeFirst(past.count - limit) }107        future.removeAll()108        current = next109    }110111    public mutating func apply(_ patches: [BlueprintPatch], label: String) throws {112        apply(try current.applying(patches), label: label)113    }114115    @discardableResult116    public mutating func undo() -> Bool {117        guard let (previous, label) = past.popLast() else { return false }118        future.append((current, label))119        current = previous120        return true121    }122123    @discardableResult124    public mutating func redo() -> Bool {125        guard let (next, label) = future.popLast() else { return false }126        past.append((current, label))127        current = next128        return true129    }130131    /// Replaces the timeline, e.g. after a rollback or an approved agent change.132    public mutating func reset(to blueprint: AppBlueprint) {133        current = blueprint134        past.removeAll()135        future.removeAll()136    }137}138
Files main
Menu

Theme