mod argument_entries;
pub use argument_entries::{ArgumentEntries, argument_entries, is_glob, is_script_runtime};
mod borp;
pub mod ci;
mod ci_action_inputs;
#[cfg(test)]
mod command_forms_tests;
mod command_wrappers;
mod config_tasks;
mod file_target_tools;
mod flag_credits;
pub mod hooks;
mod node_test;
pub mod nx_targets;
mod resolve;
mod shell;
mod shell_helpers;
pub mod vite_plus;
mod workspace_selection;
mod yarn_run;
#[expect(
clippy::disallowed_types,
reason = "package.json scripts are deserialized as std HashMap"
)]
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use rustc_hash::{FxHashMap, FxHashSet};
use command_wrappers::{command_wrapper_child_index, skip_command_wrappers};
pub use config_tasks::config_task_scripts;
use file_target_tools::file_target_tool;
pub use resolve::{
DependencyBinaries, all_dependency_names, build_bin_to_package_map, credit_npm_aliases,
project_bin_map, resolve_binary_to_packages, resolve_known_dependency_binary,
};
use shell::is_builtin_command;
pub use shell::{command_substitutions, split_shell_operators};
pub use workspace_selection::WorkspacePackages;
use workspace_selection::{PackageSelector, WorkspacePackage, relative_dir};
const ENV_WRAPPERS: &[&str] = &["cross-env", "dotenv", "env"];
const NODE_RUNNERS: &[&str] = &["node", "ts-node", "tsx", "babel-node", "bun"];
#[must_use]
pub fn script_externalizes_packages(script: &str) -> bool {
shell::split_shell_operators(script)
.into_iter()
.any(|segment| {
let words = shell::split_words(segment);
let tokens: Vec<&str> = words.iter().map(|word| word.value.as_ref()).collect();
command_externalizes_packages(&tokens)
})
}
#[must_use]
pub fn script_program_files(script: &str) -> Vec<String> {
shell::split_shell_operators(script)
.into_iter()
.filter_map(|segment| {
let words = shell::split_words(segment);
let tokens: Vec<&str> = words.iter().map(|word| word.value.as_ref()).collect();
command_program_file(&tokens)
})
.collect()
}
const NODE_INLINE_CODE_FLAGS: &[&str] = &["-e", "--eval", "-p", "--print"];
const NODE_RUNNER_VALUE_FLAGS: &[&str] = &[
"-r",
"--require",
"--import",
"--loader",
"--experimental-loader",
"-C",
"--conditions",
"--env-file",
"--env-file-if-exists",
"--input-type",
"--tsconfig",
];
const TEST_DIRECTORY_SEGMENTS: &[&str] = &["test", "tests", "__tests__"];
fn looks_like_test_file(path: &str) -> bool {
let mut segments = path.split('/').filter(|segment| !segment.is_empty());
let file_name = segments.next_back().unwrap_or_default();
file_name.contains(".test.")
|| file_name.contains(".spec.")
|| segments.any(|segment| TEST_DIRECTORY_SEGMENTS.contains(&segment))
}
fn command_program_file(tokens: &[&str]) -> Option<String> {
let idx = shell::skip_initial_wrappers(tokens, 0)?;
let runs_binary = tokens[idx] != "bun" || matches!(tokens.get(idx + 1), Some(&("x" | "exec")));
let runner_idx = if runs_binary {
shell::advance_past_package_manager(tokens, idx)?
} else {
idx
};
let runner = tool_name(tokens[runner_idx]);
if !NODE_RUNNERS.contains(&runner) {
return None;
}
let mut i = runner_idx + 1;
while let Some(&token) = tokens.get(i) {
if NODE_INLINE_CODE_FLAGS.contains(&token) || token.starts_with("--test") {
return None;
}
if NODE_RUNNER_VALUE_FLAGS.contains(&token) {
i += 2;
continue;
}
if token.starts_with('-') || (runner == "bun" && matches!(token, "run" | "run-script")) {
i += 1;
continue;
}
return (looks_like_file_path(token) && !looks_like_test_file(token))
.then(|| token.to_string());
}
None
}
fn command_externalizes_packages(tokens: &[&str]) -> bool {
let Some(idx) = shell::skip_initial_wrappers(tokens, 0) else {
return false;
};
let args_start = if let Some(build_idx) = bun_build_subcommand(tokens, idx) {
build_idx + 1
} else {
let Some(binary_idx) = shell::advance_past_package_manager(tokens, idx) else {
return false;
};
if tool_name(tokens[binary_idx]) != "esbuild" {
return false;
}
binary_idx + 1
};
let args = tokens.get(args_start..).unwrap_or_default();
args.iter().enumerate().any(|(i, arg)| {
*arg == "--packages=external"
|| (*arg == "--packages" && args.get(i + 1) == Some(&"external"))
})
}
fn bun_build_subcommand(tokens: &[&str], idx: usize) -> Option<usize> {
if tokens.get(idx) != Some(&"bun") {
return None;
}
let mut next = idx + 1;
while tokens
.get(next)
.is_some_and(|token| shell::BUN_RUNTIME_FLAGS.contains(token))
{
next += 1;
}
(tokens.get(next) == Some(&"build")).then_some(next)
}
#[must_use]
pub fn is_file_target_tool(binary: &str) -> bool {
file_target_tool(binary).is_some()
}
fn tool_name(binary: &str) -> &str {
binary.rsplit('/').next().unwrap_or(binary)
}
#[derive(Debug, Clone, Copy, Default)]
pub struct IgnoredCommandEntries<'a> {
names: &'a [String],
}
impl<'a> IgnoredCommandEntries<'a> {
pub const NONE: Self = Self { names: &[] };
#[must_use]
pub const fn new(names: &'a [String]) -> Self {
Self { names }
}
#[must_use]
pub fn contains(&self, command: &str) -> bool {
let name = tool_name(command);
self.names
.iter()
.any(|ignored| ignored == "*" || ignored == name)
}
}
const DIRECTORY_MODULE_GLOB: &str = "*.{js,cjs,mjs,ts,cts,mts}";
#[must_use]
pub fn file_target_tool_loaded_files(binary: &str, args: &[&str]) -> Vec<String> {
let Some(tool) = file_target_tool(binary) else {
return Vec::new();
};
let takes_value =
|flag: &str| tool.loading_flags.contains(&flag) || tool.directory_flags.contains(&flag);
let mut files = Vec::new();
let mut idx = 0;
while idx < args.len() {
let token = args[idx];
idx += 1;
let (flag, value) = if takes_value(token) {
let Some(&next) = args.get(idx) else { break };
idx += 1;
(token, next)
} else if let Some((flag, value)) = token.split_once('=')
&& takes_value(flag)
{
(flag, value)
} else {
continue;
};
let value = strip_surrounding_quotes(value);
if tool.directory_flags.contains(&flag) {
files.extend(directory_module_glob(value));
} else if looks_like_file_path(value) {
files.push(value.to_string());
}
}
files
}
fn directory_module_glob(dir: &str) -> Option<String> {
if dir.is_empty()
|| dir.starts_with('-')
|| dir.starts_with('@')
|| dir.contains("://")
|| dir.contains(char::is_whitespace)
|| !could_be_file_path(dir)
{
return None;
}
let dir = dir.trim_end_matches('/');
Some(match dir.trim_start_matches("./") {
"" | "." => DIRECTORY_MODULE_GLOB.to_string(),
_ => format!("{dir}/{DIRECTORY_MODULE_GLOB}"),
})
}
const SCRIPT_MULTIPLEXERS: &[&str] = &[
"concurrently",
"npm-run-all",
"npm-run-all2",
"run-s",
"run-p",
"run-s2",
"run-p2",
];
const CONCURRENTLY: &str = "concurrently";
const CONCURRENTLY_SCRIPT_SHORTCUTS: &[&str] =
&["npm:", "pnpm:", "yarn:", "bun:", "node:", "deno:"];
const CONCURRENTLY_VALUE_FLAGS: &[&str] = &[
"-m",
"--max-processes",
"-n",
"--names",
"--name-separator",
"-s",
"--success",
"--hide",
"-p",
"--prefix",
"-c",
"--prefix-colors",
"-l",
"--prefix-length",
"-t",
"--timestamp-format",
"--kill-signal",
"--ks",
"--kill-timeout",
"--restart-tries",
"--restart-after",
"--default-input-target",
];
const CONCURRENTLY_TEARDOWN_FLAG: &str = "--teardown";
const CONCURRENTLY_PASSTHROUGH_FLAGS: &[&str] = &["-P", "--passthrough-arguments"];
fn concurrently_inline_commands<'a>(args: &[&'a str]) -> Vec<&'a str> {
let passthrough = args
.iter()
.any(|arg| CONCURRENTLY_PASSTHROUGH_FLAGS.contains(arg));
let mut commands = Vec::new();
let mut options_done = false;
let mut iter = args.iter().copied();
while let Some(arg) = iter.next() {
if !options_done && arg == "--" {
if passthrough {
break;
}
options_done = true;
continue;
}
if !options_done && arg.starts_with('-') {
if arg == CONCURRENTLY_TEARDOWN_FLAG {
commands.extend(iter.next());
} else if let Some(value) = arg.strip_prefix("--teardown=") {
commands.push(value);
} else if CONCURRENTLY_VALUE_FLAGS.contains(&arg) {
iter.next();
}
continue;
}
let is_script_shortcut = CONCURRENTLY_SCRIPT_SHORTCUTS
.iter()
.any(|prefix| arg.starts_with(prefix));
if !is_script_shortcut && !arg.trim().is_empty() {
commands.push(arg);
}
}
commands
}
const PNPM_BUILTIN_COMMANDS: &[&str] = &[
"add",
"audit",
"bin",
"catalog",
"ci",
"config",
"dedupe",
"deploy",
"env",
"exec",
"fetch",
"import",
"init",
"install",
"licenses",
"link",
"list",
"outdated",
"pack",
"patch",
"prune",
"publish",
"rebuild",
"remove",
"root",
"run",
"run-script",
"setup",
"start",
"stop",
"store",
"test",
"unlink",
"update",
"why",
];
const NPM_LOCATION_VALUE_FLAGS: &[&str] = &[
"-w",
"--workspace",
"-C",
"--prefix",
"-L",
"--location",
"--userconfig",
"--globalconfig",
"--cache",
"--logs-dir",
"--pack-destination",
];
const NPM_REGISTRY_VALUE_FLAGS: &[&str] = &[
"--registry",
"--reg",
"--replace-registry-host",
"--scope",
"--otp",
"--auth-type",
"--access",
"--ca",
"--cafile",
"--cert",
"--key",
"--proxy",
"--https-proxy",
"--noproxy",
"--local-address",
"--cidr",
"--user-agent",
"--maxsockets",
"--fetch-retries",
"--fetch-retry-factor",
"--fetch-retry-maxtimeout",
"--fetch-retry-mintimeout",
"--fetch-timeout",
"--cache-max",
"--cache-min",
];
const NPM_DEPENDENCY_VALUE_FLAGS: &[&str] = &[
"--tag",
"--before",
"--enjoy-by",
"--include",
"--omit",
"--only",
"--also",
"--install-strategy",
"--save-prefix",
"--lockfile-version",
"--depth",
"--cpu",
"--os",
"--libc",
"--package",
];
const NPM_RUNTIME_VALUE_FLAGS: &[&str] = &[
"--node-options",
"--script-shell",
"--shell",
"-c",
"--call",
"--editor",
"--viewer",
"--umask",
"--which",
];
const NPM_OUTPUT_VALUE_FLAGS: &[&str] = &[
"--loglevel",
"--logs-max",
"--heading",
"--audit-level",
"--diff",
"--diff-dst-prefix",
"--diff-src-prefix",
"--diff-unified",
"--sbom-format",
"--sbom-type",
"--searchexclude",
"--searchlimit",
"--searchopts",
"--searchstaleness",
"--expect-result-count",
];
const NPM_PUBLISH_VALUE_FLAGS: &[&str] = &[
"-m",
"--message",
"--preid",
"--tag-version-prefix",
"--git",
"--provenance-file",
"--init-author-email",
"--init-author-name",
"--init-author-url",
"--init-license",
"--init-module",
"--init-version",
];
const NPM_CONFIG_VALUE_FLAG_GROUPS: &[&[&str]] = &[
NPM_LOCATION_VALUE_FLAGS,
NPM_REGISTRY_VALUE_FLAGS,
NPM_DEPENDENCY_VALUE_FLAGS,
NPM_RUNTIME_VALUE_FLAGS,
NPM_OUTPUT_VALUE_FLAGS,
NPM_PUBLISH_VALUE_FLAGS,
];
fn npm_flag_takes_value(flag: &str) -> bool {
NPM_CONFIG_VALUE_FLAG_GROUPS
.iter()
.any(|group| group.contains(&flag))
}
const YARN_FOREACH_BOOLEAN_FLAGS: &[&str] = &[
"-A",
"--all",
"-R",
"--recursive",
"-W",
"--worktree",
"-v",
"--verbose",
"-p",
"--parallel",
"-i",
"--interlaced",
"-t",
"--topological",
"--topological-dev",
"--no-private",
"-n",
"--dry-run",
"--since",
];
const YARN_FOREACH_VALUE_FLAGS: &[&str] = &["-j", "--jobs", "--include", "--exclude", "--from"];
const TASK_RUNNERS: &[&str] = &["turbo", "nx", "lerna"];
const PNPM_FILTER_FLAGS: &[&str] = &["--filter", "-F", "--filter-prod"];
const PNPM_EXEC_BOOLEAN_FLAGS: &[&str] = &[
"--silent",
"-s",
"-r",
"--recursive",
"--parallel",
"--stream",
"-w",
"--workspace-root",
"--include-workspace-root",
"--no-bail",
"--sequential",
"--reverse",
"--report-summary",
];
const PNPM_EXEC_VALUE_FLAGS: &[&str] = &[
"--filter",
"-F",
"--filter-prod",
"-C",
"--dir",
"--workspace-concurrency",
"--resume-from",
];
const PACKAGE_MANAGER_BUILTIN_COMMANDS: &[&str] = &[
"add",
"audit",
"bin",
"cache",
"config",
"create",
"dedupe",
"dlx",
"exec",
"global",
"import",
"info",
"init",
"install",
"link",
"list",
"login",
"logout",
"ls",
"node",
"outdated",
"pack",
"patch",
"publish",
"remove",
"run",
"run-script",
"set",
"unlink",
"up",
"upgrade",
"version",
"why",
"workspace",
"workspaces",
];
pub const MAX_SCRIPT_INDIRECTION_DEPTH: usize = 8;
pub const MAX_SCRIPT_EXPANSIONS: usize = 64;
pub const MAX_SUBSTITUTION_DEPTH: usize = 8;
#[derive(Debug, Clone)]
struct CatalogBody {
body: String,
local: bool,
}
#[derive(Debug, Default, Clone)]
pub struct ScriptCatalog {
names: FxHashSet<String>,
bodies: FxHashMap<String, CatalogBody>,
ambiguous: FxHashSet<String>,
workspaces: Option<Arc<WorkspacePackages>>,
package_dir: String,
helper_base: shell_helpers::HelperBase,
}
impl ScriptCatalog {
#[cfg(test)]
pub const EMPTY: &'static Self = &Self {
names: FxHashSet::with_hasher(rustc_hash::FxBuildHasher),
bodies: FxHashMap::with_hasher(rustc_hash::FxBuildHasher),
ambiguous: FxHashSet::with_hasher(rustc_hash::FxBuildHasher),
workspaces: None,
package_dir: String::new(),
helper_base: shell_helpers::HelperBase::Package,
};
#[must_use]
pub fn with_workspaces(
mut self,
workspaces: Arc<WorkspacePackages>,
package_dir: &str,
) -> Self {
self.workspaces = Some(workspaces);
package_dir
.trim_matches('/')
.clone_into(&mut self.package_dir);
self
}
fn selected_packages(&self, selectors: &[PackageSelector]) -> Vec<&WorkspacePackage> {
self.workspaces
.as_deref()
.map(|workspaces| workspaces.select(selectors, &self.package_dir))
.unwrap_or_default()
}
fn location_packages(&self, location: &RunLocation) -> Option<Vec<&WorkspacePackage>> {
match location {
RunLocation::Packages(selectors) => Some(self.selected_packages(selectors)),
RunLocation::Directory(dir) => {
Some(self.selected_packages(&[PackageSelector::directory(dir)]))
}
RunLocation::Here | RunLocation::OtherPackages => None,
}
}
fn script_call_location(&self, location: RunLocation) -> RunLocation {
if let RunLocation::Directory(dir) = &location {
let selector = PackageSelector::directory(dir);
if !self
.selected_packages(std::slice::from_ref(&selector))
.is_empty()
{
return RunLocation::Packages(vec![selector]);
}
}
location
}
fn relative_package_dir(&self, package: &WorkspacePackage) -> String {
relative_dir(&self.package_dir, package.dir())
}
#[must_use]
pub fn for_package_command(&self, command: &PackageScriptCommand) -> Self {
self.workspaces
.as_deref()
.and_then(|workspaces| workspaces.find_dir(&command.package_dir))
.map_or_else(Self::default, |package| self.package_catalog(package))
}
fn package_catalog(&self, package: &WorkspacePackage) -> Self {
let catalog = Self::from_scripts(package.scripts());
match &self.workspaces {
Some(workspaces) => catalog.with_workspaces(Arc::clone(workspaces), package.dir()),
None => catalog,
}
}
fn declares_script_at(&self, name: &str, location: &RunLocation) -> bool {
if let Some(packages) = self.location_packages(location)
&& !packages.is_empty()
{
return packages
.iter()
.any(|package| package.scripts().contains_key(name));
}
self.contains(name)
}
#[must_use]
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn from_scripts(scripts: &HashMap<String, String>) -> Self {
let mut catalog = Self::default();
catalog.merge_scripts(scripts);
catalog
}
#[must_use]
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn from_scripts_with_bodies(
all: &HashMap<String, String>,
analyzed: &HashMap<String, String>,
) -> Self {
let mut catalog = Self::from_scripts(analyzed);
catalog.names.extend(all.keys().cloned());
catalog
}
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn merge_scripts(&mut self, scripts: &HashMap<String, String>) {
self.merge(scripts, true);
}
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn merge_workspace_scripts(&mut self, scripts: &HashMap<String, String>) {
self.merge(scripts, false);
}
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
fn merge(&mut self, scripts: &HashMap<String, String>, local: bool) {
for (name, body) in scripts {
self.names.insert(name.clone());
if self.ambiguous.contains(name) {
continue;
}
match self.bodies.get_mut(name) {
Some(existing) if existing.body == *body => {
existing.local = existing.local || local;
}
Some(_) => {
self.bodies.remove(name);
self.ambiguous.insert(name.clone());
}
None => {
self.bodies.insert(
name.clone(),
CatalogBody {
body: body.clone(),
local,
},
);
}
}
}
}
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.names.contains(name)
}
fn body(&self, name: &str) -> Option<&CatalogBody> {
if self.ambiguous.contains(name) {
return None;
}
self.bodies.get(name)
}
}
struct ScriptExpansion {
active: Vec<String>,
expansions: usize,
local_paths: bool,
substitution_depth: usize,
}
impl ScriptExpansion {
fn new() -> Self {
Self {
active: Vec::new(),
expansions: 0,
local_paths: true,
substitution_depth: 0,
}
}
}
struct ScriptCommandContext<'a> {
declared_packages: &'a FxHashSet<String>,
scripts: &'a ScriptCatalog,
ignored: IgnoredCommandEntries<'a>,
}
enum PackageManagerTarget {
Binary(usize, RunLocation),
Script {
name: String,
forwarded: Vec<usize>,
location: RunLocation,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum RunLocation {
Here,
Directory(String),
Packages(Vec<PackageSelector>),
OtherPackages,
}
impl RunLocation {
fn select_all_packages(&mut self) {
self.select_package(PackageSelector::all());
}
fn select_unresolved_packages(&mut self) {
*self = Self::OtherPackages;
}
fn select_package(&mut self, selector: PackageSelector) {
match self {
Self::Packages(selectors) => selectors.push(selector),
_ => *self = Self::Packages(vec![selector]),
}
}
fn select_directory(&mut self, dir: &str) {
if *self == Self::Here {
*self = Self::Directory(strip_surrounding_quotes(dir).to_string());
}
}
fn nest(self, inner: Self) -> Self {
match (self, inner) {
(Self::OtherPackages, _)
| (_, Self::OtherPackages)
| (Self::Packages(_), Self::Directory(_)) => Self::OtherPackages,
(Self::Here, inner) => inner,
(outer, Self::Here) => outer,
(Self::Directory(outer), Self::Directory(inner)) => {
Self::Directory(rebase_path(&outer, &inner))
}
(_, Self::Packages(selectors)) => Self::Packages(selectors),
}
}
fn base_dirs(&self, catalog: &ScriptCatalog) -> Option<Vec<String>> {
match self {
Self::Here => None,
Self::Directory(dir) => Some(vec![dir.clone()]),
Self::Packages(selectors) => Some(
catalog
.selected_packages(selectors)
.into_iter()
.map(|package| catalog.relative_package_dir(package))
.collect(),
),
Self::OtherPackages => Some(Vec::new()),
}
}
fn resolve_all(&self, paths: Vec<String>, catalog: &ScriptCatalog) -> Vec<String> {
match self.base_dirs(catalog) {
None => paths,
Some(dirs) => rebase_all(&dirs, &paths),
}
}
}
fn rebase_all(dirs: &[String], paths: &[String]) -> Vec<String> {
dirs.iter()
.flat_map(|dir| paths.iter().map(|path| rebase_path(dir, path)))
.collect()
}
#[must_use]
pub fn rebase_path(dir: &str, path: &str) -> String {
let dir = dir.trim_end_matches('/');
let path = path.trim_start_matches("./");
match dir.trim_start_matches("./") {
"" | "." => path.to_string(),
_ => format!("{dir}/{path}"),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvokedCommand {
pub index: usize,
base_dirs: Option<Vec<String>>,
}
impl InvokedCommand {
#[must_use]
pub fn file_refs(&self, path: &str) -> Vec<String> {
match &self.base_dirs {
None => vec![path.to_string()],
Some(dirs) => dirs.iter().map(|dir| rebase_path(dir, path)).collect(),
}
}
#[must_use]
pub fn runs_in_other_packages(&self) -> bool {
self.base_dirs.as_ref().is_some_and(Vec::is_empty)
}
}
#[derive(Debug, Default)]
pub struct ScriptAnalysis {
pub used_packages: FxHashSet<String>,
pub config_files: Vec<String>,
pub binary_config_files: Vec<BinaryConfigFile>,
pub entry_files: Vec<String>,
pub test_entry_files: Vec<String>,
}
impl ScriptAnalysis {
fn dedupe_paths(&mut self) {
retain_first_seen(&mut self.config_files);
retain_first_seen(&mut self.binary_config_files);
retain_first_seen(&mut self.entry_files);
retain_first_seen(&mut self.test_entry_files);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BinaryConfigFile {
pub binary: String,
pub path: String,
}
fn retain_first_seen<T: Clone + Eq + std::hash::Hash>(values: &mut Vec<T>) {
let mut seen: FxHashSet<T> = FxHashSet::default();
values.retain(|value| seen.insert(value.clone()));
}
#[must_use]
pub fn normalize_script_entry_pattern(ws_prefix: &str, raw: &str) -> Option<String> {
let trimmed = raw.trim_start_matches("./");
if trimmed.is_empty() || trimmed.starts_with('/') {
return None;
}
let combined = if ws_prefix.is_empty() {
trimmed.to_string()
} else {
format!("{}/{}", ws_prefix.trim_end_matches('/'), trimmed)
};
let mut stack: Vec<&str> = Vec::new();
let mut segments = combined.split('/').peekable();
while let Some(segment) = segments.next() {
match segment {
"" if segments.peek().is_some() => return None,
"" | "." => {}
".." => {
stack.pop()?;
}
other => stack.push(other),
}
}
if stack.is_empty() {
None
} else {
Some(stack.join("/"))
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct ScriptCommand {
pub binary: String,
pub config_args: Vec<String>,
pub file_args: Vec<String>,
pub file_args_command: String,
pub flag_packages: Vec<String>,
pub production_runtime_host: Option<&'static str>,
pub test_file_args: Vec<String>,
}
impl ScriptCommand {
#[must_use]
pub fn entry_files(&self, ignored: IgnoredCommandEntries<'_>) -> &[String] {
if ignored.contains(&self.file_args_command) {
&[]
} else {
&self.file_args
}
}
#[must_use]
pub fn test_entry_files(&self, ignored: IgnoredCommandEntries<'_>) -> &[String] {
if ignored.contains(&self.file_args_command) {
&[]
} else {
&self.test_file_args
}
}
fn map_paths(&mut self, map: impl Fn(Vec<String>) -> Vec<String>) {
self.config_args = map(std::mem::take(&mut self.config_args));
self.file_args = map(std::mem::take(&mut self.file_args));
self.test_file_args = map(std::mem::take(&mut self.test_file_args));
}
}
#[must_use]
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn filter_production_scripts(scripts: &HashMap<String, String>) -> HashMap<String, String> {
scripts
.iter()
.filter(|(name, _)| is_production_script(name))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
pub fn production_runtime_hosts(pkg: &fallow_config::PackageJson) -> FxHashSet<String> {
let Some(scripts) = &pkg.scripts else {
return FxHashSet::default();
};
let catalog = ScriptCatalog::from_scripts(scripts);
let declared = pkg.all_dependency_names();
let mut queue: Vec<String> = scripts
.keys()
.filter(|name| {
let name = name.split(':').next().unwrap_or(name);
let base = name
.strip_prefix("pre")
.or_else(|| name.strip_prefix("post"))
.unwrap_or(name);
matches!(base, "start" | "serve")
})
.cloned()
.collect();
let mut visited = FxHashSet::default();
let mut hosts = FxHashSet::default();
while let Some(name) = queue.pop() {
if !visited.insert(name.clone()) {
continue;
}
let Some(script) = scripts.get(&name) else {
continue;
};
queue.extend(referenced_package_scripts(script, &catalog));
hosts.extend(
parse_script_with_catalog(script, &catalog)
.into_iter()
.filter_map(|command| command.production_runtime_host)
.filter(|package| declared.iter().any(|name| name == package))
.map(str::to_string),
);
}
hosts
}
fn is_production_script(name: &str) -> bool {
let root_name = name.split(':').next().unwrap_or(name);
if matches!(
root_name,
"start" | "build" | "serve" | "preview" | "prepare" | "prepublishOnly" | "postinstall"
) {
return true;
}
let base = root_name
.strip_prefix("pre")
.or_else(|| root_name.strip_prefix("post"));
base.is_some_and(|base| matches!(base, "start" | "build" | "serve" | "install"))
}
#[must_use]
#[expect(
clippy::disallowed_types,
reason = "API matches serde-deserialized HashMap from package.json"
)]
pub fn analyze_scripts_with_dependency_context(
scripts: &HashMap<String, String>,
root: &Path,
bin_map: &FxHashMap<String, String>,
declared_packages: &FxHashSet<String>,
catalog: &ScriptCatalog,
ignored: IgnoredCommandEntries<'_>,
) -> ScriptAnalysis {
analyze_commands_with_context(
scripts.values(),
root,
bin_map,
declared_packages,
catalog,
ignored,
)
}
#[must_use]
pub fn analyze_commands_with_context<'a, I>(
commands: I,
root: &Path,
bin_map: &FxHashMap<String, String>,
declared_packages: &FxHashSet<String>,
catalog: &ScriptCatalog,
ignored: IgnoredCommandEntries<'_>,
) -> ScriptAnalysis
where
I: IntoIterator<Item = &'a String>,
{
let mut result = ScriptAnalysis::default();
let context = ScriptCommandContext {
declared_packages,
scripts: catalog,
ignored,
};
for command in commands {
shell_helpers::accumulate_command_and_helpers(
command,
root,
bin_map,
&context,
&mut result,
);
}
result.dedupe_paths();
result
}
#[must_use]
pub fn analyze_command(
command: &str,
root: &Path,
bin_map: &FxHashMap<String, String>,
) -> ScriptAnalysis {
let mut result = ScriptAnalysis::default();
accumulate_command(command, root, bin_map, &mut result);
result.dedupe_paths();
result
}
fn accumulate_command(
command: &str,
root: &Path,
bin_map: &FxHashMap<String, String>,
result: &mut ScriptAnalysis,
) {
accumulate_parsed_commands(
command,
root,
bin_map,
parse_script(command),
IgnoredCommandEntries::NONE,
result,
);
}
fn accumulate_parsed_commands(
command: &str,
root: &Path,
bin_map: &FxHashMap<String, String>,
parsed: Vec<ScriptCommand>,
ignored: IgnoredCommandEntries<'_>,
result: &mut ScriptAnalysis,
) {
for wrapper in ENV_WRAPPERS {
if command.split_whitespace().any(|token| token == *wrapper) && !is_builtin_command(wrapper)
{
result
.used_packages
.extend(resolve_binary_to_packages(wrapper, root, bin_map));
}
}
for cmd in parsed {
if !cmd.binary.is_empty() && !is_builtin_command(&cmd.binary) {
let runner = NODE_RUNNERS.contains(&resolve::binary_name(&cmd.binary));
for binary in resolve::credited_binaries(&cmd.binary, &cmd.file_args, runner) {
result
.used_packages
.extend(resolve_binary_to_packages(binary, root, bin_map));
}
}
result
.test_entry_files
.extend_from_slice(cmd.test_entry_files(ignored));
result
.entry_files
.extend_from_slice(cmd.entry_files(ignored));
result.used_packages.extend(cmd.flag_packages);
result
.binary_config_files
.extend(cmd.config_args.iter().map(|path| BinaryConfigFile {
binary: cmd.file_args_command.clone(),
path: path.clone(),
}));
result.config_files.extend(cmd.config_args);
}
}
#[must_use]
pub fn is_shell_builtin(cmd: &str) -> bool {
is_builtin_command(cmd)
}
#[must_use]
pub fn script_binaries(script: &str) -> Vec<String> {
let mut binaries = Vec::new();
for segment in shell::split_shell_operators(script) {
if shell::downloads_its_command(segment) {
continue;
}
for command in parse_script(segment) {
if !command.binary.is_empty() && !binaries.contains(&command.binary) {
binaries.push(command.binary);
}
}
}
binaries
}
#[must_use]
pub fn package_bin_names(pkg: &fallow_config::PackageJson) -> Vec<String> {
let (Some(name), Some(bin)) = (pkg.name.as_deref(), pkg.bin.as_ref()) else {
return Vec::new();
};
resolve::bin_names(name, bin)
.into_iter()
.map(str::to_string)
.collect()
}
#[must_use]
pub fn parse_script(script: &str) -> Vec<ScriptCommand> {
parse_script_with_catalog(script, &ScriptCatalog::default())
}
#[must_use]
pub fn parse_script_with_catalog(script: &str, catalog: &ScriptCatalog) -> Vec<ScriptCommand> {
let mut commands = Vec::new();
let mut state = ScriptExpansion::new();
parse_script_internal(
script,
&|tokens, idx, catalog| {
bun_file_runner_target(tokens, idx, catalog)
.or_else(|| script_invocation_target(tokens, idx, catalog))
.or_else(|| {
package_manager_exec_binary(tokens, idx).map(|(binary_idx, location)| {
PackageManagerTarget::Binary(binary_idx, location)
})
})
.or_else(|| {
shell::advance_past_package_manager(tokens, idx).map(|binary_idx| {
PackageManagerTarget::Binary(binary_idx, RunLocation::Here)
})
})
},
catalog,
&mut state,
&mut commands,
);
commands
}
pub fn referenced_package_scripts(command: &str, catalog: &ScriptCatalog) -> FxHashSet<String> {
let mut names = FxHashSet::default();
for segment in shell::split_shell_operators(command) {
let words = shell::split_words(segment);
let tokens: Vec<&str> = words.iter().map(|word| word.value.as_ref()).collect();
let Some(idx) = skip_command_wrappers(&tokens) else {
continue;
};
if let Some(binary) = tokens.get(idx).copied()
&& SCRIPT_MULTIPLEXERS.contains(&binary)
{
let mut skip_next = false;
for token in &tokens[idx + 1..] {
if skip_next {
skip_next = false;
continue;
}
if matches!(*token, "--names" | "--prefix" | "--max-parallel") {
skip_next = true;
continue;
}
let name = token.strip_prefix("npm:").unwrap_or(token);
if !name.starts_with('-') && catalog.contains(name) {
names.insert(name.to_string());
}
}
if binary == CONCURRENTLY {
for inline in concurrently_inline_commands(&tokens[idx + 1..]) {
names.extend(referenced_package_scripts(inline, catalog));
}
}
continue;
}
if let Some(invocation) = declared_script_invocation(&tokens, idx, catalog)
&& invocation.location == RunLocation::Here
{
names.insert(invocation.name.to_string());
}
}
names
}
pub fn referenced_workspace_scripts(
command: &str,
catalog: &ScriptCatalog,
) -> Vec<(String, String)> {
let mut references = Vec::new();
for segment in shell::split_shell_operators(command) {
let words = shell::split_words(segment);
let tokens: Vec<&str> = words.iter().map(|word| word.value.as_ref()).collect();
let Some(idx) = shell::skip_initial_wrappers(&tokens, 0) else {
continue;
};
if tokens[idx] == CONCURRENTLY {
for inline in concurrently_inline_commands(&tokens[idx + 1..]) {
references.extend(referenced_workspace_scripts(inline, catalog));
}
continue;
}
let Some(invocation) = declared_script_invocation(&tokens, idx, catalog) else {
continue;
};
let RunLocation::Packages(selectors) = &invocation.location else {
continue;
};
references.extend(
catalog
.selected_packages(selectors)
.into_iter()
.filter(|package| package.scripts().contains_key(invocation.name))
.map(|package| (package.dir().to_string(), invocation.name.to_string())),
);
}
references.sort_unstable();
references.dedup();
references
}
fn parse_script_with_context(
script: &str,
root: &Path,
bin_map: &FxHashMap<String, String>,
context: &ScriptCommandContext<'_>,
) -> Vec<ScriptCommand> {
let mut commands = Vec::new();
let mut state = ScriptExpansion::new();
parse_script_internal(
script,
&|tokens, idx, catalog| {
advance_past_package_manager_with_context(tokens, idx, root, bin_map, context, catalog)
},
context.scripts,
&mut state,
&mut commands,
);
commands
}
fn parse_script_internal(
script: &str,
advance_package_manager: &impl Fn(&[&str], usize, &ScriptCatalog) -> Option<PackageManagerTarget>,
catalog: &ScriptCatalog,
state: &mut ScriptExpansion,
commands: &mut Vec<ScriptCommand>,
) {
for segment in shell::split_shell_operators(script) {
let segment = segment.trim();
if segment.is_empty() {
continue;
}
for outcome in parse_command_segment(segment, advance_package_manager, catalog) {
match outcome {
SegmentOutcome::Command(mut cmd) => {
if !state.local_paths {
cmd.config_args.clear();
cmd.file_args.clear();
cmd.test_file_args.clear();
}
commands.push(cmd);
}
SegmentOutcome::ScriptCall {
name,
extra_args,
location: RunLocation::Packages(selectors),
} => {
for package in catalog.selected_packages(&selectors) {
let dir = catalog.relative_package_dir(package);
let package_catalog = catalog.package_catalog(package);
let start = commands.len();
resolve_script_call(
&name,
&extra_args,
advance_package_manager,
&package_catalog,
state,
commands,
);
for cmd in &mut commands[start..] {
cmd.map_paths(|paths| rebase_all(std::slice::from_ref(&dir), &paths));
}
}
}
SegmentOutcome::InlineCommand { command, location } => {
let start = commands.len();
parse_script_internal(
&command,
advance_package_manager,
catalog,
state,
commands,
);
for cmd in &mut commands[start..] {
cmd.map_paths(|paths| location.resolve_all(paths, catalog));
}
}
SegmentOutcome::ScriptCall {
name, extra_args, ..
} => {
resolve_script_call(
&name,
&extra_args,
advance_package_manager,
catalog,
state,
commands,
);
}
}
}
}
if state.substitution_depth >= MAX_SUBSTITUTION_DEPTH {
return;
}
for body in shell::command_substitutions(script) {
state.substitution_depth += 1;
parse_script_internal(body, advance_package_manager, catalog, state, commands);
state.substitution_depth -= 1;
}
}
fn resolve_script_call(
name: &str,
extra_args: &str,
advance_package_manager: &impl Fn(&[&str], usize, &ScriptCatalog) -> Option<PackageManagerTarget>,
catalog: &ScriptCatalog,
state: &mut ScriptExpansion,
commands: &mut Vec<ScriptCommand>,
) {
if extra_args.is_empty()
|| state.active.len() >= MAX_SCRIPT_INDIRECTION_DEPTH
|| state.expansions >= MAX_SCRIPT_EXPANSIONS
{
return;
}
let Some(entry) = catalog.body(name) else {
return;
};
if state.active.iter().any(|active_name| active_name == name) {
return;
}
let expanded = format!("{} {extra_args}", entry.body);
let outer_local_paths = state.local_paths;
state.local_paths = state.local_paths && entry.local;
state.expansions += 1;
state.active.push(name.to_string());
parse_script_internal(&expanded, advance_package_manager, catalog, state, commands);
state.active.pop();
state.local_paths = outer_local_paths;
}
fn extract_args_for_binary(
tokens: &[&str],
mut idx: usize,
is_node_runner: bool,
) -> (Vec<String>, Vec<String>) {
let mut file_args = Vec::new();
let mut config_args = Vec::new();
while idx < tokens.len() {
let token = tokens[idx];
if is_node_runner
&& matches!(
token,
"-e" | "--eval" | "-p" | "--print" | "-r" | "--require"
)
{
idx += 2;
continue;
}
if is_node_runner && node_test::takes_non_module_value(token) {
idx += 2;
continue;
}
if let Some(config) = extract_config_arg(token, tokens.get(idx + 1).copied()) {
config_args.push(config);
if token.contains('=') || token.starts_with("--config=") || token.starts_with("-c=") {
idx += 1;
} else {
idx += 2;
}
continue;
}
if token.starts_with('-') {
idx += 1;
continue;
}
if looks_like_file_path(token) {
file_args.push(token.to_string());
}
idx += 1;
}
(file_args, config_args)
}
fn strip_surrounding_quotes(token: &str) -> &str {
if token.len() >= 2 {
let first = token.as_bytes()[0];
let last = token.as_bytes()[token.len() - 1];
if (first == b'\'' || first == b'"') && first == last {
return &token[1..token.len() - 1];
}
}
token
}
fn advance_past_package_manager_with_context(
tokens: &[&str],
idx: usize,
root: &Path,
bin_map: &FxHashMap<String, String>,
context: &ScriptCommandContext<'_>,
catalog: &ScriptCatalog,
) -> Option<PackageManagerTarget> {
if let Some(target) = bun_file_runner_target(tokens, idx, catalog) {
return Some(target);
}
if let Some(target) = script_invocation_target(tokens, idx, catalog) {
return Some(target);
}
if let Some((binary_idx, location)) = package_manager_exec_binary(tokens, idx) {
return Some(PackageManagerTarget::Binary(binary_idx, location));
}
if let Some(run) = package_manager_run(tokens, idx)
&& run.runs_binary_without_script()
&& !run.declares_script(catalog)
{
return resolve_known_dependency_binary(run.name, root, bin_map, context.declared_packages)
.map(|_| PackageManagerTarget::Binary(run.name_idx, run.location));
}
shell::advance_past_package_manager(tokens, idx)
.map(|binary_idx| PackageManagerTarget::Binary(binary_idx, RunLocation::Here))
}
fn bun_file_runner_target(
tokens: &[&str],
idx: usize,
catalog: &ScriptCatalog,
) -> Option<PackageManagerTarget> {
if tokens.get(idx) != Some(&"bun") {
return None;
}
let skip_runtime_flags = |mut i: usize| {
while tokens
.get(i)
.is_some_and(|token| shell::BUN_RUNTIME_FLAGS.contains(token))
{
i += 1;
}
i
};
let mut next = skip_runtime_flags(idx + 1);
if tokens.get(next) == Some(&"test") {
return Some(PackageManagerTarget::Binary(idx, RunLocation::Here));
}
if matches!(tokens.get(next), Some(&("run" | "run-script"))) {
next = skip_runtime_flags(next + 1);
}
let target = *tokens.get(next)?;
(looks_like_script_file(target) && !catalog.declares_script_at(target, &RunLocation::Here))
.then_some(PackageManagerTarget::Binary(idx, RunLocation::Here))
}
fn script_invocation_target(
tokens: &[&str],
idx: usize,
catalog: &ScriptCatalog,
) -> Option<PackageManagerTarget> {
let call = script_call_arguments(tokens, idx, catalog)?;
Some(PackageManagerTarget::Script {
name: call.name.to_string(),
forwarded: call.forwarded,
location: call.location,
})
}
struct ScriptCallArguments<'a> {
name: &'a str,
forwarded: Vec<usize>,
location: RunLocation,
}
fn script_call_arguments<'a>(
tokens: &'a [&'a str],
idx: usize,
catalog: &ScriptCatalog,
) -> Option<ScriptCallArguments<'a>> {
let invocation = declared_script_invocation(tokens, idx, catalog)?;
let first = invocation.name_idx + 1;
let forwarded = if matches!(
invocation.location,
RunLocation::Directory(_) | RunLocation::OtherPackages
) {
Vec::new()
} else if tokens.get(first) == Some(&"--") {
(first + 1..tokens.len()).collect()
} else if !invocation.npm_config_flags {
(first..tokens.len()).collect()
} else {
npm_forwarded_arguments(tokens, first)
};
Some(ScriptCallArguments {
name: invocation.name,
forwarded,
location: invocation.location,
})
}
fn npm_forwarded_arguments(tokens: &[&str], first: usize) -> Vec<usize> {
let mut forwarded = Vec::new();
let mut i = first;
while let Some(&token) = tokens.get(i) {
if token == "--" {
forwarded.extend(i + 1..tokens.len());
break;
}
if npm_flag_takes_value(token) {
i += 2;
continue;
}
if !token.starts_with('-') {
forwarded.push(i);
}
i += 1;
}
forwarded
}
#[derive(Debug, PartialEq, Eq)]
pub enum DeclaredScriptCall {
NoFileRefs,
UnknownBody,
Command(String),
InPackages(Vec<PackageScriptCommand>),
}
#[derive(Debug, PartialEq, Eq)]
pub struct PackageScriptCommand {
pub dir: String,
pub command: String,
package_dir: String,
}
#[must_use]
pub fn declared_script_call(
tokens: &[&str],
catalog: &ScriptCatalog,
) -> Option<DeclaredScriptCall> {
let idx = skip_command_wrappers(tokens)?;
let ScriptCallArguments {
name,
forwarded,
location,
} = script_call_arguments(tokens, idx, catalog)?;
if forwarded.is_empty() {
return Some(DeclaredScriptCall::NoFileRefs);
}
let extra_args: Vec<&str> = forwarded.iter().map(|&i| tokens[i]).collect();
let extra_args = extra_args.join(" ");
if let RunLocation::Packages(selectors) = &location {
let commands: Vec<PackageScriptCommand> = catalog
.selected_packages(selectors)
.into_iter()
.filter_map(|package| {
let body = package.scripts().get(name)?;
Some(PackageScriptCommand {
dir: catalog.relative_package_dir(package),
command: format!("{body} {extra_args}"),
package_dir: package.dir().to_string(),
})
})
.collect();
return Some(if commands.is_empty() {
DeclaredScriptCall::NoFileRefs
} else {
DeclaredScriptCall::InPackages(commands)
});
}
let Some(entry) = catalog.body(name) else {
return Some(DeclaredScriptCall::UnknownBody);
};
if !entry.local {
return Some(DeclaredScriptCall::NoFileRefs);
}
Some(DeclaredScriptCall::Command(format!(
"{} {extra_args}",
entry.body
)))
}
struct DeclaredScriptInvocation<'a> {
name: &'a str,
name_idx: usize,
npm_config_flags: bool,
location: RunLocation,
}
fn declared_script_invocation<'a>(
tokens: &'a [&'a str],
idx: usize,
catalog: &ScriptCatalog,
) -> Option<DeclaredScriptInvocation<'a>> {
let run = package_manager_run(tokens, idx)?;
if !run.declares_script(catalog) {
return None;
}
Some(DeclaredScriptInvocation {
name: run.name,
name_idx: run.name_idx,
npm_config_flags: run.explicit && run.manager == "npm",
location: catalog.script_call_location(run.location),
})
}
struct PackageManagerRun<'a> {
manager: &'a str,
name: &'a str,
name_idx: usize,
explicit: bool,
location: RunLocation,
skips_local_scripts: bool,
}
impl PackageManagerRun<'_> {
fn runs_binary_without_script(&self) -> bool {
match self.manager {
"yarn" => true,
"pnpm" => !self.explicit && !PNPM_BUILTIN_COMMANDS.contains(&self.name),
"bun" => self.explicit,
_ => false,
}
}
}
struct ManagerPrefix<'a> {
manager: &'a str,
subcmd_idx: usize,
location: RunLocation,
}
fn package_manager_prefix<'a>(tokens: &[&'a str], idx: usize) -> Option<ManagerPrefix<'a>> {
let mut location = RunLocation::Here;
if yarn_run::is_shell_run(tokens, idx) {
return Some(ManagerPrefix {
manager: "yarn",
subcmd_idx: idx,
location,
});
}
let manager = *tokens.get(idx)?;
let subcmd_idx = match manager {
"pnpm" => skip_pnpm_flags(tokens, idx + 1, &mut location),
"npm" => skip_npm_flags(tokens, idx + 1, &mut location),
"yarn" => skip_yarn_selection(tokens, idx + 1, &mut location),
"bun" | "vp" | vite_plus::VPR => idx + 1,
_ => return None,
};
Some(ManagerPrefix {
manager,
subcmd_idx,
location,
})
}
fn package_manager_run<'a>(tokens: &'a [&'a str], idx: usize) -> Option<PackageManagerRun<'a>> {
let ManagerPrefix {
manager,
subcmd_idx: next,
mut location,
} = package_manager_prefix(tokens, idx)?;
let subcmd = *tokens.get(next)?;
if manager == "yarn" && subcmd == "node" {
return None;
}
let (name_idx, explicit) = if manager == vite_plus::VPR {
(vite_plus::skip_run_flags(tokens, next, &mut location), true)
} else if matches!(subcmd, "run" | "run-script") {
let name_idx = match manager {
"npm" => {
npm_run_location(tokens, next + 1, &mut location);
npm_include_workspace_root(&tokens[idx + 1..], &mut location);
skip_npm_config_flags(tokens, next + 1)
}
"pnpm" => skip_pnpm_flags(tokens, next + 1, &mut location),
"yarn" => yarn_run::skip_run_flags(tokens, next + 1),
"vp" => vite_plus::skip_run_flags(tokens, next + 1, &mut location),
_ => next + 1,
};
(name_idx, true)
} else if matches!(manager, "yarn" | "pnpm" | "bun")
&& !subcmd.starts_with('-')
&& !PACKAGE_MANAGER_BUILTIN_COMMANDS.contains(&subcmd)
{
(next, false)
} else {
return None;
};
let name = *tokens.get(name_idx)?;
Some(PackageManagerRun {
skips_local_scripts: manager == "yarn"
&& yarn_run::skips_local_scripts(&tokens[next..name_idx]),
manager,
name,
name_idx,
explicit,
location,
})
}
fn skip_pnpm_flags(tokens: &[&str], mut idx: usize, location: &mut RunLocation) -> usize {
let mut include_root = false;
while let Some(&token) = tokens.get(idx) {
if PNPM_EXEC_BOOLEAN_FLAGS.contains(&token) {
match token {
"-r" | "--recursive" => location.select_all_packages(),
"-w" | "--workspace-root" => location.select_package(PackageSelector::root()),
"--include-workspace-root" => include_root = true,
_ => {}
}
idx += 1;
continue;
}
let (flag, value, width) = if PNPM_EXEC_VALUE_FLAGS.contains(&token) {
(token, tokens.get(idx + 1).copied(), 2)
} else if let Some((flag, value)) = token.split_once('=')
&& PNPM_EXEC_VALUE_FLAGS.contains(&flag)
{
(flag, Some(value), 1)
} else {
break;
};
if PNPM_FILTER_FLAGS.contains(&flag) {
location.select_package(value.map_or_else(
|| PackageSelector::pnpm_filter(""),
PackageSelector::pnpm_filter,
));
} else if matches!(flag, "-C" | "--dir")
&& let Some(dir) = value
{
location.select_directory(dir);
}
idx += width;
}
if include_root && matches!(location, RunLocation::Packages(_)) {
location.select_package(PackageSelector::include_root());
}
idx.min(tokens.len())
}
fn skip_npm_flags(tokens: &[&str], mut idx: usize, location: &mut RunLocation) -> usize {
while let Some(&token) = tokens.get(idx) {
if token == "--" || !token.starts_with('-') {
break;
}
idx += apply_npm_flag(tokens, idx, location);
}
idx.min(tokens.len())
}
fn npm_run_location(tokens: &[&str], from: usize, location: &mut RunLocation) {
let mut idx = from;
while let Some(&token) = tokens.get(idx) {
if token == "--" {
break;
}
idx += if token.starts_with('-') {
apply_npm_flag(tokens, idx, location)
} else {
1
};
}
}
fn npm_include_workspace_root(tokens: &[&str], location: &mut RunLocation) {
let include_root = tokens.iter().take_while(|token| **token != "--").fold(
false,
|include, token| match *token {
"-iwr" | "--include-workspace-root" | "--include-workspace-root=true" => true,
"--include-workspace-root=false" | "--no-include-workspace-root" => false,
_ => include,
},
);
if include_root && matches!(location, RunLocation::Packages(_)) {
location.select_package(PackageSelector::root());
}
}
fn apply_npm_flag(tokens: &[&str], idx: usize, location: &mut RunLocation) -> usize {
let token = tokens[idx];
let (flag, value, width) = if npm_flag_takes_value(token) {
(token, tokens.get(idx + 1).copied(), 2)
} else if let Some((flag, value)) = token.split_once('=') {
(flag, Some(value), 1)
} else {
(token, None, 1)
};
match flag {
"-w" | "--workspace" => {
location.select_package(PackageSelector::npm_workspace(value.unwrap_or_default()));
}
"-ws" => location.select_package(PackageSelector::npm_workspaces()),
"--workspaces" if value.is_none_or(|value| value == "true") => {
location.select_package(PackageSelector::npm_workspaces());
}
"-C" | "--prefix" => {
if let Some(dir) = value {
location.select_directory(dir);
}
}
_ => {}
}
width
}
fn skip_yarn_selection(tokens: &[&str], mut idx: usize, location: &mut RunLocation) -> usize {
while let Some(&token) = tokens.get(idx) {
if token == "--cwd" {
if let Some(dir) = tokens.get(idx + 1) {
location.select_directory(dir);
}
idx += 2;
} else if let Some(dir) = token.strip_prefix("--cwd=") {
location.select_directory(dir);
idx += 1;
} else if matches!(token, "-s" | "--silent") {
idx += 1;
} else {
break;
}
}
let idx = idx.min(tokens.len());
match tokens.get(idx..idx + 2) {
Some(["workspace", name]) => {
location.select_package(PackageSelector::yarn_workspace(name));
idx + 2
}
Some(["workspaces", "foreach"]) => skip_yarn_foreach_flags(tokens, idx + 2, location),
Some(["workspaces", "run"]) => {
location.select_all_packages();
idx + 1
}
_ => idx,
}
}
fn skip_yarn_foreach_flags(tokens: &[&str], mut idx: usize, location: &mut RunLocation) -> usize {
let mut all = false;
let mut resolved = true;
let mut selectors = Vec::new();
while let Some(&token) = tokens.get(idx) {
let (flag, value, width) = if YARN_FOREACH_BOOLEAN_FLAGS.contains(&token) {
(token, None, 1)
} else if YARN_FOREACH_VALUE_FLAGS.contains(&token) {
(token, tokens.get(idx + 1).copied(), 2)
} else if let Some((flag, value)) = token.split_once('=')
&& (YARN_FOREACH_VALUE_FLAGS.contains(&flag) || flag == "--since")
{
(flag, Some(value), 1)
} else {
break;
};
match (flag, value) {
("-A" | "--all", _) => all = true,
("--include", Some(glob)) => {
selectors.push(PackageSelector::yarn_foreach_glob(glob, false));
}
("--exclude", Some(glob)) => {
selectors.push(PackageSelector::yarn_foreach_glob(glob, true));
}
(
"-R" | "--recursive" | "-W" | "--worktree" | "--since" | "--from" | "--no-private",
_,
) => resolved = false,
_ => {}
}
idx += width;
}
if all && resolved {
location.select_all_packages();
location.select_package(PackageSelector::include_root());
for selector in selectors {
location.select_package(selector);
}
} else {
location.select_unresolved_packages();
}
idx.min(tokens.len())
}
fn skip_npm_config_flags(tokens: &[&str], idx: usize) -> usize {
skip_npm_flags(tokens, idx, &mut RunLocation::Here)
}
fn package_manager_exec_binary(tokens: &[&str], idx: usize) -> Option<(usize, RunLocation)> {
let ManagerPrefix {
manager,
subcmd_idx,
mut location,
} = package_manager_prefix(tokens, idx)?;
let subcmd = *tokens.get(subcmd_idx)?;
let mut next = match (manager, subcmd) {
("pnpm", "exec" | "dlx") => skip_pnpm_flags(tokens, subcmd_idx + 1, &mut location),
("npm", "exec" | "x") => {
let next = skip_npm_flags(tokens, subcmd_idx + 1, &mut location);
npm_include_workspace_root(&tokens[idx + 1..next], &mut location);
next
}
("yarn", "exec" | "dlx") => subcmd_idx + 1,
("yarn", "node") => return Some((subcmd_idx, location)),
_ => return None,
};
if tokens.get(next) == Some(&"--") {
next += 1;
}
(next < tokens.len()).then_some((next, location))
}
#[must_use]
pub fn invoked_command(
tokens: &[&str],
mut idx: usize,
catalog: &ScriptCatalog,
) -> Option<InvokedCommand> {
let mut location = RunLocation::Here;
loop {
idx = shell::skip_initial_wrappers(tokens, idx)?;
let run = package_manager_run(tokens, idx);
if let Some(run) = &run
&& (run.declares_script(catalog) || !run.runs_binary_without_script())
{
if run.location == RunLocation::Here {
return None;
}
return Some(InvokedCommand {
index: run.name_idx,
base_dirs: Some(Vec::new()),
});
}
let (binary_idx, binary_location) =
if let Some(exec) = package_manager_exec_binary(tokens, idx) {
exec
} else if let Some(run) = run
&& run.runs_binary_without_script()
{
(run.name_idx, run.location)
} else {
(
shell::advance_past_package_manager(tokens, idx)?,
RunLocation::Here,
)
};
location = location.nest(binary_location);
match command_wrapper_child_index(tokens, binary_idx) {
Some(child_idx) => idx = child_idx,
None => {
return Some(InvokedCommand {
index: binary_idx,
base_dirs: location.base_dirs(catalog),
});
}
}
}
}
fn wrapped_command_target(
tokens: &[&str],
mut idx: usize,
advance_package_manager: &impl Fn(&[&str], usize, &ScriptCatalog) -> Option<PackageManagerTarget>,
catalog: &ScriptCatalog,
) -> Option<PackageManagerTarget> {
let mut location = RunLocation::Here;
loop {
idx = shell::skip_initial_wrappers(tokens, idx)?;
match advance_package_manager(tokens, idx, catalog)? {
PackageManagerTarget::Binary(binary_idx, binary_location) => {
location = location.nest(binary_location);
match command_wrapper_child_index(tokens, binary_idx) {
Some(child_idx) => idx = child_idx,
None => return Some(PackageManagerTarget::Binary(binary_idx, location)),
}
}
script @ PackageManagerTarget::Script { .. } => return Some(script),
}
}
}
enum SegmentOutcome {
Command(ScriptCommand),
ScriptCall {
name: String,
extra_args: String,
location: RunLocation,
},
InlineCommand {
command: String,
location: RunLocation,
},
}
fn command_runtime_host(
binary: &str,
args: &[&str],
location: &RunLocation,
) -> Option<&'static str> {
(location == &RunLocation::Here && binary == "next" && args.first() == Some(&"start"))
.then_some("next")
}
fn parse_command_segment(
segment: &str,
advance_package_manager: &impl Fn(&[&str], usize, &ScriptCatalog) -> Option<PackageManagerTarget>,
catalog: &ScriptCatalog,
) -> Vec<SegmentOutcome> {
let mut outcomes = Vec::new();
let expanded = shell::expand_npm_bin(segment);
let segment = expanded.as_ref();
let words = shell::split_words(segment);
let tokens: Vec<&str> = words.iter().map(|word| word.value.as_ref()).collect();
let Some(mut idx) = shell::skip_initial_wrappers(&tokens, 0) else {
return outcomes;
};
let mut location = RunLocation::Here;
for _ in 0..command_wrappers::MAX_COMMAND_WRAPPER_DEPTH {
let Some(target) = advance_package_manager(&tokens, idx, catalog) else {
return outcomes;
};
idx = match target {
PackageManagerTarget::Binary(binary_idx, binary_location) => {
location = location.nest(binary_location);
binary_idx
}
PackageManagerTarget::Script {
name,
forwarded,
location: script_location,
} => {
outcomes.push(SegmentOutcome::ScriptCall {
name,
extra_args: forwarded_arguments(segment, &words, &forwarded),
location: location.nest(script_location),
});
return outcomes;
}
};
let Some(command_start) = command_wrapper_child_index(&tokens, idx) else {
break;
};
let wrapped =
wrapped_command_args(&tokens, command_start, advance_package_manager, catalog);
outcomes.push(SegmentOutcome::Command(ScriptCommand {
binary: tokens[idx].to_string(),
config_args: location.resolve_all(wrapped.config_args, catalog),
file_args: location.resolve_all(wrapped.file_args, catalog),
file_args_command: wrapped.command.to_string(),
flag_packages: Vec::new(),
production_runtime_host: None,
test_file_args: location.resolve_all(wrapped.test_file_args, catalog),
}));
let Some(next) = shell::skip_initial_wrappers(&tokens, command_start) else {
return outcomes;
};
idx = next;
}
let binary = tokens[idx].to_string();
if SCRIPT_MULTIPLEXERS.contains(&binary.as_str()) {
let inline_commands = if binary == CONCURRENTLY {
concurrently_inline_commands(&tokens[idx + 1..])
} else {
Vec::new()
};
outcomes.push(SegmentOutcome::Command(ScriptCommand {
file_args_command: binary.clone(),
binary,
config_args: Vec::new(),
file_args: Vec::new(),
flag_packages: Vec::new(),
production_runtime_host: None,
test_file_args: Vec::new(),
}));
outcomes.extend(
inline_commands
.into_iter()
.map(|command| SegmentOutcome::InlineCommand {
command: command.to_string(),
location: location.clone(),
}),
);
return outcomes;
}
let (args_command, (file_args, config_args)) = match vite_plus::subcommand_tool(&tokens, idx) {
Some((Some(tool), sub_idx)) => (tool.to_string(), binary_path_args(tool, &tokens, sub_idx)),
Some((None, _)) => (binary.clone(), (Vec::new(), Vec::new())),
None => (binary.clone(), binary_path_args(&binary, &tokens, idx)),
};
let flag_packages = flag_credits::flag_referenced_packages(&binary, &tokens[idx + 1..]);
let production_runtime_host = command_runtime_host(&binary, &tokens[idx + 1..], &location);
let test_file_args = node_test::test_file_args(&binary, &tokens[idx + 1..], &file_args);
outcomes.push(SegmentOutcome::Command(ScriptCommand {
test_file_args: location.resolve_all(test_file_args, catalog),
file_args_command: args_command,
binary,
config_args: location.resolve_all(config_args, catalog),
file_args: location.resolve_all(file_args, catalog),
flag_packages,
production_runtime_host,
}));
outcomes
}
fn binary_path_args(binary: &str, tokens: &[&str], idx: usize) -> (Vec<String>, Vec<String>) {
let args = &tokens[idx + 1..];
let (mut file_args, mut config_args) =
extract_args_for_binary(tokens, idx + 1, NODE_RUNNERS.contains(&binary));
file_args = argument_entries::entry_file_args(binary, args, file_args);
if is_task_runner(binary) {
file_args.clear();
config_args.clear();
}
let file_args = node_test::with_default_test_patterns(binary, args, file_args);
(file_args, config_args)
}
struct WrappedCommandArgs<'a> {
file_args: Vec<String>,
config_args: Vec<String>,
command: &'a str,
test_file_args: Vec<String>,
}
impl<'a> WrappedCommandArgs<'a> {
const fn without_args(command: &'a str) -> Self {
Self {
file_args: Vec::new(),
config_args: Vec::new(),
command,
test_file_args: Vec::new(),
}
}
}
fn wrapped_command_args<'a>(
tokens: &[&'a str],
command_start: usize,
advance_package_manager: &impl Fn(&[&str], usize, &ScriptCatalog) -> Option<PackageManagerTarget>,
catalog: &ScriptCatalog,
) -> WrappedCommandArgs<'a> {
let (child_idx, runs_here) =
match wrapped_command_target(tokens, command_start, advance_package_manager, catalog) {
Some(PackageManagerTarget::Binary(child_idx, location)) => {
(child_idx, location == RunLocation::Here)
}
Some(PackageManagerTarget::Script { .. }) => {
return WrappedCommandArgs::without_args(tokens[command_start]);
}
None => invoked_command(tokens, command_start, &ScriptCatalog::default())
.map_or((command_start, true), |invoked| {
(invoked.index, invoked.base_dirs.is_none())
}),
};
let child = tokens[child_idx];
if !runs_here {
return WrappedCommandArgs::without_args(child);
}
let (mut file_args, mut config_args) = extract_args_for_binary(tokens, command_start, false);
file_args = argument_entries::entry_file_args(child, &tokens[child_idx + 1..], file_args);
if is_task_runner(child) {
file_args.clear();
config_args.clear();
}
let file_args =
node_test::with_default_test_patterns(child, &tokens[child_idx + 1..], file_args);
WrappedCommandArgs {
test_file_args: node_test::test_file_args(child, &tokens[child_idx + 1..], &file_args),
file_args,
config_args,
command: child,
}
}
#[must_use]
pub fn is_task_runner(binary: &str) -> bool {
TASK_RUNNERS.contains(&tool_name(binary))
}
fn forwarded_arguments(
segment: &str,
words: &[shell::ShellWord<'_>],
forwarded: &[usize],
) -> String {
forwarded
.iter()
.filter_map(|&i| {
let start = words.get(i)?.start;
let end = words.get(i + 1).map_or(segment.len(), |next| next.start);
Some(segment[start..end].trim_end())
})
.collect::<Vec<_>>()
.join(" ")
}
fn extract_config_arg(token: &str, next: Option<&str>) -> Option<String> {
if let Some(value) = token.strip_prefix("--config=")
&& !value.is_empty()
{
return Some(value.to_string());
}
if let Some(value) = token.strip_prefix("-c=")
&& !value.is_empty()
{
return Some(value.to_string());
}
if matches!(token, "--config" | "-c")
&& let Some(next_token) = next
&& !next_token.starts_with('-')
{
return Some(next_token.to_string());
}
None
}
fn is_env_assignment(token: &str) -> bool {
token.find('=').is_some_and(|eq_pos| {
let name = &token[..eq_pos];
!name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
})
}
pub fn could_be_file_path(token: &str) -> bool {
if token.contains("${{") || (token.contains("}}") && !token.contains("{{")) {
return false;
}
if token.contains('\\') {
return false;
}
if let Some(open) = token.find('[') {
let after_open = &token[open + 1..];
let close_offset = after_open.find(']');
if !matches!(close_offset, Some(offset) if offset > 0) {
return false;
}
if close_offset.is_some_and(|offset| after_open[..offset].contains('/')) {
return false;
}
}
true
}
fn looks_like_file_path(token: &str) -> bool {
if !could_be_file_path(token) {
return false;
}
const EXTENSIONS: &[&str] = &[
".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", ".jsx", ".tsx", ".json", ".yaml", ".yml",
".toml", ".sh", ".bash",
];
if EXTENSIONS.iter().any(|ext| token.ends_with(ext)) {
return true;
}
if token.starts_with("./") || token.starts_with("../") {
return true;
}
token.contains('/')
&& !token.contains(char::is_whitespace)
&& !token.starts_with('@')
&& !token.contains("://")
}
#[must_use]
pub fn looks_like_script_file(token: &str) -> bool {
if !could_be_file_path(token) {
return false;
}
let extensions = [
".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", ".jsx", ".tsx", ".gts", ".gjs",
];
if !extensions.iter().any(|ext| token.ends_with(ext)) {
return false;
}
token.contains('/') || token.starts_with("./") || token.starts_with("../")
}
#[cfg(test)]
#[expect(
clippy::disallowed_types,
reason = "test assertions use std HashMap for readability"
)]
#[path = "scripts_tests.rs"]
mod tests;