1use rkyv::{Archive, Deserialize, Serialize};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Archive, Serialize, Deserialize)]
16pub enum AddressKind {
17 #[default]
19 Http,
20 File,
22 Data,
24 GraphshellClip,
26 Directory,
28 Unknown,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
43#[rkyv(derive(Debug, PartialEq))]
44pub enum Address {
45 Http(String),
47 File(String),
49 Data(String),
51 Clip(String),
54 Directory(String),
56 Custom(String),
58}
59
60impl Address {
61 pub fn as_url_str(&self) -> &str {
63 match self {
64 Address::Http(s)
65 | Address::File(s)
66 | Address::Data(s)
67 | Address::Directory(s)
68 | Address::Custom(s)
69 | Address::Clip(s) => s.as_str(),
70 }
71 }
72
73 pub fn address_kind(&self) -> AddressKind {
78 match self {
79 Address::Http(_) => AddressKind::Http,
80 Address::File(_) => AddressKind::File,
81 Address::Data(_) => AddressKind::Data,
82 Address::Clip(_) => AddressKind::GraphshellClip,
83 Address::Directory(_) => AddressKind::Directory,
84 Address::Custom(_) => AddressKind::Unknown,
85 }
86 }
87}
88
89impl chartulary::ContainerAddress for Address {
90 fn to_address(&self) -> chartulary::Address {
91 chartulary::Address::new(self.as_url_str())
92 }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
102#[rkyv(derive(Debug, PartialEq))]
103pub enum AddressRole {
104 Primary,
106 Alias,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
117#[rkyv(derive(Debug, PartialEq))]
118pub struct AddressClaim {
119 pub address: Address,
120 pub role: AddressRole,
121}
122
123impl AddressClaim {
124 pub fn primary(address: Address) -> Self {
126 Self {
127 address,
128 role: AddressRole::Primary,
129 }
130 }
131
132 pub fn alias(address: Address) -> Self {
134 Self {
135 address,
136 role: AddressRole::Alias,
137 }
138 }
139
140 pub fn is_primary(&self) -> bool {
142 matches!(self.role, AddressRole::Primary)
143 }
144}
145
146pub fn address_from_url(url: &str) -> Address {
151 let lower = url.to_ascii_lowercase();
152 if lower.starts_with("http://") || lower.starts_with("https://") {
153 Address::Http(url.to_owned())
154 } else if lower.starts_with("data:") {
155 Address::Data(url.to_owned())
156 } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
157 Address::Clip(url.to_owned())
158 } else if lower.starts_with("file://") {
159 if file_url_uses_directory_syntax(url) {
160 Address::Directory(url.to_owned())
161 } else {
162 Address::File(url.to_owned())
163 }
164 } else {
165 Address::Custom(url.to_owned())
166 }
167}
168
169pub fn address_kind_from_url(url: &str) -> AddressKind {
171 let lower = url.to_ascii_lowercase();
172 if lower.starts_with("http://") || lower.starts_with("https://") {
173 AddressKind::Http
174 } else if lower.starts_with("data:") {
175 AddressKind::Data
176 } else if lower.starts_with("verso://clip/") || lower.starts_with("graphshell://clip/") {
177 AddressKind::GraphshellClip
178 } else if lower.starts_with("file://") {
179 if file_url_uses_directory_syntax(url) {
180 AddressKind::Directory
181 } else {
182 AddressKind::File
183 }
184 } else {
185 AddressKind::Unknown
186 }
187}
188
189fn file_url_uses_directory_syntax(url: &str) -> bool {
190 url::Url::parse(url)
193 .ok()
194 .is_some_and(|parsed| parsed.path().ends_with('/'))
195}
196
197pub fn cached_host_from_url(url: &str) -> Option<String> {
198 url::Url::parse(url)
199 .ok()
200 .and_then(|parsed| parsed.host_str().map(str::to_owned))
201}
202
203pub fn detect_mime(url: &str, content_bytes: Option<&[u8]>) -> Option<String> {
212 let no_fragment = url.split('#').next().unwrap_or(url);
213 let no_query = no_fragment.split('?').next().unwrap_or(no_fragment);
214 let path = no_query
216 .strip_prefix("file://")
217 .unwrap_or(no_query)
218 .trim_start_matches('/');
219 let guess_path = format!("/{path}");
221 let guessed: Vec<String> = mime_guess::from_path(&guess_path)
222 .into_iter()
223 .map(|m| m.to_string())
224 .collect();
225
226 let is_ambiguous = guessed.len() > 1
227 || guessed
228 .first()
229 .map(|m| m == "application/octet-stream")
230 .unwrap_or(false);
231
232 if !guessed.is_empty() && !is_ambiguous {
233 return guessed.first().cloned();
234 }
235
236 if let Some(bytes) = content_bytes {
237 if let Some(kind) = infer::get(bytes) {
238 return Some(kind.mime_type().to_string());
239 }
240 }
241
242 guessed.first().cloned()
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 #[test]
250 fn detect_mime_returns_pdf_for_pdf_path() {
251 assert_eq!(
252 detect_mime("file:///home/user/document.pdf", None),
253 Some("application/pdf".to_string())
254 );
255 }
256
257 #[test]
258 fn detect_mime_returns_text_plain_for_txt_path() {
259 assert_eq!(
260 detect_mime("file:///notes/readme.txt", None),
261 Some("text/plain".to_string())
262 );
263 }
264
265 #[test]
266 fn detect_mime_returns_none_for_no_extension() {
267 assert!(detect_mime("https://example.com/page", None).is_none());
268 }
269
270 #[test]
271 fn detect_mime_uses_magic_bytes_when_extension_is_missing() {
272 let pdf_header = b"%PDF-1.7\n1 0 obj\n";
273 assert_eq!(
274 detect_mime("https://example.com/no-extension", Some(pdf_header)),
275 Some("application/pdf".to_string())
276 );
277 }
278
279 #[test]
280 fn detect_mime_prefers_extension_when_unambiguous() {
281 let pdf_header = b"%PDF-1.7\n1 0 obj\n";
282 assert_eq!(
283 detect_mime("file:///home/user/readme.txt", Some(pdf_header)),
284 Some("text/plain".to_string())
285 );
286 }
287
288 #[test]
289 fn detect_mime_falls_back_to_extension_when_magic_unknown() {
290 let unknown = b"not a known magic signature";
291 assert_eq!(
292 detect_mime("file:///home/user/data.json", Some(unknown)),
293 Some("application/json".to_string())
294 );
295 }
296
297 #[test]
298 fn address_kind_from_url_http() {
299 assert_eq!(
300 address_kind_from_url("http://example.com"),
301 AddressKind::Http
302 );
303 assert_eq!(
304 address_kind_from_url("https://example.com"),
305 AddressKind::Http
306 );
307 }
308
309 #[test]
310 fn address_kind_from_url_file() {
311 assert_eq!(
312 address_kind_from_url("file:///home/user/file.txt"),
313 AddressKind::File
314 );
315 }
316
317 #[test]
318 fn address_kind_from_url_data_clip_directory_and_unknown() {
319 assert_eq!(
320 address_kind_from_url("data:text/plain,hello"),
321 AddressKind::Data
322 );
323 assert_eq!(
324 address_kind_from_url("verso://clip/clip-123"),
325 AddressKind::GraphshellClip
326 );
327 assert_eq!(
328 address_kind_from_url("file:///tmp/sample-dir/"),
329 AddressKind::Directory
330 );
331 assert_eq!(
332 address_kind_from_url("gemini://gemini.circumlunar.space/"),
333 AddressKind::Unknown
334 );
335 assert_eq!(
336 address_kind_from_url("ftp://files.example.com/"),
337 AddressKind::Unknown
338 );
339 }
340
341 #[test]
342 fn address_kind_from_url_file_directory_classification_is_syntax_based() {
343 assert_eq!(
344 address_kind_from_url("file:///tmp/sample-dir/"),
345 AddressKind::Directory
346 );
347 assert_eq!(
348 address_kind_from_url("file:///tmp/sample-dir"),
349 AddressKind::File
350 );
351 }
352
353 #[test]
354 fn address_from_url_http() {
355 assert_eq!(
356 address_from_url("https://example.com"),
357 Address::Http("https://example.com".to_string())
358 );
359 assert_eq!(
360 address_from_url("http://example.com/path"),
361 Address::Http("http://example.com/path".to_string())
362 );
363 }
364
365 #[test]
366 fn address_from_url_file_and_directory() {
367 assert_eq!(
368 address_from_url("file:///home/user/file.txt"),
369 Address::File("file:///home/user/file.txt".to_string())
370 );
371 assert_eq!(
372 address_from_url("file:///tmp/mydir/"),
373 Address::Directory("file:///tmp/mydir/".to_string())
374 );
375 }
376
377 #[test]
378 fn address_from_url_data_and_custom() {
379 assert_eq!(
380 address_from_url("data:text/plain,hello"),
381 Address::Data("data:text/plain,hello".to_string())
382 );
383 assert_eq!(
384 address_from_url("gemini://gemini.circumlunar.space/"),
385 Address::Custom("gemini://gemini.circumlunar.space/".to_string())
386 );
387 }
388
389 #[test]
390 fn address_from_url_clip_stores_full_url() {
391 assert_eq!(
392 address_from_url("verso://clip/clip-abc-123"),
393 Address::Clip("verso://clip/clip-abc-123".to_string())
394 );
395 assert_eq!(
396 address_from_url("graphshell://clip/clip-xyz"),
397 Address::Clip("graphshell://clip/clip-xyz".to_string())
398 );
399 }
400
401 #[test]
402 fn address_as_url_str_roundtrips_for_all_variants() {
403 let cases = [
404 "https://example.com",
405 "file:///home/user/file.txt",
406 "file:///tmp/mydir/",
407 "data:text/plain,hello",
408 "gemini://example.com/",
409 "verso://clip/clip-abc",
410 "graphshell://clip/clip-xyz",
411 ];
412 for url in cases {
413 let addr = address_from_url(url);
414 assert_eq!(
415 addr.as_url_str(),
416 url,
417 "as_url_str should return the original URL for {url}"
418 );
419 }
420 }
421
422 #[test]
423 fn address_address_kind_bridge_matches_legacy_inference() {
424 let cases = [
425 ("https://example.com", AddressKind::Http),
426 ("http://example.com", AddressKind::Http),
427 ("file:///home/user/file.txt", AddressKind::File),
428 ("file:///tmp/mydir/", AddressKind::Directory),
429 ("data:text/plain,hello", AddressKind::Data),
430 ("verso://clip/clip-123", AddressKind::GraphshellClip),
431 ("graphshell://clip/clip-456", AddressKind::GraphshellClip),
432 ("gemini://example.com/", AddressKind::Unknown),
433 ];
434 for (url, expected_kind) in cases {
435 assert_eq!(
436 address_from_url(url).address_kind(),
437 expected_kind,
438 "address_kind() mismatch for {url}"
439 );
440 assert_eq!(
441 address_kind_from_url(url),
442 expected_kind,
443 "address_kind_from_url mismatch for {url}"
444 );
445 }
446 }
447}