fallow_config/config/mod.rs
1mod boundaries;
2mod duplicates_config;
3mod finding_ignore;
4mod flags;
5mod format;
6pub mod glob_validation;
7mod health;
8mod parsing;
9mod resolution;
10mod resolve;
11mod rules;
12mod similar_code;
13mod used_class_members;
14
15#[expect(
16 clippy::redundant_pub_crate,
17 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"
18)]
19pub(crate) use boundaries::wildcard_placement_error;
20pub use boundaries::{
21 AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
22 BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
23 LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
24 ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
25 ZoneReferenceKind, ZoneValidationError,
26};
27pub use duplicates_config::{
28 DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
29};
30pub use finding_ignore::FindingIgnoreMatcher;
31pub use flags::{FlagsConfig, SdkPattern};
32pub use format::OutputFormat;
33pub use health::{EmailMode, HealthConfig, HealthThresholdOverride, OwnershipConfig};
34pub use parsing::ConfigLoadOptions;
35pub use resolution::{
36 AnalysisSnapshot, CompiledIgnoreCatalogReferenceRule, CompiledIgnoreDependencyOverrideRule,
37 CompiledIgnoreExportRule, ConfigOverride, DEFAULT_MAX_FILE_SIZE_BYTES,
38 DEFAULT_MAX_FILE_SIZE_MB, IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule,
39 IgnoreExportRule, ResolvedConfig, ResolvedOverride, resolve_max_file_size_bytes,
40};
41pub use resolve::ResolveConfig;
42pub use rules::{
43 KNOWN_RULE_NAMES, PartialRulesConfig, RulesConfig, Severity, closest_known_rule_name,
44 default_severity_for_kind, is_opt_in_kind,
45};
46pub use similar_code::SimilarCodeConfig;
47pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
48
49use schemars::JsonSchema;
50use serde::{Deserialize, Deserializer, Serialize};
51use std::ops::Not;
52use std::path::PathBuf;
53
54use crate::external_plugin::ExternalPluginDef;
55use crate::workspace::WorkspaceConfig;
56
57/// Value of the `ignoreExportsUsedInFile` config key: whether an export
58/// referenced elsewhere in its own file is suppressed from `unused-export`.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
60#[serde(untagged, rename_all = "camelCase")]
61pub enum IgnoreExportsUsedInFileConfig {
62 /// Blanket toggle: `true` suppresses any export with a same-file use,
63 /// regardless of kind. The default is `false`.
64 Bool(bool),
65 /// Knip-parity object form restricting the suppression to type-only
66 /// exports.
67 ByKind(IgnoreExportsUsedInFileByKind),
68}
69
70impl Default for IgnoreExportsUsedInFileConfig {
71 fn default() -> Self {
72 Self::Bool(false)
73 }
74}
75
76impl From<bool> for IgnoreExportsUsedInFileConfig {
77 fn from(value: bool) -> Self {
78 Self::Bool(value)
79 }
80}
81
82impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
83 fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
84 Self::ByKind(value)
85 }
86}
87
88impl IgnoreExportsUsedInFileConfig {
89 /// Whether any form of the same-file-use suppression is active (the bool
90 /// form is `true`, or either by-kind field is set).
91 #[must_use]
92 pub const fn is_enabled(self) -> bool {
93 match self {
94 Self::Bool(value) => value,
95 Self::ByKind(kind) => kind.type_ || kind.interface,
96 }
97 }
98
99 /// Whether an export with a same-file use should be suppressed, given
100 /// whether fallow classified it as type-only. The bool form suppresses
101 /// regardless of kind; the by-kind form suppresses type-only exports only.
102 #[must_use]
103 pub const fn suppresses(self, is_type_only: bool) -> bool {
104 match self {
105 Self::Bool(value) => value,
106 Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
107 }
108 }
109}
110
111/// Object form of `ignoreExportsUsedInFile` (`{ "type": ..., "interface": ... }`),
112/// restricting the same-file-use suppression to type-only exports.
113#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
114#[serde(rename_all = "camelCase")]
115pub struct IgnoreExportsUsedInFileByKind {
116 /// 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.
117 #[serde(default, rename = "type")]
118 pub type_: bool,
119 /// 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.
120 #[serde(default)]
121 pub interface: bool,
122}
123
124/// Options for the `unused-component-props` rule.
125///
126/// Lets a project exempt component props whose local destructure binding name
127/// matches a regex from `unused-component-props`, honoring the
128/// "accepted-but-intentionally-unused" leading-underscore convention (Svelte 5
129/// `$props()`, React destructure) that mirrors TypeScript `noUnusedParameters`
130/// and ESLint `@typescript-eslint/no-unused-vars` `varsIgnorePattern` /
131/// `argsIgnorePattern`. Opt-in; an unset `ignorePattern` leaves the rule's
132/// behavior unchanged.
133#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
134#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
135pub struct UnusedComponentPropsConfig {
136 /// Regex matched against each declared prop's LOCAL destructure binding name
137 /// (e.g. `_stage` in `let { stage: _stage } = $props()`), which falls back
138 /// to the public prop name when there is no alias. A prop whose local name
139 /// matches is treated as intentionally unused and never reported as
140 /// `unused-component-props`. Matching is unanchored (substring), like
141 /// ESLint's `RegExp.test`, so anchor with `^_` to match a leading
142 /// underscore. Compiled and validated at config load (an invalid regex fails
143 /// load). Applies to Vue, Svelte, Astro, and React/Preact props.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub ignore_pattern: Option<String>,
146}
147
148impl UnusedComponentPropsConfig {
149 /// True when no option is set, so serialization can omit the section.
150 #[must_use]
151 pub fn is_default(&self) -> bool {
152 self.ignore_pattern.is_none()
153 }
154}
155
156/// The `fix` config section: settings for `fallow fix` apply behavior.
157#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
158#[serde(rename_all = "camelCase")]
159pub struct FixConfig {
160 /// 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.
161 #[serde(default)]
162 pub catalog: CatalogFixConfig,
163}
164
165/// The `fix.catalog` section: how `fallow fix` cleans up unused
166/// `pnpm-workspace.yaml` catalog entries.
167#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
168#[serde(rename_all = "camelCase")]
169pub struct CatalogFixConfig {
170 /// 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.
171 #[serde(default)]
172 pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
173}
174
175/// Value of `fix.catalog.deletePrecedingComments`: what happens to comment
176/// lines directly above a catalog entry that `fallow fix` removes. A
177/// `fallow-keep` marker in the block always preserves it regardless of policy.
178#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
179#[serde(rename_all = "lowercase")]
180pub enum CatalogPrecedingCommentPolicy {
181 /// Delete the adjacent comment block only when heuristics attribute it to
182 /// the entry (preceded by a blank line or directly under the catalog
183 /// header) and it is not a section banner. The default.
184 #[default]
185 Auto,
186 /// Always delete the adjacent comment block with the entry.
187 Always,
188 /// Never delete preceding comments.
189 Never,
190}
191
192/// Completeness policy for opt-in TypeScript semantic analysis.
193#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
194#[serde(rename_all = "kebab-case")]
195pub enum TypeAwareRequire {
196 /// Keep conservative findings and report semantic gaps without failing.
197 #[default]
198 BestEffort,
199 /// Fail the quality gate when any requested semantic query is incomplete.
200 Complete,
201}
202
203impl From<TypeAwareRequire> for fallow_types::semantic::SemanticCompletenessRequirement {
204 fn from(value: TypeAwareRequire) -> Self {
205 match value {
206 TypeAwareRequire::BestEffort => Self::BestEffort,
207 TypeAwareRequire::Complete => Self::Complete,
208 }
209 }
210}
211
212/// Shared opt-in configuration for TypeScript semantic analysis.
213#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
214#[serde(deny_unknown_fields, rename_all = "camelCase")]
215pub struct TypeAwareConfig {
216 /// Enable the optional TypeScript semantic pass. Disabled by default.
217 #[serde(default)]
218 pub enabled: bool,
219 /// TypeScript project config paths, resolved relative to the project root.
220 #[serde(default, skip_serializing_if = "Vec::is_empty")]
221 pub projects: Vec<String>,
222 /// Decide whether partial semantic analysis is advisory or gating.
223 #[serde(default, skip_serializing_if = "is_default_type_aware_require")]
224 pub require: TypeAwareRequire,
225}
226
227#[expect(
228 clippy::trivially_copy_pass_by_ref,
229 reason = "serde skip_serializing_if callbacks receive field values by reference"
230)]
231fn is_default_type_aware_require(value: &TypeAwareRequire) -> bool {
232 matches!(value, TypeAwareRequire::BestEffort)
233}
234
235impl TypeAwareConfig {
236 /// True when the section equals its default (disabled, no projects,
237 /// best-effort), so serialization can omit it.
238 #[must_use]
239 pub fn is_default(&self) -> bool {
240 !self.enabled && self.projects.is_empty() && self.require == TypeAwareRequire::BestEffort
241 }
242}
243
244/// The user-facing fallow configuration as authored in `.fallowrc.json` /
245/// `.fallowrc.jsonc` / `fallow.toml` (or the `fallow` key of `package.json`).
246///
247/// Every field documents its serialized meaning, default, and precedence
248/// against CLI flags and environment variables where they exist.
249/// `FallowConfig::resolve` compiles the loaded config (globs, regexes,
250/// plugin and rule-pack discovery) into a [`ResolvedConfig`] for analysis.
251/// Unknown keys are rejected at load so typos fail loud.
252#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
253#[serde(deny_unknown_fields, rename_all = "camelCase")]
254pub struct FallowConfig {
255 /// 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.
256 #[serde(rename = "$schema", default, skip_serializing)]
257 pub schema: Option<String>,
258
259 /// 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.
260 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub minimum_version: Option<String>,
262
263 /// 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).
264 #[serde(default, skip_serializing)]
265 pub extends: Vec<String>,
266
267 /// 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.
268 #[serde(default)]
269 pub entry: Vec<String>,
270
271 /// 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.
272 #[serde(default)]
273 pub ignore_patterns: Vec<String>,
274
275 /// 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.
276 #[serde(default, skip_serializing_if = "Vec::is_empty")]
277 pub ignore_findings: Vec<String>,
278
279 /// 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.
280 #[serde(default)]
281 pub framework: Vec<ExternalPluginDef>,
282
283 /// Monorepo workspace configuration whose sole sub-key patterns (array of globs) adds workspace package roots beyond those discovered from package.json workspaces, pnpm-workspace.yaml, and tsconfig references. Optional and absent by default (discovery uses the manifests alone); set it only when workspaces live in directories the standard manifests do not declare.
284 #[serde(default)]
285 pub workspaces: Option<WorkspaceConfig>,
286
287 /// A list of exact package names 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; matching is exact string equality against the package name, not a glob.
288 #[serde(default)]
289 pub ignore_dependencies: Vec<String>,
290
291 /// 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.
292 #[serde(default)]
293 pub ignore_unresolved_imports: Vec<String>,
294
295 /// 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.
296 #[serde(default)]
297 pub ignore_exports: Vec<IgnoreExportRule>,
298
299 /// 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.
300 #[serde(default, skip_serializing_if = "Vec::is_empty")]
301 pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
302
303 /// 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"`.
304 #[serde(default, skip_serializing_if = "Vec::is_empty")]
305 pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
306
307 /// 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.
308 #[serde(default)]
309 pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
310
311 /// 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.
312 #[serde(default, skip_serializing_if = "Vec::is_empty")]
313 pub ignore_decorators: Vec<String>,
314
315 /// 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.
316 #[serde(default)]
317 pub used_class_members: Vec<UsedClassMemberRule>,
318
319 /// 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.
320 #[serde(default)]
321 pub duplicates: DuplicatesConfig,
322
323 /// Configures the explicit local `similar-code` candidate workflow:
324 /// `threshold` (0.80, model-specific cosine floor), `minLines` (3), and
325 /// additional `ignore` globs. Provider identity, setup, executables,
326 /// endpoints, credentials, and consent cannot be set by project config.
327 #[serde(default)]
328 pub similar_code: SimilarCodeConfig,
329
330 /// 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.
331 #[serde(default)]
332 pub health: HealthConfig,
333
334 /// Opts into TypeScript semantic analysis for project-wide symbol use,
335 /// provenance, API surface, symbol impact, and public-signature coupling.
336 /// This does not surface compiler diagnostics or typed lint rules.
337 #[serde(default, skip_serializing_if = "TypeAwareConfig::is_default")]
338 pub type_aware: TypeAwareConfig,
339
340 /// 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`, `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.
341 #[serde(default)]
342 pub rules: RulesConfig,
343
344 #[serde(
345 default,
346 skip_serializing_if = "UnusedComponentPropsConfig::is_default"
347 )]
348 /// 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).
349 pub unused_component_props: UnusedComponentPropsConfig,
350
351 /// 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).
352 #[serde(default)]
353 pub boundaries: BoundaryConfig,
354
355 /// 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.*` 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`).
356 #[serde(default)]
357 pub flags: FlagsConfig,
358
359 /// 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.
360 #[serde(default)]
361 pub security: SecurityConfig,
362
363 /// 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.
364 #[serde(default)]
365 pub fix: FixConfig,
366
367 /// 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.
368 #[serde(default)]
369 pub resolve: ResolveConfig,
370
371 /// 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).
372 #[serde(default)]
373 pub production: ProductionConfig,
374
375 /// 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).
376 #[serde(default)]
377 pub plugins: Vec<String>,
378
379 /// Paths to declarative rule-pack files (JSON or JSONC), relative to the
380 /// project root. Each pack declares `banned-call`, `banned-import`, or
381 /// `banned-effect` rules that report as `policy-violation` findings. Packs
382 /// are pure data: no project code is executed. Invalid or missing packs
383 /// fail config load.
384 #[serde(default, skip_serializing_if = "Vec::is_empty")]
385 pub rule_packs: Vec<String>,
386
387 /// 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.
388 #[serde(default)]
389 pub dynamically_loaded: Vec<String>,
390
391 /// 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).
392 #[serde(default)]
393 pub overrides: Vec<ConfigOverride>,
394
395 /// 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.
396 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub codeowners: Option<String>,
398
399 /// 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).
400 #[serde(default)]
401 pub public_packages: Vec<String>,
402
403 /// 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.
404 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub regression: Option<RegressionConfig>,
406
407 /// 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.
408 #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
409 pub audit: AuditConfig,
410
411 /// 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.
412 #[serde(default)]
413 pub sealed: bool,
414
415 /// 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.
416 #[serde(default)]
417 pub include_entry_exports: bool,
418
419 /// When true, drops Nuxt convention-based entry-pattern fallbacks: component fallbacks are dropped unless nuxt.config declares components:, and composable/util fallbacks are dropped unless it declares imports:, so genuinely-unreferenced convention files surface as unused-file. 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.
420 #[serde(default)]
421 pub auto_imports: bool,
422
423 /// 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`.
424 #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
425 pub cache: CacheConfig,
426}
427
428/// Scopes `fallow security` catalogue behavior. An absent category block admits
429/// every catalogue category. `hardcoded-secret` is include-required and only
430/// runs when explicitly listed in `security.categories.include`.
431#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
432#[serde(deny_unknown_fields, rename_all = "camelCase")]
433pub struct SecurityConfig {
434 /// Include/exclude filter over category ids (e.g. `dangerous-html`).
435 #[serde(default, skip_serializing_if = "Option::is_none")]
436 pub categories: Option<SecurityCategories>,
437 /// Additional project-local names for HTTP request objects. These names
438 /// extend the built-in receiver allowlist for `*.query`, `*.params`, and
439 /// `*.body` source patterns. They do not replace the built-ins and do not
440 /// gate `*.searchParams`, which intentionally stays ungated.
441 #[serde(default, skip_serializing_if = "Vec::is_empty")]
442 pub request_receivers: Vec<String>,
443}
444
445impl SecurityConfig {
446 /// The configured `requestReceivers` trimmed, lowercased, and deduplicated
447 /// in first-seen order, with empty entries dropped; the form the matcher
448 /// compares receiver names against (matching is case-insensitive).
449 #[must_use]
450 pub fn normalized_request_receivers(&self) -> Vec<String> {
451 let mut receivers = Vec::new();
452 for receiver in &self.request_receivers {
453 let normalized = receiver.trim().to_ascii_lowercase();
454 if !normalized.is_empty() && !receivers.contains(&normalized) {
455 receivers.push(normalized);
456 }
457 }
458 receivers
459 }
460
461 /// False when any configured receiver is empty or whitespace-only, which
462 /// config validation reports as an error instead of silently dropping it.
463 #[must_use]
464 pub fn request_receivers_are_valid(&self) -> bool {
465 self.request_receivers
466 .iter()
467 .all(|receiver| !receiver.trim().is_empty())
468 }
469}
470
471/// Include/exclude lists scoping the active security categories. When `include`
472/// is set, only those categories are active; `exclude` removes categories from
473/// the admitted set. Both unset admits catalogue categories. `hardcoded-secret`
474/// still requires explicit inclusion.
475#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
476#[serde(deny_unknown_fields, rename_all = "camelCase")]
477pub struct SecurityCategories {
478 /// Catalogue category ids to admit. When set, all others are excluded.
479 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub include: Option<Vec<String>>,
481 /// Catalogue category ids to remove from the admitted set.
482 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub exclude: Option<Vec<String>>,
484}
485
486/// The `cache` config section: location and size ceiling of fallow's
487/// persistent caches (default directory `<root>/.fallow`).
488#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
489#[serde(deny_unknown_fields, rename_all = "camelCase")]
490pub struct CacheConfig {
491 /// Directory for fallow's persistent analysis cache. Relative paths resolve
492 /// from the project root.
493 #[serde(default, skip_serializing_if = "Option::is_none")]
494 pub dir: Option<PathBuf>,
495 /// Maximum size of the persistent extraction cache, in megabytes.
496 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub max_size_mb: Option<u32>,
498}
499
500impl CacheConfig {
501 /// True when neither field is set, so serialization can omit the section.
502 #[must_use]
503 pub fn is_default(&self) -> bool {
504 self.dir.is_none() && self.max_size_mb.is_none()
505 }
506}
507
508/// The analysis families production mode can be scoped to independently via
509/// the object form of the `production` config key.
510#[derive(Debug, Clone, Copy, PartialEq, Eq)]
511pub enum ProductionAnalysis {
512 /// Unused files/exports/dependencies detection.
513 DeadCode,
514 /// Complexity and health scoring.
515 Health,
516 /// Clone detection.
517 Dupes,
518}
519
520/// Value of the `production` config key: excludes test/spec/story/dev files
521/// from discovery, either globally or per analysis family.
522#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
523#[serde(untagged)]
524pub enum ProductionConfig {
525 /// Boolean form applying to every analysis. The default is `false`.
526 Global(bool),
527 /// Object form (`{ deadCode?, health?, dupes? }`) scoping production mode
528 /// per analysis family.
529 PerAnalysis(PerAnalysisProductionConfig),
530}
531
532impl<'de> Deserialize<'de> for ProductionConfig {
533 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
534 where
535 D: Deserializer<'de>,
536 {
537 struct ProductionConfigVisitor;
538
539 impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
540 type Value = ProductionConfig;
541
542 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543 formatter.write_str("a boolean or per-analysis production config object")
544 }
545
546 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
547 where
548 E: serde::de::Error,
549 {
550 Ok(ProductionConfig::Global(value))
551 }
552
553 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
554 where
555 A: serde::de::MapAccess<'de>,
556 {
557 PerAnalysisProductionConfig::deserialize(
558 serde::de::value::MapAccessDeserializer::new(map),
559 )
560 .map(ProductionConfig::PerAnalysis)
561 }
562 }
563
564 deserializer.deserialize_any(ProductionConfigVisitor)
565 }
566}
567
568impl Default for ProductionConfig {
569 fn default() -> Self {
570 Self::Global(false)
571 }
572}
573
574impl From<bool> for ProductionConfig {
575 fn from(value: bool) -> Self {
576 Self::Global(value)
577 }
578}
579
580impl Not for ProductionConfig {
581 type Output = bool;
582
583 fn not(self) -> Self::Output {
584 !self.any_enabled()
585 }
586}
587
588impl ProductionConfig {
589 /// Whether production mode applies to `analysis` under this config.
590 #[must_use]
591 pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
592 match self {
593 Self::Global(value) => value,
594 Self::PerAnalysis(config) => match analysis {
595 ProductionAnalysis::DeadCode => config.dead_code,
596 ProductionAnalysis::Health => config.health,
597 ProductionAnalysis::Dupes => config.dupes,
598 },
599 }
600 }
601
602 /// The boolean form's value; `false` for the per-analysis form, which has
603 /// no global toggle.
604 #[must_use]
605 pub const fn global(self) -> bool {
606 match self {
607 Self::Global(value) => value,
608 Self::PerAnalysis(_) => false,
609 }
610 }
611
612 /// Whether production mode is enabled for at least one analysis family.
613 #[must_use]
614 pub const fn any_enabled(self) -> bool {
615 match self {
616 Self::Global(value) => value,
617 Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
618 }
619 }
620}
621
622/// Object form of the `production` config key, scoping production mode to
623/// individual analysis families in combined `fallow` and `fallow audit`.
624#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
625#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
626pub struct PerAnalysisProductionConfig {
627 /// 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.
628 pub dead_code: bool,
629 /// 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.
630 pub health: bool,
631 /// 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.
632 pub dupes: bool,
633}
634
635/// The `audit` config section: in-repo defaults for `fallow audit`, each
636/// overridable by its matching CLI flag.
637#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
638#[serde(rename_all = "camelCase")]
639pub struct AuditConfig {
640 /// 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.
641 #[serde(default, skip_serializing_if = "AuditGate::is_default")]
642 pub gate: AuditGate,
643
644 /// 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.
645 #[serde(default, skip_serializing_if = "Option::is_none")]
646 pub css: Option<bool>,
647
648 /// 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.
649 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub css_deep: Option<bool>,
651
652 /// 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`.
653 #[serde(default, skip_serializing_if = "Option::is_none")]
654 pub dead_code_baseline: Option<String>,
655
656 /// 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.
657 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub health_baseline: Option<String>,
659
660 /// 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.
661 #[serde(default, skip_serializing_if = "Option::is_none")]
662 pub dupes_baseline: Option<String>,
663
664 /// 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.
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub cache_max_age_days: Option<u32>,
667
668 /// 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.
669 #[serde(default, skip_serializing_if = "Option::is_none")]
670 pub type_aware: Option<bool>,
671}
672
673impl AuditConfig {
674 /// True when every field is unset, so serialization can omit the section.
675 #[must_use]
676 pub fn is_empty(&self) -> bool {
677 self.gate.is_default()
678 && self.css.is_none()
679 && self.css_deep.is_none()
680 && self.dead_code_baseline.is_none()
681 && self.health_baseline.is_none()
682 && self.dupes_baseline.is_none()
683 && self.cache_max_age_days.is_none()
684 && self.type_aware.is_none()
685 }
686}
687
688/// Value of `audit.gate`: which findings drive the `fallow audit` verdict.
689#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
690#[serde(rename_all = "kebab-case")]
691pub enum AuditGate {
692 /// Fail only on findings the current changeset introduced, determined by
693 /// a base-snapshot attribution pass. The default.
694 #[default]
695 NewOnly,
696 /// Fail on every finding in changed files, skipping the attribution pass.
697 All,
698}
699
700impl AuditGate {
701 /// True for the default `new-only` gate, so serialization can omit it.
702 #[must_use]
703 pub const fn is_default(&self) -> bool {
704 matches!(self, Self::NewOnly)
705 }
706}
707
708/// The `regression` config section holding the saved issue-count baseline for
709/// the `--fail-on-regression` gate.
710#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
711#[serde(rename_all = "camelCase")]
712pub struct RegressionConfig {
713 /// 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.
714 #[serde(default, skip_serializing_if = "Option::is_none")]
715 pub baseline: Option<RegressionBaseline>,
716}
717
718/// Saved per-issue-type counts written by `--save-baseline` and compared by
719/// `--fail-on-regression`. Every count defaults to `0` when its key is missing,
720/// so hand-trimmed baselines stay loadable.
721#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
722#[serde(rename_all = "camelCase")]
723pub struct RegressionBaseline {
724 /// Compatibility identity for the analysis that produced these counts.
725 /// Missing values in existing configs are treated as syntactic.
726 #[serde(default)]
727 pub analysis_identity: fallow_types::semantic::SemanticAnalysisIdentity,
728 /// Baseline count across all issue types.
729 #[serde(default)]
730 pub total_issues: usize,
731 /// Baseline count of `unused-files` findings.
732 #[serde(default)]
733 pub unused_files: usize,
734 /// Baseline count of `unused-exports` findings.
735 #[serde(default)]
736 pub unused_exports: usize,
737 /// Baseline count of `unused-types` findings.
738 #[serde(default)]
739 pub unused_types: usize,
740 /// Baseline count of `unused-dependencies` findings.
741 #[serde(default)]
742 pub unused_dependencies: usize,
743 /// Baseline count of `unused-dev-dependencies` findings.
744 #[serde(default)]
745 pub unused_dev_dependencies: usize,
746 /// Baseline count of `unused-optional-dependencies` findings.
747 #[serde(default)]
748 pub unused_optional_dependencies: usize,
749 /// Baseline count of `unused-enum-members` findings.
750 #[serde(default)]
751 pub unused_enum_members: usize,
752 /// Baseline count of `unused-class-members` findings.
753 #[serde(default)]
754 pub unused_class_members: usize,
755 /// Baseline count of `unresolved-imports` findings.
756 #[serde(default)]
757 pub unresolved_imports: usize,
758 /// Baseline count of `unlisted-dependencies` findings.
759 #[serde(default)]
760 pub unlisted_dependencies: usize,
761 /// Baseline count of `duplicate-exports` findings.
762 #[serde(default)]
763 pub duplicate_exports: usize,
764 /// Baseline count of `circular-dependencies` findings.
765 #[serde(default)]
766 pub circular_dependencies: usize,
767 /// Baseline count of `re-export-cycle` findings.
768 #[serde(default)]
769 pub re_export_cycles: usize,
770 /// Baseline count of `type-only-dependencies` findings.
771 #[serde(default)]
772 pub type_only_dependencies: usize,
773 /// Baseline count of `test-only-dependencies` findings.
774 #[serde(default)]
775 pub test_only_dependencies: usize,
776 /// Baseline count of `dev-dependencies-in-production` findings.
777 #[serde(default)]
778 pub dev_dependencies_in_production: usize,
779 /// Baseline count of `boundary-violation` findings.
780 #[serde(default)]
781 pub boundary_violations: usize,
782 /// Baseline count of boundary-coverage-violation findings.
783 #[serde(default)]
784 pub boundary_coverage_violations: usize,
785 /// Baseline count of boundary-call-violation findings.
786 #[serde(default)]
787 pub boundary_call_violations: usize,
788 /// Baseline count of `policy-violation` findings.
789 #[serde(default)]
790 pub policy_violations: usize,
791}
792
793#[cfg(test)]
794mod tests {
795 use super::*;
796
797 #[test]
798 fn default_config_has_empty_collections() {
799 let config = FallowConfig::default();
800 assert!(config.schema.is_none());
801 assert!(config.extends.is_empty());
802 assert!(config.entry.is_empty());
803 assert!(config.ignore_patterns.is_empty());
804 assert!(config.ignore_findings.is_empty());
805 assert!(config.framework.is_empty());
806 assert!(config.workspaces.is_none());
807 assert!(config.ignore_dependencies.is_empty());
808 assert!(config.ignore_exports.is_empty());
809 assert!(config.used_class_members.is_empty());
810 assert!(config.plugins.is_empty());
811 assert!(config.dynamically_loaded.is_empty());
812 assert!(config.overrides.is_empty());
813 assert!(config.public_packages.is_empty());
814 assert_eq!(
815 config.fix.catalog.delete_preceding_comments,
816 CatalogPrecedingCommentPolicy::Auto
817 );
818 assert!(!config.production);
819 }
820
821 #[test]
822 fn default_config_rules_are_error() {
823 let config = FallowConfig::default();
824 assert_eq!(config.rules.unused_files, Severity::Error);
825 assert_eq!(config.rules.unused_exports, Severity::Error);
826 assert_eq!(config.rules.unused_dependencies, Severity::Error);
827 }
828
829 #[test]
830 fn default_config_duplicates_enabled() {
831 let config = FallowConfig::default();
832 assert!(config.duplicates.enabled);
833 assert_eq!(config.duplicates.min_tokens, 50);
834 assert_eq!(config.duplicates.min_lines, 5);
835 }
836
837 #[test]
838 fn default_config_health_thresholds() {
839 let config = FallowConfig::default();
840 assert_eq!(config.health.max_cyclomatic, 20);
841 assert_eq!(config.health.max_cognitive, 15);
842 }
843
844 #[test]
845 fn deserialize_empty_json_object() {
846 let config: FallowConfig = serde_json::from_str("{}").unwrap();
847 assert!(config.entry.is_empty());
848 assert!(!config.production);
849 assert!(!config.type_aware.enabled);
850 assert_eq!(config.type_aware.require, TypeAwareRequire::BestEffort);
851 }
852
853 #[test]
854 fn deserialize_type_aware_config() {
855 let config: FallowConfig = serde_json::from_str(
856 r#"{"typeAware":{"enabled":true,"projects":["tsconfig.app.json"],"require":"complete"}}"#,
857 )
858 .unwrap();
859
860 assert!(config.type_aware.enabled);
861 assert_eq!(config.type_aware.projects, ["tsconfig.app.json"]);
862 assert_eq!(config.type_aware.require, TypeAwareRequire::Complete);
863 }
864
865 #[test]
866 fn deserialize_type_aware_config_rejects_unknown_fields() {
867 let result = serde_json::from_str::<FallowConfig>(
868 r#"{"typeAware":{"enabled":true,"compilerDiagnostics":true}}"#,
869 );
870 assert!(result.is_err());
871 }
872
873 #[test]
874 fn deserialize_json_with_all_top_level_fields() {
875 let json = r#"{
876 "$schema": "./node_modules/fallow/schema.json",
877 "entry": ["src/main.ts"],
878 "ignorePatterns": ["generated/**"],
879 "ignoreFindings": ["**/*.test.ts", "!src/public/**"],
880 "ignoreDependencies": ["postcss"],
881 "production": true,
882 "plugins": ["custom-plugin.toml"],
883 "rules": {"unused-files": "warn"},
884 "duplicates": {"enabled": false},
885 "health": {"maxCyclomatic": 30}
886 }"#;
887 let config: FallowConfig = serde_json::from_str(json).unwrap();
888 assert_eq!(
889 config.schema.as_deref(),
890 Some("./node_modules/fallow/schema.json")
891 );
892 assert_eq!(config.entry, vec!["src/main.ts"]);
893 assert_eq!(config.ignore_patterns, vec!["generated/**"]);
894 assert_eq!(
895 config.ignore_findings,
896 vec!["**/*.test.ts", "!src/public/**"]
897 );
898 assert_eq!(config.ignore_dependencies, vec!["postcss"]);
899 assert!(config.production);
900 assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
901 assert_eq!(config.rules.unused_files, Severity::Warn);
902 assert!(!config.duplicates.enabled);
903 assert_eq!(config.health.max_cyclomatic, 30);
904 }
905
906 #[test]
907 fn deserialize_json_deny_unknown_fields() {
908 let json = r#"{"unknownField": true}"#;
909 let result: Result<FallowConfig, _> = serde_json::from_str(json);
910 assert!(result.is_err(), "unknown fields should be rejected");
911 }
912
913 #[test]
914 fn ignore_findings_serialization_is_canonical_and_sparse() {
915 let default_value = serde_json::to_value(FallowConfig::default()).unwrap();
916 assert!(default_value.get("ignoreFindings").is_none());
917
918 let config = FallowConfig {
919 ignore_findings: vec!["**/*.test.ts".to_string(), "!src/public/**".to_string()],
920 ..Default::default()
921 };
922 let value = serde_json::to_value(config).unwrap();
923 assert_eq!(
924 value.get("ignoreFindings"),
925 Some(&serde_json::json!(["**/*.test.ts", "!src/public/**"]))
926 );
927 }
928
929 #[test]
930 fn ignore_findings_deserializes_from_toml() {
931 let config: FallowConfig =
932 toml::from_str(r#"ignoreFindings = ["**/*.test.ts", "!src/public/**"]"#).unwrap();
933
934 assert_eq!(
935 config.ignore_findings,
936 vec!["**/*.test.ts", "!src/public/**"]
937 );
938 }
939
940 #[test]
941 fn generic_ignore_alias_is_rejected() {
942 let result = serde_json::from_str::<FallowConfig>(r#"{"ignore": ["**/*.test.ts"]}"#);
943
944 assert!(result.is_err());
945 }
946
947 #[test]
948 fn deserialize_json_production_mode_default_false() {
949 let config: FallowConfig = serde_json::from_str("{}").unwrap();
950 assert!(!config.production);
951 }
952
953 #[test]
954 fn deserialize_json_production_mode_true() {
955 let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
956 assert!(config.production);
957 }
958
959 #[test]
960 fn deserialize_json_per_analysis_production_mode() {
961 let config: FallowConfig = serde_json::from_str(
962 r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
963 )
964 .unwrap();
965 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
966 assert!(config.production.for_analysis(ProductionAnalysis::Health));
967 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
968 }
969
970 #[test]
971 fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
972 let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
973 .unwrap_err();
974 assert!(
975 err.to_string().contains("healthTypo"),
976 "error should name the unknown field: {err}"
977 );
978 }
979
980 #[test]
981 fn deserialize_json_dynamically_loaded() {
982 let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
983 let config: FallowConfig = serde_json::from_str(json).unwrap();
984 assert_eq!(
985 config.dynamically_loaded,
986 vec!["plugins/**/*.ts", "locales/**/*.json"]
987 );
988 }
989
990 #[test]
991 fn deserialize_json_dynamically_loaded_defaults_empty() {
992 let config: FallowConfig = serde_json::from_str("{}").unwrap();
993 assert!(config.dynamically_loaded.is_empty());
994 }
995
996 #[test]
997 fn deserialize_json_fix_catalog_delete_preceding_comments() {
998 let config: FallowConfig =
999 serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
1000 .unwrap();
1001 assert_eq!(
1002 config.fix.catalog.delete_preceding_comments,
1003 CatalogPrecedingCommentPolicy::Always
1004 );
1005 }
1006
1007 #[test]
1008 fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
1009 let err = serde_json::from_str::<FallowConfig>(
1010 r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
1011 )
1012 .unwrap_err();
1013 assert!(
1014 err.to_string().contains("sometimes"),
1015 "error should name the bad policy: {err}"
1016 );
1017 }
1018
1019 #[test]
1020 fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
1021 let json = r#"{
1022 "usedClassMembers": [
1023 "agInit",
1024 { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
1025 { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
1026 ]
1027 }"#;
1028 let config: FallowConfig = serde_json::from_str(json).unwrap();
1029 assert_eq!(
1030 config.used_class_members,
1031 vec![
1032 UsedClassMemberRule::from("agInit"),
1033 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1034 extends: None,
1035 implements: Some("ICellRendererAngularComp".to_string()),
1036 members: vec!["refresh".to_string()],
1037 }),
1038 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1039 extends: Some("BaseCommand".to_string()),
1040 implements: Some("CanActivate".to_string()),
1041 members: vec!["execute".to_string()],
1042 }),
1043 ]
1044 );
1045 }
1046
1047 #[test]
1048 fn deserialize_toml_minimal() {
1049 let toml_str = r#"
1050entry = ["src/index.ts"]
1051production = true
1052"#;
1053 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1054 assert_eq!(config.entry, vec!["src/index.ts"]);
1055 assert!(config.production);
1056 }
1057
1058 #[test]
1059 fn workspaces_packages_key_is_accepted_as_patterns_alias() {
1060 // An older `fallow init --toml` wrote `[workspaces]` with a `packages`
1061 // key; the back-compat serde alias keeps those existing configs scoping
1062 // instead of silently dropping the (unknown) key and losing the patterns.
1063 let config: FallowConfig =
1064 toml::from_str("[workspaces]\npackages = [\"packages/*\", \"apps/*\"]").unwrap();
1065 assert_eq!(
1066 config.workspaces.map(|w| w.patterns).unwrap_or_default(),
1067 vec!["packages/*".to_string(), "apps/*".to_string()],
1068 "the `packages` alias must populate `patterns`"
1069 );
1070 }
1071
1072 #[test]
1073 fn deserialize_toml_per_analysis_production_mode() {
1074 let toml_str = r"
1075[production]
1076deadCode = false
1077health = true
1078dupes = false
1079";
1080 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1081 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
1082 assert!(config.production.for_analysis(ProductionAnalysis::Health));
1083 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
1084 }
1085
1086 #[test]
1087 fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
1088 let err = toml::from_str::<FallowConfig>(
1089 r"
1090[production]
1091healthTypo = true
1092",
1093 )
1094 .unwrap_err();
1095 assert!(
1096 err.to_string().contains("healthTypo"),
1097 "error should name the unknown field: {err}"
1098 );
1099 }
1100
1101 #[test]
1102 fn deserialize_toml_with_inline_framework() {
1103 let toml_str = r#"
1104[[framework]]
1105name = "my-framework"
1106enablers = ["my-framework-pkg"]
1107entryPoints = ["src/routes/**/*.tsx"]
1108"#;
1109 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1110 assert_eq!(config.framework.len(), 1);
1111 assert_eq!(config.framework[0].name, "my-framework");
1112 assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
1113 assert_eq!(
1114 config.framework[0].entry_points,
1115 vec!["src/routes/**/*.tsx"]
1116 );
1117 }
1118
1119 #[test]
1120 fn deserialize_toml_fix_catalog_delete_preceding_comments() {
1121 let toml_str = r#"
1122[fix.catalog]
1123deletePrecedingComments = "never"
1124"#;
1125 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1126 assert_eq!(
1127 config.fix.catalog.delete_preceding_comments,
1128 CatalogPrecedingCommentPolicy::Never
1129 );
1130 }
1131
1132 #[test]
1133 fn deserialize_toml_with_workspace_config() {
1134 let toml_str = r#"
1135[workspaces]
1136patterns = ["packages/*", "apps/*"]
1137"#;
1138 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1139 assert!(config.workspaces.is_some());
1140 let ws = config.workspaces.unwrap();
1141 assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
1142 }
1143
1144 #[test]
1145 fn deserialize_toml_with_ignore_exports() {
1146 let toml_str = r#"
1147[[ignoreExports]]
1148file = "src/types/**/*.ts"
1149exports = ["*"]
1150"#;
1151 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1152 assert_eq!(config.ignore_exports.len(), 1);
1153 assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
1154 assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
1155 }
1156
1157 #[test]
1158 fn deserialize_toml_used_class_members_supports_scoped_rules() {
1159 let toml_str = r#"
1160usedClassMembers = [
1161 { implements = "ICellRendererAngularComp", members = ["refresh"] },
1162 { extends = "BaseCommand", members = ["execute"] },
1163]
1164"#;
1165 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1166 assert_eq!(
1167 config.used_class_members,
1168 vec![
1169 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1170 extends: None,
1171 implements: Some("ICellRendererAngularComp".to_string()),
1172 members: vec!["refresh".to_string()],
1173 }),
1174 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
1175 extends: Some("BaseCommand".to_string()),
1176 implements: None,
1177 members: vec!["execute".to_string()],
1178 }),
1179 ]
1180 );
1181 }
1182
1183 #[test]
1184 fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
1185 let result = serde_json::from_str::<FallowConfig>(
1186 r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
1187 );
1188 assert!(
1189 result.is_err(),
1190 "unconstrained scoped rule should be rejected"
1191 );
1192 }
1193
1194 #[test]
1195 fn deserialize_ignore_exports_used_in_file_bool() {
1196 let config: FallowConfig =
1197 serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
1198
1199 assert!(config.ignore_exports_used_in_file.suppresses(false));
1200 assert!(config.ignore_exports_used_in_file.suppresses(true));
1201 }
1202
1203 #[test]
1204 fn deserialize_ignore_exports_used_in_file_kind_form() {
1205 let config: FallowConfig =
1206 serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
1207
1208 assert!(!config.ignore_exports_used_in_file.suppresses(false));
1209 assert!(config.ignore_exports_used_in_file.suppresses(true));
1210 }
1211
1212 #[test]
1213 fn deserialize_toml_deny_unknown_fields() {
1214 let toml_str = r"bogus_field = true";
1215 let result: Result<FallowConfig, _> = toml::from_str(toml_str);
1216 assert!(result.is_err(), "unknown fields should be rejected");
1217 }
1218
1219 #[test]
1220 fn json_serialize_roundtrip() {
1221 let config = FallowConfig {
1222 entry: vec!["src/main.ts".to_string()],
1223 production: true.into(),
1224 ..FallowConfig::default()
1225 };
1226 let json = serde_json::to_string(&config).unwrap();
1227 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1228 assert_eq!(restored.entry, vec!["src/main.ts"]);
1229 assert!(restored.production);
1230 }
1231
1232 #[test]
1233 fn schema_field_not_serialized() {
1234 let config = FallowConfig {
1235 schema: Some("https://example.com/schema.json".to_string()),
1236 ..FallowConfig::default()
1237 };
1238 let json = serde_json::to_string(&config).unwrap();
1239 assert!(
1240 !json.contains("$schema"),
1241 "schema field should be skipped in serialization"
1242 );
1243 }
1244
1245 #[test]
1246 fn extends_field_not_serialized() {
1247 let config = FallowConfig {
1248 extends: vec!["base.json".to_string()],
1249 ..FallowConfig::default()
1250 };
1251 let json = serde_json::to_string(&config).unwrap();
1252 assert!(
1253 !json.contains("extends"),
1254 "extends field should be skipped in serialization"
1255 );
1256 }
1257
1258 #[test]
1259 fn regression_config_deserialize_json() {
1260 let json = r#"{
1261 "regression": {
1262 "baseline": {
1263 "totalIssues": 42,
1264 "unusedFiles": 10,
1265 "unusedExports": 5,
1266 "circularDependencies": 2
1267 }
1268 }
1269 }"#;
1270 let config: FallowConfig = serde_json::from_str(json).unwrap();
1271 let regression = config.regression.unwrap();
1272 let baseline = regression.baseline.unwrap();
1273 assert_eq!(baseline.total_issues, 42);
1274 assert_eq!(baseline.unused_files, 10);
1275 assert_eq!(baseline.unused_exports, 5);
1276 assert_eq!(baseline.circular_dependencies, 2);
1277 assert_eq!(baseline.unused_types, 0);
1278 assert_eq!(baseline.boundary_violations, 0);
1279 }
1280
1281 #[test]
1282 fn regression_config_defaults_to_none() {
1283 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1284 assert!(config.regression.is_none());
1285 }
1286
1287 #[test]
1288 fn regression_baseline_all_zeros_by_default() {
1289 let baseline = RegressionBaseline::default();
1290 assert_eq!(baseline.total_issues, 0);
1291 assert_eq!(baseline.unused_files, 0);
1292 assert_eq!(baseline.unused_exports, 0);
1293 assert_eq!(baseline.unused_types, 0);
1294 assert_eq!(baseline.unused_dependencies, 0);
1295 assert_eq!(baseline.unused_dev_dependencies, 0);
1296 assert_eq!(baseline.unused_optional_dependencies, 0);
1297 assert_eq!(baseline.unused_enum_members, 0);
1298 assert_eq!(baseline.unused_class_members, 0);
1299 assert_eq!(baseline.unresolved_imports, 0);
1300 assert_eq!(baseline.unlisted_dependencies, 0);
1301 assert_eq!(baseline.duplicate_exports, 0);
1302 assert_eq!(baseline.circular_dependencies, 0);
1303 assert_eq!(baseline.type_only_dependencies, 0);
1304 assert_eq!(baseline.test_only_dependencies, 0);
1305 assert_eq!(baseline.boundary_violations, 0);
1306 }
1307
1308 #[test]
1309 fn regression_config_serialize_roundtrip() {
1310 let baseline = RegressionBaseline {
1311 total_issues: 100,
1312 unused_files: 20,
1313 unused_exports: 30,
1314 ..RegressionBaseline::default()
1315 };
1316 let regression = RegressionConfig {
1317 baseline: Some(baseline),
1318 };
1319 let config = FallowConfig {
1320 regression: Some(regression),
1321 ..FallowConfig::default()
1322 };
1323 let json = serde_json::to_string(&config).unwrap();
1324 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1325 let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1326 assert_eq!(restored_baseline.total_issues, 100);
1327 assert_eq!(restored_baseline.unused_files, 20);
1328 assert_eq!(restored_baseline.unused_exports, 30);
1329 assert_eq!(restored_baseline.unused_types, 0);
1330 }
1331
1332 #[test]
1333 fn regression_config_empty_baseline_deserialize() {
1334 let json = r#"{"regression": {}}"#;
1335 let config: FallowConfig = serde_json::from_str(json).unwrap();
1336 let regression = config.regression.unwrap();
1337 assert!(regression.baseline.is_none());
1338 }
1339
1340 #[test]
1341 fn regression_baseline_not_serialized_when_none() {
1342 let config = FallowConfig {
1343 regression: None,
1344 ..FallowConfig::default()
1345 };
1346 let json = serde_json::to_string(&config).unwrap();
1347 assert!(
1348 !json.contains("regression"),
1349 "regression should be skipped when None"
1350 );
1351 }
1352
1353 #[test]
1354 fn deserialize_json_with_overrides() {
1355 let json = r#"{
1356 "overrides": [
1357 {
1358 "files": ["*.test.ts", "*.spec.ts"],
1359 "rules": {
1360 "unused-exports": "off",
1361 "unused-files": "warn"
1362 }
1363 }
1364 ]
1365 }"#;
1366 let config: FallowConfig = serde_json::from_str(json).unwrap();
1367 assert_eq!(config.overrides.len(), 1);
1368 assert_eq!(config.overrides[0].files.len(), 2);
1369 assert_eq!(
1370 config.overrides[0].rules.unused_exports,
1371 Some(Severity::Off)
1372 );
1373 assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1374 }
1375
1376 #[test]
1377 fn deserialize_json_with_boundaries() {
1378 let json = r#"{
1379 "boundaries": {
1380 "preset": "layered"
1381 }
1382 }"#;
1383 let config: FallowConfig = serde_json::from_str(json).unwrap();
1384 assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1385 }
1386
1387 #[test]
1388 fn deserialize_toml_with_regression_baseline() {
1389 let toml_str = r"
1390[regression.baseline]
1391totalIssues = 50
1392unusedFiles = 10
1393unusedExports = 15
1394";
1395 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1396 let baseline = config.regression.unwrap().baseline.unwrap();
1397 assert_eq!(baseline.total_issues, 50);
1398 assert_eq!(baseline.unused_files, 10);
1399 assert_eq!(baseline.unused_exports, 15);
1400 }
1401
1402 #[test]
1403 fn deserialize_toml_with_overrides() {
1404 let toml_str = r#"
1405[[overrides]]
1406files = ["*.test.ts"]
1407
1408[overrides.rules]
1409unused-exports = "off"
1410
1411[[overrides]]
1412files = ["*.stories.tsx"]
1413
1414[overrides.rules]
1415unused-files = "off"
1416"#;
1417 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1418 assert_eq!(config.overrides.len(), 2);
1419 assert_eq!(
1420 config.overrides[0].rules.unused_exports,
1421 Some(Severity::Off)
1422 );
1423 assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1424 }
1425
1426 #[test]
1427 fn regression_config_default_is_none_baseline() {
1428 let config = RegressionConfig::default();
1429 assert!(config.baseline.is_none());
1430 }
1431
1432 #[test]
1433 fn deserialize_json_multiple_ignore_export_rules() {
1434 let json = r#"{
1435 "ignoreExports": [
1436 {"file": "src/types/**/*.ts", "exports": ["*"]},
1437 {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1438 {"file": "src/index.ts", "exports": ["default"]}
1439 ]
1440 }"#;
1441 let config: FallowConfig = serde_json::from_str(json).unwrap();
1442 assert_eq!(config.ignore_exports.len(), 3);
1443 assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1444 }
1445
1446 #[test]
1447 fn deserialize_json_public_packages_camel_case() {
1448 let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1449 let config: FallowConfig = serde_json::from_str(json).unwrap();
1450 assert_eq!(
1451 config.public_packages,
1452 vec!["@myorg/shared-lib", "@myorg/utils"]
1453 );
1454 }
1455
1456 #[test]
1457 fn deserialize_json_public_packages_rejects_snake_case() {
1458 let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1459 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1460 assert!(
1461 result.is_err(),
1462 "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1463 );
1464 }
1465
1466 #[test]
1467 fn deserialize_json_public_packages_empty() {
1468 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1469 assert!(config.public_packages.is_empty());
1470 }
1471
1472 #[test]
1473 fn deserialize_toml_public_packages() {
1474 let toml_str = r#"
1475publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1476"#;
1477 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1478 assert_eq!(
1479 config.public_packages,
1480 vec!["@myorg/shared-lib", "@myorg/ui"]
1481 );
1482 }
1483
1484 #[test]
1485 fn public_packages_serialize_roundtrip() {
1486 let config = FallowConfig {
1487 public_packages: vec!["@myorg/shared-lib".to_string()],
1488 ..FallowConfig::default()
1489 };
1490 let json = serde_json::to_string(&config).unwrap();
1491 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1492 assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1493 }
1494}