Skip to main content

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