88 lines
4.4 KiB
Swift
88 lines
4.4 KiB
Swift
import Foundation
|
|
import MarkdownUI
|
|
import cmark_gfm
|
|
import cmark_gfm_extensions
|
|
|
|
/// Agent images come only from validated attachment descriptors. Rewrite parsed nodes,
|
|
/// including reference/nested images, so neither MarkdownUI image loader receives a URL.
|
|
enum AgentMessageMarkdown {
|
|
static func content(_ source: String) -> MarkdownContent {
|
|
cmark_gfm_core_extensions_ensure_registered()
|
|
guard let parser = cmark_parser_new(CMARK_OPT_DEFAULT) else { return literal(source) }
|
|
defer { cmark_parser_free(parser) }
|
|
for name in ["table", "strikethrough", "autolink", "tasklist"] {
|
|
if let ext = cmark_find_syntax_extension(name) { cmark_parser_attach_syntax_extension(parser, ext) }
|
|
}
|
|
source.withCString { cmark_parser_feed(parser, $0, source.utf8.count) }
|
|
guard let document = cmark_parser_finish(parser) else { return literal(source) }
|
|
defer { cmark_node_free(document) }
|
|
stripImagesAndHTML(document)
|
|
guard let markdown = cmark_render_commonmark(document, CMARK_OPT_DEFAULT, 0) else { return literal(source) }
|
|
defer { free(markdown) }
|
|
return MarkdownContent(String(cString: markdown))
|
|
}
|
|
|
|
private static func literal(_ source: String) -> MarkdownContent {
|
|
MarkdownContent { Paragraph { source } }
|
|
}
|
|
|
|
private static func stripImagesAndHTML(_ parent: UnsafeMutablePointer<cmark_node>) {
|
|
var child = cmark_node_first_child(parent)
|
|
while let node = child {
|
|
child = cmark_node_next(node)
|
|
let type = cmark_node_get_type(node)
|
|
if type == CMARK_NODE_IMAGE || type == CMARK_NODE_HTML_INLINE || type == CMARK_NODE_HTML_BLOCK {
|
|
let text = type == CMARK_NODE_IMAGE ? altText(node) : htmlText(cmark_node_get_literal(node).map { String(cString: $0) } ?? "")
|
|
let replacement = cmark_node_new(type == CMARK_NODE_HTML_BLOCK ? CMARK_NODE_PARAGRAPH : CMARK_NODE_TEXT)!
|
|
if type == CMARK_NODE_HTML_BLOCK {
|
|
let inline = cmark_node_new(CMARK_NODE_TEXT)!
|
|
// cmark includes the HTML block's terminating newline in its literal.
|
|
// It is a block delimiter, not an extra line in the visible alt text.
|
|
cmark_node_set_literal(inline, text.trimmingCharacters(in: .newlines))
|
|
cmark_node_append_child(replacement, inline)
|
|
} else {
|
|
cmark_node_set_literal(replacement, text)
|
|
}
|
|
cmark_node_replace(node, replacement)
|
|
cmark_node_free(node)
|
|
} else {
|
|
stripImagesAndHTML(node)
|
|
}
|
|
}
|
|
}
|
|
|
|
private static func altText(_ parent: UnsafeMutablePointer<cmark_node>) -> String {
|
|
var result = "", child = cmark_node_first_child(parent)
|
|
while let node = child {
|
|
let type = cmark_node_get_type(node)
|
|
if type == CMARK_NODE_TEXT || type == CMARK_NODE_CODE {
|
|
result += cmark_node_get_literal(node).map { String(cString: $0) } ?? ""
|
|
} else if type == CMARK_NODE_SOFTBREAK || type == CMARK_NODE_LINEBREAK {
|
|
result += " "
|
|
} else if type != CMARK_NODE_HTML_INLINE {
|
|
result += altText(node)
|
|
}
|
|
child = cmark_node_next(node)
|
|
}
|
|
return result
|
|
}
|
|
|
|
private static func htmlText(_ source: String) -> String {
|
|
// HTML is never rendered. Retain ordinary text and img alt attributes as text
|
|
// nodes; quoted '>' characters cannot expose the rest of an image attribute.
|
|
let tags = try! NSRegularExpression(pattern: #"(?s)<(?:[^>"']|"[^"]*"|'[^']*')*>"#)
|
|
let alt = try! NSRegularExpression(pattern: #"(?is)^<img\b.*?\s+alt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))"#)
|
|
var result = source
|
|
for tag in tags.matches(in: source, range: NSRange(source.startIndex..., in: source)).reversed() {
|
|
let range = Range(tag.range, in: source)!
|
|
let value = String(source[range])
|
|
let match = alt.firstMatch(in: value, range: NSRange(value.startIndex..., in: value))
|
|
let label = match.flatMap { match in
|
|
(1...3).compactMap { Range(match.range(at: $0), in: value).map { String(value[$0]) } }.first
|
|
} ?? ""
|
|
result.replaceSubrange(Range(tag.range, in: result)!, with: label)
|
|
}
|
|
return result
|
|
}
|
|
}
|