1mod boundaries;
2mod duplicates_config;
3mod flags;
4mod format;
5pub mod glob_validation;
6mod health;
7mod parsing;
8mod resolution;
9mod resolve;
10mod rules;
11mod used_class_members;
12
13#[expect(
14 clippy::redundant_pub_crate,
15 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"
16)]
17pub(crate) use boundaries::wildcard_placement_error;
18pub use boundaries::{
19 AuthoredRule, BoundaryCallsConfig, BoundaryConfig, BoundaryCoverageConfig, BoundaryPreset,
20 BoundaryRule, BoundaryZone, ForbiddenCallRule, ForbiddenCallee, InvalidForbiddenCallee,
21 LogicalGroup, LogicalGroupStatus, RedundantRootPrefix, ResolvedBoundaryConfig,
22 ResolvedBoundaryCoverageConfig, ResolvedBoundaryRule, ResolvedZone, UnknownZoneRef,
23 ZoneReferenceKind, ZoneValidationError,
24};
25pub use duplicates_config::{
26 DetectionMode, DuplicatesConfig, NormalizationConfig, ResolvedNormalization,
27};
28pub use flags::{FlagsConfig, SdkPattern};
29pub use format::OutputFormat;
30pub use health::{EmailMode, HealthConfig, HealthThresholdOverride, OwnershipConfig};
31pub use resolution::{
32 CompiledIgnoreCatalogReferenceRule, CompiledIgnoreDependencyOverrideRule,
33 CompiledIgnoreExportRule, ConfigOverride, DEFAULT_MAX_FILE_SIZE_BYTES,
34 DEFAULT_MAX_FILE_SIZE_MB, IgnoreCatalogReferenceRule, IgnoreDependencyOverrideRule,
35 IgnoreExportRule, ResolvedConfig, ResolvedOverride, resolve_max_file_size_bytes,
36};
37pub use resolve::ResolveConfig;
38pub use rules::{PartialRulesConfig, RulesConfig, Severity};
39pub use used_class_members::{ScopedUsedClassMemberRule, UsedClassMemberRule};
40
41use schemars::JsonSchema;
42use serde::{Deserialize, Deserializer, Serialize};
43use std::ops::Not;
44use std::path::PathBuf;
45
46use crate::external_plugin::ExternalPluginDef;
47use crate::workspace::WorkspaceConfig;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
50#[serde(untagged, rename_all = "camelCase")]
51pub enum IgnoreExportsUsedInFileConfig {
52 Bool(bool),
53 ByKind(IgnoreExportsUsedInFileByKind),
54}
55
56impl Default for IgnoreExportsUsedInFileConfig {
57 fn default() -> Self {
58 Self::Bool(false)
59 }
60}
61
62impl From<bool> for IgnoreExportsUsedInFileConfig {
63 fn from(value: bool) -> Self {
64 Self::Bool(value)
65 }
66}
67
68impl From<IgnoreExportsUsedInFileByKind> for IgnoreExportsUsedInFileConfig {
69 fn from(value: IgnoreExportsUsedInFileByKind) -> Self {
70 Self::ByKind(value)
71 }
72}
73
74impl IgnoreExportsUsedInFileConfig {
75 #[must_use]
76 pub const fn is_enabled(self) -> bool {
77 match self {
78 Self::Bool(value) => value,
79 Self::ByKind(kind) => kind.type_ || kind.interface,
80 }
81 }
82
83 #[must_use]
84 pub const fn suppresses(self, is_type_only: bool) -> bool {
85 match self {
86 Self::Bool(value) => value,
87 Self::ByKind(kind) => is_type_only && (kind.type_ || kind.interface),
88 }
89 }
90}
91
92#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
93#[serde(rename_all = "camelCase")]
94pub struct IgnoreExportsUsedInFileByKind {
95 #[serde(default, rename = "type")]
96 pub type_: bool,
97 #[serde(default)]
98 pub interface: bool,
99}
100
101#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
111#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
112pub struct UnusedComponentPropsConfig {
113 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub ignore_pattern: Option<String>,
123}
124
125impl UnusedComponentPropsConfig {
126 #[must_use]
127 pub fn is_default(&self) -> bool {
128 self.ignore_pattern.is_none()
129 }
130}
131
132#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
133#[serde(rename_all = "camelCase")]
134pub struct FixConfig {
135 #[serde(default)]
136 pub catalog: CatalogFixConfig,
137}
138
139#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
140#[serde(rename_all = "camelCase")]
141pub struct CatalogFixConfig {
142 #[serde(default)]
143 pub delete_preceding_comments: CatalogPrecedingCommentPolicy,
144}
145
146#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
147#[serde(rename_all = "lowercase")]
148pub enum CatalogPrecedingCommentPolicy {
149 #[default]
150 Auto,
151 Always,
152 Never,
153}
154
155#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
156#[serde(deny_unknown_fields, rename_all = "camelCase")]
157pub struct FallowConfig {
158 #[serde(rename = "$schema", default, skip_serializing)]
159 pub schema: Option<String>,
160
161 #[serde(default, skip_serializing)]
162 pub extends: Vec<String>,
163
164 #[serde(default)]
165 pub entry: Vec<String>,
166
167 #[serde(default)]
168 pub ignore_patterns: Vec<String>,
169
170 #[serde(default)]
171 pub framework: Vec<ExternalPluginDef>,
172
173 #[serde(default)]
174 pub workspaces: Option<WorkspaceConfig>,
175
176 #[serde(default)]
177 pub ignore_dependencies: Vec<String>,
178
179 #[serde(default)]
180 pub ignore_unresolved_imports: Vec<String>,
181
182 #[serde(default)]
183 pub ignore_exports: Vec<IgnoreExportRule>,
184
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
186 pub ignore_catalog_references: Vec<IgnoreCatalogReferenceRule>,
187
188 #[serde(default, skip_serializing_if = "Vec::is_empty")]
189 pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
190
191 #[serde(default)]
192 pub ignore_exports_used_in_file: IgnoreExportsUsedInFileConfig,
193
194 #[serde(default, skip_serializing_if = "Vec::is_empty")]
195 pub ignore_decorators: Vec<String>,
196
197 #[serde(default)]
198 pub used_class_members: Vec<UsedClassMemberRule>,
199
200 #[serde(default)]
201 pub duplicates: DuplicatesConfig,
202
203 #[serde(default)]
204 pub health: HealthConfig,
205
206 #[serde(default)]
207 pub rules: RulesConfig,
208
209 #[serde(
210 default,
211 skip_serializing_if = "UnusedComponentPropsConfig::is_default"
212 )]
213 pub unused_component_props: UnusedComponentPropsConfig,
214
215 #[serde(default)]
216 pub boundaries: BoundaryConfig,
217
218 #[serde(default)]
219 pub flags: FlagsConfig,
220
221 #[serde(default)]
222 pub security: SecurityConfig,
223
224 #[serde(default)]
225 pub fix: FixConfig,
226
227 #[serde(default)]
228 pub resolve: ResolveConfig,
229
230 #[serde(default)]
231 pub production: ProductionConfig,
232
233 #[serde(default)]
234 pub plugins: Vec<String>,
235
236 #[serde(default, skip_serializing_if = "Vec::is_empty")]
242 pub rule_packs: Vec<String>,
243
244 #[serde(default)]
245 pub dynamically_loaded: Vec<String>,
246
247 #[serde(default)]
248 pub overrides: Vec<ConfigOverride>,
249
250 #[serde(default, skip_serializing_if = "Option::is_none")]
251 pub codeowners: Option<String>,
252
253 #[serde(default)]
254 pub public_packages: Vec<String>,
255
256 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub regression: Option<RegressionConfig>,
258
259 #[serde(default, skip_serializing_if = "AuditConfig::is_empty")]
260 pub audit: AuditConfig,
261
262 #[serde(default)]
263 pub sealed: bool,
264
265 #[serde(default)]
266 pub include_entry_exports: bool,
267
268 #[serde(default)]
269 pub auto_imports: bool,
270
271 #[serde(default, skip_serializing_if = "CacheConfig::is_default")]
272 pub cache: CacheConfig,
273}
274
275#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
279#[serde(deny_unknown_fields, rename_all = "camelCase")]
280pub struct SecurityConfig {
281 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub categories: Option<SecurityCategories>,
284 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 pub request_receivers: Vec<String>,
290}
291
292impl SecurityConfig {
293 #[must_use]
294 pub fn normalized_request_receivers(&self) -> Vec<String> {
295 let mut receivers = Vec::new();
296 for receiver in &self.request_receivers {
297 let normalized = receiver.trim().to_ascii_lowercase();
298 if !normalized.is_empty() && !receivers.contains(&normalized) {
299 receivers.push(normalized);
300 }
301 }
302 receivers
303 }
304
305 #[must_use]
306 pub fn request_receivers_are_valid(&self) -> bool {
307 self.request_receivers
308 .iter()
309 .all(|receiver| !receiver.trim().is_empty())
310 }
311}
312
313#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
318#[serde(deny_unknown_fields, rename_all = "camelCase")]
319pub struct SecurityCategories {
320 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub include: Option<Vec<String>>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub exclude: Option<Vec<String>>,
326}
327
328#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
329#[serde(deny_unknown_fields, rename_all = "camelCase")]
330pub struct CacheConfig {
331 #[serde(default, skip_serializing_if = "Option::is_none")]
334 pub dir: Option<PathBuf>,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub max_size_mb: Option<u32>,
338}
339
340impl CacheConfig {
341 #[must_use]
342 pub fn is_default(&self) -> bool {
343 self.dir.is_none() && self.max_size_mb.is_none()
344 }
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub enum ProductionAnalysis {
349 DeadCode,
350 Health,
351 Dupes,
352}
353
354#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
355#[serde(untagged)]
356pub enum ProductionConfig {
357 Global(bool),
358 PerAnalysis(PerAnalysisProductionConfig),
359}
360
361impl<'de> Deserialize<'de> for ProductionConfig {
362 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
363 where
364 D: Deserializer<'de>,
365 {
366 struct ProductionConfigVisitor;
367
368 impl<'de> serde::de::Visitor<'de> for ProductionConfigVisitor {
369 type Value = ProductionConfig;
370
371 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 formatter.write_str("a boolean or per-analysis production config object")
373 }
374
375 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
376 where
377 E: serde::de::Error,
378 {
379 Ok(ProductionConfig::Global(value))
380 }
381
382 fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
383 where
384 A: serde::de::MapAccess<'de>,
385 {
386 PerAnalysisProductionConfig::deserialize(
387 serde::de::value::MapAccessDeserializer::new(map),
388 )
389 .map(ProductionConfig::PerAnalysis)
390 }
391 }
392
393 deserializer.deserialize_any(ProductionConfigVisitor)
394 }
395}
396
397impl Default for ProductionConfig {
398 fn default() -> Self {
399 Self::Global(false)
400 }
401}
402
403impl From<bool> for ProductionConfig {
404 fn from(value: bool) -> Self {
405 Self::Global(value)
406 }
407}
408
409impl Not for ProductionConfig {
410 type Output = bool;
411
412 fn not(self) -> Self::Output {
413 !self.any_enabled()
414 }
415}
416
417impl ProductionConfig {
418 #[must_use]
419 pub const fn for_analysis(self, analysis: ProductionAnalysis) -> bool {
420 match self {
421 Self::Global(value) => value,
422 Self::PerAnalysis(config) => match analysis {
423 ProductionAnalysis::DeadCode => config.dead_code,
424 ProductionAnalysis::Health => config.health,
425 ProductionAnalysis::Dupes => config.dupes,
426 },
427 }
428 }
429
430 #[must_use]
431 pub const fn global(self) -> bool {
432 match self {
433 Self::Global(value) => value,
434 Self::PerAnalysis(_) => false,
435 }
436 }
437
438 #[must_use]
439 pub const fn any_enabled(self) -> bool {
440 match self {
441 Self::Global(value) => value,
442 Self::PerAnalysis(config) => config.dead_code || config.health || config.dupes,
443 }
444 }
445}
446
447#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
448#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
449pub struct PerAnalysisProductionConfig {
450 pub dead_code: bool,
451 pub health: bool,
452 pub dupes: bool,
453}
454
455#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
456#[serde(rename_all = "camelCase")]
457pub struct AuditConfig {
458 #[serde(default, skip_serializing_if = "AuditGate::is_default")]
459 pub gate: AuditGate,
460
461 #[serde(default, skip_serializing_if = "Option::is_none")]
462 pub css: Option<bool>,
463
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub css_deep: Option<bool>,
466
467 #[serde(default, skip_serializing_if = "Option::is_none")]
468 pub dead_code_baseline: Option<String>,
469
470 #[serde(default, skip_serializing_if = "Option::is_none")]
471 pub health_baseline: Option<String>,
472
473 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub dupes_baseline: Option<String>,
475
476 #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub cache_max_age_days: Option<u32>,
478}
479
480impl AuditConfig {
481 #[must_use]
482 pub fn is_empty(&self) -> bool {
483 self.gate.is_default()
484 && self.css.is_none()
485 && self.css_deep.is_none()
486 && self.dead_code_baseline.is_none()
487 && self.health_baseline.is_none()
488 && self.dupes_baseline.is_none()
489 && self.cache_max_age_days.is_none()
490 }
491}
492
493#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
494#[serde(rename_all = "kebab-case")]
495pub enum AuditGate {
496 #[default]
497 NewOnly,
498 All,
499}
500
501impl AuditGate {
502 #[must_use]
503 pub const fn is_default(&self) -> bool {
504 matches!(self, Self::NewOnly)
505 }
506}
507
508#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
509#[serde(rename_all = "camelCase")]
510pub struct RegressionConfig {
511 #[serde(default, skip_serializing_if = "Option::is_none")]
512 pub baseline: Option<RegressionBaseline>,
513}
514
515#[derive(Debug, Default, Clone, Deserialize, Serialize, JsonSchema)]
516#[serde(rename_all = "camelCase")]
517pub struct RegressionBaseline {
518 #[serde(default)]
519 pub total_issues: usize,
520 #[serde(default)]
521 pub unused_files: usize,
522 #[serde(default)]
523 pub unused_exports: usize,
524 #[serde(default)]
525 pub unused_types: usize,
526 #[serde(default)]
527 pub unused_dependencies: usize,
528 #[serde(default)]
529 pub unused_dev_dependencies: usize,
530 #[serde(default)]
531 pub unused_optional_dependencies: usize,
532 #[serde(default)]
533 pub unused_enum_members: usize,
534 #[serde(default)]
535 pub unused_class_members: usize,
536 #[serde(default)]
537 pub unresolved_imports: usize,
538 #[serde(default)]
539 pub unlisted_dependencies: usize,
540 #[serde(default)]
541 pub duplicate_exports: usize,
542 #[serde(default)]
543 pub circular_dependencies: usize,
544 #[serde(default)]
545 pub re_export_cycles: usize,
546 #[serde(default)]
547 pub type_only_dependencies: usize,
548 #[serde(default)]
549 pub test_only_dependencies: usize,
550 #[serde(default)]
551 pub boundary_violations: usize,
552 #[serde(default)]
553 pub boundary_coverage_violations: usize,
554 #[serde(default)]
555 pub boundary_call_violations: usize,
556 #[serde(default)]
557 pub policy_violations: usize,
558}
559
560#[cfg(test)]
561mod tests {
562 use super::*;
563
564 #[test]
565 fn default_config_has_empty_collections() {
566 let config = FallowConfig::default();
567 assert!(config.schema.is_none());
568 assert!(config.extends.is_empty());
569 assert!(config.entry.is_empty());
570 assert!(config.ignore_patterns.is_empty());
571 assert!(config.framework.is_empty());
572 assert!(config.workspaces.is_none());
573 assert!(config.ignore_dependencies.is_empty());
574 assert!(config.ignore_exports.is_empty());
575 assert!(config.used_class_members.is_empty());
576 assert!(config.plugins.is_empty());
577 assert!(config.dynamically_loaded.is_empty());
578 assert!(config.overrides.is_empty());
579 assert!(config.public_packages.is_empty());
580 assert_eq!(
581 config.fix.catalog.delete_preceding_comments,
582 CatalogPrecedingCommentPolicy::Auto
583 );
584 assert!(!config.production);
585 }
586
587 #[test]
588 fn default_config_rules_are_error() {
589 let config = FallowConfig::default();
590 assert_eq!(config.rules.unused_files, Severity::Error);
591 assert_eq!(config.rules.unused_exports, Severity::Error);
592 assert_eq!(config.rules.unused_dependencies, Severity::Error);
593 }
594
595 #[test]
596 fn default_config_duplicates_enabled() {
597 let config = FallowConfig::default();
598 assert!(config.duplicates.enabled);
599 assert_eq!(config.duplicates.min_tokens, 50);
600 assert_eq!(config.duplicates.min_lines, 5);
601 }
602
603 #[test]
604 fn default_config_health_thresholds() {
605 let config = FallowConfig::default();
606 assert_eq!(config.health.max_cyclomatic, 20);
607 assert_eq!(config.health.max_cognitive, 15);
608 }
609
610 #[test]
611 fn deserialize_empty_json_object() {
612 let config: FallowConfig = serde_json::from_str("{}").unwrap();
613 assert!(config.entry.is_empty());
614 assert!(!config.production);
615 }
616
617 #[test]
618 fn deserialize_json_with_all_top_level_fields() {
619 let json = r#"{
620 "$schema": "https://fallow.dev/schema.json",
621 "entry": ["src/main.ts"],
622 "ignorePatterns": ["generated/**"],
623 "ignoreDependencies": ["postcss"],
624 "production": true,
625 "plugins": ["custom-plugin.toml"],
626 "rules": {"unused-files": "warn"},
627 "duplicates": {"enabled": false},
628 "health": {"maxCyclomatic": 30}
629 }"#;
630 let config: FallowConfig = serde_json::from_str(json).unwrap();
631 assert_eq!(
632 config.schema.as_deref(),
633 Some("https://fallow.dev/schema.json")
634 );
635 assert_eq!(config.entry, vec!["src/main.ts"]);
636 assert_eq!(config.ignore_patterns, vec!["generated/**"]);
637 assert_eq!(config.ignore_dependencies, vec!["postcss"]);
638 assert!(config.production);
639 assert_eq!(config.plugins, vec!["custom-plugin.toml"]);
640 assert_eq!(config.rules.unused_files, Severity::Warn);
641 assert!(!config.duplicates.enabled);
642 assert_eq!(config.health.max_cyclomatic, 30);
643 }
644
645 #[test]
646 fn deserialize_json_deny_unknown_fields() {
647 let json = r#"{"unknownField": true}"#;
648 let result: Result<FallowConfig, _> = serde_json::from_str(json);
649 assert!(result.is_err(), "unknown fields should be rejected");
650 }
651
652 #[test]
653 fn deserialize_json_production_mode_default_false() {
654 let config: FallowConfig = serde_json::from_str("{}").unwrap();
655 assert!(!config.production);
656 }
657
658 #[test]
659 fn deserialize_json_production_mode_true() {
660 let config: FallowConfig = serde_json::from_str(r#"{"production": true}"#).unwrap();
661 assert!(config.production);
662 }
663
664 #[test]
665 fn deserialize_json_per_analysis_production_mode() {
666 let config: FallowConfig = serde_json::from_str(
667 r#"{"production": {"deadCode": false, "health": true, "dupes": false}}"#,
668 )
669 .unwrap();
670 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
671 assert!(config.production.for_analysis(ProductionAnalysis::Health));
672 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
673 }
674
675 #[test]
676 fn deserialize_json_per_analysis_production_mode_rejects_unknown_fields() {
677 let err = serde_json::from_str::<FallowConfig>(r#"{"production": {"healthTypo": true}}"#)
678 .unwrap_err();
679 assert!(
680 err.to_string().contains("healthTypo"),
681 "error should name the unknown field: {err}"
682 );
683 }
684
685 #[test]
686 fn deserialize_json_dynamically_loaded() {
687 let json = r#"{"dynamicallyLoaded": ["plugins/**/*.ts", "locales/**/*.json"]}"#;
688 let config: FallowConfig = serde_json::from_str(json).unwrap();
689 assert_eq!(
690 config.dynamically_loaded,
691 vec!["plugins/**/*.ts", "locales/**/*.json"]
692 );
693 }
694
695 #[test]
696 fn deserialize_json_dynamically_loaded_defaults_empty() {
697 let config: FallowConfig = serde_json::from_str("{}").unwrap();
698 assert!(config.dynamically_loaded.is_empty());
699 }
700
701 #[test]
702 fn deserialize_json_fix_catalog_delete_preceding_comments() {
703 let config: FallowConfig =
704 serde_json::from_str(r#"{"fix": {"catalog": {"deletePrecedingComments": "always"}}}"#)
705 .unwrap();
706 assert_eq!(
707 config.fix.catalog.delete_preceding_comments,
708 CatalogPrecedingCommentPolicy::Always
709 );
710 }
711
712 #[test]
713 fn deserialize_json_fix_catalog_delete_preceding_comments_rejects_unknown_policy() {
714 let err = serde_json::from_str::<FallowConfig>(
715 r#"{"fix": {"catalog": {"deletePrecedingComments": "sometimes"}}}"#,
716 )
717 .unwrap_err();
718 assert!(
719 err.to_string().contains("sometimes"),
720 "error should name the bad policy: {err}"
721 );
722 }
723
724 #[test]
725 fn deserialize_json_used_class_members_supports_strings_and_scoped_rules() {
726 let json = r#"{
727 "usedClassMembers": [
728 "agInit",
729 { "implements": "ICellRendererAngularComp", "members": ["refresh"] },
730 { "extends": "BaseCommand", "implements": "CanActivate", "members": ["execute"] }
731 ]
732 }"#;
733 let config: FallowConfig = serde_json::from_str(json).unwrap();
734 assert_eq!(
735 config.used_class_members,
736 vec![
737 UsedClassMemberRule::from("agInit"),
738 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
739 extends: None,
740 implements: Some("ICellRendererAngularComp".to_string()),
741 members: vec!["refresh".to_string()],
742 }),
743 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
744 extends: Some("BaseCommand".to_string()),
745 implements: Some("CanActivate".to_string()),
746 members: vec!["execute".to_string()],
747 }),
748 ]
749 );
750 }
751
752 #[test]
753 fn deserialize_toml_minimal() {
754 let toml_str = r#"
755entry = ["src/index.ts"]
756production = true
757"#;
758 let config: FallowConfig = toml::from_str(toml_str).unwrap();
759 assert_eq!(config.entry, vec!["src/index.ts"]);
760 assert!(config.production);
761 }
762
763 #[test]
764 fn deserialize_toml_per_analysis_production_mode() {
765 let toml_str = r"
766[production]
767deadCode = false
768health = true
769dupes = false
770";
771 let config: FallowConfig = toml::from_str(toml_str).unwrap();
772 assert!(!config.production.for_analysis(ProductionAnalysis::DeadCode));
773 assert!(config.production.for_analysis(ProductionAnalysis::Health));
774 assert!(!config.production.for_analysis(ProductionAnalysis::Dupes));
775 }
776
777 #[test]
778 fn deserialize_toml_per_analysis_production_mode_rejects_unknown_fields() {
779 let err = toml::from_str::<FallowConfig>(
780 r"
781[production]
782healthTypo = true
783",
784 )
785 .unwrap_err();
786 assert!(
787 err.to_string().contains("healthTypo"),
788 "error should name the unknown field: {err}"
789 );
790 }
791
792 #[test]
793 fn deserialize_toml_with_inline_framework() {
794 let toml_str = r#"
795[[framework]]
796name = "my-framework"
797enablers = ["my-framework-pkg"]
798entryPoints = ["src/routes/**/*.tsx"]
799"#;
800 let config: FallowConfig = toml::from_str(toml_str).unwrap();
801 assert_eq!(config.framework.len(), 1);
802 assert_eq!(config.framework[0].name, "my-framework");
803 assert_eq!(config.framework[0].enablers, vec!["my-framework-pkg"]);
804 assert_eq!(
805 config.framework[0].entry_points,
806 vec!["src/routes/**/*.tsx"]
807 );
808 }
809
810 #[test]
811 fn deserialize_toml_fix_catalog_delete_preceding_comments() {
812 let toml_str = r#"
813[fix.catalog]
814deletePrecedingComments = "never"
815"#;
816 let config: FallowConfig = toml::from_str(toml_str).unwrap();
817 assert_eq!(
818 config.fix.catalog.delete_preceding_comments,
819 CatalogPrecedingCommentPolicy::Never
820 );
821 }
822
823 #[test]
824 fn deserialize_toml_with_workspace_config() {
825 let toml_str = r#"
826[workspaces]
827patterns = ["packages/*", "apps/*"]
828"#;
829 let config: FallowConfig = toml::from_str(toml_str).unwrap();
830 assert!(config.workspaces.is_some());
831 let ws = config.workspaces.unwrap();
832 assert_eq!(ws.patterns, vec!["packages/*", "apps/*"]);
833 }
834
835 #[test]
836 fn deserialize_toml_with_ignore_exports() {
837 let toml_str = r#"
838[[ignoreExports]]
839file = "src/types/**/*.ts"
840exports = ["*"]
841"#;
842 let config: FallowConfig = toml::from_str(toml_str).unwrap();
843 assert_eq!(config.ignore_exports.len(), 1);
844 assert_eq!(config.ignore_exports[0].file, "src/types/**/*.ts");
845 assert_eq!(config.ignore_exports[0].exports, vec!["*"]);
846 }
847
848 #[test]
849 fn deserialize_toml_used_class_members_supports_scoped_rules() {
850 let toml_str = r#"
851usedClassMembers = [
852 { implements = "ICellRendererAngularComp", members = ["refresh"] },
853 { extends = "BaseCommand", members = ["execute"] },
854]
855"#;
856 let config: FallowConfig = toml::from_str(toml_str).unwrap();
857 assert_eq!(
858 config.used_class_members,
859 vec![
860 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
861 extends: None,
862 implements: Some("ICellRendererAngularComp".to_string()),
863 members: vec!["refresh".to_string()],
864 }),
865 UsedClassMemberRule::Scoped(ScopedUsedClassMemberRule {
866 extends: Some("BaseCommand".to_string()),
867 implements: None,
868 members: vec!["execute".to_string()],
869 }),
870 ]
871 );
872 }
873
874 #[test]
875 fn deserialize_json_used_class_members_rejects_unconstrained_scoped_rules() {
876 let result = serde_json::from_str::<FallowConfig>(
877 r#"{"usedClassMembers":[{"members":["refresh"]}]}"#,
878 );
879 assert!(
880 result.is_err(),
881 "unconstrained scoped rule should be rejected"
882 );
883 }
884
885 #[test]
886 fn deserialize_ignore_exports_used_in_file_bool() {
887 let config: FallowConfig =
888 serde_json::from_str(r#"{"ignoreExportsUsedInFile":true}"#).unwrap();
889
890 assert!(config.ignore_exports_used_in_file.suppresses(false));
891 assert!(config.ignore_exports_used_in_file.suppresses(true));
892 }
893
894 #[test]
895 fn deserialize_ignore_exports_used_in_file_kind_form() {
896 let config: FallowConfig =
897 serde_json::from_str(r#"{"ignoreExportsUsedInFile":{"type":true}}"#).unwrap();
898
899 assert!(!config.ignore_exports_used_in_file.suppresses(false));
900 assert!(config.ignore_exports_used_in_file.suppresses(true));
901 }
902
903 #[test]
904 fn deserialize_toml_deny_unknown_fields() {
905 let toml_str = r"bogus_field = true";
906 let result: Result<FallowConfig, _> = toml::from_str(toml_str);
907 assert!(result.is_err(), "unknown fields should be rejected");
908 }
909
910 #[test]
911 fn json_serialize_roundtrip() {
912 let config = FallowConfig {
913 entry: vec!["src/main.ts".to_string()],
914 production: true.into(),
915 ..FallowConfig::default()
916 };
917 let json = serde_json::to_string(&config).unwrap();
918 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
919 assert_eq!(restored.entry, vec!["src/main.ts"]);
920 assert!(restored.production);
921 }
922
923 #[test]
924 fn schema_field_not_serialized() {
925 let config = FallowConfig {
926 schema: Some("https://example.com/schema.json".to_string()),
927 ..FallowConfig::default()
928 };
929 let json = serde_json::to_string(&config).unwrap();
930 assert!(
931 !json.contains("$schema"),
932 "schema field should be skipped in serialization"
933 );
934 }
935
936 #[test]
937 fn extends_field_not_serialized() {
938 let config = FallowConfig {
939 extends: vec!["base.json".to_string()],
940 ..FallowConfig::default()
941 };
942 let json = serde_json::to_string(&config).unwrap();
943 assert!(
944 !json.contains("extends"),
945 "extends field should be skipped in serialization"
946 );
947 }
948
949 #[test]
950 fn regression_config_deserialize_json() {
951 let json = r#"{
952 "regression": {
953 "baseline": {
954 "totalIssues": 42,
955 "unusedFiles": 10,
956 "unusedExports": 5,
957 "circularDependencies": 2
958 }
959 }
960 }"#;
961 let config: FallowConfig = serde_json::from_str(json).unwrap();
962 let regression = config.regression.unwrap();
963 let baseline = regression.baseline.unwrap();
964 assert_eq!(baseline.total_issues, 42);
965 assert_eq!(baseline.unused_files, 10);
966 assert_eq!(baseline.unused_exports, 5);
967 assert_eq!(baseline.circular_dependencies, 2);
968 assert_eq!(baseline.unused_types, 0);
969 assert_eq!(baseline.boundary_violations, 0);
970 }
971
972 #[test]
973 fn regression_config_defaults_to_none() {
974 let config: FallowConfig = serde_json::from_str("{}").unwrap();
975 assert!(config.regression.is_none());
976 }
977
978 #[test]
979 fn regression_baseline_all_zeros_by_default() {
980 let baseline = RegressionBaseline::default();
981 assert_eq!(baseline.total_issues, 0);
982 assert_eq!(baseline.unused_files, 0);
983 assert_eq!(baseline.unused_exports, 0);
984 assert_eq!(baseline.unused_types, 0);
985 assert_eq!(baseline.unused_dependencies, 0);
986 assert_eq!(baseline.unused_dev_dependencies, 0);
987 assert_eq!(baseline.unused_optional_dependencies, 0);
988 assert_eq!(baseline.unused_enum_members, 0);
989 assert_eq!(baseline.unused_class_members, 0);
990 assert_eq!(baseline.unresolved_imports, 0);
991 assert_eq!(baseline.unlisted_dependencies, 0);
992 assert_eq!(baseline.duplicate_exports, 0);
993 assert_eq!(baseline.circular_dependencies, 0);
994 assert_eq!(baseline.type_only_dependencies, 0);
995 assert_eq!(baseline.test_only_dependencies, 0);
996 assert_eq!(baseline.boundary_violations, 0);
997 }
998
999 #[test]
1000 fn regression_config_serialize_roundtrip() {
1001 let baseline = RegressionBaseline {
1002 total_issues: 100,
1003 unused_files: 20,
1004 unused_exports: 30,
1005 ..RegressionBaseline::default()
1006 };
1007 let regression = RegressionConfig {
1008 baseline: Some(baseline),
1009 };
1010 let config = FallowConfig {
1011 regression: Some(regression),
1012 ..FallowConfig::default()
1013 };
1014 let json = serde_json::to_string(&config).unwrap();
1015 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1016 let restored_baseline = restored.regression.unwrap().baseline.unwrap();
1017 assert_eq!(restored_baseline.total_issues, 100);
1018 assert_eq!(restored_baseline.unused_files, 20);
1019 assert_eq!(restored_baseline.unused_exports, 30);
1020 assert_eq!(restored_baseline.unused_types, 0);
1021 }
1022
1023 #[test]
1024 fn regression_config_empty_baseline_deserialize() {
1025 let json = r#"{"regression": {}}"#;
1026 let config: FallowConfig = serde_json::from_str(json).unwrap();
1027 let regression = config.regression.unwrap();
1028 assert!(regression.baseline.is_none());
1029 }
1030
1031 #[test]
1032 fn regression_baseline_not_serialized_when_none() {
1033 let config = FallowConfig {
1034 regression: None,
1035 ..FallowConfig::default()
1036 };
1037 let json = serde_json::to_string(&config).unwrap();
1038 assert!(
1039 !json.contains("regression"),
1040 "regression should be skipped when None"
1041 );
1042 }
1043
1044 #[test]
1045 fn deserialize_json_with_overrides() {
1046 let json = r#"{
1047 "overrides": [
1048 {
1049 "files": ["*.test.ts", "*.spec.ts"],
1050 "rules": {
1051 "unused-exports": "off",
1052 "unused-files": "warn"
1053 }
1054 }
1055 ]
1056 }"#;
1057 let config: FallowConfig = serde_json::from_str(json).unwrap();
1058 assert_eq!(config.overrides.len(), 1);
1059 assert_eq!(config.overrides[0].files.len(), 2);
1060 assert_eq!(
1061 config.overrides[0].rules.unused_exports,
1062 Some(Severity::Off)
1063 );
1064 assert_eq!(config.overrides[0].rules.unused_files, Some(Severity::Warn));
1065 }
1066
1067 #[test]
1068 fn deserialize_json_with_boundaries() {
1069 let json = r#"{
1070 "boundaries": {
1071 "preset": "layered"
1072 }
1073 }"#;
1074 let config: FallowConfig = serde_json::from_str(json).unwrap();
1075 assert_eq!(config.boundaries.preset, Some(BoundaryPreset::Layered));
1076 }
1077
1078 #[test]
1079 fn deserialize_toml_with_regression_baseline() {
1080 let toml_str = r"
1081[regression.baseline]
1082totalIssues = 50
1083unusedFiles = 10
1084unusedExports = 15
1085";
1086 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1087 let baseline = config.regression.unwrap().baseline.unwrap();
1088 assert_eq!(baseline.total_issues, 50);
1089 assert_eq!(baseline.unused_files, 10);
1090 assert_eq!(baseline.unused_exports, 15);
1091 }
1092
1093 #[test]
1094 fn deserialize_toml_with_overrides() {
1095 let toml_str = r#"
1096[[overrides]]
1097files = ["*.test.ts"]
1098
1099[overrides.rules]
1100unused-exports = "off"
1101
1102[[overrides]]
1103files = ["*.stories.tsx"]
1104
1105[overrides.rules]
1106unused-files = "off"
1107"#;
1108 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1109 assert_eq!(config.overrides.len(), 2);
1110 assert_eq!(
1111 config.overrides[0].rules.unused_exports,
1112 Some(Severity::Off)
1113 );
1114 assert_eq!(config.overrides[1].rules.unused_files, Some(Severity::Off));
1115 }
1116
1117 #[test]
1118 fn regression_config_default_is_none_baseline() {
1119 let config = RegressionConfig::default();
1120 assert!(config.baseline.is_none());
1121 }
1122
1123 #[test]
1124 fn deserialize_json_multiple_ignore_export_rules() {
1125 let json = r#"{
1126 "ignoreExports": [
1127 {"file": "src/types/**/*.ts", "exports": ["*"]},
1128 {"file": "src/constants.ts", "exports": ["FOO", "BAR"]},
1129 {"file": "src/index.ts", "exports": ["default"]}
1130 ]
1131 }"#;
1132 let config: FallowConfig = serde_json::from_str(json).unwrap();
1133 assert_eq!(config.ignore_exports.len(), 3);
1134 assert_eq!(config.ignore_exports[2].exports, vec!["default"]);
1135 }
1136
1137 #[test]
1138 fn deserialize_json_public_packages_camel_case() {
1139 let json = r#"{"publicPackages": ["@myorg/shared-lib", "@myorg/utils"]}"#;
1140 let config: FallowConfig = serde_json::from_str(json).unwrap();
1141 assert_eq!(
1142 config.public_packages,
1143 vec!["@myorg/shared-lib", "@myorg/utils"]
1144 );
1145 }
1146
1147 #[test]
1148 fn deserialize_json_public_packages_rejects_snake_case() {
1149 let json = r#"{"public_packages": ["@myorg/shared-lib"]}"#;
1150 let result: Result<FallowConfig, _> = serde_json::from_str(json);
1151 assert!(
1152 result.is_err(),
1153 "snake_case should be rejected by deny_unknown_fields + rename_all camelCase"
1154 );
1155 }
1156
1157 #[test]
1158 fn deserialize_json_public_packages_empty() {
1159 let config: FallowConfig = serde_json::from_str("{}").unwrap();
1160 assert!(config.public_packages.is_empty());
1161 }
1162
1163 #[test]
1164 fn deserialize_toml_public_packages() {
1165 let toml_str = r#"
1166publicPackages = ["@myorg/shared-lib", "@myorg/ui"]
1167"#;
1168 let config: FallowConfig = toml::from_str(toml_str).unwrap();
1169 assert_eq!(
1170 config.public_packages,
1171 vec!["@myorg/shared-lib", "@myorg/ui"]
1172 );
1173 }
1174
1175 #[test]
1176 fn public_packages_serialize_roundtrip() {
1177 let config = FallowConfig {
1178 public_packages: vec!["@myorg/shared-lib".to_string()],
1179 ..FallowConfig::default()
1180 };
1181 let json = serde_json::to_string(&config).unwrap();
1182 let restored: FallowConfig = serde_json::from_str(&json).unwrap();
1183 assert_eq!(restored.public_packages, vec!["@myorg/shared-lib"]);
1184 }
1185}