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