use http::HeaderMap;
use http::header::{CACHE_CONTROL, CONTENT_TYPE, HeaderValue, VARY};
pub const RSC_VARY: &str = "RSC, Next-Router-State-Tree, Next-Router-Prefetch";
pub const RSC_CACHE_CONTROL: &str = "public, max-age=60, stale-while-revalidate=300";
pub const HTML_NO_STORE: &str = "no-store, no-cache, must-revalidate, max-age=0";
pub(crate) fn clean(p: &str) -> String {
let mut segs: Vec<&str> = Vec::new();
for seg in p.split('/') {
match seg {
"" | "." => {}
".." => {
segs.pop();
}
s => segs.push(s),
}
}
let mut out = String::with_capacity(p.len() + 1);
for s in &segs {
out.push('/');
out.push_str(s);
}
if out.is_empty() {
out.push('/');
}
out
}
pub(crate) fn ext(p: &str) -> &str {
let base = &p[p.rfind('/').map_or(0, |i| i + 1)..];
base.rfind('.').map_or("", |i| &base[i..])
}
pub(crate) fn dir(p: &str) -> &str {
match p.rfind('/') {
Some(0) | None => "/",
Some(i) => &p[..i],
}
}
pub(crate) fn join(dir: &str, name: &str) -> String {
if dir == "/" {
format!("/{name}")
} else {
format!("{dir}/{name}")
}
}
pub fn is_rsc_payload(p: &str) -> bool {
let base = p.rsplit('/').next().unwrap_or(p).to_ascii_lowercase();
if !base.ends_with(".txt") {
return false;
}
base == "index.txt" || base.starts_with("__next.") || base.ends_with("__page__.txt")
}
fn set(headers: &mut HeaderMap, name: http::HeaderName, value: &'static str) {
headers.insert(name, HeaderValue::from_static(value));
}
pub fn set_headers(headers: &mut HeaderMap, url_path: &str) {
let lower = url_path.to_ascii_lowercase();
if is_rsc_payload(&lower) {
set(headers, CONTENT_TYPE, "text/x-component; charset=utf-8");
set(headers, VARY, RSC_VARY);
set(headers, CACHE_CONTROL, RSC_CACHE_CONTROL);
} else if lower == "/sw.js" {
set(headers, CONTENT_TYPE, "application/javascript; charset=utf-8");
set(headers, CACHE_CONTROL, "no-cache");
headers.insert("service-worker-allowed", HeaderValue::from_static("/"));
} else if lower == "/manifest.json" || lower.ends_with(".webmanifest") {
set(headers, CONTENT_TYPE, "application/manifest+json; charset=utf-8");
set(headers, CACHE_CONTROL, "public, max-age=300");
} else if lower == "/robots.txt" || lower == "/sitemap.xml" {
set(headers, CACHE_CONTROL, "public, max-age=3600");
if lower.ends_with(".txt") {
set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
}
} else if lower.starts_with("/_next/static/") {
set(headers, CACHE_CONTROL, "public, max-age=31536000, immutable");
} else if lower.ends_with(".txt") {
set(headers, CONTENT_TYPE, "text/plain; charset=utf-8");
} else if [
".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".otf",
]
.iter()
.any(|s| lower.ends_with(s))
{
set(headers, CACHE_CONTROL, "public, max-age=86400");
}
}
pub(crate) fn restore_rsc_dot_path(p: &str) -> Option<String> {
let idx = p.find("/__next.")?;
let dir_part = &p[..=idx];
let after = &p[idx + "/__next.".len()..];
if after.starts_with('_') {
return None;
}
let stem = after.strip_suffix(".txt")?;
let parts: Vec<&str> = stem.split('.').collect();
if parts.len() < 2 {
return None;
}
let mut out = format!("{dir_part}__next.{}", parts[0]);
for seg in &parts[1..parts.len() - 1] {
out.push('/');
out.push_str(seg);
}
out.push('/');
out.push_str(parts[parts.len() - 1]);
out.push_str(".txt");
Some(out)
}
fn split_last_dir(p: &str) -> Option<(&str, &str)> {
let slash = p.rfind('/')?;
let (d, base) = (&p[..slash], &p[slash + 1..]);
if d.is_empty() {
return None;
}
Some((dir(d), base))
}
pub(crate) fn placeholder_path(p: &str) -> Option<String> {
split_last_dir(p).map(|(parent, base)| join(&join(parent, "_"), base))
}
pub(crate) fn drop_last_dir(p: &str) -> Option<String> {
split_last_dir(p).map(|(parent, base)| join(parent, base))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clean_paths() {
for (input, want) in [
("/", "/"),
("//", "/"),
("/a/b/", "/a/b"),
("/a//b/./c", "/a/b/c"),
("/../../etc/passwd", "/etc/passwd"),
("/a/../../b", "/b"),
("/a/..", "/"),
("//evil.com", "/evil.com"),
] {
assert_eq!(clean(input), want, "{input}");
}
}
#[test]
fn ext_and_dir() {
assert_eq!(ext("/a/b.js"), ".js");
assert_eq!(ext("/v1.2/foo"), "");
assert_eq!(ext("/foo."), ".");
assert_eq!(ext("/"), "");
assert_eq!(dir("/a/b"), "/a");
assert_eq!(dir("/a"), "/");
assert_eq!(join("/", "x"), "/x");
assert_eq!(join("/a", "x"), "/a/x");
}
#[test]
fn rsc_payload() {
for (p, want) in [
("/index.txt", true),
("/INDEX.TXT", true),
("/about/__next._index.txt", true),
("/about/__next._head.txt", true),
("/about/__next._tree.txt", true),
("/about/__next._full.txt", true),
("/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt", true),
("/x/__PAGE__.txt", true),
("/robots.txt", false),
("/ads.txt", false),
("/.well-known/security.txt", false),
("/app.js", false),
] {
assert_eq!(is_rsc_payload(p), want, "{p}");
}
}
#[test]
fn restore_dot_path() {
let cases = [
(
"/admin/users/__next.!KGNvbnNvbGUp.admin.users.__PAGE__.txt",
Some("/admin/users/__next.!KGNvbnNvbGUp/admin/users/__PAGE__.txt"),
),
(
"/voddetail/123/__next.voddetail.$d$id.__PAGE__.txt",
Some("/voddetail/123/__next.voddetail/$d$id/__PAGE__.txt"),
),
("/about/__next._index.txt", None),
("/about/__next._tree.txt", None),
("/__next.__PAGE__.txt", None),
("/robots.txt", None),
];
for (input, want) in cases {
assert_eq!(restore_rsc_dot_path(input).as_deref(), want, "{input}");
}
}
#[test]
fn placeholder_and_parent() {
assert_eq!(
placeholder_path("/voddetail/123/index.html").as_deref(),
Some("/voddetail/_/index.html")
);
assert_eq!(placeholder_path("/123/index.html").as_deref(), Some("/_/index.html"));
assert_eq!(placeholder_path("/index.html"), None);
assert_eq!(drop_last_dir("/app/12345/index.txt").as_deref(), Some("/app/index.txt"));
assert_eq!(drop_last_dir("/app/index.txt").as_deref(), Some("/index.txt"));
assert_eq!(drop_last_dir("/index.txt"), None);
}
#[test]
fn header_classes() {
let check = |p: &str| {
let mut h = HeaderMap::new();
set_headers(&mut h, p);
h
};
let h = check("/about/__next._index.txt");
assert_eq!(h[CONTENT_TYPE], "text/x-component; charset=utf-8");
assert_eq!(h[VARY], RSC_VARY);
assert_eq!(h[CACHE_CONTROL], RSC_CACHE_CONTROL);
let h = check("/sw.js");
assert_eq!(h[CACHE_CONTROL], "no-cache");
assert_eq!(h["service-worker-allowed"], "/");
assert_eq!(
check("/manifest.json")[CONTENT_TYPE],
"application/manifest+json; charset=utf-8"
);
assert_eq!(check("/site.webmanifest")[CACHE_CONTROL], "public, max-age=300");
assert_eq!(check("/robots.txt")[CACHE_CONTROL], "public, max-age=3600");
assert!(check("/robots.txt").get(VARY).is_none());
assert_eq!(
check("/_NEXT/static/chunk.js")[CACHE_CONTROL],
"public, max-age=31536000, immutable"
);
assert_eq!(check("/ads.txt")[CONTENT_TYPE], "text/plain; charset=utf-8");
assert_eq!(check("/logo.PNG")[CACHE_CONTROL], "public, max-age=86400");
assert!(check("/app.js").is_empty());
}
}