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