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