1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import Foundation
enum BlueskyPostMapper {
static func decodedFacets(from rawValue: Any?, text: String) -> [PostFacet] {
guard let values = rawValue as? [[String: Any]] else { return [] }
let utf8 = Array(text.utf8)
return values.compactMap { facet in
guard let index = facet["index"] as? [String: Any],
let start = index["byteStart"] as? Int,
let end = index["byteEnd"] as? Int,
start >= 0, end > start, end <= utf8.count,
String(bytes: Array(utf8[start..<end]), encoding: .utf8) != nil,
let features = facet["features"] as? [[String: Any]],
let feature = features.first,
let type = feature["$type"] as? String
else { return nil }
let decoded: PostFacet.Feature
switch type {
case "app.bsky.richtext.facet#link":
guard let urlString = feature["uri"] as? String, let url = URL(string: urlString) else { return nil }
decoded = .link(url)
case "app.bsky.richtext.facet#mention":
guard let did = feature["did"] as? String, did.hasPrefix("did:") else { return nil }
decoded = .mention(did)
case "app.bsky.richtext.facet#tag":
guard let tag = feature["tag"] as? String else { return nil }
decoded = .tag(tag)
default:
return nil
}
return PostFacet(byteStart: start, byteEnd: end, feature: decoded)
}
}
}