dart-decimate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
package/src/config.rs ADDED
@@ -0,0 +1,635 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use serde::{Deserialize, Serialize};
5
+ use serde_json::{Value, json};
6
+ use thiserror::Error;
7
+
8
+ use crate::graph::normalize_path;
9
+ use crate::{
10
+ BoundaryCallRule, BoundaryPreset, BoundaryRule, DuplicateMode, DuplicateOptions,
11
+ DuplicationThreshold, FeatureFlagOptions, HealthOptions, SecurityCategory, SecurityOptions,
12
+ };
13
+
14
+ mod boundary_config;
15
+ mod cache;
16
+ mod dependencies;
17
+ mod health;
18
+ mod jsonc;
19
+ mod policy;
20
+ mod rule_aliases;
21
+ mod rules;
22
+ use boundary_config::RawBoundaries;
23
+ pub use cache::CacheConfig;
24
+ pub use dependencies::IgnoreDependencyOverrideRule;
25
+ pub(crate) use dependencies::{filter_ignored_dependencies, filter_ignored_dependency_overrides};
26
+ pub use health::HealthConfig;
27
+ pub use rules::{
28
+ RuleConfig, RuleError, RuleLevel, apply_rules_to_report, missing_suppression_reasons_enabled,
29
+ private_type_leaks_enabled, validate_rules,
30
+ };
31
+
32
+ /// Stable Dart Decimate configuration schema version.
33
+ pub const CONFIG_SCHEMA_VERSION: &str = "dart-decimate.config.v1";
34
+
35
+ /// A discovered or explicitly loaded Dart Decimate configuration.
36
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
37
+ pub struct DartDecimateConfig {
38
+ /// Config file path, when one was loaded.
39
+ pub path: Option<PathBuf>,
40
+ /// Default output format for CLI commands.
41
+ pub output_format: Option<ConfigOutputFormat>,
42
+ /// Default reachability entry points.
43
+ pub entry_points: Vec<PathBuf>,
44
+ /// Whether default reachability should use production entry points only.
45
+ pub production: bool,
46
+ /// Whether unused public declarations in entry libraries should be reported.
47
+ pub include_entry_exports: bool,
48
+ /// Architecture boundary rules.
49
+ pub boundaries: Vec<BoundaryRule>,
50
+ /// Built-in architecture boundary presets expanded into boundary rules.
51
+ pub boundary_presets: Vec<BoundaryPreset>,
52
+ /// Whether configured boundaries must cover every Dart library file.
53
+ pub boundary_coverage: bool,
54
+ /// Root-relative globs exempt from boundary coverage gaps.
55
+ pub boundary_allow_unmatched: Vec<String>,
56
+ /// Boundary-local forbidden call rules.
57
+ pub boundary_calls: Vec<BoundaryCallRule>,
58
+ /// Declarative policy pack paths.
59
+ pub policy_packs: Vec<PathBuf>,
60
+ /// Glob patterns excluded from Dart file discovery.
61
+ pub ignore_patterns: Vec<String>,
62
+ /// Pub dependency names ignored by dependency hygiene checks.
63
+ pub ignore_dependencies: Vec<String>,
64
+ /// Known intentional dependency override declarations.
65
+ pub ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
66
+ /// Cache configuration metadata.
67
+ pub cache: CacheConfig,
68
+ /// Health analyzer defaults.
69
+ pub health: HealthConfig,
70
+ /// Duplicate-code analyzer defaults.
71
+ pub dupes: DuplicateConfig,
72
+ /// Feature flag analyzer defaults.
73
+ pub flags: FeatureFlagConfig,
74
+ /// Security analyzer defaults.
75
+ pub security: SecurityConfig,
76
+ /// Rule severity controls.
77
+ pub rules: RuleConfig,
78
+ }
79
+
80
+ /// Output formats accepted in Dart Decimate config.
81
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
82
+ #[serde(rename_all = "kebab-case")]
83
+ pub enum ConfigOutputFormat {
84
+ /// Human-readable terminal output.
85
+ Human,
86
+ /// Agent-readable JSON output.
87
+ Json,
88
+ }
89
+
90
+ /// Duplicate-code analyzer config defaults.
91
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
92
+ #[serde(deny_unknown_fields)]
93
+ pub struct DuplicateConfig {
94
+ /// Detection mode.
95
+ #[serde(default)]
96
+ pub mode: Option<DuplicateMode>,
97
+ /// Minimum tokens per clone.
98
+ #[serde(default, alias = "minTokens")]
99
+ pub min_tokens: Option<usize>,
100
+ /// Minimum lines per clone.
101
+ #[serde(default, alias = "minLines")]
102
+ pub min_lines: Option<usize>,
103
+ /// Minimum clone instances per group.
104
+ #[serde(default, alias = "minOccurrences")]
105
+ pub min_occurrences: Option<usize>,
106
+ /// Limit output to the N largest clone groups.
107
+ #[serde(default)]
108
+ pub top: Option<usize>,
109
+ /// Fail when duplicated Dart lines exceed this percentage.
110
+ #[serde(default)]
111
+ pub threshold: Option<DuplicationThreshold>,
112
+ /// Only report cross-directory duplicates.
113
+ #[serde(default, alias = "skipLocal")]
114
+ pub skip_local: Option<bool>,
115
+ /// Ignore import/export/part/augment directives.
116
+ #[serde(default, alias = "ignoreImports")]
117
+ pub ignore_imports: Option<bool>,
118
+ }
119
+
120
+ /// Feature flag analyzer config defaults.
121
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
122
+ #[serde(deny_unknown_fields)]
123
+ pub struct FeatureFlagConfig {
124
+ /// Limit output to the N most frequently referenced flags.
125
+ #[serde(default)]
126
+ pub top: Option<usize>,
127
+ }
128
+
129
+ /// Security analyzer config defaults.
130
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
131
+ #[serde(deny_unknown_fields)]
132
+ pub struct SecurityConfig {
133
+ /// Limit output to the N most frequent candidate groups.
134
+ #[serde(default)]
135
+ pub top: Option<usize>,
136
+ /// Include attack-surface inventory entries.
137
+ #[serde(default)]
138
+ pub surface: Option<bool>,
139
+ /// Security candidate categories to include. Empty means all categories.
140
+ #[serde(default)]
141
+ pub categories: Vec<SecurityCategory>,
142
+ }
143
+
144
+ /// Errors returned while reading Dart Decimate config.
145
+ #[derive(Debug, Error)]
146
+ pub enum ConfigError {
147
+ /// Current directory could not be read.
148
+ #[error("failed to read current directory: {source}")]
149
+ CurrentDir {
150
+ /// Underlying IO error.
151
+ source: std::io::Error,
152
+ },
153
+ /// Explicit config path did not exist.
154
+ #[error("config file not found: {path}")]
155
+ NotFound {
156
+ /// Missing config path.
157
+ path: PathBuf,
158
+ },
159
+ /// Config file could not be read.
160
+ #[error("failed to read config {path}: {source}")]
161
+ Read {
162
+ /// Config path.
163
+ path: PathBuf,
164
+ /// Underlying IO error.
165
+ source: std::io::Error,
166
+ },
167
+ /// JSON or JSONC config could not be parsed.
168
+ #[error("failed to parse config {path}: {source}")]
169
+ ParseJson {
170
+ /// Config path.
171
+ path: PathBuf,
172
+ /// JSON parse error.
173
+ source: serde_json::Error,
174
+ },
175
+ /// TOML config could not be parsed.
176
+ #[error("failed to parse config {path}: {source}")]
177
+ ParseToml {
178
+ /// Config path.
179
+ path: PathBuf,
180
+ /// TOML parse error.
181
+ source: toml::de::Error,
182
+ },
183
+ /// Boundary rule syntax was invalid.
184
+ #[error("invalid config boundary rule {value:?}; expected FROM:DISALLOW or from/disallow")]
185
+ BoundaryRule {
186
+ /// Raw boundary value.
187
+ value: String,
188
+ },
189
+ /// Boundary call rule syntax was invalid.
190
+ #[error("invalid config boundary call rule {value:?}; expected FROM:PATTERN or from/forbidden")]
191
+ BoundaryCallRule {
192
+ /// Raw boundary call value.
193
+ value: String,
194
+ },
195
+ /// Health threshold override syntax was invalid.
196
+ #[error("invalid config health.thresholdOverrides[{index}]: {message}")]
197
+ HealthThresholdOverride {
198
+ /// Override index.
199
+ index: usize,
200
+ /// Validation failure.
201
+ message: String,
202
+ },
203
+ /// Configured rule name was invalid.
204
+ #[error(transparent)]
205
+ Rule(#[from] RuleError),
206
+ }
207
+
208
+ /// Load Dart Decimate config discovered from `root`, or from an explicit config path.
209
+ ///
210
+ /// # Errors
211
+ ///
212
+ /// Returns [`ConfigError`] when an explicit config is missing, unreadable,
213
+ /// malformed, or contains an invalid boundary rule.
214
+ pub fn load_dart_decimate_config(
215
+ root: impl AsRef<Path>,
216
+ explicit: Option<&Path>,
217
+ ) -> Result<DartDecimateConfig, ConfigError> {
218
+ let root = normalize_config_root(root.as_ref())?;
219
+ let Some(path) = config_path(&root, explicit)? else {
220
+ return Ok(DartDecimateConfig::default());
221
+ };
222
+ parse_config_file(&path)
223
+ }
224
+
225
+ /// Return a JSON schema describing supported Dart Decimate config keys.
226
+ #[must_use]
227
+ pub fn config_schema() -> Value {
228
+ json!({
229
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
230
+ "schema_version": CONFIG_SCHEMA_VERSION,
231
+ "title": "Dart Decimate configuration",
232
+ "type": "object",
233
+ "additionalProperties": false,
234
+ "properties": {
235
+ "format": format_schema(),
236
+ "production": { "type": "boolean" },
237
+ "include_entry_exports": { "type": "boolean" },
238
+ "includeEntryExports": { "type": "boolean" },
239
+ "cli": cli_schema(),
240
+ "entry": path_list_schema(),
241
+ "entries": path_list_schema(),
242
+ "boundary": boundary_config::boundary_schema(),
243
+ "boundaries": boundary_config::boundary_schema(),
244
+ "boundary_coverage": { "type": "boolean" },
245
+ "boundaryCoverage": { "type": "boolean" },
246
+ "boundary_calls": policy::boundary_calls_schema(),
247
+ "boundaryCalls": policy::boundary_calls_schema(),
248
+ "rule_packs": policy::rule_packs_schema(),
249
+ "rulePacks": policy::rule_packs_schema(),
250
+ "ignore_patterns": string_list_schema(),
251
+ "ignorePatterns": string_list_schema(),
252
+ "ignore_dependencies": string_list_schema(),
253
+ "ignoreDependencies": string_list_schema(),
254
+ "ignore_dependency_overrides": dependencies::ignore_dependency_overrides_schema(),
255
+ "ignoreDependencyOverrides": dependencies::ignore_dependency_overrides_schema(),
256
+ "cache": cache::cache_schema(),
257
+ "health": health::health_schema(),
258
+ "dupes": dupes_schema(),
259
+ "flags": top_schema(),
260
+ "security": security_schema(),
261
+ "rules": rules_schema()
262
+ }
263
+ })
264
+ }
265
+
266
+ impl DartDecimateConfig {
267
+ /// Build health analyzer options from config defaults.
268
+ #[must_use]
269
+ pub fn health_options(&self) -> HealthOptions {
270
+ let mut options = HealthOptions::default();
271
+ self.health.apply_to(&mut options);
272
+ options
273
+ }
274
+
275
+ /// Build duplicate-code analyzer options from config defaults.
276
+ #[must_use]
277
+ pub fn duplicate_options(&self) -> DuplicateOptions {
278
+ let mut options = DuplicateOptions::default();
279
+ self.dupes.apply_to(&mut options);
280
+ options
281
+ }
282
+
283
+ /// Build feature flag analyzer options from config defaults.
284
+ #[must_use]
285
+ pub fn feature_flag_options(&self) -> FeatureFlagOptions {
286
+ FeatureFlagOptions {
287
+ top: self.flags.top,
288
+ }
289
+ }
290
+
291
+ /// Build security analyzer options from config defaults.
292
+ #[must_use]
293
+ pub fn security_options(&self) -> SecurityOptions {
294
+ SecurityOptions {
295
+ top: self.security.top,
296
+ surface: self.security.surface.unwrap_or_default(),
297
+ categories: self.security.categories.iter().copied().collect(),
298
+ }
299
+ }
300
+ }
301
+
302
+ impl DuplicateConfig {
303
+ fn apply_to(&self, options: &mut DuplicateOptions) {
304
+ if let Some(mode) = self.mode {
305
+ options.mode = mode;
306
+ }
307
+ if let Some(min_tokens) = self.min_tokens {
308
+ options.min_tokens = min_tokens;
309
+ }
310
+ if let Some(min_lines) = self.min_lines {
311
+ options.min_lines = min_lines;
312
+ }
313
+ if let Some(min_occurrences) = self.min_occurrences {
314
+ options.min_occurrences = min_occurrences.max(2);
315
+ }
316
+ if self.top.is_some() {
317
+ options.top = self.top;
318
+ }
319
+ if self.threshold.is_some() {
320
+ options.threshold = self.threshold;
321
+ }
322
+ if let Some(skip_local) = self.skip_local {
323
+ options.skip_local = skip_local;
324
+ }
325
+ if let Some(ignore_imports) = self.ignore_imports {
326
+ options.ignore_imports = ignore_imports;
327
+ }
328
+ }
329
+ }
330
+
331
+ #[derive(Debug, Clone, Default, Deserialize)]
332
+ #[serde(default, deny_unknown_fields)]
333
+ struct RawConfig {
334
+ format: Option<ConfigOutputFormat>,
335
+ cli: RawCliConfig,
336
+ #[serde(alias = "entries")]
337
+ entry: Vec<PathBuf>,
338
+ production: Option<bool>,
339
+ #[serde(alias = "includeEntryExports")]
340
+ include_entry_exports: Option<bool>,
341
+ #[serde(alias = "boundary")]
342
+ boundaries: RawBoundaries,
343
+ #[serde(alias = "boundaryCoverage")]
344
+ boundary_coverage: Option<bool>,
345
+ #[serde(alias = "boundaryCalls")]
346
+ boundary_calls: Vec<policy::RawBoundaryCall>,
347
+ #[serde(alias = "rulePacks")]
348
+ rule_packs: Vec<PathBuf>,
349
+ #[serde(alias = "ignorePatterns")]
350
+ ignore_patterns: Vec<String>,
351
+ #[serde(alias = "ignoreDependencies")]
352
+ ignore_dependencies: Vec<String>,
353
+ #[serde(alias = "ignoreDependencyOverrides")]
354
+ ignore_dependency_overrides: Vec<IgnoreDependencyOverrideRule>,
355
+ cache: CacheConfig,
356
+ health: HealthConfig,
357
+ dupes: DuplicateConfig,
358
+ flags: FeatureFlagConfig,
359
+ security: SecurityConfig,
360
+ rules: RuleConfig,
361
+ }
362
+
363
+ #[derive(Debug, Clone, Default, Deserialize)]
364
+ #[serde(default, deny_unknown_fields)]
365
+ struct RawCliConfig {
366
+ format: Option<ConfigOutputFormat>,
367
+ #[serde(alias = "entries")]
368
+ entry: Vec<PathBuf>,
369
+ production: Option<bool>,
370
+ #[serde(alias = "includeEntryExports")]
371
+ include_entry_exports: Option<bool>,
372
+ #[serde(alias = "boundary")]
373
+ boundaries: RawBoundaries,
374
+ #[serde(alias = "boundaryCoverage")]
375
+ boundary_coverage: Option<bool>,
376
+ #[serde(alias = "boundaryCalls")]
377
+ boundary_calls: Vec<policy::RawBoundaryCall>,
378
+ #[serde(alias = "rulePacks")]
379
+ rule_packs: Vec<PathBuf>,
380
+ }
381
+
382
+ impl RawConfig {
383
+ fn into_config(self, path: PathBuf) -> Result<DartDecimateConfig, ConfigError> {
384
+ validate_rules(&self.rules)?;
385
+ self.health.validate()?;
386
+ let mut entry_points = self.entry;
387
+ entry_points.extend(self.cli.entry);
388
+
389
+ let mut boundary_settings = self.boundaries.into_settings()?;
390
+ boundary_settings.merge(self.cli.boundaries.into_settings()?);
391
+ let boundary_require_all_files = boundary_settings.require_all_files;
392
+ let (boundaries, boundary_presets, boundary_allow_unmatched) = boundary_settings.finish();
393
+ let mut raw_boundary_calls = self.boundary_calls;
394
+ raw_boundary_calls.extend(self.cli.boundary_calls);
395
+ let boundary_calls = raw_boundary_calls
396
+ .into_iter()
397
+ .map(policy::parse_boundary_call)
398
+ .collect::<Result<Vec<_>, _>>()?;
399
+ let mut policy_packs = self.rule_packs;
400
+ policy_packs.extend(self.cli.rule_packs);
401
+
402
+ Ok(DartDecimateConfig {
403
+ path: Some(path),
404
+ output_format: self.cli.format.or(self.format),
405
+ entry_points,
406
+ production: self.cli.production.or(self.production).unwrap_or_default(),
407
+ include_entry_exports: self
408
+ .cli
409
+ .include_entry_exports
410
+ .or(self.include_entry_exports)
411
+ .unwrap_or_default(),
412
+ boundaries,
413
+ boundary_presets,
414
+ boundary_coverage: self
415
+ .cli
416
+ .boundary_coverage
417
+ .or(self.boundary_coverage)
418
+ .or(boundary_require_all_files)
419
+ .unwrap_or_default(),
420
+ boundary_allow_unmatched,
421
+ boundary_calls,
422
+ policy_packs,
423
+ ignore_patterns: self.ignore_patterns,
424
+ ignore_dependencies: self.ignore_dependencies,
425
+ ignore_dependency_overrides: self.ignore_dependency_overrides,
426
+ cache: self.cache,
427
+ health: self.health,
428
+ dupes: self.dupes,
429
+ flags: self.flags,
430
+ security: self.security,
431
+ rules: self.rules,
432
+ })
433
+ }
434
+ }
435
+
436
+ fn normalize_config_root(root: &Path) -> Result<PathBuf, ConfigError> {
437
+ if root.is_absolute() {
438
+ return Ok(normalize_path(root));
439
+ }
440
+
441
+ let current_dir =
442
+ std::env::current_dir().map_err(|source| ConfigError::CurrentDir { source })?;
443
+ Ok(normalize_path(&current_dir.join(root)))
444
+ }
445
+
446
+ fn config_path(root: &Path, explicit: Option<&Path>) -> Result<Option<PathBuf>, ConfigError> {
447
+ if let Some(path) = explicit {
448
+ let path = if path.is_absolute() {
449
+ normalize_path(path)
450
+ } else {
451
+ normalize_path(&root.join(path))
452
+ };
453
+ if path.is_file() {
454
+ return Ok(Some(path));
455
+ }
456
+ return Err(ConfigError::NotFound { path });
457
+ }
458
+
459
+ Ok(config_candidates(root)
460
+ .into_iter()
461
+ .find(|candidate| candidate.is_file()))
462
+ }
463
+
464
+ fn config_candidates(root: &Path) -> Vec<PathBuf> {
465
+ [
466
+ ".dart-decimaterc",
467
+ ".dart-decimaterc.json",
468
+ ".dart-decimaterc.jsonc",
469
+ "dart-decimate.toml",
470
+ ".dart-decimate.toml",
471
+ ]
472
+ .into_iter()
473
+ .map(|name| root.join(name))
474
+ .collect()
475
+ }
476
+
477
+ fn parse_config_file(path: &Path) -> Result<DartDecimateConfig, ConfigError> {
478
+ let source = fs::read_to_string(path).map_err(|source| ConfigError::Read {
479
+ path: path.to_path_buf(),
480
+ source,
481
+ })?;
482
+ let raw: RawConfig = match config_format(path, &source) {
483
+ ConfigFormat::Json => {
484
+ serde_json::from_str(&source).map_err(|source| ConfigError::ParseJson {
485
+ path: path.to_path_buf(),
486
+ source,
487
+ })?
488
+ }
489
+ ConfigFormat::Jsonc => {
490
+ serde_json::from_str(&jsonc::strip_json_comments(&source)).map_err(|source| {
491
+ ConfigError::ParseJson {
492
+ path: path.to_path_buf(),
493
+ source,
494
+ }
495
+ })?
496
+ }
497
+ ConfigFormat::Toml => toml::from_str(&source).map_err(|source| ConfigError::ParseToml {
498
+ path: path.to_path_buf(),
499
+ source,
500
+ })?,
501
+ };
502
+ raw.into_config(path.to_path_buf())
503
+ }
504
+
505
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
506
+ enum ConfigFormat {
507
+ Json,
508
+ Jsonc,
509
+ Toml,
510
+ }
511
+
512
+ fn config_format(path: &Path, source: &str) -> ConfigFormat {
513
+ match path.extension().and_then(|extension| extension.to_str()) {
514
+ Some("json") => ConfigFormat::Json,
515
+ Some("jsonc") => ConfigFormat::Jsonc,
516
+ Some("toml") => ConfigFormat::Toml,
517
+ _ if source.trim_start().starts_with('{') => ConfigFormat::Jsonc,
518
+ _ => ConfigFormat::Toml,
519
+ }
520
+ }
521
+
522
+ fn format_schema() -> Value {
523
+ json!({ "type": "string", "enum": ["human", "json"] })
524
+ }
525
+
526
+ fn cli_schema() -> Value {
527
+ json!({
528
+ "type": "object",
529
+ "additionalProperties": false,
530
+ "properties": {
531
+ "format": format_schema(),
532
+ "production": { "type": "boolean" },
533
+ "include_entry_exports": { "type": "boolean" },
534
+ "includeEntryExports": { "type": "boolean" },
535
+ "entry": path_list_schema(),
536
+ "entries": path_list_schema(),
537
+ "boundary": boundary_config::boundary_schema(),
538
+ "boundaries": boundary_config::boundary_schema(),
539
+ "boundary_coverage": { "type": "boolean" },
540
+ "boundaryCoverage": { "type": "boolean" },
541
+ "boundary_calls": policy::boundary_calls_schema(),
542
+ "boundaryCalls": policy::boundary_calls_schema(),
543
+ "rule_packs": policy::rule_packs_schema(),
544
+ "rulePacks": policy::rule_packs_schema()
545
+ }
546
+ })
547
+ }
548
+
549
+ fn path_list_schema() -> Value {
550
+ json!({ "type": "array", "items": { "type": "string" } })
551
+ }
552
+
553
+ fn string_list_schema() -> Value {
554
+ json!({ "type": "array", "items": { "type": "string" } })
555
+ }
556
+
557
+ fn dupes_schema() -> Value {
558
+ json!({
559
+ "type": "object",
560
+ "additionalProperties": false,
561
+ "properties": {
562
+ "mode": {
563
+ "type": "string",
564
+ "enum": ["strict", "mild", "weak", "semantic"]
565
+ },
566
+ "min_tokens": positive_integer_schema(),
567
+ "minTokens": positive_integer_schema(),
568
+ "min_lines": positive_integer_schema(),
569
+ "minLines": positive_integer_schema(),
570
+ "min_occurrences": positive_integer_schema(),
571
+ "minOccurrences": positive_integer_schema(),
572
+ "top": positive_integer_schema(),
573
+ "threshold": percentage_schema(),
574
+ "skip_local": { "type": "boolean" },
575
+ "skipLocal": { "type": "boolean" },
576
+ "ignore_imports": { "type": "boolean" },
577
+ "ignoreImports": { "type": "boolean" }
578
+ }
579
+ })
580
+ }
581
+
582
+ fn top_schema() -> Value {
583
+ json!({
584
+ "type": "object",
585
+ "additionalProperties": false,
586
+ "properties": {
587
+ "top": positive_integer_schema()
588
+ }
589
+ })
590
+ }
591
+
592
+ fn security_schema() -> Value {
593
+ json!({
594
+ "type": "object",
595
+ "additionalProperties": false,
596
+ "properties": {
597
+ "top": positive_integer_schema(),
598
+ "surface": { "type": "boolean" },
599
+ "categories": {
600
+ "type": "array",
601
+ "items": {
602
+ "type": "string",
603
+ "enum": [
604
+ "hardcoded-secret",
605
+ "insecure-transport",
606
+ "tls-bypass",
607
+ "web-view-risk",
608
+ "process-execution",
609
+ "raw-sql",
610
+ "plain-secret-storage"
611
+ ]
612
+ },
613
+ "uniqueItems": true
614
+ }
615
+ }
616
+ })
617
+ }
618
+
619
+ fn rules_schema() -> Value {
620
+ json!({
621
+ "type": "object",
622
+ "additionalProperties": {
623
+ "type": "string",
624
+ "enum": ["error", "warn", "off"]
625
+ }
626
+ })
627
+ }
628
+
629
+ fn positive_integer_schema() -> Value {
630
+ json!({ "type": "integer", "minimum": 1 })
631
+ }
632
+
633
+ fn percentage_schema() -> Value {
634
+ json!({ "type": "number", "minimum": 0, "maximum": 100 })
635
+ }