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