Skip to main content

fallow_config/config/
mod.rs

1mod boundaries;
2mod dependency_ignore;
3mod duplicates_config;
4mod entry_span;
5mod finding_ignore;
6mod flags;
7mod format;
8pub mod glob_validation;
9mod health;
10mod ignore_patterns;
11mod parsing;
12mod resolution;
13mod resolve;
14mod rules;
15mod similar_code;
16mod used_class_members;
17
18#[expect(
19    clippy::redundant_pub_crate,
20    reason = "this module is glob re-exported from lib.rs, so `pub` would leak the helper into the public API; pub(crate) keeps it internal to the crate"
21)]
22pub(crate) use boundaries::wildcard_placement_error;
23pub use boundaries::{
24    AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
25    BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
26    LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
27    ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
28    ZoneReferenceKind, ZoneValidationError,
29};
30pub use dependency_ignore::{IgnoreDependencyMatcher, is_dependency_glob};
31pub use duplicates_config::{
32    DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
33};
34pub use entry_span::ConfigEntrySpan;
35pub use finding_ignore::FindingIgnoreMatcher;
36pub use flags::{FlagsConfig, SdkPattern};
37pub use format::OutputFormat;
38pub use health::{EmailMode, HealthConfig, HealthThresholdOverride, OwnershipConfig};
39pub use ignore_patterns::{IgnorePatternSet, UNLIFTABLE_IGNORE_SEGMENTS};
40pub use parsing::{CONFIG_FILE_NAMES, ConfigLoadOptions};
41pub use resolution::{
42    AnalysisSnapshot, CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, CompiledIgnoreCatalogReferenceRule,
43    CompiledIgnoreDependencyOverrideRule, CompiledIgnoreExportRule, ConfigOverride,
44    DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_FILE_SIZE_BYTES, DEFAULT_MAX_FILE_SIZE_MB,
45    IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule, IgnoreExportRule,
46    PACKAGE_BASELINES_ENV, ResolvedConfig, ResolvedOverride, cache_config_hash,
47    cache_dir_env_override, cache_dir_from_env_value, cache_max_size_env_override,
48    cache_max_size_from_env_value, package_baselines_disabled_by_env_value,
49    resolve_max_file_size_bytes,
50};
51pub use resolve::ResolveConfig;
52pub use rules::{
53    KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, Severity, closest_known_rule_name,
54    default_severity_for_kind, is_opt_in_kind,
55};
56pub use similar_code::SimilarCodeConfig;
57pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
58
59use schemars::JsonSchema;
60use serde::{Deserialize, Deserializer, Serialize};
61use std::ops::Not;
62use std::path::PathBuf;
63
64use crate::external_plugin::ExternalPluginDef;
65use crate::workspace::WorkspaceConfig;
66
67/// Value of the `ignoreExportsUsedInFile` config key: whether an export
68/// referenced elsewhere in its own file is suppressed from `unused-export`.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
70#[serde(untagged, rename_all = "camelCase")]
71pub enum IgnoreExportsUsedInFileConfig {
72    /// Blanket toggle: `true` suppresses any export with a same-file use,
73    /// regardless of kind. The default is `false`.
74    Bool(bool),
75    /// Knip-parity object form restricting the suppression to type-only
76    /// exports.
77    ByKind(IgnoreExportsUsedInFileByKind),
78}
79
80impl Default for IgnoreExportsUsedInFileConfig {
81    fn default() -> Self {
82        Self::Bool(false)
83    }
84}
85
86impl From<bool> for IgnoreExportsUsedInFileConfig {
87    fn from(value: bool) -> Self {
88        Self::Bool(value)
89    }
90}
91
92impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
93    fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
94        Self::ByKind(value)
95    }
96}
97
98impl IgnoreExportsUsedInFileConfig {
99    /// Whether any form of the same-file-use suppression is active (the bool
100    /// form is `true`, or either by-kind field is set).
101    #[must_use]
102    pub const fn is_enabled(self) -> bool {
103        match self {
104            Self::Bool(value) => value,
105            Self::ByKind(kind) => kind.type_ || kind.interface,
106        }
107    }
108
109    /// Whether an export with a same-file use should be suppressed, given
110    /// whether fallow classified it as type-only. The bool form suppresses
111    /// regardless of kind; the by-kind form suppresses type-only exports only.
112    #[must_use]
113    pub const fn suppresses(self, is_type_only: bool) -> bool {
114        match self {
115            Self::Bool(value) => value,
116            Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
117        }
118    }
119}
120
121/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
122/// restricting the same-file-use suppression to type-only exports.
123#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
124#[serde(rename_all = "camelCase")]
125pub struct IgnoreExportsUsedInFileByKind {
126    /// When `true`, enables the same-file-use suppression for type-only exports (serialized as `type`; part of the object form of `ignoreExportsUsedInFile`). Because fallow groups type aliases and interfaces under one issue kind, setting either `type` or `interface` enables the identical type-only suppression, applied only to exports fallow classifies as type-only.
127    #[serde(default, rename = "type")]
128    pub type_: bool,
129    /// When `true`, enables the same-file-use suppression for type-only exports (part of the object form of `ignoreExportsUsedInFile`). Fallow does not distinguish interfaces from type aliases in this issue kind, so `interface` behaves identically to `type`: setting either one turns on the type-only same-file suppression.
130    #[serde(default)]
131    pub interface: bool,
132}
133
134/// Options for the `unused-component-props` rule.
135///
136/// Lets a project exempt component props whose local destructure binding name
137/// matches a regex from `unused-component-props`, honoring the
138/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
139/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
140/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
141/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
142/// behavior unchanged.
143#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
144#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
145pub struct UnusedComponentPropsConfig {
146    /// Regex matched against each declared prop's LOCAL destructure binding name
147    /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
148    /// to the public prop name when there is no alias. A prop whose local name
149    /// matches is treated as intentionally unused and never reported as
150    /// `unused-component-props`. Matching is unanchored (substring), like
151    /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
152    /// underscore. Compiled and validated at config load (an invalid regex fails
153    /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub ignore_pattern: Option<String>,
156}
157
158impl UnusedComponentPropsConfig {
159    /// True when no option is set, so serialization can omit the section.
160    #[must_use]
161    pub fn is_default(&self) -> bool {
162        self.ignore_pattern.is_none()
163    }
164}
165
166/// Options for the `circular-dependencies` rule.
167///
168/// The default leaves the rule unchanged: every runtime import edge takes
169/// part in cycle detection, and only type-only edges are skipped.
170#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
171#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
172pub struct CircularDependenciesConfig {
173    /// Skip import edges that load their target on demand or on another
174    /// thread when fallow looks for cycles. A literal `import()` inside a
175    /// function, a template `import()`, a lazy `import.meta.glob`, a worker
176    /// URL and a webpack worker loader request (`worker-loader!./work.js`)
177    /// are lazy edges. A top-level `await import()`, `require()` and an
178    /// eager `import.meta.glob` load before the module finishes, so they stay.
179    /// An edge that also carries a static import stays. Default `false`.
180    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
181    pub ignore_lazy_imports: bool,
182}
183
184impl CircularDependenciesConfig {
185    /// True when no option is set, so serialization can omit the section.
186    #[must_use]
187    pub const fn is_default(&self) -> bool {
188        !self.ignore_lazy_imports
189    }
190}
191
192/// The `fix` config section: settings for `fallow fix` apply behavior.
193#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
194#[serde(rename_all = "camelCase")]
195pub struct FixConfig {
196    /// Groups `fallow fix` settings for pnpm workspace catalog cleanup. Its only key, `deletePrecedingComments` (`auto` default, `always`, `never`), controls whether a comment block directly above a removed unused `pnpm-workspace.yaml` catalog entry is deleted with the entry.
197    #[serde(default)]
198    pub catalog: CatalogFixConfig,
199}
200
201/// The `fix.catalog` section: how `fallow fix` cleans up unused
202/// `pnpm-workspace.yaml` catalog entries.
203#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
204#[serde(rename_all = "camelCase")]
205pub struct CatalogFixConfig {
206    /// Controls whether comment lines immediately above an unused `pnpm-workspace.yaml` catalog entry are removed when `fallow fix` deletes that entry: `auto` (default: delete only when the comment block is preceded by a blank line or sits directly under the parent catalog header, and never when it is a section banner like `# ====`), `always` (always remove the adjacent comment block), or `never` (leave all preceding comments). A `fallow-keep` marker anywhere in the block always preserves it regardless of this setting. Set `never` for teams that keep hand-authored notes above catalog pins.
207    #[serde(default)]
208    pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
209}
210
211/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
212/// lines directly above a catalog entry that `fallow fix` removes. A
213/// `fallow-keep` marker in the block always preserves it regardless of policy.
214#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
215#[serde(rename_all = "lowercase")]
216pub enum CatalogPrecedingCommentPolicy {
217    /// Delete the adjacent comment block only when heuristics attribute it to
218    /// the entry (preceded by a blank line or directly under the catalog
219    /// header) and it is not a section banner. The default.
220    #[default]
221    Auto,
222    /// Always delete the adjacent comment block with the entry.
223    Always,
224    /// Never delete preceding comments.
225    Never,
226}
227
228/// Completeness policy for opt-in TypeScript semantic analysis.
229#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
230#[serde(rename_all = "kebab-case")]
231pub enum TypeAwareRequire {
232    /// Keep conservative findings and report semantic gaps without failing.
233    #[default]
234    BestEffort,
235    /// Fail the quality gate when any requested semantic query is incomplete.
236    Complete,
237}
238
239impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
240    fn from(value: TypeAwareRequire) -> Self {
241        match value {
242            TypeAwareRequire::BestEffort => Self::BestEffort,
243            TypeAwareRequire::Complete => Self::Complete,
244        }
245    }
246}
247
248/// Shared opt-in configuration for TypeScript semantic analysis.
249#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
250#[serde(deny_unknown_fields, rename_all = "camelCase")]
251pub struct TypeAwareConfig {
252    /// Enable the optional TypeScript semantic pass. Disabled by default.
253    #[serde(default)]
254    pub enabled: bool,
255    /// TypeScript project config paths, resolved relative to the project root.
256    #[serde(default, skip_serializing_if = "Vec::is_empty")]
257    pub projects: Vec<String>,
258    /// Decide whether partial semantic analysis is advisory or gating.
259    #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
260    pub require: TypeAwareRequire,
261}
262
263#[expect(
264    clippy::trivially_copy_pass_by_ref,
265    reason = "serde skip_serializing_if callbacks receive field values by reference"
266)]
267fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
268    matches!(value, TypeAwareRequire::BestEffort)
269}
270
271impl TypeAwareConfig {
272    /// True when the section equals its default (disabled, no projects,
273    /// best-effort), so serialization can omit it.
274    #[must_use]
275    pub fn is_default(&self) -> bool {
276        !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
277    }
278}
279
280/// The user-facing fallow configuration as authored in `.fallowrc.json` /
281/// `.fallowrc.jsonc` / `fallow.toml` / `.fallow.toml`.
282///
283/// Every field documents its serialized meaning, default, and precedence
284/// against CLI flags and environment variables where they exist.
285/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
286/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
287/// Unknown keys are rejected at load so typos fail loud.
288#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
289#[serde(deny_unknown_fields, rename_all = "camelCase")]
290// Both `.fallowrc.json` and `.fallowrc.jsonc` are read with the JSONC dialect
291// from `crate::jsonc::parse_options`, so the schema declares the same dialect.
292// JSON language service clients (VS Code, Zed) read these two keywords off the
293// root object and otherwise flag syntax the loader accepts. They are
294// annotations only: nothing in fallow reads them back.
295#[schemars(extend("allowComments" = true, "allowTrailingCommas" = true))]
296pub struct FallowConfig {
297    /// A string pointing at fallow's JSON Schema URL, used only by editors for autocomplete and validation of the config file; it has no effect on analysis and is stripped before serialization (serde skip_serializing, writeOnly in the schema). Set it to `./node_modules/fallow/schema.json` for npm installs (version-aligned, offline, avoids VS Code's untrusted-remote-schema prompt), or `https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json` for non-npm installs; any other value is ignored by fallow.
298    #[serde(rename = "$schema", default, skip_serializing)]
299    pub schema: Option<String>,
300
301    /// The lowest fallow version this config is written for, as `MAJOR.MINOR.PATCH`. An older binary stops with a message naming both versions instead of failing on the first field it does not recognize, so a config committed to a shared repository says which upgrade it needs rather than reading like a typo. Optional and unset by default; set it in the same change that adds a field introduced in a newer version. It gates nothing on its own: an unknown key still fails on a binary at or above this version, because there the key really is a typo.
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub minimum_version: Option<String>,
304
305    /// An ordered array of parent config sources to inherit before this file's own keys apply; each entry is a file-relative path, an `npm:<package>` specifier, or an `https://` URL (`http://` is rejected), deep-merged in order so objects merge field-by-field while arrays and scalars in this file replace the parent's, with cycle and depth guards. Set it to share a base config across a monorepo or team; it is consumed at load and stripped before serialization (serde skip_serializing).
306    #[serde(default, skip_serializing)]
307    pub extends: Vec<String>,
308
309    /// An array of project-root-relative glob patterns whose matching files are seeded as manual entry points, on top of the framework and package.json entries fallow discovers automatically, so their transitive imports are not reported as unused. Set it (e.g. `["src/main.ts"]`) when a file is a real runtime root that no plugin or manifest declares; patterns are validated at load and matched against discovered files.
310    #[serde(default)]
311    pub entry: Vec<String>,
312
313    /// An array of project-root-relative glob patterns for files to exclude from analysis entirely; entries are unioned with fallow's built-in defaults (**/node_modules/**, **/dist/**, **/build/**, **/.git/**, **/coverage/**, **/*.min.js, **/*.min.mjs, **/*.min.cjs, **/*.bundle.js), so custom globs add to rather than replace them. Set it (e.g. `["generated/**"]`) to drop generated or vendored trees from every detector; patterns are validated at load. A `!`-prefixed entry is an exception that applies after the defaults and the positive patterns: `"!src/policy/coverage/**"` brings back hand-written source under a built-in default such as `**/coverage/**`, and `"!.config/**"` adds a hidden directory to discovery. Paths under `node_modules` or `.git` can not be lifted, and a `!` entry that names one of these segments is a config error.
314    #[serde(default)]
315    pub ignore_patterns: Vec<String>,
316
317    /// An array of project-root-relative glob patterns whose source-owned dead-code findings are hidden after analysis without excluding matching files from discovery, parsing, resolution, or the module graph. Use `/` as the path separator on every platform. Positive patterns select paths to hide; `!`-prefixed patterns keep matching paths reportable, and a negated-only array reports only those exception paths. A finding with multiple source owners is hidden only when every owner matches, so a cycle, duplicate-export group, or unlisted dependency with any reportable location remains visible. Architecture, policy, suppression-hygiene, and framework-correctness findings remain visible even when a referenced path matches, as do manifest-owned findings that no source file owns: unused dependencies, unused dev and optional dependencies, catalog entries, and dependency overrides. Use `ignorePatterns` instead when a generated or vendored file must not be analyzed at all.
318    #[serde(default, skip_serializing_if = "Vec::is_empty")]
319    pub ignore_findings: Vec<String>,
320
321    /// Declares inline external framework plugins as data (array of plugin objects), each with `name` plus optional `enablers` (package names that activate it) or richer `detection` (dependency/file-existence/`all`/`any` checks, taking priority over `enablers`), `entryPoints` (+ `entryPointRole` runtime/support/test), `configPatterns`, `alwaysUsed`, `toolingDependencies`, `usedExports` (`{ pattern, exports }`), and `usedClassMembers`. Set it to keep a custom or in-house framework's entry points, config files, and conventions reachable without a Rust plugin; these definitions are appended to plugins discovered via `plugins`, `.fallow/plugins/`, and root `fallow-plugin-*` files (first occurrence of a name wins), and cannot do AST-based config parsing.
322    #[serde(default)]
323    pub framework: Vec<ExternalPluginDef>,
324
325    /// Monorepo workspace configuration. `patterns` adds workspace package roots beyond manifest discovery; `changedSince` maps exact project-root-relative workspace roots to Git baseline refs. A global changed-since request overrides those per-package baselines.
326    #[serde(default)]
327    pub workspaces: Option<WorkspaceConfig>,
328
329    /// A list of package names or package-name globs excluded from BOTH unused-dependency and unlisted-dependency detection, so a runtime-provided or otherwise-untracked package (e.g. `bun:sqlite`, a peer supplied at deploy time) is never flagged as unused when declared nor as unlisted when imported. Set it for packages fallow cannot observe being used and cannot observe being declared. An entry without glob characters matches the package name exactly; an entry with `*`, `?`, `[` or `{` is a glob in the `ignorePatterns` syntax matched against the package name, so `@acme/*` covers every package in the `@acme` scope.
330    #[serde(default)]
331    pub ignore_dependencies: Vec<String>,
332
333    /// A list of command names whose file arguments fallow does not make entry points. Fallow reads commands in package.json scripts (root and workspace packages), CI files (GitHub Actions and GitLab CI), Dockerfiles, Procfiles, and fly.toml files, and a file that a command names (such as `node scripts/seed.ts`) normally becomes an entry point. A listed command still counts as a used dependency, and its `--config` file is still tracked. Formatters and linters (ESLint, Prettier, Oxlint, Oxfmt, Biome, Stylelint, and similar tools) never make their targets entry points, so they do not need to be listed. Set it for a command whose file arguments are data, not code that runs (e.g. `["my-codegen"]`), or use `["*"]` to turn off entry points from all commands and declare real entries in `entry`. A name matches the command after environment, package-manager, and wrapper prefixes (`npx`, `pnpm exec`, `yarn run`, `varlock run --`), by exact file name; `*` is the only wildcard.
334    #[serde(default, skip_serializing_if = "Vec::is_empty")]
335    pub ignore_command_entries: Vec<String>,
336
337    /// A list of glob patterns that suppress only `unresolved-import` findings whose raw import specifier matches; it does not change dependency usage accounting or resolver behavior. Patterns match the import string as written (not a filesystem path), so list both `@example/icons` and `@example/icons/**` to cover a bare package and its subpaths; parent-relative generated specifiers like `../generated/**` are valid, and broad values like `**` can hide real missing modules.
338    #[serde(default)]
339    pub ignore_unresolved_imports: Vec<String>,
340
341    /// A list of per-file rules that exempt named exports from `unused-export` and from duplicate-exports grouping for files matching a glob. Each entry is `{ file: <glob>, exports: [<name>, ...] }` where `exports: ["*"]` exempts every export in the file and a name list exempts only those names; built for component-library barrels (shadcn/Radix/bits-ui `index.ts`) that intentionally re-export the same short names across many files.
342    #[serde(default)]
343    pub ignore_exports: Vec<IgnoreExportRule>,
344
345    /// A list of rules that suppress `unresolved-catalog-reference` findings (a workspace `package.json` referencing a `catalog:` or `catalog:<name>` that the catalog does not declare); config-only because `package.json` has no inline-suppression comment surface. Each entry needs a `package` (exact match) plus optional `catalog` (exact catalog-name match) and `consumer` (glob on the consuming package.json path); use it for staged catalog migrations where the catalog edit lands in a separate change.
346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
347    pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
348
349    /// A list of rules that suppress `unused-dependency-override` and `misconfigured-dependency-override` findings for pnpm `overrides` entries; config-only, matched against the override's target package. Each entry needs a `package` (exact match) plus an optional `source` to scope the suppression to `"pnpm-workspace.yaml"` or `"package.json"`.
350    #[serde(default, skip_serializing_if = "Vec::is_empty")]
351    pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
352
353    /// Controls whether an export referenced only by another symbol in the same file is treated as used (suppressed from `unused-export`) until it becomes completely unreferenced; references inside an export specifier itself (`export { foo }`, `export default foo`) do not count as same-file uses. Accepts `true`/`false` (default `false`, suppress nothing) or the knip-parity object `{ "type": true, "interface": true }`, which restricts the suppression to type-only exports; fallow groups type aliases and interfaces under one kind, so both object fields behave identically.
354    #[serde(default)]
355    pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
356
357    /// A list of decorator names that no longer grant a class member automatic exemption from `unused-class-member`: a member whose every decorator is in this set is checked normally, while a member carrying any decorator NOT listed here stays skipped (frameworks consume decorated members reflectively). Dotted entries match the full decorator path (`ns.foo`) and bare entries match the leftmost segment (so `"decorators"` collapses every `@decorators.*`); both `"@step"` and `"step"` are accepted (leading `@` stripped), and an unmatched entry emits a one-time warning.
358    #[serde(default, skip_serializing_if = "Vec::is_empty")]
359    pub ignore_decorators: Vec<String>,
360
361    /// A list of class-member names or glob patterns treated as framework-used, so a method a library invokes reflectively (ag-Grid `agInit`/`refresh`, Web Component `connectedCallback`) is not reported as `unused-class-member`; it applies to class members only, not enum members. Each entry is either a plain string/glob (`"agInit"`, `"enter*"`, `"*"`) applied to every class, or a scoped object `{ extends?, implements?, members: [...] }` that applies only when the class matches that heritage clause (a scoped rule requires `extends` or `implements`); patterns matching zero members warn once.
362    #[serde(default)]
363    pub used_class_members: Vec<UsedClassMemberRule>,
364
365    /// Configures clone detection: `enabled` (default true), `mode` (`strict`, `mild` default, `weak`, `semantic`, from least to most identifier/literal blinding; `strict` and `mild` are equivalent under fallow's AST tokenizer, `weak` blinds string literals, `semantic` blinds all identifiers and literals for Type-2 renamed-variable detection), `near` (false, add bounded function-scoped near-miss detection), `minTokens` (50), `minLines` (5), `minOccurrences` (integer >= 2, deserialization fails below 2), `threshold` (max duplication percentage, 0 = no limit), `ignore` globs, `ignoredClones` (reviewed clone keys to hide until their content or occurrence count changes), `ignoreDefaults` (true, merge built-in generated-file ignores), `skipLocal` (only report cross-directory clones), `crossLanguage` (strip TS type annotations to match .ts against .js), `ignoreImports` (true, strip ES import/re-export/top-level require wiring from the token stream), and `normalization` (per-flag `ignoreIdentifiers`/`ignoreStringValues`/`ignoreNumericValues` overrides on top of `mode`). Raise `minOccurrences` to focus on widespread copy-paste, enable `near` for gapped structural clones, or set `mode` to `semantic` to catch renamed-variable exact clones.
366    #[serde(default)]
367    pub duplicates: DuplicatesConfig,
368
369    /// Configures the explicit local `similar-code` candidate workflow:
370    /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
371    /// additional `ignore` globs. Provider identity, setup, executables,
372    /// endpoints, credentials, and consent cannot be set by project config.
373    #[serde(default)]
374    pub similar_code: SimilarCodeConfig,
375
376    /// Sets complexity and health thresholds for `fallow health` (also applied in combined `fallow` and `fallow audit`): `maxCyclomatic` (20), `maxCognitive` (15), `maxCrap` (30.0, findings at or above this are reported), `crapRefactorBand` (5, cyclomatic band below `maxCyclomatic` where a secondary refactor action is added), `maxUnitSize` (max function lines before a large-function finding, 60), `coverage`/`coverageRoot` (Istanbul coverage path and path-prefix strip for accurate CRAP), `ignore` globs (remove files from findings AND the health score), `thresholdOverrides` (per-file/per-function ceilings via `files`/`functions`/`maxCyclomatic`/`maxCognitive`/`maxCrap`/`maxUnitSize`/`reason`), `ownership` (`botPatterns` and `emailMode` for `--ownership`), and `suggestInlineSuppression` (true, emit `suppress-line` action hints in JSON). Raise thresholds to relax which functions are flagged, wire `coverage` for real CRAP scores, or exempt generated/test files via `ignore` (drops them from the score too) or `thresholdOverrides` (keeps them visible under a higher ceiling). The four `max*` thresholds govern findings only and never move `health_score`: its penalties use fixed calibration so grades stay comparable across projects, and `ignore` is the lever that removes files from the score.
377    #[serde(default)]
378    pub health: HealthConfig,
379
380    /// Opts into TypeScript semantic analysis for project-wide symbol use,
381    /// provenance, API surface, symbol impact, and public-signature coupling.
382    /// This does not surface compiler diagnostics or typed lint rules.
383    #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
384    pub type_aware: TypeAwareConfig,
385
386    /// Sets per-issue-type severity, keyed by kebab-case rule id: `error` reports and fails CI (non-zero exit), `warn` reports without failing, `off` disables detection and reporting entirely (e.g. `{ "unused-files": "error", "unused-exports": "warn", "private-type-leaks": "off" }`). Set a rule `off` to silence it, `warn` to demote below CI gating, or `error` to promote a warn/off-default rule to gating; most rules default to `error`, dev/optional-dependency and component/store/inject/CSS/catalog rules default to `warn`, and opt-in rules (`private-type-leaks`, `deprecated-exports-in-use`, `security-*`, `prop-drilling`, `thin-wrapper`, `duplicate-prop-shape`, `coverage-gaps`, `feature-flags`, `require-suppression-reason`) default to `off`. Singular aliases (`unused-file`) and `warning`/`none` severity spellings are accepted.
387    #[serde(default)]
388    pub rules: RulesConfig,
389
390    #[serde(
391        default,
392        skip_serializing_if = "UnusedComponentPropsConfig::is_default"
393    )]
394    /// Options for the `unused-component-props` rule, currently only `ignorePattern`: a regex matched against each declared prop's local destructure binding name (falling back to the public prop name when unaliased) to exempt intentionally-unused props such as the leading-underscore convention. Set `{ "ignorePattern": "^_" }` to skip props like `_stage`; matching is unanchored (substring, like ESLint's `RegExp.test`) so anchor with `^`, the pattern is validated at config load (invalid regex fails load), and it applies to Vue, Svelte, Astro, and React/Preact props (unset leaves the rule unchanged).
395    pub unused_component_props: UnusedComponentPropsConfig,
396
397    #[serde(
398        default,
399        skip_serializing_if = "CircularDependenciesConfig::is_default"
400    )]
401    /// Options for the `circular-dependencies` rule, currently only `ignoreLazyImports`. Set `{ "ignoreLazyImports": true }` to skip import edges that load on demand or on another thread (an `import()` inside a function, a template `import()`, a lazy `import.meta.glob`, a worker URL, a webpack worker loader request such as `worker-loader!./work.js`) when fallow looks for cycles. A top-level `await import()`, `require()`, an eager glob, and an edge that also has a static import stay in the cycle graph. Default `false` leaves the rule unchanged.
402    pub circular_dependencies: CircularDependenciesConfig,
403
404    /// Configures architecture boundary enforcement: which source directories belong to which named zone and which zones may import which others, reported as boundary-violation, boundary-coverage-violation, and boundary-call-violation findings (severity via rules.boundary-violation, default error). Set to enforce a layered/module architecture; the object holds `preset` (one of layered, hexagonal, feature-sliced, bulletproof, whose default zones/rules are merged in with the user-declared zones/rules taking precedence), `zones` (each with `name`, `patterns`, `autoDiscover`, optional `root`), `rules` (each with `from`, `allow`, `allowTypeOnly` target-zone lists), `coverage` (`requireAllFiles` plus `allowUnmatched` globs for files matching no zone), and `calls` (a `forbidden` list of `{from, callee}` banned-call rules per zone).
405    #[serde(default)]
406    pub boundaries: BoundaryConfig,
407
408    /// Configures feature-flag detection: `sdkPatterns` (custom flag-evaluating call signatures, each `{ function, nameArg (zero-based arg index of the flag name, default 0), provider? }`, merged with built-ins for LaunchDarkly, Statsig, Unleash, GrowthBook, Split, PostHog, Vercel Flags, ConfigCat, Flagsmith, Optimizely, and Eppo), `envPrefixes` (env-var prefixes marking `process.env.*` and `import.meta.env.*` accesses as flags, merged with built-ins), and `configObjectHeuristics` (default false; when true, property accesses on objects whose name contains `feature`/`flag`/`toggle` are reported as low-confidence flags). Set `sdkPatterns`/`envPrefixes` to teach fallow a proprietary flag SDK or naming convention, or enable `configObjectHeuristics` for projects that read flags off config objects (higher false-positive rate). Feature-flag findings surface only when the `feature-flags` rule is enabled (default `off`).
409    #[serde(default)]
410    pub flags: FlagsConfig,
411
412    /// Scopes the opt-in `fallow security` catalogue: which candidate categories run and which extra local identifiers count as HTTP request objects. Set when tuning security-candidate detection; the object holds `categories` (an object with `include` and/or `exclude` string arrays of catalogue category ids, where `include` restricts to a whitelist and `exclude` removes from the admitted set, both unset admits all ordinary categories) and `requestReceivers` (a string array of project-local names that extend, not replace, the built-in `*.query`/`*.params`/`*.body` source-receiver allowlist). The `hardcoded-secret` and `secret-to-network` categories are include-required: they fire only when explicitly listed in `categories.include`, even when no include list is otherwise set. The valid category ids are enumerated (with title, CWE, and include-required flag) in the `security_categories` block of `fallow schema`, and also listed by `fallow security --help`; they are not in this config-schema.
413    #[serde(default)]
414    pub security: SecurityConfig,
415
416    /// Configures `fallow fix` behavior. Currently holds one nested section, `catalog` (a `CatalogFixConfig`), whose only key `deletePrecedingComments` (`auto` default, `always`, `never`) governs whether comment lines directly above a removed unused `pnpm-workspace.yaml` catalog entry are deleted with it.
417    #[serde(default)]
418    pub fix: FixConfig,
419
420    /// Configures the module resolver. Its one key `conditions` is a list of additional package.json `exports`/`imports` condition names to honor, matched at higher priority than fallow's built-ins (`development`, `import`, `require`, `default`, `types`, `node`, plus `react-native`/`browser` when the React Native or Expo plugin is active). Set it when a package's `exports` map has custom branches (e.g. `worker`, `deno`, `edge`) that fallow should follow instead of the default branch.
421    #[serde(default)]
422    pub resolve: ResolveConfig,
423
424    /// Enables production mode, which excludes test/spec/story/dev files from discovery and forces `unused-dev-dependencies` and `unused-optional-dependencies` to `off`. Accepts a boolean (default false) applied to all analyses, or a per-analysis object `{ deadCode?, health?, dupes? }` (each boolean, default false) that scopes production mode to individual analyses in combined `fallow` and `fallow audit`. Set it to analyze only shipped code; the `--production`/`--no-production` and `--production-{dead-code,health,dupes}` CLI flags and `FALLOW_PRODUCTION*` env vars override this value (CLI flags win, then per-analysis env, then global env, then config).
425    #[serde(default)]
426    pub production: ProductionConfig,
427
428    /// List of paths (relative to the project root, must resolve within it) to external plugin definition files or directories in JSONC/JSON/TOML, loaded in addition to the auto-discovered `.fallow/plugins/` directory and root `fallow-plugin-*` files. Set it to load plugin definitions kept outside those default locations; a path resolving outside the project root is skipped with a `tracing::warn`, and paths listed here are searched before the auto-discovered locations (first occurrence of a plugin name wins).
429    #[serde(default)]
430    pub plugins: Vec<String>,
431
432    /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
433    /// project root. Each pack declares `banned-call`, `banned-import`, or
434    /// `banned-effect` rules that report as `policy-violation` findings. Packs
435    /// are pure data: no project code is executed. Invalid or missing packs
436    /// fail config load.
437    #[serde(default, skip_serializing_if = "Vec::is_empty")]
438    pub rule_packs: Vec<String>,
439
440    /// An array of project-root-relative glob patterns for files loaded at runtime by a mechanism the static graph cannot see (dynamic path resolution, config-driven loading); matching files are seeded as entry points so they and their imports stay reachable. Empty by default; set it (e.g. `["plugins/**/*.ts", "locales/**/*.json"]`) for plugin or locale trees pulled in dynamically.
441    #[serde(default)]
442    pub dynamically_loaded: Vec<String>,
443
444    /// An ordered list of per-file rule-severity overrides: each entry re-severities specific analysis rules for files its globs match, layered on top of the top-level `rules` defaults. Set to relax or tighten rules for a subset of paths (e.g. downgrade unused-exports to warn under a generated directory); each entry has `files` (glob-pattern array) and `rules` (a partial per-rule severity map of error/warn/off). Entries apply in list order and a file matched by several entries takes every matching entry's overrides (later entries win on conflict); inter-file rules (duplicate-exports, circular-dependencies, re-export-cycle) have no effect in an override (fallow warns during analysis and points to the right mechanism: top-level `ignoreExports` for duplicate-exports, a file-level `// fallow-ignore-file` comment for the others).
445    #[serde(default)]
446    pub overrides: Vec<ConfigOverride>,
447
448    /// A project-root-relative path to a CODEOWNERS file, used by fallow health --hotspots --ownership to attribute declared owners and compute unowned/drifting ownership state; setting it overrides the default probe order (CODEOWNERS, .github/CODEOWNERS, .gitlab/CODEOWNERS, docs/CODEOWNERS). String, defaults to null (auto-probe the standard locations); set it only when the CODEOWNERS file lives at a non-standard location.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub codeowners: Option<String>,
451
452    /// An array of internal workspace package names (or globs matched against workspace package names) whose public API is intentionally consumed outside the analyzed graph; their entry points and re-export surface become reachability roots, so their exported files, exports, and class members are not reported as unused. Set it (e.g. `["@myorg/shared-lib", "@myorg/*"]`) for library packages in a monorepo that ship an API to external consumers; only meaningful when workspaces are present (an empty list or no workspaces is a no-op).
453    #[serde(default)]
454    pub public_packages: Vec<String>,
455
456    /// Holds a saved issue-count baseline that the `--fail-on-regression` gate compares the current run against, failing only when counts grow beyond tolerance relative to the baseline. Usually written by `--save-baseline` rather than hand-authored; the object has a single `baseline` sub-key holding per-issue-type counts (total_issues plus per-kind fields like unused_exports, boundary_violations, policy_violations, each defaulting to 0). Absent means no baseline is embedded in config.
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub regression: Option<RegressionConfig>,
459
460    /// Sets in-repo defaults for `fallow audit` (the changed-files quality gate) so CLI flags need not repeat per run. Set to pin audit behavior; the object holds `gate` (`new-only` or `all`, which findings drive the verdict), `css`/`cssDeep` (booleans toggling styling analysis and the project-wide CSS reachability pass), `deadCodeBaseline`/`healthBaseline`/`dupesBaseline` (per-sub-analysis baseline file paths), and `cacheMaxAgeDays` (GC window in days for the reusable base-snapshot worktree cache). The matching CLI flag overrides each field.
461    #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
462    pub audit: AuditConfig,
463
464    /// When true, restricts this config's extends entries to file-relative paths that resolve inside the config file's own directory; any https:// URL, npm: package, or relative path escaping that directory is rejected at load with a hard error. Boolean, defaults to false (URL, npm, and any-relative extends are permitted); set it to true to harden a config against pulling in remote or out-of-tree bases.
465    #[serde(default)]
466    pub sealed: bool,
467
468    /// When true, exports of entry-point files are subject to unused-export detection instead of being auto-credited as used, so a typo'd or stray export in a framework route or package entry (e.g. meatdata for metadata) is flagged; plugin used_exports allowlists are still honored. Boolean, defaults to false; the CLI flag --include-entry-exports applies the same behavior for one run.
469    #[serde(default)]
470    pub include_entry_exports: bool,
471
472    /// When true, drops Nuxt convention-based entry-pattern fallbacks so genuinely-unreferenced convention files surface as unused-file. Component fallbacks are kept when nuxt.config customizes components: in a way fallow does not model, and composable/util fallbacks are kept when it customizes imports:; a config that scans no more than the Nuxt defaults (components: false, components: [], components: { dirs: [] }, components: true, imports: { scan: false }, imports: {}, imports: { dirs: [] }) is treated like the default and its fallbacks are dropped; imports: { autoImport: false } on its own is not, because it only switches the injection off while the same directories stay registered behind #imports. A nuxt.config that carries any top-level key fallow cannot read statically, a computed key, an accessor, or a spread such as { ...base, devtools: {} }, keeps both surfaces' fallbacks for that root, because the spread may hold the keys that decide. Only top-level keys count when the config object is readable: a nested key such as a routeRules path ending in components does not keep a fallback. Nested components or imports keys in $production, $development, $test or `$env.<name>`, and components or imports hooks (a components:* key or a nested components object in hooks, also inside those overrides), count as that surface's key; such an override object or hooks object that fallow cannot read statically falls back to a text match for the keys. Each root is classified on its own config plus the configs of its local layers, so one custom nuxt.config in a monorepo does not keep every other workspace's fallbacks. A local layer is a directory named in extends, or a `layers/<name>` directory, that holds a nuxt.config; its convention files are entry points with the flag off and auto-import sources with it on, and `#layers/<name>/` resolves to it by its $meta.name (a `layers/<name>` directory without one uses its directory name). A remote or package layer is only a dependency reference. Component names follow Nuxt: a component under components/global or components/islands is named after its own directory (components/global/Foo.vue is `<Foo>`), and .client, .server, .global and .island suffixes are stripped. A name imported or re-exported by hand from #components or #imports credits its convention file just like a template tag or a bare call; a namespace import names nothing and credits nothing. Boolean, defaults to false; set it for a Nuxt project that has explicitly configured its auto-import directories. Synthesis of auto-import graph edges (resolving `<Card />` or `useUserStore()` to their convention files) happens regardless of this flag.
473    #[serde(default)]
474    pub auto_imports: bool,
475
476    /// When true, the run fails with exit code 1 if fallow could not parse a source file cleanly (a `source-parse-degraded` entry in `workspace_diagnostics[]`), and the `parse-error` entry of `gate_outcomes` names each such file. Boolean, defaults to false, so a file the parser rejects only warns. Applies to `fallow dead-code`, `fallow health`, `fallow audit` and the bare `fallow` run; the CLI flag `--fail-on-parse-error` arms the same gate for one run. Older fallow versions reject this key as unknown, so pair it with `minimumVersion` set to the release that added it.
477    #[serde(default)]
478    pub fail_on_parse_error: bool,
479
480    /// Overrides the location and size ceiling of fallow's persistent extraction cache (default `.fallow/cache.bin` under the project root). Set to relocate the cache or cap its footprint; the object holds `dir` (cache directory, relative paths resolve from the project root) and `maxSizeMb` (extraction-cache size limit in megabytes). The `FALLOW_CACHE_MAX_SIZE` environment variable overrides `maxSizeMb`.
481    #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
482    pub cache: CacheConfig,
483}
484
485/// Scopes `fallow security` catalogue behavior. An absent category block admits
486/// every catalogue category. `hardcoded-secret` is include-required and only
487/// runs when explicitly listed in `security.categories.include`.
488#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
489#[serde(deny_unknown_fields, rename_all = "camelCase")]
490pub struct SecurityConfig {
491    /// Include/exclude filter over category ids (e.g. `dangerous-html`).
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub categories: Option<SecurityCategories>,
494    /// Additional project-local names for HTTP request objects. These names
495    /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
496    /// `*.body` source patterns. They do not replace the built-ins and do not
497    /// gate `*.searchParams`, which intentionally stays ungated.
498    #[serde(default, skip_serializing_if = "Vec::is_empty")]
499    pub request_receivers: Vec<String>,
500}
501
502impl SecurityConfig {
503    /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
504    /// in first-seen order, with empty entries dropped; the form the matcher
505    /// compares receiver names against (matching is case-insensitive).
506    #[must_use]
507    pub fn normalized_request_receivers(&self) -> Vec<String> {
508        let mut receivers = Vec::new();
509        for receiver in &self.request_receivers {
510            let normalized = receiver.trim().to_ascii_lowercase();
511            if !normalized.is_empty() && !receivers.contains(&normalized) {
512                receivers.push(normalized);
513            }
514        }
515        receivers
516    }
517
518    /// False when any configured receiver is empty or whitespace-only, which
519    /// config validation reports as an error instead of silently dropping it.
520    #[must_use]
521    pub fn request_receivers_are_valid(&self) -> bool {
522        self.request_receivers
523            .iter()
524            .all(|receiver| !receiver.trim().is_empty())
525    }
526}
527
528/// Include/exclude lists scoping the active security categories. When `include`
529/// is set, only those categories are active; `exclude` removes categories from
530/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
531/// still requires explicit inclusion.
532#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
533#[serde(deny_unknown_fields, rename_all = "camelCase")]
534pub struct SecurityCategories {
535    /// Catalogue category ids to admit. When set, all others are excluded.
536    #[serde(default, skip_serializing_if = "Option::is_none")]
537    pub include: Option<Vec<String>>,
538    /// Catalogue category ids to remove from the admitted set.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub exclude: Option<Vec<String>>,
541}
542
543/// The `cache` config section: location and size ceiling of fallow's
544/// persistent caches (default directory `<root>/.fallow`).
545#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
546#[serde(deny_unknown_fields, rename_all = "camelCase")]
547pub struct CacheConfig {
548    /// Directory for fallow's persistent analysis cache. Relative paths resolve
549    /// from the project root.
550    #[serde(default, skip_serializing_if = "Option::is_none")]
551    pub dir: Option<PathBuf>,
552    /// Maximum size of the persistent extraction cache, in megabytes.
553    #[serde(default, skip_serializing_if = "Option::is_none")]
554    pub max_size_mb: Option<u32>,
555}
556
557impl CacheConfig {
558    /// True when neither field is set, so serialization can omit the section.
559    #[must_use]
560    pub fn is_default(&self) -> bool {
561        self.dir.is_none() && self.max_size_mb.is_none()
562    }
563}
564
565/// The analysis families production mode can be scoped to independently via
566/// the object form of the `production` config key.
567#[derive(Debug, Clone, Copy, PartialEq, Eq)]
568pub enum ProductionAnalysis {
569    /// Unused files/exports/dependencies detection.
570    DeadCode,
571    /// Complexity and health scoring.
572    Health,
573    /// Clone detection.
574    Dupes,
575}
576
577/// Value of the `production` config key: excludes test/spec/story/dev files
578/// from discovery, either globally or per analysis family.
579#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
580#[serde(untagged)]
581pub enum ProductionConfig {
582    /// Boolean form applying to every analysis. The default is `false`.
583    Global(bool),
584    /// Object form (`{ deadCode?, health?, dupes? }`) scoping production mode
585    /// per analysis family.
586    PerAnalysis(PerAnalysisProductionConfig),
587}
588
589impl<'de> Deserialize<'de> for ProductionConfig {
590    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
591    where
592        D: Deserializer<'de>,
593    {
594        struct ProductionConfigVisitor;
595
596        impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
597            type Value = ProductionConfig;
598
599            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
600                formatter.write_str("a boolean or per-analysis production config object")
601            }
602
603            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
604            where
605                E: serde::de::Error,
606            {
607                Ok(ProductionConfig::Global(value))
608            }
609
610            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
611            where
612                A: serde::de::MapAccess<'de>,
613            {
614                PerAnalysisProductionConfig::deserialize(
615                    serde::de::value::MapAccessDeserializer::new(map),
616                )
617                .map(ProductionConfig::PerAnalysis)
618            }
619        }
620
621        deserializer.deserialize_any(ProductionConfigVisitor)
622    }
623}
624
625impl Default for ProductionConfig {
626    fn default() -> Self {
627        Self::Global(false)
628    }
629}
630
631impl From<bool> for ProductionConfig {
632    fn from(value: bool) -> Self {
633        Self::Global(value)
634    }
635}
636
637impl Not for ProductionConfig {
638    type Output = bool;
639
640    fn not(self) -> Self::Output {
641        !self.any_enabled()
642    }
643}
644
645impl ProductionConfig {
646    /// Whether production mode applies to `analysis` under this config.
647    #[must_use]
648    pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
649        match self {
650            Self::Global(value) => value,
651            Self::PerAnalysis(config) => match analysis {
652                ProductionAnalysis::DeadCode => config.dead_code,
653                ProductionAnalysis::Health => config.health,
654                ProductionAnalysis::Dupes => config.dupes,
655            },
656        }
657    }
658
659    /// The boolean form's value; `false` for the per-analysis form, which has
660    /// no global toggle.
661    #[must_use]
662    pub const fn global(self) -> bool {
663        match self {
664            Self::Global(value) => value,
665            Self::PerAnalysis(_) => false,
666        }
667    }
668
669    /// Whether production mode is enabled for at least one analysis family.
670    #[must_use]
671    pub const fn any_enabled(self) -> bool {
672        match self {
673            Self::Global(value) => value,
674            Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
675        }
676    }
677}
678
679/// Object form of the `production` config key, scoping production mode to
680/// individual analysis families in combined `fallow` and `fallow audit`.
681#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
682#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
683pub struct PerAnalysisProductionConfig {
684    /// When `production` is a per-analysis object, enables production mode for dead-code analysis only (boolean, default false): unused-files/exports/dependencies detection excludes test/spec/story/dev files and forces `unused-dev-dependencies`/`unused-optional-dependencies` to `off`, while health and dupes stay on the full tree. Set it to scope production analysis to dead code independently.
685    pub dead_code: bool,
686    /// When `production` is a per-analysis object, enables production mode for the health/complexity analysis only (boolean, default false), so `fallow health` in combined `fallow` and `fallow audit` scores only shipped code (test/spec/story/dev files excluded) while dead-code and dupes stay on the full tree. Set it to scope production analysis to health independently.
687    pub health: bool,
688    /// When `production` is a per-analysis object, enables production mode for duplication analysis only (boolean, default false), so clone detection runs on shipped code only (test/spec/story/dev files excluded) while dead-code and health stay on the full tree. Set it to scope production analysis to dupes independently.
689    pub dupes: bool,
690}
691
692/// The `audit` config section: in-repo defaults for `fallow audit`, each
693/// overridable by its matching CLI flag.
694#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
695#[serde(rename_all = "camelCase")]
696pub struct AuditConfig {
697    /// Selects which findings affect the `fallow audit` verdict: `new-only` (default) fails only on findings introduced by the current changeset (running a base-snapshot attribution pass), while `all` fails on every finding in changed files and skips that pass. Set to `all` to gate the full backlog in changed files; the `--gate` CLI flag overrides this.
698    #[serde(default, skip_serializing_if = "AuditGate::is_default")]
699    pub gate: AuditGate,
700
701    /// Toggles styling analytics (CSS and CSS-in-JS) in the `fallow audit` health sub-pass; these findings are descriptive and verdict-neutral by default (they change the exit code only when a css-* rule is set to error). Defaults to on when unset; set `false` to skip styling analysis. The `--no-css` CLI flag forces it off regardless.
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    pub css: Option<bool>,
704
705    /// Toggles the project-wide CSS reachability pass in `fallow audit`, whose cross-file findings are narrowed back to changed anchors. Defaults to on when unset and runs only when css analytics are enabled; set `false` to keep local styling analytics but skip the whole-project scan. The `--css-deep` flag re-enables it and `--no-css-deep` forces it off.
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub css_deep: Option<bool>,
708
709    /// Path to a saved dead-code baseline file (produced by `fallow dead-code --save-baseline`) that the audit's dead-code sub-analysis compares against, suppressing pre-existing dead-code issues. The `--dead-code-baseline` CLI flag overrides it and both resolve relative to the project root; each sub-analysis uses a distinct baseline format, so this is separate from `healthBaseline` and `dupesBaseline`.
710    #[serde(default, skip_serializing_if = "Option::is_none")]
711    pub dead_code_baseline: Option<String>,
712
713    /// Path to a saved health/complexity baseline file (produced by `fallow health --save-baseline`) that the audit's health sub-analysis compares against, suppressing pre-existing complexity/health findings. The `--health-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and dupes baselines.
714    #[serde(default, skip_serializing_if = "Option::is_none")]
715    pub health_baseline: Option<String>,
716
717    /// Path to a saved duplication baseline file (produced by `fallow dupes --save-baseline`) that the audit's duplication sub-analysis compares clone groups against, suppressing pre-existing duplicate clones. The `--dupes-baseline` CLI flag overrides it and both resolve relative to the project root; its baseline format is distinct from the dead-code and health baselines.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub dupes_baseline: Option<String>,
720
721    /// Garbage-collection threshold, in whole days, for the persistent reusable base-snapshot worktree caches `fallow audit` creates: entries older than this window are swept on each audit run. Set to control cache accumulation; `0` disables the sweep and unset defaults to 30 days. Each sweep also reclaims abandoned entries minted under other repo identities (deleted or moved repos, other git worktrees) once they age past this repo's threshold; entries whose recorded owner root still exists are skipped and stay governed by that repo's own setting. The `FALLOW_AUDIT_CACHE_MAX_AGE_DAYS` environment variable overrides this field.
722    #[serde(default, skip_serializing_if = "Option::is_none")]
723    pub cache_max_age_days: Option<u32>,
724
725    /// Overrides the top-level `typeAware.enabled` opt-in for `fallow audit` only: set `false` to keep persistent type-aware analysis on for cleanup commands (`dead-code`, `fix`, `health`) while the audit gate stays syntactic, or `true` to enable it for audit alone. Unset inherits `typeAware.enabled`. The `--type-aware`/`--no-type-aware` CLI flags and the `FALLOW_TYPE_AWARE` environment variable both take precedence over this field.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub type_aware: Option<bool>,
728}
729
730impl AuditConfig {
731    /// True when every field is unset, so serialization can omit the section.
732    #[must_use]
733    pub fn is_empty(&self) -> bool {
734        self.gate.is_default()
735            && self.css.is_none()
736            && self.css_deep.is_none()
737            && self.dead_code_baseline.is_none()
738            && self.health_baseline.is_none()
739            && self.dupes_baseline.is_none()
740            && self.cache_max_age_days.is_none()
741            && self.type_aware.is_none()
742    }
743}
744
745/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
746#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
747#[serde(rename_all = "kebab-case")]
748pub enum AuditGate {
749    /// Fail only on findings the current changeset introduced, determined by
750    /// a base-snapshot attribution pass. The default.
751    #[default]
752    NewOnly,
753    /// Fail on every finding in changed files, skipping the attribution pass.
754    All,
755}
756
757impl AuditGate {
758    /// True for the default `new-only` gate, so serialization can omit it.
759    #[must_use]
760    pub const fn is_default(&self) -> bool {
761        matches!(self, Self::NewOnly)
762    }
763}
764
765/// The `regression` config section holding the saved issue-count baseline for
766/// the `--fail-on-regression` gate.
767#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
768#[serde(rename_all = "camelCase")]
769pub struct RegressionConfig {
770    /// The saved per-issue-type issue counts that `--fail-on-regression` compares the current run against; the gate fails only when counts grow beyond the configured tolerance. Typically written by `--save-baseline` rather than hand-authored; each field (total_issues plus per-kind counts like unused_exports, boundary_violations, policy_violations) is an integer defaulting to 0 when omitted. Absent means no baseline is embedded.
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub baseline: Option<RegressionBaseline>,
773}
774
775/// Saved per-issue-type counts written by `--save-baseline` and compared by
776/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
777/// so hand-trimmed baselines stay loadable.
778#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
779#[serde(rename_all = "camelCase")]
780pub struct RegressionBaseline {
781    /// Compatibility identity for the analysis that produced these counts.
782    /// Missing values in existing configs are treated as syntactic.
783    #[serde(default)]
784    pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
785    /// Baseline count across all issue types.
786    #[serde(default)]
787    pub total_issues: usize,
788    /// Baseline count of `unused-files` findings.
789    #[serde(default)]
790    pub unused_files: usize,
791    /// Baseline count of `unused-exports` findings.
792    #[serde(default)]
793    pub unused_exports: usize,
794    /// Baseline count of `unused-types` findings.
795    #[serde(default)]
796    pub unused_types: usize,
797    /// Baseline count of `unused-dependencies` findings.
798    #[serde(default)]
799    pub unused_dependencies: usize,
800    /// Baseline count of `unused-dev-dependencies` findings.
801    #[serde(default)]
802    pub unused_dev_dependencies: usize,
803    /// Baseline count of `unused-optional-dependencies` findings.
804    #[serde(default)]
805    pub unused_optional_dependencies: usize,
806    /// Baseline count of `unused-enum-members` findings.
807    #[serde(default)]
808    pub unused_enum_members: usize,
809    /// Baseline count of `unused-class-members` findings.
810    #[serde(default)]
811    pub unused_class_members: usize,
812    /// Baseline count of `unresolved-imports` findings.
813    #[serde(default)]
814    pub unresolved_imports: usize,
815    /// Baseline count of `unlisted-dependencies` findings.
816    #[serde(default)]
817    pub unlisted_dependencies: usize,
818    /// Baseline count of `duplicate-exports` findings.
819    #[serde(default)]
820    pub duplicate_exports: usize,
821    /// Baseline count of `circular-dependencies` findings.
822    #[serde(default)]
823    pub circular_dependencies: usize,
824    /// Baseline count of `re-export-cycle` findings.
825    #[serde(default)]
826    pub re_export_cycles: usize,
827    /// Baseline count of `package-cycle` findings.
828    #[serde(default)]
829    pub package_cycles: usize,
830    /// Baseline count of `type-only-dependencies` findings.
831    #[serde(default)]
832    pub type_only_dependencies: usize,
833    /// Baseline count of `test-only-dependencies` findings.
834    #[serde(default)]
835    pub test_only_dependencies: usize,
836    /// Baseline count of `dev-dependencies-in-production` findings.
837    #[serde(default)]
838    pub dev_dependencies_in_production: usize,
839    /// Baseline count of `boundary-violation` findings.
840    #[serde(default)]
841    pub boundary_violations: usize,
842    /// Baseline count of boundary-coverage-violation findings.
843    #[serde(default)]
844    pub boundary_coverage_violations: usize,
845    /// Baseline count of boundary-call-violation findings.
846    #[serde(default)]
847    pub boundary_call_violations: usize,
848    /// Baseline count of `policy-violation` findings.
849    #[serde(default)]
850    pub policy_violations: usize,
851}
852
853#[cfg(test)]
854mod tests {
855    use super::*;
856
857    #[test]
858    fn default_config_has_empty_collections() {
859        let config = FallowConfig::default();
860        assert!(config.schema.is_none());
861        assert!(config.extends.is_empty());
862        assert!(config.entry.is_empty());
863        assert!(config.ignore_patterns.is_empty());
864        assert!(config.ignore_findings.is_empty());
865        assert!(config.framework.is_empty());
866        assert!(config.workspaces.is_none());
867        assert!(config.ignore_dependencies.is_empty());
868        assert!(config.ignore_exports.is_empty());
869        assert!(config.used_class_members.is_empty());
870        assert!(config.plugins.is_empty());
871        assert!(config.dynamically_loaded.is_empty());
872        assert!(config.overrides.is_empty());
873        assert!(config.public_packages.is_empty());
874        assert_eq!(
875            config.fix.catalog.delete_preceding_comments,
876            CatalogPrecedingCommentPolicy::Auto
877        );
878        assert!(!config.production);
879    }
880
881    #[test]
882    fn deserialize_empty_json_object() {
883        let config: FallowConfig = serde_json::from_str("{}").unwrap();
884        assert!(config.entry.is_empty());
885        assert!(!config.production);
886        assert!(!config.type_aware.enabled);
887        assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
888    }
889
890    #[test]
891    fn deserialize_type_aware_config() {
892        let config: FallowConfig = serde_json::from_str(
893            r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
894        )
895        .unwrap();
896
897        assert!(config.type_aware.enabled);
898        assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
899        assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
900    }
901
902    #[test]
903    fn deserialize_type_aware_config_rejects_unknown_fields() {
904        let result = serde_json::from_str::<FallowConfig>(
905            r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
906        );
907        assert!(result.is_err());
908    }
909
910    #[test]
911    fn deserialize_json_with_all_top_level_fields() {
912        let json = r#"{
913            "$schema": "./node_modules/fallow/schema.json",
914            "entry": ["src/main.ts"],
915            "ignorePatterns": ["generated/**"],
916            "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
917            "ignoreDependencies": ["postcss"],
918            "production": true,
919            "plugins": ["custom-plugin.toml"],
920            "rules": {"unused-files": "warn"},
921            "duplicates": {"enabled": false},
922            "health": {"maxCyclomatic": 30}
923        }"#;
924        let config: FallowConfig = serde_json::from_str(json).unwrap();
925        assert_eq!(
926            config.schema.as_deref(),
927            Some("./node_modules/fallow/schema.json")
928        );
929        assert_eq!(config.entry, vec!["src/main.ts"]);
930        assert_eq!(config.ignore_patterns, vec!["generated/**"]);
931        assert_eq!(
932            config.ignore_findings,
933            vec!["**/*.test.ts", "!src/public/**"]
934        );
935        assert_eq!(config.ignore_dependencies, vec!["postcss"]);
936        assert!(config.production);
937        assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
938        assert_eq!(config.rules.unused_files, Severity::Warn);
939        assert!(!config.duplicates.enabled);
940        assert_eq!(config.health.max_cyclomatic, 30);
941    }
942
943    #[test]
944    fn deserialize_json_deny_unknown_fields() {
945        let json = r#"{"unknownField": true}"#;
946        let result: Result<FallowConfig, _> = serde_json::from_str(json);
947        assert!(result.is_err(), "unknown fields should be rejected");
948    }
949
950    #[test]
951    fn ignore_findings_serialization_is_canonical_and_sparse() {
952        let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
953        assert!(default_value.get("ignoreFindings").is_none());
954
955        let config = FallowConfig {
956            ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
957            ..Default::default()
958        };
959        let value = serde_json::to_value(config).unwrap();
960        assert_eq!(
961            value.get("ignoreFindings"),
962            Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
963        );
964    }
965
966    #[test]
967    fn ignore_findings_deserializes_from_toml() {
968        let config: FallowConfig =
969            toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
970
971        assert_eq!(
972            config.ignore_findings,
973            vec!["**/*.test.ts", "!src/public/**"]
974        );
975    }
976
977    #[test]
978    fn generic_ignore_alias_is_rejected() {
979        let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
980
981        assert!(result.is_err());
982    }
983
984    #[test]
985    fn deserialize_json_production_mode_default_false() {
986        let config: FallowConfig = serde_json::from_str("{}").unwrap();
987        assert!(!config.production);
988    }
989
990    #[test]
991    fn deserialize_json_production_mode_true() {
992        let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
993        assert!(config.production);
994    }
995
996    #[test]
997    fn deserialize_json_per_analysis_production_mode() {
998        let config: FallowConfig = serde_json::from_str(
999            r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
1000        )
1001        .unwrap();
1002        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1003        assert!(config.production.for_analysis(ProductionAnalysis::Health));
1004        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1005    }
1006
1007    #[test]
1008    fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
1009        let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
1010            .unwrap_err();
1011        assert!(
1012            err.to_string().contains("healthTypo"),
1013            "error should name the unknown field: {err}"
1014        );
1015    }
1016
1017    #[test]
1018    fn deserialize_json_dynamically_loaded() {
1019        let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
1020        let config: FallowConfig = serde_json::from_str(json).unwrap();
1021        assert_eq!(
1022            config.dynamically_loaded,
1023            vec!["plugins/**/*.ts", "locales/**/*.json"]
1024        );
1025    }
1026
1027    #[test]
1028    fn deserialize_json_dynamically_loaded_defaults_empty() {
1029        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1030        assert!(config.dynamically_loaded.is_empty());
1031    }
1032
1033    #[test]
1034    fn deserialize_json_fix_catalog_delete_preceding_comments() {
1035        let config: FallowConfig =
1036            serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
1037                .unwrap();
1038        assert_eq!(
1039            config.fix.catalog.delete_preceding_comments,
1040            CatalogPrecedingCommentPolicy::Always
1041        );
1042    }
1043
1044    #[test]
1045    fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
1046        let err = serde_json::from_str::<FallowConfig>(
1047            r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
1048        )
1049        .unwrap_err();
1050        assert!(
1051            err.to_string().contains("sometimes"),
1052            "error should name the bad policy: {err}"
1053        );
1054    }
1055
1056    #[test]
1057    fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1058        let json = r#"{
1059            "usedClassMembers": [
1060                "agInit",
1061                { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1062                { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1063            ]
1064        }"#;
1065        let config: FallowConfig = serde_json::from_str(json).unwrap();
1066        assert_eq!(
1067            config.used_class_members,
1068            vec![
1069                UsedClassMemberRule::from("agInit"),
1070                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1071                    extends: None,
1072                    implements: Some("ICellRendererAngularComp".to_string()),
1073                    members: vec!["refresh".to_string()],
1074                }),
1075                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1076                    extends: Some("BaseCommand".to_string()),
1077                    implements: Some("CanActivate".to_string()),
1078                    members: vec!["execute".to_string()],
1079                }),
1080            ]
1081        );
1082    }
1083
1084    #[test]
1085    fn deserialize_toml_minimal() {
1086        let toml_str = r#"
1087entry = ["src/index.ts"]
1088production = true
1089"#;
1090        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1091        assert_eq!(config.entry, vec!["src/index.ts"]);
1092        assert!(config.production);
1093    }
1094
1095    #[test]
1096    fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1097        // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1098        // key; the back-compat serde alias keeps those existing configs scoping
1099        // instead of silently dropping the (unknown) key and losing the patterns.
1100        let config: FallowConfig =
1101            toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1102        assert_eq!(
1103            config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1104            vec!["packages/*".to_string(), "apps/*".to_string()],
1105            "the `packages` alias must populate `patterns`"
1106        );
1107    }
1108
1109    #[test]
1110    fn deserialize_toml_per_analysis_production_mode() {
1111        let toml_str = r"
1112[production]
1113deadCode = false
1114health = true
1115dupes = false
1116";
1117        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1118        assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1119        assert!(config.production.for_analysis(ProductionAnalysis::Health));
1120        assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1121    }
1122
1123    #[test]
1124    fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1125        let err = toml::from_str::<FallowConfig>(
1126            r"
1127[production]
1128healthTypo = true
1129",
1130        )
1131        .unwrap_err();
1132        assert!(
1133            err.to_string().contains("healthTypo"),
1134            "error should name the unknown field: {err}"
1135        );
1136    }
1137
1138    #[test]
1139    fn deserialize_toml_with_inline_framework() {
1140        let toml_str = r#"
1141[[framework]]
1142name = "my-framework"
1143enablers = ["my-framework-pkg"]
1144entryPoints = ["src/routes/**/*.tsx"]
1145"#;
1146        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1147        assert_eq!(config.framework.len(), 1);
1148        assert_eq!(config.framework[0].name, "my-framework");
1149        assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1150        assert_eq!(
1151            config.framework[0].entry_points,
1152            vec!["src/routes/**/*.tsx"]
1153        );
1154    }
1155
1156    #[test]
1157    fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1158        let toml_str = r#"
1159[fix.catalog]
1160deletePrecedingComments = "never"
1161"#;
1162        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1163        assert_eq!(
1164            config.fix.catalog.delete_preceding_comments,
1165            CatalogPrecedingCommentPolicy::Never
1166        );
1167    }
1168
1169    #[test]
1170    fn deserialize_toml_with_workspace_config() {
1171        let toml_str = r#"
1172[workspaces]
1173patterns = ["packages/*", "apps/*"]
1174[workspaces.changedSince]
1175"packages/web" = "main"
1176"packages/legacy" = "release/2024.10"
1177"#;
1178        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1179        assert!(config.workspaces.is_some());
1180        let ws = config.workspaces.unwrap();
1181        assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1182        assert_eq!(ws.changed_since["packages/web"], "main");
1183        assert_eq!(ws.changed_since["packages/legacy"], "release/2024.10");
1184    }
1185
1186    #[test]
1187    fn deserialize_toml_with_ignore_exports() {
1188        let toml_str = r#"
1189[[ignoreExports]]
1190file = "src/types/**/*.ts"
1191exports = ["*"]
1192"#;
1193        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1194        assert_eq!(config.ignore_exports.len(), 1);
1195        assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1196        assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1197    }
1198
1199    #[test]
1200    fn deserialize_toml_used_class_members_supports_scoped_rules() {
1201        let toml_str = r#"
1202usedClassMembers = [
1203  { implements = "ICellRendererAngularComp", members = ["refresh"] },
1204  { extends = "BaseCommand", members = ["execute"] },
1205]
1206"#;
1207        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1208        assert_eq!(
1209            config.used_class_members,
1210            vec![
1211                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1212                    extends: None,
1213                    implements: Some("ICellRendererAngularComp".to_string()),
1214                    members: vec!["refresh".to_string()],
1215                }),
1216                UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1217                    extends: Some("BaseCommand".to_string()),
1218                    implements: None,
1219                    members: vec!["execute".to_string()],
1220                }),
1221            ]
1222        );
1223    }
1224
1225    #[test]
1226    fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1227        let result = serde_json::from_str::<FallowConfig>(
1228            r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1229        );
1230        assert!(
1231            result.is_err(),
1232            "unconstrained scoped rule should be rejected"
1233        );
1234    }
1235
1236    #[test]
1237    fn deserialize_ignore_exports_used_in_file_bool() {
1238        let config: FallowConfig =
1239            serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1240
1241        assert!(config.ignore_exports_used_in_file.suppresses(false));
1242        assert!(config.ignore_exports_used_in_file.suppresses(true));
1243    }
1244
1245    #[test]
1246    fn deserialize_ignore_exports_used_in_file_kind_form() {
1247        let config: FallowConfig =
1248            serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1249
1250        assert!(!config.ignore_exports_used_in_file.suppresses(false));
1251        assert!(config.ignore_exports_used_in_file.suppresses(true));
1252    }
1253
1254    #[test]
1255    fn deserialize_toml_deny_unknown_fields() {
1256        let toml_str = r"bogus_field = true";
1257        let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1258        assert!(result.is_err(), "unknown fields should be rejected");
1259    }
1260
1261    #[test]
1262    fn json_serialize_roundtrip() {
1263        let config = FallowConfig {
1264            entry: vec!["src/main.ts".to_string()],
1265            production: true.into(),
1266            ..FallowConfig::default()
1267        };
1268        let json = serde_json::to_string(&config).unwrap();
1269        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1270        assert_eq!(restored.entry, vec!["src/main.ts"]);
1271        assert!(restored.production);
1272    }
1273
1274    #[test]
1275    fn schema_field_not_serialized() {
1276        let config = FallowConfig {
1277            schema: Some("https://example.com/schema.json".to_string()),
1278            ..FallowConfig::default()
1279        };
1280        let json = serde_json::to_string(&config).unwrap();
1281        assert!(
1282            !json.contains("$schema"),
1283            "schema field should be skipped in serialization"
1284        );
1285    }
1286
1287    #[test]
1288    fn extends_field_not_serialized() {
1289        let config = FallowConfig {
1290            extends: vec!["base.json".to_string()],
1291            ..FallowConfig::default()
1292        };
1293        let json = serde_json::to_string(&config).unwrap();
1294        assert!(
1295            !json.contains("extends"),
1296            "extends field should be skipped in serialization"
1297        );
1298    }
1299
1300    #[test]
1301    fn regression_config_deserialize_json() {
1302        let json = r#"{
1303            "regression": {
1304                "baseline": {
1305                    "totalIssues": 42,
1306                    "unusedFiles": 10,
1307                    "unusedExports": 5,
1308                    "circularDependencies": 2
1309                }
1310            }
1311        }"#;
1312        let config: FallowConfig = serde_json::from_str(json).unwrap();
1313        let regression = config.regression.unwrap();
1314        let baseline = regression.baseline.unwrap();
1315        assert_eq!(baseline.total_issues, 42);
1316        assert_eq!(baseline.unused_files, 10);
1317        assert_eq!(baseline.unused_exports, 5);
1318        assert_eq!(baseline.circular_dependencies, 2);
1319        assert_eq!(baseline.unused_types, 0);
1320        assert_eq!(baseline.boundary_violations, 0);
1321    }
1322
1323    #[test]
1324    fn regression_config_defaults_to_none() {
1325        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1326        assert!(config.regression.is_none());
1327    }
1328
1329    #[test]
1330    fn regression_baseline_all_zeros_by_default() {
1331        let baseline = RegressionBaseline::default();
1332        assert_eq!(baseline.total_issues, 0);
1333        assert_eq!(baseline.unused_files, 0);
1334        assert_eq!(baseline.unused_exports, 0);
1335        assert_eq!(baseline.unused_types, 0);
1336        assert_eq!(baseline.unused_dependencies, 0);
1337        assert_eq!(baseline.unused_dev_dependencies, 0);
1338        assert_eq!(baseline.unused_optional_dependencies, 0);
1339        assert_eq!(baseline.unused_enum_members, 0);
1340        assert_eq!(baseline.unused_class_members, 0);
1341        assert_eq!(baseline.unresolved_imports, 0);
1342        assert_eq!(baseline.unlisted_dependencies, 0);
1343        assert_eq!(baseline.duplicate_exports, 0);
1344        assert_eq!(baseline.circular_dependencies, 0);
1345        assert_eq!(baseline.type_only_dependencies, 0);
1346        assert_eq!(baseline.test_only_dependencies, 0);
1347        assert_eq!(baseline.boundary_violations, 0);
1348    }
1349
1350    #[test]
1351    fn regression_config_serialize_roundtrip() {
1352        let baseline = RegressionBaseline {
1353            total_issues: 100,
1354            unused_files: 20,
1355            unused_exports: 30,
1356            ..RegressionBaseline::default()
1357        };
1358        let regression = RegressionConfig {
1359            baseline: Some(baseline),
1360        };
1361        let config = FallowConfig {
1362            regression: Some(regression),
1363            ..FallowConfig::default()
1364        };
1365        let json = serde_json::to_string(&config).unwrap();
1366        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1367        let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1368        assert_eq!(restored_baseline.total_issues, 100);
1369        assert_eq!(restored_baseline.unused_files, 20);
1370        assert_eq!(restored_baseline.unused_exports, 30);
1371        assert_eq!(restored_baseline.unused_types, 0);
1372    }
1373
1374    #[test]
1375    fn regression_config_empty_baseline_deserialize() {
1376        let json = r#"{"regression": {}}"#;
1377        let config: FallowConfig = serde_json::from_str(json).unwrap();
1378        let regression = config.regression.unwrap();
1379        assert!(regression.baseline.is_none());
1380    }
1381
1382    #[test]
1383    fn regression_baseline_not_serialized_when_none() {
1384        let config = FallowConfig {
1385            regression: None,
1386            ..FallowConfig::default()
1387        };
1388        let json = serde_json::to_string(&config).unwrap();
1389        assert!(
1390            !json.contains("regression"),
1391            "regression should be skipped when None"
1392        );
1393    }
1394
1395    #[test]
1396    fn deserialize_json_with_overrides() {
1397        let json = r#"{
1398            "overrides": [
1399                {
1400                    "files": ["*.test.ts", "*.spec.ts"],
1401                    "rules": {
1402                        "unused-exports": "off",
1403                        "unused-files": "warn"
1404                    }
1405                }
1406            ]
1407        }"#;
1408        let config: FallowConfig = serde_json::from_str(json).unwrap();
1409        assert_eq!(config.overrides.len(), 1);
1410        assert_eq!(config.overrides[0].files.len(), 2);
1411        assert_eq!(
1412            config.overrides[0].rules.unused_exports,
1413            Some(Severity::Off)
1414        );
1415        assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1416    }
1417
1418    #[test]
1419    fn deserialize_json_with_boundaries() {
1420        let json = r#"{
1421            "boundaries": {
1422                "preset": "layered"
1423            }
1424        }"#;
1425        let config: FallowConfig = serde_json::from_str(json).unwrap();
1426        assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1427    }
1428
1429    #[test]
1430    fn deserialize_toml_with_regression_baseline() {
1431        let toml_str = r"
1432[regression.baseline]
1433totalIssues = 50
1434unusedFiles = 10
1435unusedExports = 15
1436";
1437        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1438        let baseline = config.regression.unwrap().baseline.unwrap();
1439        assert_eq!(baseline.total_issues, 50);
1440        assert_eq!(baseline.unused_files, 10);
1441        assert_eq!(baseline.unused_exports, 15);
1442    }
1443
1444    #[test]
1445    fn deserialize_toml_with_overrides() {
1446        let toml_str = r#"
1447[[overrides]]
1448files = ["*.test.ts"]
1449
1450[overrides.rules]
1451unused-exports = "off"
1452
1453[[overrides]]
1454files = ["*.stories.tsx"]
1455
1456[overrides.rules]
1457unused-files = "off"
1458"#;
1459        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1460        assert_eq!(config.overrides.len(), 2);
1461        assert_eq!(
1462            config.overrides[0].rules.unused_exports,
1463            Some(Severity::Off)
1464        );
1465        assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1466    }
1467
1468    #[test]
1469    fn regression_config_default_is_none_baseline() {
1470        let config = RegressionConfig::default();
1471        assert!(config.baseline.is_none());
1472    }
1473
1474    #[test]
1475    fn deserialize_json_multiple_ignore_export_rules() {
1476        let json = r#"{
1477            "ignoreExports": [
1478                {"file": "src/types/**/*.ts", "exports": ["*"]},
1479                {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1480                {"file": "src/index.ts", "exports": ["default"]}
1481            ]
1482        }"#;
1483        let config: FallowConfig = serde_json::from_str(json).unwrap();
1484        assert_eq!(config.ignore_exports.len(), 3);
1485        assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1486    }
1487
1488    #[test]
1489    fn deserialize_json_public_packages_camel_case() {
1490        let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1491        let config: FallowConfig = serde_json::from_str(json).unwrap();
1492        assert_eq!(
1493            config.public_packages,
1494            vec!["@myorg/shared-lib", "@myorg/utils"]
1495        );
1496    }
1497
1498    #[test]
1499    fn deserialize_json_public_packages_rejects_snake_case() {
1500        let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1501        let result: Result<FallowConfig, _> = serde_json::from_str(json);
1502        assert!(
1503            result.is_err(),
1504            "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1505        );
1506    }
1507
1508    #[test]
1509    fn deserialize_json_public_packages_empty() {
1510        let config: FallowConfig = serde_json::from_str("{}").unwrap();
1511        assert!(config.public_packages.is_empty());
1512    }
1513
1514    #[test]
1515    fn deserialize_toml_public_packages() {
1516        let toml_str = r#"
1517publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1518"#;
1519        let config: FallowConfig = toml::from_str(toml_str).unwrap();
1520        assert_eq!(
1521            config.public_packages,
1522            vec!["@myorg/shared-lib", "@myorg/ui"]
1523        );
1524    }
1525
1526    #[test]
1527    fn public_packages_serialize_roundtrip() {
1528        let config = FallowConfig {
1529            public_packages: vec!["@myorg/shared-lib".to_string()],
1530            ..FallowConfig::default()
1531        };
1532        let json = serde_json::to_string(&config).unwrap();
1533        let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1534        assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1535    }
1536}