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
//! The detector's rules, on inline code snippets.
use super::surface;
use crate::obligations::Family;
use crate::obligations::surface::Surface;
fn run(source: &str) -> Surface {
surface("src/app.ts", source)
}
/// The items of a family, sorted, as `scope/name` when the flag has a command.
fn items(s: &Surface, family: Family) -> Vec<String> {
let mut out: Vec<String> = s
.found
.iter()
.filter(|f| f.family == family)
.map(|f| match &f.scope {
Some(scope) => format!("{scope}/{}", f.name),
None => f.name.clone(),
})
.collect();
out.sort();
out
}
fn reasons(s: &Surface, family: Family) -> Vec<String> {
s.unresolved
.iter()
.filter(|u| u.family == family)
.map(|u| u.reason.clone())
.collect()
}
fn detail(s: &Surface, family: Family, name: &str) -> Option<String> {
s.found
.iter()
.find(|f| f.family == family && f.name == name)
.and_then(|f| f.detail.clone())
}
fn nothing_unresolved(s: &Surface) {
assert!(s.unresolved.is_empty(), "{:?}", s.unresolved);
}
// --- environment variables ---
#[test]
fn env_reads_in_every_form() {
let s = run(r#"
const a = process.env.PORT;
const b = process.env["HOST"];
const c = process.env?.TOKEN;
const d = Bun.env.BUN_VAR;
const e = import.meta.env.VITE_URL;
const f = Deno.env.get("DENO_VAR");
const g = (process.env as any).CAST;
const h = process.env!.BANG;
if ("PRESENT" in process.env) {}
"#);
assert_eq!(
items(&s, Family::Env),
[
"BANG", "BUN_VAR", "CAST", "DENO_VAR", "HOST", "PORT", "PRESENT", "TOKEN", "VITE_URL"
]
);
nothing_unresolved(&s);
}
#[test]
fn env_destructuring_lists_each_name_with_its_default() {
let s = run(r#"
const { A, B: b, C = "x" } = process.env;
({ D, E: e } = process.env);
"#);
assert_eq!(items(&s, Family::Env), ["A", "B", "C", "D", "E"]);
assert_eq!(
detail(&s, Family::Env, "C").as_deref(),
Some("default \"x\"")
);
nothing_unresolved(&s);
}
#[test]
fn env_destructuring_with_a_rest_or_computed_key_is_unresolved() {
let s = run("const { A, ...rest } = process.env; const { [k]: v } = process.env;");
assert_eq!(items(&s, Family::Env), ["A"]);
assert_eq!(reasons(&s, Family::Env).len(), 2);
}
#[test]
fn env_alias_resolves_member_reads() {
let s = run("const env = process.env; const p = env.PORT; const h = env['HOST'];");
assert_eq!(items(&s, Family::Env), ["HOST", "PORT"]);
nothing_unresolved(&s);
}
#[test]
fn env_alias_passed_on_is_unresolved() {
let s = run("const env = process.env; use(env);");
assert_eq!(reasons(&s, Family::Env).len(), 1);
}
#[test]
fn computed_env_name_is_unresolved() {
let s = run("const v = process.env[name]; const w = Deno.env.get(key);");
assert!(items(&s, Family::Env).is_empty());
assert_eq!(
reasons(&s, Family::Env),
[
"environment variable name is not a string literal",
"environment variable name is not a string literal"
]
);
}
#[test]
fn whole_environment_uses_are_unresolved() {
for source in [
"const c = { ...process.env, X: 1 };",
"Object.keys(process.env);",
"for (const k in process.env) {}",
"JSON.stringify(process.env);",
"const copy = { ...process.env };",
"Deno.env.toObject();",
"const { ...all } = process.env;",
"log(import.meta.env);",
"process.env.hasOwnProperty('X');",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Env).len(), 1, "{source}");
}
}
#[test]
fn env_writes_are_not_obligations() {
let s = run(r#"
process.env.WRITTEN = "1";
process.env["ALSO"] = "2";
delete process.env.GONE;
process.env.NODE_ENV ||= "development";
"#);
assert_eq!(items(&s, Family::Env), ["NODE_ENV"]);
nothing_unresolved(&s);
}
#[test]
fn forwarding_the_environment_to_a_child_process_is_not_reported() {
let s = run(r#"
import { spawn, execSync } from "node:child_process";
spawn("ls", [], { env: process.env });
execSync("ls", { env: { ...process.env, EXTRA: "1" } });
"#);
assert!(items(&s, Family::Env).is_empty());
nothing_unresolved(&s);
}
#[test]
fn the_forwarding_exception_is_narrow() {
// Only the `env` option of a process launcher passes the object on without reading it;
// anywhere else, under another name or in a property, the whole object is a site.
for source in [
"const config = { env: process.env };",
"log({ env: process.env });",
"import { spawn } from 'child_process'; spawn('ls', { stdio: process.env });",
"other.env = { ...process.env };",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Env).len(), 1, "{source}");
}
}
#[test]
fn env_names_in_strings_and_comments_do_not_match() {
let s = run(r#"
// process.env.COMMENTED
/* process.env.BLOCK */
const text = "process.env.STRING";
const tpl = `process.env.TEMPLATE`;
"#);
assert!(s.found.is_empty());
nothing_unresolved(&s);
}
// --- commander ---
const COMMANDER: &str = r#"
import { Command, Option } from "commander";
const program = new Command();
program.option("-v, --verbose", "chatty").option("--no-color");
program
.command("serve <dir> [mode]")
.alias("s")
.description("serve")
.option("-p, --port <number>", "port", "80")
.requiredOption("-H, --host <name>")
.addOption(new Option("-t, --token <t>").env("TOKEN").default("x"))
.action(() => {});
const show = program.command("show");
show.option("-x");
show.option("--long [value]");
program.command("clone", "executable subcommand");
program.version("1.2.3");
program.parse(process.argv);
"#;
#[test]
fn commander_commands_and_scoped_flags() {
let s = run(COMMANDER);
assert_eq!(items(&s, Family::Command), ["clone", "serve", "show"]);
assert_eq!(
items(&s, Family::Flag),
[
"--no-color",
"--verbose",
"--version",
"serve/--host",
"serve/--port",
"serve/--token",
"serve/<dir>",
"serve/[mode]",
"show/--long",
"show/-x",
]
);
assert_eq!(items(&s, Family::Env), ["TOKEN"]);
// `clone` is an executable subcommand: its flags belong to another program.
assert_eq!(
reasons(&s, Family::Flag),
["flags of executable subcommand clone are read by another executable"]
);
assert!(reasons(&s, Family::Command).is_empty());
assert!(reasons(&s, Family::Env).is_empty());
}
#[test]
fn commander_details_carry_arguments_aliases_and_placeholders() {
let s = run(COMMANDER);
assert_eq!(
detail(&s, Family::Command, "serve").as_deref(),
Some("<dir> [mode]; alias s")
);
assert_eq!(
detail(&s, Family::Flag, "--port").as_deref(),
Some("-p <number>")
);
assert_eq!(detail(&s, Family::Flag, "--version").as_deref(), Some("-V"));
assert!(
s.recognised
.contains(&(Family::Command, "commander".into()))
);
assert!(s.recognised.contains(&(Family::Flag, "commander".into())));
}
#[test]
fn commander_parse_of_argv_is_not_unresolved() {
let s = run("import { program } from 'commander'; program.parse(process.argv);");
nothing_unresolved(&s);
let s = run(
"import { program } from 'commander'; program.parse(process.argv); const a = process.argv.slice(2);",
);
assert_eq!(reasons(&s, Family::Flag).len(), 1);
assert_eq!(reasons(&s, Family::Command).len(), 1);
}
#[test]
fn commander_in_a_cjs_file() {
let s = surface(
"bin/cli.cjs",
"const { Command } = require('commander');\nconst p = new Command();\np.command('init').option('-f, --force');",
);
assert_eq!(items(&s, Family::Command), ["init"]);
assert_eq!(items(&s, Family::Flag), ["init/--force"]);
}
#[test]
fn commander_add_command_names_a_sub_command_built_here() {
let s = run(r#"
import { Command } from "commander";
const program = new Command("tool");
const build = new Command("build");
build.option("-w, --watch");
program.addCommand(build);
program.addCommand(imported);
"#);
assert_eq!(items(&s, Family::Command), ["build"]);
assert_eq!(items(&s, Family::Flag), ["build/--watch"]);
assert_eq!(reasons(&s, Family::Command).len(), 1);
}
#[test]
fn commander_non_literal_names_are_unresolved() {
let s = run(r#"
import { program } from "commander";
program.command(name);
program.command(`x-${y}`).option("-a");
program.option(flags);
program.option(`--${long}`);
"#);
assert!(items(&s, Family::Command).is_empty());
assert_eq!(reasons(&s, Family::Command).len(), 2);
assert_eq!(reasons(&s, Family::Flag).len(), 3);
}
#[test]
fn commander_option_object_in_a_variable() {
let s = run(r#"
import { Command, Option } from "commander";
const program = new Command();
const port = new Option("-p, --port <n>");
program.addOption(port);
program.addOption(makeOption());
"#);
assert_eq!(items(&s, Family::Flag), ["--port"]);
assert_eq!(reasons(&s, Family::Flag).len(), 1);
}
#[test]
fn commander_short_only_flag_keeps_its_short_name() {
let s = run("import { program } from 'commander'; program.option('-q');");
assert_eq!(items(&s, Family::Flag), ["-q"]);
}
#[test]
fn method_calls_without_commander_are_not_commands() {
let s = run("const x = list.command('a'); list.option('-p'); const y = other.alias('b');");
assert!(s.found.is_empty());
}
// --- yargs ---
#[test]
fn yargs_commands_and_flags() {
let s = run(r#"
import yargs from "yargs/yargs";
import { hideBin } from "yargs/helpers";
yargs(hideBin(process.argv))
.option("verbose", { alias: "v", type: "boolean" })
.options({ out: { alias: ["o"] }, q: {} })
.boolean("quiet")
.string(["name", "title"])
.number("n")
.count("level")
.positional("skip", {})
.command("serve [port]", "serve", (y) => y.option("port", { type: "number" }).boolean("tls"), () => {})
.command(["build", "b"], "build")
.command({ command: "lint <file>", aliases: ["l"], builder: { fix: { type: "boolean" } }, handler() {} })
.command("$0", "default")
.parse();
"#);
// `$0` is the default command, not a named command.
assert_eq!(items(&s, Family::Command), ["build", "lint", "serve"]);
assert_eq!(
items(&s, Family::Flag),
[
"--level",
"--name",
"--out",
"--quiet",
"--title",
"--verbose",
"-n",
"-q",
"<skip>",
"lint/--fix",
"lint/<file>",
// `.option("port")` describes the positional `[port]` of `serve`, not a flag.
"serve/--tls",
"serve/[port]"
]
);
assert_eq!(
detail(&s, Family::Flag, "--verbose").as_deref(),
Some("-v (boolean)")
);
assert_eq!(
detail(&s, Family::Command, "build").as_deref(),
Some("alias b")
);
assert_eq!(
detail(&s, Family::Command, "lint").as_deref(),
Some("<file>; alias l")
);
nothing_unresolved(&s);
}
#[test]
fn yargs_builder_declared_as_a_property_function_scopes_its_flags() {
let s = run(r#"
const yargs = require("yargs");
yargs.command({ command: "run", builder: (y) => y.option("fast", {}), handler: () => {} }).option("global", {});
"#);
assert_eq!(items(&s, Family::Flag), ["--global", "run/--fast"]);
}
#[test]
fn yargs_dynamic_sites_are_unresolved() {
let s = run(r#"
import yargs from "yargs";
yargs.command(serveModule);
yargs.command(name, "d");
yargs.command("run", "d", buildRun);
yargs.commandDir("cmds");
yargs.option(flagName, {});
yargs.options(shared);
yargs.env("APP");
"#);
assert_eq!(reasons(&s, Family::Command).len(), 3);
// `commandDir` and the command module also hide the flags they declare.
assert_eq!(reasons(&s, Family::Flag).len(), 5);
assert_eq!(reasons(&s, Family::Env).len(), 1);
}
// --- util.parseArgs ---
#[test]
fn parse_args_options_become_flags() {
let s = run(r#"
import { parseArgs } from "node:util";
const { values } = parseArgs({
args: process.argv.slice(2),
options: { verbose: { type: "boolean", short: "v" }, out: { type: "string" } },
});
"#);
assert_eq!(items(&s, Family::Flag), ["--out", "--verbose"]);
assert_eq!(
detail(&s, Family::Flag, "--verbose").as_deref(),
Some("-v (boolean)")
);
nothing_unresolved(&s);
}
#[test]
fn parse_args_through_the_module_and_with_dynamic_options() {
let s = run(r#"
const util = require("util");
util.parseArgs({ options });
util.parseArgs({ options: { ...base, a: {} } });
"#);
assert_eq!(items(&s, Family::Flag), ["--a"]);
assert_eq!(reasons(&s, Family::Flag).len(), 2);
}
#[test]
fn parse_args_without_the_util_import_is_ignored() {
let s = run("parseArgs({ options: { x: {} } });");
assert!(s.found.is_empty());
}
// --- hand-read arguments and parsers without a detector ---
#[test]
fn raw_argv_is_unresolved_without_a_parser() {
for source in [
"const [, , cmd] = process.argv;",
"const first = process.argv[2];",
"const args = process.argv.slice(2);",
"const { argv } = process;",
"const a = Deno.args;",
"import { argv } from 'node:process'; const a = argv.slice(2);",
"const b = Bun.argv;",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Flag).len(), 1, "{source}");
}
let s = run("const a = process.argv.slice(2);");
assert_eq!(reasons(&s, Family::Flag), ["process.argv is read directly"]);
assert_eq!(
reasons(&s, Family::Command),
["process.argv is read directly"]
);
}
#[test]
fn argv_in_strings_and_comments_does_not_match() {
let s = run("// process.argv\nconst t = 'process.argv';");
nothing_unresolved(&s);
}
#[test]
fn argv_given_to_parse_args_is_not_unresolved() {
let s = run(
"import { parseArgs } from 'util'; parseArgs({ args: process.argv.slice(2), options: {} });",
);
nothing_unresolved(&s);
}
#[test]
fn parsers_without_a_detector_are_reported_once_at_the_import() {
let s = run(
"import minimist from 'minimist';\nimport type { X } from 'minimist';\nconst a = minimist(process.argv.slice(2));",
);
let reason = "arguments are parsed by minimist, which has no detector";
assert_eq!(
s.unresolved
.iter()
.map(|u| (u.family, u.line, u.reason.as_str()))
.collect::<Vec<_>>(),
[
(Family::Flag, 1, reason),
(Family::Command, 1, reason),
// An argv passed to a function we do not read is also a hand-read.
(Family::Flag, 3, "process.argv is read directly"),
(Family::Command, 3, "process.argv is read directly"),
]
);
for package in [
"meow",
"cac",
"arg",
"command-line-args",
"oclif",
"@oclif/core",
"clipanion",
"citty",
"sade",
"mri",
"caporal",
] {
let s = run(&format!("import x from '{package}/sub';"));
assert_eq!(
reasons(&s, Family::Flag),
[format!(
"arguments are parsed by {} , which has no detector",
package
)
.replace(" ,", ",")],
"{package}"
);
}
}
// --- routes ---
const EXPRESS: &str = r#"
import express from "express";
const app = express();
const router = express.Router();
app.get("/users/:id", getUser);
app.post("/users", (req, res) => res.end());
app.del("/users/:id", remove);
router.all("*", fallback);
app.get(["/a", "/b"], h);
app.route("/items").get(list).post(create);
app.use("/api", router);
app.get("settings");
"#;
#[test]
fn express_routes_arrays_and_route_chains() {
let s = run(EXPRESS);
assert_eq!(
items(&s, Family::Route),
[
"ALL *",
"DELETE /users/:id",
"GET /a",
"GET /b",
"GET /items",
"GET /users/:id",
"POST /items",
"POST /users",
]
);
assert_eq!(
detail(&s, Family::Route, "GET /users/:id").as_deref(),
Some("getUser")
);
assert!(s.recognised.contains(&(Family::Route, "express".into())));
}
#[test]
fn mounting_under_a_prefix_is_unresolved_and_says_so() {
let s = run(EXPRESS);
assert_eq!(
reasons(&s, Family::Route),
["routes are mounted under a prefix \"/api\"; listed paths under it are relative"]
);
}
#[test]
fn routes_in_a_cjs_express_file() {
let s = surface(
"server.js",
"const express = require('express');\nconst app = express();\napp.get('/ping', (req, res) => res.send('ok'));",
);
assert_eq!(items(&s, Family::Route), ["GET /ping"]);
nothing_unresolved(&s);
}
#[test]
fn non_route_calls_are_not_reported() {
let s = run(r#"
import express from "express";
const map = new Map();
map.get("/x");
client.get("/users");
headers.get("accept", def);
app.get("not/a/path", handler);
"#);
assert!(s.found.is_empty());
nothing_unresolved(&s);
}
#[test]
fn http_client_calls_without_a_framework_import_are_not_routes() {
let s = run(r#"
import axios from "axios";
const client = axios.create();
client.get("/users");
client.post("/users", body);
"#);
assert!(s.found.is_empty());
nothing_unresolved(&s);
}
#[test]
fn dynamic_route_paths_are_unresolved() {
let s = run(r#"
import express from "express";
const app = express();
app.get(path, handler);
app.get(`/v${v}/x`, handler);
app.get("/a" + suffix, handler);
app.get(/^\/re/, handler);
app.get(["/ok", dynamic], handler);
app.route(base).get(list);
app.get("/fine", handler);
"#);
assert_eq!(items(&s, Family::Route), ["GET /fine", "GET /ok"]);
assert_eq!(reasons(&s, Family::Route).len(), 6);
}
#[test]
fn fastify_routes_objects_and_register_prefix() {
let s = run(r#"
import Fastify from "fastify";
const fastify = Fastify();
fastify.get("/health", async () => ({}));
fastify.route({ method: "GET", url: "/a", handler: ha });
fastify.route({ method: ["PUT", "PATCH"], url: "/b", handler });
fastify.route({ method, url: "/c" });
fastify.register(plugin, { prefix: "/v1" });
fastify.register(other);
"#);
assert_eq!(
items(&s, Family::Route),
["GET /a", "GET /health", "PATCH /b", "PUT /b"]
);
assert_eq!(reasons(&s, Family::Route).len(), 2);
assert!(s.recognised.contains(&(Family::Route, "fastify".into())));
}
#[test]
fn hapi_routes_single_and_arrays() {
let s = run(r#"
const Hapi = require("@hapi/hapi");
const server = Hapi.server();
server.route({ method: "GET", path: "/users/{id}", handler: h });
server.route([{ method: "post", path: "/users" }, { method: "*", path: "/any" }]);
server.route(routes);
"#);
assert_eq!(
items(&s, Family::Route),
["ALL /any", "GET /users/{id}", "POST /users"]
);
assert_eq!(reasons(&s, Family::Route).len(), 1);
}
#[test]
fn hono_routes_on_mount_and_base_path() {
let s = run(r#"
import { Hono } from "hono";
import { cors } from "hono/cors";
const app = new Hono();
app.get("/", (c) => c.text("hi"));
app.on(["GET", "POST"], "/multi", h);
app.route("/books", books);
const sub = new Hono().basePath("/api");
"#);
assert_eq!(
items(&s, Family::Route),
["GET /", "GET /multi", "POST /multi"]
);
// `books` comes from elsewhere: its prefix stays a site. `basePath` on an application
// created here is followed and leaves nothing behind.
assert_eq!(
reasons(&s, Family::Route),
["routes are mounted under a prefix \"/books\"; listed paths under it are relative"]
);
}
#[test]
fn koa_router_named_routes_and_prefix() {
let s = run(r#"
import Router from "@koa/router";
const router = new Router({ prefix: "/api" });
router.get("user", "/users/:id", handler);
router.get("/plain", handler);
"#);
// The router's literal prefix is composed in; the router is not mounted here, so its paths
// stay relative to the mount in another file.
assert_eq!(
items(&s, Family::Route),
["GET /api/plain", "GET /api/users/:id"]
);
assert_eq!(
detail(&s, Family::Route, "GET /api/plain").as_deref(),
Some("handler; relative to a mount prefix that was not read")
);
nothing_unresolved(&s);
}
#[test]
fn other_frameworks_are_read_too() {
for (package, call) in [
("@tinyhttp/app", "app.get('/t', h)"),
("restify", "server.get('/t', h)"),
("polka", "app.get('/t', h)"),
("itty-router", "router.get('/t', h)"),
("koa-router", "router.get('/t', h)"),
] {
let s = run(&format!("import x from '{package}';\n{call};"));
assert_eq!(items(&s, Family::Route), ["GET /t"], "{package}");
}
}
#[test]
fn a_raw_http_server_is_unresolved() {
for source in [
"import http from 'node:http';\nhttp.createServer((req, res) => res.end()).listen(1);",
"const http = require('http');\nhttp.createServer(handler);",
"import { createServer } from 'https';\ncreateServer(opts, handler);",
"import * as http2 from 'node:http2';\nhttp2.createSecureServer(opts, h);",
"require('http').createServer(h);",
"Bun.serve({ fetch() {} });",
"Deno.serve((req) => new Response());",
] {
let s = run(source);
assert_eq!(
reasons(&s, Family::Route),
["requests are handled by a raw http server; routes cannot be enumerated"],
"{source}"
);
}
}
#[test]
fn a_framework_app_on_a_raw_server_is_not_a_raw_server() {
let s = run(
"import http from 'http';\nimport express from 'express';\nconst app = express();\napp.get('/x', h);\nhttp.createServer(app).listen(1);",
);
assert_eq!(items(&s, Family::Route), ["GET /x"]);
nothing_unresolved(&s);
}
#[test]
fn net_create_server_is_not_an_http_server() {
let s = run("import net from 'node:net';\nnet.createServer(c => {});");
nothing_unresolved(&s);
}
// --- tolerance and formats ---
#[test]
fn tsx_and_mjs_paths_are_parsed() {
let tsx = surface(
"src/App.tsx",
"export const App = () => <div>{process.env.REACT_APP_NAME}</div>;",
);
assert_eq!(items(&tsx, Family::Env), ["REACT_APP_NAME"]);
let mjs = surface(
"tool.mjs",
"import { program } from 'commander';\nprogram.command('go');",
);
assert_eq!(items(&mjs, Family::Command), ["go"]);
}
#[test]
fn typescript_syntax_is_read() {
let s = run(r#"
import express, { Request } from "express";
const app: express.Express = express();
app.get("/typed", (req: Request, res): void => { const p = process.env.TYPED as string; });
"#);
assert_eq!(items(&s, Family::Route), ["GET /typed"]);
assert_eq!(items(&s, Family::Env), ["TYPED"]);
}
#[test]
fn a_file_that_does_not_parse_never_panics() {
let s = run("const a = process.env.BEFORE;
const = ;
const b = process.env.AFTER;");
assert!(s.found.len() <= 2);
assert!(run("@@@ ((( {{{").found.is_empty());
}
#[test]
fn lines_point_at_the_method_name_of_a_chain() {
let s =
run("import { program } from 'commander';\nprogram\n .command('a')\n .option('-x');\n");
let lines: Vec<(String, u32)> = s.found.iter().map(|f| (f.name.clone(), f.line)).collect();
assert_eq!(lines, [("a".to_string(), 3), ("-x".to_string(), 4)]);
}
#[test]
fn nested_commander_commands_use_the_space_joined_path_as_name_and_scope() {
let s = run(r#"
import { Command } from "commander";
const program = new Command();
program.command("remote").command("add <name>").option("--force");
const remote = program.command("remote2");
remote.command("rm").option("-f");
program.command("serve").option("--port <n>");
"#);
assert_eq!(
items(&s, Family::Command),
["remote", "remote add", "remote2", "remote2 rm", "serve"]
);
assert_eq!(
items(&s, Family::Flag),
[
"remote add/--force",
"remote add/<name>",
"remote2 rm/-f",
"serve/--port"
]
);
assert_eq!(
detail(&s, Family::Command, "remote add").as_deref(),
Some("<name>")
);
}
#[test]
fn nested_yargs_builders_use_the_path_as_name_and_scope() {
let s = run(r#"
import yargs from "yargs";
yargs.command("remote", "r", (y) =>
y.command("add <name>", "a", (z) => z.option("force", {})).option("verbose", {}));
"#);
assert_eq!(items(&s, Family::Command), ["remote", "remote add"]);
assert_eq!(
items(&s, Family::Flag),
[
"remote add/--force",
"remote add/<name>",
"remote/--verbose"
]
);
}
#[test]
fn recognised_names_libraries_consistently() {
let s = run(
"import express from 'express';\nimport { parseArgs } from 'util';\nexpress().get('/a', h);\nparseArgs({options:{a:{}}});\nconst x = process.env.X;",
);
for want in [
(Family::Route, "express"),
(Family::Flag, "parseArgs"),
(Family::Env, "process.env"),
] {
assert!(
s.recognised.contains(&(want.0, want.1.to_string())),
"{want:?}"
);
}
}
// --- origin of a route's receiver ---
#[test]
fn a_receiver_made_by_the_framework_is_a_route_literal_or_not() {
let s = run(r#"
import express, { Router } from "express";
import { Hono } from "hono";
const app = express();
const r = Router();
const h = new Hono();
let late;
late = express();
app.get("/a", handler);
r.get("/b", handler);
h.get("/c", handler);
late.get("/d", handler);
app.get(dynamic, handler);
r.post(`/x/${id}`, handler);
h.get(other, handler);
late.get(other2, handler);
"#);
assert_eq!(
items(&s, Family::Route),
["GET /a", "GET /b", "GET /c", "GET /d"]
);
assert_eq!(reasons(&s, Family::Route).len(), 4);
}
#[test]
fn a_receiver_proved_not_to_be_the_framework_is_ignored() {
let s = run(r#"
import express from "express";
import LRU from "lru-cache";
import axios from "axios";
const app = express();
const cache = new LRU();
const map = new Map();
const lit = { get() {} };
const client = axios.create();
cache.get("/key", fallback);
cache.get(key, fallback);
map.get("/m", fallback);
map.get(key, fallback);
lit.get("/l", fallback);
client.get("/users", cfg);
client.get(url, cfg);
app.get("/real", handler);
"#);
assert_eq!(items(&s, Family::Route), ["GET /real"]);
nothing_unresolved(&s);
}
#[test]
fn a_receiver_of_unknown_origin_is_a_route_when_the_call_has_a_route_shape() {
let s = run(r#"
import express from "express";
import { shared } from "./shared";
export function mount(v1, other) {
v1.get("/lit", handler);
v1.get(path, (req, res) => res.end());
shared.get("/imported", handler);
this.router.get(dyn, handler);
other.get(key, 0);
other.get("/not-a-route", 0);
other.get("accept", handler);
}
"#);
// On an object of unknown origin, only literal data after the path makes it a plain
// access (`other.get("/not-a-route", 0)`); a handler keeps the route, marked, and a
// computed path in an express file is a site.
assert_eq!(items(&s, Family::Route), ["GET /imported", "GET /lit"]);
assert_eq!(
detail(&s, Family::Route, "GET /lit").as_deref(),
Some("handler; receiver of unknown origin")
);
assert_eq!(
reasons(&s, Family::Route),
[
"route path is not a string literal",
"route path is not a string literal",
"2 route(s) declared on an object whose origin is not known; they may not be routes"
]
);
}
// --- Vite constants ---
#[test]
fn vite_constants_are_not_environment_variables_but_everything_else_is() {
let s = run(r#"
const a = import.meta.env.DEV;
const b = import.meta.env.PROD;
const c = import.meta.env["MODE"];
const d = import.meta.env.BASE_URL;
const e = import.meta.env.SSR;
const f = import.meta.env.VITE_API;
const g = import.meta.env.DEVELOPER;
const h = process.env.DEV;
const { MODE, VITE_X } = import.meta.env;
"#);
assert_eq!(
items(&s, Family::Env),
["DEV", "DEVELOPER", "VITE_API", "VITE_X"]
);
nothing_unresolved(&s);
}
// --- addCommand: the parent's path ---
#[test]
fn add_command_names_the_sub_command_under_its_parent() {
let s = run(r#"
import { Command } from "commander";
const program = new Command("tool");
const remote = program.command("remote");
const add = new Command("add");
add.option("--force");
remote.addCommand(add);
const late = new Command("late");
remote.addCommand(late);
late.option("-q");
const top = new Command("top");
top.option("-x");
program.addCommand(top);
program.option("-g");
"#);
assert_eq!(
items(&s, Family::Command),
["remote", "remote add", "remote late", "top"]
);
assert_eq!(
items(&s, Family::Flag),
["-g", "remote add/--force", "remote late/-q", "top/-x"]
);
nothing_unresolved(&s);
}
#[test]
fn add_command_with_an_unknown_parent_or_name_is_unresolved_not_guessed() {
let s = run(r#"
import { Command } from "commander";
const program = new Command();
const sub = new Command("sub");
program.command(dynamic).addCommand(sub);
program.addCommand(new Command(name));
program.addCommand(imported);
"#);
assert!(items(&s, Family::Command).is_empty());
assert_eq!(reasons(&s, Family::Command).len(), 4);
}
// --- raw arguments: the reason names the source ---
#[test]
fn raw_argument_reasons_name_their_source_under_command_and_flag() {
for (source, reason) in [
("const a = Deno.args;", "Deno.args is read directly"),
("const b = Bun.argv;", "Bun.argv is read directly"),
("const c = process.argv;", "process.argv is read directly"),
(
"import meow from 'meow';",
"arguments are parsed by meow, which has no detector",
),
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Flag), [reason], "{source}");
assert_eq!(reasons(&s, Family::Command), [reason], "{source}");
}
}
// --- non-enumerable environment ---
#[test]
fn each_non_enumerable_environment_use_is_one_unresolved_env_site() {
for source in [
"const v = process.env[name];",
"const { A, ...rest } = process.env;",
"f(process.env);",
"const o = { ...process.env };",
"Object.keys(process.env);",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Env).len(), 1, "{source}");
assert!(
!items(&s, Family::Env).iter().any(|n| n != "A"),
"{source}: {:?}",
items(&s, Family::Env)
);
}
}
// --- `recognised`: a parser in use, even when it declares nothing ---
fn has(s: &Surface, family: Family, library: &str) -> bool {
s.recognised.contains(&(family, library.to_string()))
}
#[test]
fn commander_with_flags_and_no_subcommand_recognises_command_too() {
let s =
run("import { program } from 'commander'; program.option('--port <n>'); program.parse();");
assert_eq!(items(&s, Family::Flag), ["--port"]);
assert!(items(&s, Family::Command).is_empty());
assert!(has(&s, Family::Command, "commander"));
assert!(has(&s, Family::Flag, "commander"));
}
#[test]
fn commander_in_use_with_nothing_declared_is_recognised() {
for source in [
"import { Command } from 'commander'; const p = new Command(); p.parse();",
"import { createCommand } from 'commander'; const p = createCommand();",
"import { program } from 'commander'; program.parse();",
"const { program } = require('commander'); program.parse();",
"require('commander').program.parse();",
"import * as c from 'commander'; export default c;",
] {
let s = run(source);
assert!(has(&s, Family::Command, "commander"), "{source}");
assert!(has(&s, Family::Flag, "commander"), "{source}");
}
}
#[test]
fn yargs_with_commands_and_no_flags_recognises_flag_too() {
let s = run(
"import yargs from 'yargs'; import { hideBin } from 'yargs/helpers';\nyargs(hideBin(process.argv)).command('serve', 'start', () => {}).parse();",
);
assert_eq!(items(&s, Family::Command), ["serve"]);
assert!(items(&s, Family::Flag).is_empty());
assert!(has(&s, Family::Flag, "yargs"));
assert!(has(&s, Family::Command, "yargs"));
let s = run("const y = require('yargs'); y.parse();");
assert!(has(&s, Family::Flag, "yargs") && has(&s, Family::Command, "yargs"));
let s = run("require('yargs')(process.argv.slice(2)).parse();");
assert!(has(&s, Family::Flag, "yargs") && has(&s, Family::Command, "yargs"));
}
#[test]
fn an_import_alone_recognises_nothing() {
for source in [
"import { Command } from 'commander'; let c: Command; type T = Command;",
"import { Command } from 'commander'; function run(c: Command) {} export { Command };",
"export { program } from 'commander';",
"import yargs from 'yargs';",
"import type { Argv } from 'yargs'; function f(a: Argv) {}",
"const program = require('commander');",
] {
let s = run(source);
assert!(s.recognised.is_empty(), "{source}: {:?}", s.recognised);
assert!(s.found.is_empty() && s.unresolved.is_empty(), "{source}");
}
}
#[test]
fn parse_args_without_positionals_recognises_command_and_flag() {
for source in [
"import { parseArgs } from 'node:util'; parseArgs({ options: { a: { type: 'boolean' } } });",
"import { parseArgs } from 'node:util'; parseArgs({ allowPositionals: false, options: {} });",
"import { parseArgs } from 'node:util'; parseArgs();",
] {
let s = run(source);
assert!(has(&s, Family::Flag, "parseArgs"), "{source}");
assert!(has(&s, Family::Command, "parseArgs"), "{source}");
assert!(reasons(&s, Family::Command).is_empty(), "{source}");
}
}
#[test]
fn parse_args_with_positionals_or_unknown_ones_leaves_commands_unresolved() {
for source in [
"import { parseArgs } from 'node:util'; parseArgs({ allowPositionals: true, options: {} });",
"import { parseArgs } from 'node:util'; parseArgs({ allowPositionals: flag, options: {} });",
"import { parseArgs } from 'node:util'; parseArgs({ ...base, options: {} });",
"import { parseArgs } from 'node:util'; parseArgs(config);",
] {
let s = run(source);
assert!(has(&s, Family::Flag, "parseArgs"), "{source}");
assert!(!has(&s, Family::Command, "parseArgs"), "{source}");
assert_eq!(
reasons(&s, Family::Command),
["positionals of parseArgs are read by hand"],
"{source}"
);
}
}
// --- an origin is proven only for a name bound once ---
#[test]
fn a_name_bound_twice_has_no_proven_origin() {
let s = run(
"import express from 'express';\nconst cache = new Map();\nfunction mount(cache) { cache.get(path, handler); }",
);
assert_eq!(reasons(&s, Family::Route).len(), 1, "{:?}", s.unresolved);
assert!(items(&s, Family::Route).is_empty());
}
#[test]
fn a_name_bound_once_keeps_its_proven_origin() {
let s = run("import express from 'express';\nconst cache = new Map();\ncache.get('/k', h);");
assert!(items(&s, Family::Route).is_empty());
nothing_unresolved(&s);
}
#[test]
fn a_catch_or_arrow_parameter_or_second_declaration_makes_the_origin_unknown() {
for source in [
"import express from 'express'; const c = new Map(); try {} catch (c) { c.get(p, h); }",
"import express from 'express'; const c = new Map(); const f = (c) => c.get(p, h);",
"import express from 'express'; var c = new Map(); { var c = 1; } c.get(p, h);",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Route).len(), 1, "{source}");
}
}
#[test]
fn a_reassignment_to_another_origin_makes_the_origin_unknown() {
let s = run(
"import express from 'express'; let x; x = new Map(); x = express(); x.get('/a', h); x.get(p, h);",
);
// Unknown origin: the shape of a route is enough to list it, marked; a computed path is
// not enumerated.
assert_eq!(items(&s, Family::Route), ["GET /a"]);
assert_eq!(
detail(&s, Family::Route, "GET /a").as_deref(),
Some("h; receiver of unknown origin")
);
assert_eq!(reasons(&s, Family::Route).len(), 2);
let s =
run("import express from 'express'; let x; x = new Map(); x.get('/a', h); x.get(p, h);");
assert!(items(&s, Family::Route).is_empty(), "{:?}", s.found);
assert!(reasons(&s, Family::Route).is_empty());
let s = run(
"import express from 'express'; let x; x = express(); x = express.Router(); x.get('/a', h);",
);
assert_eq!(items(&s, Family::Route), ["GET /a"]);
}
#[test]
fn a_command_variable_bound_twice_carries_no_guessed_scope() {
let s = run(
"import { program } from 'commander';\nconst sub = program.command('serve');\nsub.option('--port <n>');\nfunction other(sub) { sub.option('--x'); }",
);
assert!(items(&s, Family::Flag).is_empty(), "{:?}", s.found);
assert_eq!(reasons(&s, Family::Flag).len(), 2);
let s = run(
"import { program } from 'commander';\nconst sub = program.command('serve');\nsub.option('--port <n>');",
);
assert_eq!(items(&s, Family::Flag), ["serve/--port"]);
}
// --- 1. environment: forms that did not go through `process.env.X` ---
fn env_names(source: &str) -> Vec<String> {
items(&run(source), Family::Env)
}
#[test]
fn env_through_destructured_process_and_imports_of_process() {
for source in [
"const { env } = process; const a = env.PORT;",
"const { env: e } = process; const a = e.PORT;",
"import { env } from 'node:process'; const a = env.PORT;",
"import { env } from 'process'; const a = env.PORT;",
"import proc from 'process'; const a = proc.env.PORT;",
"import * as proc from 'node:process'; const a = proc.env.PORT;",
"const p = require('process'); const a = p.env.PORT;",
"const { env } = require('node:process'); const a = env.PORT;",
"const a = globalThis.process.env.PORT;",
"const e = process.env; const a = e.PORT;",
"const e = import.meta.env; const a = e.PORT;",
"const a = Bun.env.PORT;",
"const a = Deno.env.get('PORT');",
"function f() { return env.PORT; } const env = process.env;",
] {
assert_eq!(env_names(source), ["PORT"], "{source}");
nothing_unresolved(&run(source));
}
}
#[test]
fn env_alias_keeps_the_vite_constants_out() {
let s = run(
"const e = import.meta.env; const a = [e.DEV, e.PROD, e.MODE, e.BASE_URL, e.SSR, e.VITE_X];",
);
assert_eq!(items(&s, Family::Env), ["VITE_X"]);
let s = run("const e = process.env; const a = e.DEV;");
assert_eq!(items(&s, Family::Env), ["DEV"]);
}
#[test]
fn env_alias_follows_the_object_rules() {
let s = run(
"const e = process.env; const k = f(); const a = e[k]; const b = { ...e }; for (const x in e) {} const c = Object.keys(e);",
);
assert!(items(&s, Family::Env).is_empty());
assert_eq!(reasons(&s, Family::Env).len(), 4);
let s = run("const { env } = process; const a = env['X' + 'Y'];");
assert_eq!(reasons(&s, Family::Env).len(), 1);
let s = run("const { env } = process; const a = Object.entries(env);");
assert_eq!(reasons(&s, Family::Env).len(), 1);
}
#[test]
fn an_env_alias_bound_more_than_once_is_unresolved() {
let s =
run("const env = process.env; const a = env.PORT; function f(env) { return env.OTHER; }");
assert!(items(&s, Family::Env).is_empty(), "{:?}", s.found);
assert_eq!(reasons(&s, Family::Env).len(), 2);
}
#[test]
fn deno_to_object_is_not_enumerable() {
let s = run("const all = Deno.env.toObject();");
assert_eq!(reasons(&s, Family::Env).len(), 1);
}
#[test]
fn env_libraries_without_a_detector_are_reported_at_use_only() {
for package in [
"env-var",
"envalid",
"convict",
"config",
"nconf",
"@nestjs/config",
"@t3-oss/env-core",
"@t3-oss/env-nextjs",
"znv",
"dotenv-safe",
"dotenv-flow",
] {
let used = run(&format!(
"import lib from '{package}';\nexport const c = lib.get('X');"
));
assert_eq!(
reasons(&used, Family::Env),
[format!(
"environment is read through {package}, which has no detector"
)],
"{package}"
);
let imported = run(&format!("import lib from '{package}';"));
nothing_unresolved(&imported);
}
let s = run("const c = require('config').get('X');");
assert_eq!(reasons(&s, Family::Env).len(), 1);
let s = run(
"import { ConfigService } from '@nestjs/config';\nclass A { constructor(private c: ConfigService) {} }",
);
assert_eq!(reasons(&s, Family::Env).len(), 1);
let s = run(
"import 'dotenv/config'; import dotenv from 'dotenv'; dotenv.config(); const a = process.env.A;",
);
nothing_unresolved(&s);
assert_eq!(items(&s, Family::Env), ["A"]);
}
// --- 2. argv next to a parser ---
#[test]
fn argv_read_by_hand_next_to_a_parser_is_reported() {
for source in [
"import { program } from 'commander'; if (process.argv[2] === 'doctor') {} program.parse(process.argv);",
"import { program } from 'commander'; const a = process.argv.includes('--x'); program.parse();",
"import { program } from 'commander'; for (const x of process.argv) {} program.parse();",
"import { program } from 'commander'; const [, , c] = process.argv; program.parse();",
"import { program } from 'commander'; const { argv } = process; program.parse();",
"import { program } from 'commander'; run(process.argv); program.parse();",
"import { program } from 'commander'; const a = process.argv.indexOf('x'); program.parse();",
"import yargs from 'yargs'; const n = process.argv[3]; yargs().parse();",
"import { parseArgs } from 'node:util'; const n = Bun.argv[2]; parseArgs({});",
"import { program } from 'commander'; const n = Deno.args[0]; program.parse();",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Command).len(), 1, "{source}");
assert_eq!(reasons(&s, Family::Flag).len(), 1, "{source}");
}
}
#[test]
fn argv_given_to_the_parser_or_executable_slots_are_not_sites() {
for source in [
"import { program } from 'commander'; program.parse(process.argv);",
"import { program } from 'commander'; program.parse(process.argv.slice(2), { from: 'user' });",
"import { program } from 'commander'; await program.parseAsync(process.argv);",
"import { Command } from 'commander'; const p = new Command(); p.command('x'); p.parse(process.argv);",
"import yargs from 'yargs'; import { hideBin } from 'yargs/helpers'; yargs(hideBin(process.argv)).parse();",
"import yargs from 'yargs'; yargs(process.argv.slice(2)).parse();",
"import yargs from 'yargs'; const y = yargs(); y.parse(process.argv.slice(2));",
"const yargs = require('yargs'); yargs(process.argv.slice(2)).argv;",
"import { parseArgs } from 'node:util'; parseArgs({ args: process.argv.slice(2), options: {} });",
"import { program } from 'commander'; const exe = process.argv[0]; const script = process.argv[1]; program.parse();",
] {
let s = run(source);
assert!(
reasons(&s, Family::Command)
.iter()
.all(|r| r != "process.argv is read directly"),
"{source}: {:?}",
s.unresolved
);
assert!(
reasons(&s, Family::Flag).is_empty(),
"{source}: {:?}",
s.unresolved
);
}
}
#[test]
fn argv_given_to_something_else_than_the_parser_is_a_site() {
let s =
run("import { program } from 'commander'; JSON.parse(process.argv[2]); program.parse();");
assert_eq!(reasons(&s, Family::Flag), ["process.argv is read directly"]);
let s = run("import { program } from 'commander'; other.parse(process.argv); program.parse();");
assert_eq!(reasons(&s, Family::Flag), ["process.argv is read directly"]);
}
// --- 3. routes on a receiver of unknown origin, in any file ---
#[test]
fn a_router_required_from_another_file_gives_routes_without_a_framework_import() {
let s = run("const router = require('./router');\nrouter.delete('/items/:id', h);");
assert_eq!(items(&s, Family::Route), ["DELETE /items/:id"]);
let s = run(
"import router from './router';\nrouter.post('/items', (req, res) => {});\nrouter.get('x', h);",
);
assert_eq!(items(&s, Family::Route), ["POST /items"]);
let s = run(
"function mount(r) { r.get('/a', h); }\nclass A { m() { this.router.put('/b', async () => {}); } }",
);
assert_eq!(items(&s, Family::Route), ["GET /a", "PUT /b"]);
}
#[test]
fn a_computed_path_on_an_unknown_object_is_a_site_unless_a_literal_follows() {
let s = run("import router from './router';\nrouter.get(path, (req, res) => {});");
assert_eq!(reasons(&s, Family::Route).len(), 1);
// A plain name can be a handler (`app.get(PATH, list)`): a site, even if that makes one
// too many for `map.get(key, fallback)`. A literal is never a function.
let s = run("const map = getMap();\nmap.get(key, cb);\nmap.get(key, 3);\nmap.get(key, { a });");
assert_eq!(
reasons(&s, Family::Route),
["route path is not a string literal"]
);
assert!(s.found.is_empty());
// The router received as a parameter in a file without a framework, with or without
// another package.
for source in [
"module.exports = (app) => { app.post(ROUTES.login, login); };",
"const _ = require('lodash');\nmodule.exports = (app) => { app.post(ROUTES.login, login); };",
"module.exports = (app) => { app.get(path, ...handlers); };",
"module.exports = (app) => { app.get(path, [auth, list]); };",
] {
let s = run(source);
assert_eq!(reasons(&s, Family::Route).len(), 1, "{source}");
assert!(s.found.is_empty(), "{source}");
}
// fastify: the handler is in the options object.
let s = run("module.exports = async (fastify) => { fastify.get('/x', { schema, handler }); };");
assert_eq!(items(&s, Family::Route), ["GET /x"]);
let s = run("module.exports = async (fastify) => { fastify.get(path, { handler }); };");
assert_eq!(reasons(&s, Family::Route).len(), 1);
let s = run("import express from 'express';\nfunction f(map) { map.get(key, cb); }");
assert_eq!(reasons(&s, Family::Route).len(), 1);
}
#[test]
fn a_literal_without_leading_slash_on_an_unknown_receiver_is_ignored() {
let s = run("function f(cache) { cache.get('key', h); }");
assert!(s.found.is_empty());
nothing_unresolved(&s);
let s = run("import express from 'express'; const cache = new Map(); cache.get('/k', h);");
assert!(s.found.is_empty());
nothing_unresolved(&s);
}
// --- 4. servers without a detector and hand-written routing ---
#[test]
fn servers_without_a_detector_are_reported_at_use() {
for (package, source) in [
(
"@nestjs/common",
"import { Controller, Get } from '@nestjs/common';\n@Controller('x') class A { @Get() f() {} }",
),
("h3", "import { createApp } from 'h3';\ncreateApp();"),
(
"@trpc/server",
"import { initTRPC } from '@trpc/server';\ninitTRPC.create();",
),
(
"apollo-server-express",
"import { ApolloServer } from 'apollo-server-express';\nnew ApolloServer({});",
),
(
"socket.io",
"import { Server } from 'socket.io';\nnew Server();",
),
(
"ws",
"import { WebSocketServer } from 'ws';\nnew WebSocketServer({});",
),
("elysia", "import { Elysia } from 'elysia';\nnew Elysia();"),
(
"@adonisjs/core",
"import router from '@adonisjs/core';\nrouter.x();",
),
(
"moleculer",
"import { ServiceBroker } from 'moleculer';\nnew ServiceBroker();",
),
] {
let s = run(source);
assert_eq!(
reasons(&s, Family::Route),
[format!(
"routes are declared by {package}, which has no detector"
)],
"{package}"
);
}
let s = run("import { Controller } from '@nestjs/common';");
nothing_unresolved(&s);
}
#[test]
fn file_based_routes_are_reported_from_the_path() {
for (path, convention) in [
("app/api/users/route.ts", "app/**/route"),
("src/app/api/users/route.js", "app/**/route"),
("pages/api/users.ts", "pages/api/**"),
("src/pages/api/users/[id].ts", "pages/api/**"),
("src/routes/api/+server.ts", "**/+server"),
("app/routes/users.tsx", "app/routes/**"),
(
"src/routes/blog/+page.server.ts",
"src/routes/**/+page.server",
),
] {
let s = surface(path, "export const x = 1;");
assert_eq!(
reasons(&s, Family::Route),
[format!("file-based route ({convention})")],
"{path}"
);
}
for path in [
"src/app.ts",
"src/lib/route.ts",
"page.tsx",
"src/pages/index.ts",
] {
assert!(
surface(path, "export const x = 1;").unresolved.is_empty(),
"{path}"
);
}
}
#[test]
fn hand_written_routing_is_reported_in_a_server_file() {
for source in [
"import Koa from 'koa'; const app = new Koa(); app.use(ctx => { if (ctx.path === '/ping') ctx.body = 1; });",
"import http from 'http'; http.createServer((req, res) => { if (req.url == '/a') {} });",
"import http from 'http'; http.createServer((req, res) => { switch (req.url) { case '/a': break; } });",
"import http from 'http'; http.createServer((req, res) => { if (req.url.startsWith('/api')) {} });",
"import http from 'http'; http.createServer((req, res) => { if (/^\\/x/.test(req.url)) {} });",
"import http from 'node:http'; http.createServer((req, res) => { req.url.match(/x/); });",
"import express from 'express'; const a = (req) => req.path !== '/health';",
"import express from 'express'; const a = (req) => req.originalUrl.includes('/x');",
"import Koa from 'koa'; const a = (ctx) => ctx.request.path === '/x' || ctx.request.url === '/y' || ctx.url === '/z';",
"import http from 'http'; const a = (request) => request.url === '/x';",
"import http from 'http'; const a = (req) => new URL(req.url, 'http://x').pathname === '/x';",
"import http from 'http'; const a = (req) => { const { pathname } = new URL(req.url, 'http://x'); return pathname === '/x'; };",
"import http from 'http'; const a = (req) => { const u = new URL(req.url, 'http://x'); return u.pathname === '/x'; };",
"import http from 'http'; const a = (req) => { const p = req.url; return p === '/x'; };",
] {
let s = run(source);
assert!(
reasons(&s, Family::Route)
.iter()
.any(|r| r == "the path is matched by hand"),
"{source}: {:?}",
s.unresolved
);
}
}
#[test]
fn comparing_a_path_in_a_file_without_a_server_is_not_routing() {
let s = run("const a = (req) => req.url === '/x';");
nothing_unresolved(&s);
let s = run("import http from 'http'; const a = (req) => req.method === 'GET';");
nothing_unresolved(&s);
}
#[test]
fn a_raw_http_server_is_still_reported() {
let s = run("import http from 'http'; http.createServer((req, res) => res.end());");
assert_eq!(
reasons(&s, Family::Route),
["requests are handled by a raw http server; routes cannot be enumerated"]
);
}
// --- 5. positionals ---
fn positionals(s: &Surface) -> Vec<String> {
s.found
.iter()
.filter(|f| f.family == Family::Flag && f.detail.as_deref() == Some("positional"))
.map(|f| match &f.scope {
Some(scope) => format!("{scope}/{}", f.name),
None => f.name.clone(),
})
.collect()
}
#[test]
fn commander_positionals_are_flags_named_with_their_brackets() {
let s = run(
"import { program } from 'commander';\nprogram.argument('<file>', 'input').argument('[dir]');\nprogram.arguments('<a> [b]');\nprogram.command('add <name> [dir]').argument('<items...>');\nprogram.command('rm <id>');",
);
assert_eq!(
positionals(&s),
[
"<file>",
"[dir]",
"<a>",
"[b]",
"add/<name>",
"add/[dir]",
"add/<items...>",
"rm/<id>"
]
);
assert!(has(&s, Family::Flag, "commander"));
nothing_unresolved(&s);
}
#[test]
fn a_computed_commander_argument_is_unresolved() {
let s = run("import { program } from 'commander'; program.argument(spec);");
assert_eq!(reasons(&s, Family::Flag).len(), 1);
}
#[test]
fn yargs_positionals_come_from_the_command_and_from_positional() {
let s = run(
"import yargs from 'yargs';\nyargs().command('add <name> [dir]', 'a', (y) => y.positional('name', {}).positional('extra', {})).command('rm [id..]', 'r');",
);
assert_eq!(
positionals(&s),
["add/<name>", "add/[dir]", "add/<extra>", "rm/[id..]"]
);
nothing_unresolved(&s);
}
// --- 6. depth ---
#[test]
fn a_very_deep_chain_gives_unresolved_sites_not_a_crash() {
let chain = ".option('--x')".repeat(300);
let s = run(&format!(
"import {{ program }} from 'commander'; const c = program.command('a'){chain};"
));
assert!(!s.found.iter().any(|f| f.name == "--x" && f.scope.is_none()));
// Options beyond the bound no longer have a known scope: they are not enumerated.
assert!(!reasons(&s, Family::Flag).is_empty());
assert!(items(&s, Family::Flag).len() < 300);
let routes = ".get('/a', h)".repeat(300);
let s = run(&format!(
"import express from 'express'; express(){routes};"
));
assert!(!s.found.is_empty());
let deep = "a.".repeat(300);
let s = run(&format!(
"import express from 'express'; {deep}b.get(p, h);"
));
assert!(!s.unresolved.is_empty());
}
#[test]
fn next_style_file_conventions_each_give_their_own_site() {
let next = "import { NextResponse } from 'next/server';
export const x = NextResponse;";
for (path, source, convention) in [
(
"app/dashboard/page.tsx",
"export default function P() {}",
"app/**/page",
),
(
"src/app/page.jsx",
"export default function P() {}",
"app/**/page",
),
(
"pages/about.tsx",
"import Link from 'next/link';
export default Link;",
"pages/**",
),
(
"src/pages/blog/[id].ts",
"import React from 'react';
export default React;",
"pages/**",
),
("middleware.ts", next, "middleware"),
("src/middleware.js", next, "middleware"),
(
"server/api/users.get.ts",
"export default 1;",
"server/api/**",
),
(
"server/routes/health.ts",
"export default 1;",
"server/routes/**",
),
(
"server/middleware/auth.ts",
"export default 1;",
"server/middleware/**",
),
] {
let s = surface(path, source);
assert_eq!(
reasons(&s, Family::Route),
[format!("file-based route ({convention})")],
"{path}"
);
assert_eq!(s.unresolved[0].line, 1, "{path}");
}
}
#[test]
fn files_outside_every_convention_give_no_site() {
for (path, source) in [
("pages/about.tsx", "export default function A() {}"),
(
"src/pages/_app.tsx",
"import React from 'react';
export default React;",
),
(
"pages/_document.tsx",
"import React from 'react';
export default React;",
),
("middleware.ts", "export default 1;"),
(
"lib/middleware.ts",
"import { x } from 'next/server';
export default x;",
),
(
"components/Nav.tsx",
"import Link from 'next/link';
export const Nav = () => Link;",
),
] {
let s = surface(path, source);
nothing_unresolved(&s);
}
}
#[test]
fn next_url_pathname_is_matched_by_hand() {
let s = run("import { NextResponse } from 'next/server';
import http from 'http';
export const m = (request) => request.nextUrl.pathname === '/a';");
assert!(
reasons(&s, Family::Route)
.iter()
.any(|r| r == "the path is matched by hand")
);
}
// --- real depth: thousands of levels, on a test's default stack ---
#[test]
fn a_member_chain_of_twenty_thousand_levels_does_not_overflow() {
let chain = "b.".repeat(20_000);
let s = run(&format!(
"const x = a.{chain}c;
const y = process.env.A;"
));
assert_eq!(items(&s, Family::Env), ["A"]);
nothing_unresolved(&s);
}
#[test]
fn a_call_chain_of_twenty_thousand_levels_does_not_overflow() {
let chain = ".g()".repeat(20_000);
let s = run(&format!(
"const x = f(){chain};
const y = process.env.A;"
));
assert_eq!(items(&s, Family::Env), ["A"]);
nothing_unresolved(&s);
}
#[test]
fn a_deep_call_chain_of_commander_options_is_read_without_overflow() {
let chain = ".option('--x')".repeat(5_000);
let s = run(&format!(
"import {{ program }} from 'commander';
program{chain};"
));
assert!(!reasons(&s, Family::Flag).is_empty());
}
// --- re-read: declaration forms the detector did not read ---
fn run_js(source: &str) -> Surface {
surface("src/app.js", source)
}
fn has_reason(s: &Surface, family: Family, start: &str) -> bool {
reasons(s, family).iter().any(|r| r.starts_with(start))
}
const NOT_LITERAL_PREFIX: &str = "routes are mounted under a prefix that is not a string literal";
#[test]
fn a_prefix_held_by_a_constant_or_an_array_is_a_mount_site() {
// The finding: a single `GET /users` obligation and no site, although the route is
// served under `/api/v1`, `/admin` and `/staff`.
let s = run_js(
"const express = require('express');
const users = require('./users');
const API_PREFIX = '/api/v1';
const app = express();
app.use(API_PREFIX, users);
app.use(['/admin', '/staff'], users);",
);
assert_eq!(
reasons(&s, Family::Route),
[
"routes are mounted under a prefix \"/api/v1\"; listed paths under it are relative",
"routes are mounted under the prefixes \"/admin\", \"/staff\"; listed paths under them are relative",
]
);
}
#[test]
fn a_prefix_that_is_not_a_literal_is_a_mount_site() {
for prefix in [
"PREFIX",
"config.prefix",
"getPrefix()",
"path.join('/a', 'b')",
"process.env.PREFIX",
"flag ? '/a' : '/b'",
"BASE + '/v1'",
"[PREFIX, '/b']",
"settings.get('prefix')",
"LET_PREFIX",
] {
let s = run(&format!(
"import express from 'express';
import path from 'node:path';
import settings from 'config';
import {{ PREFIX }} from './config';
import users from './users';
let LET_PREFIX = '/x';
const app = express();
app.use({prefix}, users);"
));
assert_eq!(
reasons(&s, Family::Route).len(),
1,
"{prefix}: {:?}",
s.unresolved
);
assert!(
has_reason(&s, Family::Route, "routes are mounted under a prefix"),
"{prefix}: {:?}",
s.unresolved
);
}
// Outside a framework file, on a router received as a parameter.
let s = run("import { PREFIX } from './config';
export default (router) => { router.use(PREFIX, sub); };");
assert_eq!(
reasons(&s, Family::Route),
[format!(
"{NOT_LITERAL_PREFIX}; listed paths under it are relative"
)]
);
}
#[test]
fn middleware_before_a_router_is_not_a_prefix() {
let s = run("import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import passport from 'passport';
import users from './users';
const app = express();
const api = express.Router();
const limiter = rateLimit({ max: 10 });
function auth(req, res, next) { next(); }
const log = (req, res, next) => next();
app.use(cors(), users);
app.use(helmet(), express.json(), users);
app.use(express.json(), users);
app.use(auth, users);
app.use(log, users);
app.use(api, users);
app.use([auth, log], users);
app.use((req, res, next) => next(), users);
app.use('/', users);
app.use(passport.initialize(), users);
passport.use('local', strategy);
passport.use(STRATEGY_NAME, strategy);
app.use(users);
import rateLimit from 'express-rate-limit';");
assert_eq!(reasons(&s, Family::Route), Vec::<String>::new());
}
#[test]
fn every_http_method_express_registers_is_a_route() {
let s = run("import express from 'express';
const app = express();
app.search('/s', h);
app.trace('/t', h);
app.copy('/c', h);
app.propfind('/p', h);
app['m-search']('/m', h);
app.route('/doc').get(h).purge(h);
const r = express.Router();
r.lock('/l', h);");
assert_eq!(
items(&s, Family::Route),
[
"COPY /c",
"GET /doc",
"LOCK /l",
"M-SEARCH /m",
"PROPFIND /p",
"PURGE /doc",
"SEARCH /s",
"TRACE /t"
]
);
nothing_unresolved(&s);
}
#[test]
fn restify_opts_is_an_options_route() {
let s = run("import restify from 'restify';
const server = restify.createServer();
server.opts('/a', h);
server.del('/b', h);");
assert_eq!(items(&s, Family::Route), ["DELETE /b", "OPTIONS /a"]);
nothing_unresolved(&s);
}
#[test]
fn a_rarer_method_on_an_object_of_unknown_origin_is_a_site_not_a_route() {
// `fs.copy`, `client.lock`: the name of a rare HTTP method is used elsewhere too.
let s = run("import express from 'express';
export function setup(fs, router) {
router.copy('/a', handler);
fs.copy('/src', '/dst');
fs.move('/a', '/b');
fn.bind(this);
handler.bind(null, '/x');
}");
assert!(items(&s, Family::Route).is_empty(), "{:?}", s.found);
assert_eq!(
reasons(&s, Family::Route),
[
"route-shaped call to .copy() on an object of unknown origin; only some frameworks declare COPY routes this way"
]
);
}
#[test]
fn another_method_called_with_a_path_on_a_framework_object_is_a_site() {
let s = run("import { AutoRouter } from 'itty-router';
const router = AutoRouter();
router.anything('/x', h);
router.fetch('/y', init);");
assert_eq!(
reasons(&s, Family::Route),
[
"route-shaped call to .anything() on a server framework object, a method the detector does not read"
]
);
// Methods known not to declare a route, and a first argument that is not a path, do
// nothing.
let s = run("import express from 'express';
const app = express();
app.listen('/tmp/app.sock', () => {});
app.set('views', dir);
app.engine('html', render);
app.param('id', load);
app.disable('x-powered-by');");
nothing_unresolved(&s);
}
#[test]
fn koa_router_redirect_declares_a_route_on_its_source() {
let s = run("import Router from '@koa/router';
const router = new Router();
router.redirect('/old', '/new');
router.redirect('home', '/new');
router.redirect(OLD, '/new');
export default async (ctx) => { ctx.redirect('/login'); };");
assert_eq!(items(&s, Family::Route), ["ALL /old"]);
// The router is not mounted anywhere here: the path is relative to its mount.
assert_eq!(
detail(&s, Family::Route, "ALL /old").as_deref(),
Some("redirect to /new; relative to a mount prefix that was not read")
);
assert_eq!(
reasons(&s, Family::Route),
[
"redirect source is a route name, so its path cannot be listed",
"route path is not a string literal"
]
);
}
#[test]
fn hono_mount_hands_a_path_to_another_application() {
let s = run("import { Hono } from 'hono';
const app = new Hono();
app.mount('/legacy', legacy.fetch);");
assert_eq!(
reasons(&s, Family::Route),
[
"requests under \"/legacy\" are handled by a mounted application, whose routes cannot be enumerated"
]
);
}
#[test]
fn bound_called_and_applied_route_methods_are_routes() {
let s = run("import express from 'express';
const app = express();
const get = app.get.bind(app);
get('/bound', h);
const post = app.post.bind(app, '/prebound');
post(h);
app.post.call(app, '/called', h);
app.put.apply(app, ['/applied', h]);
app.get.call(app, 'env');
const { patch } = app;
patch('/destructured', h);");
assert_eq!(
items(&s, Family::Route),
[
"GET /bound",
"PATCH /destructured",
"POST /called",
"POST /prebound",
"PUT /applied"
]
);
nothing_unresolved(&s);
}
#[test]
fn route_methods_passed_on_or_called_with_computed_paths_are_sites() {
let s = run("import express from 'express';
const app = express();
register(app.get.bind(app));
app.post.apply(app, args);
app.post.call(app, path, h);
const get = app.get.bind(app);
get(path, h);
app.use.call(app, '/x', r);");
assert!(items(&s, Family::Route).is_empty(), "{:?}", s.found);
assert_eq!(reasons(&s, Family::Route).len(), 5, "{:?}", s.unresolved);
// Control: `bind` and `call` outside a framework object are not routes.
let s = run("import express from 'express';
const m = new Map();
const g = m.get.bind(m);
g('/k', 1);
fn.call(null, '/x', h);");
assert!(items(&s, Family::Route).is_empty(), "{:?}", s.found);
}
#[test]
fn a_route_held_in_a_variable_declares_its_verbs() {
let s = run("import express from 'express';
const app = express();
const doc = app.route('/doc');
doc.get(show).post(save);
const other = app.route(PATH);
other.delete(remove);");
assert_eq!(items(&s, Family::Route), ["GET /doc", "POST /doc"]);
assert_eq!(
reasons(&s, Family::Route),
["route path is not a string literal"]
);
}
#[test]
fn a_spread_route_call_is_a_site_even_alone() {
let s = run("import express from 'express';
const app = express();
app.get(...args);
new Map().get(...k);");
assert_eq!(
reasons(&s, Family::Route),
["route path is not a string literal"]
);
}
#[test]
fn express_static_serves_paths_that_cannot_be_listed() {
let s = run("import express from 'express';
const app = express();
app.use(express.static('public'));
app.use('/assets', require('express').static(dir));");
assert_eq!(
reasons(&s, Family::Route),
[
"files under \"public\" are served by express.static; their paths cannot be enumerated",
"files are served by express.static from a directory that is not a string literal; their paths cannot be enumerated",
"routes are mounted under a prefix \"/assets\"; listed paths under it are relative",
]
);
}
#[test]
fn router_and_plugin_options_that_are_not_literal_may_hold_a_prefix() {
let s = run("import Router from '@koa/router';
const a = new Router(options);
const b = new Router({ ...options });
const c = new Router({ methods: ['GET'] });");
assert_eq!(reasons(&s, Family::Route).len(), 2, "{:?}", s.unresolved);
let s = run("import Fastify from 'fastify';
const app = Fastify();
app.register(plugin, opts);
app.register(plugin, { routes: { prefix: '/v2' } });
app.register(cors, { origin: true });
app.register(plugin);");
assert_eq!(
reasons(&s, Family::Route),
[
"plugin options are not an object literal, so a path prefix cannot be ruled out",
"routes are mounted under a prefix \"/v2\"; listed paths under it are relative",
]
);
}
// --- variables expanded by a shell ---
#[test]
fn variables_expanded_by_a_shell_command_are_obligations() {
let s = run_js(
"const { execSync, exec } = require('child_process');
execSync('pg_dump \"$DATABASE_URL\" > /tmp/dump.sql');
exec('echo ${GREETING:-hi}');",
);
assert_eq!(items(&s, Family::Env), ["DATABASE_URL", "GREETING"]);
assert_eq!(
detail(&s, Family::Env, "GREETING").as_deref(),
Some("expanded by a shell command")
);
nothing_unresolved(&s);
}
#[test]
fn every_way_of_launching_a_shell_reads_its_variables() {
let s = run("import cp from 'node:child_process';
import { spawn, execFile } from 'child_process';
import { promisify } from 'node:util';
import { execa, execaCommand, $ as execa$ } from 'execa';
import { $ } from 'zx';
const run = promisify(cp.exec);
const CMD = 'echo $FROM_CONSTANT';
cp.execSync(CMD);
await run('echo $PROMISIFIED');
spawn('echo $SPAWNED', { shell: true });
spawn('sh', ['-c', 'echo $IN_ARGS'], { shell: true });
execFile('echo', ['$IN_FILE_ARGS'], { shell: '/bin/bash' });
await execa('echo $EXECA_SHELL', { shell: true });
await execaCommand('echo $EXECA_COMMAND', { shell: true });
await $`echo $ZX ${value}`;
await execa$({ shell: true })`echo $EXECA_TAG`;
await require('child_process').exec('echo $REQUIRED');");
assert_eq!(
items(&s, Family::Env),
[
"EXECA_COMMAND",
"EXECA_SHELL",
"EXECA_TAG",
"FROM_CONSTANT",
"IN_ARGS",
"IN_FILE_ARGS",
"PROMISIFIED",
"REQUIRED",
"SPAWNED",
"ZX"
]
);
nothing_unresolved(&s);
}
#[test]
fn a_command_without_a_shell_expands_nothing() {
let s = run("import { spawn, execFile } from 'child_process';
import { execa, $ } from 'execa';
spawn('echo', ['$HOME']);
spawn('echo $A', { shell: false });
execFile('echo', ['$B']);
await execa('echo', ['$C']);
await $`echo $D`;
console.log('$E');
other('echo $F');");
assert!(items(&s, Family::Env).is_empty(), "{:?}", s.found);
nothing_unresolved(&s);
}
#[test]
fn a_command_built_at_runtime_is_a_site() {
let s = run("import { exec, spawn } from 'child_process';
exec(`pg_dump $DATABASE_URL > ${file}`);
exec(command);
exec('cd ' + dir + ' && make $TARGET');
spawn('echo $MAYBE', options);");
assert_eq!(items(&s, Family::Env), ["DATABASE_URL", "TARGET"]);
assert_eq!(
reasons(&s, Family::Env),
[
"a shell command is built at runtime, so the environment variables it expands cannot be listed",
"a shell command is built at runtime, so the environment variables it expands cannot be listed",
"a shell command is built at runtime, so the environment variables it expands cannot be listed",
"a command that names environment variables may run through a shell (its options are not literal), so what it reads cannot be listed",
]
);
}
#[test]
fn shell_text_that_is_not_an_environment_variable_is_not_listed() {
for (command, expected) in [
("echo $1 $? $$ $! $# $@ $* $- $0", vec![]),
("echo $(date) $((1 + 2))", vec![]),
("echo '$QUOTED' \\$ESCAPED $'$ANSI'", vec![]),
("X=1; echo $X", vec![]),
("export Y=2 && echo ${Y}", vec![]),
("for f in *.txt; do echo $f; done", vec![]),
("read -p prompt name; echo $name", vec![]),
("echo $RANDOM $PWD $UID $LINENO $_", vec![]),
(
"echo \"$HOME\" ${#LEN} ${A:-$B}",
vec!["A", "B", "HOME", "LEN"],
),
("FOO=bar cmd \"$BAR\"", vec!["BAR"]),
] {
let vars = super::strings::shell_vars(command);
let mut names = vars.names.clone();
names.sort();
assert_eq!(names, expected, "{command}");
assert!(!vars.indirect, "{command}");
}
assert!(super::strings::shell_vars("echo ${!name}").indirect);
let s = run("import { execSync } from 'child_process'; execSync('echo ${!ref}');");
assert_eq!(
reasons(&s, Family::Env),
["a shell command expands a variable whose name is itself a variable (${!name})"]
);
}
// --- `process` imported dynamically ---
#[test]
fn a_dynamically_imported_process_reads_the_environment() {
let s = run("const { env } = await import('node:process');
env.SECRET_TOKEN;
const p = await import('process');
p.env.OTHER;
const { default: proc } = await import('process');
proc.env.THIRD;
(await import('process')).env.FOURTH;
(await import('node:process')).default.env.FIFTH;");
assert_eq!(
items(&s, Family::Env),
["FIFTH", "FOURTH", "OTHER", "SECRET_TOKEN", "THIRD"]
);
nothing_unresolved(&s);
}
#[test]
fn a_dynamically_imported_process_passed_on_is_a_site() {
for source in [
"import('process').then((p) => use(p.env));",
"const p = await import('process'); use(p);",
"export const p = await import('node:process');",
] {
let s = run(source);
assert!(
has_reason(&s, Family::Env, "the process object is passed on"),
"{source}: {:?}",
s.unresolved
);
}
// Control: another dynamically imported module is not `process`.
let s = run("const p = await import('./process.js'); p.env.X;");
assert!(items(&s, Family::Env).is_empty());
}
#[test]
fn every_other_way_to_reach_the_environment_is_read() {
let s = run("const a = require('process').env.A;
const { env: e } = require('node:process');
e.B;
const proc = require('process');
proc.env.C;
globalThis.process.env.D;
global['process'].env.E;
const f = import.meta.env.F;
const g = Deno.env.get('G');
const h = Bun.env.H;");
assert_eq!(
items(&s, Family::Env),
["A", "B", "C", "D", "E", "F", "G", "H"]
);
nothing_unresolved(&s);
let s = run("Deno.env.toObject(); Deno.env.set('X', '1'); Deno.env.entries();");
assert_eq!(reasons(&s, Family::Env).len(), 2, "{:?}", s.unresolved);
}
// --- evaluated code ---
#[test]
fn code_passed_as_a_string_is_a_site_in_every_surface_family() {
for source in [
"eval('process.env.API_TOKEN');",
"(0, eval)('process.env.API_TOKEN');",
"globalThis.eval(code);",
"new Function('return process.env.API_KEY')();",
"Function('return 1')();",
"import vm from 'node:vm'; vm.runInThisContext(code);",
"import { runInNewContext } from 'vm'; runInNewContext(code, {});",
"import vm from 'vm'; new vm.Script(code);",
"import { Worker } from 'worker_threads'; new Worker(code, { eval: true });",
] {
let s = run(source);
for family in [Family::Env, Family::Command, Family::Flag, Family::Route] {
assert!(
has_reason(&s, family, "code is evaluated from a string"),
"{source} {family:?}: {:?}",
s.unresolved
);
}
}
// Controls: a local function named `eval`, an `.eval` method of another object.
for source in [
"function evaluate(eval) { return eval(x); }",
"redis.eval(script, 0);",
"new Function();",
"import { Worker } from 'worker_threads'; new Worker('./w.js', { eval: false });",
] {
let s = run(source);
assert!(s.unresolved.is_empty(), "{source}: {:?}", s.unresolved);
}
}
// --- commander: aliases and help ---
#[test]
fn commander_aliases_and_help_command_are_listed() {
let s = run("import { Command } from 'commander';
const program = new Command();
program.command('remove').aliases(['rm', 'uninstall']);
program.command('list').alias('ls');
program.addCommand(new Command('show').alias('s'));
program.helpCommand('assist [command]', 'show assistance');
program.helpOption('-e, --HELP', 'help');
program.parse();");
assert_eq!(
items(&s, Family::Command),
["assist", "list", "remove", "show"]
);
assert_eq!(
detail(&s, Family::Command, "remove").as_deref(),
Some("alias rm; alias uninstall")
);
assert_eq!(
detail(&s, Family::Command, "show").as_deref(),
Some("alias s")
);
assert_eq!(
detail(&s, Family::Command, "list").as_deref(),
Some("alias ls")
);
assert_eq!(items(&s, Family::Flag), ["--HELP"]);
nothing_unresolved(&s);
}
#[test]
fn commander_computed_aliases_and_unknown_command_listeners_are_sites() {
let s = run("import { Command } from 'commander';
const program = new Command();
program.command('remove').alias(name);
program.command('list').aliases(names);
program.helpCommand(false);
program.helpOption(false);
program.on('command:*', () => {});
program.on('option:verbose', () => {});
program.parse();");
assert_eq!(
reasons(&s, Family::Command),
[
"command alias is not a string literal",
"command alias is not a string literal",
"commands the parser does not declare are handled by a listener, so they are read by hand",
]
);
assert_eq!(items(&s, Family::Command), ["list", "remove"]);
}
// --- mount prefixes read in the same file ---
#[test]
fn an_express_router_mounted_in_the_same_file_takes_the_prefix_whatever_the_order() {
let s = run(r#"
import express from "express";
const app = express();
app.use("/api", router);
app.use(express.json());
const router = express.Router();
router.get("/users", handler);
router.get("/", handler);
"#);
assert_eq!(items(&s, Family::Route), ["GET /api", "GET /api/users"]);
assert_eq!(
detail(&s, Family::Route, "GET /api/users").as_deref(),
Some("handler")
);
nothing_unresolved(&s);
}
#[test]
fn a_router_under_several_prefixes_and_chained_mounts_gives_each_composed_path() {
let s = run(r#"
const express = require("express");
const app = express();
const v1 = express.Router();
const users = express.Router();
users.get("/me", h);
v1.use("/users", users);
app.use(["/api", "/v1/"], v1);
app.get("/health", h);
"#);
assert_eq!(
items(&s, Family::Route),
["GET /api/users/me", "GET /health", "GET /v1/users/me"]
);
nothing_unresolved(&s);
}
#[test]
fn a_mount_that_cannot_be_followed_keeps_the_relative_path_and_its_site() {
let s = run(r#"
import express from "express";
const app = express();
const router = express.Router();
router.get("/u", h);
router.get("*", h);
app.use(PREFIX, router);
const other = express.Router();
other.get("/o", h);
app.use("/x", other);
app.use("/x", other);
const fallback = express.Router();
fallback.all("*", h);
app.use("/f", fallback);
"#);
assert_eq!(
items(&s, Family::Route),
["ALL *", "GET *", "GET /u", "GET /x/o"]
);
assert_eq!(
detail(&s, Family::Route, "GET /u").as_deref(),
Some("h; relative to a mount prefix that was not read")
);
assert_eq!(
reasons(&s, Family::Route),
[
"routes are mounted under a prefix that is not a string literal; listed paths under it are relative",
"routes are mounted under a prefix \"/f\"; listed paths under it are relative"
]
);
}
#[test]
fn mounts_that_form_a_cycle_end_with_a_relative_path() {
let s = run(r#"
import express from "express";
const a = express.Router();
const b = express.Router();
a.use("/b", b);
b.use("/a", a);
a.get("/z", h);
"#);
assert_eq!(items(&s, Family::Route), ["GET /z"]);
assert_eq!(
detail(&s, Family::Route, "GET /z").as_deref(),
Some("h; relative to a mount prefix that was not read")
);
assert_eq!(
reasons(&s, Family::Route),
[
"1 route(s) sit under mounts that form a cycle or nest too deeply; listed paths under them are relative"
]
);
}
#[test]
fn a_fastify_prefix_without_a_leading_slash_gets_one() {
let s = run(r#"
import Fastify from "fastify";
const app = Fastify();
app.register(async (inst) => {
inst.get("/b", h);
inst.get("/", h);
inst.register(async (deep) => { deep.get("/c", h); }, { prefix: "x" });
}, { prefix: "v1" });
app.register(async (inst) => { inst.get("/s", h); }, { prefix: "/v2/" });
"#);
assert_eq!(
items(&s, Family::Route),
["GET /v1", "GET /v1/b", "GET /v1/x/c", "GET /v2/s"]
);
assert!(reasons(&s, Family::Route).is_empty(), "{:?}", s.unresolved);
}
#[test]
fn fastify_joins_the_route_once_under_the_composed_prefix() {
// fastify serves `/v1/`, not `/v1`: the composed prefix `/v1/` keeps its trailing slash.
let s = run(r#"
import Fastify from "fastify";
const app = Fastify();
app.register(async (inst) => {
inst.register(async (deep) => {
deep.get("/", h);
deep.get("/c", h);
}, { prefix: "/" });
}, { prefix: "v1" });
"#);
assert_eq!(items(&s, Family::Route), ["GET /v1/", "GET /v1/c"]);
assert!(reasons(&s, Family::Route).is_empty(), "{:?}", s.unresolved);
}
#[test]
fn a_fastify_join_that_depends_on_the_major_version_is_a_site() {
// `/v1/` above `x`: `/v1//x/c` under fastify 4, `/v1/x/c` under fastify 5.
let s = run(r#"
import Fastify from "fastify";
const app = Fastify();
app.register(async (inst) => {
inst.register(async (deep) => { deep.get("/c", h); }, { prefix: "x" });
}, { prefix: "/v1/" });
"#);
assert_eq!(items(&s, Family::Route), ["GET /x/c"]);
assert_eq!(
detail(&s, Family::Route, "GET /x/c").as_deref(),
Some("h; relative to a mount prefix that was not read")
);
assert_eq!(
reasons(&s, Family::Route),
["routes are mounted under a prefix \"/v1/\"; listed paths under it are relative"]
);
}
#[test]
fn koa_router_prefixes_and_nested_routers_are_composed() {
let s = run(r#"
import Koa from "koa";
import Router from "@koa/router";
const app = new Koa();
const router = new Router({ prefix: "/api" });
const r2 = new Router();
r2.get("/y", h);
router.get("/x", h);
router.use("/nested", r2.routes());
app.use(router.routes()).use(router.allowedMethods());
const r3 = new Router();
r3.prefix("/v3/");
r3.get("/", h);
app.use(r3.routes());
"#);
assert_eq!(
items(&s, Family::Route),
["GET /api/nested/y", "GET /api/x", "GET /v3"]
);
assert_eq!(
detail(&s, Family::Route, "GET /api/x").as_deref(),
Some("h")
);
nothing_unresolved(&s);
}
#[test]
fn a_fastify_inline_plugin_takes_its_prefix() {
let s = run(r#"
import Fastify from "fastify";
const app = Fastify();
app.register(async (inst) => {
inst.get("/b", h);
inst.get("/", h);
}, { prefix: "/v1" });
app.register(async function (api) { api.post("/c", h); });
app.register(external, { prefix: "/ext" });
app.get("/root", h);
"#);
assert_eq!(
items(&s, Family::Route),
["GET /root", "GET /v1", "GET /v1/b", "POST /c"]
);
assert_eq!(
reasons(&s, Family::Route),
["routes are mounted under a prefix \"/ext\"; listed paths under it are relative"]
);
}
#[test]
fn hono_base_path_and_route_are_composed() {
let s = run(r#"
import { Hono } from "hono";
const app = new Hono();
const api = new Hono().basePath("/api").get("/z", h);
const books = new Hono();
books.get("/", h);
books.get("/:id", h);
app.route("/books", books);
"#);
assert_eq!(
items(&s, Family::Route),
["GET /api/z", "GET /books", "GET /books/:id"]
);
assert_eq!(
detail(&s, Family::Route, "GET /books").as_deref(),
Some("h")
);
nothing_unresolved(&s);
}
// --- hono: `env(c)` and `c.env` ---
#[test]
fn hono_adapter_env_reads_are_named() {
let s = run(r#"
import { Hono } from "hono";
import { env } from "hono/adapter";
const app = new Hono();
app.get("/", (c) => {
const { API_KEY } = env(c);
const b = env(c).B;
const e = env(c);
return c.text(e.C);
});
"#);
assert_eq!(items(&s, Family::Env), ["API_KEY", "B", "C"]);
assert!(reasons(&s, Family::Env).is_empty(), "{:?}", s.unresolved);
}
#[test]
fn hono_adapter_env_that_escapes_or_is_read_by_a_computed_key_is_a_site() {
let s = run(r#"
import { Hono } from "hono";
import { env } from "hono/adapter";
const app = new Hono();
app.get("/", (c) => {
send(env(c));
return c.text(env(c)[key]);
});
"#);
assert!(items(&s, Family::Env).is_empty(), "{:?}", s.found);
assert_eq!(reasons(&s, Family::Env).len(), 2, "{:?}", s.unresolved);
}
#[test]
fn hono_bindings_read_through_c_env_leave_one_site_per_file() {
let s = run(r#"
import { Hono } from "hono";
const app = new Hono();
app.get("/", (c) => c.text(c.env.DB_URL));
app.get("/x", (ctx) => ctx.text(ctx.env["OTHER"]));
"#);
assert!(items(&s, Family::Env).is_empty(), "{:?}", s.found);
assert_eq!(
reasons(&s, Family::Env),
["the handler reads runtime bindings through c.env; they are not listed"]
);
}
// --- yargs: the default command ---
#[test]
fn a_yargs_default_command_is_top_level() {
let s = run(r#"
import yargs from "yargs";
yargs(process.argv.slice(2))
.command("$0 [file]", "default", (y) => y.option("watch", { type: "boolean" }))
.command(["serve", "s", "$0"], "serve", { port: {} })
.command("*", "catch-all")
.parse();
"#);
assert_eq!(items(&s, Family::Command), ["serve"]);
assert_eq!(
detail(&s, Family::Command, "serve").as_deref(),
Some("alias s; default command")
);
assert_eq!(
items(&s, Family::Flag),
["--watch", "[file]", "serve/--port"]
);
}
// --- routes on an object of unknown origin ---
#[test]
fn literal_arguments_on_an_unknown_receiver_are_not_a_route() {
let s = run(r#"
import express from "express";
export async function download(sftp) {
await sftp.get("/remote/report.csv", "/tmp/report.csv");
await sftp.put("/tmp/a", "/remote/a", { mode: 0o644 }, ["x", 1, null, true]);
}
"#);
assert!(items(&s, Family::Route).is_empty(), "{:?}", s.found);
nothing_unresolved(&s);
}
#[test]
fn routes_on_an_unknown_receiver_are_marked_with_one_site_per_file() {
let s = run(r#"
import express from "express";
export function mount(r) {
r.get("/x", h);
r.post("/y", (req, res) => res.end());
}
"#);
assert_eq!(items(&s, Family::Route), ["GET /x", "POST /y"]);
assert_eq!(
detail(&s, Family::Route, "GET /x").as_deref(),
Some("h; receiver of unknown origin")
);
assert_eq!(
detail(&s, Family::Route, "POST /y").as_deref(),
Some("receiver of unknown origin")
);
assert_eq!(
reasons(&s, Family::Route),
["2 route(s) declared on an object whose origin is not known; they may not be routes"]
);
}