Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

22.5 KB
Raw Blame
//! The mount prefixes read in the same file: express's `app.use("/api", router)`, koa-router's
//! `new Router({ prefix })` and `router.use("/x", r.routes())`, fastify's `register(plugin,
//! { prefix })`, hono's `basePath` and `route("/x", sub)`.
//!
//! Routes are listed only once the whole file is read: the order of statements does not matter.
//! A route set on an object created here (an application, a router, a plugin written in place)
//! climbs its mounts up to an application and takes the path composed by the rule of its
//! framework. A mount that cannot be followed (computed prefix, unknown parent, child that comes
//! from elsewhere, path that cannot be composed) keeps its site, and the route keeps its
//! relative path, marked as such.

use std::collections::{BTreeSet, HashMap};

use oxc_span::Span;

use super::{Collector, MAX_DEPTH};
use crate::obligations::Family;
use crate::obligations::surface::Found;

/// The detail of a route whose path is relative to a prefix that was not read.
pub(super) const RELATIVE: &str = "relative to a mount prefix that was not read";
/// The detail of a route set on an object whose origin is not known.
pub(super) const UNKNOWN_RECEIVER: &str = "receiver of unknown origin";

/// Beyond this depth of mounts, the path stays relative.
const MAX_MOUNTS: usize = 64;

/// The key of an expression: its start and its end, so that `new Hono()` and
/// `new Hono().basePath("/api")`, which start at the same place, stay distinct.
pub(super) fn key(span: Span) -> u64 {
    (u64::from(span.start) << 32) | u64::from(span.end)
}

/// The framework of an object created here, which sets how a prefix and a path are joined.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Kit {
    Express,
    Koa,
    Fastify,
    Hono,
}

/// An application is a root: not mounted, its paths are absolute. A router not mounted here may
/// be mounted elsewhere.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Role {
    App,
    Router,
}

/// The own prefix of an object (`new Router({ prefix })`, `basePath("/api")`).
#[derive(Clone)]
pub(super) enum Own {
    None,
    Prefix(String),
    /// A prefix that is not read (computed, spread options).
    Unread,
}

pub(super) struct Node {
    pub kit: Kit,
    pub role: Role,
    pub own: Own,
}

/// What an expression stands for in the mounts, judged once the file is read.
#[derive(Clone, PartialEq, Eq, Debug)]
pub(super) enum Foot {
    /// The expression of this key (`key`): an object created here if there is one.
    Expr(u64),
    /// A name, read at this position.
    Name(String, u32),
    /// Proven not to be a router: a function, a middleware from a package.
    NotRouter,
    Unknown,
}

pub(super) struct Mount {
    /// What is mounted (the arguments after the prefix).
    pub children: Vec<Foot>,
    /// The object it is mounted on.
    pub parent: Foot,
    /// The literal prefixes (`""` without a prefix); `None` if it is computed.
    pub prefixes: Option<Vec<String>>,
    /// The join rule; `None`: the parent's.
    pub join: Option<Kit>,
    /// The site the mount leaves if it is not resolved: (line, reason).
    pub site: Option<(u32, String)>,
    /// The site stays whatever happens (own prefix unreadable).
    pub forced: bool,
}

/// A route that was read, listed at the end.
pub(super) struct Pending {
    pub verb: String,
    pub path: String,
    pub line: u32,
    pub handler: Option<String>,
    pub foot: Foot,
    /// The object of the call is of unknown origin.
    pub unknown: bool,
}

/// A fastify plugin written in place: its parameter stands for the plugin instance in the
/// body of the function.
pub(super) struct Plugin {
    pub param: String,
    /// The key of the plugin among the objects created here.
    pub node: u64,
    pub start: u32,
    pub end: u32,
}

#[derive(Default)]
pub(super) struct Mounts {
    pub nodes: HashMap<u64, Node>,
    /// `const x = <expr>` and `x = <expr>`: the names and what they receive.
    pub vars: Vec<(String, Foot)>,
    pub mounts: Vec<Mount>,
    pub routes: Vec<Pending>,
    pub plugins: Vec<Plugin>,
    /// The object of the routing call being read, and whether it is of unknown origin.
    pub current: Option<(Foot, bool)>,
    /// koa-router's `router.prefix(x)`: (router, literal prefix, line).
    pub prefix_calls: Vec<(Foot, Option<String>, u32)>,
}

/// Joins a literal prefix and a path by the framework's rule; `None` if it cannot be composed
/// (a `*` path under express, koa-router or fastify).
fn join(kit: Kit, prefix: &str, path: &str) -> Option<String> {
    if prefix.is_empty() {
        return Some(path.to_string());
    }
    match kit {
        // pillarjs's `router` strips the prefix (without its trailing slash) from the URL.
        Kit::Express => {
            if path.starts_with('*') {
                return None;
            }
            let base = prefix.trim_end_matches('/');
            Some(if base.is_empty() {
                path.to_string()
            } else if path == "/" {
                base.to_string()
            } else {
                format!("{base}{path}")
            })
        }
        // `Layer#setPrefix` of @koa/router: `/` alone becomes the prefix, otherwise concatenation.
        Kit::Koa => {
            if path.starts_with('*') {
                return None;
            }
            Some(if path == "/" {
                prefix.to_string()
            } else {
                format!("{prefix}{path}")
            })
        }
        Kit::Fastify => {
            if path.starts_with('*') {
                return None;
            }
            Some(fastify_path(std::iter::once(prefix), path))
        }
        Kit::Hono => Some(merge_path(prefix, path)),
    }
}

/// hono's `mergePath` (`src/utils/url.ts`).
fn merge_path(base: &str, sub: &str) -> String {
    let lead = if base.starts_with('/') { "" } else { "/" };
    let tail = if sub == "/" {
        String::new()
    } else {
        let slash = if base.ends_with('/') { "" } else { "/" };
        format!("{slash}{}", sub.strip_prefix('/').unwrap_or(sub))
    };
    format!("{lead}{base}{tail}")
}

/// The path a route `path` gets under the plugin prefixes `prefixes`, from the outermost to the
/// innermost. fastify composes the prefixes first (`buildRoutePrefix`,
/// `lib/plugin-override.js`): an empty prefix changes nothing, one slash at the join, and a
/// prefix without a leading slash gets one (`prefix: 'v1'` serves `/v1/b`). The route is then
/// joined once (`lib/route.js`): `/` alone becomes the prefix, one slash at the join. Joining
/// level by level would lose the trailing slash of `/v1` + `/` + `/`, which fastify serves
/// under `/v1/`.
fn fastify_path<'a>(prefixes: impl Iterator<Item = &'a str>, path: &str) -> String {
    let mut prefix = String::new();
    for plugin in prefixes {
        if prefix.ends_with('/') {
            prefix.push_str(plugin.strip_prefix('/').unwrap_or(plugin));
        } else {
            if !plugin.is_empty() && !plugin.starts_with('/') {
                prefix.push('/');
            }
            prefix.push_str(plugin);
        }
    }
    if path == "/" && !prefix.is_empty() {
        prefix
    } else if prefix.ends_with('/') && path.starts_with('/') {
        format!("{prefix}{}", &path[1..])
    } else {
        format!("{prefix}{path}")
    }
}

/// A path being composed, from the route toward the application.
#[derive(Clone)]
struct Trail {
    /// The path, already composed for the frameworks that join level by level.
    path: String,
    /// fastify: the non-empty prefixes of the plugins crossed, from the innermost to the
    /// outermost. They are joined to the path only once all are read (`fastify_path`).
    plugins: Vec<String>,
}

impl Trail {
    fn new(path: String) -> Self {
        Self {
            path,
            plugins: Vec::new(),
        }
    }

    /// The path as it is known at this level.
    fn render(&self) -> String {
        if self.plugins.is_empty() {
            self.path.clone()
        } else {
            fastify_path(self.plugins.iter().rev().map(String::as_str), &self.path)
        }
    }

    /// The same path, mounted under `prefix`; `None` if it cannot be composed.
    fn under(&self, kit: Kit, prefix: &str) -> Option<Self> {
        if kit != Kit::Fastify {
            return join(kit, prefix, &self.render()).map(Self::new);
        }
        if prefix.is_empty() {
            return Some(self.clone());
        }
        if self.path.starts_with('*') {
            return None;
        }
        // A prefix that ends with `/` above a prefix without a leading slash: fastify 4 serves
        // `/v1//x`, fastify 5 `/v1/x`. The code does not choose between them: no path is composed.
        if prefix.ends_with('/') && self.plugins.last().is_some_and(|p| !p.starts_with('/')) {
            return None;
        }
        let mut plugins = self.plugins.clone();
        plugins.push(prefix.to_string());
        Some(Self {
            path: self.path.clone(),
            plugins,
        })
    }
}

impl Collector {
    /// The object created here that `foot` stands for.
    fn mount_node(&self, foot: &Foot, depth: usize) -> Option<u64> {
        if depth > MAX_DEPTH {
            return None;
        }
        match foot {
            Foot::Expr(start) => self.mounts.nodes.contains_key(start).then_some(*start),
            Foot::Name(name, at) => {
                // The parameter of a plugin written in place, the innermost one.
                let plugins: Vec<&Plugin> = self
                    .mounts
                    .plugins
                    .iter()
                    .filter(|p| p.param == *name)
                    .collect();
                if let Some(plugin) = plugins
                    .iter()
                    .filter(|p| p.start <= *at && *at < p.end)
                    .min_by_key(|p| p.end - p.start)
                {
                    // Another binding of the same name may shadow it: without scopes, it is not
                    // followed.
                    let others = self.bindings.count(name) as usize > plugins.len();
                    return (!others).then_some(plugin.node);
                }
                if self.bindings.is_ambiguous(name) {
                    return None;
                }
                let mut values = self.mounts.vars.iter().filter(|(n, _)| n == name);
                match (values.next(), values.next()) {
                    (Some((_, value)), None) => self.mount_node(value, depth + 1),
                    _ => None,
                }
            }
            Foot::NotRouter | Foot::Unknown => None,
        }
    }

    /// The paths under which a route set on `node` is served: (path, relative).
    /// `broken`: the mounts through which a path could not be composed. `cycle`: the mounts
    /// go in a circle (or go too deep), no composed path is safe.
    fn expand(
        &self,
        node: u64,
        trail: Trail,
        visited: &mut Vec<u64>,
        out: &mut BTreeSet<(String, bool)>,
        broken: &mut BTreeSet<usize>,
        cycle: &mut bool,
    ) {
        let Some(current) = self.mounts.nodes.get(&node) else {
            out.insert((trail.render(), true));
            return;
        };
        if visited.len() > MAX_MOUNTS || visited.contains(&node) {
            *cycle = true;
            return;
        }
        let trail = match &current.own {
            Own::None => trail,
            Own::Prefix(prefix) => match trail.under(current.kit, prefix) {
                Some(joined) => joined,
                None => {
                    out.insert((trail.render(), true));
                    return;
                }
            },
            Own::Unread => {
                out.insert((trail.render(), true));
                return;
            }
        };
        let ups: Vec<usize> = self
            .mounts
            .mounts
            .iter()
            .enumerate()
            .filter(|(_, m)| {
                m.children
                    .iter()
                    .any(|c| self.mount_node(c, 0) == Some(node))
            })
            .map(|(i, _)| i)
            .collect();
        if ups.is_empty() {
            out.insert((trail.render(), current.role == Role::Router));
            return;
        }
        visited.push(node);
        for index in ups {
            let mount = &self.mounts.mounts[index];
            let parent = self.mount_node(&mount.parent, 0).filter(|p| {
                self.mounts
                    .nodes
                    .get(p)
                    .is_some_and(|n| n.kit == current.kit)
            });
            match (parent, &mount.prefixes) {
                (Some(parent), Some(prefixes)) => {
                    for prefix in prefixes {
                        match trail.under(mount.join.unwrap_or(current.kit), prefix) {
                            Some(joined) => {
                                self.expand(parent, joined, visited, out, broken, cycle);
                            }
                            None => {
                                broken.insert(index);
                                out.insert((trail.render(), true));
                            }
                        }
                    }
                }
                _ => {
                    out.insert((trail.render(), true));
                }
            }
        }
        visited.pop();
    }

    /// Is the mount fully followed (literal prefixes, parent and children created here)?
    fn mount_resolved(&self, mount: &Mount) -> bool {
        let Some(parent) = self.mount_node(&mount.parent, 0) else {
            return false;
        };
        let Some(kit) = self.mounts.nodes.get(&parent).map(|n| n.kit) else {
            return false;
        };
        let mut routers = 0;
        for child in &mount.children {
            match child {
                Foot::NotRouter => {}
                other => match self.mount_node(other, 0) {
                    Some(node) if self.mounts.nodes.get(&node).is_some_and(|n| n.kit == kit) => {
                        routers += 1;
                    }
                    _ => return false,
                },
            }
        }
        !mount.forced && mount.prefixes.is_some() && routers > 0
    }

    /// koa-router's `router.prefix("/api")`: a single literal call on a router created here
    /// without a prefix becomes its own prefix (without a trailing slash, as `Router#prefix`).
    /// Any other case makes the router's prefix unreadable and leaves a site.
    fn apply_prefix_calls(&mut self) {
        let calls = std::mem::take(&mut self.mounts.prefix_calls);
        let targets: Vec<Option<u64>> = calls
            .iter()
            .map(|(f, _, _)| self.mount_node(f, 0))
            .collect();
        for (index, (_, prefix, line)) in calls.iter().enumerate() {
            let target = targets[index];
            let alone = targets.iter().filter(|t| **t == target).count() == 1;
            let node = target.and_then(|t| self.mounts.nodes.get_mut(&t).map(|n| (t, n)));
            match (node, prefix) {
                (Some((_, node)), Some(prefix))
                    if alone
                        && node.kit == Kit::Koa
                        && node.role == Role::Router
                        && matches!(node.own, Own::None) =>
                {
                    let trimmed = prefix.trim_end_matches('/');
                    node.own = Own::Prefix(trimmed.to_string());
                }
                (node, prefix) => {
                    if let Some((_, node)) = node {
                        node.own = Own::Unread;
                    }
                    let reason = super::routes::prefix_reason(prefix.as_deref());
                    self.unresolved_at(Family::Route, *line, &reason);
                }
            }
        }
    }

    /// Lists the routes that were read, with their composed paths, and the sites of the mounts
    /// that were not followed.
    pub(super) fn emit_routes(&mut self) {
        self.apply_prefix_calls();
        let routes = std::mem::take(&mut self.mounts.routes);
        let mut broken = BTreeSet::new();
        let mut unknown = Vec::new();
        let mut cyclic = Vec::new();
        for route in &routes {
            let node = self.mount_node(&route.foot, 0);
            let paths = match node {
                Some(node) => {
                    let mut out = BTreeSet::new();
                    let mut cycle = false;
                    self.expand(
                        node,
                        Trail::new(route.path.clone()),
                        &mut Vec::new(),
                        &mut out,
                        &mut broken,
                        &mut cycle,
                    );
                    if cycle {
                        // The path as written, relative: a composed prefix would be invented.
                        out = BTreeSet::from([(route.path.clone(), true)]);
                        cyclic.push(route.line);
                    }
                    // A path served both under a root and relatively: relative.
                    let relative: BTreeSet<&String> =
                        out.iter().filter(|(_, r)| *r).map(|(p, _)| p).collect();
                    out.iter()
                        .filter(|(p, r)| *r || !relative.contains(p))
                        .cloned()
                        .collect::<Vec<_>>()
                }
                None => vec![(route.path.clone(), false)],
            };
            let unknown_origin = node.is_none() && route.unknown;
            if unknown_origin {
                unknown.push(route.line);
            }
            for (path, relative) in paths {
                let notes: Vec<&str> = route
                    .handler
                    .as_deref()
                    .into_iter()
                    .chain(relative.then_some(RELATIVE))
                    .chain(unknown_origin.then_some(UNKNOWN_RECEIVER))
                    .collect();
                let detail = (!notes.is_empty()).then(|| notes.join("; "));
                self.out.found.push(Found {
                    family: Family::Route,
                    name: format!("{} {path}", route.verb),
                    line: route.line,
                    scope: None,
                    detail,
                });
            }
        }
        if let Some(first) = unknown.iter().min() {
            let reason = format!(
                "{} route(s) declared on an object whose origin is not known; they may not be routes",
                unknown.len()
            );
            self.unresolved_at(Family::Route, *first, &reason);
        }
        // A cycle breaks no mount in particular: without this site, the family would stay
        // enumerated while some listed paths are relative.
        if let Some(first) = cyclic.iter().min() {
            let reason = format!(
                "{} route(s) sit under mounts that form a cycle or nest too deeply; listed paths under them are relative",
                cyclic.len()
            );
            self.unresolved_at(Family::Route, *first, &reason);
        }
        let sites: Vec<(u32, String)> = self
            .mounts
            .mounts
            .iter()
            .enumerate()
            .filter(|(i, m)| broken.contains(i) || !self.mount_resolved(m))
            .filter_map(|(_, m)| m.site.clone())
            .collect();
        for (line, reason) in sites {
            self.unresolved_at(Family::Route, line, &reason);
        }
    }
}

#[cfg(test)]
mod join_tests {
    use super::{Kit, Trail, fastify_path, join, merge_path};

    #[test]
    fn each_framework_joins_its_own_way() {
        assert_eq!(
            join(Kit::Express, "/api", "/users").as_deref(),
            Some("/api/users")
        );
        assert_eq!(
            join(Kit::Express, "/api/", "/users").as_deref(),
            Some("/api/users")
        );
        assert_eq!(join(Kit::Express, "/api", "/").as_deref(), Some("/api"));
        assert_eq!(join(Kit::Express, "/api", "*"), None);
        assert_eq!(join(Kit::Koa, "/api", "/").as_deref(), Some("/api"));
        assert_eq!(join(Kit::Koa, "/api/", "/x").as_deref(), Some("/api//x"));
        assert_eq!(join(Kit::Fastify, "/v1", "/").as_deref(), Some("/v1"));
        assert_eq!(join(Kit::Fastify, "/v1/", "/b").as_deref(), Some("/v1/b"));
        assert_eq!(join(Kit::Fastify, "/v1", "*"), None);
        assert_eq!(join(Kit::Fastify, "v1", "/b").as_deref(), Some("/v1/b"));
        assert_eq!(join(Kit::Fastify, "v1", "/").as_deref(), Some("/v1"));
        assert_eq!(join(Kit::Fastify, "", "/").as_deref(), Some("/"));
        assert_eq!(join(Kit::Hono, "/books", "/").as_deref(), Some("/books"));
        assert_eq!(join(Kit::Hono, "/api", "*").as_deref(), Some("/api/*"));
        assert_eq!(merge_path("api", "x"), "/api/x");
        assert_eq!(merge_path("/api/", "/x"), "/api/x");
        assert_eq!(join(Kit::Koa, "", "/x").as_deref(), Some("/x"));
    }
    /// The path of a route under fastify plugins, given from the inside to the outside.
    fn nested(path: &str, inner_to_outer: &[&str]) -> Option<String> {
        let mut trail = Trail::new(path.to_string());
        for prefix in inner_to_outer {
            trail = trail.under(Kit::Fastify, prefix)?;
        }
        Some(trail.render())
    }

    #[test]
    fn fastify_composes_plugin_prefixes_before_joining_the_route() {
        assert_eq!(nested("/c", &["x", "v1"]).as_deref(), Some("/v1/x/c"));
        assert_eq!(nested("/c", &["/x", "/v1"]).as_deref(), Some("/v1/x/c"));
        assert_eq!(nested("/c", &["/x", "/v1/"]).as_deref(), Some("/v1/x/c"));
        assert_eq!(nested("/c", &["/x/", "v1"]).as_deref(), Some("/v1/x/c"));
        // An inner plugin under `/`: the trailing slash stays, fastify serves `/v1/` not `/v1`.
        assert_eq!(nested("/", &["/", "v1"]).as_deref(), Some("/v1/"));
        assert_eq!(nested("/", &["/", "/v1"]).as_deref(), Some("/v1/"));
        assert_eq!(nested("/c", &["/", "/v1"]).as_deref(), Some("/v1/c"));
        assert_eq!(nested("/", &["x", "v1"]).as_deref(), Some("/v1/x"));
        // A plugin without a prefix changes nothing, wherever it is.
        assert_eq!(
            nested("/c", &["", "x", "", "v1", ""]).as_deref(),
            Some("/v1/x/c")
        );
        assert_eq!(nested("/", &["", ""]).as_deref(), Some("/"));
        assert_eq!(nested("/", &["/"]).as_deref(), Some("/"));
        // fastify 4 and 5 do not join `/v1/` and `x` the same way: no path is composed.
        assert_eq!(nested("/c", &["x", "/v1/"]), None);
        assert_eq!(nested("/c", &["x/", "/"]), None);
        assert_eq!(nested("/c", &["x", "", "v1/"]), None);
        assert_eq!(nested("*", &["v1"]), None);
        assert_eq!(nested("*", &[""]).as_deref(), Some("*"));
        assert_eq!(fastify_path(["/a/", "/b"].into_iter(), "/c"), "/a/b/c");
    }
}