SPB Git

Repository Public

Workflow.swift 20.4 KB 370 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocAutomation/Workflow.swift3// Description: The workflow model: a named, ordered list of document operations, its JSON form and its validation.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import DocModel9import DocContainer10import DocAudit11import DocLayout12import DocReferences13import DocTemplates1415/// The audit profile a workflow or the command-line tool runs.16public enum AuditProfile: String, Codable, Sendable, CaseIterable {17    case standard, academic, business, minimal1819    public var options: AuditOptions {20        switch self {21        case .standard: return AuditOptions()22        case .academic: return .academic23        case .business: return .business24        case .minimal: return .minimal25        }26    }27}2829/// Page geometry applied to every section of a document. Absent values are left as they are.30public struct PageSetupOptions: Codable, Sendable, Hashable {31    /// A paper name ("A4", "US Letter") or one of the short forms `a4`, `letter`, `legal`, `a5`, `b5`, `tabloid`, `trade`.32    public var paper: String?33    /// `portrait` or `landscape`.34    public var orientation: String?35    /// The four margins at once, in points.36    public var margins: Double?37    public var marginTop: Double?38    public var marginBottom: Double?39    public var marginLeft: Double?40    public var marginRight: Double?4142    public init(paper: String? = nil, orientation: String? = nil, margins: Double? = nil, marginTop: Double? = nil, marginBottom: Double? = nil,43                marginLeft: Double? = nil, marginRight: Double? = nil) {44        self.paper = paper; self.orientation = orientation; self.margins = margins45        self.marginTop = marginTop; self.marginBottom = marginBottom; self.marginLeft = marginLeft; self.marginRight = marginRight46    }4748    /// Resolves a paper name or short form.49    public static func paperSize(named name: String) -> PaperSize? {50        let key = name.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")51        switch key {52        case "a4": return .a453        case "a5": return .a554        case "b5": return .b555        case "letter", "usletter": return .letter56        case "legal", "uslegal": return .legal57        case "tabloid": return .tabloid58        case "trade", "trade6x9", "6x9": return .trade6x959        default: return PaperSize.all.first { $0.name.lowercased().replacingOccurrences(of: " ", with: "") == key }60        }61    }62}6364/// Document properties set by a workflow. Absent values are left as they are.65public struct MetadataOptions: Codable, Sendable, Hashable {66    public var title: String?67    public var author: String?68    public var subject: String?69    public var keywords: [String]?70    public var language: String?71    public init(title: String? = nil, author: String? = nil, subject: String? = nil, keywords: [String]? = nil, language: String? = nil) {72        self.title = title; self.author = author; self.subject = subject; self.keywords = keywords; self.language = language73    }74}7576/// PDF publishing options in their serialisable form.77public struct PDFExportOptions: Codable, Sendable, Hashable {78    public var outline: Bool?79    public var tagged: Bool?80    public var cropMarks: Bool?81    public var bleed: Double?82    /// 1-based, inclusive.83    public var firstPage: Int?84    public var lastPage: Int?85    public init(outline: Bool? = nil, tagged: Bool? = nil, cropMarks: Bool? = nil, bleed: Double? = nil, firstPage: Int? = nil, lastPage: Int? = nil) {86        self.outline = outline; self.tagged = tagged; self.cropMarks = cropMarks; self.bleed = bleed; self.firstPage = firstPage; self.lastPage = lastPage87    }8889    public var pdfOptions: PDFOptions {90        var o = PDFOptions()91        if let outline { o.includeOutline = outline }92        if let tagged { o.tagged = tagged }93        if let cropMarks { o.cropMarks = cropMarks }94        if let bleed { o.bleed = CGFloat(max(0, bleed)) }95        if let first = firstPage ?? (lastPage == nil ? nil : 1) {96            let last = max(first, lastPage ?? Int.max / 2)97            o.pageRange = max(1, first)...last98        }99        return o100    }101}102103/// One operation of a workflow. Every case is a document operation of the engine: there is no step that runs a script,104/// a shell command or anything outside this package.105public enum WorkflowStep: Sendable, Hashable {106    /// Reads the document. `path == nil` takes the input given to the run (a file of a batch, or the document passed in).107    case importDocument(path: String?)108    case applyTheme(name: String)109    /// Replaces the style sheet by the one of a template; paragraphs keep their style id.110    case applyTemplateStyles(templateID: String)111    case setPageSetup(PageSetupOptions)112    case acceptAllChanges113    case rejectAllChanges114    case removeComments115    /// Inserts a table of contents at the start when the document has none; an existing one gets `maxLevel` and `title`.116    case tableOfContents(title: String?, maxLevel: Int)117    /// Appends the bibliography when the document cites sources and has no bibliography block.118    case insertBibliography(title: String?)119    case setCitationStyle(id: String)120    case recalculateTables121    case setMetadata(MetadataOptions)122    /// Collects findings. With `failOnErrors` the workflow stops when a finding has severity `error`.123    case audit(profile: AuditProfile, failOnErrors: Bool)124    /// Writes the document into the output folder. `fileName` may use `{name}` (input name without extension).125    case export(format: DocFormat, fileName: String?, pdf: PDFExportOptions?)126    /// Writes the findings of the last audit step next to the output (`json`, `md` … any export format).127    case writeAuditReport(format: String, fileName: String?)128129    /// The identifier used in JSON (`"type"`).130    public var type: String {131        switch self {132        case .importDocument: return "import"133        case .applyTheme: return "applyTheme"134        case .applyTemplateStyles: return "applyTemplateStyles"135        case .setPageSetup: return "setPageSetup"136        case .acceptAllChanges: return "acceptAllChanges"137        case .rejectAllChanges: return "rejectAllChanges"138        case .removeComments: return "removeComments"139        case .tableOfContents: return "tableOfContents"140        case .insertBibliography: return "insertBibliography"141        case .setCitationStyle: return "setCitationStyle"142        case .recalculateTables: return "recalculateTables"143        case .setMetadata: return "setMetadata"144        case .audit: return "audit"145        case .export: return "export"146        case .writeAuditReport: return "writeAuditReport"147        }148    }149150    public static let allTypes = ["import", "applyTheme", "applyTemplateStyles", "setPageSetup", "acceptAllChanges", "rejectAllChanges", "removeComments",151                                  "tableOfContents", "insertBibliography", "setCitationStyle", "recalculateTables", "setMetadata", "audit", "export",152                                  "writeAuditReport"]153154    /// A plain-language description (English; the application localises its own).155    public var summary: String {156        switch self {157        case .importDocument(let path): return path.map { "Open “\(($0 as NSString).lastPathComponent)”" } ?? "Open the input document"158        case .applyTheme(let name): return "Apply the “\(name)” theme"159        case .applyTemplateStyles(let id): return "Apply the styles of the “\(TemplateLibrary.template(id: id)?.name("en") ?? id)” template"160        case .setPageSetup(let o):161            var parts: [String] = []162            if let p = o.paper { parts.append(PageSetupOptions.paperSize(named: p)?.name ?? p) }163            if let d = o.orientation { parts.append(d) }164            if o.margins != nil || o.marginTop != nil || o.marginBottom != nil || o.marginLeft != nil || o.marginRight != nil { parts.append("margins") }165            return "Set the page setup" + (parts.isEmpty ? "" : " (\(parts.joined(separator: ", ")))")166        case .acceptAllChanges: return "Accept all tracked changes"167        case .rejectAllChanges: return "Reject all tracked changes"168        case .removeComments: return "Remove all comments"169        case .tableOfContents(_, let level): return "Insert or refresh the table of contents (levels 1–\(level))"170        case .insertBibliography: return "Insert the bibliography when sources are cited"171        case .setCitationStyle(let id): return "Use the “\(CitationEngine.styles.first { $0.id == id }?.name ?? id)” citation style"172        case .recalculateTables: return "Recalculate table formulas"173        case .setMetadata: return "Set document properties"174        case .audit(let profile, let fail): return "Audit the document (\(profile.rawValue) profile)" + (fail ? "; stop on errors" : "")175        case .export(let format, _, _): return "Export as \(format.displayName)"176        case .writeAuditReport(let format, _): return "Write the audit report (\(format.uppercased()))"177        }178    }179}180181extension WorkflowStep: Codable {182    private enum Key: String, CodingKey {183        case type, path, theme, template, paper, orientation, margins, marginTop, marginBottom, marginLeft, marginRight184        case title, maxLevel, style, author, subject, keywords, language, profile, failOnErrors, format, fileName, pdf185    }186187    public init(from decoder: Decoder) throws {188        let c = try decoder.container(keyedBy: Key.self)189        let type = try c.decode(String.self, forKey: .type)190        switch type {191        case "import": self = .importDocument(path: try c.decodeIfPresent(String.self, forKey: .path))192        case "applyTheme": self = .applyTheme(name: try c.decode(String.self, forKey: .theme))193        case "applyTemplateStyles": self = .applyTemplateStyles(templateID: try c.decode(String.self, forKey: .template))194        case "setPageSetup": self = .setPageSetup(try PageSetupOptions(from: decoder))195        case "acceptAllChanges": self = .acceptAllChanges196        case "rejectAllChanges": self = .rejectAllChanges197        case "removeComments": self = .removeComments198        case "tableOfContents":199            self = .tableOfContents(title: try c.decodeIfPresent(String.self, forKey: .title), maxLevel: try c.decodeIfPresent(Int.self, forKey: .maxLevel) ?? 3)200        case "insertBibliography": self = .insertBibliography(title: try c.decodeIfPresent(String.self, forKey: .title))201        case "setCitationStyle": self = .setCitationStyle(id: try c.decode(String.self, forKey: .style))202        case "recalculateTables": self = .recalculateTables203        case "setMetadata": self = .setMetadata(try MetadataOptions(from: decoder))204        case "audit":205            let name = try c.decodeIfPresent(String.self, forKey: .profile) ?? AuditProfile.standard.rawValue206            guard let profile = AuditProfile(rawValue: name) else {207                throw DecodingError.dataCorruptedError(forKey: .profile, in: c, debugDescription: "Unknown audit profile “\(name)”.")208            }209            self = .audit(profile: profile, failOnErrors: try c.decodeIfPresent(Bool.self, forKey: .failOnErrors) ?? false)210        case "export":211            let name = try c.decode(String.self, forKey: .format)212            guard let format = DocFormat(rawValue: name) ?? DocFormat(fileExtension: name), DocumentConverter.exportFormats.contains(format) else {213                throw DecodingError.dataCorruptedError(forKey: .format, in: c, debugDescription: "Unknown export format “\(name)”.")214            }215            self = .export(format: format, fileName: try c.decodeIfPresent(String.self, forKey: .fileName), pdf: try c.decodeIfPresent(PDFExportOptions.self, forKey: .pdf))216        case "writeAuditReport":217            self = .writeAuditReport(format: try c.decodeIfPresent(String.self, forKey: .format) ?? "md", fileName: try c.decodeIfPresent(String.self, forKey: .fileName))218        default:219            throw WorkflowValidationError.unknownStep(type)220        }221    }222223    public func encode(to encoder: Encoder) throws {224        var c = encoder.container(keyedBy: Key.self)225        try c.encode(type, forKey: .type)226        switch self {227        case .importDocument(let path): try c.encodeIfPresent(path, forKey: .path)228        case .applyTheme(let name): try c.encode(name, forKey: .theme)229        case .applyTemplateStyles(let id): try c.encode(id, forKey: .template)230        case .setPageSetup(let o): try o.encode(to: encoder)231        case .acceptAllChanges, .rejectAllChanges, .removeComments, .recalculateTables: break232        case .tableOfContents(let title, let level): try c.encodeIfPresent(title, forKey: .title); try c.encode(level, forKey: .maxLevel)233        case .insertBibliography(let title): try c.encodeIfPresent(title, forKey: .title)234        case .setCitationStyle(let id): try c.encode(id, forKey: .style)235        case .setMetadata(let o): try o.encode(to: encoder)236        case .audit(let profile, let fail): try c.encode(profile.rawValue, forKey: .profile); try c.encode(fail, forKey: .failOnErrors)237        case .export(let format, let name, let pdf):238            try c.encode(format.rawValue, forKey: .format); try c.encodeIfPresent(name, forKey: .fileName); try c.encodeIfPresent(pdf, forKey: .pdf)239        case .writeAuditReport(let format, let name): try c.encode(format, forKey: .format); try c.encodeIfPresent(name, forKey: .fileName)240        }241    }242}243244/// Why a workflow definition is refused before anything runs.245public enum WorkflowValidationError: Error, Equatable, CustomStringConvertible, Sendable {246    case unknownStep(String)247    case malformed(String)248    case empty249    /// A step would write outside the output folder.250    case pathEscapesOutputFolder(step: Int, path: String)251    case invalidValue(step: Int, detail: String)252253    public var description: String {254        switch self {255        case .unknownStep(let type): return "Unknown step type “\(type)”. Supported: \(WorkflowStep.allTypes.joined(separator: ", "))."256        case .malformed(let why): return "The workflow file is not valid: \(why)"257        case .empty: return "The workflow has no steps."258        case .pathEscapesOutputFolder(let step, let path): return "Step \(step + 1) would write “\(path)” outside the output folder."259        case .invalidValue(let step, let detail): return "Step \(step + 1): \(detail)"260        }261    }262}263264public struct Workflow: Codable, Sendable, Hashable, Identifiable {265    public var id: String266    public var name: String267    public var summary: String268    public var steps: [WorkflowStep]269270    public init(id: String = DocID.make(), name: String, summary: String = "", steps: [WorkflowStep]) {271        self.id = id; self.name = name; self.summary = summary; self.steps = steps272    }273274    private enum Key: String, CodingKey { case id, name, summary, steps }275276    public init(from decoder: Decoder) throws {277        let c = try decoder.container(keyedBy: Key.self)278        name = try c.decode(String.self, forKey: .name)279        id = try c.decodeIfPresent(String.self, forKey: .id) ?? Workflow.slug(name)280        summary = try c.decodeIfPresent(String.self, forKey: .summary) ?? ""281        steps = try c.decode([WorkflowStep].self, forKey: .steps)282    }283284    static func slug(_ name: String) -> String {285        let s = name.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" }286        return String(s).split(separator: "-").joined(separator: "-")287    }288289    /// Decodes and validates a workflow written as JSON. Unknown step types, unknown values and paths that leave the290    /// output folder are refused here, before any file is touched.291    public static func load(json data: Data) throws -> Workflow {292        guard data.count <= 1_048_576 else { throw WorkflowValidationError.malformed("the file is larger than 1 MB.") }293        let workflow: Workflow294        do { workflow = try JSONDecoder().decode(Workflow.self, from: data) }295        catch let e as WorkflowValidationError { throw e }296        catch let e as DecodingError {297            // A validation error thrown while decoding a step arrives wrapped.298            if case .dataCorrupted(let ctx) = e, let inner = ctx.underlyingError as? WorkflowValidationError { throw inner }299            throw WorkflowValidationError.malformed(Workflow.explain(e))300        } catch { throw WorkflowValidationError.malformed("\(error)") }301        try workflow.validate()302        return workflow303    }304305    public static func load(contentsOf url: URL) throws -> Workflow { try load(json: try Data(contentsOf: url)) }306307    public func jsonData() throws -> Data {308        let e = JSONEncoder()309        e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]310        return try e.encode(self)311    }312313    private static func explain(_ e: DecodingError) -> String {314        func path(_ c: DecodingError.Context) -> String { c.codingPath.map { $0.intValue.map { "[\($0)]" } ?? $0.stringValue }.joined(separator: ".") }315        switch e {316        case .keyNotFound(let k, let c): return "“\(k.stringValue)” is missing at \(path(c).isEmpty ? "the top level" : path(c))."317        case .typeMismatch(_, let c), .valueNotFound(_, let c): return "wrong kind of value at \(path(c)): \(c.debugDescription)"318        case .dataCorrupted(let c): return c.debugDescription + (path(c).isEmpty ? "" : " (\(path(c)))")319        @unknown default: return "\(e)"320        }321    }322323    /// Checks every step: known themes, templates, papers and styles, and output names that stay inside the output folder.324    public func validate() throws {325        guard !steps.isEmpty else { throw WorkflowValidationError.empty }326        for (i, step) in steps.enumerated() {327            switch step {328            case .applyTheme(let name):329                guard Theme.named(name) != nil else {330                    throw WorkflowValidationError.invalidValue(step: i, detail: "unknown theme “\(name)”. Themes: \(Theme.all.map(\.name).joined(separator: ", ")).")331                }332            case .applyTemplateStyles(let id):333                guard TemplateLibrary.template(id: id) != nil else {334                    throw WorkflowValidationError.invalidValue(step: i, detail: "unknown template “\(id)”. Templates: \(TemplateLibrary.all.map(\.id).joined(separator: ", ")).")335                }336            case .setPageSetup(let o):337                if let p = o.paper, PageSetupOptions.paperSize(named: p) == nil { throw WorkflowValidationError.invalidValue(step: i, detail: "unknown paper “\(p)”.") }338                if let d = o.orientation, !["portrait", "landscape"].contains(d.lowercased()) {339                    throw WorkflowValidationError.invalidValue(step: i, detail: "orientation must be “portrait” or “landscape”.")340                }341                for m in [o.margins, o.marginTop, o.marginBottom, o.marginLeft, o.marginRight].compactMap({ $0 }) where !(0...1000).contains(m) {342                    throw WorkflowValidationError.invalidValue(step: i, detail: "margins are given in points, between 0 and 1000.")343                }344            case .tableOfContents(_, let level):345                guard (1...9).contains(level) else { throw WorkflowValidationError.invalidValue(step: i, detail: "maxLevel must be between 1 and 9.") }346            case .setCitationStyle(let id):347                guard CitationEngine.styles.contains(where: { $0.id == id }) else {348                    throw WorkflowValidationError.invalidValue(step: i, detail: "unknown citation style “\(id)”. Styles: \(CitationEngine.styles.map(\.id).joined(separator: ", ")).")349                }350            case .export(_, let name, _):351                if let name { try Workflow.checkRelative(name, step: i) }352            case .writeAuditReport(let format, let name):353                guard format == "json" || DocFormat(rawValue: format) != nil || DocFormat(fileExtension: format) != nil else {354                    throw WorkflowValidationError.invalidValue(step: i, detail: "unknown report format “\(format)”.")355                }356                if let name { try Workflow.checkRelative(name, step: i) }357            default: break358            }359        }360    }361362    /// Output names are relative to the output folder and may not climb out of it.363    static func checkRelative(_ name: String, step: Int) throws {364        let components = name.split(separator: "/", omittingEmptySubsequences: false).map(String.init)365        let bad = name.isEmpty || name.hasPrefix("/") || name.hasPrefix("~") || name.contains("\0") || name.contains("\\")366            || components.contains("..") || components.contains(".") || components.contains("")367        if bad { throw WorkflowValidationError.pathEscapesOutputFolder(step: step, path: name) }368    }369}370
Files main
Menu

Theme