import Foundation import Testing @testable import EquipoKit struct MarkdownGolden: Codable { var name: String var source: String var draft: Bool var tree: [ChatMarkdownNode] } @Suite struct ChatMarkdownTests { @Test func linksFollowTheWebPolicyAndOnlyLocalTasksNavigateInApp() { let origin = URL(string: "https://team.example.test")! #expect(MarkdownActions.destination("/tasks/tkabc123", origin: origin) == .task("tkabc123")) #expect(MarkdownActions.destination("/projects/p_abc", origin: origin) == .external(origin.appendingPathComponent("projects/p_abc"))) for target in ["https://other.test/path", "http://other.test", "mailto:person@example.test", "https://team.example.test/tasks/tkabc"] { #expect(MarkdownActions.destination(target, origin: origin) == .external(URL(string: target)!)) } for target in ["file:/tmp/x", "ftp://x", "tel:1", "sms:1", "blob:https://x", "vbscript:x", "custom:x", "javascript:alert(1)", "data:text/html,evil", "//evil.test", "/settings", "/tasks/tkabc?x=1", "/tasks/tkabc/../../logout", "/tasks/TKabc", "/tasks/tkabc%00", "https://example.test/%xx"] { #expect(MarkdownActions.destination(target, origin: origin) == nil) } } @Test func blankCodeLinesPreserveOriginalBytesInLinearTime() throws { let block = "```ts\nconst a = 1\n\nfoo[i](>x)\n```\n" let clock = ContinuousClock() let start = clock.now let tree = ChatMarkdown.parse(String(repeating: block, count: 3000), draft: false) #expect(tree.count == 3000) #expect(tree.allSatisfy { MarkdownActions.copyText($0) == "const a = 1\n\nfoo[i](>x)" }) #expect(start.duration(to: clock.now) < .seconds(2)) } @Test func schemePolicyIsAnExactAllowlist() { #expect(MarkdownLinks.schemes == ["http", "https", "mailto"]) // Valid scheme grammar, arbitrary suffixes and case variants. The // property is membership, independent of authority/path validation. var schemes = ["http", "https", "mailto", "webcal", "file", "ftp", "tel", "sms", "blob", "vbscript", "custom"] for first in "abcdefghijklmnopqrstuvwxyz" { for tail in ["", "+x", "-1", ".test", "0", "http", "mailto"] { schemes.append(String(first) + tail) } } for scheme in schemes { for variant in [scheme, scheme.uppercased(), scheme.capitalized] { let expected = ["http", "https", "mailto"].contains(scheme) for suffix in ["opaque", "//example.test/path", "a@b.test"] { #expect(ChatMarkdown.allowsLink(variant + ":" + suffix) == expected) } } } } @Test func syntaxInsideALabelCannotChangeItsDestination() { let source = "[`x](https://evil.test)`](https://good.test/x)" let tree = ChatMarkdown.parse(source, draft: false) #expect(tree.first?.children.first?.target == "https://good.test/x") } @Test func oddButWebAllowedHostsHaveActionableNativeURLs() { let origin = URL(string: "https://team.example.test")! for (raw, escaped) in [("http://]", "http://%5D"), ("https://\";", "https://%22;")] { #expect(MarkdownActions.destination(raw, origin: origin) == .external(URL(string: escaped)!)) // The encoded URL was never itself allowed by the web. The view // must resolve it through its actual rendered link's original target. #expect(!ChatMarkdown.allowsLink(escaped)) let tree = ChatMarkdown.parse("[x](" + raw + ")", draft: false) #expect(MarkdownActions.originalTarget(URL(string: escaped)!, in: tree) == raw) #expect(MarkdownActions.originalTarget(URL(string: "https://evil.test")!, in: tree) == nil) } } @Test func copyWaitsForClosureAndDropsOnlyTheLastNewline() throws { let source = "```sh\nls & \n\n" let open = try #require(ChatMarkdown.parse(source, draft: true).first) #expect(MarkdownActions.copyText(open) == nil) let closed = try #require(ChatMarkdown.parse(source + "```\n", draft: true).first) #expect(MarkdownActions.copyText(closed) == "ls & \n") var expected = open expected.copyEnabled = true #expect(closed == expected, "closing a fence changes only Copy availability") #expect(MarkdownActions.copyText(ChatMarkdownNode(kind: "text", text: "ordinary prose")) == nil) let finished = try #require(ChatMarkdown.parse(source, draft: false).first) #expect(MarkdownActions.copyText(finished) == "ls & \n") } @Test func deepQuotesOnPhoneSizedStack() async { await withCheckedContinuation { continuation in let worker = Thread { for depth in [200, 1000, 5000] { let tree = ChatMarkdown.parse(String(repeating: "> ", count: depth) + "x", draft: false) #expect(tree == [ChatMarkdownNode(kind: "paragraph", children: [ChatMarkdownNode(kind: "text", text: "x")])]) } continuation.resume() } worker.stackSize = 1024 * 1024 worker.start() } } @Test func draftMarkerScanHasLinearCost() { let clock = ContinuousClock() let elapsed = clock.measure { for count in [800, 1600, 3200] { let text = String(repeating: " ", count: count) + "x" #expect(MarkdownDraft.steady(text) == text) } } #expect(elapsed < .seconds(1)) } @MainActor @Test func backgroundParsingLeavesTheMainThread() async { let result = await ChatMarkdown.parseInBackground("**hello**", draft: false) #expect(result.first?.children.first?.kind == "strong") } @Test func manyReferencesAreScannedOnce() { let source = (0..<2000).map { "[label\($0)][r]" }.joined(separator: " ") + "\n\n[r]: https://good.test/x" let clock = ContinuousClock() let start = clock.now let tree = ChatMarkdown.parse(source, draft: false) #expect(tree.first?.children.filter { $0.kind == "link" }.count == 2000) #expect(start.duration(to: clock.now) < .seconds(2)) } @Test func dependencyAndUserVisibleNoticeStayWired() throws { let apple = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() let manifest = try String(contentsOf: apple.appendingPathComponent("Package.swift"), encoding: .utf8) #expect(manifest.contains("revision: \"08ddb528923cc1a6527e02b7a1aee9e516ca749a\"")) let account = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/UI/Screens/AccountScreen.swift"), encoding: .utf8) #expect(account.contains("MarkdownNotices()")) let renderer = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/ChatMarkdownView.swift"), encoding: .utf8) #expect(renderer.contains(".accessibilityLabel(Text(verbatim: MarkdownPresentation.pasteLabel(node)))")) let streaming = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/MarkdownStreamRenderer.swift"), encoding: .utf8) #expect(streaming.contains("await ChatMarkdown.parseInBackground")) #expect(renderer.contains(".onChange(of: request)")) #expect(renderer.contains(".onAppear {")) #expect(!renderer.contains(".onDisappear")) #expect(renderer.contains("stream = transcript.renderer(for: request.messageID)")) let strings = try String(contentsOf: apple.deletingLastPathComponent().appendingPathComponent("scripts/strings.json"), encoding: .utf8) #expect(!strings.contains("message.coordinator_spoken")) let parser = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/ChatMarkdown.swift"), encoding: .utf8) let linkFunction = parser.components(separatedBy: "func linkTarget").last!.components(separatedBy: "func textValue").first! #expect(!linkFunction.contains("NSRegularExpression")) #expect(!linkFunction.contains("matches(in: source")) } @Test func matchesEveryWebGolden() throws { var fixtures = try JSONDecoder().decode([MarkdownGolden].self, from: Fixture.data("markdown/golden")) if let path = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_DIFFERENTIAL"] { let generated = try JSONDecoder().decode([MarkdownGolden].self, from: Data(contentsOf: URL(fileURLWithPath: path))) #expect(generated.count >= 20_000) #expect(Set(generated.map(\.source)).count == generated.count) fixtures += generated } var failures = 0 var actual = fixtures for (index, fixture) in fixtures.enumerated() { let tree = ChatMarkdown.parse(fixture.source, draft: fixture.draft) func controls(_ values: [ChatMarkdownNode]) -> [UInt8] { var pending = values, result: [UInt8] = [] while let item = pending.popLast() { result += (item.text ?? "").utf8.filter { (1...8).contains($0) || $0 == 127 } pending += item.children } return result.sorted() } #expect(controls(tree) == controls(fixture.tree), "introduced placeholder in \(fixture.name)") actual[index].tree = tree if tree != fixture.tree { failures += 1 if failures <= 5 { Issue.record("\(fixture.name): \(String(reflecting: fixture.source))\nactual: \(tree)\nexpected: \(fixture.tree)") } } } #expect(failures == 0, "\(failures) of \(fixtures.count) web fixtures differ") if let path = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_ACTUAL"] { try JSONEncoder().encode(actual).write(to: URL(fileURLWithPath: path)) } } }