use std::collections::{BTreeMap, BTreeSet};
use laravel::http::Request;
use serde::Serialize;
use serde_json::{Map, Value};
use super::hosts::{ContextError, ContextHosts};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextTarget {
#[default]
WebHydrate,
SpaOnly,
Native,
Api,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ContextLinksRule {
#[default]
Public,
Ability(String),
Private,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContextSpec {
pub slug: String,
pub as_prefix: String,
pub hosts: Vec<String>,
pub prefix: String,
pub target: ContextTarget,
pub links_rule: ContextLinksRule,
pub priority: i32,
}
impl ContextSpec {
pub fn new(slug: impl Into<String>) -> Self {
let slug = slug.into();
Self {
as_prefix: slug.clone(),
slug,
hosts: Vec::new(),
prefix: String::new(),
target: ContextTarget::default(),
links_rule: ContextLinksRule::default(),
priority: 0,
}
}
pub fn with_as(mut self, as_prefix: impl Into<String>) -> Self {
self.as_prefix = as_prefix.into();
self
}
pub fn with_hosts<I, S>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.hosts = ContextHosts::normalize(hosts);
self
}
pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = prefix.into();
self
}
pub fn with_target(mut self, target: ContextTarget) -> Self {
self.target = target;
self
}
pub fn with_links_rule(mut self, rule: ContextLinksRule) -> Self {
self.links_rule = rule;
self
}
pub fn with_priority(mut self, priority: i32) -> Self {
self.priority = priority;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouteEntry {
pub full_name: String,
pub context: Option<String>,
pub uri: String,
pub hosts: Vec<String>,
}
impl RouteEntry {
pub fn new(full_name: impl Into<String>, uri: impl Into<String>) -> Self {
Self {
full_name: full_name.into(),
context: None,
uri: uri.into(),
hosts: Vec::new(),
}
}
pub fn with_context(mut self, context: impl Into<String>) -> Self {
self.context = Some(context.into());
self
}
pub fn with_hosts<I, S>(mut self, hosts: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.hosts = ContextHosts::normalize(hosts);
self
}
}
#[derive(Debug, Clone, Default)]
pub struct HrefOptions {
pub context: Option<String>,
pub absolute: bool,
pub request_host: Option<String>,
pub request_scheme: Option<String>,
pub request_port: Option<u16>,
pub current_route_name: Option<String>,
}
impl HrefOptions {
pub fn from_request(request: &Request) -> Self {
let origin = request.origin();
let parsed = parse_origin(&origin);
let host = ContextHosts::normalize_one(&request.host());
let scheme = if request.is_secure() {
"https".to_owned()
} else {
parsed.scheme.unwrap_or_else(|| "http".to_owned())
};
Self {
context: None,
absolute: false,
request_host: host,
request_scheme: Some(scheme),
request_port: parsed.port,
current_route_name: None,
}
}
pub fn from_url(url: &str, context: Option<&str>) -> Self {
let parsed = parse_origin(url);
Self {
context: context.map(str::to_owned),
absolute: false,
request_host: Some(parsed.host),
request_scheme: parsed.scheme,
request_port: parsed.port,
current_route_name: None,
}
}
pub fn with_context(mut self, context: impl Into<String>) -> Self {
self.context = Some(context.into());
self
}
pub fn absolute(mut self) -> Self {
self.absolute = true;
self
}
pub fn with_current_route_name(mut self, route_name: impl Into<String>) -> Self {
self.current_route_name = Some(route_name.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientLinkEntry {
pub context: String,
pub uri: String,
pub hosts: Option<Vec<String>>,
}
impl Serialize for ClientLinkEntry {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq;
let len = if self.hosts.is_some() { 3 } else { 2 };
let mut seq = serializer.serialize_seq(Some(len))?;
seq.serialize_element(&self.context)?;
seq.serialize_element(&self.uri)?;
if let Some(hosts) = &self.hosts {
seq.serialize_element(hosts)?;
}
seq.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ClientContextMeta {
#[serde(rename = "as")]
pub as_prefix: String,
pub hosts: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ClientLinks {
pub context: String,
pub links: BTreeMap<String, ClientLinkEntry>,
pub contexts: BTreeMap<String, ClientContextMeta>,
pub primary: String,
}
#[derive(Debug, Clone)]
struct IndexedRoute {
uri: String,
context: Option<String>,
hosts: Vec<String>,
}
#[derive(Debug, Clone)]
struct ParsedOrigin {
scheme: Option<String>,
host: String,
port: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct RouteIndex {
contexts: BTreeMap<String, ContextSpec>,
host_table: BTreeMap<String, String>,
prefixes: Vec<(String, String)>,
routes: BTreeMap<String, IndexedRoute>,
short: BTreeMap<String, Vec<String>>,
primary: ParsedOrigin,
}
impl RouteIndex {
pub fn new(
contexts: Vec<ContextSpec>,
entries: Vec<RouteEntry>,
primary_url: &str,
) -> Result<Self, ContextError> {
let host_table = ContextHosts::table(&contexts)?;
let mut context_map = BTreeMap::new();
let mut prefixes = Vec::new();
for ctx in contexts {
if !ctx.as_prefix.is_empty() {
prefixes.push((ctx.as_prefix.clone(), ctx.slug.clone()));
}
context_map.insert(ctx.slug.clone(), ctx);
}
prefixes.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
let mut routes = BTreeMap::new();
let mut short: BTreeMap<String, Vec<String>> = BTreeMap::new();
for entry in entries {
if routes.contains_key(&entry.full_name) {
continue;
}
let mut resolved_ctx = entry.context.clone();
let mut matched_as = None;
for (as_prefix, slug) in &prefixes {
if let Some(rest) = entry.full_name.strip_prefix(&format!("{as_prefix}.")) {
if resolved_ctx.is_none() {
resolved_ctx = Some(slug.clone());
}
matched_as = Some(rest.to_owned());
break;
}
}
if let Some(short_name) = matched_as {
short
.entry(short_name)
.or_default()
.push(entry.full_name.clone());
}
let hosts = if !entry.hosts.is_empty() {
entry.hosts
} else if let Some(ctx_slug) = &resolved_ctx {
context_map
.get(ctx_slug)
.map(|c| c.hosts.clone())
.unwrap_or_default()
} else {
Vec::new()
};
routes.insert(
entry.full_name,
IndexedRoute {
uri: normalize_uri(&entry.uri),
context: resolved_ctx,
hosts,
},
);
}
Ok(Self {
contexts: context_map,
host_table,
prefixes,
routes,
short,
primary: parse_origin(primary_url),
})
}
pub fn href(
&self,
name: &str,
params: &BTreeMap<String, String>,
options: &HrefOptions,
) -> Result<String, ContextError> {
let mut map = Map::new();
for (k, v) in params {
map.insert(k.clone(), Value::String(v.clone()));
}
self.href_values(name, &map, options)
}
pub fn href_values(
&self,
name: &str,
params: &Map<String, Value>,
options: &HrefOptions,
) -> Result<String, ContextError> {
let has_request =
options.request_host.is_some() || options.current_route_name.is_some();
let current = self.current_context(options);
let full = self.resolve_name(
name,
current.as_deref(),
has_request || options.context.is_some(),
)?;
let route = &self.routes[full];
let path = expand_uri_values(full, &route.uri, params)?;
let req_host = options
.request_host
.as_deref()
.and_then(ContextHosts::normalize_one);
let same_host = route.hosts.is_empty()
|| req_host
.as_ref()
.is_some_and(|h| route.hosts.contains(h));
if has_request && route.context == current && same_host && !options.absolute {
return Ok(path);
}
let mut used_primary = false;
let use_host = if !route.hosts.is_empty() {
if let Some(h) = &req_host
&& route.hosts.contains(h)
{
h.clone()
} else {
route.hosts[0].clone()
}
} else if let Some(h) = &req_host
&& !self.host_table.contains_key(h)
{
h.clone()
} else {
used_primary = true;
self.primary.host.clone()
};
let scheme = if used_primary {
self.primary
.scheme
.as_deref()
.or(options.request_scheme.as_deref())
.unwrap_or("https")
} else {
options
.request_scheme
.as_deref()
.or(self.primary.scheme.as_deref())
.unwrap_or("https")
};
let request_port = options.request_port.filter(|p| *p != 80 && *p != 443);
let port = if req_host.as_deref() == Some(use_host.as_str()) {
request_port
} else {
self.primary.port.or(request_port)
};
let default_port = if scheme == "https" { 443 } else { 80 };
let port_suffix = match port {
Some(p) if p != default_port => format!(":{p}"),
_ => String::new(),
};
Ok(format!("{scheme}://{use_host}{port_suffix}{path}"))
}
pub fn client_links(&self, context: &str, allowed_abilities: &[&str]) -> ClientLinks {
let mut allowed: BTreeMap<String, bool> = BTreeMap::new();
for (slug, spec) in &self.contexts {
if slug == context {
continue;
}
let is_allowed = match &spec.links_rule {
ContextLinksRule::Public => true,
ContextLinksRule::Ability(ability) => allowed_abilities.contains(&ability.as_str()),
ContextLinksRule::Private => false,
};
allowed.insert(slug.clone(), is_allowed);
}
let mut links = BTreeMap::new();
for (name, route) in &self.routes {
let Some(slug) = &route.context else {
continue;
};
let ctx_hosts = self
.contexts
.get(slug)
.map(|c| c.hosts.as_slice())
.unwrap_or(&[]);
let overrides_hosts = route.hosts.as_slice() != ctx_hosts;
if *allowed.get(slug).unwrap_or(&false) || (slug == context && overrides_hosts) {
links.insert(
name.clone(),
ClientLinkEntry {
context: slug.clone(),
uri: route.uri.clone(),
hosts: overrides_hosts.then(|| route.hosts.clone()),
},
);
}
}
let mut contexts_meta = BTreeMap::new();
for (slug, spec) in &self.contexts {
if slug == context
|| *allowed.get(slug).unwrap_or(&false)
|| !spec.hosts.is_empty()
{
contexts_meta.insert(
slug.clone(),
ClientContextMeta {
as_prefix: spec.as_prefix.clone(),
hosts: spec.hosts.clone(),
},
);
}
}
let scheme = self.primary.scheme.as_deref().unwrap_or("https");
let port_suffix = match self.primary.port {
Some(p) => format!(":{p}"),
None => String::new(),
};
let primary = format!("{scheme}://{}{}", self.primary.host, port_suffix);
ClientLinks {
context: context.to_owned(),
links,
contexts: contexts_meta,
primary,
}
}
fn current_context(&self, options: &HrefOptions) -> Option<String> {
if let Some(route_name) = &options.current_route_name
&& let Some(route) = self.routes.get(route_name)
{
return route.context.clone();
}
if let Some(host) = options
.request_host
.as_deref()
.and_then(ContextHosts::normalize_one)
&& let Some(owner) = self.host_table.get(&host)
{
return Some(owner.clone());
}
options.context.clone()
}
fn resolve_name<'a>(
&'a self,
name: &'a str,
current: Option<&str>,
has_context: bool,
) -> Result<&'a str, ContextError> {
if let Some((k, _)) = self.routes.get_key_value(name) {
return Ok(k.as_str());
}
if let Some(current_slug) = current
&& let Some((as_prefix, _)) = self
.prefixes
.iter()
.find(|(_, slug)| slug == current_slug)
{
let candidate = format!("{as_prefix}.{name}");
if let Some((k, _)) = self.routes.get_key_value(&candidate) {
return Ok(k.as_str());
}
}
if !has_context {
return Err(ContextError::MissingContext {
name: name.to_owned(),
});
}
match self.short.get(name) {
Some(matches) if matches.len() == 1 => Ok(matches[0].as_str()),
Some(matches) if !matches.is_empty() => Err(ContextError::AmbiguousRoute {
name: name.to_owned(),
matches: matches.clone(),
}),
_ => Err(ContextError::RouteNotFound {
name: name.to_owned(),
}),
}
}
}
fn normalize_uri(uri: &str) -> String {
let trimmed = uri.trim_start_matches('/');
format!("/{trimmed}")
}
fn expand_uri_values(
route_name: &str,
template: &str,
params: &Map<String, Value>,
) -> Result<String, ContextError> {
let mut used = BTreeSet::new();
let mut path_buf = String::with_capacity(template.len());
let mut rest = template;
while let Some(open) = rest.find('{') {
path_buf.push_str(&rest[..open]);
let after_open = &rest[open + 1..];
let Some(close) = after_open.find('}') else {
path_buf.push_str(&rest[open..]);
rest = "";
break;
};
let placeholder = &after_open[..close];
rest = &after_open[close + 1..];
let (raw_name, optional) = match placeholder.strip_suffix('?') {
Some(name) => (name, true),
None => (placeholder, false),
};
let clean_name = raw_name.trim_start_matches('*');
used.insert(clean_name.to_owned());
let scalar = match params.get(clean_name) {
None | Some(Value::Null) => None,
Some(Value::String(s)) if s.is_empty() => None,
Some(Value::String(s)) => Some(s.clone()),
Some(Value::Bool(true)) => Some("1".to_owned()),
Some(Value::Bool(false)) => None,
Some(Value::Number(n)) => Some(n.to_string()),
Some(other) => Some(other.to_string()),
};
match scalar {
Some(val) => {
for ch in val.chars() {
match ch {
'%' => path_buf.push_str("%25"),
'?' => path_buf.push_str("%3F"),
'#' => path_buf.push_str("%23"),
other => path_buf.push(other),
}
}
}
None if optional => {
if path_buf.ends_with('/') && (rest.is_empty() || rest.starts_with('/')) {
path_buf.pop();
}
}
None => {
return Err(ContextError::MissingParameter {
name: route_name.to_owned(),
param: clean_name.to_owned(),
});
}
}
}
path_buf.push_str(rest);
let trimmed = path_buf.trim_matches('/');
let encoded_path = encode_laravel_path(trimmed);
let mut query_parts = Vec::new();
for (key, value) in params {
if !used.contains(key.as_str()) {
append_query_value(value, key, &mut query_parts);
}
}
if query_parts.is_empty() {
Ok(format!("/{encoded_path}"))
} else {
Ok(format!("/{encoded_path}?{}", query_parts.join("&")))
}
}
fn encode_laravel_path(path: &str) -> String {
const ALLOWED: &[u8] = b"/@:;,=+!*|?&#%";
let encoded = percent_encode_rfc3986(path);
let bytes = encoded.as_bytes();
let mut out = String::with_capacity(encoded.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Some(decoded) = decode_hex_byte(bytes[i + 1], bytes[i + 2])
&& ALLOWED.contains(&decoded)
{
out.push(decoded as char);
i += 3;
continue;
}
}
out.push(bytes[i] as char);
i += 1;
}
out
}
fn append_query_value(value: &Value, key: &str, parts: &mut Vec<String>) {
match value {
Value::Null => {}
Value::Array(items) => {
for (idx, item) in items.iter().enumerate() {
append_query_value(item, &format!("{key}[{idx}]"), parts);
}
}
Value::Object(map) => {
for (child, entry) in map {
append_query_value(entry, &format!("{key}[{child}]"), parts);
}
}
Value::Bool(b) => {
parts.push(format!(
"{}={}",
percent_encode_rfc3986(key),
if *b { "1" } else { "0" }
));
}
Value::Number(n) => {
parts.push(format!(
"{}={}",
percent_encode_rfc3986(key),
percent_encode_rfc3986(&n.to_string())
));
}
Value::String(s) => {
parts.push(format!(
"{}={}",
percent_encode_rfc3986(key),
percent_encode_rfc3986(s)
));
}
}
}
fn percent_encode_rfc3986(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for byte in input.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(byte as char);
} else {
out.push('%');
out.push(hex_upper(byte >> 4));
out.push(hex_upper(byte & 0x0f));
}
}
out
}
fn decode_hex_byte(hi: u8, lo: u8) -> Option<u8> {
let h = from_hex_digit(hi)?;
let l = from_hex_digit(lo)?;
Some((h << 4) | l)
}
fn from_hex_digit(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'A'..=b'F' => Some(b - b'A' + 10),
b'a'..=b'f' => Some(b - b'a' + 10),
_ => None,
}
}
fn hex_upper(nibble: u8) -> char {
match nibble {
0..=9 => (b'0' + nibble) as char,
_ => (b'A' + (nibble - 10)) as char,
}
}
fn parse_origin(raw: &str) -> ParsedOrigin {
let trimmed = raw.trim();
if trimmed.is_empty() {
return ParsedOrigin {
scheme: None,
host: "localhost".to_owned(),
port: None,
};
}
let (scheme, rest) = if let Some(pos) = trimmed.find("://") {
let s = trimmed[..pos].to_ascii_lowercase();
(Some(s), &trimmed[pos + 3..])
} else if let Some(stripped) = trimmed.strip_prefix("//") {
(None, stripped)
} else {
(None, trimmed)
};
let authority = rest.split('/').next().unwrap_or("");
let (host, port) = if let Some(after_bracket) = authority.strip_prefix('[') {
if let Some(end) = after_bracket.find(']') {
let h = &authority[..=end + 1];
let p = authority[end + 2..]
.strip_prefix(':')
.and_then(|s| s.parse::<u16>().ok());
(h.to_ascii_lowercase(), p)
} else {
(authority.to_ascii_lowercase(), None)
}
} else if let Some((h, p_str)) = authority.split_once(':') {
(h.to_ascii_lowercase(), p_str.parse::<u16>().ok())
} else {
(authority.to_ascii_lowercase(), None)
};
ParsedOrigin {
scheme,
host: if host.is_empty() {
"localhost".to_owned()
} else {
host
},
port,
}
}