Repository Public
1// ORIX Sonata2// File: Packages/SonataUI/Tests/SonataUITests/DocsTests.swift3// Description: The Documentation space's logic: Markdown parsing, the manual's manifest and4// links, the search index, and the code-block rule — every Sonata block of the manual behaves5// as tagged when run exactly as the Run button runs it.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SonataBridge11import Testing12@testable import SonataUI1314/// The manual of the repository this test file belongs to.15func repositoryManual() throws -> Manual {16 let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()17 return try Manual(root: root.appendingPathComponent("Documentation/manual"))18}1920@Test func markdownBlocks() {21 let source = """22 <!--23 header comment24 -->25 # Title *with* `code`2627 A paragraph on28 two lines with **strong** text and a [link](other.md#part-two).2930 * first31 * second item32 continues here33 - nested34 1. one35 2. two3637 | Name | Value |38 |---|---|39 | `a\\|b` | 1 |40 | c |4142 > quoted43 > text4445 ```sonata,error=S200146 composition "T" { }47 ```48 ---49 """50 let blocks = Markdown.parse(source)51 #expect(blocks.count == 8, "\(blocks)")52 guard case .heading(let level, let inlines, let anchor) = blocks[0] else { Issue.record("no heading"); return }53 #expect(level == 1 && anchor == "title-with-code")54 #expect(inlines == [.text("Title "), .emphasis([.text("with")]), .text(" "), .code("code")])55 guard case .paragraph(let p) = blocks[1] else { Issue.record("no paragraph"); return }56 #expect(p.map(\.plain).joined() == "A paragraph on two lines with strong text and a link.")57 #expect(p.contains(.link(text: [.text("link")], target: "other.md#part-two")))58 guard case .list(false, let items) = blocks[2] else { Issue.record("no list"); return }59 #expect(items.count == 2 && items[1].inlines.map(\.plain).joined() == "second item continues here" && items[1].children.count == 1)60 guard case .list(true, let numbered) = blocks[3] else { Issue.record("no ordered list"); return }61 #expect(numbered.count == 2)62 guard case .table(let header, let rows) = blocks[4] else { Issue.record("no table"); return }63 #expect(header.count == 2 && rows.count == 2)64 #expect(rows[0][0] == [.code("a\\|b")] || rows[0][0].map(\.plain).joined().contains("a"))65 #expect(rows[1].count == 2 && rows[1][1].isEmpty, "short rows are padded")66 #expect(blocks[5] == .quote([.text("quoted text")]))67 #expect(blocks[6] == .code(info: "sonata,error=S2001", text: "composition \"T\" { }"))68 #expect(blocks[7] == .rule)69}7071@Test func markdownInlineEdgeCases() {72 #expect(Markdown.parseInline("2 * 3 * 4") == [.text("2 * 3 * 4")], "spaced asterisks are multiplication, not emphasis")73 #expect(Markdown.parseInline("`a*b*c`") == [.code("a*b*c")])74 #expect(Markdown.parseInline("an unclosed `tick") == [.text("an unclosed `tick")])75 #expect(Markdown.parseInline("[text] (not a link)") == [.text("[text] (not a link)")])76 #expect(Markdown.parseInline("**a `b` c**") == [.strong([.text("a "), .code("b"), .text(" c")])])77 #expect(Markdown.anchor("How studio edits relate to the code") == "how-studio-edits-relate-to-the-code")78 #expect(Markdown.anchor("Audio files in a project") == "audio-files-in-a-project")79 #expect(Markdown.parse("").isEmpty)80 #expect(Markdown.parse("```\nnever closed").count == 1)81}8283@Test func manifestIsCompleteAndChaptersParse() throws {84 let manual = try repositoryManual()85 #expect(manual.chapters.count >= 24)86 #expect(Set(manual.chapters.map(\.id)).count == manual.chapters.count)87 #expect(manual.chapters.map(\.order) == manual.chapters.map(\.order).sorted())88 #expect(manual.chapters.contains { $0.language == "fr-CA" })89 #expect(manual.sections.first?.name == "Start")90 for chapter in manual.chapters {91 let blocks = manual.blocks(of: chapter)92 guard case .heading(1, _, _)? = blocks.first else {93 Issue.record("\(chapter.file) does not start with a level-1 heading")94 continue95 }96 #expect(blocks.count >= 3, "\(chapter.file) is nearly empty")97 }98 // Every Markdown file of the folder is a chapter.99 let files = FileManager.default.enumerator(at: manual.root, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL }.filter { $0.pathExtension == "md" } ?? []100 let listed = Set(manual.chapters.map(\.file))101 for file in files where file.lastPathComponent != "README.md" {102 let relative = String(file.resolvingSymlinksInPath().path.dropFirst(manual.root.resolvingSymlinksInPath().path.count + 1))103 #expect(listed.contains(relative), "\(relative) is not in the manifest")104 }105}106107@Test func linksBetweenChaptersResolveToHeadings() throws {108 let manual = try repositoryManual()109 var checked = 0110 func links(_ inlines: [MarkdownInline]) -> [String] {111 inlines.flatMap { inline -> [String] in112 switch inline {113 case .link(let text, let target): [target] + links(text)114 case .strong(let c), .emphasis(let c): links(c)115 default: []116 }117 }118 }119 for chapter in manual.chapters {120 var targets: [String] = []121 for block in manual.blocks(of: chapter) {122 switch block {123 case .paragraph(let i), .quote(let i), .heading(_, let i, _): targets += links(i)124 case .list(_, let items): for item in items { targets += links(item.inlines) + item.children.flatMap { links($0.inlines) } }125 case .table(let header, let rows): targets += header.flatMap(links) + rows.flatMap { $0.flatMap(links) }126 default: break127 }128 }129 for target in targets where !target.hasPrefix("http") {130 guard let resolved = manual.resolve(link: target, from: chapter) else {131 Issue.record("\(chapter.file): link \(target) leads nowhere in the manual")132 continue133 }134 if let anchor = resolved.anchor, !anchor.isEmpty {135 let anchors = manual.blocks(of: resolved.chapter).compactMap { block -> String? in136 if case .heading(_, _, let a) = block { return a }137 return nil138 }139 #expect(anchors.contains(anchor), "\(chapter.file): no heading #\(anchor) in \(resolved.chapter.file)")140 }141 checked += 1142 }143 }144 #expect(checked >= 40, "only \(checked) links checked")145 let first = manual.chapters[0]146 #expect(manual.resolve(link: "https://example.org", from: first) == nil)147 #expect(manual.resolve(link: "../../etc/passwd", from: first) == nil)148 #expect(manual.resolve(link: "#save-and-export", from: first)?.chapter == first)149}150151@Test func searchFindsRanksAndFolds() throws {152 let manual = try repositoryManual()153 let index = ManualSearchIndex(manual: manual)154 #expect(index.sections.count > 100)155 let swing = index.search("swing")156 #expect(swing.first?.chapter == "rhythm" && swing.first?.heading == "Swing", "\(swing.prefix(3).map(\.id))")157 #expect(swing.first?.snippet.localizedCaseInsensitiveContains("swing") == true)158 // Every word must be present; case and accents do not matter.159 #expect(index.search("TEMPO ramp").contains { $0.chapter == "rhythm" })160 #expect(index.search("demarrage").contains { $0.chapter == "demarrage" }, "accents are folded")161 #expect(index.search("premiere note").contains { $0.chapter == "demarrage" })162 #expect(index.search("zzzqqqxxx").isEmpty)163 #expect(index.search(" ").isEmpty)164 // Code is searchable too, and the generated reference is indexed.165 #expect(index.search("peak_limit off").contains { $0.chapter == "mixing" })166 #expect(index.search("plucked_string damping").contains { $0.chapter == "ref-instruments" })167 #expect(index.search("the", limit: 5).count == 5)168}169170@Test func codeTagsAndWrapping() {171 #expect(DocCodeTag(info: "text") == nil)172 #expect(DocCodeTag(info: "") == nil)173 #expect(DocCodeTag(info: "sonata")?.kind == .program)174 #expect(DocCodeTag(info: "sonata,error=S2001")?.kind == .expectedError("S2001"))175 #expect(DocCodeTag(info: "sonata,warning=M4001")?.kind == .expectedWarning("M4001"))176 #expect(DocCodeTag(info: "sonata,fragment")?.kind == .trackFragment)177 #expect(DocCodeTag(info: "sonata,fragment=composition")?.kind == .compositionFragment)178 #expect(DocCodeTag(info: "sonata,module=lib.motifs")?.kind == .module("lib.motifs"))179 let wrapped = DocCodeTag(info: "sonata,fragment")!.program(for: "play C4\n\nplay D4")180 #expect(wrapped == "composition \"Fragment\" {\n instrument fragment: GrandPiano {\n play C4\n\n play D4\n }\n}\n")181 #expect(DocCodeTag(info: "sonata,error=S2001")!.isPlayable == false)182 #expect(DocCodeTag(info: "sonata,module=m")!.isPlayable == false)183 #expect(DocCodeTag(info: "sonata")!.isPlayable)184}185186/// The Run button and the manual agree: each block, run exactly as the app runs it, compiles or187/// fails as its tag says. This is the same contract as the Rust test, through the app's path.188@Test @MainActor func everyManualBlockRunsAsTagged() async throws {189 let manual = try repositoryManual()190 var counts = (ok: 0, documentedErrors: 0)191 for chapter in manual.chapters {192 let blocks = manual.blocks(of: chapter)193 let runner = DocRunner()194 var modules: [String: String] = [:]195 for case .code(let info, let text) in blocks {196 if case .module(let name)? = DocCodeTag(info: info)?.kind { modules[name] = text }197 }198 runner.modules = modules199 for (index, block) in blocks.enumerated() {200 guard case .code(let info, let text) = block, let tag = DocCodeTag(info: info) else { continue }201 await runner.run(block: index, tag: tag, text: text)202 let result = try #require(runner.results[index])203 switch tag.kind {204 case .expectedError(let code):205 #expect(result.asDocumented, "\(chapter.file) block \(index): expected \(code), got \(result.diagnostics.map(\.code))")206 counts.documentedErrors += 1207 case .expectedWarning(let code):208 #expect(result.ok && result.diagnostics.contains { $0.code == code }, "\(chapter.file) block \(index)")209 counts.ok += 1210 default:211 #expect(result.ok && result.diagnostics.isEmpty, "\(chapter.file) block \(index): \(result.diagnostics.map { "\($0.code) \($0.message)" })")212 counts.ok += 1213 }214 }215 }216 #expect(counts.ok >= 60 && counts.documentedErrors >= 5, "\(counts)")217}218219/// Listen renders through the offline renderer and yields real PCM; with the output disabled220/// nothing is played, but the waveform and the measured levels are there.221@Test @MainActor func listenRendersRealAudio() async throws {222 let runner = DocRunner()223 let tag = try #require(DocCodeTag(info: "sonata"))224 let source = "composition \"L\" {\n instrument piano: GrandPiano {\n play A4 duration 1/2\n }\n}\n"225 UserDefaults.standard.set(true, forKey: "SonataNoAudio")226 await runner.listen(block: 0, tag: tag, text: source)227 let audio = try #require(runner.rendered[0])228 #expect(audio.duration >= 1.0 && audio.channels == 2)229 let o = audio.overview(channel: 0, startFrame: 0, framesPerBucket: Double(audio.frames) / 100, buckets: 100)230 #expect((o.max.max() ?? 0) > 0.01, "the rendered note is not silent")231 #expect(runner.renderInfo[0]?.contains("dBFS") == true)232 runner.cleanUp()233}234