Repository Public
1// SP Notes Core2// File: Sources/SPNotesDocument/SchemaValidation.swift3// Description: Native check of a document against the web editor's schema (content expressions, marks, and in strict4// mode the exact attribute sets), for debug assertions and tests without the JavaScript validator.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension PMNode {11 /// What the web schema would reject in this `doc` node; empty when the document is valid.12 /// With `strict`, also reports what ProseMirror would silently normalize: attributes missing or unknown, marks13 /// out of schema order, unknown keys, empty `content` arrays.14 public func schemaViolations(strict: Bool = false) -> [String] {15 var out: [String] = []16 if type != NodeType.doc { out.append("root is \(type), not doc") }17 SchemaChecker(strict: strict).check(self, at: "doc", into: &out)18 return out19 }20}2122extension NoteDocument {23 /// What the web schema would reject in this document; empty when it is valid. See `PMNode.schemaViolations`.24 public func schemaViolations(strict: Bool = false) -> [String] { pmNode().schemaViolations(strict: strict) }25}2627struct SchemaChecker {28 let strict: Bool29 static let leaves: Set<String> = Set([NodeType.horizontalRule, NodeType.image, NodeType.youtube, NodeType.blockMath, NodeType.fileBlock,30 NodeType.hardBreak, NodeType.mention, NodeType.inlineMath, NodeType.footnoteRef, NodeType.text,31 NodeType.citation]).union(Schema.nextBlocks)32 static let known: Set<String> = Schema.blockGroup.union(Schema.inlineGroup).union([33 NodeType.doc, NodeType.listItem, NodeType.taskItem, NodeType.tableRow, NodeType.tableHeader, NodeType.tableCell,34 NodeType.detailsSummary, NodeType.detailsContent,35 ])3637 func check(_ n: PMNode, at path: String, into out: inout [String]) {38 guard Self.known.contains(n.type) else { out.append("\(path): unknown node type \(n.type)"); return }39 let kids = n.content ?? []40 let types = kids.map(\.type)41 func all(_ set: Set<String>, _ what: String, min: Int = 0) {42 if kids.count < min { out.append("\(path): needs at least \(min) \(what)") }43 for t in types where !set.contains(t) { out.append("\(path): \(t) is not allowed here (expected \(what))") }44 }45 switch n.type {46 case NodeType.doc, NodeType.blockquote, NodeType.callout, NodeType.aiBlock, NodeType.detailsContent, NodeType.tableHeader, NodeType.tableCell:47 all(Schema.blockGroup, "block", min: 1)48 case NodeType.paragraph, NodeType.heading, NodeType.footnote:49 all(Schema.inlineGroup, "inline")50 case NodeType.codeBlock, NodeType.detailsSummary:51 all([NodeType.text], "text")52 if n.type == NodeType.codeBlock, kids.contains(where: { !($0.marks ?? []).isEmpty }) { out.append("\(path): marks are not allowed in a code block") }53 case NodeType.bulletList, NodeType.orderedList:54 all([NodeType.listItem], "listItem", min: 1)55 case NodeType.taskList:56 all([NodeType.taskItem], "taskItem", min: 1)57 case NodeType.listItem, NodeType.taskItem:58 if types.first != NodeType.paragraph { out.append("\(path): must start with a paragraph") }59 all(Schema.blockGroup, "block")60 case NodeType.table:61 all([NodeType.tableRow], "tableRow", min: 1)62 case NodeType.tableRow:63 all([NodeType.tableCell, NodeType.tableHeader], "table cell")64 case NodeType.details:65 if types != [NodeType.detailsSummary, NodeType.detailsContent] { out.append("\(path): must hold detailsSummary then detailsContent") }66 default:67 if !kids.isEmpty { out.append("\(path): a \(n.type) has no content") }68 }69 if n.type == NodeType.text {70 if (n.text ?? "").isEmpty { out.append("\(path): empty text node") }71 } else if n.text != nil { out.append("\(path): text on a \(n.type) node") }72 if let marks = n.marks, !marks.isEmpty {73 if !Schema.inlineGroup.contains(n.type) { out.append("\(path): marks on a block node") }74 for m in marks where !Schema.markOrder.contains(m.type) { out.append("\(path): unknown mark \(m.type)") }75 let valid = InlineTools.validMarks(marks)76 if Set(valid) != Set(marks) || valid.count != marks.count { out.append("\(path): invalid collection of marks") }77 else if strict, valid != marks { out.append("\(path): marks are not in schema order") }78 }79 if strict {80 let expected = Set((Schema.nodeDefaults[n.type] ?? [:]).keys)81 let actual = Set((n.attrs ?? [:]).keys)82 // Attributes added in 3.0 may be absent (a document written by a 2.x editor); nothing else may differ.83 let required = expected.subtracting(Schema.optionalAttrs[n.type] ?? [])84 if !required.isSubset(of: actual) || !actual.isSubset(of: expected) { out.append("\(path): attrs \(actual.sorted()) differ from the schema's \(expected.sorted())") }85 if n.attrs?.isEmpty == true { out.append("\(path): empty attrs object") }86 if n.content?.isEmpty == true { out.append("\(path): empty content array") }87 if n.marks?.isEmpty == true { out.append("\(path): empty marks array") }88 if !n.extra.isEmpty { out.append("\(path): unknown keys \(n.extra.keys.sorted())") }89 for m in n.marks ?? [] {90 let want = m.type == "link" ? Set(Schema.linkDefaults.keys) : []91 if Set((m.attrs ?? [:]).keys) != want || m.attrs?.isEmpty == true { out.append("\(path): attrs of mark \(m.type) differ from the schema's") }92 }93 for (i, k) in kids.enumerated() where i > 0 && k.type == NodeType.text && kids[i - 1].type == NodeType.text && kids[i - 1].marks == k.marks {94 out.append("\(path): adjacent text nodes with the same marks")95 }96 }97 for (i, k) in kids.enumerated() { check(k, at: "\(path)/\(k.type)[\(i)]", into: &out) }98 }99}100