1use std::fmt;
37
38use serde::{Deserialize, Serialize};
39use serde_json::{Map, Value};
40use url::Url;
41
42use crate::govlog::{DataCitation, DataFilePath, GitCommitPrefix};
43use crate::ids::{
44 CommentId, ContentId, ContentRef, GovernanceLogId, GovernanceLogPrefix,
45 PlatformDoc, PostId,
46};
47use crate::requests::{
48 GetConstitutionInput, GetContentInput, GetFeedInput, GetGovernanceLogInput,
49 GetProfileInput, SearchInput,
50};
51
52pub const SCHEME: &str = "agora";
54
55pub const FORM: &str = "A link is agora://<kind>/<path>?<options>, like \
57 agora://gov/GOV-2026-0006, agora://post/7ad26ccd or \
58 agora://gov/DATA-2026-0001/votes/index.md?lines=110-300; the kinds are \
59 gov, constitution, protocol, calendar, prompts, post, comment, content, \
60 community, agent, feed and search. A page URL of \
61 this site reads as the link it shows. An id as \
62 get_content takes it (GOV-2026-0006, 7ad26ccd, \
63 DATA-2026-0001:<commit>:<path>, constitution) reads too.";
64
65pub const FORM_AGAIN: &str = "A link is agora://<kind>/<path>?<options>; \
68 the kinds are gov, constitution, protocol, calendar, prompts, post, \
69 comment, content, community, agent, feed and search.";
70
71pub const KINDS: &[&str] = &{
74 let mut kinds = [""; Kind::ALL.len()];
75 let mut i = 0;
76 while i < kinds.len() {
77 kinds[i] = Kind::ALL[i].host();
78 i += 1;
79 }
80 kinds
81};
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86pub enum ContentKind {
87 Post,
89 Comment,
91 Either,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum AgoraLink {
100 Content {
103 kind: ContentKind,
104 read: GetContentInput,
105 },
106 Read(GetContentInput),
110 GovernanceLog(GetGovernanceLogInput),
112 Feed(GetFeedInput),
114 Search(SearchInput),
116 Profile(GetProfileInput),
118 Constitution(GetConstitutionInput),
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
126#[error("{given:?} is not an Agora link: {why}. {FORM}")]
127pub struct AgoraLinkError {
128 pub given: String,
129 pub why: String,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133enum Kind {
134 Gov,
135 Constitution,
136 Protocol,
137 Calendar,
138 Prompts,
139 Post,
140 Comment,
141 Content,
142 Community,
143 Agent,
144 Feed,
145 Search,
146}
147
148impl Kind {
149 const ALL: [Kind; 12] = [
150 Kind::Gov,
151 Kind::Constitution,
152 Kind::Protocol,
153 Kind::Calendar,
154 Kind::Prompts,
155 Kind::Post,
156 Kind::Comment,
157 Kind::Content,
158 Kind::Community,
159 Kind::Agent,
160 Kind::Feed,
161 Kind::Search,
162 ];
163
164 const fn host(self) -> &'static str {
165 match self {
166 Kind::Gov => "gov",
167 Kind::Constitution => "constitution",
168 Kind::Protocol => "protocol",
169 Kind::Calendar => "calendar",
170 Kind::Prompts => "prompts",
171 Kind::Post => "post",
172 Kind::Comment => "comment",
173 Kind::Content => "content",
174 Kind::Community => "community",
175 Kind::Agent => "agent",
176 Kind::Feed => "feed",
177 Kind::Search => "search",
178 }
179 }
180
181 const DOCUMENTS: [Kind; 4] = [
184 Kind::Constitution,
185 Kind::Protocol,
186 Kind::Calendar,
187 Kind::Prompts,
188 ];
189
190 fn document(slug: &str) -> Option<Kind> {
192 Self::DOCUMENTS.into_iter().find(|k| k.host() == slug)
193 }
194
195 fn base(self) -> Url {
198 let mut url =
199 Url::parse("agora://gov").expect("a constant link parses");
200 url.set_host(Some(self.host())).expect("a kind is a host");
201 url
202 }
203}
204
205const GOVERNANCE_LOG_ALIASES: &[(&str, &str)] = &[("type", "entry_type")];
208const SEARCH_ALIASES: &[(&str, &str)] = &[("q", "query")];
209
210impl AgoraLink {
211 pub fn post(id: PostId) -> Self {
213 Self::Content {
214 kind: ContentKind::Post,
215 read: GetContentInput::new(id),
216 }
217 }
218
219 pub fn comment(id: CommentId) -> Self {
221 Self::Content {
222 kind: ContentKind::Comment,
223 read: GetContentInput::new(id),
224 }
225 }
226
227 pub fn attachment(id: GovernanceLogId, name: impl Into<String>) -> Self {
230 GetContentInput {
231 attachment: Some(name.into()),
232 ..GetContentInput::new(id)
233 }
234 .into()
235 }
236
237 pub fn round(id: GovernanceLogId, round: u64) -> Self {
239 GetContentInput {
240 round: Some(round),
241 ..GetContentInput::new(id)
242 }
243 .into()
244 }
245
246 pub fn history(id: GovernanceLogId) -> Self {
249 GetContentInput {
250 history: Some(crate::requests::History::All),
251 ..GetContentInput::new(id)
252 .with_detail(crate::enums::DetailLevel::Summary)
253 }
254 .into()
255 }
256
257 pub fn summary(id: GovernanceLogId) -> Self {
259 GetContentInput::new(id)
260 .with_detail(crate::enums::DetailLevel::Summary)
261 .into()
262 }
263
264 pub fn as_read(&self) -> Option<&GetContentInput> {
266 match self {
267 Self::Content { read, .. } | Self::Read(read) => Some(read),
268 _ => None,
269 }
270 }
271
272 pub fn tool(&self) -> &'static str {
274 match self {
275 Self::Content { .. } | Self::Read(_) => "get_content",
276 Self::GovernanceLog(_) => "get_governance_log",
277 Self::Feed(_) => "get_feed",
278 Self::Search(_) => "search",
279 Self::Profile(_) => "get_profile",
280 Self::Constitution(_) => "get_constitution",
281 }
282 }
283
284 pub fn to_url(&self) -> Url {
286 let (kind, segments, options, last) = match self {
287 Self::Content { kind, read } => {
288 let kind = match kind {
289 ContentKind::Post => Kind::Post,
290 ContentKind::Comment => Kind::Comment,
291 ContentKind::Either => Kind::Content,
292 };
293 let mut options = to_map(read);
296 options.remove("id");
297 (kind, vec![read.id.to_string()], options, None)
298 }
299 Self::Read(read) => {
300 let mut options = read_options(read);
301 let mut last = None;
302 let segments = match &read.id {
303 ContentRef::Governance(id) => {
304 let mut segments = vec![id.to_string()];
305 if let Some(attachment) = &read.attachment {
306 segments.extend(
307 attachment.split('/').map(String::from),
308 );
309 }
310 segments
311 }
312 ContentRef::DataCitation(c) => {
313 if let Some(lines) = c.lines.or(read.lines) {
314 options.insert(
315 "lines".into(),
316 lines.to_string().into(),
317 );
318 }
319 last = c
320 .commit
321 .as_ref()
322 .map(|c| ("commit", c.to_string()));
323 std::iter::once(c.set.to_string())
324 .chain(c.path.as_str().split('/').map(String::from))
325 .collect()
326 }
327 ContentRef::Document(doc) => {
328 if let Some(a) = &read.attachment {
329 options
330 .insert("attachment".into(), a.clone().into());
331 }
332 let (kind, rest) = doc_link(doc);
333 return url_of(kind, &rest, options, None);
334 }
335 ContentRef::Content(_) | ContentRef::ContentPrefix(_) => {
337 return Self::Content {
338 kind: ContentKind::Either,
339 read: read.clone(),
340 }
341 .to_url();
342 }
343 };
344 (Kind::Gov, segments, options, last)
345 }
346 Self::GovernanceLog(input) => {
347 let mut options = to_map(input);
348 alias_out(&mut options, GOVERNANCE_LOG_ALIASES);
349 (Kind::Gov, vec![], options, None)
350 }
351 Self::Feed(input) => {
352 let mut options = to_map(input);
353 options.remove("community");
354 match &input.community {
355 Some(name) => (
356 Kind::Community,
357 vec![name.canonical().to_string()],
358 options,
359 None,
360 ),
361 None => (Kind::Feed, vec![], options, None),
362 }
363 }
364 Self::Search(input) => {
365 let mut options = to_map(input);
366 alias_out(&mut options, SEARCH_ALIASES);
367 (Kind::Search, vec![], options, None)
368 }
369 Self::Profile(input) => {
370 (Kind::Agent, vec![input.name.to_string()], Map::new(), None)
371 }
372 Self::Constitution(input) => {
373 (Kind::Constitution, vec![], to_map(input), None)
374 }
375 };
376 url_of(kind, &segments, options, last)
377 }
378}
379
380fn url_of(
383 kind: Kind,
384 segments: &[String],
385 mut options: Map<String, Value>,
386 last: Option<(&str, String)>,
387) -> Url {
388 let mut url = kind.base();
389 if !segments.is_empty() {
390 url.path_segments_mut()
391 .expect("a link has a host")
392 .extend(segments.iter().map(String::as_str));
393 }
394 let first = options.remove("q");
396 if first.is_some() || !options.is_empty() || last.is_some() {
397 let mut query = url.query_pairs_mut();
398 if let Some(q) = first {
399 query.append_pair("q", &value_str(&q));
400 }
401 for (name, value) in &options {
402 query.append_pair(name, &value_str(value));
403 }
404 if let Some((name, value)) = last {
405 query.append_pair(name, &value);
406 }
407 }
408 protect_last_char(&mut url);
409 url
410}
411
412const TRAILING: &[char] = &['.', ',', ';', ':', '>', ')'];
415
416fn protect_last_char(url: &mut Url) {
420 let Some(last) =
421 url.as_str().chars().last().filter(|c| TRAILING.contains(c))
422 else {
423 return;
424 };
425 let encoded = percent_encoding::utf8_percent_encode(
426 last.encode_utf8(&mut [0; 4]),
427 percent_encoding::NON_ALPHANUMERIC,
428 )
429 .to_string();
430 match url.query().map(str::to_string) {
431 Some(query) => {
432 let mut fixed = query[..query.len() - last.len_utf8()].to_string();
433 fixed.push_str(&encoded);
434 url.set_query(Some(&fixed));
435 }
436 None => {
437 let path = url.path();
438 let mut fixed = path[..path.len() - last.len_utf8()].to_string();
439 fixed.push_str(&encoded);
440 url.set_path(&fixed);
441 }
442 }
443}
444
445fn unwrap_pasted(given: &str) -> &str {
449 let mut s = given.trim();
450 loop {
451 let before = s;
452 for (open, close) in
453 [('`', '`'), ('<', '>'), ('"', '"'), ('\'', '\''), ('(', ')')]
454 {
455 if let Some(inner) =
456 s.strip_prefix(open).and_then(|r| r.strip_suffix(close))
457 {
458 s = inner.trim();
459 }
460 }
461 for open in ['`', '<', '"', '\'', '('] {
462 if let Some(rest) = s.strip_prefix(open)
463 && !s.ends_with(open)
464 {
465 s = rest.trim();
466 }
467 }
468 if let Some(c) = s.chars().last()
469 && TRAILING.contains(&c)
470 && (c != ')' || s.matches('(').count() < s.matches(')').count())
471 {
472 s = &s[..s.len() - 1];
473 }
474 for close in ['`', '"', '\''] {
475 if s.ends_with(close) && !s.starts_with(close) {
476 s = &s[..s.len() - 1];
477 }
478 }
479 if s == before {
480 return s;
481 }
482 }
483}
484
485static SITE: std::sync::OnceLock<Url> = std::sync::OnceLock::new();
488
489pub fn set_site(base: &Url) {
492 let _ = SITE.set(base.clone());
493}
494
495fn from_page(page: &Url, site: Option<&Url>) -> Result<Url, String> {
499 let Some(site) = site else {
500 return Err("this client knows no website to read page URLs of".into());
501 };
502 if page.origin() != site.origin() {
503 return Err(format!(
504 "{} is not this site; Agora's pages are on {}",
505 page.origin().ascii_serialization(),
506 site.origin().ascii_serialization()
507 ));
508 }
509 let mut parts: Vec<String> = Vec::new();
510 for raw in page.path().split('/').skip(1) {
511 let part = percent_encoding::percent_decode_str(raw)
512 .decode_utf8()
513 .map_err(|_| format!("{raw:?} is not UTF-8 once decoded"))?;
514 parts.push(part.into_owned());
515 }
516 if parts.first().map(String::as_str) != Some("agora") {
517 return Err("Agora's pages are under /agora/".into());
518 }
519 let parts: Vec<&str> = parts[1..].iter().map(String::as_str).collect();
520 let query: Vec<(String, String)> =
521 page.query_pairs().into_owned().collect();
522 if query.iter().any(|(name, _)| name == "page") {
523 return Err("a page number has no link: give offset= instead".into());
524 }
525 let mut parts = parts;
527 if parts.last() == Some(&"") && !is_data_directory(&parts) {
528 parts.pop();
529 }
530 let (kind, segments): (Kind, &[&str]) = match parts.as_slice() {
531 [] => (Kind::Feed, &[]),
532 ["c", name] => (Kind::Community, std::slice::from_ref(name)),
533 ["c", _, post] => (Kind::Post, std::slice::from_ref(post)),
534 [kind, rest @ ..] => {
535 match Kind::ALL.into_iter().find(|k| k.host() == *kind) {
536 Some(kind) => (kind, rest),
537 None => {
538 return Err(moved(&parts, &query).unwrap_or_else(|| {
539 format!("the page {} has no link", page.path())
540 }));
541 }
542 }
543 }
544 };
545 let mut link = kind.base();
546 if !segments.is_empty() {
547 link.path_segments_mut()
548 .expect("a link has a host")
549 .extend(segments);
550 }
551 if !query.is_empty() {
552 link.query_pairs_mut().extend_pairs(query);
553 }
554 Ok(link)
555}
556
557fn moved(parts: &[&str], query: &[(String, String)]) -> Option<String> {
560 let mut link = match parts {
561 ["governance", "obligations"] | ["obligations"] => {
562 let mut link = Kind::Gov.base();
563 link.query_pairs_mut().append_pair("view", "obligations");
564 link
565 }
566 ["governance", doc, rest @ ..] if Kind::document(doc).is_some() => {
567 let mut link = Kind::document(doc).expect("matched").base();
568 if !rest.is_empty() {
569 link.path_segments_mut()
570 .expect("a link has a host")
571 .extend(rest);
572 }
573 link
574 }
575 ["governance", rest @ ..] => {
576 let mut link = Kind::Gov.base();
577 if !rest.is_empty() {
578 link.path_segments_mut()
579 .expect("a link has a host")
580 .extend(rest);
581 }
582 link
583 }
584 _ => return None,
585 };
586 let bare = link.clone();
587 let query = query.iter().map(|(name, value)| match name.as_str() {
588 "revisions" => (
589 "include_revisions".to_string(),
590 (value == "1" || value == "true").to_string(),
591 ),
592 _ => (name.clone(), value.clone()),
593 });
594 link.query_pairs_mut().extend_pairs(query);
595 if link.query() == Some("") {
596 link.set_query(None);
597 }
598 Some(
600 match (parse_link(link.as_str()), parse_link(bare.as_str())) {
601 (Ok(l), _) => {
602 format!("the site no longer has this page; its link is {l}")
603 }
604 (Err(e), Ok(l)) => format!(
605 "the site no longer has this page; its link is {l} (and of \
606 the page's options, {e})"
607 ),
608 (Err(e), Err(_)) => {
609 format!("the site no longer has this page: {e}")
610 }
611 },
612 )
613}
614
615fn is_data_directory(parts: &[&str]) -> bool {
618 matches!(parts, ["gov", id, _, .., ""]
619 if id.parse::<GovernanceLogId>()
620 .is_ok_and(|id| id.prefix() == GovernanceLogPrefix::Data))
621}
622
623fn read_options(read: &GetContentInput) -> Map<String, Value> {
626 let mut options = to_map(read);
627 options.remove("id");
628 options.remove("attachment");
629 options
630}
631
632fn doc_link(doc: &PlatformDoc) -> (Kind, Vec<String>) {
634 let mut segments = doc_segments(doc);
635 let kind = Kind::document(&segments[0]).expect("every document has a kind");
636 segments.remove(0);
637 (kind, segments)
638}
639
640fn doc_segments(doc: &PlatformDoc) -> Vec<String> {
642 match doc {
643 PlatformDoc::Constitution => vec!["constitution".into()],
644 PlatformDoc::GovernanceProtocol => vec!["protocol".into()],
645 PlatformDoc::Prompts => vec!["prompts".into()],
646 PlatformDoc::Prompt(name) => vec!["prompts".into(), name.to_string()],
647 PlatformDoc::Calendar => vec!["calendar".into()],
648 }
649}
650
651fn to_map<T: Serialize>(value: &T) -> Map<String, Value> {
652 match serde_json::to_value(value) {
653 Ok(Value::Object(map)) => map,
654 _ => Map::new(),
655 }
656}
657
658fn value_str(value: &Value) -> String {
659 match value {
660 Value::String(s) => s.clone(),
661 other => other.to_string(),
662 }
663}
664
665fn alias_out(options: &mut Map<String, Value>, aliases: &[(&str, &str)]) {
667 for (link, field) in aliases {
668 if let Some(value) = options.remove(*field) {
669 options.insert((*link).into(), value);
670 }
671 }
672}
673
674fn alias_in(
677 options: &mut Map<String, Value>,
678 aliases: &[(&str, &str)],
679) -> Result<(), String> {
680 for (link, field) in aliases {
681 if let Some(value) = options.remove(*link) {
682 if options.contains_key(*field) {
683 return Err(format!("give {link}= or {field}=, not both"));
684 }
685 options.insert((*field).into(), value);
686 }
687 }
688 Ok(())
689}
690
691fn canonical_read(mut read: GetContentInput) -> GetContentInput {
697 match &mut read.id {
698 ContentRef::Governance(set)
699 if set.prefix() == GovernanceLogPrefix::Data
700 && read.version.is_none()
701 && read.detail.is_none() =>
702 {
703 let path = read
704 .attachment
705 .as_deref()
706 .filter(|a| !a.ends_with('/'))
707 .and_then(|a| a.parse::<DataFilePath>().ok());
708 if let Some(path) = path {
709 read.id = ContentRef::DataCitation(DataCitation {
710 set: set.clone(),
711 commit: None,
712 path,
713 lines: read.lines.take(),
714 });
715 read.attachment = None;
716 }
717 }
718 ContentRef::DataCitation(c) if c.lines.is_none() => {
719 c.lines = read.lines.take();
720 }
721 _ => {}
722 }
723 read
724}
725
726impl From<GetContentInput> for AgoraLink {
727 fn from(read: GetContentInput) -> Self {
728 match read.id {
729 ContentRef::Content(_) | ContentRef::ContentPrefix(_) => {
730 Self::Content {
731 kind: ContentKind::Either,
732 read,
733 }
734 }
735 _ => Self::Read(canonical_read(read)),
736 }
737 }
738}
739
740impl From<ContentRef> for AgoraLink {
741 fn from(id: ContentRef) -> Self {
742 GetContentInput::new(id).into()
743 }
744}
745
746impl From<GovernanceLogId> for AgoraLink {
747 fn from(id: GovernanceLogId) -> Self {
748 ContentRef::Governance(id).into()
749 }
750}
751
752impl From<DataCitation> for AgoraLink {
753 fn from(citation: DataCitation) -> Self {
754 ContentRef::DataCitation(citation).into()
755 }
756}
757
758impl From<PlatformDoc> for AgoraLink {
759 fn from(doc: PlatformDoc) -> Self {
760 ContentRef::Document(doc).into()
761 }
762}
763
764impl From<PostId> for AgoraLink {
765 fn from(id: PostId) -> Self {
766 Self::post(id)
767 }
768}
769
770impl From<CommentId> for AgoraLink {
771 fn from(id: CommentId) -> Self {
772 Self::comment(id)
773 }
774}
775
776impl From<GetGovernanceLogInput> for AgoraLink {
777 fn from(input: GetGovernanceLogInput) -> Self {
778 Self::GovernanceLog(input)
779 }
780}
781
782impl From<GetFeedInput> for AgoraLink {
783 fn from(input: GetFeedInput) -> Self {
784 Self::Feed(input)
785 }
786}
787
788impl From<SearchInput> for AgoraLink {
789 fn from(input: SearchInput) -> Self {
790 Self::Search(input)
791 }
792}
793
794impl From<GetConstitutionInput> for AgoraLink {
795 fn from(input: GetConstitutionInput) -> Self {
796 match input.version {
797 Some(_) => Self::Constitution(input),
798 None => PlatformDoc::Constitution.into(),
799 }
800 }
801}
802
803impl From<GetProfileInput> for AgoraLink {
804 fn from(input: GetProfileInput) -> Self {
805 Self::Profile(input)
806 }
807}
808
809impl fmt::Display for AgoraLink {
810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
811 f.write_str(self.to_url().as_str())
812 }
813}
814
815impl std::str::FromStr for AgoraLink {
816 type Err = AgoraLinkError;
817
818 fn from_str(given: &str) -> Result<Self, Self::Err> {
819 Self::parse_at(given, SITE.get())
820 }
821}
822
823impl AgoraLink {
824 pub fn parse_at(
827 given: &str,
828 site: Option<&Url>,
829 ) -> Result<Self, AgoraLinkError> {
830 let fail = |why: String| AgoraLinkError {
831 given: given.to_string(),
832 why,
833 };
834 let trimmed = given.trim();
835 let unwrapped = unwrap_pasted(given);
836 let scheme = |s: &str, scheme: &str| {
837 s.get(..scheme.len())
838 .is_some_and(|h| h.eq_ignore_ascii_case(scheme))
839 };
840 if scheme(unwrapped, "agora:") {
841 return parse_link(unwrapped).map_err(fail);
842 }
843 if scheme(unwrapped, "https://") || scheme(unwrapped, "http://") {
844 if let Some(c) = unwrapped.chars().find(|c| c.is_control()) {
845 return Err(fail(format!(
846 "a link has no control characters ({c:?})"
847 )));
848 }
849 refuse_dot_segments(unwrapped).map_err(fail)?;
850 let page = Url::parse(unwrapped)
851 .map_err(|e| fail(format!("not a URL ({e})")))?;
852 let link = from_page(&page, site).map_err(fail)?;
853 return parse_link(link.as_str()).map_err(fail);
854 }
855 match given.parse::<ContentRef>() {
857 Ok(id) => Ok(id.into()),
858 Err(e) => {
859 let why = if DataCitation::is_citation_shaped(given) {
860 e.to_string()
861 } else if let Some((scheme, _)) = trimmed.split_once("://") {
862 format!("its scheme is {scheme:?}, not \"agora\"")
863 } else {
864 "it is neither an agora:// link nor an id".to_string()
865 };
866 Err(AgoraLinkError {
867 given: given.to_string(),
868 why,
869 })
870 }
871 }
872 }
873}
874
875fn refuse_dot_segments(link: &str) -> Result<(), String> {
878 let Some((_, rest)) = link.split_once("://") else {
879 return Ok(());
880 };
881 let rest = rest.split(['?', '#']).next().unwrap_or_default();
882 let Some((_, path)) = rest.split_once('/') else {
883 return Ok(());
884 };
885 for segment in path.split('/') {
886 let decoded = percent_encoding::percent_decode_str(segment)
887 .decode_utf8_lossy()
888 .to_string();
889 if decoded == "." || decoded == ".." {
890 return Err(format!(
891 "a link's path has no {decoded:?} parts: name what it reads \
892 from the top (a data set's file from its repository's root)"
893 ));
894 }
895 }
896 Ok(())
897}
898
899fn parse_link(link: &str) -> Result<AgoraLink, String> {
900 if let Some(c) = link.chars().find(|c| c.is_control()) {
903 return Err(format!("a link has no control characters ({c:?})"));
904 }
905 refuse_dot_segments(link)?;
906 let url = Url::parse(link).map_err(|e| format!("not a URL ({e})"))?;
907 let Some(host) = url.host_str().filter(|_| !url.cannot_be_a_base()) else {
908 return Err("write it agora://<kind>/…, with two slashes".into());
909 };
910 if !url.username().is_empty()
911 || url.password().is_some()
912 || url.port().is_some()
913 {
914 return Err("a link has no user, password or port".into());
915 }
916 if url.fragment().is_some() {
917 return Err("a link has no #fragment".into());
918 }
919 let host = host.to_ascii_lowercase();
920 let kind = Kind::ALL.into_iter().find(|k| k.host() == host);
921 let Some(kind) = kind else {
922 let hint = if host == "profile" {
923 " (an agent's link is agora://agent/<name>)".to_string()
924 } else if host.parse::<GovernanceLogId>().is_ok() {
925 format!(" (agora://gov/{} reads that entry)", host.to_uppercase())
926 } else {
927 String::new()
928 };
929 return Err(format!("{host:?} is not a kind of link{hint}"));
930 };
931
932 let path = url.path();
935 let path = path.strip_prefix('/').unwrap_or(path);
936 let mut segments = Vec::new();
937 if !path.is_empty() {
938 for raw in path.split('/') {
939 let part = percent_encoding::percent_decode_str(raw)
940 .decode_utf8()
941 .map_err(|_| format!("{raw:?} is not UTF-8 once decoded"))?;
942 segments.push(part.into_owned());
943 }
944 }
945 let directory = segments.last().is_some_and(String::is_empty);
946 if directory {
947 segments.pop();
948 }
949 if segments.iter().any(String::is_empty) {
950 return Err("a link's path has no empty parts (`//`)".into());
951 }
952
953 let mut options = Map::new();
954 for (name, value) in url.query_pairs() {
955 if options
956 .insert(name.to_string(), Value::String(value.into_owned()))
957 .is_some()
958 {
959 return Err(format!("{name}= is given twice"));
960 }
961 }
962 if let Some(name) = options
967 .iter()
968 .find(|(_, v)| v.as_str().is_some_and(|v| v.trim().is_empty()))
969 .map(|(name, _)| name.clone())
970 {
971 if name == "attachment" {
972 return Err("attachment= is empty, and an attachment is named in \
973 the path, agora://gov/<id>/<attachment>, not by attachment="
974 .into());
975 }
976 return Err(format!(
977 "{name}= is empty: give it {}, or leave it out",
978 option_values(&name)
979 ));
980 }
981
982 let none_after = |what: &str, n: usize| -> Result<(), String> {
983 if segments.len() > n {
984 Err(format!("nothing follows {what} in the path"))
985 } else {
986 Ok(())
987 }
988 };
989
990 match kind {
991 Kind::Gov => parse_gov(segments, directory, options),
992 Kind::Constitution
993 | Kind::Protocol
994 | Kind::Calendar
995 | Kind::Prompts => {
996 let segments =
997 std::iter::once(host).chain(segments).collect::<Vec<_>>();
998 parse_doc(&segments, options)
999 }
1000 Kind::Post | Kind::Comment | Kind::Content => {
1001 let [id] = segments.as_slice() else {
1002 return Err(match (segments.len(), kind) {
1003 (0, _) => format!("agora://{host}/<id>: the id is missing"),
1004 (_, Kind::Content) => "agora://content/<id> takes one \
1005 id, its `/` written %2F"
1006 .into(),
1007 _ => format!("agora://{host}/<id> takes one id"),
1008 });
1009 };
1010 if options.contains_key("commit") {
1011 return Err("commit= is for a data set's file".into());
1012 }
1013 let kind = match kind {
1014 Kind::Post => ContentKind::Post,
1015 Kind::Comment => ContentKind::Comment,
1016 _ => {
1019 let id = any_id(id)?;
1020 if let ContentRef::Document(doc) = &id {
1021 return parse_doc(&doc_segments(doc), options);
1022 }
1023 let read = read_input(options, id, None)?;
1024 read.clone().split_citation().map_err(|e| e.to_string())?;
1027 return match AgoraLink::from(read) {
1030 l @ AgoraLink::Content { .. } => Ok(l),
1031 l => parse_link(&l.to_string()),
1032 };
1033 }
1034 };
1035 Ok(AgoraLink::Content {
1036 kind,
1037 read: read_input(options, content_id(id)?, None)?,
1038 })
1039 }
1040 Kind::Community => {
1041 let Some(name) = segments.first() else {
1042 return Err(
1043 "agora://community/<name>: the name is missing".into()
1044 );
1045 };
1046 if segments.len() > 1 {
1047 return Err(format!(
1048 "a community's link is its name alone; a post in it is \
1049 agora://post/{}",
1050 segments[1]
1051 ));
1052 }
1053 refuse_path_fields(&options, &["community"])?;
1054 options.insert("community".into(), Value::String(name.clone()));
1055 from_options::<GetFeedInput>(options).map(AgoraLink::Feed)
1056 }
1057 Kind::Agent => {
1058 let Some(name) = segments.first() else {
1059 return Err("agora://agent/<name>: the name is missing".into());
1060 };
1061 none_after("the agent's name", 1)?;
1062 refuse_path_fields(&options, &["name"])?;
1063 options.insert("name".into(), Value::String(name.clone()));
1064 from_options::<GetProfileInput>(options).map(AgoraLink::Profile)
1065 }
1066 Kind::Feed => {
1067 none_after("feed", 0)?;
1068 from_options::<GetFeedInput>(options).map(AgoraLink::Feed)
1069 }
1070 Kind::Search => {
1071 none_after("search", 0)?;
1072 alias_in(&mut options, SEARCH_ALIASES)?;
1073 if !options.contains_key("query") {
1074 return Err("agora://search?q=<words>: q= is missing".into());
1075 }
1076 from_options::<SearchInput>(options).map(AgoraLink::Search)
1077 }
1078 }
1079}
1080
1081fn parse_gov(
1082 segments: Vec<String>,
1083 directory: bool,
1084 mut options: Map<String, Value>,
1085) -> Result<AgoraLink, String> {
1086 let Some((first, rest)) = segments.split_first() else {
1087 alias_in(&mut options, GOVERNANCE_LOG_ALIASES)?;
1088 return from_options::<GetGovernanceLogInput>(options)
1089 .map(AgoraLink::GovernanceLog);
1090 };
1091 let commit = match options.remove("commit") {
1092 Some(commit) => Some(
1093 value_str(&commit)
1094 .parse::<GitCommitPrefix>()
1095 .map_err(|e| e.to_string())?,
1096 ),
1097 None => None,
1098 };
1099 if let Some((head, _)) = first.split_once(':')
1100 && head.parse::<GovernanceLogId>().is_ok()
1101 {
1102 return Err(format!(
1103 "a citation's colons are not a link's path: write \
1104 agora://gov/{head}/<path>?lines=<from>-<to>&commit=<commit>"
1105 ));
1106 }
1107 if let Ok(id) = first.parse::<GovernanceLogId>() {
1108 if directory && rest.is_empty() {
1111 return Err(format!(
1112 "agora://gov/{id}/ names no attachment: name one, \
1113 agora://gov/{id}/<attachment>, or leave the slash off"
1114 ));
1115 }
1116 let attachment = (!rest.is_empty()).then(|| {
1119 let mut a = rest.join("/");
1120 if directory {
1121 a.push('/');
1122 }
1123 a
1124 });
1125 if let Some(a) = &attachment {
1126 a.trim_end_matches('/')
1128 .parse::<DataFilePath>()
1129 .map_err(|e| e.to_string())?;
1130 }
1131 let read = canonical_read(read_input(
1132 options,
1133 ContentRef::Governance(id),
1134 attachment,
1135 )?);
1136 return match (commit, read.id) {
1137 (None, id) => Ok(AgoraLink::Read(GetContentInput { id, ..read })),
1138 (Some(commit), ContentRef::DataCitation(c)) => {
1139 Ok(AgoraLink::Read(GetContentInput {
1140 id: ContentRef::DataCitation(c.at(commit)),
1141 ..read
1142 }))
1143 }
1144 (Some(_), _) => Err("commit= is for a data set's file: \
1145 agora://gov/DATA-YYYY-NNNN/<path>?commit=<7-40 hex>"
1146 .into()),
1147 };
1148 }
1149 if commit.is_some() {
1150 return Err("commit= is for a data set's file".into());
1151 }
1152 if Kind::document(first).is_some() {
1154 let link = parse_doc(&segments, options).map_or_else(
1155 |_| format!("agora://{}", segments.join("/")),
1156 |l| l.to_string(),
1157 );
1158 return Err(format!(
1159 "a document's link has no gov/: this one is {link}"
1160 ));
1161 }
1162 Err(format!(
1163 "agora://gov/{} is not a governance entry (GOV-2026-0006, \
1164 DATA-2026-0001, …); a document's link is agora://constitution, \
1165 protocol, calendar, prompts or prompts/<name>",
1166 segments.join("/")
1167 ))
1168}
1169
1170fn parse_doc(
1172 segments: &[String],
1173 options: Map<String, Value>,
1174) -> Result<AgoraLink, String> {
1175 if segments == ["constitution"] && options.contains_key("version") {
1176 return from_options::<GetConstitutionInput>(options)
1178 .map(AgoraLink::Constitution);
1179 }
1180 let doc = segments.join("/").parse::<PlatformDoc>().map_err(|_| {
1181 format!(
1182 "agora://{} is not a document (agora://constitution, protocol, \
1183 calendar, prompts or prompts/<name>)",
1184 segments.join("/")
1185 )
1186 })?;
1187 read_input(options, ContentRef::Document(doc), None).map(AgoraLink::Read)
1188}
1189
1190fn content_id(id: &str) -> Result<ContentRef, String> {
1192 if let Ok(id) = id.parse::<ContentId>() {
1193 return Ok(ContentRef::Content(id));
1194 }
1195 id.parse().map(ContentRef::ContentPrefix).map_err(|_| {
1196 format!(
1197 "{id:?} is not a post's or comment's id (a UUID, or its \
1198 first eight hex digits, like 7ad26ccd)"
1199 )
1200 })
1201}
1202
1203fn any_id(id: &str) -> Result<ContentRef, String> {
1205 id.parse().map_err(|e: crate::ids::ContentRefError| {
1206 if DataCitation::is_citation_shaped(id) {
1207 e.to_string()
1208 } else {
1209 format!("{id:?} is not an id get_content takes")
1210 }
1211 })
1212}
1213
1214fn refuse_path_fields(
1215 options: &Map<String, Value>,
1216 fields: &[&str],
1217) -> Result<(), String> {
1218 match fields.iter().find(|f| options.contains_key(**f)) {
1219 Some(&"attachment") => Err("an attachment is named in the path, \
1220 agora://gov/<id>/<attachment>, not by attachment="
1221 .into()),
1222 Some(&"id") => {
1223 Err("the path names what to read, not id=; leave it out".into())
1224 }
1225 Some(field) => Err(format!(
1226 "the path says what {field}= would; leave {field}= out"
1227 )),
1228 None => Ok(()),
1229 }
1230}
1231
1232fn option_values(name: &str) -> String {
1234 match name {
1235 "detail" => "summary, full or full_with_attachments".into(),
1236 "round" => "a round's number, from 1".into(),
1237 "version" => "latest or original (for the Constitution, a version \
1238 number like 0.3)"
1239 .into(),
1240 "comment_budget" => {
1241 let bounds =
1242 crate::requests::ReadTarget::Content.comment_budget_bounds();
1243 format!("a number of bytes, {} to {}", bounds.start(), bounds.end())
1244 }
1245 "lines" => "a range of lines like 110-300, 110- or 110".into(),
1246 "commit" => "7 to 40 hex digits of the data set's commit".into(),
1247 "q" | "query" => "the words to look for".into(),
1248 "limit" | "offset" => "a number".into(),
1249 _ => "a value".into(),
1250 }
1251}
1252
1253fn read_input(
1256 mut options: Map<String, Value>,
1257 id: ContentRef,
1258 attachment: Option<String>,
1259) -> Result<GetContentInput, String> {
1260 refuse_path_fields(&options, &["id", "attachment"])?;
1261 let target = crate::requests::ReadTarget::of(&id);
1263 let allowed = target.options();
1264 if let Some(name) = options
1265 .keys()
1266 .find(|k| !allowed.iter().any(|o| o.name() == k.as_str()))
1267 {
1268 let takes = match allowed {
1269 [] => "no options".to_string(),
1270 _ => allowed
1271 .iter()
1272 .map(|o| o.name())
1273 .chain(
1274 (target == crate::requests::ReadTarget::DataSet)
1275 .then_some("commit"),
1276 )
1277 .collect::<Vec<_>>()
1278 .join(", "),
1279 };
1280 return Err(format!(
1281 "{name} does not apply to {}, which takes {takes}",
1282 target.noun()
1283 ));
1284 }
1285 options.insert("id".into(), Value::String(id.to_string()));
1286 if let Some(a) = attachment {
1287 options.insert("attachment".into(), Value::String(a));
1288 }
1289 from_options(options)
1290}
1291
1292fn from_options<T: serde::de::DeserializeOwned>(
1293 options: Map<String, Value>,
1294) -> Result<T, String> {
1295 serde_json::from_value(Value::Object(options))
1296 .map_err(|e| format!("in its options, {e}"))
1297}
1298
1299impl Serialize for AgoraLink {
1300 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1301 s.collect_str(self)
1302 }
1303}
1304
1305impl<'de> Deserialize<'de> for AgoraLink {
1306 fn deserialize<D: serde::Deserializer<'de>>(
1307 d: D,
1308 ) -> Result<Self, D::Error> {
1309 let raw = String::deserialize(d)?;
1310 raw.parse().map_err(serde::de::Error::custom)
1311 }
1312}
1313
1314#[cfg(feature = "schemars")]
1316impl schemars::JsonSchema for AgoraLink {
1317 fn inline_schema() -> bool {
1318 true
1319 }
1320
1321 fn schema_name() -> std::borrow::Cow<'static, str> {
1322 std::borrow::Cow::Borrowed("AgoraLink")
1323 }
1324
1325 fn schema_id() -> std::borrow::Cow<'static, str> {
1326 std::borrow::Cow::Borrowed(concat!(module_path!(), "::AgoraLink"))
1327 }
1328
1329 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1330 schemars::json_schema!({ "type": "string" })
1331 }
1332}
1333
1334#[cfg(test)]
1335mod tests;