| 1 | // Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7, |
| 2 | // native/apple/Sources/EquipoKit/Markdown/MarkdownActions.swift). Base's changes are |
| 3 | // marked "Base:"; keep the rest in step with Equipo's. |
| 4 | import Foundation |
| 5 | |
| 6 | // Base: every link Base's Assistant may write is a web address; there are |
| 7 | // no task links (Equipo's /tasks/ and /projects/ paths). |
| 8 | enum MarkdownDestination: Equatable { |
| 9 | case external(URL) |
| 10 | } |
| 11 | |
| 12 | enum MarkdownActions { |
| 13 | static func destination(_ target: String, origin: URL) -> MarkdownDestination? { |
| 14 | guard let url = linkURL(target) else { return nil } |
| 15 | return .external(url) |
| 16 | } |
| 17 | static func linkURL(_ target: String) -> URL? { |
| 18 | guard ChatMarkdown.allowsLink(target) else { return nil } |
| 19 | if let url = URL(string: target) { return url } |
| 20 | // Foundation rejects a few host characters Go's URL parser allows. |
| 21 | // Encode only that authority after validating the original target. |
| 22 | guard let scheme = target.range(of: "://") else { return nil } |
| 23 | let rest = target[scheme.upperBound...] |
| 24 | let end = rest.firstIndex(where: { "/?#".contains($0) }) ?? target.endIndex |
| 25 | let authority = target[scheme.upperBound..<end] |
| 26 | let safe = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:%@") |
| 27 | guard let encoded = String(authority).addingPercentEncoding(withAllowedCharacters: safe) else { return nil } |
| 28 | return URL(string: String(target[..<scheme.upperBound]) + encoded + target[end...]) |
| 29 | } |
| 30 | static func originalTarget(_ url: URL, in nodes: [ChatMarkdownNode]) -> String? { |
| 31 | var stack = nodes |
| 32 | while let node = stack.popLast() { |
| 33 | if node.kind == "link", let target = node.target, linkURL(target) == url { return target } |
| 34 | stack.append(contentsOf: node.children) |
| 35 | } |
| 36 | return nil |
| 37 | } |
| 38 | static func copyText(_ node: ChatMarkdownNode) -> String? { |
| 39 | guard node.kind == "paste", node.copyEnabled == true else { return nil } |
| 40 | let text = node.text ?? "" |
| 41 | return text.hasSuffix("\n") ? String(text.dropLast()) : text |
| 42 | } |
| 43 | } |
| 44 | |