Repository Public License
1import Foundation2import PrismCore3import PrismDataRuntime4import PrismIconKit5import PrismLogicRuntime6import PrismObjectModel7import PrismScriptRuntime89/// The one validation function shared by the agent, the editor and the publisher (ADR 0002).10public enum BlueprintValidator {11 public static func validate(_ bp: AppBlueprint, registry: ComponentRegistry) -> [ValidationIssue] {12 var issues = StructuralValidator.validate(bp)13 func err(_ code: String, _ id: String?, _ m: String) { issues.append(.init(.error, code, id, m)) }14 func warn(_ code: String, _ id: String?, _ m: String) { issues.append(.init(.warning, code, id, m)) }1516 // Permissions: default-deny.17 for p in bp.permissions {18 if Permission.unavailable.contains(p) { err("permission.unavailable", nil, "Permission `\(p)` is not available in this version of PRISM.") }19 else if Permission.grantable[p] == nil { err("permission.unknown", nil, "`\(p)` is not a known permission.") }20 }2122 // Look: theme tokens and the designed icon.23 for p in ThemeSpec.problems(bp.theme) { p.isError ? err("theme.invalid", nil, p.message) : warn("theme.contrast", nil, p.message) }24 if let icon = bp.icon { for p in IconSpec.problems(icon).prefix(6) { err("icon.invalid", nil, "App icon: \(p)") } }2526 // Data tables.27 var schemas: [String: TableSchema] = [:]28 for t in bp.tables {29 do { schemas[t.id] = try TableSchema(object: t) } catch { err("table.schema", t.id, error.localizedDescription) }30 }31 if !schemas.isEmpty && !bp.permissions.contains(Permission.storageLocal) {32 err("permission.missing", nil, "The app stores data but does not declare `\(Permission.storageLocal)`.")33 }3435 // Scripts and on-demand components (ADR 0009).36 for sc in bp.scripts {37 if let problem = ScriptEngine.syntaxError(sc.props["source"]?.stringValue ?? "") { err("script.syntax", sc.id, "Script `\(sc.id)`: \(problem)") }38 }39 for d in bp.componentDefinitions {40 do { _ = try CustomComponent.manifest(d) } catch { err("component.definition", d.id, error.localizedDescription) }41 guard let source = d.props["source"]?.stringValue, !source.isEmpty else { err("component.definition", d.id, "Component `\(d.id)` has no `source`."); continue }42 if let problem = ScriptEngine.syntaxError(source, asFunctionBody: true) { err("script.syntax", d.id, "Component `\(d.id)`: \(problem)") }43 if let t = d.props["tick"], t.doubleValue.map({ $0 >= 0.03 && $0 <= 3600 }) != true { err("component.definition", d.id, "Component `\(d.id)`: `tick` must be between 0.03 and 3600 seconds.") }44 }45 if bp.componentDefinitions.count > CustomComponent.maxDefinitions { err("component.definition", nil, "At most \(CustomComponent.maxDefinitions) on-demand components per app.") }46 if !(bp.scripts.isEmpty && bp.componentDefinitions.isEmpty) && !bp.permissions.contains(Permission.scripts) {47 err("permission.missing", nil, "The app carries custom logic but does not declare `\(Permission.scripts)`.")48 }4950 let context = Context(bp: bp, schemas: schemas, queryIDs: Set(bp.queries.map(\.id)))5152 // Named queries.53 for q in bp.queries {54 guard let json = q.props["query"] else { err("query.missing", q.id, "The query object has no `query`."); continue }55 context.checkQuery(json, owner: q.id, issues: &issues)56 }5758 for o in bp.objects where o.isPage || o.isComponent {59 if o.isPage {60 if o.children.count > 1 { warn("page.children", o.id, "A page shows only its first child; wrap the content in a stack.") }61 continue62 }63 guard let manifest = registry.manifest(o.type, in: bp) else {64 err("component.unknown", o.id, o.isCustomInstance ? "`\(o.type)` is not defined: there is no on-demand component `\(CustomComponent.id(ofType: o.type) ?? "")` in this app." : "`\(o.type)` is not in the component catalog.")65 continue66 }67 if !o.children.isEmpty && !manifest.acceptsChildren { err("children.notAllowed", o.id, "\(manifest.name) cannot contain other components.") }68 if let max = manifest.maxChildren, o.children.count > max { err("children.tooMany", o.id, "\(manifest.name) accepts at most \(max) children.") }69 for p in manifest.permissions where !bp.permissions.contains(p) {70 err("permission.missing", o.id, "\(manifest.name) needs the `\(p)` permission, which the app does not declare.")71 }72 for spec in manifest.props where spec.required && o.props[spec.name] == nil {73 err("prop.required", o.id, "\(manifest.name) needs `\(spec.name)`: \(spec.summary)")74 }75 for (name, value) in o.props.sorted(by: { $0.key < $1.key }) {76 guard let spec = manifest.prop(name) else {77 err("prop.unknown", o.id, "\(manifest.name) has no property `\(name)`. Known: \(manifest.props.map(\.name).joined(separator: ", ")).")78 continue79 }80 context.checkProp(spec, value, object: o, manifest: manifest, issues: &issues)81 }82 for (event, actions) in o.events.sorted(by: { $0.key < $1.key }) {83 guard manifest.events.contains(event) else {84 err("event.unknown", o.id, "\(manifest.name) has no `\(event)` event. Known: \(manifest.events.joined(separator: ", ")).")85 continue86 }87 for a in actions { context.checkAction(a, owner: o.id, issues: &issues, depth: 0) }88 }89 if let labelProp = manifest.accessibilityLabelProp, o.props[labelProp] == nil, o.props["accessibilityLabel"] == nil,90 manifest.prop(labelProp)?.required == false {91 warn("accessibility.label", o.id, "\(manifest.name) has no `\(labelProp)` or `accessibilityLabel`; VoiceOver will not be able to name it.")92 }93 }94 return issues95 }9697 struct Context {98 let bp: AppBlueprint99 let schemas: [String: TableSchema]100 let queryIDs: Set<String>101102 func checkExpression(_ source: String, owner: String, what: String, issues: inout [ValidationIssue]) {103 do {104 let e = try Expression(source)105 for fn in e.calledFunctions where !Evaluator.functionNames.contains(fn) {106 issues.append(.init(.error, "expression.function", owner, "\(what): unknown function `\(fn)`."))107 }108 for ref in e.references {109 let parts = ref.split(separator: ".").map(String.init)110 guard ExpressionScope.knownRoots.contains(parts[0]) else {111 issues.append(.init(.error, "expression.name", owner, "\(what): unknown name `\(parts[0])`. Use state, row, queries, value or item."))112 continue113 }114 if parts[0] == "queries", parts.count > 1, !queryIDs.contains(parts[1]) {115 issues.append(.init(.error, "expression.query", owner, "\(what): there is no query object `\(parts[1])`."))116 }117 if parts[0] == "state", parts.count > 1, bp.state[parts[1]] == nil {118 issues.append(.init(.error, "state.undeclared", owner, "\(what): `state.\(parts[1])` is not declared in the app's `state`."))119 }120 }121 } catch {122 issues.append(.init(.error, "expression.syntax", owner, "\(what): \(error.localizedDescription) (in `\(source)`)"))123 }124 }125126 func checkBinding(_ path: String, owner: String, what: String, issues: inout [ValidationIssue]) {127 guard StatePath.isValid(path) else {128 issues.append(.init(.error, "binding.path", owner, "\(what): `\(path)` is not a valid state path."))129 return130 }131 let top = String(path.split(separator: ".")[0])132 if bp.state[top] == nil {133 issues.append(.init(.error, "state.undeclared", owner, "\(what): `state.\(top)` is not declared in the app's `state`."))134 }135 }136137 /// Checks every `$expr` / `$bind` found anywhere inside a value.138 func checkDynamics(_ value: JSONValue, owner: String, what: String, issues: inout [ValidationIssue]) {139 switch DynamicValue(value) {140 case .expression(let s): checkExpression(s, owner: owner, what: what, issues: &issues)141 case .binding(let p): checkBinding(p, owner: owner, what: what, issues: &issues)142 case .literal(let v):143 if let a = v.arrayValue { for x in a { checkDynamics(x, owner: owner, what: what, issues: &issues) } }144 if let o = v.objectValue { for (_, x) in o { checkDynamics(x, owner: owner, what: what, issues: &issues) } }145 }146 }147148 @discardableResult149 func checkQuery(_ json: JSONValue, owner: String, issues: inout [ValidationIssue]) -> (DataQuery, TableSchema)? {150 if let ref = json["$ref"]?.stringValue {151 guard let target = bp.object(ref), target.isQuery, let inner = target.props["query"] else {152 issues.append(.init(.error, "query.ref", owner, "There is no query object `\(ref)`."))153 return nil154 }155 guard let q = try? DataQuery(json: inner), let schema = schemas[q.table] else { return nil }156 return (q, schema)157 }158 do {159 let q = try DataQuery(json: json)160 guard let schema = schemas[q.table] else {161 issues.append(.init(.error, "query.table", owner, "The query reads table `\(q.table)`, which the app does not define."))162 return nil163 }164 for p in q.problems(schema: schema) { issues.append(.init(.error, "query.invalid", owner, p)) }165 checkDynamics(json, owner: owner, what: "query", issues: &issues)166 return (q, schema)167 } catch {168 issues.append(.init(.error, "query.invalid", owner, error.localizedDescription))169 return nil170 }171 }172173 func checkProp(_ spec: PropSpec, _ value: JSONValue, object o: PrismObject, manifest: ComponentManifest, issues: inout [ValidationIssue]) {174 let what = "`\(spec.name)`"175 func err(_ code: String, _ m: String) { issues.append(.init(.error, code, o.id, m)) }176 switch DynamicValue(value) {177 case .expression(let source):178 guard spec.dynamic else { err("prop.static", "\(what) of \(manifest.name) must be a fixed value, not an expression."); return }179 checkExpression(source, owner: o.id, what: what, issues: &issues)180 return181 case .binding(let path):182 guard spec.binding != .none else { err("prop.binding", "\(what) of \(manifest.name) cannot be bound to state; use `$expr` to read a value."); return }183 checkBinding(path, owner: o.id, what: what, issues: &issues)184 return185 case .literal:186 if spec.binding == .required { err("prop.binding", "\(what) of \(manifest.name) must be `{\"$bind\": \"stateKey\"}` so the component can write the value."); return }187 }188 switch spec.kind {189 case .string: if value.stringValue == nil { err("prop.type", "\(what) must be text, not \(value.typeName).") }190 case .number: if value.doubleValue == nil { err("prop.type", "\(what) must be a number, not \(value.typeName).") }191 case .boolean: if value.boolValue == nil { err("prop.type", "\(what) must be true or false, not \(value.typeName).") }192 case .enum:193 if let s = value.stringValue, spec.enumValues.contains(s) { break }194 err("prop.enum", "\(what) must be one of: \(spec.enumValues.joined(separator: ", ")).")195 case .list:196 guard value.arrayValue != nil else { err("prop.type", "\(what) must be a list, not \(value.typeName)."); break }197 checkDynamics(value, owner: o.id, what: what, issues: &issues)198 case .object:199 guard value.objectValue != nil else { err("prop.type", "\(what) must be an object, not \(value.typeName)."); break }200 checkDynamics(value, owner: o.id, what: what, issues: &issues)201 case .query:202 if let (q, schema) = checkQuery(value, owner: o.id, issues: &issues) { checkColumns(of: o, query: q, schema: schema, issues: &issues) }203 case .any: checkDynamics(value, owner: o.id, what: what, issues: &issues)204 }205 if spec.name == "table", let name = value.stringValue, schemas[name] == nil {206 err("table.missing", "\(manifest.name) uses table `\(name)`, which the app does not define.")207 }208 if spec.name == "items" || spec.name == "menuItems" {209 for item in value.arrayValue ?? [] {210 for a in item["actions"]?.arrayValue ?? [] { checkAction(a, owner: o.id, issues: &issues, depth: 0) }211 if let page = item["page"]?.stringValue, bp.object(page)?.isPage != true {212 err("navigate.page", "An item points to page `\(page)`, which does not exist.")213 }214 }215 }216 }217218 /// Column names a data component reads must be produced by its query.219 func checkColumns(of o: PrismObject, query: DataQuery, schema: TableSchema, issues: inout [ValidationIssue]) {220 let outputs = Set(query.outputColumns(schema: schema))221 var used: [String] = []222 for key in ["x", "y", "label", "value", "valueColumn", "labelColumn"] {223 if let s = o.props[key]?.stringValue, key != "label" || o.type.hasPrefix("prism.chart") { used.append(s) }224 }225 for c in o.props["columns"]?.arrayValue ?? [] { if let s = c["column"]?.stringValue ?? c.stringValue { used.append(s) } }226 for name in used where !outputs.contains(name) {227 issues.append(.init(.error, "column.unknown", o.id, "`\(name)` is not produced by the query. Available: \(outputs.sorted().joined(separator: ", "))."))228 }229 }230231 static let actionTypes: Set<String> = [232 "setState", "toggleState", "navigate", "createRecord", "updateRecord", "deleteRecord", "importCSV", "exportCSV",233 "showNotification", "validate", "when", "runScript",234 ]235236 func checkAction(_ a: JSONValue, owner: String, issues: inout [ValidationIssue], depth: Int) {237 func err(_ m: String) { issues.append(.init(.error, "action.invalid", owner, m)) }238 guard depth < 8 else { err("Actions are nested too deeply."); return }239 guard let type = a["type"]?.stringValue else { err("An action needs a `type`."); return }240 guard Self.actionTypes.contains(type) else {241 err("Unknown action `\(type)`. Known: \(Self.actionTypes.sorted().joined(separator: ", ")).")242 return243 }244 func table() -> TableSchema? {245 guard let name = a["table"]?.stringValue else { err("`\(type)` needs a `table`."); return nil }246 guard let s = schemas[name] else { err("`\(type)` uses table `\(name)`, which the app does not define."); return nil }247 return s248 }249 func values(_ schema: TableSchema) {250 guard let v = a["values"]?.objectValue else { err("`\(type)` needs `values`."); return }251 for (k, x) in v {252 if schema.column(k) == nil { err("`\(type)`: table `\(schema.name)` has no column `\(k)`.") }253 checkDynamics(x, owner: owner, what: "`\(type)` value `\(k)`", issues: &issues)254 }255 }256 func stateKey() {257 guard let key = a["key"]?.stringValue else { err("`\(type)` needs a `key`."); return }258 checkBinding(key.hasPrefix("state.") ? String(key.dropFirst(6)) : key, owner: owner, what: "`\(type)`", issues: &issues)259 }260 switch type {261 case "setState":262 stateKey()263 guard let v = a["value"] else { err("`setState` needs a `value`."); return }264 checkDynamics(v, owner: owner, what: "`setState` value", issues: &issues)265 case "toggleState": stateKey()266 case "navigate":267 guard let page = a["page"]?.stringValue, bp.object(page)?.isPage == true else { err("`navigate` needs an existing `page`."); return }268 case "createRecord": if let s = table() { values(s) }269 case "updateRecord", "deleteRecord":270 guard let id = a["id"] else { err("`\(type)` needs the record `id`."); return }271 checkDynamics(id, owner: owner, what: "`\(type)` id", issues: &issues)272 if let s = table(), type == "updateRecord" { values(s) }273 case "importCSV":274 _ = table()275 if !bp.permissions.contains(Permission.filesImport) { err("`importCSV` needs the `\(Permission.filesImport)` permission.") }276 case "exportCSV":277 if let q = a["query"] { checkQuery(q, owner: owner, issues: &issues) } else { _ = table() }278 if !bp.permissions.contains(Permission.filesExport) { err("`exportCSV` needs the `\(Permission.filesExport)` permission.") }279 case "showNotification":280 guard let m = a["message"] else { err("`showNotification` needs a `message`."); return }281 checkDynamics(m, owner: owner, what: "`showNotification` message", issues: &issues)282 case "validate":283 guard let rules = a["rules"]?.arrayValue, !rules.isEmpty else { err("`validate` needs `rules`."); return }284 for r in rules {285 guard let w = r["when"], r["message"] != nil else { err("A validation rule needs `when` and `message`."); continue }286 checkDynamics(w, owner: owner, what: "validation rule", issues: &issues)287 }288 case "runScript":289 guard let fn = a["function"]?.stringValue, ScriptEngine.isIdentifier(fn) else { err("`runScript` needs the `function` name."); return }290 if bp.scripts.isEmpty { err("`runScript` calls `\(fn)`, but the app has no script. Create one with logic.createScript.") }291 if let args = a["args"] {292 guard args.arrayValue != nil else { err("`runScript` `args` must be a list."); return }293 checkDynamics(args, owner: owner, what: "`runScript` args", issues: &issues)294 }295 case "when":296 guard let c = a["condition"] else { err("`when` needs a `condition`."); return }297 checkDynamics(c, owner: owner, what: "`when` condition", issues: &issues)298 for x in (a["then"]?.arrayValue ?? []) + (a["else"]?.arrayValue ?? []) { checkAction(x, owner: owner, issues: &issues, depth: depth + 1) }299 default: break300 }301 }302 }303}304