Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion crates/cli/tests/integration/dependencies.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
mod workspace_links;

use std::fs;
use std::path::Path;
use std::process::Output;
Expand Down Expand Up @@ -94,6 +96,49 @@ fn assert_language_hygiene(
);
}

#[test]
fn unrelated_manifest_preserves_the_external_dependency_declaration() {
let repo = init_git_repo(&[
(
"package.json",
r#"{
"workspaces": ["packages/*"],
"dependencies": {"lodash": "1", "unused": "1"},
"devDependencies": {"dev-only": "1"}
}"#,
),
(
"src/index.ts",
"import lodash from 'lodash'; import dev from 'dev-only'; export default [lodash, dev];",
),
]);
let root = repo.path();
let before = expect_json(root, None, &["check", "--format", "json"], 0);
let expected = &before["dependencies"];
assert_eq!(dep_names(expected, "unused_dependencies"), ["unused"]);
assert!(dep_names(expected, "unlisted_dependencies").is_empty());
assert_eq!(
dep_names(expected, "dev_in_production_dependencies"),
["dev-only"]
);

for name in ["lodash", "unused", "dev-only"] {
write_repo_file(
root,
&format!("fixtures/{name}/package.json"),
&json!({"name": name}).to_string(),
);
}

let after = expect_json(root, None, &["check", "--format", "json"], 0);
let dependencies = &after["dependencies"];
assert_eq!(
dep_names(dependencies, "unlisted_dependencies"),
Vec::<String>::new()
);
assert_eq!(dependencies, expected);
}

#[test]
fn typescript_monorepo_reports_dependency_hygiene_across_all_formats_ignore_and_package_filter() {
let root_manifest = json!({
Expand All @@ -110,7 +155,7 @@ fn typescript_monorepo_reports_dependency_hygiene_across_all_formats_ignore_and_
.to_string();
let api_manifest = json!({
"name": "@hygiene/api",
"dependencies": { "zod": "^3.0.0", "moment": "^2.30.0" },
"dependencies": { "@hygiene/shared": "1.0.0", "zod": "^3.0.0", "moment": "^2.30.0" },
"devDependencies": { "vitest": "^1.0.0", "faker": "^8.0.0", "eslint": "^9.0.0" },
})
.to_string();
Expand Down
41 changes: 41 additions & 0 deletions crates/cli/tests/integration/dependencies/workspace_links.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use serde_json::json;

use super::{assert_all_dep_metrics_empty, expect_json, init_git_repo};

#[test]
fn invalid_pnpm_manifest_preserves_package_json_workspace_links() {
let repo = init_git_repo(&[
(
"package.json",
r#"{"workspaces":["packages/*"],"dependencies":{"@app/lib":"1.0.0","lodash":"1"}}"#,
),
("pnpm-workspace.yaml", "packages: [broken\n"),
(
"packages/lib/package.json",
r#"{"name":"@app/lib","main":"index.ts"}"#,
),
("packages/lib/index.ts", "export default 1;"),
(
"src/index.ts",
"import lodash from 'lodash'; import local from '@app/lib'; export default [lodash, local];",
),
]);
let trace = expect_json(
repo.path(),
None,
&[
"trace",
"src/index.ts",
"packages/lib/index.ts",
"--format",
"json",
],
0,
);
assert_eq!(
trace["paths"],
json!([["src/index.ts", "packages/lib/index.ts"]])
);
let report = expect_json(repo.path(), None, &["check", "--format", "json"], 0);
assert_all_dep_metrics_empty(&report["dependencies"]);
}
3 changes: 3 additions & 0 deletions docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1735,6 +1735,9 @@ codeint compares declared manifest dependencies against imported external packag
- `dev_in_production_dependencies`: dependencies declared only as dev dependencies (including Go modules named only by `tool` directives without a plain `require` line) that are imported by runtime Production files.
Dev dependencies imported by Test files or Tooling files (files inside universal repository tooling folders `.github/`, `scripts/`, `docs/`, `examples/`, `tools/`, and `benches/` at the repository root or a package root, plus language-specific Tooling files marked `is-tooling-file` by their owning Language plugin) are treated as used and are not flagged.

For JavaScript and TypeScript, codeint excludes declarations for the same local package names that import resolution links.
A nested manifest outside the declared workspaces leaves a matching external dependency declaration eligible for all three Metrics.

List canonical external package names under `dependencies.ignore` to exclude them from all three dependency Metrics.
Set independent Budgets under `budgets.unused_dependencies`, `budgets.unlisted_dependencies`, and `budgets.dev_in_production_dependencies`, and adjust `codeint diff` Regression limits under `regression_limits` (all three default to `new_findings: "any_new_finding"`):

Expand Down
8 changes: 8 additions & 0 deletions docs/verification/features/check.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ docs/verification/verify.sh assert "$RUN_DIR" check

Assert also checks that `FIXTURE_REPO` has empty `git status --porcelain` and unchanged `HEAD`.

Run the Dependency hygiene regression through the CLI integration test:

```sh
cargo test --locked -p codeint --test integration -- --exact dependencies::unrelated_manifest_preserves_the_external_dependency_declaration
```

The test compares all three Dependency hygiene Metrics before and after adding fixture manifests whose names match external dependencies.

## Evidence and Cleanup

Evidence files are stored under `$EVIDENCE_DIR/check/` and `$EVIDENCE_DIR/verdict.json`.
Expand Down
6 changes: 3 additions & 3 deletions plugins/languages/ts/HOW-TO.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ fn find_empty_statements(program: &Program<'_>, _code: &str) -> Vec<Span> {
- `src/resolution/snapshot.rs` is the virtual file system that `oxc_resolver` reads: the repository paths, the manifest texts, and a `node_modules` link for each package of the repository.
It reads no real file, so a tsconfig never reaches outside the snapshot.
- `manifest_paths` is also how the plugin asks for the `package.json` files that `analyze_manifests` reads, so the host reads each manifest once.
- `src/resolution/packages.rs` links the `package.json` of each workspace package that the workspace declares, plus the root `package.json` when its `name` does not collide with a workspace member, so an import of a workspace package follows its `exports` field (falling back to source files or `Builtin` when build outputs are absent).
It finds the workspace packages with `src/workspaces.rs`, the same rule that splits the report by package.
- `src/package_links.rs` selects the `package.json` of each workspace package that the workspace declares, plus the root `package.json` when its `name` does not collide with a workspace member, so an import of a workspace package follows its `exports` field (falling back to source files or `Builtin` when build outputs are absent).
Both callers pass the workspace packages discovered by `src/workspaces.rs`, which also splits the report by package.
A non-root package outside the declared workspaces (including subfolder packages in a repository without workspaces) is not linked, because npm, Yarn, and Bun do not install it in `node_modules`.
Two packages with the same name are both left unlinked.
- The primary `exports` conditions include `bun`, `node`, and `default`.
Expand All @@ -81,7 +81,7 @@ fn find_empty_statements(program: &Program<'_>, _code: &str) -> Vec<Span> {
- `bun`, `bun:*`, `node:*`, `cloudflare:*`, and `deno:*` specifiers are always `Builtin` runtime modules, and `npm:` / `jsr:` specifiers strip their registry prefix and optional `@version` before normalizing the external package name.
- When `oxc_resolver` fails to resolve an import, `classify_error` falls back to `Resolution::Builtin` for framework virtual modules (`virtual:*`, `$app`, `$app/*`, `$env/*`, and `$service-worker`), so real `tsconfig.json` `paths` aliases resolve first while unbuilt framework virtual modules never trigger false `Unresolved` or `unlisted_dependencies` Findings.
- A bare specifier that fails to resolve is `External`, unless it names a linked package or matches a tsconfig `paths` key of the importer; then it is `Unresolved`.
- `src/dependencies.rs` parses `package.json` dependency sections (`dependencies` as `Runtime`, `devDependencies` as `Dev`, and `optionalDependencies` / `peerDependencies` as `Optional`), excluding `workspace:` entries and local package names.
- `src/dependencies.rs` parses `package.json` dependency sections (`dependencies` as `Runtime`, `devDependencies` as `Dev`, and `optionalDependencies` / `peerDependencies` as `Optional`), excluding `workspace:` entries and names linked by the same selection rule as import resolution.
Ambient `@types/*` declarations emit as `Optional` so they are never flagged as unused and satisfy explicit imports without hiding undeclared `@types/*` imports.
- Prove a change with `tests/integration/conformance.rs` through `manifest_paths` and `resolve_imports`, and with a cycle test in `crates/cli/tests/integration/check.rs`.

Expand Down
23 changes: 8 additions & 15 deletions plugins/languages/ts/src/dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,18 @@ const DEP_SECTIONS: [(&str, u8); 4] = [
pub(crate) fn extract_declared(manifests: &[Manifest]) -> Vec<DeclaredDep> {
let active: Vec<(&str, &str, Value)> =
manifests.iter().filter_map(parse_active_package).collect();
extract_declared_from_active(&active)
let members = crate::workspaces::workspace_packages(manifests).unwrap_or_default();
let local_names = crate::workspaces::linked_package_names(manifests, &active, &members);
extract_declared_from_active(&active, &local_names)
}

pub(crate) fn extract_declared_from_active(active: &[(&str, &str, Value)]) -> Vec<DeclaredDep> {
let local_names = collect_local_names(active);

pub(crate) fn extract_declared_from_active(
active: &[(&str, &str, Value)],
local_names: &HashSet<String>,
) -> Vec<DeclaredDep> {
let mut collected = BTreeSet::new();
for (root, _, doc) in active {
collect_package_deps(root, doc, &local_names, &mut collected);
collect_package_deps(root, doc, local_names, &mut collected);
}

collected
Expand All @@ -44,16 +47,6 @@ pub(crate) fn extract_declared_from_active(active: &[(&str, &str, Value)]) -> Ve
.collect()
}

fn collect_local_names(active: &[(&str, &str, Value)]) -> HashSet<String> {
active
.iter()
.filter_map(|(_, _, doc)| doc.get("name").and_then(Value::as_str))
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_owned)
.collect()
}

fn is_ambient_types_package(name: &str) -> bool {
name.starts_with("@types/")
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/languages/ts/src/entry_points.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use codeint_model::language::Manifest;
use codeint_model::scan::normalize_relative_path;
use serde_json::Value;

use crate::workspaces::PACKAGE_MANIFEST;
use crate::package_links::PACKAGE_MANIFEST;

const OUTPUT_TO_SOURCE_ALIASES: [(&str, &[&str]); 4] = [
(".js", &[".ts", ".tsx"]),
Expand Down
1 change: 1 addition & 0 deletions plugins/languages/ts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod entry_points;
mod frameworks;
mod functions;
mod nesting;
mod package_links;
mod package_scripts;
mod resolution;
mod rules;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
use std::collections::{HashMap, HashSet};

use codeint_model::language::Manifest;
use serde_json::Value;

use crate::workspaces::{PACKAGE_MANIFEST, workspace_packages};
pub(crate) const PACKAGE_MANIFEST: &str = "package.json";

pub(super) struct PackageLink {
pub(super) name: String,
pub(super) folder: String,
pub(crate) struct PackageLink {
pub(crate) name: String,
pub(crate) folder: String,
}

pub(super) fn package_links(manifests: &[Manifest]) -> Vec<PackageLink> {
let members: HashSet<String> = workspace_packages(manifests)
.unwrap_or_default()
.into_iter()
.collect();
pub(crate) fn links_for_members<'manifest, T>(
mut manifests: impl Iterator<Item = (&'manifest str, T)> + Clone,
members: &[String],
package_name: impl Fn(T) -> Option<String>,
) -> Vec<PackageLink> {
let members: HashSet<&str> = members.iter().map(String::as_str).collect();
let mut folders_by_name: HashMap<String, Vec<&str>> = HashMap::new();
for manifest in manifests {
let Some(folder) = manifest
.path
for (path, manifest) in manifests.clone() {
let Some(folder) = path
.strip_suffix(PACKAGE_MANIFEST)
.and_then(|folder| folder.strip_suffix('/'))
else {
Expand All @@ -27,7 +26,7 @@ pub(super) fn package_links(manifests: &[Manifest]) -> Vec<PackageLink> {
if !members.contains(folder) {
continue;
}
if let Some(name) = package_name(&manifest.text) {
if let Some(name) = package_name(manifest) {
folders_by_name.entry(name).or_default().push(folder);
}
}
Expand All @@ -41,8 +40,8 @@ pub(super) fn package_links(manifests: &[Manifest]) -> Vec<PackageLink> {
_ => None,
})
.collect();
if let Some(root) = manifests.iter().find(|m| m.path == PACKAGE_MANIFEST)
&& let Some(name) = package_name(&root.text)
if let Some((_, root)) = manifests.find(|(path, _)| *path == PACKAGE_MANIFEST)
&& let Some(name) = package_name(root)
&& !folders_by_name.contains_key(&name)
{
links.push(PackageLink {
Expand All @@ -54,8 +53,11 @@ pub(super) fn package_links(manifests: &[Manifest]) -> Vec<PackageLink> {
links
}

fn package_name(text: &str) -> Option<String> {
let manifest: Value = serde_json::from_str(text).ok()?;
pub(crate) fn name_from_text(text: &str) -> Option<String> {
name_from_doc(&serde_json::from_str(text).ok()?)
}

pub(crate) fn name_from_doc(manifest: &Value) -> Option<String> {
let name = manifest.get("name")?.as_str()?;
is_package_name(name).then(|| name.to_owned())
}
Expand Down
16 changes: 11 additions & 5 deletions plugins/languages/ts/src/resolution.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
mod packages;
mod snapshot;
#[cfg(test)]
mod tests;
Expand All @@ -10,9 +9,9 @@ use codeint_model::language::{ImportKind, ImportRequest, Manifest, Resolution};
use oxc_resolver::{ResolveError, ResolveOptions, ResolverGeneric, TsconfigDiscovery};

use crate::EXTENSIONS;
use crate::resolution::packages::PackageLink;
use crate::package_links::{self, PACKAGE_MANIFEST, links_for_members, name_from_text};
use crate::resolution::snapshot::Snapshot;
use crate::workspaces::{PACKAGE_MANIFEST, PNPM_WORKSPACE_MANIFEST};
use crate::workspaces::{PNPM_WORKSPACE_MANIFEST, workspace_packages};

const TYPESCRIPT_SOURCES_OF_JAVASCRIPT_OUTPUT: [(&str, &[&str]); 4] = [
(".js", &[".js", ".ts", ".tsx"]),
Expand Down Expand Up @@ -119,7 +118,14 @@ impl ProjectResolver {
manifest_package_roots
.sort_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right)));
manifest_package_roots.dedup();
let links: Vec<PackageLink> = packages::package_links(&manifests);
let members = workspace_packages(&manifests).unwrap_or_default();
let links = links_for_members(
manifests
.iter()
.map(|manifest| (manifest.path.as_str(), manifest.text.as_str())),
&members,
name_from_text,
);
let package_folders = links
.iter()
.map(|link| (link.name.clone(), link.folder.clone()))
Expand Down Expand Up @@ -477,7 +483,7 @@ fn package_name(specifier: &str) -> &str {
let candidate = &body[..end];
let resolved = if has_registry_prefix {
let stripped = strip_registry_version(candidate);
if packages::is_package_name(stripped) {
if package_links::is_package_name(stripped) {
stripped
} else {
""
Expand Down
2 changes: 1 addition & 1 deletion plugins/languages/ts/src/resolution/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::{Component, Path, PathBuf};
use codeint_model::language::Manifest;
use oxc_resolver::{FileMetadata, FileSystem, ResolveError};

use crate::resolution::packages::PackageLink;
use crate::package_links::PackageLink;

const PACKAGE_FOLDER: &str = "node_modules";

Expand Down
Loading
Loading