1use std::collections::{BTreeMap, BTreeSet};
2
3use laravel::http::Request;
4use serde::Serialize;
5use serde_json::{Map, Value};
6
7use super::hosts::{ContextError, ContextHosts};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
10#[serde(rename_all = "snake_case")]
11pub enum ContextTarget {
12 #[default]
13 WebHydrate,
14 SpaOnly,
15 Native,
16 Api,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Default)]
20pub enum ContextLinksRule {
21 #[default]
22 Public,
23 Ability(String),
24 Private,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct ContextSpec {
29 pub slug: String,
30 pub as_prefix: String,
31 pub hosts: Vec<String>,
32 pub prefix: String,
33 pub target: ContextTarget,
34 pub links_rule: ContextLinksRule,
35 pub priority: i32,
36}
37
38impl ContextSpec {
39 pub fn new(slug: impl Into<String>) -> Self {
40 let slug = slug.into();
41 Self {
42 as_prefix: slug.clone(),
43 slug,
44 hosts: Vec::new(),
45 prefix: String::new(),
46 target: ContextTarget::default(),
47 links_rule: ContextLinksRule::default(),
48 priority: 0,
49 }
50 }
51
52 pub fn with_as(mut self, as_prefix: impl Into<String>) -> Self {
53 self.as_prefix = as_prefix.into();
54 self
55 }
56
57 pub fn with_hosts<I, S>(mut self, hosts: I) -> Self
58 where
59 I: IntoIterator<Item = S>,
60 S: AsRef<str>,
61 {
62 self.hosts = ContextHosts::normalize(hosts);
63 self
64 }
65
66 pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
67 self.prefix = prefix.into();
68 self
69 }
70
71 pub fn with_target(mut self, target: ContextTarget) -> Self {
72 self.target = target;
73 self
74 }
75
76 pub fn with_links_rule(mut self, rule: ContextLinksRule) -> Self {
77 self.links_rule = rule;
78 self
79 }
80
81 pub fn with_priority(mut self, priority: i32) -> Self {
82 self.priority = priority;
83 self
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct RouteEntry {
89 pub full_name: String,
90 pub context: Option<String>,
91 pub uri: String,
92 pub hosts: Vec<String>,
93}
94
95impl RouteEntry {
96 pub fn new(full_name: impl Into<String>, uri: impl Into<String>) -> Self {
97 Self {
98 full_name: full_name.into(),
99 context: None,
100 uri: uri.into(),
101 hosts: Vec::new(),
102 }
103 }
104
105 pub fn with_context(mut self, context: impl Into<String>) -> Self {
106 self.context = Some(context.into());
107 self
108 }
109
110 pub fn with_hosts<I, S>(mut self, hosts: I) -> Self
111 where
112 I: IntoIterator<Item = S>,
113 S: AsRef<str>,
114 {
115 self.hosts = ContextHosts::normalize(hosts);
116 self
117 }
118}
119
120#[derive(Debug, Clone, Default)]
121pub struct HrefOptions {
122 pub context: Option<String>,
123 pub absolute: bool,
124 pub request_host: Option<String>,
125 pub request_scheme: Option<String>,
126 pub request_port: Option<u16>,
127 pub current_route_name: Option<String>,
128}
129
130impl HrefOptions {
131 pub fn from_request(request: &Request) -> Self {
132 let origin = request.origin();
133 let parsed = parse_origin(&origin);
134 let host = ContextHosts::normalize_one(&request.host());
135 let scheme = if request.is_secure() {
136 "https".to_owned()
137 } else {
138 parsed.scheme.unwrap_or_else(|| "http".to_owned())
139 };
140 Self {
141 context: None,
142 absolute: false,
143 request_host: host,
144 request_scheme: Some(scheme),
145 request_port: parsed.port,
146 current_route_name: None,
147 }
148 }
149
150 pub fn from_url(url: &str, context: Option<&str>) -> Self {
151 let parsed = parse_origin(url);
152 Self {
153 context: context.map(str::to_owned),
154 absolute: false,
155 request_host: Some(parsed.host),
156 request_scheme: parsed.scheme,
157 request_port: parsed.port,
158 current_route_name: None,
159 }
160 }
161
162 pub fn with_context(mut self, context: impl Into<String>) -> Self {
163 self.context = Some(context.into());
164 self
165 }
166
167 pub fn absolute(mut self) -> Self {
168 self.absolute = true;
169 self
170 }
171
172 pub fn with_current_route_name(mut self, route_name: impl Into<String>) -> Self {
173 self.current_route_name = Some(route_name.into());
174 self
175 }
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct ClientLinkEntry {
180 pub context: String,
181 pub uri: String,
182 pub hosts: Option<Vec<String>>,
183}
184
185impl Serialize for ClientLinkEntry {
186 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
187 use serde::ser::SerializeSeq;
188 let len = if self.hosts.is_some() { 3 } else { 2 };
189 let mut seq = serializer.serialize_seq(Some(len))?;
190 seq.serialize_element(&self.context)?;
191 seq.serialize_element(&self.uri)?;
192 if let Some(hosts) = &self.hosts {
193 seq.serialize_element(hosts)?;
194 }
195 seq.end()
196 }
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
200pub struct ClientContextMeta {
201 #[serde(rename = "as")]
202 pub as_prefix: String,
203 pub hosts: Vec<String>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
207pub struct ClientLinks {
208 pub context: String,
209 pub links: BTreeMap<String, ClientLinkEntry>,
210 pub contexts: BTreeMap<String, ClientContextMeta>,
211 pub primary: String,
212}
213
214#[derive(Debug, Clone)]
215struct IndexedRoute {
216 uri: String,
217 context: Option<String>,
218 hosts: Vec<String>,
219}
220
221#[derive(Debug, Clone)]
222struct ParsedOrigin {
223 scheme: Option<String>,
224 host: String,
225 port: Option<u16>,
226}
227
228#[derive(Debug, Clone)]
230pub struct RouteIndex {
231 contexts: BTreeMap<String, ContextSpec>,
232 host_table: BTreeMap<String, String>,
233 prefixes: Vec<(String, String)>,
234 routes: BTreeMap<String, IndexedRoute>,
235 short: BTreeMap<String, Vec<String>>,
236 primary: ParsedOrigin,
237}
238
239impl RouteIndex {
240 pub fn new(
241 contexts: Vec<ContextSpec>,
242 entries: Vec<RouteEntry>,
243 primary_url: &str,
244 ) -> Result<Self, ContextError> {
245 let host_table = ContextHosts::table(&contexts)?;
246
247 let mut context_map = BTreeMap::new();
248 let mut prefixes = Vec::new();
249 for ctx in contexts {
250 if !ctx.as_prefix.is_empty() {
251 prefixes.push((ctx.as_prefix.clone(), ctx.slug.clone()));
252 }
253 context_map.insert(ctx.slug.clone(), ctx);
254 }
255 prefixes.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
256
257 let mut routes = BTreeMap::new();
258 let mut short: BTreeMap<String, Vec<String>> = BTreeMap::new();
259
260 for entry in entries {
261 if routes.contains_key(&entry.full_name) {
262 continue;
263 }
264 let mut resolved_ctx = entry.context.clone();
265 let mut matched_as = None;
266 for (as_prefix, slug) in &prefixes {
267 if let Some(rest) = entry.full_name.strip_prefix(&format!("{as_prefix}.")) {
268 if resolved_ctx.is_none() {
269 resolved_ctx = Some(slug.clone());
270 }
271 matched_as = Some(rest.to_owned());
272 break;
273 }
274 }
275 if let Some(short_name) = matched_as {
276 short
277 .entry(short_name)
278 .or_default()
279 .push(entry.full_name.clone());
280 }
281 let hosts = if !entry.hosts.is_empty() {
282 entry.hosts
283 } else if let Some(ctx_slug) = &resolved_ctx {
284 context_map
285 .get(ctx_slug)
286 .map(|c| c.hosts.clone())
287 .unwrap_or_default()
288 } else {
289 Vec::new()
290 };
291
292 routes.insert(
293 entry.full_name,
294 IndexedRoute {
295 uri: normalize_uri(&entry.uri),
296 context: resolved_ctx,
297 hosts,
298 },
299 );
300 }
301
302 Ok(Self {
303 contexts: context_map,
304 host_table,
305 prefixes,
306 routes,
307 short,
308 primary: parse_origin(primary_url),
309 })
310 }
311
312 pub fn href(
313 &self,
314 name: &str,
315 params: &BTreeMap<String, String>,
316 options: &HrefOptions,
317 ) -> Result<String, ContextError> {
318 let mut map = Map::new();
319 for (k, v) in params {
320 map.insert(k.clone(), Value::String(v.clone()));
321 }
322 self.href_values(name, &map, options)
323 }
324
325 pub fn href_values(
326 &self,
327 name: &str,
328 params: &Map<String, Value>,
329 options: &HrefOptions,
330 ) -> Result<String, ContextError> {
331 let has_request =
332 options.request_host.is_some() || options.current_route_name.is_some();
333 let current = self.current_context(options);
334 let full = self.resolve_name(
335 name,
336 current.as_deref(),
337 has_request || options.context.is_some(),
338 )?;
339 let route = &self.routes[full];
340
341 let path = expand_uri_values(full, &route.uri, params)?;
342 let req_host = options
343 .request_host
344 .as_deref()
345 .and_then(ContextHosts::normalize_one);
346
347 let same_host = route.hosts.is_empty()
348 || req_host
349 .as_ref()
350 .is_some_and(|h| route.hosts.contains(h));
351
352 if has_request && route.context == current && same_host && !options.absolute {
353 return Ok(path);
354 }
355
356 let mut used_primary = false;
357 let use_host = if !route.hosts.is_empty() {
358 if let Some(h) = &req_host
359 && route.hosts.contains(h)
360 {
361 h.clone()
362 } else {
363 route.hosts[0].clone()
364 }
365 } else if let Some(h) = &req_host
366 && !self.host_table.contains_key(h)
367 {
368 h.clone()
369 } else {
370 used_primary = true;
371 self.primary.host.clone()
372 };
373
374 let scheme = if used_primary {
375 self.primary
376 .scheme
377 .as_deref()
378 .or(options.request_scheme.as_deref())
379 .unwrap_or("https")
380 } else {
381 options
382 .request_scheme
383 .as_deref()
384 .or(self.primary.scheme.as_deref())
385 .unwrap_or("https")
386 };
387
388 let request_port = options.request_port.filter(|p| *p != 80 && *p != 443);
389 let port = if req_host.as_deref() == Some(use_host.as_str()) {
390 request_port
391 } else {
392 self.primary.port.or(request_port)
393 };
394 let default_port = if scheme == "https" { 443 } else { 80 };
395 let port_suffix = match port {
396 Some(p) if p != default_port => format!(":{p}"),
397 _ => String::new(),
398 };
399
400 Ok(format!("{scheme}://{use_host}{port_suffix}{path}"))
401 }
402
403 pub fn client_links(&self, context: &str, allowed_abilities: &[&str]) -> ClientLinks {
404 let mut allowed: BTreeMap<String, bool> = BTreeMap::new();
405 for (slug, spec) in &self.contexts {
406 if slug == context {
407 continue;
408 }
409 let is_allowed = match &spec.links_rule {
410 ContextLinksRule::Public => true,
411 ContextLinksRule::Ability(ability) => allowed_abilities.contains(&ability.as_str()),
412 ContextLinksRule::Private => false,
413 };
414 allowed.insert(slug.clone(), is_allowed);
415 }
416
417 let mut links = BTreeMap::new();
418 for (name, route) in &self.routes {
419 let Some(slug) = &route.context else {
420 continue;
421 };
422 let ctx_hosts = self
423 .contexts
424 .get(slug)
425 .map(|c| c.hosts.as_slice())
426 .unwrap_or(&[]);
427 let overrides_hosts = route.hosts.as_slice() != ctx_hosts;
428 if *allowed.get(slug).unwrap_or(&false) || (slug == context && overrides_hosts) {
429 links.insert(
430 name.clone(),
431 ClientLinkEntry {
432 context: slug.clone(),
433 uri: route.uri.clone(),
434 hosts: overrides_hosts.then(|| route.hosts.clone()),
435 },
436 );
437 }
438 }
439
440 let mut contexts_meta = BTreeMap::new();
441 for (slug, spec) in &self.contexts {
442 if slug == context
443 || *allowed.get(slug).unwrap_or(&false)
444 || !spec.hosts.is_empty()
445 {
446 contexts_meta.insert(
447 slug.clone(),
448 ClientContextMeta {
449 as_prefix: spec.as_prefix.clone(),
450 hosts: spec.hosts.clone(),
451 },
452 );
453 }
454 }
455
456 let scheme = self.primary.scheme.as_deref().unwrap_or("https");
457 let port_suffix = match self.primary.port {
458 Some(p) => format!(":{p}"),
459 None => String::new(),
460 };
461 let primary = format!("{scheme}://{}{}", self.primary.host, port_suffix);
462
463 ClientLinks {
464 context: context.to_owned(),
465 links,
466 contexts: contexts_meta,
467 primary,
468 }
469 }
470
471 fn current_context(&self, options: &HrefOptions) -> Option<String> {
472 if let Some(route_name) = &options.current_route_name
473 && let Some(route) = self.routes.get(route_name)
474 {
475 return route.context.clone();
476 }
477 if let Some(host) = options
478 .request_host
479 .as_deref()
480 .and_then(ContextHosts::normalize_one)
481 && let Some(owner) = self.host_table.get(&host)
482 {
483 return Some(owner.clone());
484 }
485 options.context.clone()
486 }
487
488 fn resolve_name<'a>(
489 &'a self,
490 name: &'a str,
491 current: Option<&str>,
492 has_context: bool,
493 ) -> Result<&'a str, ContextError> {
494 if let Some((k, _)) = self.routes.get_key_value(name) {
495 return Ok(k.as_str());
496 }
497 if let Some(current_slug) = current
498 && let Some((as_prefix, _)) = self
499 .prefixes
500 .iter()
501 .find(|(_, slug)| slug == current_slug)
502 {
503 let candidate = format!("{as_prefix}.{name}");
504 if let Some((k, _)) = self.routes.get_key_value(&candidate) {
505 return Ok(k.as_str());
506 }
507 }
508 if !has_context {
509 return Err(ContextError::MissingContext {
510 name: name.to_owned(),
511 });
512 }
513 match self.short.get(name) {
514 Some(matches) if matches.len() == 1 => Ok(matches[0].as_str()),
515 Some(matches) if !matches.is_empty() => Err(ContextError::AmbiguousRoute {
516 name: name.to_owned(),
517 matches: matches.clone(),
518 }),
519 _ => Err(ContextError::RouteNotFound {
520 name: name.to_owned(),
521 }),
522 }
523 }
524}
525
526fn normalize_uri(uri: &str) -> String {
527 let trimmed = uri.trim_start_matches('/');
528 format!("/{trimmed}")
529}
530
531fn expand_uri_values(
533 route_name: &str,
534 template: &str,
535 params: &Map<String, Value>,
536) -> Result<String, ContextError> {
537 let mut used = BTreeSet::new();
538 let mut path_buf = String::with_capacity(template.len());
539 let mut rest = template;
540
541 while let Some(open) = rest.find('{') {
542 path_buf.push_str(&rest[..open]);
543 let after_open = &rest[open + 1..];
544 let Some(close) = after_open.find('}') else {
545 path_buf.push_str(&rest[open..]);
546 rest = "";
547 break;
548 };
549 let placeholder = &after_open[..close];
550 rest = &after_open[close + 1..];
551
552 let (raw_name, optional) = match placeholder.strip_suffix('?') {
553 Some(name) => (name, true),
554 None => (placeholder, false),
555 };
556 let clean_name = raw_name.trim_start_matches('*');
557 used.insert(clean_name.to_owned());
558
559 let scalar = match params.get(clean_name) {
560 None | Some(Value::Null) => None,
561 Some(Value::String(s)) if s.is_empty() => None,
562 Some(Value::String(s)) => Some(s.clone()),
563 Some(Value::Bool(true)) => Some("1".to_owned()),
564 Some(Value::Bool(false)) => None,
565 Some(Value::Number(n)) => Some(n.to_string()),
566 Some(other) => Some(other.to_string()),
567 };
568
569 match scalar {
570 Some(val) => {
571 for ch in val.chars() {
574 match ch {
575 '%' => path_buf.push_str("%25"),
576 '?' => path_buf.push_str("%3F"),
577 '#' => path_buf.push_str("%23"),
578 other => path_buf.push(other),
579 }
580 }
581 }
582 None if optional => {
583 if path_buf.ends_with('/') && (rest.is_empty() || rest.starts_with('/')) {
585 path_buf.pop();
586 }
587 }
588 None => {
589 return Err(ContextError::MissingParameter {
590 name: route_name.to_owned(),
591 param: clean_name.to_owned(),
592 });
593 }
594 }
595 }
596 path_buf.push_str(rest);
597
598 let trimmed = path_buf.trim_matches('/');
599 let encoded_path = encode_laravel_path(trimmed);
600
601 let mut query_parts = Vec::new();
602 for (key, value) in params {
603 if !used.contains(key.as_str()) {
604 append_query_value(value, key, &mut query_parts);
605 }
606 }
607
608 if query_parts.is_empty() {
609 Ok(format!("/{encoded_path}"))
610 } else {
611 Ok(format!("/{encoded_path}?{}", query_parts.join("&")))
612 }
613}
614
615fn encode_laravel_path(path: &str) -> String {
618 const ALLOWED: &[u8] = b"/@:;,=+!*|?&#%";
619 let encoded = percent_encode_rfc3986(path);
620 let bytes = encoded.as_bytes();
621 let mut out = String::with_capacity(encoded.len());
622 let mut i = 0;
623 while i < bytes.len() {
624 if bytes[i] == b'%' && i + 2 < bytes.len() {
625 if let Some(decoded) = decode_hex_byte(bytes[i + 1], bytes[i + 2])
626 && ALLOWED.contains(&decoded)
627 {
628 out.push(decoded as char);
629 i += 3;
630 continue;
631 }
632 }
633 out.push(bytes[i] as char);
634 i += 1;
635 }
636 out
637}
638
639fn append_query_value(value: &Value, key: &str, parts: &mut Vec<String>) {
640 match value {
641 Value::Null => {}
642 Value::Array(items) => {
643 for (idx, item) in items.iter().enumerate() {
644 append_query_value(item, &format!("{key}[{idx}]"), parts);
645 }
646 }
647 Value::Object(map) => {
648 for (child, entry) in map {
649 append_query_value(entry, &format!("{key}[{child}]"), parts);
650 }
651 }
652 Value::Bool(b) => {
653 parts.push(format!(
654 "{}={}",
655 percent_encode_rfc3986(key),
656 if *b { "1" } else { "0" }
657 ));
658 }
659 Value::Number(n) => {
660 parts.push(format!(
661 "{}={}",
662 percent_encode_rfc3986(key),
663 percent_encode_rfc3986(&n.to_string())
664 ));
665 }
666 Value::String(s) => {
667 parts.push(format!(
668 "{}={}",
669 percent_encode_rfc3986(key),
670 percent_encode_rfc3986(s)
671 ));
672 }
673 }
674}
675
676fn percent_encode_rfc3986(input: &str) -> String {
677 let mut out = String::with_capacity(input.len());
678 for byte in input.bytes() {
679 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
680 out.push(byte as char);
681 } else {
682 out.push('%');
683 out.push(hex_upper(byte >> 4));
684 out.push(hex_upper(byte & 0x0f));
685 }
686 }
687 out
688}
689
690fn decode_hex_byte(hi: u8, lo: u8) -> Option<u8> {
691 let h = from_hex_digit(hi)?;
692 let l = from_hex_digit(lo)?;
693 Some((h << 4) | l)
694}
695
696fn from_hex_digit(b: u8) -> Option<u8> {
697 match b {
698 b'0'..=b'9' => Some(b - b'0'),
699 b'A'..=b'F' => Some(b - b'A' + 10),
700 b'a'..=b'f' => Some(b - b'a' + 10),
701 _ => None,
702 }
703}
704
705fn hex_upper(nibble: u8) -> char {
706 match nibble {
707 0..=9 => (b'0' + nibble) as char,
708 _ => (b'A' + (nibble - 10)) as char,
709 }
710}
711
712fn parse_origin(raw: &str) -> ParsedOrigin {
713 let trimmed = raw.trim();
714 if trimmed.is_empty() {
715 return ParsedOrigin {
716 scheme: None,
717 host: "localhost".to_owned(),
718 port: None,
719 };
720 }
721
722 let (scheme, rest) = if let Some(pos) = trimmed.find("://") {
723 let s = trimmed[..pos].to_ascii_lowercase();
724 (Some(s), &trimmed[pos + 3..])
725 } else if let Some(stripped) = trimmed.strip_prefix("//") {
726 (None, stripped)
727 } else {
728 (None, trimmed)
729 };
730
731 let authority = rest.split('/').next().unwrap_or("");
732 let (host, port) = if let Some(after_bracket) = authority.strip_prefix('[') {
733 if let Some(end) = after_bracket.find(']') {
734 let h = &authority[..=end + 1];
735 let p = authority[end + 2..]
736 .strip_prefix(':')
737 .and_then(|s| s.parse::<u16>().ok());
738 (h.to_ascii_lowercase(), p)
739 } else {
740 (authority.to_ascii_lowercase(), None)
741 }
742 } else if let Some((h, p_str)) = authority.split_once(':') {
743 (h.to_ascii_lowercase(), p_str.parse::<u16>().ok())
744 } else {
745 (authority.to_ascii_lowercase(), None)
746 };
747
748 ParsedOrigin {
749 scheme,
750 host: if host.is_empty() {
751 "localhost".to_owned()
752 } else {
753 host
754 },
755 port,
756 }
757}