fallow_types/results.rs
1//! Analysis result types for all issue categories.
2
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::extract::{
8 MemberKind, SecurityControlKind, SecurityUrlShape, SkippedSecurityCalleeExpressionKind,
9 SkippedSecurityCalleeReason,
10};
11use crate::output::{
12 FixAction, FixActionType, IssueAction, SuppressLineAction, SuppressLineKind, SuppressLineScope,
13};
14use crate::output_dead_code::{
15 BoundaryCallViolationFinding, BoundaryCoverageViolationFinding, BoundaryViolationFinding,
16 CircularDependencyFinding, DeprecatedExportInUseFinding, DevDependencyInProductionFinding,
17 DuplicateExportAliasFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
18 DynamicSegmentNameConflictFinding, EmptyCatalogGroupFinding, InvalidClientExportFinding,
19 MisconfiguredDependencyOverrideFinding, MisplacedDirectiveFinding,
20 MixedClientServerBarrelFinding, PackageCycleFinding, PolicyViolationFinding,
21 PrivateTypeLeakFinding, PropDrillingChainFinding, ReExportCycleFinding, RouteCollisionFinding,
22 TestOnlyDependencyFinding, ThinWrapperFinding, TypeOnlyDependencyFinding,
23 UnlistedBinaryFinding, UnlistedDependencyFinding, UnprovidedInjectFinding,
24 UnrenderedComponentFinding, UnresolvedCatalogReferenceFinding, UnresolvedImportFinding,
25 UnusedCatalogEntryFinding, UnusedClassMemberFinding, UnusedComponentEmitFinding,
26 UnusedComponentInputFinding, UnusedComponentOutputFinding, UnusedComponentPropFinding,
27 UnusedDependencyFinding, UnusedDependencyOverrideFinding, UnusedDevDependencyFinding,
28 UnusedEnumMemberFinding, UnusedExportFinding, UnusedFileFinding, UnusedLoadDataKeyFinding,
29 UnusedNamespaceMemberFinding, UnusedOptionalDependencyFinding,
30 UnusedProtectedClassMemberFinding, UnusedServerActionFinding, UnusedStoreMemberFinding,
31 UnusedSvelteEventFinding, UnusedTypeFinding,
32};
33pub use crate::output_dead_code::{
34 UnproducedCatchTagFinding, UnusedEffectLayerFinding, UnusedTaggedErrorFinding,
35};
36#[path = "results_boundary.rs"]
37mod boundary;
38#[path = "results_trace_hop.rs"]
39mod trace_hop;
40pub use trace_hop::{TraceHop, TraceHopRole, TraceSecretRead};
41#[path = "results_caller_review.rs"]
42mod caller_review;
43#[path = "results_component_health.rs"]
44mod component_health;
45pub use boundary::{BoundaryViolation, BoundaryViolationReason};
46pub use caller_review::*;
47
48pub use component_health::ERROR_ONLY_RESULT_KEYS;
49
50use crate::serde_path;
51use crate::suppress::closest_known_kind_name;
52#[path = "results_ignore_findings.rs"]
53mod ignore_findings;
54use ignore_findings::classify_ignore_findings_fields;
55
56#[path = "results_active_suppression.rs"]
57mod active_suppression;
58pub use active_suppression::ActiveSuppression;
59#[path = "results_inventory_merge.rs"]
60mod inventory_merge;
61#[path = "results_merge_parts.rs"]
62mod merge_parts;
63use merge_parts::split_merge_parts;
64
65/// Summary of detected entry points, grouped by discovery source.
66///
67/// Used to surface entry-point detection status in human and JSON output,
68/// so library authors can verify that fallow found the right entry points.
69#[derive(Debug, Clone, Default)]
70#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
71pub struct EntryPointSummary {
72 /// Total number of entry points detected.
73 pub total: usize,
74 /// Breakdown by source category (e.g., "package.json" -> 3, "plugin" -> 12).
75 /// Sorted by key for deterministic output.
76 pub by_source: Vec<(String, usize)>,
77}
78
79/// Per-component render fan-in counts plus the precomputed concentration aggregates.
80///
81/// DESCRIPTIVE blast-radius signal (NOT a rule, finding, or threshold): the
82/// component-graph analogue of module-level fan-in. Module fan-in counts
83/// importing MODULES; render fan-in counts JSX render CALL SITES (a shared
84/// `<Button>` is rendered in far more places than it is imported).
85///
86/// `per_component` is the internal carrier (keyed for hotspot path annotation),
87/// `#[serde(skip)]` on [`AnalysisResults`] so it never appears under bare
88/// `fallow` / `audit`; the aggregates feed the descriptive `VitalSigns` block
89/// (`p95_render_fan_in` / `render_fan_in_high_pct` / `max_render_fan_in`).
90///
91/// UNDERCOUNT is the documented safe direction: a child rendered via a JSX
92/// spread, a dynamic / `createElement(var)` form, or a member-expression tag
93/// (`<Lib.Button/>`) is not resolved by the shared `ChildResolver` and so
94/// increments no component's fan-in. A true high-fan-in component can only be
95/// undersold, never falsely flagged. A rare name-collision over-credit is
96/// possible via the default-import sole-component fallback (inherited verbatim
97/// from the prop-drilling / thin-wrapper resolver); low-harm for a descriptive,
98/// non-gating metric.
99#[derive(Debug, Clone, Default)]
100pub struct RenderFanInMetric {
101 /// Per-component render-site + distinct-parent counts. Keyed by
102 /// `(component file path, component name)` so the hotspot surface can map a
103 /// file back to its top component's fan-in. Components rendered nowhere ARE
104 /// included as a real `0` so the percentile distribution is not skewed.
105 pub per_component: Vec<RenderFanInComponent>,
106 /// 95th-percentile DISTINCT-PARENTS render fan-in across components (the
107 /// per-component distribution analogue of the module-fan-in p95). `None` on
108 /// an empty population. Mirrors `compute_coupling_concentration`.
109 pub p95_distinct_parents: Option<u32>,
110 /// Percentage of components whose distinct-parents render fan-in exceeds the
111 /// `max(p95, 10)` threshold (the same floor coupling concentration uses).
112 /// `None` on an empty population.
113 pub high_pct: Option<f64>,
114 /// The single highest distinct-parent count across all components (the
115 /// headline blast-radius number: the most distinct render locations any one
116 /// component is rendered from, the honest edit-ripple count). `None` on an
117 /// empty population. `render_sites` (incl. repeats) is secondary per-component
118 /// context, never the headline.
119 pub max_distinct_parents: Option<u32>,
120}
121
122/// One component's render fan-in detail: how many JSX render SITES target it and
123/// how many DISTINCT parent components render it.
124#[derive(Debug, Clone)]
125pub struct RenderFanInComponent {
126 /// Absolute path of the file declaring the component.
127 pub file: PathBuf,
128 /// The component name.
129 pub component: String,
130 /// Total JSX render sites that resolve to this component across the project
131 /// (each capitalized / member JSX tag is one site). SECONDARY context ("incl.
132 /// repeats"): a single parent rendering one child five times is five sites but
133 /// one distinct parent, so render_sites overcounts blast radius.
134 pub render_sites: u32,
135 /// Distinct `(parent_file, parent_component)` keys that render this
136 /// component. The HEADLINE blast-radius axis: the honest count of distinct
137 /// render LOCATIONS, the percentiled distribution analogue of "distinct importers".
138 pub distinct_parents: u32,
139}
140
141/// Per-kind hook counts for a React component, summarized from `hook_uses`.
142/// DESCRIPTIVE editor context (the LSP code-lens hook breakdown), never a
143/// finding, severity, or `total_issues` input. `custom` collects every
144/// `use*`-named call that is not one of the four built-ins.
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146pub struct ReactHookSummary {
147 /// `useState(...)` call count.
148 pub state: u16,
149 /// `useEffect(...)` call count.
150 pub effect: u16,
151 /// `useMemo(...)` call count.
152 pub memo: u16,
153 /// `useCallback(...)` call count.
154 pub callback: u16,
155 /// Count of any other `use*`-named call (a custom hook).
156 pub custom: u16,
157}
158
159/// A prop-drilling trace for a prop at the ROOT of a forwarding chain.
160/// DESCRIPTIVE ambient editor context (the LSP per-prop hover): the prop is
161/// forwarded unchanged through `depth` components before a component
162/// substantively consumes it. Reuses the `prop-drilling` chain machinery's
163/// abstain ladder (spread / `cloneElement` / dynamic / provider-in-subtree drop
164/// the whole chain), so the trace is honest. NOT a finding (the opt-in
165/// `prop-drilling` rule owns the finding); this rides the `#[serde(skip)]`
166/// `ReactComponentIntel` carrier.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct ReactPropDrill {
169 /// The chain depth = number of components the prop is forwarded THROUGH
170 /// (source + intermediates + consumer), matching `PropDrillingChain.depth`.
171 pub depth: u32,
172 /// The ordered component names from source to consumer (`hops[0]` owns the
173 /// prop, the last consumes it).
174 pub hops: Vec<String>,
175}
176
177/// Per-prop usage intelligence for one React component prop. DESCRIPTIVE editor
178/// context (the LSP per-prop hover): whether the prop is read in the component
179/// body and how many render sites pass it. NOT a finding (the
180/// `unused-component-prop` React arm owns the deadness rule); this is ambient
181/// signal. `anchor_line` / `anchor_col` follow the same convention the React
182/// `unused-component-prop` findings use (1-based line, byte-derived col from
183/// `byte_offset_to_line_col`).
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct ReactPropIntel {
186 /// The declared prop name.
187 pub name: String,
188 /// 1-based line of the prop declaration (anchors the hover).
189 pub anchor_line: u32,
190 /// Column of the prop declaration (byte-derived, matching the React
191 /// `unused-component-prop` finding convention).
192 pub anchor_col: u32,
193 /// Whether the prop is referenced in the component body (`used_in_script`
194 /// for the React arm: a resolved reference to the destructured local).
195 pub used_in_body: bool,
196 /// Count of render sites (test/spec/story/fixture files excluded) whose
197 /// passed-attribute set contains this prop name.
198 pub passed_from_sites: u32,
199 /// A prop-drilling trace, present only when this prop is the ROOT of a
200 /// forwarding chain that reaches a consumer through `>= N` pass-through
201 /// components. `None` for an ordinary prop. Test/spec/story/fixture source
202 /// components never carry a drill trace.
203 pub drill: Option<ReactPropDrill>,
204}
205
206/// Per-component render + prop + hook intelligence for one React component.
207/// DESCRIPTIVE ambient editor context surfaced by the LSP (a component summary
208/// code lens plus per-prop hovers), NOT a finding, IssueKind, severity, or
209/// `total_issues` input. Carried in-process on the `#[serde(skip)]`
210/// `AnalysisResults::react_component_intel` field (like
211/// [`RenderFanInMetric`]); never serialized, so bare `fallow` / `audit` and the
212/// JSON / schema surface are untouched.
213///
214/// Counts are HONEST: test/spec/story/fixture render sites are excluded from
215/// `render_sites`, `distinct_parents`, and per-prop `passed_from_sites`, and
216/// `distinct_parents` (not the repeat-inflated `render_sites`) is the headline,
217/// mirroring the render-fan-in metric's discipline.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct ReactComponentIntel {
220 /// Absolute path of the file declaring the component.
221 pub path: PathBuf,
222 /// The component name.
223 pub component_name: String,
224 /// 1-based line of the component definition (anchors the code lens).
225 pub anchor_line: u32,
226 /// Column of the component definition (byte-derived).
227 pub anchor_col: u32,
228 /// Total JSX render SITES that resolve to this component (each capitalized /
229 /// member JSX tag is one site). SECONDARY context: a single parent rendering
230 /// the child five times is five sites but one distinct parent.
231 pub render_sites: u32,
232 /// Distinct `(parent_file, parent_component)` keys rendering this component.
233 /// The HEADLINE blast-radius count (never the repeat-inflated site count).
234 pub distinct_parents: u32,
235 /// Number of declared props on this component.
236 pub prop_count: u16,
237 /// Per-kind hook counts.
238 pub hooks: ReactHookSummary,
239 /// Per-prop usage intelligence (one entry per declared prop).
240 pub props: Vec<ReactPropIntel>,
241}
242
243/// Complete analysis results.
244///
245/// # Examples
246///
247/// ```
248/// use fallow_types::output_dead_code::UnusedFileFinding;
249/// use fallow_types::results::{AnalysisResults, UnusedFile};
250/// use std::path::PathBuf;
251///
252/// let mut results = AnalysisResults::default();
253/// assert_eq!(results.total_issues(), 0);
254/// assert!(!results.has_issues());
255///
256/// results
257/// .unused_files
258/// .push(UnusedFileFinding::with_actions(UnusedFile {
259/// path: PathBuf::from("src/dead.ts"),
260/// }));
261/// assert_eq!(results.total_issues(), 1);
262/// assert!(results.has_issues());
263/// ```
264#[derive(Debug, Default, Clone, Serialize, Deserialize)]
265#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
266pub struct AnalysisResults {
267 /// Optional architecture inventory, excluded from issue totals and gates.
268 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub shared_state: Option<crate::shared_state::SharedStateInventory>,
270 /// Files not reachable from any entry point. Wrapped in
271 /// [`UnusedFileFinding`] so each entry carries a typed `actions` array
272 /// natively, replacing the pre-2.76 post-pass injection.
273 pub unused_files: Vec<UnusedFileFinding>,
274 /// Exports never imported by other modules. Wrapped in
275 /// [`UnusedExportFinding`] so each entry carries a typed `actions`
276 /// array natively.
277 pub unused_exports: Vec<UnusedExportFinding>,
278 /// Type exports never imported by other modules. Wrapped in
279 /// [`UnusedTypeFinding`]: the inner [`UnusedExport`] struct is shared
280 /// with `unused_exports` but the wrapper emits a type-targeted fix
281 /// description.
282 pub unused_types: Vec<UnusedTypeFinding>,
283 /// Exported symbols whose public signature references same-file private
284 /// types. Wrapped in [`PrivateTypeLeakFinding`] so each entry carries a
285 /// typed `actions` array natively.
286 pub private_type_leaks: Vec<PrivateTypeLeakFinding>,
287 /// Exports marked `@deprecated` that still have at least one consumer in
288 /// a reachable file. Wrapped in [`DeprecatedExportInUseFinding`]. Opt-in: the
289 /// `deprecated-exports-in-use` rule defaults to `off`.
290 #[serde(default)]
291 pub deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
292 /// Dependencies listed in package.json but never imported. Wrapped in
293 /// [`UnusedDependencyFinding`] so each entry carries a typed `actions`
294 /// array natively. The fix action swaps from `remove-dependency` to
295 /// `move-dependency` when `used_in_workspaces` is non-empty.
296 pub unused_dependencies: Vec<UnusedDependencyFinding>,
297 /// Dev dependencies listed in package.json but never imported. Wrapped
298 /// in [`UnusedDevDependencyFinding`]: same bare struct as
299 /// `unused_dependencies` with a `devDependencies`-targeted fix
300 /// description.
301 pub unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
302 /// Optional dependencies listed in package.json but never imported.
303 /// Wrapped in [`UnusedOptionalDependencyFinding`] with an
304 /// `optionalDependencies`-targeted fix description.
305 pub unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
306 /// Enum members never accessed. Wrapped in
307 /// [`UnusedEnumMemberFinding`] so each entry carries a typed `actions`
308 /// array natively.
309 pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
310 /// Class members never accessed. Wrapped in
311 /// [`UnusedClassMemberFinding`]: same inner [`UnusedMember`] struct as
312 /// `unused_enum_members`, with a class-targeted fix description and the
313 /// `auto_fixable: false` default to reflect dependency-injection
314 /// patterns.
315 pub unused_class_members: Vec<UnusedClassMemberFinding>,
316 /// Exported members of an exported TypeScript namespace that no code
317 /// reads. Wrapped in [`UnusedNamespaceMemberFinding`]: same inner
318 /// [`UnusedMember`] struct as `unused_enum_members`. `member_name` is the
319 /// dotted path from the exported namespace (`Inner.x`).
320 #[serde(default, skip_serializing_if = "Vec::is_empty")]
321 pub unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
322 /// `protected` class members that neither the class nor a subclass
323 /// reads. Wrapped in [`UnusedProtectedClassMemberFinding`]: same inner
324 /// [`UnusedMember`] struct as `unused_class_members`. The rule is `off`
325 /// by default, so this array is empty unless a config turns it on.
326 #[serde(default, skip_serializing_if = "Vec::is_empty")]
327 pub unused_protected_class_members: Vec<UnusedProtectedClassMemberFinding>,
328 /// Store members (Pinia `state` / `getters` / `actions` key, or a
329 /// setup-store returned key) declared but never accessed by any consumer
330 /// project-wide. Wrapped in [`UnusedStoreMemberFinding`]: same inner
331 /// [`UnusedMember`] struct as `unused_class_members`, with a
332 /// store-targeted fix description. Cross-graph: the store binding is
333 /// imported (the module is reachable) yet a specific member is dead.
334 #[serde(default, skip_serializing_if = "Vec::is_empty")]
335 pub unused_store_members: Vec<UnusedStoreMemberFinding>,
336 /// Import specifiers that could not be resolved. Wrapped in
337 /// [`UnresolvedImportFinding`] so each entry carries a typed `actions`
338 /// array natively.
339 pub unresolved_imports: Vec<UnresolvedImportFinding>,
340 /// Dependencies used in code but not listed in package.json. Wrapped in
341 /// [`UnlistedDependencyFinding`].
342 pub unlisted_dependencies: Vec<UnlistedDependencyFinding>,
343 /// Binaries that package.json scripts or process calls run, but that no
344 /// installed or listed package provides. Wrapped in
345 /// [`UnlistedBinaryFinding`].
346 #[serde(default)]
347 pub unlisted_binaries: Vec<UnlistedBinaryFinding>,
348 /// Exports with the same name across multiple modules. Wrapped in
349 /// [`DuplicateExportFinding`] so each entry carries a typed `actions`
350 /// array natively, with the position-0 `add-to-config` `ignoreExports`
351 /// snippet wired in at wrapper construction.
352 pub duplicate_exports: Vec<DuplicateExportFinding>,
353 /// One module that exports one binding under two or more names. Wrapped
354 /// in [`DuplicateExportAliasFinding`]. Default severity is `warn`.
355 #[serde(default, skip_serializing_if = "Vec::is_empty")]
356 pub duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
357 /// Production dependencies only used via type-only imports (could be
358 /// devDependencies). Only populated in production mode. Wrapped in
359 /// [`TypeOnlyDependencyFinding`].
360 pub type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
361 /// Production dependencies only imported by test files (could be
362 /// devDependencies). Wrapped in [`TestOnlyDependencyFinding`].
363 #[serde(default)]
364 pub test_only_dependencies: Vec<TestOnlyDependencyFinding>,
365 /// devDependencies imported by production (non-test, non-config) source code
366 /// via a runtime/value import; they should be promoted to dependencies.
367 /// The promote-side mirror of [`TestOnlyDependencyFinding`]. Wrapped in
368 /// [`DevDependencyInProductionFinding`].
369 #[serde(default)]
370 pub dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
371 /// Circular dependency chains detected in the module graph. Wrapped in
372 /// [`CircularDependencyFinding`] so each entry carries a typed `actions`
373 /// array natively.
374 pub circular_dependencies: Vec<CircularDependencyFinding>,
375 /// Cycles or self-loops in the re-export edge subgraph (barrel files
376 /// re-exporting from each other in a loop). Wrapped in
377 /// [`ReExportCycleFinding`] so each entry carries a typed `actions`
378 /// array natively (a `refactor-re-export-cycle` informational primary
379 /// plus a `suppress-file` secondary; cycles are file-scoped so a single
380 /// suppression breaks the cycle).
381 #[serde(default)]
382 pub re_export_cycles: Vec<ReExportCycleFinding>,
383 /// Dependency cycles between workspace packages, built from resolved
384 /// cross-package imports. Wrapped in [`PackageCycleFinding`] so each
385 /// entry carries a typed `actions` array natively.
386 #[serde(default)]
387 pub package_cycles: Vec<PackageCycleFinding>,
388 /// Imports that cross architecture boundary rules. Wrapped in
389 /// [`BoundaryViolationFinding`] so each entry carries a typed `actions`
390 /// array natively.
391 #[serde(default)]
392 pub boundary_violations: Vec<BoundaryViolationFinding>,
393 /// Files that matched no architecture boundary zone while
394 /// `boundaries.coverage.requireAllFiles` was enabled.
395 #[serde(default)]
396 pub boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
397 /// Calls from zoned files to callees forbidden for that zone via
398 /// `boundaries.calls.forbidden`. Wrapped in
399 /// [`BoundaryCallViolationFinding`] so each entry carries a typed
400 /// `actions` array natively.
401 #[serde(default)]
402 pub boundary_call_violations: Vec<BoundaryCallViolationFinding>,
403 /// Banned calls, imports, and catalogue-derived effects matched by
404 /// declarative rule packs
405 /// (`rulePacks` config). Wrapped in [`PolicyViolationFinding`] so each
406 /// entry carries a typed `actions` array natively. Each finding carries
407 /// its effective per-rule severity.
408 #[serde(default)]
409 pub policy_violations: Vec<PolicyViolationFinding>,
410 /// Suppression comments or JSDoc tags that no longer match any issue.
411 #[serde(default)]
412 pub stale_suppressions: Vec<StaleSuppression>,
413 /// Entries in package manager catalog sections not referenced by any
414 /// workspace package via the catalog: protocol. Supports
415 /// `pnpm-workspace.yaml` catalogs and Bun root `package.json` catalogs.
416 /// Wrapped in [`UnusedCatalogEntryFinding`] so each entry carries a typed
417 /// `actions` array natively, with per-instance `auto_fixable` derived
418 /// from `hardcoded_consumers` and the catalog source file.
419 #[serde(default)]
420 pub unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
421 /// Named groups under package manager catalogs sections that declare no
422 /// package entries. The top-level catalog: map is not reported. Wrapped in
423 /// [`EmptyCatalogGroupFinding`].
424 #[serde(default)]
425 pub empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
426 /// Workspace package.json references to catalogs (`catalog:` or
427 /// `catalog:<name>`) that do not declare the consumed package. The package
428 /// manager install will error until the named catalog grows to include the
429 /// package or the reference is switched / removed. Wrapped in
430 /// [`UnresolvedCatalogReferenceFinding`] with the discriminated
431 /// `add-catalog-entry` / `update-catalog-reference` primary at position 0.
432 #[serde(default)]
433 pub unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
434 /// Entries in pnpm-workspace.yaml's overrides section, package.json's
435 /// pnpm.overrides block, npm or Bun's top-level overrides object, or Bun's
436 /// top-level resolutions object,
437 /// whose target package is not declared by any workspace package and is
438 /// not present in pnpm-lock.yaml, package-lock.json, npm-shrinkwrap.json,
439 /// or bun.lock. Default severity is warn because projects without a
440 /// readable lockfile fall back to manifest-only checks; the hint field
441 /// flags those conservative cases. When the only lockfile is bun's binary
442 /// bun.lockb, resolution cannot be read and the check emits nothing.
443 /// Wrapped in [`UnusedDependencyOverrideFinding`].
444 #[serde(default)]
445 pub unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
446 /// Package-manager override or resolution entries whose key or value does
447 /// not parse in the declaration source's grammar (empty key, empty value,
448 /// malformed selector, unbalanced parent matcher). The package manager may
449 /// reject or ignore these at install time. Default severity is error. Wrapped in
450 /// [`MisconfiguredDependencyOverrideFinding`].
451 #[serde(default)]
452 pub misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
453 /// `"use client"` files that export a Next.js server-only / route-segment
454 /// config name (e.g. `metadata`, `revalidate`, `GET`). Next.js rejects this
455 /// at build time. Wrapped in [`InvalidClientExportFinding`] so each entry
456 /// carries a typed `actions` array natively. Default severity is `warn`.
457 #[serde(default)]
458 pub invalid_client_exports: Vec<InvalidClientExportFinding>,
459 /// Barrel files that re-export both a `"use client"` origin module and a
460 /// server-only origin module (the Next.js App Router footgun). Wrapped in
461 /// [`MixedClientServerBarrelFinding`] so each entry carries a typed
462 /// `actions` array natively. Default severity is `warn`.
463 #[serde(default)]
464 pub mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
465 /// `"use client"` / `"use server"` directives written as expression
466 /// statements after a non-directive statement, so the RSC bundler parses
467 /// them as ordinary strings and silently ignores them. Wrapped in
468 /// [`MisplacedDirectiveFinding`] so each entry carries a typed `actions`
469 /// array natively. Default severity is `warn`.
470 #[serde(default)]
471 pub misplaced_directives: Vec<MisplacedDirectiveFinding>,
472 /// Vue `inject(KEY)` / Svelte `getContext(KEY)` calls whose symbol KEY is
473 /// provided nowhere in the project (the injected-never-provided dead-half).
474 /// Wrapped in [`UnprovidedInjectFinding`] so each entry carries a typed
475 /// `actions` array natively. Default severity is `warn`.
476 #[serde(default, skip_serializing_if = "Vec::is_empty")]
477 pub unprovided_injects: Vec<UnprovidedInjectFinding>,
478 /// Vue/Svelte single-file components that are reachable but rendered nowhere
479 /// (the imported-but-never-rendered dead-half). Wrapped in
480 /// [`UnrenderedComponentFinding`] so each entry carries a typed `actions`
481 /// array natively. Default severity is `warn`.
482 #[serde(default, skip_serializing_if = "Vec::is_empty")]
483 pub unrendered_components: Vec<UnrenderedComponentFinding>,
484 /// Next.js App Router route files that resolve to the same URL within one
485 /// app-root (a guaranteed `next build` failure). Wrapped in
486 /// [`RouteCollisionFinding`] so each entry carries a typed `actions` array
487 /// natively. One finding per colliding file. Default severity is `warn`.
488 #[serde(default)]
489 pub route_collisions: Vec<RouteCollisionFinding>,
490 /// Sibling Next.js dynamic route segments at one tree position using
491 /// different param spellings (a dev / runtime error; `next build` does NOT
492 /// catch it). Wrapped in [`DynamicSegmentNameConflictFinding`] so each entry
493 /// carries a typed `actions` array natively. Default severity is `warn`.
494 #[serde(default)]
495 pub dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
496 /// Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, and React props
497 /// referenced nowhere in their own component. Wrapped in
498 /// [`UnusedComponentPropFinding`] so each entry carries a typed `actions`
499 /// array natively. Default severity is `warn`.
500 #[serde(default, skip_serializing_if = "Vec::is_empty")]
501 pub unused_component_props: Vec<UnusedComponentPropFinding>,
502 /// Used optional component inputs absent from inspected reachable callers. Off by default.
503 #[serde(default, skip_serializing_if = "Vec::is_empty")]
504 pub absent_component_props: Vec<AbsentComponentPropFinding>,
505 /// Parameters that each visible call passes in one way. Off by default.
506 #[serde(default, skip_serializing_if = "Vec::is_empty")]
507 pub constant_parameters: Vec<ConstantParameterFinding>,
508 /// Vue `<script setup>` `defineEmits` events emitted nowhere in their own SFC
509 /// (no `emit('<name>')` call). Wrapped in [`UnusedComponentEmitFinding`] so
510 /// each entry carries a typed `actions` array natively. Default severity is
511 /// `warn`.
512 #[serde(default, skip_serializing_if = "Vec::is_empty")]
513 pub unused_component_emits: Vec<UnusedComponentEmitFinding>,
514 /// Angular `@Input()` / signal `input()` / `model()` inputs read nowhere in
515 /// their own component (neither the template nor the class body). Wrapped in
516 /// [`UnusedComponentInputFinding`] so each entry carries a typed `actions`
517 /// array natively. Default severity is `warn`.
518 #[serde(default, skip_serializing_if = "Vec::is_empty")]
519 pub unused_component_inputs: Vec<UnusedComponentInputFinding>,
520 /// Angular `@Output()` / signal `output()` outputs emitted nowhere in their
521 /// own component (no `this.<output>.emit(...)`). Wrapped in
522 /// [`UnusedComponentOutputFinding`] so each entry carries a typed `actions`
523 /// array natively. Default severity is `warn`.
524 #[serde(default, skip_serializing_if = "Vec::is_empty")]
525 pub unused_component_outputs: Vec<UnusedComponentOutputFinding>,
526 /// Svelte components dispatching a custom event via `createEventDispatcher()`
527 /// whose event name is listened to nowhere project-wide (cross-file
528 /// dead-output direction). Wrapped in [`UnusedSvelteEventFinding`] so each
529 /// entry carries a typed `actions` array natively. Default severity is
530 /// `warn`.
531 #[serde(default, skip_serializing_if = "Vec::is_empty")]
532 pub unused_svelte_events: Vec<UnusedSvelteEventFinding>,
533 /// Effect layers composed only into other layers that nothing uses.
534 /// Gated on the project declaring `effect`. Default severity is `warn`.
535 #[serde(default, skip_serializing_if = "Vec::is_empty")]
536 pub unused_effect_layers: Vec<UnusedEffectLayerFinding>,
537 /// Effect tagged error classes that only type positions or `catchTag`
538 /// handlers reference. Gated on the project declaring `effect`. Default
539 /// severity is `warn`.
540 #[serde(default, skip_serializing_if = "Vec::is_empty")]
541 pub unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
542 /// `catchTag` / `catchTags` handlers for a project tag that no code
543 /// produces and that no `unused_tagged_errors` entry covers. Gated on the
544 /// project declaring `effect`. Default severity is `warn`.
545 #[serde(default, skip_serializing_if = "Vec::is_empty")]
546 pub unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
547 /// Next.js Server Actions (exports of `"use server"` files) that no code in
548 /// the project references. Reclassified out of `unused_exports` for
549 /// `"use server"` files. Wrapped in [`UnusedServerActionFinding`] so each
550 /// entry carries a typed `actions` array natively. Default severity is
551 /// `warn`.
552 #[serde(default, skip_serializing_if = "Vec::is_empty")]
553 pub unused_server_actions: Vec<UnusedServerActionFinding>,
554 /// SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object keys
555 /// read by no consumer. Wrapped in [`UnusedLoadDataKeyFinding`] so each entry
556 /// carries a typed `actions` array natively. Default severity is `warn`.
557 #[serde(default, skip_serializing_if = "Vec::is_empty")]
558 pub unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
559 /// `true` when the `unused-load-data-key` detector abstained project-wide
560 /// because a whole-object use of `page.data` / `$page.data` was seen
561 /// somewhere (S1 observability: an empty `unused_load_data_keys` with this
562 /// flag set is NOT a clean bill, it means the rule could not run safely).
563 /// Serialized only when `true` so the default JSON contract is unchanged.
564 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
565 pub unused_load_data_keys_global_abstain: bool,
566 /// React/Preact props forwarded unchanged through `>= N` intermediate
567 /// pass-through components until a consumer (located per-chain records).
568 /// Wrapped in [`PropDrillingChainFinding`] so each entry carries a typed
569 /// `actions` array natively. Health signal: the rule defaults to `off`
570 /// (opt-in), so this is dormant and populated only when the user enables it.
571 #[serde(default, skip_serializing_if = "Vec::is_empty")]
572 pub prop_drilling_chains: Vec<PropDrillingChainFinding>,
573 /// React/Preact components whose entire body is a single spread-forwarded
574 /// child render (`return <Child {...props}/>`): pure structural indirection,
575 /// a candidate for inlining at call sites. Wrapped in [`ThinWrapperFinding`]
576 /// so each entry carries a typed `actions` array natively. Health signal: the
577 /// rule defaults to `off` (opt-in), so this is dormant and populated only
578 /// when the user enables it.
579 #[serde(default, skip_serializing_if = "Vec::is_empty")]
580 pub thin_wrappers: Vec<ThinWrapperFinding>,
581 /// React/Preact components that participate in a duplicate-prop-shape group:
582 /// three or more components across two or more files whose statically-known
583 /// prop NAME set is identical after stripping ubiquitous DOM / passthrough
584 /// names (a missing shared `Props` type / base component). Wrapped in
585 /// [`DuplicatePropShapeFinding`] so each entry carries a typed `actions`
586 /// array and its sibling roster natively. Health signal: the rule defaults to
587 /// `off` (opt-in), so this is dormant and populated only when the user
588 /// enables it.
589 #[serde(default, skip_serializing_if = "Vec::is_empty")]
590 pub duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
591 /// Number of `unused_exports`, `unused_types`, `unused_class_members` and
592 /// `unused_enum_members` findings that this run did not report because
593 /// their file is an unused file. Deleting the file removes them, so they
594 /// add no information. `--show-cascade` or the `showCascade` config key
595 /// keeps them in the report, and then this count is zero. The count is
596 /// taken after the scope and the rules and before a baseline. Serialized
597 /// only when not zero, so a run without such findings keeps its JSON.
598 #[serde(default, skip_serializing_if = "is_zero")]
599 pub cascade_hidden: usize,
600 /// In-process state of the unused-file cascade filter: the unused-file
601 /// candidates of the detector and the findings that the filter removed.
602 /// Skipped in machine output; [`Self::cascade_hidden`] is the public count.
603 #[serde(skip)]
604 #[cfg_attr(feature = "schema", schemars(skip))]
605 pub cascade: CascadeState,
606 /// Number of suppression entries that matched an issue during analysis.
607 /// Human output uses this for the suppression footer; it is skipped in
608 /// machine output to avoid changing the public JSON issue contract.
609 #[serde(skip)]
610 pub suppression_count: usize,
611 /// Number of component props exempted from `unused-component-props` this run
612 /// because their local destructure binding name matched
613 /// `unusedComponentProps.ignorePattern`. Drives a human-output note so a
614 /// mistyped pattern (matching nothing) is not a silent no-op; skipped in
615 /// machine output, like [`Self::suppression_count`].
616 #[serde(skip)]
617 pub unused_component_props_exempted: usize,
618 /// Suppression comments present in analyzed files this run (every present
619 /// marker, all kinds, not only consumed ones). Internal: read in-process by
620 /// `fallow impact` to distinguish a genuinely resolved finding from one
621 /// silenced by a `fallow-ignore`. Skipped during serialization, like
622 /// [`Self::suppression_count`], so the public JSON output contract is
623 /// unchanged.
624 #[serde(skip)]
625 pub active_suppressions: Vec<ActiveSuppression>,
626 /// Detected feature flag patterns. Advisory output, not included in issue counts.
627 /// Skipped during default serialization: injected separately in JSON output when enabled.
628 #[serde(skip)]
629 pub feature_flags: Vec<FeatureFlag>,
630 /// Security candidates to verify, not verified vulnerabilities. Set only when a `security_*`
631 /// rule is on (`fallow security` turns them on). Skipped in serialization and not counted in
632 /// `total_issues`, so bare `fallow` never shows them; `fallow security` has its own envelope.
633 #[serde(skip)]
634 pub security_findings: Vec<SecurityFinding>,
635 /// Inline-suppressed security candidates. The stable id ordinals count them; then cleared.
636 #[serde(skip)]
637 pub suppressed_security_findings: Vec<SecurityFinding>,
638 /// In-band blind-spot count: number of `"use client"` files whose transitive
639 /// import cone contains a dynamic `import()` the reachability BFS cannot
640 /// follow. Surfaced by `fallow security` so a leak hidden behind an
641 /// unresolved edge is never silently reported as "clean". Skipped during
642 /// serialization like [`Self::security_findings`].
643 #[serde(skip)]
644 pub security_unresolved_edge_files: usize,
645 /// In-band blind-spot count: number of sink-shaped nodes the catalogue
646 /// detector could not flatten to a static callee path (dynamic dispatch,
647 /// computed members, aliased bindings). Surfaced by `fallow security` so an
648 /// empty catalogue result with a non-zero count is not reported as "clean".
649 /// Skipped during serialization like [`Self::security_findings`].
650 #[serde(skip)]
651 pub security_unresolved_callee_sites: usize,
652 /// Location samples for sink-shaped nodes the catalogue detector could not
653 /// flatten to a static callee path. Skipped during default serialization;
654 /// `fallow security` summarizes this metadata in its own envelope.
655 #[serde(skip)]
656 pub security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
657 /// Usage counts for all exports across the project. Used by the LSP for Code Lens.
658 /// Not included in issue counts -- this is metadata, not an issue type.
659 /// Skipped during serialization: this is internal LSP data, not part of the JSON output schema.
660 #[serde(skip)]
661 pub export_usages: Vec<ExportUsage>,
662 /// Summary of detected entry points, grouped by discovery source.
663 /// Not included in issue counts -- this is informational metadata.
664 /// Skipped during serialization: rendered separately in JSON output.
665 #[serde(skip)]
666 pub entry_point_summary: Option<EntryPointSummary>,
667 /// Internal component render metrics, exposed through health aggregates.
668 #[serde(skip)]
669 pub render_fan_in: Option<RenderFanInMetric>,
670 /// Internal component intelligence used by editor overlays.
671 #[serde(skip)]
672 pub react_component_intel: Vec<ReactComponentIntel>,
673 /// Reachable files in the discovery scope, captured before report filters.
674 /// Empty or deserialized scope cannot grant semantic usage credit.
675 #[serde(skip)]
676 #[cfg_attr(feature = "schema", schemars(skip))]
677 pub semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
678 /// Plugin-owned framework contracts carried only into the optional
679 /// semantic reconciliation pass.
680 #[serde(skip)]
681 #[cfg_attr(feature = "schema", schemars(skip))]
682 pub semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
683 /// `constant-parameter` candidates for the optional semantic pass.
684 #[serde(skip)]
685 #[cfg_attr(feature = "schema", schemars(skip))]
686 pub constant_parameter_candidates: ConstantParameterCandidates,
687}
688
689#[expect(
690 clippy::trivially_copy_pass_by_ref,
691 reason = "serde `skip_serializing_if` passes the field by reference"
692)]
693const fn is_zero(count: &usize) -> bool {
694 *count == 0
695}
696
697/// In-process state of the unused-file cascade filter.
698///
699/// An unused file in the report makes every export and member finding in it
700/// redundant: deleting the file removes them. The filter needs the files that
701/// a suppression comment removed from the report, and it keeps the findings
702/// that it removed, because a baseline entry for such a finding still
703/// describes the project and must not count as stale.
704#[derive(Debug, Default, Clone)]
705pub struct CascadeState {
706 /// Unused files whose finding an inline `fallow-ignore-file unused-file`
707 /// comment suppressed. The cascade filter treats them as reported, so a
708 /// suppression comment never makes a hidden finding visible again. An
709 /// issue-type selection without unused files clears this list.
710 pub suppressed_unused_files: Vec<PathBuf>,
711 /// The findings that the filter removed from the report.
712 pub hidden: CascadeHiddenFindings,
713}
714
715/// Findings that the unused-file cascade filter removed from the report.
716#[derive(Debug, Default, Clone)]
717pub struct CascadeHiddenFindings {
718 /// Hidden `unused_exports` findings.
719 pub unused_exports: Vec<UnusedExportFinding>,
720 /// Hidden `unused_types` findings.
721 pub unused_types: Vec<UnusedTypeFinding>,
722 /// Hidden `unused_enum_members` findings.
723 pub unused_enum_members: Vec<UnusedEnumMemberFinding>,
724 /// Hidden `unused_class_members` findings.
725 pub unused_class_members: Vec<UnusedClassMemberFinding>,
726}
727
728impl CascadeHiddenFindings {
729 /// Number of hidden findings.
730 #[must_use]
731 pub fn len(&self) -> usize {
732 self.unused_exports.len()
733 + self.unused_types.len()
734 + self.unused_enum_members.len()
735 + self.unused_class_members.len()
736 }
737
738 /// Whether the filter removed no finding.
739 #[must_use]
740 pub fn is_empty(&self) -> bool {
741 self.len() == 0
742 }
743
744 /// The hidden findings as a result set, for a baseline comparison.
745 #[must_use]
746 pub fn to_results(&self) -> AnalysisResults {
747 AnalysisResults {
748 unused_exports: self.unused_exports.clone(),
749 unused_types: self.unused_types.clone(),
750 unused_enum_members: self.unused_enum_members.clone(),
751 unused_class_members: self.unused_class_members.clone(),
752 ..AnalysisResults::default()
753 }
754 }
755
756 fn extend(&mut self, other: Self) {
757 self.unused_exports.extend(other.unused_exports);
758 self.unused_types.extend(other.unused_types);
759 self.unused_enum_members.extend(other.unused_enum_members);
760 self.unused_class_members.extend(other.unused_class_members);
761 }
762}
763
764struct AnalysisResultsCoreMergeParts {
765 unused_files: Vec<UnusedFileFinding>,
766 unused_exports: Vec<UnusedExportFinding>,
767 unused_types: Vec<UnusedTypeFinding>,
768 private_type_leaks: Vec<PrivateTypeLeakFinding>,
769 deprecated_exports_in_use: Vec<DeprecatedExportInUseFinding>,
770 unused_enum_members: Vec<UnusedEnumMemberFinding>,
771 unused_class_members: Vec<UnusedClassMemberFinding>,
772 unused_namespace_members: Vec<UnusedNamespaceMemberFinding>,
773 unused_protected_class_members: Vec<UnusedProtectedClassMemberFinding>,
774 unused_store_members: Vec<UnusedStoreMemberFinding>,
775 unresolved_imports: Vec<UnresolvedImportFinding>,
776 boundary_violations: Vec<BoundaryViolationFinding>,
777 boundary_coverage_violations: Vec<BoundaryCoverageViolationFinding>,
778 boundary_call_violations: Vec<BoundaryCallViolationFinding>,
779 policy_violations: Vec<PolicyViolationFinding>,
780 stale_suppressions: Vec<StaleSuppression>,
781}
782
783struct AnalysisResultsGraphMergeParts {
784 unused_dependencies: Vec<UnusedDependencyFinding>,
785 unused_dev_dependencies: Vec<UnusedDevDependencyFinding>,
786 unused_optional_dependencies: Vec<UnusedOptionalDependencyFinding>,
787 unlisted_dependencies: Vec<UnlistedDependencyFinding>,
788 unlisted_binaries: Vec<UnlistedBinaryFinding>,
789 duplicate_exports: Vec<DuplicateExportFinding>,
790 duplicate_export_aliases: Vec<DuplicateExportAliasFinding>,
791 type_only_dependencies: Vec<TypeOnlyDependencyFinding>,
792 test_only_dependencies: Vec<TestOnlyDependencyFinding>,
793 dev_dependencies_in_production: Vec<DevDependencyInProductionFinding>,
794 circular_dependencies: Vec<CircularDependencyFinding>,
795 re_export_cycles: Vec<ReExportCycleFinding>,
796 package_cycles: Vec<PackageCycleFinding>,
797}
798
799struct AnalysisResultsWorkspaceMergeParts {
800 unused_catalog_entries: Vec<UnusedCatalogEntryFinding>,
801 empty_catalog_groups: Vec<EmptyCatalogGroupFinding>,
802 unresolved_catalog_references: Vec<UnresolvedCatalogReferenceFinding>,
803 unused_dependency_overrides: Vec<UnusedDependencyOverrideFinding>,
804 misconfigured_dependency_overrides: Vec<MisconfiguredDependencyOverrideFinding>,
805}
806
807struct AnalysisResultsFrameworkMergeParts {
808 invalid_client_exports: Vec<InvalidClientExportFinding>,
809 mixed_client_server_barrels: Vec<MixedClientServerBarrelFinding>,
810 misplaced_directives: Vec<MisplacedDirectiveFinding>,
811 unprovided_injects: Vec<UnprovidedInjectFinding>,
812 unrendered_components: Vec<UnrenderedComponentFinding>,
813 route_collisions: Vec<RouteCollisionFinding>,
814 dynamic_segment_name_conflicts: Vec<DynamicSegmentNameConflictFinding>,
815 unused_component_props: Vec<UnusedComponentPropFinding>,
816 absent_component_props: Vec<AbsentComponentPropFinding>,
817 constant_parameters: Vec<ConstantParameterFinding>,
818 unused_component_emits: Vec<UnusedComponentEmitFinding>,
819 unused_component_inputs: Vec<UnusedComponentInputFinding>,
820 unused_component_outputs: Vec<UnusedComponentOutputFinding>,
821 unused_svelte_events: Vec<UnusedSvelteEventFinding>,
822 unused_effect_layers: Vec<UnusedEffectLayerFinding>,
823 unused_tagged_errors: Vec<UnusedTaggedErrorFinding>,
824 unproduced_catch_tags: Vec<UnproducedCatchTagFinding>,
825 unused_server_actions: Vec<UnusedServerActionFinding>,
826 unused_load_data_keys: Vec<UnusedLoadDataKeyFinding>,
827 unused_load_data_keys_global_abstain: bool,
828 prop_drilling_chains: Vec<PropDrillingChainFinding>,
829 thin_wrappers: Vec<ThinWrapperFinding>,
830 duplicate_prop_shapes: Vec<DuplicatePropShapeFinding>,
831}
832
833struct AnalysisResultsMetadataMergeParts {
834 shared_state: Option<crate::shared_state::SharedStateInventory>,
835 cascade_hidden: usize,
836 cascade: CascadeState,
837 suppression_count: usize,
838 unused_component_props_exempted: usize,
839 active_suppressions: Vec<ActiveSuppression>,
840 feature_flags: Vec<FeatureFlag>,
841 security_findings: Vec<SecurityFinding>,
842 suppressed_security_findings: Vec<SecurityFinding>,
843 security_unresolved_edge_files: usize,
844 security_unresolved_callee_sites: usize,
845 security_unresolved_callee_diagnostics: Vec<SecurityUnresolvedCalleeDiagnostic>,
846 export_usages: Vec<ExportUsage>,
847 entry_point_summary: Option<EntryPointSummary>,
848 render_fan_in: Option<RenderFanInMetric>,
849 react_component_intel: Vec<ReactComponentIntel>,
850 semantic_reachable_files: rustc_hash::FxHashSet<PathBuf>,
851 semantic_framework_contracts: Vec<crate::semantic::SemanticFrameworkContract>,
852 constant_parameter_candidates: ConstantParameterCandidates,
853}
854
855macro_rules! counted_analysis_result_fields {
856 ($callback:ident $(, $arg:expr)? ) => {
857 $callback! {
858 $($arg,)?
859 unused_files => "unused_files",
860 unused_exports => "unused_exports",
861 unused_types => "unused_types",
862 private_type_leaks => "private_type_leaks",
863 deprecated_exports_in_use => "deprecated_exports_in_use",
864 unused_dependencies => "unused_dependencies",
865 unused_dev_dependencies => "unused_dev_dependencies",
866 unused_optional_dependencies => "unused_optional_dependencies",
867 unused_enum_members => "unused_enum_members",
868 unused_class_members => "unused_class_members",
869 unused_namespace_members => "unused_namespace_members",
870 unused_protected_class_members => "unused_protected_class_members",
871 unused_store_members => "unused_store_members",
872 unresolved_imports => "unresolved_imports",
873 unlisted_dependencies => "unlisted_dependencies",
874 unlisted_binaries => "unlisted_binaries",
875 duplicate_exports => "duplicate_exports",
876 duplicate_export_aliases => "duplicate_export_aliases",
877 type_only_dependencies => "type_only_dependencies",
878 test_only_dependencies => "test_only_dependencies",
879 dev_dependencies_in_production => "dev_dependencies_in_production",
880 circular_dependencies => "circular_dependencies",
881 re_export_cycles => "re_export_cycles",
882 package_cycles => "package_cycles",
883 boundary_violations => "boundary_violations",
884 boundary_coverage_violations => "boundary_coverage_violations",
885 boundary_call_violations => "boundary_call_violations",
886 policy_violations => "policy_violations",
887 stale_suppressions => "stale_suppressions",
888 unused_catalog_entries => "unused_catalog_entries",
889 empty_catalog_groups => "empty_catalog_groups",
890 unresolved_catalog_references => "unresolved_catalog_references",
891 unused_dependency_overrides => "unused_dependency_overrides",
892 misconfigured_dependency_overrides => "misconfigured_dependency_overrides",
893 invalid_client_exports => "invalid_client_exports",
894 mixed_client_server_barrels => "mixed_client_server_barrels",
895 misplaced_directives => "misplaced_directives",
896 unprovided_injects => "unprovided_injects",
897 unrendered_components => "unrendered_components",
898 route_collisions => "route_collisions",
899 dynamic_segment_name_conflicts => "dynamic_segment_name_conflicts",
900 unused_component_props => "unused_component_props",
901 absent_component_props => "absent_component_props",
902 constant_parameters => "constant_parameters",
903 unused_component_emits => "unused_component_emits",
904 unused_component_inputs => "unused_component_inputs",
905 unused_component_outputs => "unused_component_outputs",
906 unused_svelte_events => "unused_svelte_events",
907 unused_effect_layers => "unused_effect_layers",
908 unused_tagged_errors => "unused_tagged_errors",
909 unproduced_catch_tags => "unproduced_catch_tags",
910 unused_server_actions => "unused_server_actions",
911 unused_load_data_keys => "unused_load_data_keys",
912 }
913 };
914}
915
916trait FindingIgnorePolicy {
917 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool;
918}
919
920macro_rules! impl_single_source_dead_code {
921 ($($finding:ty => $($field:ident).+),+ $(,)?) => {
922 $(
923 impl FindingIgnorePolicy for $finding {
924 fn should_ignore(
925 &self,
926 predicate: &mut impl FnMut(&Path) -> bool,
927 ) -> bool {
928 predicate(&self.$($field).+)
929 }
930 }
931 )+
932 };
933}
934
935impl_single_source_dead_code! {
936 UnusedFileFinding => file.path,
937 UnusedExportFinding => export.path,
938 UnusedTypeFinding => export.path,
939 PrivateTypeLeakFinding => leak.path,
940 DeprecatedExportInUseFinding => export.path,
941 UnusedEnumMemberFinding => member.path,
942 UnusedClassMemberFinding => member.path,
943 UnusedNamespaceMemberFinding => member.path,
944 UnusedProtectedClassMemberFinding => member.path,
945 UnusedStoreMemberFinding => member.path,
946 UnresolvedImportFinding => import.path,
947 UnprovidedInjectFinding => inject.path,
948 UnrenderedComponentFinding => component.path,
949 UnusedComponentPropFinding => prop.path,
950 AbsentComponentPropFinding => prop.path,
951 ConstantParameterFinding => parameter.path,
952 UnusedComponentEmitFinding => emit.path,
953 UnusedComponentInputFinding => input.path,
954 UnusedComponentOutputFinding => output.path,
955 UnusedSvelteEventFinding => event.path,
956 UnusedEffectLayerFinding => layer.path,
957 DuplicateExportAliasFinding => alias.path,
958 UnusedTaggedErrorFinding => error.path,
959 UnproducedCatchTagFinding => catch_tag.path,
960 UnusedServerActionFinding => action.path,
961 UnusedLoadDataKeyFinding => key.path,
962 ThinWrapperFinding => wrapper.file,
963 DuplicatePropShapeFinding => shape.file,
964}
965
966macro_rules! impl_never_ignored_finding {
967 ($($finding:ty),+ $(,)?) => {
968 $(
969 impl FindingIgnorePolicy for $finding {
970 fn should_ignore(
971 &self,
972 _predicate: &mut impl FnMut(&Path) -> bool,
973 ) -> bool {
974 false
975 }
976 }
977 )+
978 };
979}
980
981impl_never_ignored_finding! {
982 UnusedDependencyFinding,
983 UnusedDevDependencyFinding,
984 UnusedOptionalDependencyFinding,
985 TypeOnlyDependencyFinding,
986 TestOnlyDependencyFinding,
987 DevDependencyInProductionFinding,
988 UnusedCatalogEntryFinding,
989 EmptyCatalogGroupFinding,
990 UnresolvedCatalogReferenceFinding,
991 UnusedDependencyOverrideFinding,
992 MisconfiguredDependencyOverrideFinding,
993 BoundaryViolationFinding,
994 BoundaryCoverageViolationFinding,
995 BoundaryCallViolationFinding,
996 PolicyViolationFinding,
997 StaleSuppression,
998 InvalidClientExportFinding,
999 MixedClientServerBarrelFinding,
1000 MisplacedDirectiveFinding,
1001 RouteCollisionFinding,
1002 DynamicSegmentNameConflictFinding,
1003}
1004
1005impl FindingIgnorePolicy for UnlistedDependencyFinding {
1006 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1007 all_nonempty_paths_match(
1008 self.dep.imported_from.iter().map(|site| &site.path),
1009 predicate,
1010 )
1011 }
1012}
1013
1014impl FindingIgnorePolicy for UnlistedBinaryFinding {
1015 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1016 all_nonempty_paths_match(self.binary.used_in.iter().map(|site| &site.path), predicate)
1017 }
1018}
1019
1020impl FindingIgnorePolicy for DuplicateExportFinding {
1021 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1022 all_nonempty_paths_match(
1023 self.export.locations.iter().map(|location| &location.path),
1024 predicate,
1025 )
1026 }
1027}
1028
1029impl FindingIgnorePolicy for CircularDependencyFinding {
1030 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1031 all_nonempty_paths_match(self.cycle.files.iter(), predicate)
1032 }
1033}
1034
1035impl FindingIgnorePolicy for ReExportCycleFinding {
1036 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1037 all_nonempty_paths_match(self.cycle.files.iter(), predicate)
1038 }
1039}
1040
1041impl FindingIgnorePolicy for PackageCycleFinding {
1042 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1043 all_nonempty_paths_match(self.cycle.edges.iter().map(|edge| &edge.path), predicate)
1044 }
1045}
1046
1047impl FindingIgnorePolicy for PropDrillingChainFinding {
1048 fn should_ignore(&self, predicate: &mut impl FnMut(&Path) -> bool) -> bool {
1049 all_nonempty_paths_match(self.chain.hops.iter().map(|hop| &hop.file), predicate)
1050 }
1051}
1052
1053/// Source-owned health families hidden by `ignoreFindings`.
1054///
1055/// These live outside the unconditional counted table: only explicit error
1056/// findings contribute to `total_issues`; warnings remain advisory.
1057macro_rules! uncounted_source_owned_result_fields {
1058 ($callback:ident $(, $arg:expr)? ) => {
1059 $callback! {
1060 $($arg,)?
1061 prop_drilling_chains => "prop_drilling_chains",
1062 thin_wrappers => "thin_wrappers",
1063 duplicate_prop_shapes => "duplicate_prop_shapes",
1064 }
1065 };
1066}
1067
1068macro_rules! remove_configured_ignored_findings {
1069 ($state:expr, $($field:ident => $key:literal,)+) => {{
1070 let (results, predicate) = $state;
1071 $(
1072 results.$field.retain(|issue| {
1073 !issue.should_ignore(&mut *predicate)
1074 });
1075 )+
1076 }};
1077}
1078
1079macro_rules! counted_result_key_slice {
1080 ($($field:ident => $key:literal,)+) => {
1081 &[$($key),+, "prop_drilling_chains", "thin_wrappers", "duplicate_prop_shapes"]
1082 };
1083}
1084
1085macro_rules! counted_result_field_sum {
1086 ($results:expr, $($field:ident => $key:literal,)+) => {
1087 0 $(+ ($results).$field.len())+
1088 };
1089}
1090#[path = "results_key_findings.rs"]
1091mod result_key_findings;
1092
1093/// Serialized `AnalysisResults` arrays that contribute to [`AnalysisResults::total_issues`].
1094pub const TOTAL_ISSUE_RESULT_KEYS: &[&str] =
1095 counted_analysis_result_fields!(counted_result_key_slice);
1096
1097impl AnalysisResults {
1098 /// Remove the export and member findings whose file `covered` selects.
1099 ///
1100 /// Only `unused_exports`, `unused_types`, `unused_enum_members` and
1101 /// `unused_class_members` change. A removed finding moves to
1102 /// [`CascadeState::hidden`] and [`Self::cascade_hidden`] counts it. A second
1103 /// call removes only findings that a later stage added, so the pass is
1104 /// idempotent.
1105 pub fn hide_cascade_findings(&mut self, covered: &dyn Fn(&Path) -> bool) {
1106 let mut hidden = CascadeHiddenFindings::default();
1107 move_covered(
1108 &mut self.unused_exports,
1109 &mut hidden.unused_exports,
1110 |finding| finding.export.path.as_path(),
1111 covered,
1112 );
1113 move_covered(
1114 &mut self.unused_types,
1115 &mut hidden.unused_types,
1116 |finding| finding.export.path.as_path(),
1117 covered,
1118 );
1119 move_covered(
1120 &mut self.unused_enum_members,
1121 &mut hidden.unused_enum_members,
1122 |finding| finding.member.path.as_path(),
1123 covered,
1124 );
1125 move_covered(
1126 &mut self.unused_class_members,
1127 &mut hidden.unused_class_members,
1128 |finding| finding.member.path.as_path(),
1129 covered,
1130 );
1131 self.cascade_hidden += hidden.len();
1132 self.cascade.hidden.extend(hidden);
1133 }
1134
1135 /// Move the findings that [`Self::hide_cascade_findings`] removed back
1136 /// into the report and reset [`Self::cascade_hidden`].
1137 ///
1138 /// Metrics that measure the code, such as the vital signs, read the
1139 /// result set after this call, so their value does not depend on
1140 /// `showCascade`.
1141 pub fn restore_cascade_findings(&mut self) {
1142 let hidden = std::mem::take(&mut self.cascade.hidden);
1143 self.unused_exports.extend(hidden.unused_exports);
1144 self.unused_types.extend(hidden.unused_types);
1145 self.unused_enum_members.extend(hidden.unused_enum_members);
1146 self.unused_class_members
1147 .extend(hidden.unused_class_members);
1148 self.cascade_hidden = 0;
1149 }
1150
1151 /// Remove dead-code findings whose complete, non-empty source-owner set
1152 /// matches `is_ignored`.
1153 ///
1154 /// Architecture, policy, suppression-hygiene, framework-correctness,
1155 /// security, and package/project findings are retained. Context paths
1156 /// embedded in a dead-code finding are not owners.
1157 #[doc(hidden)]
1158 pub fn remove_ignored_dead_code_findings(&mut self, mut is_ignored: impl FnMut(&Path) -> bool) {
1159 classify_ignore_findings_fields(self);
1160 counted_analysis_result_fields!(
1161 remove_configured_ignored_findings,
1162 (&mut *self, &mut is_ignored)
1163 );
1164 uncounted_source_owned_result_fields!(
1165 remove_configured_ignored_findings,
1166 (&mut *self, &mut is_ignored)
1167 );
1168 }
1169
1170 /// Total number of issues found.
1171 ///
1172 /// Sums across all issue categories (unused files, exports, types,
1173 /// dependencies, members, unresolved imports, unlisted deps, duplicates,
1174 /// type-only deps, circular deps, and boundary violations).
1175 ///
1176 /// # Examples
1177 ///
1178 /// ```
1179 /// use fallow_types::output_dead_code::{UnresolvedImportFinding, UnusedFileFinding};
1180 /// use fallow_types::results::{AnalysisResults, UnresolvedImport, UnusedFile};
1181 /// use std::path::PathBuf;
1182 ///
1183 /// let mut results = AnalysisResults::default();
1184 /// results
1185 /// .unused_files
1186 /// .push(UnusedFileFinding::with_actions(UnusedFile {
1187 /// path: PathBuf::from("a.ts"),
1188 /// }));
1189 /// results
1190 /// .unresolved_imports
1191 /// .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
1192 /// path: PathBuf::from("b.ts"),
1193 /// specifier: "./missing".to_string(),
1194 /// line: 1,
1195 /// col: 0,
1196 /// specifier_col: 0,
1197 /// }));
1198 /// assert_eq!(results.total_issues(), 2);
1199 /// ```
1200 #[must_use]
1201 pub const fn total_issues(&self) -> usize {
1202 counted_analysis_result_fields!(counted_result_field_sum, self)
1203 + self.enforced_prop_drilling_count()
1204 + self.enforced_thin_wrapper_count()
1205 + self.enforced_duplicate_prop_shape_count()
1206 }
1207
1208 /// Whether any issues were found.
1209 #[must_use]
1210 pub const fn has_issues(&self) -> bool {
1211 self.total_issues() > 0
1212 }
1213
1214 /// Merge `other` into `self`, taking the union of every field.
1215 ///
1216 /// This is the single canonical way to combine two [`AnalysisResults`]
1217 /// (the LSP merges per-project-root results through it). The method
1218 /// exhaustively destructures `Self`, so adding a field to the struct
1219 /// becomes a compile error here instead of a silently-dropped field. See
1220 /// issue #444.
1221 ///
1222 /// Every `Vec` field is appended (callers dedup downstream where needed,
1223 /// e.g. the LSP's identity-keyed `dedup_results`). `suppression_count`
1224 /// sums; `entry_point_summary` keeps `self`'s value when present and
1225 /// otherwise adopts `other`'s.
1226 pub fn merge_into(&mut self, other: Self) {
1227 let (core, graph, workspace, framework, metadata) = split_merge_parts(other);
1228 self.merge_core_findings(core);
1229 self.merge_dependency_and_graph_findings(graph);
1230 self.merge_workspace_findings(workspace);
1231 self.merge_framework_findings(framework);
1232 self.merge_metadata_and_security(metadata);
1233 }
1234
1235 fn merge_core_findings(&mut self, parts: AnalysisResultsCoreMergeParts) {
1236 self.unused_files.extend(parts.unused_files);
1237 self.unused_exports.extend(parts.unused_exports);
1238 self.unused_types.extend(parts.unused_types);
1239 self.private_type_leaks.extend(parts.private_type_leaks);
1240 self.deprecated_exports_in_use
1241 .extend(parts.deprecated_exports_in_use);
1242 self.unused_enum_members.extend(parts.unused_enum_members);
1243 self.unused_class_members.extend(parts.unused_class_members);
1244 self.unused_namespace_members
1245 .extend(parts.unused_namespace_members);
1246 self.unused_protected_class_members
1247 .extend(parts.unused_protected_class_members);
1248 self.unused_store_members.extend(parts.unused_store_members);
1249 self.unresolved_imports.extend(parts.unresolved_imports);
1250 self.boundary_violations.extend(parts.boundary_violations);
1251 self.boundary_coverage_violations
1252 .extend(parts.boundary_coverage_violations);
1253 self.boundary_call_violations
1254 .extend(parts.boundary_call_violations);
1255 self.policy_violations.extend(parts.policy_violations);
1256 self.stale_suppressions.extend(parts.stale_suppressions);
1257 }
1258
1259 fn merge_dependency_and_graph_findings(&mut self, parts: AnalysisResultsGraphMergeParts) {
1260 self.unused_dependencies.extend(parts.unused_dependencies);
1261 self.unused_dev_dependencies
1262 .extend(parts.unused_dev_dependencies);
1263 self.unused_optional_dependencies
1264 .extend(parts.unused_optional_dependencies);
1265 self.unlisted_dependencies
1266 .extend(parts.unlisted_dependencies);
1267 self.unlisted_binaries.extend(parts.unlisted_binaries);
1268 self.duplicate_exports.extend(parts.duplicate_exports);
1269 self.duplicate_export_aliases
1270 .extend(parts.duplicate_export_aliases);
1271 self.type_only_dependencies
1272 .extend(parts.type_only_dependencies);
1273 self.test_only_dependencies
1274 .extend(parts.test_only_dependencies);
1275 self.dev_dependencies_in_production
1276 .extend(parts.dev_dependencies_in_production);
1277 self.circular_dependencies
1278 .extend(parts.circular_dependencies);
1279 self.re_export_cycles.extend(parts.re_export_cycles);
1280 self.package_cycles.extend(parts.package_cycles);
1281 }
1282
1283 fn merge_workspace_findings(&mut self, parts: AnalysisResultsWorkspaceMergeParts) {
1284 self.unused_catalog_entries
1285 .extend(parts.unused_catalog_entries);
1286 self.empty_catalog_groups.extend(parts.empty_catalog_groups);
1287 self.unresolved_catalog_references
1288 .extend(parts.unresolved_catalog_references);
1289 self.unused_dependency_overrides
1290 .extend(parts.unused_dependency_overrides);
1291 self.misconfigured_dependency_overrides
1292 .extend(parts.misconfigured_dependency_overrides);
1293 }
1294
1295 fn merge_framework_findings(&mut self, parts: AnalysisResultsFrameworkMergeParts) {
1296 self.invalid_client_exports
1297 .extend(parts.invalid_client_exports);
1298 self.mixed_client_server_barrels
1299 .extend(parts.mixed_client_server_barrels);
1300 self.misplaced_directives.extend(parts.misplaced_directives);
1301 self.unprovided_injects.extend(parts.unprovided_injects);
1302 self.unrendered_components
1303 .extend(parts.unrendered_components);
1304 self.route_collisions.extend(parts.route_collisions);
1305 self.dynamic_segment_name_conflicts
1306 .extend(parts.dynamic_segment_name_conflicts);
1307 self.unused_component_props
1308 .extend(parts.unused_component_props);
1309 self.absent_component_props
1310 .extend(parts.absent_component_props);
1311 self.constant_parameters.extend(parts.constant_parameters);
1312 self.unused_component_emits
1313 .extend(parts.unused_component_emits);
1314 self.unused_component_inputs
1315 .extend(parts.unused_component_inputs);
1316 self.unused_component_outputs
1317 .extend(parts.unused_component_outputs);
1318 self.unused_svelte_events.extend(parts.unused_svelte_events);
1319 self.unused_effect_layers.extend(parts.unused_effect_layers);
1320 self.unused_tagged_errors.extend(parts.unused_tagged_errors);
1321 self.unproduced_catch_tags
1322 .extend(parts.unproduced_catch_tags);
1323 self.unused_server_actions
1324 .extend(parts.unused_server_actions);
1325 self.unused_load_data_keys
1326 .extend(parts.unused_load_data_keys);
1327 self.unused_load_data_keys_global_abstain |= parts.unused_load_data_keys_global_abstain;
1328 self.prop_drilling_chains.extend(parts.prop_drilling_chains);
1329 self.thin_wrappers.extend(parts.thin_wrappers);
1330 self.duplicate_prop_shapes
1331 .extend(parts.duplicate_prop_shapes);
1332 }
1333
1334 /// Sort all result arrays for deterministic output ordering.
1335 ///
1336 /// Parallel collection (rayon, `FxHashMap` iteration) does not guarantee
1337 /// insertion order, so the same project can produce different orderings
1338 /// across runs. This method canonicalises every result list by sorting on
1339 /// (path, line, col, name) so that JSON/SARIF/human output is stable.
1340 pub fn sort(&mut self) {
1341 self.semantic_framework_contracts.sort();
1342 self.sort_core_findings();
1343 self.sort_dependency_findings();
1344 self.sort_graph_findings();
1345 self.sort_catalog_findings();
1346 self.sort_metadata_findings();
1347 self.sort_export_usages();
1348 }
1349
1350 fn sort_core_findings(&mut self) {
1351 self.sort_core_declaration_findings();
1352 self.sort_core_member_findings();
1353 self.sort_core_framework_findings();
1354 self.sort_core_route_and_load_findings();
1355 }
1356
1357 fn sort_core_declaration_findings(&mut self) {
1358 self.unused_files
1359 .sort_by(|a, b| a.file.path.cmp(&b.file.path));
1360
1361 self.unused_exports.sort_by(|a, b| {
1362 a.export
1363 .path
1364 .cmp(&b.export.path)
1365 .then(a.export.line.cmp(&b.export.line))
1366 .then(a.export.export_name.cmp(&b.export.export_name))
1367 });
1368
1369 self.unused_types.sort_by(|a, b| {
1370 a.export
1371 .path
1372 .cmp(&b.export.path)
1373 .then(a.export.line.cmp(&b.export.line))
1374 .then(a.export.export_name.cmp(&b.export.export_name))
1375 });
1376
1377 self.private_type_leaks.sort_by(|a, b| {
1378 a.leak
1379 .path
1380 .cmp(&b.leak.path)
1381 .then(a.leak.line.cmp(&b.leak.line))
1382 .then(a.leak.export_name.cmp(&b.leak.export_name))
1383 .then(a.leak.type_name.cmp(&b.leak.type_name))
1384 });
1385
1386 self.deprecated_exports_in_use.sort_by(|a, b| {
1387 a.export
1388 .path
1389 .cmp(&b.export.path)
1390 .then(a.export.line.cmp(&b.export.line))
1391 .then(a.export.export_name.cmp(&b.export.export_name))
1392 });
1393
1394 self.unused_dependencies.sort_by(|a, b| {
1395 a.dep
1396 .path
1397 .cmp(&b.dep.path)
1398 .then(a.dep.line.cmp(&b.dep.line))
1399 .then(a.dep.package_name.cmp(&b.dep.package_name))
1400 });
1401
1402 self.unused_dev_dependencies.sort_by(|a, b| {
1403 a.dep
1404 .path
1405 .cmp(&b.dep.path)
1406 .then(a.dep.line.cmp(&b.dep.line))
1407 .then(a.dep.package_name.cmp(&b.dep.package_name))
1408 });
1409
1410 self.unused_optional_dependencies.sort_by(|a, b| {
1411 a.dep
1412 .path
1413 .cmp(&b.dep.path)
1414 .then(a.dep.line.cmp(&b.dep.line))
1415 .then(a.dep.package_name.cmp(&b.dep.package_name))
1416 });
1417 }
1418
1419 fn sort_core_member_findings(&mut self) {
1420 self.unused_enum_members.sort_by(|a, b| {
1421 a.member
1422 .path
1423 .cmp(&b.member.path)
1424 .then(a.member.line.cmp(&b.member.line))
1425 .then(a.member.parent_name.cmp(&b.member.parent_name))
1426 .then(a.member.member_name.cmp(&b.member.member_name))
1427 });
1428
1429 self.unused_class_members.sort_by(|a, b| {
1430 a.member
1431 .path
1432 .cmp(&b.member.path)
1433 .then(a.member.line.cmp(&b.member.line))
1434 .then(a.member.parent_name.cmp(&b.member.parent_name))
1435 .then(a.member.member_name.cmp(&b.member.member_name))
1436 });
1437
1438 self.unused_protected_class_members.sort_by(|a, b| {
1439 a.member
1440 .path
1441 .cmp(&b.member.path)
1442 .then(a.member.line.cmp(&b.member.line))
1443 .then(a.member.parent_name.cmp(&b.member.parent_name))
1444 .then(a.member.member_name.cmp(&b.member.member_name))
1445 });
1446
1447 self.unused_namespace_members.sort_by(|a, b| {
1448 a.member
1449 .path
1450 .cmp(&b.member.path)
1451 .then(a.member.line.cmp(&b.member.line))
1452 .then(a.member.parent_name.cmp(&b.member.parent_name))
1453 .then(a.member.member_name.cmp(&b.member.member_name))
1454 });
1455
1456 self.unused_store_members.sort_by(|a, b| {
1457 a.member
1458 .path
1459 .cmp(&b.member.path)
1460 .then(a.member.line.cmp(&b.member.line))
1461 .then(a.member.parent_name.cmp(&b.member.parent_name))
1462 .then(a.member.member_name.cmp(&b.member.member_name))
1463 });
1464
1465 self.unresolved_imports.sort_by(|a, b| {
1466 a.import
1467 .path
1468 .cmp(&b.import.path)
1469 .then(a.import.line.cmp(&b.import.line))
1470 .then(a.import.col.cmp(&b.import.col))
1471 .then(a.import.specifier.cmp(&b.import.specifier))
1472 });
1473 }
1474
1475 fn sort_core_framework_findings(&mut self) {
1476 self.invalid_client_exports.sort_by(|a, b| {
1477 a.export
1478 .path
1479 .cmp(&b.export.path)
1480 .then(a.export.line.cmp(&b.export.line))
1481 .then(a.export.export_name.cmp(&b.export.export_name))
1482 });
1483
1484 self.mixed_client_server_barrels.sort_by(|a, b| {
1485 a.barrel
1486 .path
1487 .cmp(&b.barrel.path)
1488 .then(a.barrel.line.cmp(&b.barrel.line))
1489 .then(a.barrel.client_origin.cmp(&b.barrel.client_origin))
1490 .then(a.barrel.server_origin.cmp(&b.barrel.server_origin))
1491 });
1492
1493 self.misplaced_directives.sort_by(|a, b| {
1494 a.directive_site
1495 .path
1496 .cmp(&b.directive_site.path)
1497 .then(a.directive_site.line.cmp(&b.directive_site.line))
1498 .then(a.directive_site.col.cmp(&b.directive_site.col))
1499 .then(a.directive_site.directive.cmp(&b.directive_site.directive))
1500 });
1501
1502 self.unprovided_injects.sort_by(|a, b| {
1503 a.inject
1504 .path
1505 .cmp(&b.inject.path)
1506 .then(a.inject.line.cmp(&b.inject.line))
1507 .then(a.inject.col.cmp(&b.inject.col))
1508 .then(a.inject.key_name.cmp(&b.inject.key_name))
1509 });
1510
1511 self.unrendered_components.sort_by(|a, b| {
1512 a.component
1513 .path
1514 .cmp(&b.component.path)
1515 .then(a.component.line.cmp(&b.component.line))
1516 .then(a.component.col.cmp(&b.component.col))
1517 .then(a.component.component_name.cmp(&b.component.component_name))
1518 });
1519 }
1520
1521 fn sort_core_route_and_load_findings(&mut self) {
1522 self.sort_core_route_findings();
1523 self.sort_core_component_prop_and_emit_findings();
1524 self.sort_core_component_io_findings();
1525 self.sort_core_server_load_findings();
1526 }
1527
1528 fn sort_core_route_findings(&mut self) {
1529 self.route_collisions.sort_by(|a, b| {
1530 a.collision
1531 .path
1532 .cmp(&b.collision.path)
1533 .then(a.collision.url.cmp(&b.collision.url))
1534 });
1535
1536 self.dynamic_segment_name_conflicts.sort_by(|a, b| {
1537 a.conflict
1538 .path
1539 .cmp(&b.conflict.path)
1540 .then(a.conflict.position.cmp(&b.conflict.position))
1541 });
1542 }
1543
1544 fn sort_core_component_prop_and_emit_findings(&mut self) {
1545 sort_constant_parameters(&mut self.constant_parameters);
1546 self.absent_component_props.sort_by(|a, b| {
1547 a.prop
1548 .path
1549 .cmp(&b.prop.path)
1550 .then(a.prop.line.cmp(&b.prop.line))
1551 .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1552 });
1553 self.unused_component_props.sort_by(|a, b| {
1554 a.prop
1555 .path
1556 .cmp(&b.prop.path)
1557 .then(a.prop.line.cmp(&b.prop.line))
1558 .then(a.prop.prop_name.cmp(&b.prop.prop_name))
1559 });
1560
1561 self.unused_component_emits.sort_by(|a, b| {
1562 a.emit
1563 .path
1564 .cmp(&b.emit.path)
1565 .then(a.emit.line.cmp(&b.emit.line))
1566 .then(a.emit.emit_name.cmp(&b.emit.emit_name))
1567 });
1568
1569 self.unused_svelte_events.sort_by(|a, b| {
1570 a.event
1571 .path
1572 .cmp(&b.event.path)
1573 .then(a.event.line.cmp(&b.event.line))
1574 .then(a.event.event_name.cmp(&b.event.event_name))
1575 });
1576 self.sort_effect_findings();
1577 }
1578
1579 fn sort_effect_findings(&mut self) {
1580 self.unused_effect_layers.sort_by(|a, b| {
1581 a.layer
1582 .path
1583 .cmp(&b.layer.path)
1584 .then(a.layer.line.cmp(&b.layer.line))
1585 .then(a.layer.name.cmp(&b.layer.name))
1586 });
1587 self.unused_tagged_errors.sort_by(|a, b| {
1588 a.error
1589 .path
1590 .cmp(&b.error.path)
1591 .then(a.error.line.cmp(&b.error.line))
1592 .then(a.error.name.cmp(&b.error.name))
1593 });
1594 self.unproduced_catch_tags.sort_by(|a, b| {
1595 a.catch_tag
1596 .path
1597 .cmp(&b.catch_tag.path)
1598 .then(a.catch_tag.line.cmp(&b.catch_tag.line))
1599 .then(a.catch_tag.col.cmp(&b.catch_tag.col))
1600 .then(a.catch_tag.tag.cmp(&b.catch_tag.tag))
1601 });
1602 }
1603
1604 fn sort_core_component_io_findings(&mut self) {
1605 self.unused_component_inputs.sort_by(|a, b| {
1606 a.input
1607 .path
1608 .cmp(&b.input.path)
1609 .then(a.input.line.cmp(&b.input.line))
1610 .then(a.input.input_name.cmp(&b.input.input_name))
1611 });
1612
1613 self.unused_component_outputs.sort_by(|a, b| {
1614 a.output
1615 .path
1616 .cmp(&b.output.path)
1617 .then(a.output.line.cmp(&b.output.line))
1618 .then(a.output.output_name.cmp(&b.output.output_name))
1619 });
1620 }
1621
1622 fn sort_core_server_load_findings(&mut self) {
1623 self.unused_server_actions.sort_by(|a, b| {
1624 a.action
1625 .path
1626 .cmp(&b.action.path)
1627 .then(a.action.line.cmp(&b.action.line))
1628 .then(a.action.col.cmp(&b.action.col))
1629 .then(a.action.action_name.cmp(&b.action.action_name))
1630 });
1631
1632 self.unused_load_data_keys.sort_by(|a, b| {
1633 a.key
1634 .path
1635 .cmp(&b.key.path)
1636 .then(a.key.line.cmp(&b.key.line))
1637 .then(a.key.col.cmp(&b.key.col))
1638 .then(a.key.key_name.cmp(&b.key.key_name))
1639 });
1640 }
1641
1642 /// Sort prop-drilling chains by their source hop (first hop): file, line,
1643 /// prop, depth, for deterministic output. Split out of `sort_core_findings`
1644 /// to keep that function under the unit-size ceiling.
1645 fn sort_prop_drilling_chains(&mut self) {
1646 self.prop_drilling_chains.sort_by(|a, b| {
1647 let a_src = a.chain.hops.first();
1648 let b_src = b.chain.hops.first();
1649 let a_file = a_src.map(|h| &h.file);
1650 let b_file = b_src.map(|h| &h.file);
1651 a_file
1652 .cmp(&b_file)
1653 .then_with(|| a_src.map(|h| h.line).cmp(&b_src.map(|h| h.line)))
1654 .then(a.chain.prop.cmp(&b.chain.prop))
1655 .then(a.chain.depth.cmp(&b.chain.depth))
1656 });
1657 }
1658
1659 /// Sort thin-wrapper findings by file, line, then component for
1660 /// deterministic output.
1661 fn sort_thin_wrappers(&mut self) {
1662 self.thin_wrappers.sort_by(|a, b| {
1663 a.wrapper
1664 .file
1665 .cmp(&b.wrapper.file)
1666 .then(a.wrapper.line.cmp(&b.wrapper.line))
1667 .then(a.wrapper.component.cmp(&b.wrapper.component))
1668 });
1669 }
1670
1671 /// Sort duplicate-prop-shape findings by the shared shape first (so a
1672 /// group's members stay adjacent), then file, line, and component, for
1673 /// deterministic output.
1674 fn sort_duplicate_prop_shapes(&mut self) {
1675 self.duplicate_prop_shapes.sort_by(|a, b| {
1676 a.shape
1677 .shape
1678 .cmp(&b.shape.shape)
1679 .then(a.shape.file.cmp(&b.shape.file))
1680 .then(a.shape.line.cmp(&b.shape.line))
1681 .then(a.shape.component.cmp(&b.shape.component))
1682 });
1683 }
1684
1685 fn sort_dependency_findings(&mut self) {
1686 self.unlisted_dependencies
1687 .sort_by(|a, b| a.dep.package_name.cmp(&b.dep.package_name));
1688 for dep in &mut self.unlisted_dependencies {
1689 dep.dep
1690 .imported_from
1691 .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1692 }
1693
1694 self.unlisted_binaries
1695 .sort_by(|a, b| a.binary.binary_name.cmp(&b.binary.binary_name));
1696 for binary in &mut self.unlisted_binaries {
1697 binary.binary.used_in.sort_by(|a, b| {
1698 a.path
1699 .cmp(&b.path)
1700 .then(a.line.cmp(&b.line))
1701 .then(a.col.cmp(&b.col))
1702 });
1703 }
1704
1705 self.duplicate_exports
1706 .sort_by(|a, b| a.export.export_name.cmp(&b.export.export_name));
1707 for dup in &mut self.duplicate_exports {
1708 dup.export
1709 .locations
1710 .sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
1711 }
1712 self.duplicate_export_aliases.sort_by(|a, b| {
1713 a.alias
1714 .path
1715 .cmp(&b.alias.path)
1716 .then(a.alias.line.cmp(&b.alias.line))
1717 .then(a.alias.col.cmp(&b.alias.col))
1718 .then_with(|| a.alias.export_names.cmp(&b.alias.export_names))
1719 });
1720
1721 self.type_only_dependencies.sort_by(|a, b| {
1722 a.dep
1723 .path
1724 .cmp(&b.dep.path)
1725 .then(a.dep.line.cmp(&b.dep.line))
1726 .then(a.dep.package_name.cmp(&b.dep.package_name))
1727 });
1728
1729 self.test_only_dependencies.sort_by(|a, b| {
1730 a.dep
1731 .path
1732 .cmp(&b.dep.path)
1733 .then(a.dep.line.cmp(&b.dep.line))
1734 .then(a.dep.package_name.cmp(&b.dep.package_name))
1735 });
1736
1737 self.dev_dependencies_in_production.sort_by(|a, b| {
1738 a.dep
1739 .path
1740 .cmp(&b.dep.path)
1741 .then(a.dep.line.cmp(&b.dep.line))
1742 .then(a.dep.package_name.cmp(&b.dep.package_name))
1743 });
1744 }
1745
1746 fn sort_graph_findings(&mut self) {
1747 self.circular_dependencies.sort_by(|a, b| {
1748 a.cycle
1749 .files
1750 .cmp(&b.cycle.files)
1751 .then(a.cycle.length.cmp(&b.cycle.length))
1752 });
1753
1754 self.re_export_cycles
1755 .sort_by(|a, b| a.cycle.files.cmp(&b.cycle.files));
1756
1757 self.package_cycles.sort_by(|a, b| {
1758 a.cycle
1759 .length
1760 .cmp(&b.cycle.length)
1761 .then_with(|| a.cycle.packages.cmp(&b.cycle.packages))
1762 });
1763
1764 self.boundary_violations.sort_by(|a, b| {
1765 a.violation
1766 .from_path
1767 .cmp(&b.violation.from_path)
1768 .then(a.violation.line.cmp(&b.violation.line))
1769 .then(a.violation.col.cmp(&b.violation.col))
1770 .then(a.violation.to_path.cmp(&b.violation.to_path))
1771 });
1772
1773 self.boundary_coverage_violations.sort_by(|a, b| {
1774 a.violation
1775 .path
1776 .cmp(&b.violation.path)
1777 .then(a.violation.line.cmp(&b.violation.line))
1778 .then(a.violation.col.cmp(&b.violation.col))
1779 });
1780
1781 self.boundary_call_violations.sort_by(|a, b| {
1782 a.violation
1783 .path
1784 .cmp(&b.violation.path)
1785 .then(a.violation.line.cmp(&b.violation.line))
1786 .then(a.violation.col.cmp(&b.violation.col))
1787 .then(a.violation.callee.cmp(&b.violation.callee))
1788 });
1789
1790 self.policy_violations.sort_by(|a, b| {
1791 a.violation
1792 .path
1793 .cmp(&b.violation.path)
1794 .then(a.violation.line.cmp(&b.violation.line))
1795 .then(a.violation.col.cmp(&b.violation.col))
1796 .then(a.violation.rule_id.cmp(&b.violation.rule_id))
1797 });
1798 }
1799
1800 fn sort_catalog_findings(&mut self) {
1801 self.sort_stale_suppressions();
1802 self.sort_unused_catalog_entries();
1803 self.sort_empty_catalog_groups();
1804 self.sort_unresolved_catalog_references();
1805 self.sort_unused_dependency_overrides();
1806 }
1807
1808 fn sort_stale_suppressions(&mut self) {
1809 self.stale_suppressions.sort_by(|a, b| {
1810 a.path
1811 .cmp(&b.path)
1812 .then(a.line.cmp(&b.line))
1813 .then(a.col.cmp(&b.col))
1814 });
1815 }
1816
1817 fn sort_unused_catalog_entries(&mut self) {
1818 self.unused_catalog_entries.sort_by(|a, b| {
1819 a.entry
1820 .path
1821 .cmp(&b.entry.path)
1822 .then_with(|| {
1823 catalog_sort_key(&a.entry.catalog_name)
1824 .cmp(&catalog_sort_key(&b.entry.catalog_name))
1825 })
1826 .then(a.entry.catalog_name.cmp(&b.entry.catalog_name))
1827 .then(a.entry.entry_name.cmp(&b.entry.entry_name))
1828 });
1829 for finding in &mut self.unused_catalog_entries {
1830 finding.entry.hardcoded_consumers.sort();
1831 finding.entry.hardcoded_consumers.dedup();
1832 }
1833 }
1834
1835 fn sort_empty_catalog_groups(&mut self) {
1836 self.empty_catalog_groups.sort_by(|a, b| {
1837 a.group
1838 .path
1839 .cmp(&b.group.path)
1840 .then_with(|| {
1841 catalog_sort_key(&a.group.catalog_name)
1842 .cmp(&catalog_sort_key(&b.group.catalog_name))
1843 })
1844 .then(a.group.catalog_name.cmp(&b.group.catalog_name))
1845 .then(a.group.line.cmp(&b.group.line))
1846 });
1847 }
1848
1849 fn sort_unresolved_catalog_references(&mut self) {
1850 self.unresolved_catalog_references.sort_by(|a, b| {
1851 a.reference
1852 .path
1853 .cmp(&b.reference.path)
1854 .then(a.reference.line.cmp(&b.reference.line))
1855 .then_with(|| {
1856 catalog_sort_key(&a.reference.catalog_name)
1857 .cmp(&catalog_sort_key(&b.reference.catalog_name))
1858 })
1859 .then(a.reference.catalog_name.cmp(&b.reference.catalog_name))
1860 .then(a.reference.entry_name.cmp(&b.reference.entry_name))
1861 });
1862 for finding in &mut self.unresolved_catalog_references {
1863 finding.reference.available_in_catalogs.sort();
1864 finding.reference.available_in_catalogs.dedup();
1865 }
1866 }
1867
1868 fn sort_unused_dependency_overrides(&mut self) {
1869 self.unused_dependency_overrides.sort_by(|a, b| {
1870 a.entry
1871 .path
1872 .cmp(&b.entry.path)
1873 .then(a.entry.line.cmp(&b.entry.line))
1874 .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1875 });
1876 }
1877
1878 fn sort_metadata_findings(&mut self) {
1879 self.sort_prop_drilling_chains();
1880 self.sort_thin_wrappers();
1881 self.sort_duplicate_prop_shapes();
1882
1883 self.misconfigured_dependency_overrides.sort_by(|a, b| {
1884 a.entry
1885 .path
1886 .cmp(&b.entry.path)
1887 .then(a.entry.line.cmp(&b.entry.line))
1888 .then(a.entry.raw_key.cmp(&b.entry.raw_key))
1889 });
1890
1891 self.feature_flags.sort_by(|a, b| {
1892 a.path
1893 .cmp(&b.path)
1894 .then(a.line.cmp(&b.line))
1895 .then(a.flag_name.cmp(&b.flag_name))
1896 });
1897
1898 self.security_unresolved_callee_diagnostics.sort_by(|a, b| {
1899 a.path
1900 .cmp(&b.path)
1901 .then(a.line.cmp(&b.line))
1902 .then(a.col.cmp(&b.col))
1903 .then(a.reason.cmp(&b.reason))
1904 .then(a.expression_kind.cmp(&b.expression_kind))
1905 });
1906 }
1907
1908 fn sort_export_usages(&mut self) {
1909 for usage in &mut self.export_usages {
1910 usage.reference_locations.sort_by(|a, b| {
1911 a.path
1912 .cmp(&b.path)
1913 .then(a.line.cmp(&b.line))
1914 .then(a.col.cmp(&b.col))
1915 });
1916 }
1917 self.export_usages.sort_by(|a, b| {
1918 a.path
1919 .cmp(&b.path)
1920 .then(a.line.cmp(&b.line))
1921 .then(a.export_name.cmp(&b.export_name))
1922 });
1923 }
1924}
1925
1926/// A file that is not reachable from any entry point.
1927#[derive(Debug, Clone, Serialize, Deserialize)]
1928#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1929pub struct UnusedFile {
1930 /// Absolute path to the unused file.
1931 #[serde(serialize_with = "serde_path::serialize")]
1932 pub path: PathBuf,
1933}
1934
1935/// An export that is never imported by other modules.
1936#[derive(Debug, Clone, Serialize, Deserialize)]
1937#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1938pub struct UnusedExport {
1939 /// File containing the unused export.
1940 #[serde(serialize_with = "serde_path::serialize")]
1941 pub path: PathBuf,
1942 /// Name of the unused export.
1943 pub export_name: String,
1944 /// Whether this is a type-only export.
1945 pub is_type_only: bool,
1946 /// 1-based line number of the export.
1947 pub line: u32,
1948 /// 0-based byte column offset.
1949 pub col: u32,
1950 /// Byte offset into the source file (used by the fix command).
1951 pub span_start: u32,
1952 /// Whether this finding comes from a barrel/index re-export rather than the source definition.
1953 pub is_re_export: bool,
1954 /// Whether the export's leading JSDoc carries `@deprecated`. Absent from
1955 /// the wire when false.
1956 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1957 pub deprecated: bool,
1958 /// Plain-text message of the `@deprecated` tag, capped at
1959 /// [`DEPRECATED_REASON_MAX_CHARS`] characters. Absent when the export is
1960 /// not deprecated or the tag carries no text.
1961 #[serde(default, skip_serializing_if = "Option::is_none")]
1962 pub deprecated_reason: Option<String>,
1963}
1964
1965/// Maximum number of consumers a [`DeprecatedExportInUse`] finding carries in
1966/// its `consumers` sample. The exact total is in `consumer_count`; the full
1967/// list is available through `fallow dead-code --trace <file>:<export>`.
1968pub const DEPRECATED_CONSUMER_SAMPLE_CAP: usize = 10;
1969
1970/// Maximum number of characters kept from a `@deprecated` tag message. A
1971/// longer message is cut at a character boundary and ends with an ellipsis.
1972pub const DEPRECATED_REASON_MAX_CHARS: usize = 200;
1973
1974/// How a consumer references a deprecated export.
1975#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1976#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1977#[serde(rename_all = "kebab-case")]
1978pub enum DeprecatedConsumerKind {
1979 /// A named import (`import { foo }`).
1980 NamedImport,
1981 /// A default import (`import Foo`).
1982 DefaultImport,
1983 /// A namespace import (`import * as ns`): a member access, or a use of
1984 /// the whole namespace object.
1985 NamespaceImport,
1986 /// A re-export (`export { foo } from './bar'`).
1987 ReExport,
1988 /// A dynamic import (`import('./foo')`).
1989 DynamicImport,
1990 /// A side-effect import (`import './foo'`).
1991 SideEffectImport,
1992}
1993
1994/// One file location that references a deprecated export.
1995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1996#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1997pub struct DeprecatedExportConsumer {
1998 /// File that references the deprecated export.
1999 #[serde(serialize_with = "serde_path::serialize")]
2000 pub path: PathBuf,
2001 /// 1-based line number of the import or re-export statement.
2002 pub line: u32,
2003 /// 0-based byte column offset of the import or re-export statement.
2004 pub col: u32,
2005 /// How the file references the export.
2006 pub kind: DeprecatedConsumerKind,
2007}
2008
2009/// An export whose leading JSDoc carries `@deprecated` and that still has at
2010/// least one consumer in a reachable file.
2011#[derive(Debug, Clone, Serialize, Deserialize)]
2012#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2013pub struct DeprecatedExportInUse {
2014 /// File that declares the deprecated export.
2015 #[serde(serialize_with = "serde_path::serialize")]
2016 pub path: PathBuf,
2017 /// Name of the deprecated export.
2018 pub export_name: String,
2019 /// Whether this is a type-only export.
2020 pub is_type_only: bool,
2021 /// 1-based line number of the export.
2022 pub line: u32,
2023 /// 0-based byte column offset of the export.
2024 pub col: u32,
2025 /// Byte offset of the export in the source file.
2026 pub span_start: u32,
2027 /// Plain-text message of the `@deprecated` tag, capped at
2028 /// [`DEPRECATED_REASON_MAX_CHARS`] characters. Absent when the tag
2029 /// carries no text.
2030 #[serde(default, skip_serializing_if = "Option::is_none")]
2031 pub deprecated_reason: Option<String>,
2032 /// Exact number of distinct consumers: reference sites in reachable
2033 /// files, one per path, line, column and kind. `consumers` holds the
2034 /// first [`DEPRECATED_CONSUMER_SAMPLE_CAP`] of them, so the sample is
2035 /// complete when this count is at most the cap.
2036 pub consumer_count: usize,
2037 /// Consumer sample sorted by path, line, column and kind, capped at
2038 /// [`DEPRECATED_CONSUMER_SAMPLE_CAP`] entries.
2039 pub consumers: Vec<DeprecatedExportConsumer>,
2040 /// True when the export is part of the public API: it lives in an entry
2041 /// point, or a re-export chain reaches an entry point. External consumers
2042 /// are not visible, so the finding makes no removal claim.
2043 pub public_api: bool,
2044}
2045
2046impl DeprecatedExportInUse {
2047 /// One-line plain-text description shared by the SARIF and CodeClimate
2048 /// formats.
2049 #[must_use]
2050 pub fn description(&self) -> String {
2051 let count = self.consumer_count;
2052 let noun = if count == 1 { "consumer" } else { "consumers" };
2053 let reason = self
2054 .deprecated_reason
2055 .as_deref()
2056 .map_or_else(String::new, |reason| format!(": {reason}"));
2057 format!(
2058 "Deprecated export '{}' is still used by {count} {noun}{reason}",
2059 self.export_name
2060 )
2061 }
2062}
2063
2064/// A public export signature that references a same-file private type.
2065#[derive(Debug, Clone, Serialize, Deserialize)]
2066#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2067pub struct PrivateTypeLeak {
2068 /// File containing the exported symbol.
2069 #[serde(serialize_with = "serde_path::serialize")]
2070 pub path: PathBuf,
2071 /// Export whose public signature leaks the private type.
2072 pub export_name: String,
2073 /// Private type referenced by the public signature.
2074 pub type_name: String,
2075 /// 1-based line number of the leaking type reference.
2076 pub line: u32,
2077 /// 0-based byte column offset.
2078 pub col: u32,
2079 /// Byte offset of the type reference.
2080 pub span_start: u32,
2081 /// Exact checker-backed provenance when type-aware analysis confirmed the
2082 /// package-public leak across files or re-exports.
2083 #[serde(default, skip_serializing_if = "Option::is_none")]
2084 pub semantic: Option<crate::semantic::SemanticPrivateTypeLeak>,
2085}
2086
2087/// A `"use client"` file that exports a Next.js server-only / route-segment
2088/// config name. Next.js rejects this combination at build time; fallow catches
2089/// it statically before the build runs.
2090#[derive(Debug, Clone, Serialize, Deserialize)]
2091#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2092pub struct InvalidClientExport {
2093 /// File carrying the `"use client"` directive and the illegal export.
2094 #[serde(serialize_with = "serde_path::serialize")]
2095 pub path: PathBuf,
2096 /// Name of the server-only / route-config export that is illegal in a
2097 /// client file (e.g. `metadata`, `generateMetadata`, `revalidate`, `GET`).
2098 pub export_name: String,
2099 /// The file-level directive that makes the export illegal. Always
2100 /// `"use client"` today; carried so the message can name it verbatim.
2101 pub directive: String,
2102 /// 1-based line number of the export.
2103 pub line: u32,
2104 /// 0-based byte column offset of the export.
2105 pub col: u32,
2106}
2107
2108/// A barrel file that re-exports both a `"use client"` origin module and a
2109/// server-only origin module. Importing one name from such a barrel drags the
2110/// other's directive context across the React Server Components boundary (the
2111/// Next.js App Router footgun); fallow catches it statically.
2112#[derive(Debug, Clone, Serialize, Deserialize)]
2113#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2114pub struct MixedClientServerBarrel {
2115 /// The barrel file re-exporting both a client and a server-only origin.
2116 #[serde(serialize_with = "serde_path::serialize")]
2117 pub path: PathBuf,
2118 /// The `"use client"` origin's relative path or specifier as written in the
2119 /// barrel's offending re-export.
2120 pub client_origin: String,
2121 /// The server-only origin's relative path or specifier as written in the
2122 /// barrel's offending re-export.
2123 pub server_origin: String,
2124 /// 1-based line number of the barrel's first offending re-export.
2125 pub line: u32,
2126 /// 0-based byte column offset of the barrel's first offending re-export.
2127 pub col: u32,
2128}
2129
2130/// A `"use client"` / `"use server"` directive written as an expression
2131/// statement after a non-directive statement (an import, a const). The RSC
2132/// bundler only honors a directive in the leading prologue, so once any
2133/// statement precedes it the string is parsed as an ordinary expression and
2134/// silently ignored: the intended client/server boundary never takes effect.
2135/// The fix is to move the directive to the very top of the file.
2136#[derive(Debug, Clone, Serialize, Deserialize)]
2137#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2138pub struct MisplacedDirective {
2139 /// The file carrying the misplaced directive.
2140 #[serde(serialize_with = "serde_path::serialize")]
2141 pub path: PathBuf,
2142 /// The directive string as written, either `"use client"` or
2143 /// `"use server"` (without the surrounding quotes).
2144 pub directive: String,
2145 /// 1-based line number of the misplaced directive statement.
2146 pub line: u32,
2147 /// 0-based byte column offset of the misplaced directive statement.
2148 pub col: u32,
2149}
2150
2151/// A Vue `inject(KEY)` or Svelte `getContext(KEY)` whose symbol KEY is
2152/// `provide`/`setContext`'d nowhere in the analyzed project. The key is a
2153/// symbol with cross-file identity, so an unmatched key is a real dead-half DI
2154/// link: at runtime the inject returns `undefined`, surfaced only at render.
2155/// The fix is binary: provide the key somewhere, or remove the dead inject.
2156#[derive(Debug, Clone, Serialize, Deserialize)]
2157#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2158pub struct UnprovidedInject {
2159 /// The file carrying the orphan inject / getContext call.
2160 #[serde(serialize_with = "serde_path::serialize")]
2161 pub path: PathBuf,
2162 /// The injected key identifier as written at the call site.
2163 pub key_name: String,
2164 /// Which framework's DI API this came from: `"vue"` or `"svelte"`.
2165 pub framework: String,
2166 /// 1-based line number of the inject / getContext call.
2167 pub line: u32,
2168 /// 0-based byte column offset of the inject / getContext call.
2169 pub col: u32,
2170}
2171
2172/// A Next.js Server Action (an export of a `"use server"` file) that no code in
2173/// the analyzed project references: no import-and-call, no `action={fn}` JSX
2174/// binding, no `<form action={fn}>`. This is the cross-graph "declared but zero
2175/// consumers" direction, reclassified out of `unused-export` for `"use server"`
2176/// files so the finding carries the action-specific signal. It does NOT mean the
2177/// endpoint is unreachable: Next still registers the action id, so it stays
2178/// POST-able. It means no project code calls it (likely forgotten / dead, and a
2179/// candidate for removal to shrink surface area).
2180#[derive(Debug, Clone, Serialize, Deserialize)]
2181#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2182pub struct UnusedServerAction {
2183 /// The `"use server"` file that exports the unreferenced action.
2184 #[serde(serialize_with = "serde_path::serialize")]
2185 pub path: PathBuf,
2186 /// The exported action name as written, or `"default"` for a default export.
2187 pub action_name: String,
2188 /// 1-based line number of the export.
2189 pub line: u32,
2190 /// 0-based byte column offset of the export.
2191 pub col: u32,
2192}
2193
2194/// A SvelteKit `+page.{ts,server.ts,js,server.js}` `load()` return-object key
2195/// read by no consumer: not off the sibling `+page.svelte`'s `data.<key>`, nor
2196/// project-wide via `page.data.<key>` / `$page.data.<key>`. A dead load key runs
2197/// a real server/DB fetch cost on every request for data nothing renders. The
2198/// fix is a human call (delete the key, or wire a consumer): a load fetch may
2199/// have side effects, so there is no safe auto-fix.
2200#[derive(Debug, Clone, Serialize, Deserialize)]
2201#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2202pub struct UnusedLoadDataKey {
2203 /// The producer `+page.{ts,server.ts,js,server.js}` file declaring the key.
2204 #[serde(serialize_with = "serde_path::serialize")]
2205 pub path: PathBuf,
2206 /// The returned-object key name read by no consumer.
2207 pub key_name: String,
2208 /// 1-based line number of the key in the return object.
2209 pub line: u32,
2210 /// 0-based byte column offset of the key.
2211 pub col: u32,
2212 /// The route directory relative to the project root (`src/routes/blog`), for
2213 /// agent remediation and per-route trend aggregation. `None` when not
2214 /// determinable.
2215 #[serde(default, skip_serializing_if = "Option::is_none")]
2216 pub route_dir: Option<String>,
2217}
2218
2219/// A Vue/Svelte single-file component (the default export of a `.vue`/`.svelte`
2220/// file) that is reachable in the module graph but rendered NOWHERE in the
2221/// project: no `<Tag>`, no `:is`/`this=` binding, no `components`/`app.component`
2222/// registration, no `h()`/auto-import use, and no script value-read. It survives
2223/// `unused-file` (a barrel re-export keeps it reachable) and `unused-export`
2224/// (the re-export counts as a use), yet no file actually instantiates it.
2225#[derive(Debug, Clone, Serialize, Deserialize)]
2226#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2227pub struct UnrenderedComponent {
2228 /// The component file that is reachable but rendered nowhere.
2229 #[serde(serialize_with = "serde_path::serialize")]
2230 pub path: PathBuf,
2231 /// The component name. For `"vue"` / `"svelte"` / `"astro"` this is the SFC
2232 /// file stem (PascalCase); for `"angular"` it is the component class name; for
2233 /// `"lit"` it is the registered custom-element TAG (e.g. `x-foo`), not a file
2234 /// stem. Use `path` to anchor the file across all frameworks.
2235 pub component_name: String,
2236 /// Which framework this component belongs to: `"vue"`, `"svelte"`, `"astro"`,
2237 /// `"angular"`, or `"lit"`.
2238 pub framework: String,
2239 /// A barrel/file that re-exports this component, kept for the remediation
2240 /// trace ("reachable via X, rendered nowhere"). Absolute in memory,
2241 /// serialized workspace-relative (like `path`); `None` when not determinable.
2242 #[serde(
2243 serialize_with = "serde_path::serialize_option",
2244 skip_serializing_if = "Option::is_none"
2245 )]
2246 pub reachable_via: Option<PathBuf>,
2247 /// 1-based line number of the component (the file head; SFCs have no explicit
2248 /// default-export statement).
2249 pub line: u32,
2250 /// 0-based byte column offset.
2251 pub col: u32,
2252}
2253
2254/// A Vue `<script setup>` `defineProps`, Svelte 5 `$props()`, or React declared
2255/// prop that is referenced NOWHERE inside its own component. Single-component
2256/// finding, zero-FP doctrine: the component abstains on any opaque public or
2257/// fallthrough signal.
2258#[derive(Debug, Clone, Serialize, Deserialize)]
2259#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2260pub struct UnusedComponentProp {
2261 /// The component file declaring the unused prop.
2262 #[serde(serialize_with = "serde_path::serialize")]
2263 pub path: PathBuf,
2264 /// The component name.
2265 pub component_name: String,
2266 /// The declared prop name that is never referenced.
2267 pub prop_name: String,
2268 /// 1-based line number of the prop declaration.
2269 pub line: u32,
2270 /// 0-based byte column offset of the prop declaration.
2271 pub col: u32,
2272}
2273
2274/// A Vue `<script setup>` `defineEmits` declared event that is EMITTED nowhere
2275/// inside its own single-file component (no `emit('<name>')` call). Single-file
2276/// finding, zero-FP doctrine: the whole file abstains on any
2277/// unharvestable / dynamic-emit / whole-object-use / `defineModel` signal.
2278#[derive(Debug, Clone, Serialize, Deserialize)]
2279#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2280pub struct UnusedComponentEmit {
2281 /// The `.vue` SFC declaring the unused emit.
2282 #[serde(serialize_with = "serde_path::serialize")]
2283 pub path: PathBuf,
2284 /// The component name (the `.vue` file stem).
2285 pub component_name: String,
2286 /// The declared emit event name that is never emitted.
2287 pub emit_name: String,
2288 /// 1-based line number of the emit declaration.
2289 pub line: u32,
2290 /// 0-based byte column offset of the emit declaration.
2291 pub col: u32,
2292}
2293
2294/// A Svelte component dispatching a custom event via `createEventDispatcher()`
2295/// whose event name is listened to NOWHERE in the analyzed project. Cross-file
2296/// dead-output direction: the component fires an event nothing handles.
2297/// Zero-FP doctrine: the whole component abstains on any dynamic-dispatch or
2298/// whole-`dispatch`-value signal, and a listener on ANY component anywhere
2299/// credits the event name (the liberal over-credit direction).
2300#[derive(Debug, Clone, Serialize, Deserialize)]
2301#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2302pub struct UnusedSvelteEvent {
2303 /// The `.svelte` component dispatching the unlistened event.
2304 #[serde(serialize_with = "serde_path::serialize")]
2305 pub path: PathBuf,
2306 /// The component name (the `.svelte` file stem).
2307 pub component_name: String,
2308 /// The dispatched event name that is listened to nowhere.
2309 pub event_name: String,
2310 /// 1-based line number of the `dispatch('<name>')` call.
2311 pub line: u32,
2312 /// 0-based byte column offset of the `dispatch('<name>')` call.
2313 pub col: u32,
2314}
2315
2316/// Kind of an Effect layer definition.
2317#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2318#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2319#[serde(rename_all = "snake_case")]
2320pub enum EffectLayerKind {
2321 /// A module-scope `const` whose initializer is a layer.
2322 TopLevel,
2323 /// A class static property whose initializer is a layer.
2324 StaticMember,
2325}
2326
2327/// An Effect layer whose every reference sits inside other layers that
2328/// nothing in the project uses. The layer is reachable only through a dead
2329/// composition, so it never reaches a runtime. A layer with zero references
2330/// is not reported here: `unused-export` or `unused-class-member` owns it.
2331#[derive(Debug, Clone, Serialize, Deserialize)]
2332#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2333pub struct UnusedEffectLayer {
2334 /// The module that defines the layer.
2335 #[serde(serialize_with = "serde_path::serialize")]
2336 pub path: PathBuf,
2337 /// `FooLive`, or `FooService.layer` for a static member.
2338 pub name: String,
2339 /// Whether the layer is a module-scope const or a class static member.
2340 pub kind: EffectLayerKind,
2341 /// 1-based line number of the layer name.
2342 pub line: u32,
2343 /// 0-based byte column offset of the layer name.
2344 pub col: u32,
2345 /// The unused layers that compose this layer, sorted by name.
2346 pub dead_consumers: Vec<String>,
2347}
2348
2349/// A source location of a `catchTag` or `catchTags` handler.
2350#[derive(Debug, Clone, Serialize, Deserialize)]
2351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2352pub struct EffectCatchSite {
2353 /// The module that contains the handler.
2354 #[serde(serialize_with = "serde_path::serialize")]
2355 pub path: PathBuf,
2356 /// 1-based line number of the handled tag.
2357 pub line: u32,
2358 /// 0-based byte column offset of the handled tag.
2359 pub col: u32,
2360}
2361
2362/// An Effect tagged error class that type positions or `catchTag` handlers
2363/// reference, but that no code constructs, fails with, or reads as a value.
2364/// Any value reference counts as a producer, including a schema union or an
2365/// API error declaration that decodes the error at a boundary.
2366#[derive(Debug, Clone, Serialize, Deserialize)]
2367#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2368pub struct UnusedTaggedError {
2369 /// The module that declares the class.
2370 #[serde(serialize_with = "serde_path::serialize")]
2371 pub path: PathBuf,
2372 /// The class name.
2373 pub name: String,
2374 /// The `_tag` value of the class.
2375 pub tag: String,
2376 /// 1-based line number of the class name.
2377 pub line: u32,
2378 /// 0-based byte column offset of the class name.
2379 pub col: u32,
2380 /// The `catchTag` / `catchTags` handlers that name the tag.
2381 pub catch_sites: Vec<EffectCatchSite>,
2382}
2383
2384/// A `catchTag("X")` / `catchTags({ X })` handler whose tag `X` belongs to
2385/// project classes that no code produces. Reported only when no
2386/// `unused-tagged-error` finding covers those classes (the rule is off, or
2387/// the class finding is suppressed).
2388#[derive(Debug, Clone, Serialize, Deserialize)]
2389#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2390pub struct UnproducedCatchTag {
2391 /// The module that contains the handler.
2392 #[serde(serialize_with = "serde_path::serialize")]
2393 pub path: PathBuf,
2394 /// The handled tag.
2395 pub tag: String,
2396 /// 1-based line number of the handled tag.
2397 pub line: u32,
2398 /// 0-based byte column offset of the handled tag.
2399 pub col: u32,
2400 /// The project classes that declare the tag, sorted by name.
2401 pub candidate_classes: Vec<String>,
2402}
2403
2404/// One hop in a prop-drilling chain: a component that received the prop and
2405/// passed it along (or, at the chain ends, the source that owns it and the
2406/// consumer that substantively reads it).
2407#[derive(Debug, Clone, Serialize, Deserialize)]
2408#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2409pub struct PropDrillHop {
2410 /// The file containing this hop's component.
2411 #[serde(serialize_with = "serde_path::serialize")]
2412 pub file: PathBuf,
2413 /// 1-based line of the component definition (or the prop declaration at the
2414 /// source hop). Anchors a jump-to-source for the agent.
2415 pub line: u32,
2416 /// The component name at this hop.
2417 pub component: String,
2418}
2419
2420/// A located prop-drilling chain: a received prop forwarded unchanged through
2421/// `>= N` intermediate pass-through components, each of which only re-passes it,
2422/// until a component that substantively consumes it. The high-confidence signal
2423/// is "the received identifier is used ONLY as the root of forwarded child-JSX
2424/// attribute values", not the attribute name matching. Health signal (rule
2425/// defaults to `off`, opt-in): a small capped penalty plus a `health --hotspots`
2426/// surface, and located per-chain records so CI / an agent can act ("colocate or
2427/// lift to context at hop B"). Zero-FP doctrine: any spread / `cloneElement` /
2428/// element-as-prop / render-prop / context-provider / dynamic shape in the path
2429/// abstains the whole chain.
2430#[derive(Debug, Clone, Serialize, Deserialize)]
2431#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2432pub struct PropDrillingChain {
2433 /// The drilled prop name as declared at the chain source.
2434 pub prop: String,
2435 /// The chain depth = the number of components the prop is forwarded through
2436 /// (source + intermediates + consumer = `hops.len()`). Always `>= N`.
2437 pub depth: u32,
2438 /// The ordered hop trail from source to consumer. The first hop owns the
2439 /// prop, the middle hops are pass-throughs, the last hop consumes it. The
2440 /// finding anchor is the first hop (`path` / `line` for suppression + CI).
2441 pub hops: Vec<PropDrillHop>,
2442}
2443
2444/// A located thin-wrapper / passthrough component: a React/Preact component
2445/// whose entire body is `return <Child {...props}/>` (a single spread-forwarded
2446/// child render, no host wrapper, no own value-add). It is pure structural
2447/// indirection, a CANDIDATE for inlining at call sites or deleting. Health
2448/// signal (rule defaults to `off`, opt-in): never a correctness error. Zero-FP
2449/// doctrine: `forwardRef` / `memo` / exported / context-provider /
2450/// `cloneElement` / render-prop / named-attr / unresolved-child wrappers all
2451/// abstain (each is an intentional indirection or unprovable shape).
2452#[derive(Debug, Clone, Serialize, Deserialize)]
2453#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2454pub struct ThinWrapper {
2455 /// The file containing the wrapper component.
2456 #[serde(serialize_with = "serde_path::serialize")]
2457 pub file: PathBuf,
2458 /// 1-based line of the wrapper component definition (the finding anchor for
2459 /// jump-to-source and line-level suppression).
2460 pub line: u32,
2461 /// The wrapper component name.
2462 pub component: String,
2463 /// The single child component the wrapper forwards its props to (as written
2464 /// at the render site).
2465 pub child_component: String,
2466}
2467
2468/// One member of a duplicate-prop-shape group: the other components that share
2469/// the same significant prop-name set, listed in each member's
2470/// `sharing_components`. Path-sorted for stable output. A located reference (no
2471/// `shape`, which is carried once on the owning [`DuplicatePropShape`]).
2472#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2473#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2474pub struct DuplicatePropShapeMember {
2475 /// The file containing the sibling component.
2476 #[serde(serialize_with = "serde_path::serialize")]
2477 pub file: PathBuf,
2478 /// 1-based line of the sibling component definition.
2479 pub line: u32,
2480 /// The sibling component name.
2481 pub component: String,
2482}
2483
2484/// A React/Preact component that participates in a duplicate-prop-shape GROUP:
2485/// three or more distinct components across two or more files whose
2486/// statically-harvested, fully-known prop NAME set is byte-for-byte IDENTICAL
2487/// after excluding a fixed denylist of ubiquitous DOM / render-passthrough prop
2488/// names, with the REMAINING significant set holding four or more members. This
2489/// is a structural-refactor health signal (extract a shared `Props` type or a
2490/// base component), never a correctness error and never an auto-fix. One finding
2491/// is emitted per participating component; `sharing_components` lists the other
2492/// members of the same group. Health signal: the rule defaults to `off`
2493/// (opt-in), so this is dormant until enabled. Exact full-set identity only: a
2494/// superset / subset relationship does NOT group (so the finding always fits one
2495/// extracted shared type).
2496#[derive(Debug, Clone, Serialize, Deserialize)]
2497#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2498pub struct DuplicatePropShape {
2499 /// The file containing this component.
2500 #[serde(serialize_with = "serde_path::serialize")]
2501 pub file: PathBuf,
2502 /// 1-based line of this component definition (the finding anchor for
2503 /// jump-to-source and line-level suppression).
2504 pub line: u32,
2505 /// This component name.
2506 pub component: String,
2507 /// The shared significant prop-name set (sorted, denylist-stripped). The
2508 /// unit being grouped; identical across every member of the group.
2509 pub shape: Vec<String>,
2510 /// The total number of components in this group (this one plus every
2511 /// sibling).
2512 pub group_size: u32,
2513 /// The other components sharing this exact prop shape (path-sorted). A
2514 /// file-level-suppressed member drops from its own finding but still appears
2515 /// here, because the group is real regardless of suppression.
2516 pub sharing_components: Vec<DuplicatePropShapeMember>,
2517}
2518
2519/// An Angular `@Input()` / signal `input()` / `model()` declared input that is
2520/// read NOWHERE inside its own component (neither the inline/external template
2521/// nor the class body). Single-file dead-input direction; the Angular analogue
2522/// of [`UnusedComponentProp`]. The whole component abstains on an unresolved
2523/// `extends` heritage clause (a base class in another file may read `this.foo`).
2524#[derive(Debug, Clone, Serialize, Deserialize)]
2525#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2526pub struct UnusedComponentInput {
2527 /// The Angular component/directive `.ts` file declaring the unused input.
2528 #[serde(serialize_with = "serde_path::serialize")]
2529 pub path: PathBuf,
2530 /// The component name (the `.ts` file stem).
2531 pub component_name: String,
2532 /// The declared input name that is never read.
2533 pub input_name: String,
2534 /// 1-based line number of the input declaration.
2535 pub line: u32,
2536 /// 0-based byte column offset of the input declaration.
2537 pub col: u32,
2538}
2539
2540/// An Angular `@Output()` / signal `output()` declared output that is EMITTED
2541/// nowhere inside its own component (no `this.<output>.emit(...)`). Single-file
2542/// dead-output direction; the Angular analogue of [`UnusedComponentEmit`]. A
2543/// `model()` is recorded as an input only, so its framework-driven `update:`
2544/// emit is never flagged here. The whole component abstains on an unresolved
2545/// `extends` heritage clause.
2546#[derive(Debug, Clone, Serialize, Deserialize)]
2547#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2548pub struct UnusedComponentOutput {
2549 /// The Angular component/directive `.ts` file declaring the unused output.
2550 #[serde(serialize_with = "serde_path::serialize")]
2551 pub path: PathBuf,
2552 /// The component name (the `.ts` file stem).
2553 pub component_name: String,
2554 /// The declared output name that is never emitted.
2555 pub output_name: String,
2556 /// 1-based line number of the output declaration.
2557 pub line: u32,
2558 /// 0-based byte column offset of the output declaration.
2559 pub col: u32,
2560}
2561
2562/// Two or more Next.js App Router route files that resolve to the SAME URL
2563/// within one app-root. Next.js fails the build ("You cannot have two parallel
2564/// pages that resolve to the same path"); fallow catches it statically and
2565/// names every colliding file at once. One finding is emitted per colliding
2566/// file; `conflicting_paths` lists the sibling files that share the URL.
2567#[derive(Debug, Clone, Serialize, Deserialize)]
2568#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2569pub struct RouteCollision {
2570 /// This colliding route file (a `page` or `route` leaf).
2571 #[serde(serialize_with = "serde_path::serialize")]
2572 pub path: PathBuf,
2573 /// The URL pathname this file resolves to within its app-root, after
2574 /// stripping route groups `(x)` and parallel-slot `@slot` prefixes (e.g.
2575 /// `/about`, `/api/health`, `/blog/:slug`).
2576 pub url: String,
2577 /// The other route files that resolve to the same URL within the same
2578 /// app-root. Path-sorted for stable output / fingerprints.
2579 #[serde(serialize_with = "serde_path::serialize_vec")]
2580 pub conflicting_paths: Vec<PathBuf>,
2581 /// 1-based line number (file-level finding, always 1).
2582 pub line: u32,
2583 /// 0-based byte column offset (file-level finding, always 0).
2584 pub col: u32,
2585}
2586
2587/// Two or more sibling dynamic route segments at the SAME App Router tree
2588/// position using different param spellings (`[id]` vs `[slug]`, or `[...x]`
2589/// vs `[[...x]]`). Next.js throws "You cannot use different slug names for the
2590/// same dynamic path" at dev / production RUNTIME when the position is hit;
2591/// `next build` does NOT catch it, so fallow's static catch surfaces a route
2592/// that would otherwise pass CI and crash at request time. One finding is
2593/// emitted per involved file.
2594#[derive(Debug, Clone, Serialize, Deserialize)]
2595#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2596pub struct DynamicSegmentNameConflict {
2597 /// This route file living under one of the conflicting dynamic segments.
2598 #[serde(serialize_with = "serde_path::serialize")]
2599 pub path: PathBuf,
2600 /// The tree position (parent URL after group/slot normalization) where the
2601 /// dynamic segments conflict, e.g. `/shop` for `/shop/[id]` vs
2602 /// `/shop/[slug]`. The app-root prefix is stripped.
2603 pub position: String,
2604 /// The distinct conflicting dynamic-segment spellings at this position, as
2605 /// written (e.g. `["[id]", "[slug]"]`). Sorted for stable output.
2606 pub conflicting_segments: Vec<String>,
2607 /// The other route files at the same position under a conflicting dynamic
2608 /// segment. Path-sorted for stable output / fingerprints.
2609 #[serde(serialize_with = "serde_path::serialize_vec")]
2610 pub conflicting_paths: Vec<PathBuf>,
2611 /// 1-based line number (file-level finding, always 1).
2612 pub line: u32,
2613 /// 0-based byte column offset (file-level finding, always 0).
2614 pub col: u32,
2615}
2616
2617/// A dependency that is listed in package.json but never imported.
2618#[derive(Debug, Clone, Serialize, Deserialize)]
2619#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2620pub struct UnusedDependency {
2621 /// Package name, including internal workspace package names.
2622 pub package_name: String,
2623 /// Whether this is in `dependencies`, `devDependencies`, or `optionalDependencies`.
2624 pub location: DependencyLocation,
2625 /// Path to the package.json where this dependency is listed.
2626 /// For root deps this is `<root>/package.json`, for workspace deps it is `<ws>/package.json`.
2627 #[serde(serialize_with = "serde_path::serialize")]
2628 pub path: PathBuf,
2629 /// 1-based line number of the dependency entry in package.json.
2630 pub line: u32,
2631 /// Workspace roots that import this package even though the declaring workspace does not.
2632 #[serde(
2633 default,
2634 serialize_with = "serde_path::serialize_vec",
2635 skip_serializing_if = "Vec::is_empty"
2636 )]
2637 #[cfg_attr(feature = "schema", schemars(default))]
2638 pub used_in_workspaces: Vec<PathBuf>,
2639 /// Workspace roots whose package.json declares this package for the files
2640 /// that import it. Only a root finding fills this field: these imports use
2641 /// the nearer workspace declaration, so the root declaration stays unused.
2642 #[serde(
2643 default,
2644 serialize_with = "serde_path::serialize_vec",
2645 skip_serializing_if = "Vec::is_empty"
2646 )]
2647 #[cfg_attr(feature = "schema", schemars(default))]
2648 pub declared_and_imported_in: Vec<PathBuf>,
2649}
2650
2651/// Where in package.json a dependency is listed.
2652///
2653/// # Examples
2654///
2655/// ```
2656/// use fallow_types::results::DependencyLocation;
2657///
2658/// // All three variants are constructible
2659/// let loc = DependencyLocation::Dependencies;
2660/// let dev = DependencyLocation::DevDependencies;
2661/// let opt = DependencyLocation::OptionalDependencies;
2662/// // Debug output includes the variant name
2663/// assert!(format!("{loc:?}").contains("Dependencies"));
2664/// assert!(format!("{dev:?}").contains("DevDependencies"));
2665/// assert!(format!("{opt:?}").contains("OptionalDependencies"));
2666/// ```
2667#[derive(Debug, Clone, Serialize, Deserialize)]
2668#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2669#[serde(rename_all = "camelCase")]
2670pub enum DependencyLocation {
2671 /// Listed in `dependencies`.
2672 Dependencies,
2673 /// Listed in `devDependencies`.
2674 DevDependencies,
2675 /// Listed in `optionalDependencies`.
2676 OptionalDependencies,
2677}
2678
2679/// An unused enum, class, store, or namespace member.
2680#[derive(Debug, Clone, Serialize, Deserialize)]
2681#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2682pub struct UnusedMember {
2683 /// File containing the unused member.
2684 #[serde(serialize_with = "serde_path::serialize")]
2685 pub path: PathBuf,
2686 /// Name of the parent enum, class, store, or exported namespace.
2687 pub parent_name: String,
2688 /// Name of the unused member. A member of a nested namespace has the dotted
2689 /// path from the exported namespace (`Inner.x`).
2690 pub member_name: String,
2691 /// The kind of member: enum member, class method, class property, store
2692 /// member, or namespace member.
2693 pub kind: MemberKind,
2694 /// 1-based line number.
2695 pub line: u32,
2696 /// 0-based byte column offset.
2697 pub col: u32,
2698}
2699
2700/// An import that could not be resolved.
2701#[derive(Debug, Clone, Serialize, Deserialize)]
2702#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2703pub struct UnresolvedImport {
2704 /// File containing the unresolved import.
2705 #[serde(serialize_with = "serde_path::serialize")]
2706 pub path: PathBuf,
2707 /// The import specifier that could not be resolved.
2708 pub specifier: String,
2709 /// 1-based line number.
2710 pub line: u32,
2711 /// 0-based byte column offset of the import statement.
2712 pub col: u32,
2713 /// 0-based byte column offset of the source string literal (the specifier in quotes).
2714 /// Used by the LSP to underline just the specifier, not the entire import line.
2715 pub specifier_col: u32,
2716}
2717
2718/// A dependency used in code but not listed in package.json.
2719#[derive(Debug, Clone, Serialize, Deserialize)]
2720#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2721pub struct UnlistedDependency {
2722 /// Package name, including internal workspace package names, that is
2723 /// imported but not listed in package.json.
2724 pub package_name: String,
2725 /// Import sites where this unlisted dependency is used (file path, line, column).
2726 pub imported_from: Vec<ImportSite>,
2727}
2728
2729/// A binary that a package.json script or a process call runs, but that no
2730/// installed or listed package provides.
2731#[derive(Debug, Clone, Serialize, Deserialize)]
2732#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2733pub struct UnlistedBinary {
2734 /// The binary name as the command runs it (for example `ffmpeg`).
2735 pub binary_name: String,
2736 /// The sites that run this binary.
2737 pub used_in: Vec<BinaryUseSite>,
2738}
2739
2740/// A location that runs a binary.
2741#[derive(Debug, Clone, Serialize, Deserialize)]
2742#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2743pub struct BinaryUseSite {
2744 /// The `package.json` that declares the script, or the source file that
2745 /// makes the process call.
2746 #[serde(serialize_with = "serde_path::serialize")]
2747 pub path: PathBuf,
2748 /// 1-based line number.
2749 pub line: u32,
2750 /// 0-based byte column offset.
2751 pub col: u32,
2752 /// The name of the package.json script that runs the binary. Absent for
2753 /// a process call in source.
2754 #[serde(default, skip_serializing_if = "Option::is_none")]
2755 pub script_name: Option<String>,
2756}
2757
2758/// A location where an import occurs.
2759#[derive(Debug, Clone, Serialize, Deserialize)]
2760#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2761pub struct ImportSite {
2762 /// File containing the import.
2763 #[serde(serialize_with = "serde_path::serialize")]
2764 pub path: PathBuf,
2765 /// 1-based line number.
2766 pub line: u32,
2767 /// 0-based byte column offset.
2768 pub col: u32,
2769}
2770
2771/// An export that appears multiple times across the project.
2772#[derive(Debug, Clone, Serialize, Deserialize)]
2773#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2774pub struct DuplicateExport {
2775 /// The duplicated export name.
2776 pub export_name: String,
2777 /// Locations where this export name appears.
2778 pub locations: Vec<DuplicateLocation>,
2779}
2780
2781/// A location where a duplicate export appears.
2782#[derive(Debug, Clone, Serialize, Deserialize)]
2783#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2784pub struct DuplicateLocation {
2785 /// File containing the duplicate export.
2786 #[serde(serialize_with = "serde_path::serialize")]
2787 pub path: PathBuf,
2788 /// 1-based line number.
2789 pub line: u32,
2790 /// 0-based byte column offset.
2791 pub col: u32,
2792}
2793
2794/// One module that exports one binding under two or more names, for example
2795/// `export const a = 1; export default a;` or `export { a, a as b }`. The
2796/// finding is about the export surface of one file, not about usage, so an
2797/// entry file can have it too. Value and type-only exports of one name are
2798/// separate bindings. Two bindings with the same initializer are not one
2799/// binding.
2800#[derive(Debug, Clone, Serialize, Deserialize)]
2801#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2802pub struct DuplicateExportAlias {
2803 /// The module that exports the binding.
2804 #[serde(serialize_with = "serde_path::serialize")]
2805 pub path: PathBuf,
2806 /// The local name of the binding. For a re-export, the name that the
2807 /// source module exports.
2808 pub local_name: String,
2809 /// The export names of the binding, in source order.
2810 pub export_names: Vec<String>,
2811 /// 1-based line number of the first export of the binding.
2812 pub line: u32,
2813 /// 0-based byte column offset of the first export of the binding.
2814 pub col: u32,
2815 /// One location for each export name, in source order.
2816 pub locations: Vec<DuplicateExportAliasLocation>,
2817}
2818
2819/// One export name of a [`DuplicateExportAlias`].
2820#[derive(Debug, Clone, Serialize, Deserialize)]
2821#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2822pub struct DuplicateExportAliasLocation {
2823 /// The export name at this location (`default` for a default export).
2824 pub export_name: String,
2825 /// 1-based line number.
2826 pub line: u32,
2827 /// 0-based byte column offset.
2828 pub col: u32,
2829}
2830
2831/// A production dependency that is only used via type-only imports.
2832/// In production builds, type imports are erased, so this dependency
2833/// is not needed at runtime and could be moved to devDependencies.
2834#[derive(Debug, Clone, Serialize, Deserialize)]
2835#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2836pub struct TypeOnlyDependency {
2837 /// Production dependency that is only used via type-only imports.
2838 pub package_name: String,
2839 /// Path to the package.json where the dependency is listed.
2840 #[serde(serialize_with = "serde_path::serialize")]
2841 pub path: PathBuf,
2842 /// 1-based line number of the dependency entry in package.json.
2843 pub line: u32,
2844}
2845
2846/// The kind of security candidate. Findings are candidates for downstream agent
2847/// verification, NOT verified vulnerabilities.
2848#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2849#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2850#[serde(rename_all = "kebab-case")]
2851pub enum SecurityFindingKind {
2852 /// A `"use client"` file transitively imports a module that reads a
2853 /// non-public `process.env` secret (graph-structural; bespoke, not catalogue).
2854 ClientServerLeak,
2855 /// A syntactic sink site matched against the data-driven catalogue
2856 /// (`security_matchers.toml`). Serializes `"tainted-sink"`; the CWE class is
2857 /// carried in `category` + `cwe`. ONE variant covers all catalogue categories.
2858 TaintedSink,
2859}
2860
2861/// How strongly the untrusted-source signal is associated with the sink, a
2862/// structured discriminator so a consumer can tier candidates without parsing
2863/// the human `evidence` prose. Present only when
2864/// [`SecurityReachability::reachable_from_untrusted_source`] is true. Neither
2865/// value proves exploitability; both are ranking signals (issue #885 doctrine:
2866/// rank, never gate).
2867#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2868#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2869#[serde(rename_all = "kebab-case")]
2870pub enum TaintConfidence {
2871 /// The sink's argument traces back to a known untrusted-source read in the
2872 /// same statement / module (the intra-module back-trace, issue #859). The
2873 /// strong, high-value candidate: a specific source expression is implicated.
2874 ArgLevel,
2875 /// The sink merely lives in a module that is import-reachable from a module
2876 /// containing an untrusted source (issue #885). The weak candidate: only the
2877 /// module is implicated, not a specific value path to the sink argument.
2878 ModuleLevel,
2879}
2880
2881/// Graph-derived reachability ranking signal for a security candidate. Computed
2882/// from the existing module graph after detection, never proven exploitable.
2883/// Used to surface candidates that sit on a request/runtime-reachable surface,
2884/// receive same-module source evidence, or are import-reachable from an
2885/// untrusted-source module above isolated helpers or scripts.
2886///
2887/// This is a relative-ordering signal, NOT a `confidence` or `signal_strength`
2888/// score: fallow does not prove the path is exploitable.
2889#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2890#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2891pub struct SecurityReachability {
2892 /// Whether the anchor module is reachable from a runtime/application entry
2893 /// point (route handlers, server entry, framework runtime roots), the
2894 /// closest graph proxy for an external/request input surface. Code reachable
2895 /// only from test entry points does not count.
2896 pub reachable_from_entry: bool,
2897 /// Whether the anchor module is reachable over value imports from a module
2898 /// that reads a known untrusted input source. Module-level only: this does
2899 /// not prove a specific source value reaches the sink argument.
2900 #[serde(default)]
2901 pub reachable_from_untrusted_source: bool,
2902 /// Structured tier of the untrusted-source association: `arg-level` when the
2903 /// sink argument traces to a same-module source read (strong), `module-level`
2904 /// when only the module is import-reachable from a source (weak). Present
2905 /// exactly when `reachable_from_untrusted_source` is true, so a consumer can
2906 /// separate strong from weak candidates from this field alone without parsing
2907 /// the `evidence` string. Not an exploitability proof.
2908 #[serde(default, skip_serializing_if = "Option::is_none")]
2909 pub taint_confidence: Option<TaintConfidence>,
2910 /// Number of value-import hops from the untrusted-source module to the sink
2911 /// module when `reachable_from_untrusted_source` is true.
2912 #[serde(default, skip_serializing_if = "Option::is_none")]
2913 pub untrusted_source_hop_count: Option<u32>,
2914 /// Module-level import path from the untrusted-source module to the sink
2915 /// anchor. Empty when no source module reaches this candidate. The path is a
2916 /// ranking explanation, not a value-flow proof.
2917 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2918 pub untrusted_source_trace: Vec<TraceHop>,
2919 /// Number of distinct modules that transitively depend on the anchor module
2920 /// (fan-in via the graph's reverse-dependency index). A higher value means a
2921 /// wider surface: more call sites could route untrusted input into the sink.
2922 pub blast_radius: u32,
2923 /// Whether the anchor module participates in an architecture-boundary
2924 /// violation found in the same run (as the importing or imported file).
2925 /// Optional pairing: a candidate that also crosses a declared boundary is a
2926 /// stronger review target.
2927 pub crosses_boundary: bool,
2928}
2929
2930/// Dead-code cross-link attached to a security candidate when fallow's dead-code
2931/// pass reports the same anchor as removable code.
2932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2933#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2934pub struct SecurityDeadCodeContext {
2935 /// Dead-code issue kind that matched the security candidate.
2936 pub kind: SecurityDeadCodeKind,
2937 /// Unused export name when `kind` is `unused-export`.
2938 #[serde(default, skip_serializing_if = "Option::is_none")]
2939 pub export_name: Option<String>,
2940 /// Dead-code finding line when available.
2941 #[serde(default, skip_serializing_if = "Option::is_none")]
2942 pub line: Option<u32>,
2943 /// Agent-facing guidance for deciding between deletion and hardening.
2944 pub guidance: String,
2945}
2946
2947/// Dead-code issue kind linked to a security candidate.
2948#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2949#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2950#[serde(rename_all = "kebab-case")]
2951pub enum SecurityDeadCodeKind {
2952 /// The candidate's anchor file is also reported as an unused file.
2953 UnusedFile,
2954 /// The candidate's anchor sits on an unused export declaration.
2955 UnusedExport,
2956}
2957
2958/// Internal row for a security sink-shaped callee that extraction could not
2959/// flatten to a static catalogue path.
2960#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2961#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2962pub struct SecurityUnresolvedCalleeDiagnostic {
2963 /// File containing the skipped callee. Absolute internally.
2964 #[serde(serialize_with = "serde_path::serialize")]
2965 pub path: PathBuf,
2966 /// 1-based line of the skipped callee.
2967 pub line: u32,
2968 /// 0-based byte column of the skipped callee.
2969 pub col: u32,
2970 /// Why the callee could not be flattened.
2971 pub reason: SkippedSecurityCalleeReason,
2972 /// Compact syntax shape of the skipped callee.
2973 pub expression_kind: SkippedSecurityCalleeExpressionKind,
2974}
2975
2976/// The sink slot of a [`SecurityCandidate`]: a self-contained description of the
2977/// matched sink site. Echoes the finding's own span (`path`/`line`/`col`) plus
2978/// the catalogue `category`/`cwe` and the captured `callee`, so an agent can act
2979/// on `candidate.sink` in isolation (e.g. after fanning a finding out to a
2980/// sub-agent) without reading the parent finding.
2981#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2982#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2983pub struct SecurityCandidateSink {
2984 /// File of the sink site. Absolute internally; JSON strips the project root
2985 /// via `serde_path::serialize`.
2986 #[serde(serialize_with = "serde_path::serialize")]
2987 pub path: PathBuf,
2988 /// 1-based line of the sink site.
2989 pub line: u32,
2990 /// 0-based byte column of the sink site.
2991 pub col: u32,
2992 /// Catalogue category id of the sink (e.g. `"dangerous-html"`). For
2993 /// `client-server-leak` this is `"client-server-leak"` for the secret-leak
2994 /// finding, and `"server-only-import"` when a `"use client"` cone reaches
2995 /// server-only code. Older releases left it absent for the secret leak.
2996 #[serde(default, skip_serializing_if = "Option::is_none")]
2997 pub category: Option<String>,
2998 /// CWE number declared by the catalogue entry. `None` for
2999 /// `client-server-leak`; never fabricated beyond the catalogue's value.
3000 #[serde(default, skip_serializing_if = "Option::is_none")]
3001 pub cwe: Option<u32>,
3002 /// The sink callee (the dangerous function or member path, e.g.
3003 /// `"el.innerHTML"`, `"child_process.exec"`) captured by the catalogue match.
3004 /// `None` for `client-server-leak` and matches that name no callee.
3005 #[serde(default, skip_serializing_if = "Option::is_none")]
3006 pub callee: Option<String>,
3007 /// URL construction shape for SSRF and open-redirect style candidates when
3008 /// fallow can classify whether the origin is fixed or dynamic. Absent for
3009 /// non-URL sinks and unclassified URL expressions.
3010 #[serde(default, skip_serializing_if = "Option::is_none")]
3011 pub url_shape: Option<SecurityUrlShape>,
3012}
3013
3014/// A declared architecture-zone crossing, recovered by correlating a finding's
3015/// anchor against the run's architecture-boundary violations.
3016#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3017#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3018pub struct SecurityZoneCrossing {
3019 /// Zone the importing side belongs to.
3020 pub from: String,
3021 /// Zone the imported side belongs to.
3022 pub to: String,
3023}
3024
3025/// The boundary slot of a [`SecurityCandidate`]: which structural boundaries the
3026/// candidate's flow crosses. A flow that crosses a client/server or module
3027/// boundary is a stronger review target than a self-contained one; the boundary
3028/// is fallow's structural signal over a pure source-sink match.
3029///
3030/// Two further boundary kinds are reserved for a follow-up and are deliberately
3031/// absent here rather than emitted as always-false: `export_visibility` (is the
3032/// sink on a publicly-exported symbol?) and a package boundary (does the flow
3033/// cross an npm-package edge?). Both need new graph derivation that does not
3034/// exist today; emitting them as `false` would misreport "we checked and it does
3035/// not cross" when fallow has not checked at all.
3036#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3037#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3038pub struct SecurityCandidateBoundary {
3039 /// Whether the finding crosses a client/server boundary (a `"use client"`
3040 /// file appears in the trace). True only for `client-server-leak` today;
3041 /// `tainted-sink` candidates carry no client/server marker.
3042 pub client_server: bool,
3043 /// Whether an untrusted source reaches the sink across one or more
3044 /// value-import (module) hops. Derived from the reachability hop count.
3045 pub cross_module: bool,
3046 /// The architecture-zone crossing when the anchor participates in a declared
3047 /// boundary-rule violation in the same run. `None` when it crosses no
3048 /// declared zone boundary.
3049 #[serde(default, skip_serializing_if = "Option::is_none")]
3050 pub architecture_zone: Option<SecurityZoneCrossing>,
3051}
3052
3053/// Network-destination context for a `secret-to-network` candidate (#890): where
3054/// the secret-bearing network call sends its data. Present only on
3055/// network-category candidates. A consuming agent uses it to triage exfil
3056/// (dynamic / untrusted destination) from intended auth (a literal provider
3057/// host) without re-reading source.
3058#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3059#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3060pub struct SecurityNetworkContext {
3061 /// The network call's destination as a static URL string literal, or absent
3062 /// when the destination is dynamic (not a literal). A dynamic destination is
3063 /// the higher-signal exfil case; a literal provider host is usually intended
3064 /// auth.
3065 #[serde(default, skip_serializing_if = "Option::is_none")]
3066 pub destination: Option<String>,
3067}
3068
3069/// An agent-actionable candidate record on a [`SecurityFinding`]. fallow fills
3070/// `source_kind`, `sink`, and `boundary`. The exploitability impact is
3071/// deliberately NOT a field: `severity` on the parent finding is only a
3072/// review-priority tier, while deciding exploitability remains the consuming
3073/// agent's job. A perpetually-null `impact` key would only train consumers to
3074/// ignore it. The agent reads this record, then writes its own impact verdict
3075/// downstream.
3076#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3077#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3078pub struct SecurityCandidate {
3079 /// The kind of untrusted input that reaches the sink, as a stable catalogue
3080 /// source id (`"http-request-input"`, `"process-env"`, `"process-argv"`,
3081 /// `"message-event-data"`, `"location-input"`, ...). `None`/absent when no
3082 /// untrusted source was matched (always `None` for `client-server-leak`).
3083 /// This is an open string set, driven by the data-driven source catalogue; a
3084 /// consumer should treat an unknown id as "untrusted source of unknown kind"
3085 /// and never drop the candidate on that basis.
3086 #[serde(default, skip_serializing_if = "Option::is_none")]
3087 pub source_kind: Option<String>,
3088 /// The sink the candidate fires on, self-contained so the record is
3089 /// actionable without reading the parent finding.
3090 pub sink: SecurityCandidateSink,
3091 /// The structural boundary the flow crosses.
3092 pub boundary: SecurityCandidateBoundary,
3093 /// Network-destination context, present only on `secret-to-network` (#890)
3094 /// candidates: the host the secret-bearing call targets, so an agent can
3095 /// triage exfil from intended auth. Absent for every other category.
3096 #[serde(default, skip_serializing_if = "Option::is_none")]
3097 pub network: Option<SecurityNetworkContext>,
3098}
3099
3100/// One endpoint (source or sink node) of a [`SecurityTaintFlow`].
3101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3102#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3103pub struct TaintEndpoint {
3104 /// File of the endpoint. Absolute internally; JSON strips the project root.
3105 #[serde(serialize_with = "serde_path::serialize")]
3106 pub path: PathBuf,
3107 /// 1-based line of the endpoint.
3108 pub line: u32,
3109 /// 0-based byte column of the endpoint.
3110 pub col: u32,
3111}
3112
3113/// Compact taint-flow path shape. The ordered per-hop trace is NOT duplicated
3114/// here: it lives on [`SecurityReachability::untrusted_source_trace`]. This
3115/// carries only the flow's structural summary (intra-module flow plus the
3116/// cross-module hop count) so consumers do not parse two copies of the hops.
3117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3118#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3119pub struct TaintPath {
3120 /// Whether the source and sink sit in the same module (no import hop between
3121 /// them); the source-to-sink association is intra-module.
3122 pub intra_module: bool,
3123 /// Number of value-import hops from the untrusted-source module to the sink
3124 /// module. Zero for an intra-module flow.
3125 pub cross_module_hops: u32,
3126}
3127
3128/// A source-to-sink taint-flow triple, emitted only when an untrusted source is
3129/// import-reachable to the sink (`reachability.reachable_from_untrusted_source`).
3130/// The `{ source, sink, path }` shape matches the model agent SAST tooling
3131/// expects (cf. Semgrep `taint_source` / `taint_sink`, SARIF `threadFlows`).
3132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3133#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3134pub struct SecurityTaintFlow {
3135 /// The untrusted-source endpoint (first hop of the reachability trace).
3136 pub source: TaintEndpoint,
3137 /// The sink endpoint (terminal hop of the reachability trace / the anchor).
3138 pub sink: TaintEndpoint,
3139 /// Compact flow shape: same-module flag plus module hop count. The full
3140 /// ordered path is `reachability.untrusted_source_trace`.
3141 pub path: TaintPath,
3142}
3143
3144/// Runtime coverage state for the function enclosing a security sink.
3145/// This is production-observation evidence, not an exploitability verdict.
3146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3147#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3148#[serde(rename_all = "kebab-case")]
3149pub enum SecurityRuntimeState {
3150 /// The sink sits inside a runtime hot path.
3151 RuntimeHot,
3152 /// The sink sits inside a tracked function with zero production invocations.
3153 RuntimeCold,
3154 /// The sink sits inside a tracked function the runtime layer marked as safe
3155 /// to delete because it was never executed.
3156 NeverExecuted,
3157 /// The sink sits inside a function that executed, but below the low-traffic
3158 /// threshold.
3159 LowTraffic,
3160 /// Runtime coverage could not classify the enclosing function.
3161 CoverageUnavailable,
3162 /// A static enclosing function was found, but the runtime report carried no
3163 /// matching evidence for it.
3164 RuntimeUnknown,
3165}
3166
3167/// Runtime coverage context attached to a security candidate when
3168/// `fallow security --runtime-coverage` is supplied.
3169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3170#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3171pub struct SecurityRuntimeContext {
3172 /// Runtime state for the enclosing function.
3173 pub state: SecurityRuntimeState,
3174 /// Enclosing function name from static extraction.
3175 pub function: String,
3176 /// 1-based line where the enclosing function starts.
3177 pub line: u32,
3178 /// Observed invocation count when the runtime report provides it.
3179 #[serde(default, skip_serializing_if = "Option::is_none")]
3180 pub invocations: Option<u64>,
3181 /// Runtime coverage stable function id, when available.
3182 #[serde(default, skip_serializing_if = "Option::is_none")]
3183 pub stable_id: Option<String>,
3184 /// Short candidate-framed explanation of the runtime evidence.
3185 #[serde(default, skip_serializing_if = "Option::is_none")]
3186 pub evidence: Option<String>,
3187}
3188
3189/// Verification-priority tier for a security candidate. This is ranking, not an
3190/// exploitability verdict.
3191#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3192#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3193#[serde(rename_all = "lowercase")]
3194pub enum SecuritySeverity {
3195 /// Highest-priority candidate based on reachability, boundary, or runtime-hot signals.
3196 High,
3197 /// Candidate has source-reachability evidence but no high-priority signal.
3198 Medium,
3199 /// Candidate has no source-reachability or boundary signal.
3200 Low,
3201}
3202
3203/// Control pattern observed in a file on an attack-surface import trace.
3204/// Its presence does not prove that it executes before the sink or protects
3205/// the same input.
3206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3207#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3208pub struct SecurityDefensiveControl {
3209 /// Control family.
3210 pub kind: SecurityControlKind,
3211 /// File of the control site. Absolute internally; JSON strips the project root.
3212 #[serde(serialize_with = "serde_path::serialize")]
3213 pub path: PathBuf,
3214 /// 1-based line of the control site.
3215 pub line: u32,
3216 /// 0-based byte column of the control site.
3217 pub col: u32,
3218 /// Flattened callee path or a stable synthetic guard name.
3219 pub callee: String,
3220}
3221
3222/// Agent-facing defensive-boundary verification context for one surface path.
3223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3224#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3225pub struct SecurityDefensiveBoundary {
3226 /// Control patterns observed in files on this import trace. These are
3227 /// verification hints, not proof of sink protection or value-level data flow.
3228 pub controls: Vec<SecurityDefensiveControl>,
3229 /// Verification question for the consuming agent. It is a prompt, not a
3230 /// missing-guard verdict.
3231 pub verification_prompt: String,
3232}
3233
3234/// One untrusted entry to reachable sink path for `fallow security --surface`.
3235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3236#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3237pub struct SecurityAttackSurfaceEntry {
3238 /// The untrusted-source endpoint.
3239 pub source: TaintEndpoint,
3240 /// The reachable sink endpoint and catalogue metadata.
3241 pub sink: SecurityCandidateSink,
3242 /// Ordered source to sink path. Same shape as the reachability trace so
3243 /// consumers can reuse existing path handling.
3244 pub path: Vec<TraceHop>,
3245 /// Defensive-boundary context detected on this path.
3246 pub defensive_boundary: SecurityDefensiveBoundary,
3247}
3248
3249/// A local security candidate for downstream agent verification, not a verified
3250/// vulnerability. Emitted only by `fallow security`, never under bare `fallow`
3251/// or the `audit` gate. There is deliberately no `confidence` or
3252/// `signal_strength` field: fallow does not prove exploitability, so the trace
3253/// (its hops and length) is the only honest signal.
3254#[derive(Debug, Clone, Serialize, Deserialize)]
3255#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3256pub struct SecurityFinding {
3257 /// Location id (rule, path, line, column), equal to SARIF `fallowSecurity/v2`; edits move it.
3258 pub finding_id: String,
3259 /// Line-independent id (`sec1:<hash>`, `~k` for repeats); a verdict may use it.
3260 #[serde(default, skip_serializing_if = "Option::is_none")]
3261 pub stable_finding_id: Option<String>,
3262 /// The rule that produced this candidate.
3263 pub kind: SecurityFindingKind,
3264 /// The catalogue category id (e.g. `"dangerous-html"`). `Some` for
3265 /// `TaintedSink`. For `ClientServerLeak` it is `"client-server-leak"` for the
3266 /// secret leak (older releases omit it) or `"server-only-import"` when a
3267 /// `"use client"` cone reaches server-only code.
3268 #[serde(default, skip_serializing_if = "Option::is_none")]
3269 pub category: Option<String>,
3270 /// The CWE number declared by the matched catalogue entry. `None` for
3271 /// `ClientServerLeak`; never fabricated beyond the catalogue's value.
3272 #[serde(default, skip_serializing_if = "Option::is_none")]
3273 pub cwe: Option<u32>,
3274 /// File the finding is anchored on (the client boundary). Absolute
3275 /// internally; JSON strips the project root via `serde_path::serialize`.
3276 #[serde(serialize_with = "serde_path::serialize")]
3277 pub path: PathBuf,
3278 /// 1-based line number of the anchor.
3279 pub line: u32,
3280 /// 0-based byte column offset of the anchor.
3281 pub col: u32,
3282 /// Agent/human-readable evidence (e.g. the named env var the chain reaches).
3283 pub evidence: String,
3284 /// Whether the sink argument was associated with a known untrusted source by
3285 /// the intra-module source-to-sink back-trace (issue #859): a local binding
3286 /// referenced in the argument was sourced from a catalogue source path
3287 /// (`req.query`, `process.argv`, message-event `data`, etc.). `true` ranks
3288 /// the candidate higher and annotates the evidence; `false` does NOT
3289 /// suppress the finding (the association is conservative, never a proof, and
3290 /// fallow prefers false-negatives over false-positives). Always `false` for
3291 /// `ClientServerLeak`. Skipped from JSON when `false` for output stability.
3292 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3293 pub source_backed: bool,
3294 /// Internal cross-pass carrier (NEVER serialized): the (1-based line, 0-based
3295 /// col) of the arg-level source read, resolved by the detector when
3296 /// `source_backed` is true and a concrete read span was captured. The ranking
3297 /// pass uses it to anchor the taint trace's source node at the real read
3298 /// instead of the module import line. `None` for module-level findings and
3299 /// for arg-level findings with no concrete read span (synthetic
3300 /// framework-param / helper-return sources), where the trace falls back to
3301 /// the sink site.
3302 #[serde(skip)]
3303 pub source_read: Option<(u32, u32)>,
3304 /// Verification-priority tier derived from existing reachability, boundary,
3305 /// source-backed, and runtime signals. Candidate-only: this does not prove
3306 /// exploitability and does not change gates.
3307 pub severity: SecuritySeverity,
3308 /// Structural import-hop trace from the client boundary to the secret source.
3309 /// The hop count is the uncalibrated signal; fallow does not prove the path
3310 /// is exploitable.
3311 pub trace: Vec<TraceHop>,
3312 /// Machine-actionable next steps. Always emitted (possibly empty for
3313 /// forward-compat). For security candidates this is a single file-level
3314 /// suppress hint (`auto_fixable: false`); there is no auto-fix because
3315 /// verification is the agent's job, not fallow's.
3316 pub actions: Vec<IssueAction>,
3317 /// Dead-code cross-link when the same sink candidate sits in code fallow also
3318 /// reports as removable. Agents should verify the dead-code finding and delete
3319 /// the code instead of hardening the sink when deletion is safe.
3320 #[serde(default, skip_serializing_if = "Option::is_none")]
3321 pub dead_code: Option<SecurityDeadCodeContext>,
3322 /// Graph-derived reachability ranking signal (issues #860 and #885). `None`
3323 /// until the post-detection ranking pass fills it; additive on the wire
3324 /// (skipped when absent). Drives the order findings are emitted in:
3325 /// runtime-reachable candidates sort first, followed by source-backed and
3326 /// source-reachable candidates, then wider blast radius.
3327 #[serde(default, skip_serializing_if = "Option::is_none")]
3328 pub reachability: Option<SecurityReachability>,
3329 /// Agent-actionable candidate record: the untrusted input kind, the sink, and the boundary
3330 /// the flow crosses. fallow fills these three slots; the exploitability verdict is the
3331 /// agent's job and is not a field here. Always present.
3332 pub candidate: SecurityCandidate,
3333 /// Source-to-sink taint-flow triple, present only when an untrusted source
3334 /// is import-reachable to this sink. Absent (skipped) otherwise.
3335 #[serde(default, skip_serializing_if = "Option::is_none")]
3336 pub taint_flow: Option<SecurityTaintFlow>,
3337 /// Production runtime coverage context for the function enclosing this
3338 /// security sink. Present only when `fallow security --runtime-coverage`
3339 /// runs and the candidate is a `tainted-sink`.
3340 #[serde(default, skip_serializing_if = "Option::is_none")]
3341 pub runtime: Option<SecurityRuntimeContext>,
3342 /// Internal projection used by `fallow security --surface`. The CLI strips this from
3343 /// per-finding JSON and promotes it to the top-level `attack_surface` field only when requested.
3344 #[serde(default, skip_serializing_if = "Option::is_none")]
3345 pub attack_surface: Option<SecurityAttackSurfaceEntry>,
3346 /// Internal input of `stable_finding_id`. Never serialized; `None` after a JSON round trip.
3347 #[serde(skip)]
3348 pub stable_id_input: Option<crate::security_stable_id::SecurityStableIdInput>,
3349}
3350
3351/// A package manager catalog entry that no workspace package references via
3352/// the `catalog:` protocol.
3353///
3354/// The default catalog uses `catalog_name: "default"`. Named catalogs
3355/// (`catalogs.<name>`) use their declared name. The source file is the
3356/// `pnpm-workspace.yaml` of the root or of a nested pnpm project, or the
3357/// root `package.json` for Bun catalogs.
3358#[derive(Debug, Clone, Serialize, Deserialize)]
3359#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3360pub struct UnusedCatalogEntry {
3361 /// Package name declared in the catalog (e.g. `"react"`, `"@scope/lib"`).
3362 pub entry_name: String,
3363 /// Catalog group: `"default"` for the default catalog map, or the named
3364 /// catalog key for entries declared under `catalogs.<name>`.
3365 pub catalog_name: String,
3366 /// Path to the catalog source file, relative to the analyzed root.
3367 #[serde(serialize_with = "serde_path::serialize")]
3368 pub path: PathBuf,
3369 /// 1-based line number of the catalog entry within the source file.
3370 pub line: u32,
3371 /// Workspace `package.json` files that declare the same package with a
3372 /// hardcoded version range instead of `catalog:`. Empty when no consumer
3373 /// uses a hardcoded version. Sorted lexicographically for deterministic
3374 /// output.
3375 #[serde(
3376 default,
3377 serialize_with = "serde_path::serialize_vec",
3378 skip_serializing_if = "Vec::is_empty"
3379 )]
3380 pub hardcoded_consumers: Vec<PathBuf>,
3381}
3382
3383/// A named `catalogs.<name>` group with no package entries.
3384#[derive(Debug, Clone, Serialize, Deserialize)]
3385#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3386pub struct EmptyCatalogGroup {
3387 /// Catalog group name declared under the `catalogs` map.
3388 pub catalog_name: String,
3389 /// Path to the catalog source file, relative to the analyzed root.
3390 #[serde(serialize_with = "serde_path::serialize")]
3391 pub path: PathBuf,
3392 /// 1-based line number of the empty group header within the source file.
3393 pub line: u32,
3394}
3395
3396/// A workspace package.json reference (`catalog:` or `catalog:<name>`) that points
3397/// at a catalog which does not declare the consumed package.
3398///
3399/// Package manager installs error when this happens. fallow surfaces it
3400/// statically so the failure is caught at `fallow dead-code` time, before any
3401/// install.
3402///
3403/// The default catalog (bare `catalog:`) uses `catalog_name: "default"`.
3404/// Named catalogs (`catalog:react17`) use the declared catalog name.
3405#[derive(Debug, Clone, Serialize, Deserialize)]
3406#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3407pub struct UnresolvedCatalogReference {
3408 /// Package name being referenced via the catalog protocol (e.g. `"react"`).
3409 pub entry_name: String,
3410 /// Catalog group the reference points at: `"default"` for bare `catalog:` references,
3411 /// or the named catalog key for `catalog:<name>` references.
3412 pub catalog_name: String,
3413 /// Absolute path to the consumer `package.json`. Matches the storage
3414 /// convention used by every path-anchored finding type (`UnusedFile`,
3415 /// `UnresolvedImport`, `UnusedExport`, etc.) so the shared filtering
3416 /// pipelines (`filter_results_by_changed_files`, per-file overrides,
3417 /// audit attribution) work without a separate root-join pass. JSON
3418 /// output strips the project-root prefix via `serde_path::serialize`.
3419 #[serde(serialize_with = "serde_path::serialize")]
3420 pub path: PathBuf,
3421 /// 1-based line number of the dependency entry in the consumer `package.json`.
3422 pub line: u32,
3423 /// Other catalogs in the same catalog source that DO declare this package.
3424 /// Empty when no catalog has the package. Sorted lexicographically. Lets
3425 /// agents and humans decide whether to switch the reference to a different
3426 /// catalog or to add the entry to the named catalog.
3427 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3428 pub available_in_catalogs: Vec<String>,
3429}
3430
3431/// Where an override entry was declared. Serialized as the filename label
3432/// (`"pnpm-workspace.yaml"` or `"package.json"`) so the value in JSON output
3433/// matches the value users write in `ignoreDependencyOverrides[].source`.
3434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3435#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3436pub enum DependencyOverrideSource {
3437 /// Top-level `overrides:` key in `pnpm-workspace.yaml`.
3438 #[serde(rename = "pnpm-workspace.yaml")]
3439 PnpmWorkspaceYaml,
3440 /// `pnpm.overrides`, the top-level npm `overrides` object, or (in a bun
3441 /// repository) the Yarn-style top-level `resolutions` object in a root
3442 /// `package.json`.
3443 #[serde(rename = "package.json")]
3444 PnpmPackageJson,
3445}
3446
3447impl DependencyOverrideSource {
3448 /// Stable string label matching the serde rename. Used in baseline keys,
3449 /// audit keys, jq comparisons, and `ignoreDependencyOverrides[].source`.
3450 #[must_use]
3451 pub const fn as_label(&self) -> &'static str {
3452 match self {
3453 Self::PnpmWorkspaceYaml => "pnpm-workspace.yaml",
3454 Self::PnpmPackageJson => "package.json",
3455 }
3456 }
3457}
3458
3459impl std::fmt::Display for DependencyOverrideSource {
3460 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3461 f.write_str(self.as_label())
3462 }
3463}
3464
3465/// An entry in pnpm's `overrides:` map (or the legacy `pnpm.overrides` in
3466/// `package.json`), in npm's top-level `overrides` object in `package.json`,
3467/// or (in a bun repository) in the Yarn-style top-level `resolutions` object
3468/// in `package.json`, whose target package is not declared in any workspace
3469/// `package.json` and is not present in `pnpm-lock.yaml`,
3470/// `package-lock.json`, or `bun.lock`. Projects without a readable lockfile
3471/// fall back to package manifest checks; the `hint` field flags that
3472/// conservative mode.
3473#[derive(Debug, Clone, Serialize, Deserialize)]
3474#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3475pub struct UnusedDependencyOverride {
3476 /// The full original override key as written in the source (e.g.
3477 /// `"react>react-dom"`, `"@types/react@<18"`). Preserved for round-trip
3478 /// reporting so agents see the unmodified spelling.
3479 pub raw_key: String,
3480 /// The target package the override rewrites (e.g. `"react-dom"` for
3481 /// `"react>react-dom"`, `"@types/react"` for `"@types/react@<18"`).
3482 pub target_package: String,
3483 /// Optional parent package (left side of `>`). `None` for bare-target keys.
3484 #[serde(default, skip_serializing_if = "Option::is_none")]
3485 pub parent_package: Option<String>,
3486 /// Optional version selector on the target (e.g. `Some("<18")` for
3487 /// `"@types/react@<18"`).
3488 #[serde(default, skip_serializing_if = "Option::is_none")]
3489 pub version_constraint: Option<String>,
3490 /// The right-hand side of the entry: the version the package manager should force.
3491 pub version_range: String,
3492 /// File the override was declared in. Matches the value users write in
3493 /// `ignoreDependencyOverrides[].source`.
3494 pub source: DependencyOverrideSource,
3495 /// Path to the source file. `pnpm-workspace.yaml` or a `package.json`,
3496 /// stored as an absolute filesystem path so `--changed-since` and
3497 /// per-file `overrides.rules` can compare directly against the analyzer's
3498 /// changed-set / per-path rule lookups. JSON serialization strips the
3499 /// project root via `serde_path::serialize`, matching the
3500 /// `UnresolvedCatalogReference` convention.
3501 #[serde(serialize_with = "serde_path::serialize")]
3502 pub path: PathBuf,
3503 /// 1-based line number of the entry within the source file.
3504 pub line: u32,
3505 /// Soft hint reminding consumers to verify the override before removal.
3506 /// Emitted on every unused-override finding (both bare-target and
3507 /// parent-chain shapes) because projects without a readable lockfile still
3508 /// use the conservative package-manifest fallback.
3509 #[serde(default, skip_serializing_if = "Option::is_none")]
3510 pub hint: Option<String>,
3511}
3512
3513/// Why a dependency-override entry is misconfigured. The active package
3514/// manager may fail at install time or silently no-op on these entries;
3515/// surfacing them statically catches the issue first.
3516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3517#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3518#[serde(rename_all = "kebab-case")]
3519pub enum DependencyOverrideMisconfigReason {
3520 /// The override key could not be parsed into a recognised source shape
3521 /// (e.g. dangling `>`, missing target, garbage characters).
3522 UnparsableKey,
3523 /// The override value is missing, empty, or contains line breaks.
3524 EmptyValue,
3525}
3526
3527impl DependencyOverrideMisconfigReason {
3528 /// Human-readable summary of the reason.
3529 #[must_use]
3530 pub const fn describe(self) -> &'static str {
3531 match self {
3532 Self::UnparsableKey => "override key cannot be parsed",
3533 Self::EmptyValue => "override value is missing or empty",
3534 }
3535 }
3536}
3537
3538/// An override entry whose key or value is malformed. Default severity is
3539/// `error` because the active package manager may refuse to install or silently
3540/// produce a no-op override when it encounters these shapes.
3541#[derive(Debug, Clone, Serialize, Deserialize)]
3542#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3543pub struct MisconfiguredDependencyOverride {
3544 /// The full original override key as written in the source.
3545 pub raw_key: String,
3546 /// Parsed target package name when the key was syntactically valid (the
3547 /// `EmptyValue` reason path). `None` for `UnparsableKey` findings whose
3548 /// key could not be parsed at all. Used by JSON `add-to-config` actions to
3549 /// emit a paste-ready `ignoreDependencyOverrides` value that matches the
3550 /// suppression matcher (which also keys on `target_package`); avoids the
3551 /// pitfall where `raw_key` like `"react@<18"` would not match the rule
3552 /// that targets package `"react"`.
3553 #[serde(default, skip_serializing_if = "Option::is_none")]
3554 pub target_package: Option<String>,
3555 /// The right-hand side of the entry, exactly as written. Empty when the
3556 /// value was missing.
3557 pub raw_value: String,
3558 /// Classifier for the misconfiguration. 'unparsable-key' = the key is not a
3559 /// valid source shape; 'empty-value' = the value is missing, empty, or
3560 /// contains line breaks.
3561 pub reason: DependencyOverrideMisconfigReason,
3562 /// Where the override entry was declared.
3563 pub source: DependencyOverrideSource,
3564 /// Path to the source file. Stored as an absolute filesystem path so
3565 /// `--changed-since` and per-file `overrides.rules` can compare directly.
3566 /// JSON serialization strips the project root via `serde_path::serialize`.
3567 #[serde(serialize_with = "serde_path::serialize")]
3568 pub path: PathBuf,
3569 /// 1-based line number of the entry within the source file.
3570 pub line: u32,
3571}
3572
3573/// A production dependency that is only imported by test files.
3574/// Since it is never used in production code, it could be moved to devDependencies.
3575#[derive(Debug, Clone, Serialize, Deserialize)]
3576#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3577pub struct TestOnlyDependency {
3578 /// Production dependency that is only imported by test files, consider
3579 /// moving to devDependencies.
3580 pub package_name: String,
3581 /// Path to the package.json where the dependency is listed.
3582 #[serde(serialize_with = "serde_path::serialize")]
3583 pub path: PathBuf,
3584 /// 1-based line number of the dependency entry in package.json.
3585 pub line: u32,
3586}
3587
3588/// A `devDependencies` package imported by production (non-test, non-config)
3589/// source code via a runtime/value import. Because a production-only install
3590/// (`pnpm install --prod`) omits devDependencies, it would break at runtime, so
3591/// the package should be promoted to `dependencies`. The promote-side mirror of
3592/// [`TestOnlyDependency`] / [`TypeOnlyDependency`].
3593#[derive(Debug, Clone, Serialize, Deserialize)]
3594#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3595pub struct DevDependencyInProduction {
3596 /// devDependency imported at runtime from production code, consider moving
3597 /// to dependencies.
3598 pub package_name: String,
3599 /// Path to the package.json where the dependency is listed.
3600 #[serde(serialize_with = "serde_path::serialize")]
3601 pub path: PathBuf,
3602 /// 1-based line number of the dependency entry in package.json.
3603 pub line: u32,
3604}
3605
3606/// One import hop in a circular dependency: the file containing the import
3607/// and where that import statement sits.
3608///
3609/// `edges[i]` is the import in `path` (the hop source, equal to the cycle's
3610/// `files[i]`) that points to the next file in the cycle
3611/// (`files[(i + 1) % files.len()]`); the target is not repeated here to keep
3612/// the wire compact. Enables a per-file diagnostic squiggly anchored under
3613/// the offending import rather than a single squiggly on the first file.
3614///
3615/// `col` is a 0-based byte column, matching the cycle's top-level `col`;
3616/// converting it to a UTF-16 code-unit column for LSP clients is a tracked
3617/// follow-up shared with the existing field.
3618#[derive(Debug, Clone, Serialize, Deserialize)]
3619#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3620pub struct CircularDependencyEdge {
3621 /// The file containing the import (the hop source; equal to `files[i]`).
3622 #[serde(serialize_with = "serde_path::serialize")]
3623 pub path: PathBuf,
3624 /// 1-based line number of the import statement pointing to the next file.
3625 pub line: u32,
3626 /// 0-based byte column offset of the import statement.
3627 pub col: u32,
3628}
3629
3630/// A circular dependency chain detected in the module graph.
3631///
3632/// The `line` and `col` fields carry `#[serde(default)]` so callers reading
3633/// historical baseline JSON without these fields can still deserialize the
3634/// struct, but the JSON output layer always emits them (u32 always
3635/// serializes, never via `skip_serializing_if`). The schemars derive sees
3636/// the serde defaults and marks both fields optional in the generated
3637/// schema; the explicit `extend("required" = ...)` override here keeps the
3638/// schema's `required` array honest about what the JSON output actually
3639/// contains.
3640///
3641/// `edges` is deliberately kept OUT of the `required` extend: it is
3642/// `#[serde(default)]` (so historical baseline JSON without it still
3643/// deserializes) and the output layer always emits it, but listing it in
3644/// `required` would make pre-upgrade JSON fail validation against the new
3645/// schema. It is a normal additive field: always present in current output,
3646/// optional for backward compatibility.
3647#[derive(Debug, Clone, Serialize, Deserialize)]
3648#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3649#[cfg_attr(feature = "schema", schemars(extend("required" = ["files", "length", "line", "col"])))]
3650pub struct CircularDependency {
3651 /// Files forming the cycle, in import order.
3652 #[serde(serialize_with = "serde_path::serialize_vec")]
3653 pub files: Vec<PathBuf>,
3654 /// Number of files in the cycle.
3655 pub length: usize,
3656 /// 1-based line number of the import that starts the cycle (in the first file).
3657 #[serde(default)]
3658 pub line: u32,
3659 /// 0-based byte column offset of the import that starts the cycle.
3660 #[serde(default)]
3661 pub col: u32,
3662 /// Per-file import anchors, one entry per hop in cycle order: `edges[i]`
3663 /// is the import in `files[i]` pointing to `files[(i + 1) % len]`. Always
3664 /// the same length as `files`. Drives the per-file LSP diagnostic
3665 /// squiggly. `#[serde(default)]` so pre-`edges` baselines deserialize;
3666 /// always emitted on output but intentionally not in the schema's
3667 /// `required` set (see the struct doc).
3668 #[serde(default)]
3669 pub edges: Vec<CircularDependencyEdge>,
3670 /// Whether this cycle crosses workspace package boundaries.
3671 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3672 pub is_cross_package: bool,
3673}
3674
3675/// A cycle or self-loop in the re-export edge subgraph, found by a Tarjan SCC
3676/// pass in `crates/graph/src/graph/re_exports/`. Chain propagation through the
3677/// loop is a no-op, so a symbol re-exported through it does not resolve.
3678#[derive(Debug, Clone, Serialize, Deserialize)]
3679#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3680pub struct ReExportCycle {
3681 /// Member files, sorted lexicographically. A self-loop has one entry.
3682 #[serde(serialize_with = "serde_path::serialize_vec")]
3683 pub files: Vec<PathBuf>,
3684 /// Which structural shape this finding describes.
3685 pub kind: ReExportCycleKind,
3686 /// 1-based line of the re-export in `files[0]` that closes the cycle, or `0` if unknown.
3687 #[serde(default)]
3688 pub line: u32,
3689 /// 0-based byte column of that re-export.
3690 #[serde(default)]
3691 pub col: u32,
3692}
3693
3694/// Discriminator for [`ReExportCycle`]: which structural shape was detected.
3695#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3696#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3697#[serde(rename_all = "kebab-case")]
3698pub enum ReExportCycleKind {
3699 /// Two or more barrel files re-export from each other in a loop
3700 /// (SCC of size >= 2).
3701 MultiNode,
3702 /// A single barrel file re-exports from itself.
3703 SelfLoop,
3704}
3705
3706/// One package hop in a [`PackageCycle`]: `from_package` imports
3707/// `to_package`, and `path` holds one example import for that hop.
3708///
3709/// The example import is the first runtime import by `(path, line)`. When
3710/// every import on the hop is type-only, it is the first type-only import.
3711#[derive(Debug, Clone, Serialize, Deserialize)]
3712#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3713pub struct PackageCycleEdge {
3714 /// Label of the importing workspace package, as in
3715 /// [`PackageCycle::packages`].
3716 pub from_package: String,
3717 /// Label of the imported workspace package, as in
3718 /// [`PackageCycle::packages`].
3719 pub to_package: String,
3720 /// File in `from_package` that holds the example import.
3721 #[serde(serialize_with = "serde_path::serialize")]
3722 pub path: PathBuf,
3723 /// File in `to_package` that the example import resolves to.
3724 #[serde(serialize_with = "serde_path::serialize")]
3725 pub target_path: PathBuf,
3726 /// 1-based line number of the example import.
3727 pub line: u32,
3728 /// 0-based byte column offset of the example import.
3729 pub col: u32,
3730 /// True when every import from `from_package` to `to_package` is
3731 /// type-only. A type-only hop has no runtime effect, but it can still
3732 /// force a build order (for example with declaration builds).
3733 pub type_only: bool,
3734}
3735
3736/// A dependency cycle between workspace packages.
3737///
3738/// Each workspace package is a node. A resolved import from a file in one
3739/// package to a file in another package is an edge. Declared `package.json`
3740/// dependencies are not edges, and imports from test, spec, story, fixture
3741/// and tooling config files are not edges. A package cycle can exist when no
3742/// file-level cycle exists.
3743#[derive(Debug, Clone, Serialize, Deserialize)]
3744#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3745pub struct PackageCycle {
3746 /// Workspace package labels in cycle order. The first entry is the
3747 /// lexicographically smallest label; the last entry imports the first.
3748 /// A label is the package name. When two or more workspace packages
3749 /// share a name, the label is `name (root)` with the project-relative
3750 /// package root, so that each label names one package.
3751 pub packages: Vec<String>,
3752 /// Package root directories in cycle order: `package_roots[i]` is the
3753 /// root of `packages[i]`.
3754 #[serde(serialize_with = "serde_path::serialize_vec")]
3755 pub package_roots: Vec<PathBuf>,
3756 /// Number of packages in the cycle.
3757 pub length: usize,
3758 /// One example import per hop, in cycle order: `edges[i]` goes from
3759 /// `packages[i]` to `packages[(i + 1) % length]`.
3760 pub edges: Vec<PackageCycleEdge>,
3761 /// True when the group of packages that holds this cycle has more
3762 /// cycles than fallow lists. The listing stops at 20 cycles per group,
3763 /// or earlier on a very dense package graph. Break a listed cycle and
3764 /// run again to see the rest.
3765 pub group_truncated: bool,
3766}
3767
3768impl PackageCycle {
3769 /// The note that every output format shows for a cycle with
3770 /// [`PackageCycle::group_truncated`] set.
3771 pub const GROUP_TRUNCATED_NOTE: &'static str = "this package group has more cycles than listed";
3772
3773 /// The package labels in cycle order, with the first label repeated at
3774 /// the end, joined with `separator`.
3775 #[must_use]
3776 pub fn chain(&self, separator: &str) -> String {
3777 let mut chain: Vec<&str> = self.packages.iter().map(String::as_str).collect();
3778 if let Some(first) = chain.first().copied() {
3779 chain.push(first);
3780 }
3781 chain.join(separator)
3782 }
3783}
3784
3785/// A source file that does not match any configured architecture boundary zone.
3786#[derive(Debug, Clone, Serialize, Deserialize)]
3787#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3788pub struct BoundaryCoverageViolation {
3789 /// The unmatched source file.
3790 #[serde(serialize_with = "serde_path::serialize")]
3791 pub path: PathBuf,
3792 /// 1-based line number used for diagnostics.
3793 pub line: u32,
3794 /// 0-based byte column offset used for diagnostics.
3795 pub col: u32,
3796}
3797
3798/// A call from a zoned file to a callee forbidden for that zone via
3799/// `boundaries.calls.forbidden`. One finding is reported per call or `new`
3800/// site.
3801#[derive(Debug, Clone, Serialize, Deserialize)]
3802#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3803pub struct BoundaryCallViolation {
3804 /// The zoned source file making the forbidden call.
3805 #[serde(serialize_with = "serde_path::serialize")]
3806 pub path: PathBuf,
3807 /// 1-based line number of the call site.
3808 pub line: u32,
3809 /// 0-based byte column offset of the call site.
3810 pub col: u32,
3811 /// The zone the calling file is classified into.
3812 pub zone: String,
3813 /// The callee path as written (e.g. `cp.exec`), with the prefix `new ` for a `new` expression.
3814 pub callee: String,
3815 /// The configured pattern that matched (e.g. `child_process.*`), so
3816 /// consumers can see both the written path and the rule that fired.
3817 pub pattern: String,
3818}
3819
3820/// Which rule-pack rule kind produced a [`PolicyViolation`].
3821#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3822#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3823#[serde(rename_all = "kebab-case")]
3824pub enum PolicyRuleKind {
3825 /// A call or `new` expression matched a `banned-call` rule's callee patterns.
3826 BannedCall,
3827 /// An import or re-export specifier matched a `banned-import` rule.
3828 BannedImport,
3829 /// A call site matched a catalogue-derived `banned-effect` rule.
3830 BannedEffect,
3831 /// An exported name matched a `banned-export` rule.
3832 BannedExport,
3833 /// A resolved gdp-ts proof factory call occurred outside allowed modules.
3834 GdpProofProducer,
3835}
3836
3837/// Effective severity of a single [`PolicyViolation`]. Per-rule `severity`
3838/// overrides the `rules."policy-violation"` master; `off` rules emit nothing,
3839/// so only `error` and `warn` appear on the wire. The exit-code gate inspects
3840/// this per-finding value, not the master severity.
3841#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3842#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3843#[serde(rename_all = "lowercase")]
3844pub enum PolicyViolationSeverity {
3845 /// Sets a non-zero exit code.
3846 Error,
3847 /// Reported without an effect on the exit code. The dead-code count gate
3848 /// of the GitHub Action counts it unless `fail-on-issues` is `false`.
3849 Warn,
3850}
3851
3852/// A banned call, banned import, banned effect, or banned export matched by a
3853/// declarative rule pack (`rulePacks` config). Banned-call and banned-effect
3854/// findings report one entry per call site (`new` sites count for banned-call
3855/// only), matching `boundary_call_violations`; banned-import findings anchor
3856/// at each matching import or re-export declaration; banned-export findings
3857/// anchor at matching export declarations.
3858#[derive(Debug, Clone, Serialize, Deserialize)]
3859#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3860pub struct PolicyViolation {
3861 /// The source file containing the banned call, import, or effectful usage.
3862 #[serde(serialize_with = "serde_path::serialize")]
3863 pub path: PathBuf,
3864 /// 1-based line number of the call site or import declaration.
3865 pub line: u32,
3866 /// 0-based byte column offset of the call site or import declaration.
3867 pub col: u32,
3868 /// Name of the rule pack that declared the matching rule.
3869 pub pack: String,
3870 /// Id of the matching rule inside the pack. `pack` plus `rule_id` is the
3871 /// finding's policy identity.
3872 pub rule_id: String,
3873 /// Which rule kind matched.
3874 pub kind: PolicyRuleKind,
3875 /// What matched: the written callee path for `banned-call` (e.g. `cp.exec`, or `new Date` for a `new` expression), `<effect>: <callee>` for `banned-effect`,
3876 /// or the exported name for `banned-export`. For `gdp-proof-producer`, the canonical factory with its JSON-quoted literal label or `...` for a dynamic label.
3877 /// For `banned-import`: the raw import specifier (e.g. `moment/locale/nl`), or `<specifier>: <binding>` when the rule sets `allowNames`.
3878 /// `<binding>` is the source-side imported name, `default`, `*` for a namespace or star form,
3879 /// or `side-effect`.
3880 pub matched: String,
3881 /// Effective severity for this finding (per-rule `severity`, else the
3882 /// `rules."policy-violation"` master).
3883 pub severity: PolicyViolationSeverity,
3884 /// The rule's author-provided message, when set.
3885 #[serde(default, skip_serializing_if = "Option::is_none")]
3886 pub message: Option<String>,
3887}
3888
3889/// The origin of a stale suppression: inline comment or JSDoc tag.
3890#[derive(Debug, Clone, Serialize, Deserialize)]
3891#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3892#[serde(rename_all = "snake_case", tag = "type")]
3893pub enum SuppressionOrigin {
3894 /// A `// fallow-ignore-next-line` or `// fallow-ignore-file` comment.
3895 Comment {
3896 /// The issue kind token from the comment (e.g., "unused-exports"), or None for blanket.
3897 #[serde(default, skip_serializing_if = "Option::is_none")]
3898 issue_kind: Option<String>,
3899 /// Human-authored reason after `--`, when present.
3900 #[serde(default, skip_serializing_if = "Option::is_none")]
3901 reason: Option<String>,
3902 /// Whether this was a file-level suppression.
3903 is_file_level: bool,
3904 /// Whether this was a `fallow-ignore-start` range marker (then
3905 /// `is_file_level` is `false`). Omitted from the wire when `false`.
3906 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3907 is_range: bool,
3908 /// Whether `issue_kind` parses to a known `IssueKind`. False when the
3909 /// token is a typo or refers to a kind that was renamed or removed in
3910 /// a newer fallow release. JSON consumers (CI annotations, MCP agents,
3911 /// VS Code) branch on this to choose the right next-step text.
3912 /// Omitted from the wire when `true` so producers that have not yet
3913 /// adopted the field stay byte-compatible. See issue #449.
3914 #[serde(default = "default_true", skip_serializing_if = "is_true")]
3915 kind_known: bool,
3916 },
3917 /// An `@expected-unused` JSDoc tag on an export.
3918 JsdocTag {
3919 /// The name of the export that was tagged.
3920 export_name: String,
3921 /// Human-authored reason after `--`, when present.
3922 #[serde(default, skip_serializing_if = "Option::is_none")]
3923 reason: Option<String>,
3924 },
3925}
3926
3927#[expect(
3928 clippy::trivially_copy_pass_by_ref,
3929 reason = "serde skip_serializing_if takes a reference by contract"
3930)]
3931const fn is_true(b: &bool) -> bool {
3932 *b
3933}
3934
3935/// Default for `SuppressionOrigin::Comment.kind_known` when the field is
3936/// absent from a deserialized payload, paired with `skip_serializing_if = is_true`
3937/// so schemars marks the field non-required in the generated JSON Schema AND
3938/// the absent case round-trips to the recognized-kind interpretation.
3939/// Referenced by the always-emitted `#[serde(default = "default_true")]`
3940/// attribute. Serde uses it when saved reports deserialize the output back
3941/// into the typed findings, while schemars uses it to keep `kind_known`
3942/// optional in the generated schema.
3943const fn default_true() -> bool {
3944 true
3945}
3946
3947/// A suppression comment or JSDoc tag that no longer matches any issue.
3948#[derive(Debug, Clone, Serialize, Deserialize)]
3949#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3950pub struct StaleSuppression {
3951 /// File containing the stale suppression.
3952 #[serde(serialize_with = "serde_path::serialize")]
3953 pub path: PathBuf,
3954 /// 1-based line number of the suppression comment or tag.
3955 pub line: u32,
3956 /// 0-based byte column offset.
3957 pub col: u32,
3958 /// The origin and details of the stale suppression.
3959 pub origin: SuppressionOrigin,
3960 /// True when `rules.require-suppression-reason` reported a suppression
3961 /// comment or tag that has no reason.
3962 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3963 pub missing_reason: bool,
3964 /// Stable id of this finding: `dc1:<rule>:<16 hex digits>`, with a
3965 /// `~<k>` suffix when several findings of one type share an identity.
3966 /// Line and column are not inputs, so the id survives line shifts,
3967 /// reformats and reorders. A rename of the file or the symbol gives a
3968 /// new id. Absent in output from older versions.
3969 #[serde(default, skip_serializing_if = "Option::is_none")]
3970 pub finding_id: Option<String>,
3971 /// Suggested next steps. Always emitted.
3972 pub actions: Vec<IssueAction>,
3973 /// Gate severity of this finding after `rules` and `overrides[].rules`
3974 /// resolve for its path. CI formats read it for the annotation, SARIF
3975 /// and CodeClimate level. Absent in output from older versions. Not
3976 /// part of the finding identity, baseline keys or fingerprints.
3977 #[serde(
3978 default,
3979 skip_serializing_if = "Option::is_none",
3980 deserialize_with = "crate::output_dead_code::deserialize_effective_severity"
3981 )]
3982 pub effective_severity: Option<crate::output_dead_code::EffectiveSeverity>,
3983}
3984
3985impl StaleSuppression {
3986 /// Build the typed action list for this suppression finding.
3987 #[must_use]
3988 pub fn actions_for(missing_reason: bool) -> Vec<IssueAction> {
3989 let (kind, description) = if missing_reason {
3990 (
3991 FixActionType::AddSuppressionReason,
3992 "Add a human-authored reason after `--` on the suppression",
3993 )
3994 } else {
3995 (
3996 FixActionType::RemoveStaleSuppression,
3997 "Remove or update the stale suppression",
3998 )
3999 };
4000 let mut actions = vec![IssueAction::Fix(FixAction {
4001 kind,
4002 auto_fixable: false,
4003 description: description.to_string(),
4004 note: None,
4005 available_in_catalogs: None,
4006 suggested_target: None,
4007 })];
4008 if !missing_reason {
4009 actions.push(IssueAction::SuppressLine(SuppressLineAction {
4010 kind: SuppressLineKind::SuppressLine,
4011 auto_fixable: false,
4012 description:
4013 "Suppress this stale suppression finding with a comment above the suppression"
4014 .to_string(),
4015 comment: "// fallow-ignore-next-line stale-suppression".to_string(),
4016 scope: Some(SuppressLineScope::PerLocation),
4017 }));
4018 }
4019 actions
4020 }
4021
4022 /// Produce a human-readable description of this stale suppression.
4023 #[must_use]
4024 pub fn description(&self) -> String {
4025 match &self.origin {
4026 SuppressionOrigin::Comment {
4027 issue_kind,
4028 reason,
4029 is_file_level,
4030 is_range,
4031 ..
4032 } => {
4033 let directive = if *is_range {
4034 "fallow-ignore-start"
4035 } else if *is_file_level {
4036 "fallow-ignore-file"
4037 } else {
4038 "fallow-ignore-next-line"
4039 };
4040 match issue_kind {
4041 Some(kind) => match reason {
4042 Some(reason) => format!("// {directive} {kind} -- {reason}"),
4043 None => format!("// {directive} {kind}"),
4044 },
4045 None => match reason {
4046 Some(reason) => format!("// {directive} -- {reason}"),
4047 None => format!("// {directive}"),
4048 },
4049 }
4050 }
4051 SuppressionOrigin::JsdocTag {
4052 export_name,
4053 reason,
4054 } => match reason {
4055 Some(reason) => format!("@expected-unused on {export_name} -- {reason}"),
4056 None => format!("@expected-unused on {export_name}"),
4057 },
4058 }
4059 }
4060
4061 /// Produce an explanation of why this suppression is stale.
4062 ///
4063 /// For comment suppressions where `kind_known == false`, surfaces the
4064 /// unknown token plus a Levenshtein "did you mean?" hint when one is
4065 /// within edit distance 2. Other tokens on the same comment line still
4066 /// apply normally (see issue #449).
4067 #[must_use]
4068 pub fn explanation(&self) -> String {
4069 match &self.origin {
4070 SuppressionOrigin::Comment {
4071 issue_kind,
4072 is_file_level,
4073 kind_known,
4074 ..
4075 } => {
4076 if self.missing_reason {
4077 return "suppression is missing a reason".to_string();
4078 }
4079 let scope = if *is_file_level {
4080 "in this file"
4081 } else {
4082 "on the next line"
4083 };
4084 match issue_kind {
4085 Some(kind) if !*kind_known => match closest_known_kind_name(kind) {
4086 Some(suggestion) => format!(
4087 "'{kind}' is not a recognized fallow issue kind. Did you mean '{suggestion}'? Other tokens on this line still apply."
4088 ),
4089 None => format!(
4090 "'{kind}' is not a recognized fallow issue kind. Other tokens on this line still apply."
4091 ),
4092 },
4093 Some(kind) => format!("no {kind} issue found {scope}"),
4094 None => format!("no issues found {scope}"),
4095 }
4096 }
4097 SuppressionOrigin::JsdocTag { export_name, .. } => {
4098 if self.missing_reason {
4099 return "suppression is missing a reason".to_string();
4100 }
4101 format!("{export_name} is now used")
4102 }
4103 }
4104 }
4105
4106 /// Per-format display message combining `description()` and `explanation()`
4107 /// for the unknown-kind case so SARIF, CodeClimate, and compact consumers
4108 /// surface the typo-fix copy and Levenshtein hint without needing to
4109 /// branch on `origin.kind_known` themselves. Stale-but-known and JSDoc
4110 /// origins keep the bare `description()` so existing wire bytes stay
4111 /// unchanged. See issue #449.
4112 #[must_use]
4113 pub fn display_message(&self) -> String {
4114 match &self.origin {
4115 SuppressionOrigin::Comment {
4116 kind_known: false, ..
4117 } => format!("{} ({})", self.description(), self.explanation()),
4118 SuppressionOrigin::Comment { .. } | SuppressionOrigin::JsdocTag { .. }
4119 if self.missing_reason =>
4120 {
4121 format!("{} ({})", self.description(), self.explanation())
4122 }
4123 SuppressionOrigin::Comment { .. } | SuppressionOrigin::JsdocTag { .. } => {
4124 self.description()
4125 }
4126 }
4127 }
4128}
4129
4130/// The detection method used to identify a feature flag.
4131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4132#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4133#[serde(rename_all = "snake_case")]
4134pub enum FlagKind {
4135 /// Environment variable check (e.g., `process.env.FEATURE_X`).
4136 EnvironmentVariable,
4137 /// Feature flag SDK call (e.g., `useFlag('name')`, `variation('name', false)`).
4138 SdkCall,
4139 /// Config object property access (e.g., `config.features.newCheckout`).
4140 ConfigObject,
4141}
4142
4143/// Detection confidence for a feature flag finding.
4144#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
4145#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4146#[serde(rename_all = "snake_case")]
4147pub enum FlagConfidence {
4148 /// Low confidence: heuristic match (config object patterns).
4149 Low,
4150 /// Medium confidence: a generic SDK name, such as `isEnabled`, in a file
4151 /// that imports no flag SDK or flag module.
4152 Medium,
4153 /// High confidence: unambiguous pattern (env vars, specific SDK calls,
4154 /// generic SDK calls in a file that imports a flag SDK or flag module).
4155 High,
4156}
4157
4158/// A detected feature flag use site.
4159#[derive(Debug, Clone, Serialize, Deserialize)]
4160#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4161pub struct FeatureFlag {
4162 /// File containing the feature flag usage.
4163 #[serde(serialize_with = "serde_path::serialize")]
4164 pub path: PathBuf,
4165 /// Name or identifier of the flag (e.g., `ENABLE_NEW_CHECKOUT`, `new-checkout`).
4166 pub flag_name: String,
4167 /// How the flag was detected.
4168 pub kind: FlagKind,
4169 /// Detection confidence level.
4170 pub confidence: FlagConfidence,
4171 /// 1-based line number.
4172 pub line: u32,
4173 /// 0-based byte column offset.
4174 pub col: u32,
4175 /// Start byte offset of the guarded code block (if-branch span), if detected.
4176 #[serde(skip)]
4177 pub guard_span_start: Option<u32>,
4178 /// End byte offset of the guarded code block (if-branch span), if detected.
4179 #[serde(skip)]
4180 pub guard_span_end: Option<u32>,
4181 /// SDK or provider name (e.g., "LaunchDarkly", "Statsig"), if detected from SDK call.
4182 #[serde(default, skip_serializing_if = "Option::is_none")]
4183 pub sdk_name: Option<String>,
4184 /// Line range of the guarded code block (derived from guard_span + line_offsets).
4185 /// Used for cross-reference with dead code findings.
4186 #[serde(skip)]
4187 pub guard_line_start: Option<u32>,
4188 /// End line of the guarded code block.
4189 #[serde(skip)]
4190 pub guard_line_end: Option<u32>,
4191 /// Unused exports found within the guarded code block.
4192 /// Populated by cross-reference with dead code analysis.
4193 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4194 pub guarded_dead_exports: Vec<String>,
4195}
4196
4197// Size assertion: FeatureFlag is stored in a Vec per analysis run.
4198const _: () = assert!(std::mem::size_of::<FeatureFlag>() <= 160);
4199
4200/// Usage count for an export symbol. Used by the LSP Code Lens to show
4201/// the number of importing files above each export declaration.
4202#[derive(Debug, Clone, Serialize, Deserialize)]
4203#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4204pub struct ExportUsage {
4205 /// File containing the export.
4206 #[serde(serialize_with = "serde_path::serialize")]
4207 pub path: PathBuf,
4208 /// Name of the exported symbol.
4209 pub export_name: String,
4210 /// 1-based line number.
4211 pub line: u32,
4212 /// 0-based byte column offset.
4213 pub col: u32,
4214 /// Number of distinct files that import this export. Two imports in one
4215 /// file count as one file.
4216 pub reference_count: usize,
4217 /// Import sites that reference this export, one entry per physical import.
4218 /// A file with two imports gives two entries, so this list can be longer
4219 /// than `reference_count`. An import without a source span has no entry.
4220 /// Used by the LSP Code Lens to enable click-to-navigate via
4221 /// `editor.action.showReferences`.
4222 pub reference_locations: Vec<ReferenceLocation>,
4223}
4224
4225/// A location where an export is referenced (import site in another file).
4226#[derive(Debug, Clone, Serialize, Deserialize)]
4227#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
4228pub struct ReferenceLocation {
4229 /// File containing the import that references the export.
4230 #[serde(serialize_with = "serde_path::serialize")]
4231 pub path: PathBuf,
4232 /// 1-based line number.
4233 pub line: u32,
4234 /// 0-based byte column offset.
4235 pub col: u32,
4236}
4237
4238#[path = "results_helpers.rs"]
4239mod results_helpers;
4240use results_helpers::{all_nonempty_paths_match, catalog_sort_key, move_covered};
4241
4242#[cfg(test)]
4243#[path = "results_tests.rs"]
4244mod tests;