use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use fallow_config::WorkspaceInfo;
use fallow_types::discover::DiscoveredFile;
use rustc_hash::{FxHashSet, FxHasher};
const PACKAGE_MANIFESTS: &[&str] = &["package.json", "deno.json", "deno.jsonc"];
const NEAREST_CONFIGS: &[&str] = &["package.json", "tsconfig.json"];
const INSTALL_STATE_FILES: &[&str] = &[
"package-lock.json",
"npm-shrinkwrap.json",
"pnpm-lock.yaml",
"yarn.lock",
"bun.lock",
"bun.lockb",
"deno.lock",
"node_modules/.package-lock.json",
"node_modules/.pnpm/lock.yaml",
"node_modules/.yarn-state.yml",
"node_modules/.yarn-integrity",
".pnp.cjs",
".pnp.data.json",
];
const BUN_LOCKFILES: &[&str] = &["bun.lock", "bun.lockb"];
const BUN_STORE_DIR: &str = ".bun";
const DENO_STORE_DIR: &str = ".deno";
pub fn resolution_inputs_hash(
root: &Path,
workspaces: &[WorkspaceInfo],
files: &[DiscoveredFile],
) -> u64 {
let mut hasher = FxHasher::default();
let mut workspace_keys: Vec<(&str, String)> = workspaces
.iter()
.map(|ws| (ws.name.as_str(), portable_key(root, &ws.root)))
.collect();
workspace_keys.sort_unstable();
workspace_keys.len().hash(&mut hasher);
for key in &workspace_keys {
key.hash(&mut hasher);
}
let mut inputs: Vec<(String, Vec<u8>)> = collect_input_files(root, workspaces, files)
.into_iter()
.filter_map(|path| {
let content = std::fs::read(&path).ok()?;
Some((portable_key(root, &path), content))
})
.collect();
inputs.sort_unstable();
inputs.len().hash(&mut hasher);
for (key, content) in &inputs {
key.hash(&mut hasher);
content.hash(&mut hasher);
}
let mut entry_targets = package_entry_target_states(root, workspaces);
entry_targets.sort_unstable();
entry_targets.len().hash(&mut hasher);
for target in &entry_targets {
target.hash(&mut hasher);
}
let mut install_states = node_modules_states(root, workspaces);
install_states.sort_unstable();
install_states.len().hash(&mut hasher);
for state in &install_states {
state.hash(&mut hasher);
}
let mut bun_listings = bun_install_listings(root, workspaces);
bun_listings.sort_unstable();
bun_listings.len().hash(&mut hasher);
for listing in &bun_listings {
listing.hash(&mut hasher);
}
let mut deno_listings = deno_store_listings(root, workspaces);
deno_listings.sort_unstable();
deno_listings.len().hash(&mut hasher);
for listing in &deno_listings {
listing.hash(&mut hasher);
}
hasher.finish()
}
fn node_modules_states(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, bool)> {
std::iter::once(root)
.chain(workspaces.iter().map(|ws| ws.root.as_path()))
.map(|dir| {
let path = dir.join("node_modules");
(portable_key(root, &path), path.is_dir())
})
.collect()
}
fn bun_install_listings(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, Vec<String>)> {
let dirs: FxHashSet<&Path> = std::iter::once(root)
.chain(workspaces.iter().map(|ws| ws.root.as_path()))
.chain(root.ancestors().skip(1))
.collect();
dirs.into_iter()
.filter(|dir| BUN_LOCKFILES.iter().any(|name| dir.join(name).is_file()))
.filter_map(|dir| {
let node_modules = dir.join("node_modules");
let names = node_modules_package_names(&node_modules)?;
Some((portable_key(root, &node_modules), names))
})
.collect()
}
fn deno_store_listings(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, Vec<String>)> {
let dirs: FxHashSet<&Path> = std::iter::once(root)
.chain(workspaces.iter().map(|ws| ws.root.as_path()))
.chain(root.ancestors().skip(1))
.collect();
dirs.into_iter()
.filter_map(|dir| {
let store = dir.join("node_modules").join(DENO_STORE_DIR);
let mut names: Vec<String> = dir_entry_names(&store)?
.into_iter()
.filter(|name| !name.starts_with('.'))
.collect();
names.sort_unstable();
Some((portable_key(root, &store), names))
})
.collect()
}
fn node_modules_package_names(node_modules: &Path) -> Option<Vec<String>> {
let mut names = Vec::new();
for name in dir_entry_names(node_modules)? {
let nested = name.starts_with('@') || name == BUN_STORE_DIR;
if nested {
for child in dir_entry_names(&node_modules.join(&name)).unwrap_or_default() {
names.push(format!("{name}/{child}"));
}
} else if !name.starts_with('.') {
names.push(name);
}
}
names.sort_unstable();
Some(names)
}
fn dir_entry_names(dir: &Path) -> Option<Vec<String>> {
let entries = std::fs::read_dir(dir).ok()?;
Some(
entries
.flatten()
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect(),
)
}
const PACKAGE_ENTRY_FIELDS: &[&str] = &["main", "module", "types", "typings"];
fn package_entry_target_states(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<(String, bool)> {
let mut states = Vec::new();
let package_dirs = std::iter::once(root).chain(workspaces.iter().map(|ws| ws.root.as_path()));
for dir in package_dirs {
let Ok(content) = std::fs::read(dir.join("package.json")) else {
continue;
};
let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&content) else {
continue;
};
let mut targets = Vec::new();
for field in PACKAGE_ENTRY_FIELDS {
if let Some(serde_json::Value::String(target)) = manifest.get(*field) {
targets.push(target.as_str());
}
}
if let Some(exports) = manifest.get("exports") {
collect_export_targets(exports, &mut targets);
}
for target in targets {
if target.contains('*') {
continue;
}
let relative = target.strip_prefix("./").unwrap_or(target);
if relative.is_empty() || relative.starts_with('/') {
continue;
}
let path = dir.join(relative);
states.push((portable_key(root, &path), path.exists()));
}
}
states
}
fn collect_export_targets<'a>(value: &'a serde_json::Value, targets: &mut Vec<&'a str>) {
match value {
serde_json::Value::String(target) => targets.push(target),
serde_json::Value::Array(items) => {
for item in items {
collect_export_targets(item, targets);
}
}
serde_json::Value::Object(map) => {
for item in map.values() {
collect_export_targets(item, targets);
}
}
_ => {}
}
}
fn collect_input_files(
root: &Path,
workspaces: &[WorkspaceInfo],
files: &[DiscoveredFile],
) -> FxHashSet<PathBuf> {
let mut inputs = FxHashSet::default();
let manifest_dirs = std::iter::once(root).chain(workspaces.iter().map(|ws| ws.root.as_path()));
for dir in manifest_dirs {
for name in PACKAGE_MANIFESTS.iter().chain(INSTALL_STATE_FILES) {
insert_if_file(&mut inputs, dir.join(name));
}
for config in root_level_tsconfigs(dir) {
inputs.insert(config);
}
}
for dir in root.ancestors().skip(1) {
for name in INSTALL_STATE_FILES {
insert_if_file(&mut inputs, dir.join(name));
}
}
for dir in source_dirs_and_ancestors(root, files) {
for name in NEAREST_CONFIGS {
insert_if_file(&mut inputs, dir.join(name));
}
}
let tsconfigs: Vec<PathBuf> = inputs
.iter()
.filter(|path| is_tsconfig_name(path))
.cloned()
.collect();
for config in tsconfigs {
inputs.extend(fallow_config::tsconfig_linked_files(&config));
}
inputs
}
fn insert_if_file(inputs: &mut FxHashSet<PathBuf>, path: PathBuf) {
if path.is_file() {
inputs.insert(path);
}
}
fn source_dirs_and_ancestors(root: &Path, files: &[DiscoveredFile]) -> FxHashSet<PathBuf> {
let mut dirs: FxHashSet<PathBuf> = root.ancestors().map(Path::to_path_buf).collect();
for file in files {
let mut dir = file.path.parent();
while let Some(current) = dir {
if !current.starts_with(root) || !dirs.insert(current.to_path_buf()) {
break;
}
dir = current.parent();
}
}
dirs
}
fn root_level_tsconfigs(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.flatten()
.map(|entry| entry.path())
.filter(|path| is_tsconfig_name(path) && path.is_file())
.collect()
}
fn is_tsconfig_name(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.starts_with("tsconfig"))
&& path.extension().is_some_and(|extension| {
extension.eq_ignore_ascii_case("json") || extension.eq_ignore_ascii_case("jsonc")
})
}
fn portable_key(root: &Path, path: &Path) -> String {
for (depth, base) in root.ancestors().enumerate() {
if let Ok(rest) = path.strip_prefix(base) {
let mut key = "../".repeat(depth);
key.push_str(&rest.to_string_lossy().replace('\\', "/"));
return key;
}
}
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn portable_key_spells_inside_and_outside_paths_relative_to_root() {
let root = Path::new("/repo/app");
assert_eq!(
portable_key(root, Path::new("/repo/app/src/a.json")),
"src/a.json"
);
assert_eq!(
portable_key(root, Path::new("/repo/tsconfig.json")),
"../tsconfig.json"
);
assert_eq!(portable_key(root, Path::new("/repo/app")), "");
}
fn write(path: &Path, content: &str) {
std::fs::create_dir_all(path.parent().expect("parent")).expect("directory");
std::fs::write(path, content).expect("file");
}
#[test]
fn install_markers_of_root_and_workspaces_key_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo");
let workspace_root = root.join("packages/ui");
let workspaces = vec![WorkspaceInfo {
root: workspace_root.clone(),
name: "ui".to_string(),
is_internal_dependency: false,
}];
let root_marker = root.join("node_modules/.package-lock.json");
let workspace_marker = workspace_root.join("node_modules/.yarn-state.yml");
write(&root_marker, "a@1\n");
write(&workspace_marker, "b@1\n");
let initial = resolution_inputs_hash(&root, &workspaces, &[]);
write(&root_marker, "a@1\n");
assert_eq!(
resolution_inputs_hash(&root, &workspaces, &[]),
initial,
"a rewrite with the same content must keep the hash"
);
write(&root_marker, "a@2\n");
let root_changed = resolution_inputs_hash(&root, &workspaces, &[]);
assert_ne!(root_changed, initial);
write(&workspace_marker, "b@2\n");
assert_ne!(
resolution_inputs_hash(&root, &workspaces, &[]),
root_changed
);
}
#[test]
fn bun_install_with_the_same_lockfile_keys_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo");
write(&root.join("bun.lock"), "{}\n");
write(&root.join("node_modules/a/package.json"), "{}");
write(&root.join("node_modules/.cache/tool/data"), "1");
let initial = resolution_inputs_hash(&root, &[], &[]);
write(&root.join("node_modules/.cache/tool/other"), "2");
assert_eq!(
resolution_inputs_hash(&root, &[], &[]),
initial,
"a tool cache in node_modules must keep the hash"
);
write(&root.join("node_modules/@scope/b/package.json"), "{}");
let scoped = resolution_inputs_hash(&root, &[], &[]);
assert_ne!(scoped, initial, "a scoped package install must change it");
write(&root.join("node_modules/.bun/c@1.0.0/node_modules/c/x"), "");
assert_ne!(
resolution_inputs_hash(&root, &[], &[]),
scoped,
"a package in the isolated store must change it"
);
}
#[test]
fn deno_lockfile_of_root_workspace_and_parent_keys_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo/app");
let workspace_root = root.join("packages/ui");
let workspaces = vec![WorkspaceInfo {
root: workspace_root.clone(),
name: "ui".to_string(),
is_internal_dependency: false,
}];
let lockfiles = [
root.join("deno.lock"),
workspace_root.join("deno.lock"),
temp.path().join("repo/deno.lock"),
];
for lockfile in &lockfiles {
write(lockfile, r#"{"version":"5"}"#);
}
let mut previous = resolution_inputs_hash(&root, &workspaces, &[]);
for lockfile in &lockfiles {
write(lockfile, r#"{"version":"5","npm":{"ms@2.1.3":{}}}"#);
let next = resolution_inputs_hash(&root, &workspaces, &[]);
assert_ne!(next, previous, "{} must key the hash", lockfile.display());
previous = next;
}
}
#[test]
fn deno_store_entries_key_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo");
let store = root.join("node_modules/.deno");
write(&store.join("ms@2.1.3/node_modules/ms/package.json"), "{}");
write(&store.join(".deno.lock"), "");
let initial = resolution_inputs_hash(&root, &[], &[]);
write(&store.join(".setup-cache.bin"), "state");
assert_eq!(
resolution_inputs_hash(&root, &[], &[]),
initial,
"a Deno state file in the store must keep the hash"
);
std::fs::rename(store.join("ms@2.1.3"), store.join("ms@2.1.2")).expect("rename");
let downgraded = resolution_inputs_hash(&root, &[], &[]);
assert_ne!(downgraded, initial, "a version change must change it");
write(
&store.join("chalk@5.6.2/node_modules/chalk/package.json"),
"{}",
);
assert_ne!(
resolution_inputs_hash(&root, &[], &[]),
downgraded,
"a new package in the store must change it"
);
}
#[test]
fn lockfile_above_the_root_keys_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo/packages/app");
std::fs::create_dir_all(&root).expect("root");
let lockfile = temp.path().join("repo/pnpm-lock.yaml");
write(&lockfile, "a: 1\n");
let initial = resolution_inputs_hash(&root, &[], &[]);
write(&lockfile, "a: 2\n");
assert_ne!(resolution_inputs_hash(&root, &[], &[]), initial);
}
#[test]
fn yarn_pnp_manifest_keys_the_hash() {
let temp = tempfile::tempdir().expect("temp");
let root = temp.path().join("repo/packages/app");
std::fs::create_dir_all(&root).expect("root");
let initial = resolution_inputs_hash(&root, &[], &[]);
let manifest = temp.path().join("repo/.pnp.cjs");
write(&manifest, "// pnp v1\n");
let with_pnp = resolution_inputs_hash(&root, &[], &[]);
assert_ne!(
with_pnp, initial,
"a new PnP manifest above the root must change it"
);
write(&root.join(".pnp.data.json"), "{}");
assert_ne!(
resolution_inputs_hash(&root, &[], &[]),
with_pnp,
"a PnP data file at the root must change it"
);
}
#[test]
fn tsconfig_names_match_root_level_variants_only() {
assert!(is_tsconfig_name(Path::new("tsconfig.json")));
assert!(is_tsconfig_name(Path::new("tsconfig.app.jsonc")));
assert!(!is_tsconfig_name(Path::new("package.json")));
assert!(!is_tsconfig_name(Path::new("tsconfig.ts")));
}
}