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.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! Surface detector for TypeScript/JavaScript: commands, flags, routes and environment
//! variables, read from the syntax tree (never from the text: strings and comments do not
//! count).
//!
//! The detector fails on the safe side: a site that is seen but cannot be enumerated (computed
//! name, options object passed as a variable, `process.argv` read by hand, raw HTTP server...)
//! is listed in `Surface::unresolved` with its reason, never ignored.
use std::collections::{HashMap, HashSet};
use oxc_allocator::Allocator;
use oxc_ast::ast::{
AssignmentExpression, BinaryExpression, CallExpression, ComputedMemberExpression,
ExportSpecifier, IdentifierReference, NewExpression, StaticMemberExpression, SwitchStatement,
TSClassImplements, TSInterfaceDeclaration, TSTypeAliasDeclaration, TSTypeName, TSTypeQuery,
TSTypeReference, UnaryExpression, VariableDeclarator,
};
use oxc_ast_visit::{Visit, walk};
use oxc_parser::Parser;
use oxc_span::{SourceType, Span};
use super::Family;
use super::surface::{Found, Surface, UnresolvedInFile};
use bindings::Bindings;
use constants::Constants;
use imports::Imports;
use syntax::Lines;
mod bindings;
mod cli;
mod constants;
mod env;
mod imports;
#[cfg(test)]
mod leak_tests;
mod leaks;
mod manual;
mod mounts;
mod packages;
mod parsed;
mod routes;
mod strings;
mod syntax;
#[cfg(test)]
mod tests;
/// The argument-parsing packages that no detector reads.
const UNSUPPORTED_PARSERS: &[&str] = &[
"minimist",
"meow",
"cac",
"arg",
"command-line-args",
"oclif",
"@oclif/core",
"clipanion",
"citty",
"sade",
"mri",
"caporal",
"@caporal/core",
"yargs-parser",
"optionator",
"nopt",
"getopts",
];
/// The server frameworks whose routes are read (package names).
const FRAMEWORKS: &[&str] = &[
"express",
"koa-router",
"@koa/router",
"fastify",
"hono",
"@tinyhttp/app",
"restify",
"polka",
"itty-router",
"@hapi/hapi",
];
/// The HTTP modules of Node: their `createServer` calls are raw servers.
const HTTP_MODULES: &[&str] = &["http", "https", "http2"];
/// The environment configuration libraries that no detector reads: the names they read are not
/// visible. `dotenv` is not one of them: its reads go through `process.env`.
const ENV_LIBRARIES: &[&str] = &[
"env-var",
"envalid",
"convict",
"config",
"nconf",
"@nestjs/config",
"@t3-oss/env-core",
"@t3-oss/env-nextjs",
"znv",
"dotenv-safe",
"dotenv-flow",
];
/// The server frameworks whose routes no detector reads (exact packages). Next, Remix,
/// SvelteKit and Nuxt are not here: their routes are files, read by `file_convention`.
const OTHER_SERVERS: &[&str] = &[
"@nestjs/common",
"@nestjs/core",
"h3",
"nitropack",
"@trpc/server",
"@apollo/server",
"graphql-yoga",
"type-graphql",
"socket.io",
"ws",
"elysia",
"moleculer",
];
/// The package prefixes of the same family (`@remix-run/node`, `apollo-server-express`...).
const OTHER_SERVER_PREFIXES: &[&str] = &["apollo-server", "@elysiajs/", "@adonisjs/"];
/// The maximum depth of any recursion on the tree: beyond it, the result is "unresolved".
use super::facts::MAX_DEPTH;
/// The commander packages.
const COMMANDER: &[&str] = &["commander", "@commander-js/extra-typings"];
/// The surface declared by a TS/JS file (`path` relative to the repository, `/` separators),
/// read on a stack sized to the file.
pub(super) fn surface(path: &str, source: &str) -> Surface {
super::facts::on_stack_for(source, &|| read_surface(path, source))
}
fn read_surface(path: &str, source: &str) -> Surface {
let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
let allocator = Allocator::default();
let ret = Parser::new(&allocator, source, source_type).parse();
let lines = Lines::new(source);
let imports = Imports::read(&ret.program, &lines);
let mut collector = Collector::new(lines, imports);
collector.added = cli::Added::read(&ret.program);
collector.bindings = Bindings::read(&ret.program);
collector.constants = Constants::read(&ret.program);
collector.seed_env_aliases(&ret.program);
if let Some(convention) = manual::file_convention(path, &collector.imports) {
collector.unresolved_at(
Family::Route,
1,
&format!("file-based route ({convention})"),
);
}
collector.visit_program(&ret.program);
leaks::find(&mut collector, &ret.program);
parsed::find(&mut collector, &ret.program);
strings::find(&mut collector, &ret.program);
collector.finish()
}
/// What the imports of the file say about the libraries in play.
struct Libs {
commander: bool,
yargs: bool,
util: bool,
/// The packages of the server frameworks that are imported.
frameworks: Vec<&'static str>,
}
impl Libs {
fn of(imports: &Imports) -> Self {
let frameworks: Vec<&'static str> = FRAMEWORKS
.iter()
.copied()
.filter(|package| imports.has(&[*package]))
.collect();
Self {
commander: imports.has(COMMANDER),
yargs: imports.has(&["yargs"]),
util: imports.has(&["util"]),
frameworks,
}
}
fn has_framework(&self, name: &str) -> bool {
self.frameworks.contains(&name)
}
}
/// The visitor: a single pass, with the state of aliases and scopes in the fields.
struct Collector {
lines: Lines,
imports: Imports,
libs: Libs,
out: Surface,
/// Variables that hold a command (`const show = program.command("show")`).
commands: HashMap<String, cli::Scope>,
/// Variables that hold a built option (`const o = new Option("-p, --port")`).
options: HashMap<String, String>,
/// Flag scopes of the yargs commands whose options builder is read, the innermost last
/// (`None`: the default command at the first level).
builder_scopes: Vec<Option<String>>,
/// Variables that stand for the whole environment (`const env = process.env`).
env_aliases: HashSet<String>,
/// Starts of the `process.env` expressions passed as they are to a child process.
forwarded: HashSet<u32>,
/// Direct reads of the arguments: (line, reason).
argv_sites: Vec<(u32, &'static str)>,
/// The names that stand for the `process` module (`import proc from 'process'`).
process_names: HashSet<String>,
/// The environment aliases that come from `import.meta.env` (Vite constants).
vite_aliases: HashSet<String>,
/// The local names of `env` imported from `hono/adapter`.
hono_env: HashSet<String>,
/// The site of the bindings read through `c.env` (hono) is already reported.
hono_bindings_seen: bool,
/// The names imported from `process` under the name `argv`.
argv_names: HashSet<String>,
/// Starts of the argument reads passed as they are to a parser: not a site.
allowed_argv: HashSet<u32>,
/// Variables at the root of which commander or yargs is found (the parser or its result).
parser_vars: HashSet<String>,
/// Variables that hold the parser object itself (not its result).
parser_values: HashSet<String>,
/// The lines already reported as declaring on a parser that comes from elsewhere.
received_lines: HashSet<u32>,
/// The libraries without a detector already reported (once each).
reported_libs: HashSet<String>,
/// Variables that hold the request path (`const { pathname } = new URL(req.url)`).
path_aliases: HashSet<String>,
/// Variables that hold an address built on that path (`new URL(req.url, base)`).
url_aliases: HashSet<String>,
/// The file imports a server: a comparison of the request path there is routing.
serves: bool,
/// What each variable is, to decide whether `x.get("/p", h)` is a route.
origins: HashMap<String, routes::Origin>,
/// The subcommands passed to `addCommand` (which tells them apart from the root program).
added: cli::Added,
/// The number of bindings of each name: beyond one, its origin is not proven.
bindings: Bindings,
/// The text constants, the functions and the routing methods detached from the file.
constants: Constants,
/// The command aliases read (`.alias("x")`): command, alias, line. Attached at the end.
pending_aliases: Vec<(String, Vec<String>, u32)>,
/// The routing objects created here, their mounts and the routes read, listed at the end.
mounts: mounts::Mounts,
}
impl Collector {
fn new(lines: Lines, imports: Imports) -> Self {
let libs = Libs::of(&imports);
let serves = manual::serves(&imports);
let mut process_names = HashSet::new();
let mut argv_names = HashSet::new();
for local in imports.locals(&["process"]) {
match local.imported.as_deref() {
None => {
process_names.insert(local.name.clone());
}
Some("argv") => {
argv_names.insert(local.name.clone());
}
Some(_) => {}
}
}
Self {
lines,
imports,
libs,
out: Surface::default(),
commands: HashMap::new(),
options: HashMap::new(),
builder_scopes: Vec::new(),
env_aliases: HashSet::new(),
forwarded: HashSet::new(),
argv_sites: Vec::new(),
process_names,
vite_aliases: HashSet::new(),
hono_env: HashSet::new(),
hono_bindings_seen: false,
argv_names,
allowed_argv: HashSet::new(),
parser_vars: HashSet::new(),
parser_values: HashSet::new(),
received_lines: HashSet::new(),
reported_libs: HashSet::new(),
path_aliases: HashSet::new(),
url_aliases: HashSet::new(),
serves,
origins: HashMap::new(),
added: cli::Added::default(),
bindings: Bindings::default(),
constants: Constants::default(),
pending_aliases: Vec::new(),
mounts: mounts::Mounts::default(),
}
}
fn add(
&mut self,
family: Family,
name: String,
span: Span,
scope: Option<String>,
detail: Option<String>,
) {
if family == Family::Env {
self.recognise(Family::Env, "process.env");
}
self.out.found.push(Found {
family,
name,
line: self.lines.of(span),
scope,
detail,
});
}
fn unresolved(&mut self, family: Family, span: Span, reason: &str) {
let line = self.lines.of(span);
self.unresolved_at(family, line, reason);
}
fn unresolved_at(&mut self, family: Family, line: u32, reason: &str) {
self.out.unresolved.push(UnresolvedInFile {
family,
line,
reason: reason.to_string(),
});
}
/// An imported name is used (not only imported): the parser is in use, even without
/// declaring anything, and a library without a detector is an unenumerated site.
fn note_use(&mut self, name: &str, span: Span) {
let Some(package) = self.imports.package_for(name) else {
return;
};
let package = package.to_string();
let line = self.lines.of(span);
self.library_used(&package, line);
}
/// The effect of using a library, whatever way it is reached.
fn library_used(&mut self, package: &str, line: u32) {
if COMMANDER.contains(&package) {
self.recognise_cli("commander");
} else if package == "yargs" {
self.recognise_cli("yargs");
} else if ENV_LIBRARIES.contains(&package) {
if self.reported_libs.insert(package.to_string()) {
let reason =
format!("environment is read through {package}, which has no detector");
self.unresolved_at(Family::Env, line, &reason);
}
} else if (OTHER_SERVERS.contains(&package)
|| OTHER_SERVER_PREFIXES.iter().any(|p| package.starts_with(p)))
&& self.reported_libs.insert(package.to_string())
{
let reason = format!("routes are declared by {package}, which has no detector");
self.unresolved_at(Family::Route, line, &reason);
}
}
/// An argument parser is used: commands and flags are both covered.
fn recognise_cli(&mut self, library: &str) {
self.recognise(Family::Command, library);
self.recognise(Family::Flag, library);
}
fn recognise(&mut self, family: Family, library: &str) {
self.out.recognised.insert((family, library.to_string()));
}
/// The sites that can only be judged once the whole file is read.
fn finish(mut self) -> Surface {
self.emit_routes();
self.attach_aliases();
self.report_unsupported_parsers();
self.report_raw_arguments();
self.report_unknown_packages();
self.out
}
}
impl<'a> Visit<'a> for Collector {
fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
if self.deno_env_call(it) || self.hono_env_call(it) {
return;
}
self.mark_child_process_env(&it.callee, &it.arguments);
self.mark_parser_args(it);
self.require_use(it);
self.manual_call(it);
if self.yargs_command(it) {
return;
}
walk::walk_call_expression(self, it);
self.inspect_call(it);
self.mount_node_call(it);
}
fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
self.mark_worker_env(&it.callee, &it.arguments);
walk::walk_new_expression(self, it);
self.inspect_new(it);
self.mount_node_new(it);
}
fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) {
if !self.static_member(it) {
walk::walk_static_member_expression(self, it);
}
}
fn visit_computed_member_expression(&mut self, it: &ComputedMemberExpression<'a>) {
if !self.computed_member(it) {
walk::walk_computed_member_expression(self, it);
}
}
fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
self.env_alias_use(it);
self.note_use(it.name.as_str(), it.span);
self.argv_name_use(it);
walk::walk_identifier_reference(self, it);
}
// Type positions and export lists do not "use" a parser: an import that only serves to type
// proves nothing.
// The one exception: an environment or server library without a detector, for which a type
// (`ConfigService`) is enough to prove use.
fn visit_ts_type_reference(&mut self, it: &TSTypeReference<'a>) {
if let TSTypeName::IdentifierReference(id) = &it.type_name
&& let Some(package) = self.imports.package_for(id.name.as_str())
&& (ENV_LIBRARIES.contains(&package) || OTHER_SERVERS.contains(&package))
{
self.note_use(id.name.as_str(), id.span);
}
}
fn visit_ts_type_query(&mut self, _it: &TSTypeQuery<'a>) {}
fn visit_ts_class_implements(&mut self, _it: &TSClassImplements<'a>) {}
fn visit_ts_interface_declaration(&mut self, _it: &TSInterfaceDeclaration<'a>) {}
fn visit_ts_type_alias_declaration(&mut self, _it: &TSTypeAliasDeclaration<'a>) {}
fn visit_export_specifier(&mut self, _it: &ExportSpecifier<'a>) {}
fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
if self.env_declarator(it) {
return;
}
self.argv_declarator(it);
self.process_declarator(it);
walk::walk_variable_declarator(self, it);
self.track_declarator(it);
self.mount_var(it);
self.manual_declarator(it);
}
fn visit_assignment_expression(&mut self, it: &AssignmentExpression<'a>) {
self.track_origin_assignment(it);
self.mount_assignment(it);
self.track_parser_assignment(it);
if !self.env_assignment(it) {
walk::walk_assignment_expression(self, it);
}
}
fn visit_switch_statement(&mut self, it: &SwitchStatement<'a>) {
self.manual_switch(it);
walk::walk_switch_statement(self, it);
}
fn visit_binary_expression(&mut self, it: &BinaryExpression<'a>) {
self.manual_binary(it);
if !self.env_in_operator(it) {
walk::walk_binary_expression(self, it);
}
}
fn visit_unary_expression(&mut self, it: &UnaryExpression<'a>) {
if !self.env_delete(it) {
walk::walk_unary_expression(self, it);
}
}
}