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
@@ -0,0 +1,212 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use tempfile::TempDir;
5
+
6
+ use super::*;
7
+ use crate::{DartLibrary, DartPart, DartPartOf};
8
+
9
+ #[test]
10
+ fn builds_edges_for_library_augment_directives() -> Result<(), Box<dyn std::error::Error>> {
11
+ let fixture = Fixture::new()?;
12
+ fixture.write("pubspec.yaml", "name: app\n")?;
13
+ let base = fixture.file("lib/base.dart");
14
+ let mut augment = fixture.file("lib/base_augment.dart");
15
+ augment.library = Some(library_augment("base.dart"));
16
+
17
+ let graph = build_module_graph(fixture.root(), &[base, augment])?;
18
+ let dependencies = graph.dependencies();
19
+
20
+ assert_eq!(dependencies.len(), 1);
21
+ assert_eq!(dependencies[0].kind, DependencyKind::Augment);
22
+ assert_eq!(
23
+ strip_root(fixture.root(), &dependencies[0].from_path),
24
+ "lib/base_augment.dart"
25
+ );
26
+ assert_eq!(
27
+ strip_root(fixture.root(), &dependencies[0].to_path),
28
+ "lib/base.dart"
29
+ );
30
+ assert!(graph.unresolved().is_empty());
31
+
32
+ Ok(())
33
+ }
34
+
35
+ #[test]
36
+ fn missing_library_augment_target_is_unresolved() -> Result<(), Box<dyn std::error::Error>> {
37
+ let fixture = Fixture::new()?;
38
+ fixture.write("pubspec.yaml", "name: app\n")?;
39
+ let mut augment = fixture.file("lib/base_augment.dart");
40
+ augment.library = Some(library_augment("base.dart"));
41
+
42
+ let graph = build_module_graph(fixture.root(), &[augment])?;
43
+
44
+ assert_eq!(graph.unresolved().len(), 1);
45
+ assert_eq!(graph.unresolved()[0].kind, DependencyKind::Augment);
46
+ assert_eq!(graph.unresolved()[0].specifier, "base.dart");
47
+ assert_eq!(
48
+ strip_root(fixture.root(), &graph.unresolved()[0].attempted_path),
49
+ "lib/base.dart"
50
+ );
51
+
52
+ Ok(())
53
+ }
54
+
55
+ #[test]
56
+ fn duplicate_part_ownership_is_reported_once() -> Result<(), Box<dyn std::error::Error>> {
57
+ let fixture = Fixture::new()?;
58
+ fixture.write("pubspec.yaml", "name: app\n")?;
59
+ let mut first = fixture.file("lib/a.dart");
60
+ first.library = Some(library_name("app.model"));
61
+ first.parts = vec![part("src/shared_part.dart")];
62
+ let mut second = fixture.file("lib/b.dart");
63
+ second.library = Some(library_name("app.model"));
64
+ second.parts = vec![part("src/shared_part.dart")];
65
+ let mut shared = fixture.file("lib/src/shared_part.dart");
66
+ shared.part_of = Some(part_of_name("app.model"));
67
+
68
+ let graph = build_module_graph(fixture.root(), &[first, second, shared])?;
69
+
70
+ assert_eq!(graph.edge_count(), 1);
71
+ assert_eq!(graph.invalid_part_relationships().len(), 1);
72
+ assert_eq!(
73
+ graph.invalid_part_relationships()[0].reason,
74
+ InvalidPartReason::DuplicatePartOwner {
75
+ existing_library_path: fixture.path("lib/a.dart")
76
+ }
77
+ );
78
+
79
+ Ok(())
80
+ }
81
+
82
+ #[test]
83
+ fn duplicate_part_ownership_wins_over_uri_mismatch() -> Result<(), Box<dyn std::error::Error>> {
84
+ let fixture = Fixture::new()?;
85
+ fixture.write("pubspec.yaml", "name: app\n")?;
86
+ let mut first = fixture.file("lib/a.dart");
87
+ first.parts = vec![part("src/model.g.dart")];
88
+ let mut second = fixture.file("lib/b.dart");
89
+ second.parts = vec![part("src/model.g.dart")];
90
+ let mut generated = fixture.file("lib/src/model.g.dart");
91
+ generated.part_of = Some(part_of_uri("../a.dart"));
92
+
93
+ let graph = build_module_graph(fixture.root(), &[first, second, generated])?;
94
+
95
+ assert_eq!(graph.edge_count(), 1);
96
+ assert_eq!(graph.invalid_part_relationships().len(), 1);
97
+ assert_eq!(
98
+ graph.invalid_part_relationships()[0].reason,
99
+ InvalidPartReason::DuplicatePartOwner {
100
+ existing_library_path: fixture.path("lib/a.dart")
101
+ }
102
+ );
103
+
104
+ Ok(())
105
+ }
106
+
107
+ #[test]
108
+ fn duplicate_part_directives_in_same_library_are_deduped() -> Result<(), Box<dyn std::error::Error>>
109
+ {
110
+ let fixture = Fixture::new()?;
111
+ fixture.write("pubspec.yaml", "name: app\n")?;
112
+ let mut library = fixture.file("lib/model.dart");
113
+ library.library = Some(library_name("app.model"));
114
+ library.parts = vec![part("src/model.g.dart"), part("src/model.g.dart")];
115
+ let mut generated = fixture.file("lib/src/model.g.dart");
116
+ generated.part_of = Some(part_of_name("app.model"));
117
+
118
+ let graph = build_module_graph(fixture.root(), &[library, generated])?;
119
+
120
+ assert_eq!(graph.edge_count(), 1);
121
+ assert!(graph.invalid_part_relationships().is_empty());
122
+
123
+ Ok(())
124
+ }
125
+
126
+ fn library_augment(uri: &str) -> DartLibrary {
127
+ DartLibrary {
128
+ name: None,
129
+ augment_uri: Some(uri.to_owned()),
130
+ location: Location { line: 1, column: 0 },
131
+ }
132
+ }
133
+
134
+ fn library_name(name: &str) -> DartLibrary {
135
+ DartLibrary {
136
+ name: Some(name.to_owned()),
137
+ augment_uri: None,
138
+ location: Location { line: 1, column: 0 },
139
+ }
140
+ }
141
+
142
+ fn part(uri: &str) -> DartPart {
143
+ DartPart {
144
+ uri: uri.to_owned(),
145
+ location: Location { line: 1, column: 0 },
146
+ }
147
+ }
148
+
149
+ fn part_of_name(name: &str) -> DartPartOf {
150
+ DartPartOf {
151
+ name: Some(name.to_owned()),
152
+ uri: None,
153
+ location: Location { line: 1, column: 0 },
154
+ }
155
+ }
156
+
157
+ fn part_of_uri(uri: &str) -> DartPartOf {
158
+ DartPartOf {
159
+ name: None,
160
+ uri: Some(uri.to_owned()),
161
+ location: Location { line: 1, column: 0 },
162
+ }
163
+ }
164
+
165
+ fn strip_root(root: &Path, path: &Path) -> String {
166
+ path.strip_prefix(root)
167
+ .unwrap_or(path)
168
+ .to_string_lossy()
169
+ .replace('\\', "/")
170
+ }
171
+
172
+ struct Fixture {
173
+ temp: TempDir,
174
+ }
175
+
176
+ impl Fixture {
177
+ fn new() -> Result<Self, std::io::Error> {
178
+ tempfile::tempdir().map(|temp| Self { temp })
179
+ }
180
+
181
+ fn root(&self) -> &Path {
182
+ self.temp.path()
183
+ }
184
+
185
+ fn path(&self, path: &str) -> PathBuf {
186
+ normalize_path(&self.root().join(path))
187
+ }
188
+
189
+ fn write(&self, path: &str, source: &str) -> Result<(), std::io::Error> {
190
+ let path = self.path(path);
191
+ if let Some(parent) = path.parent() {
192
+ fs::create_dir_all(parent)?;
193
+ }
194
+ fs::write(path, source)
195
+ }
196
+
197
+ fn file(&self, path: &str) -> DartFile {
198
+ DartFile {
199
+ path: self.path(path),
200
+ library: None,
201
+ part_of: None,
202
+ imports: vec![],
203
+ exports: vec![],
204
+ parts: vec![],
205
+ declarations: vec![],
206
+ members: vec![],
207
+ references: vec![],
208
+ signature_references: vec![],
209
+ routes: vec![],
210
+ }
211
+ }
212
+ }
@@ -0,0 +1,74 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ use crate::{DartExport, DartImport, DartUriCondition, Location};
4
+
5
+ pub(super) fn selected_imports<'a>(
6
+ imports: &'a [DartImport],
7
+ environment: &BTreeMap<String, String>,
8
+ ) -> Vec<&'a DartImport> {
9
+ if environment.is_empty() {
10
+ return imports.iter().collect();
11
+ }
12
+ select_configurable_items(imports, environment, |import| {
13
+ (import.location, import.condition.as_ref())
14
+ })
15
+ }
16
+
17
+ pub(super) fn selected_exports<'a>(
18
+ exports: &'a [DartExport],
19
+ environment: &BTreeMap<String, String>,
20
+ ) -> Vec<&'a DartExport> {
21
+ if environment.is_empty() {
22
+ return exports.iter().collect();
23
+ }
24
+ select_configurable_items(exports, environment, |export| {
25
+ (export.location, export.condition.as_ref())
26
+ })
27
+ }
28
+
29
+ fn select_configurable_items<'a, T>(
30
+ items: &'a [T],
31
+ environment: &BTreeMap<String, String>,
32
+ metadata: impl Fn(&'a T) -> (Location, Option<&'a DartUriCondition>),
33
+ ) -> Vec<&'a T> {
34
+ let mut selected = Vec::new();
35
+ let mut index = 0;
36
+
37
+ while index < items.len() {
38
+ let (location, first_condition) = metadata(&items[index]);
39
+ let mut end = index + 1;
40
+ let mut has_condition = first_condition.is_some();
41
+ while end < items.len() {
42
+ let (next_location, next_condition) = metadata(&items[end]);
43
+ if next_location != location {
44
+ break;
45
+ }
46
+ has_condition |= next_condition.is_some();
47
+ end += 1;
48
+ }
49
+
50
+ let group = &items[index..end];
51
+ if !has_condition {
52
+ selected.extend(group.iter());
53
+ } else if let Some(item) = group.iter().find(|item| {
54
+ metadata(item)
55
+ .1
56
+ .is_some_and(|condition| condition_matches(condition, environment))
57
+ }) {
58
+ selected.push(item);
59
+ } else if let Some(default_item) = group.iter().find(|item| metadata(item).1.is_none()) {
60
+ selected.push(default_item);
61
+ }
62
+
63
+ index = end;
64
+ }
65
+
66
+ selected
67
+ }
68
+
69
+ fn condition_matches(condition: &DartUriCondition, environment: &BTreeMap<String, String>) -> bool {
70
+ environment
71
+ .get(&condition.variable)
72
+ .map_or("false", String::as_str)
73
+ == condition.expected_value
74
+ }
@@ -0,0 +1,100 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use tempfile::TempDir;
5
+
6
+ use super::*;
7
+ use crate::{DartFile, DartImport};
8
+
9
+ #[test]
10
+ fn resolves_package_imports_using_ancestor_package_config_from_member_root()
11
+ -> Result<(), Box<dyn std::error::Error>> {
12
+ let fixture = tempfile::tempdir()?;
13
+ write(
14
+ &fixture,
15
+ ".dart_tool/package_config.json",
16
+ r#"{
17
+ "configVersion": 2,
18
+ "packages": [
19
+ {"name": "app", "rootUri": "../packages/app", "packageUri": "lib/"},
20
+ {"name": "shared", "rootUri": "../packages/shared", "packageUri": "lib/"}
21
+ ]
22
+ }
23
+ "#,
24
+ )?;
25
+ write(
26
+ &fixture,
27
+ "packages/app/pubspec.yaml",
28
+ "name: app\nresolution: workspace\n",
29
+ )?;
30
+ write(
31
+ &fixture,
32
+ "packages/shared/pubspec.yaml",
33
+ "name: shared\nresolution: workspace\n",
34
+ )?;
35
+
36
+ let root = fixture.path().join("packages/app");
37
+ let main = dart_file(
38
+ fixture.path().join("packages/app/lib/main.dart"),
39
+ "package:shared/shared.dart",
40
+ );
41
+ let shared = DartFile {
42
+ path: fixture.path().join("packages/shared/lib/shared.dart"),
43
+ library: None,
44
+ part_of: None,
45
+ imports: Vec::new(),
46
+ exports: Vec::new(),
47
+ parts: Vec::new(),
48
+ declarations: Vec::new(),
49
+ members: Vec::new(),
50
+ references: Vec::new(),
51
+ signature_references: Vec::new(),
52
+ routes: Vec::new(),
53
+ };
54
+
55
+ let graph = build_module_graph(&root, &[main, shared])?;
56
+
57
+ assert_eq!(graph.edge_count(), 1);
58
+ assert_eq!(
59
+ strip_root(fixture.path(), &graph.dependencies()[0].to_path),
60
+ PathBuf::from("packages/shared/lib/shared.dart")
61
+ );
62
+ assert!(graph.unresolved().is_empty());
63
+
64
+ Ok(())
65
+ }
66
+
67
+ fn dart_file(path: PathBuf, import_uri: &str) -> DartFile {
68
+ DartFile {
69
+ path,
70
+ library: None,
71
+ part_of: None,
72
+ imports: vec![DartImport {
73
+ uri: import_uri.to_owned(),
74
+ condition: None,
75
+ prefix: None,
76
+ deferred: false,
77
+ combinators: Vec::new(),
78
+ location: Location { line: 1, column: 0 },
79
+ }],
80
+ exports: Vec::new(),
81
+ parts: Vec::new(),
82
+ declarations: Vec::new(),
83
+ members: Vec::new(),
84
+ references: Vec::new(),
85
+ signature_references: Vec::new(),
86
+ routes: Vec::new(),
87
+ }
88
+ }
89
+
90
+ fn strip_root(root: &Path, path: &Path) -> PathBuf {
91
+ path.strip_prefix(root).unwrap_or(path).to_path_buf()
92
+ }
93
+
94
+ fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
95
+ let path = fixture.path().join(path);
96
+ if let Some(parent) = path.parent() {
97
+ fs::create_dir_all(parent)?;
98
+ }
99
+ fs::write(path, source)
100
+ }
@@ -0,0 +1,248 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use petgraph::graph::NodeIndex;
5
+ use serde::{Deserialize, Serialize};
6
+
7
+ use crate::package_map::PackageMap;
8
+ use crate::{DartFile, Location};
9
+
10
+ use super::{
11
+ DependencyEdge, DependencyGraph, DependencyKind, DependencyVisibility, UnresolvedDependency,
12
+ normalize_against, resolve_local_uri,
13
+ };
14
+
15
+ /// A resolved `part` edge whose target file does not point back to its library.
16
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17
+ pub struct InvalidPartRelationship {
18
+ /// Library file that should own this part, when known.
19
+ pub library_path: Option<PathBuf>,
20
+ /// Part file resolved from the `part` directive.
21
+ pub part_path: PathBuf,
22
+ /// Raw URI from the library's `part` directive.
23
+ pub specifier: String,
24
+ /// Location of the invalid or missing `part of` directive.
25
+ pub location: Location,
26
+ /// Specific consistency failure.
27
+ pub reason: InvalidPartReason,
28
+ }
29
+
30
+ /// Reason a resolved Dart `part` relationship is invalid.
31
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32
+ #[serde(rename_all = "kebab-case")]
33
+ pub enum InvalidPartReason {
34
+ /// The resolved part file has no `part of` directive.
35
+ MissingPartOf,
36
+ /// The `part of` directive has no library name or URI.
37
+ EmptyPartOf,
38
+ /// The file has a `part of` directive but no parsed library has a matching `part`.
39
+ OrphanPartOf {
40
+ /// Library name from the part file, if the directive used a name.
41
+ actual_name: Option<String>,
42
+ /// Library URI from the part file, if the directive used a URI.
43
+ actual_specifier: Option<String>,
44
+ },
45
+ /// Another library already owns this part file.
46
+ DuplicatePartOwner {
47
+ /// Library path that already has a valid `part` edge to this part file.
48
+ existing_library_path: PathBuf,
49
+ },
50
+ /// The `part of` URI could not be resolved as a local Dart file.
51
+ PartOfUriUnresolved {
52
+ /// Raw URI from the part file's `part of` directive.
53
+ actual_specifier: String,
54
+ },
55
+ /// The `part of` URI resolves to a different library file.
56
+ PartOfUriMismatch {
57
+ /// Path the `part` edge expects as the owning library.
58
+ expected_path: PathBuf,
59
+ /// Path resolved from the part file's `part of` URI.
60
+ actual_path: PathBuf,
61
+ /// Raw URI from the part file's `part of` directive.
62
+ actual_specifier: String,
63
+ },
64
+ /// The `part of` library name does not match the source file's library name.
65
+ PartOfNameMismatch {
66
+ /// Library name declared by the source file, if any.
67
+ expected_name: Option<String>,
68
+ /// Library name declared by the part file.
69
+ actual_name: String,
70
+ },
71
+ }
72
+
73
+ #[expect(
74
+ clippy::too_many_arguments,
75
+ reason = "part edges need graph insertion plus reciprocal Dart library validation"
76
+ )]
77
+ pub(super) fn add_part_dependency(
78
+ root: &Path,
79
+ packages: &PackageMap,
80
+ known_paths: &BTreeSet<PathBuf>,
81
+ nodes_by_path: &BTreeMap<PathBuf, NodeIndex>,
82
+ files_by_path: &BTreeMap<PathBuf, &DartFile>,
83
+ graph: &mut DependencyGraph,
84
+ unresolved: &mut Vec<UnresolvedDependency>,
85
+ invalid_part_relationships: &mut Vec<InvalidPartRelationship>,
86
+ referenced_part_paths: &mut BTreeSet<PathBuf>,
87
+ part_owners: &mut BTreeMap<PathBuf, PathBuf>,
88
+ from_index: NodeIndex,
89
+ from_path: &Path,
90
+ library: &DartFile,
91
+ specifier: &str,
92
+ location: Location,
93
+ ) {
94
+ let Some(target) = resolve_local_uri(root, packages, from_path, specifier) else {
95
+ return;
96
+ };
97
+ let target_path = target.path;
98
+
99
+ if !known_paths.contains(&target_path) {
100
+ if target.local {
101
+ unresolved.push(UnresolvedDependency {
102
+ from_path: from_path.to_path_buf(),
103
+ specifier: specifier.to_owned(),
104
+ kind: DependencyKind::Part,
105
+ location,
106
+ attempted_path: target_path,
107
+ visibility: DependencyVisibility::default(),
108
+ });
109
+ }
110
+ return;
111
+ }
112
+
113
+ referenced_part_paths.insert(target_path.clone());
114
+ if let Some(existing_library_path) = part_owners.get(&target_path) {
115
+ if existing_library_path == from_path {
116
+ return;
117
+ }
118
+ invalid_part_relationships.push(InvalidPartRelationship {
119
+ library_path: Some(from_path.to_path_buf()),
120
+ part_path: target_path.clone(),
121
+ specifier: specifier.to_owned(),
122
+ location: files_by_path
123
+ .get(&target_path)
124
+ .and_then(|part| part.part_of.as_ref().map(|part_of| part_of.location))
125
+ .unwrap_or(location),
126
+ reason: InvalidPartReason::DuplicatePartOwner {
127
+ existing_library_path: existing_library_path.clone(),
128
+ },
129
+ });
130
+ return;
131
+ }
132
+ if let Some(part) = files_by_path.get(&target_path).copied() {
133
+ if let Some(relationship) =
134
+ invalid_part_relationship(root, packages, library, part, specifier)
135
+ {
136
+ invalid_part_relationships.push(relationship);
137
+ return;
138
+ }
139
+ }
140
+ part_owners.insert(target_path.clone(), from_path.to_path_buf());
141
+
142
+ let Some(target_index) = nodes_by_path.get(&target_path).copied() else {
143
+ return;
144
+ };
145
+
146
+ graph.add_edge(
147
+ from_index,
148
+ target_index,
149
+ DependencyEdge {
150
+ specifier: specifier.to_owned(),
151
+ kind: DependencyKind::Part,
152
+ location,
153
+ visibility: DependencyVisibility::default(),
154
+ },
155
+ );
156
+ }
157
+
158
+ pub(super) fn add_orphan_part_relationships(
159
+ root: &Path,
160
+ packages: &PackageMap,
161
+ files_by_path: &BTreeMap<PathBuf, &DartFile>,
162
+ referenced_part_paths: &BTreeSet<PathBuf>,
163
+ invalid_part_relationships: &mut Vec<InvalidPartRelationship>,
164
+ ) {
165
+ for (part_path, file) in files_by_path {
166
+ let Some(part_of) = &file.part_of else {
167
+ continue;
168
+ };
169
+ if referenced_part_paths.contains(part_path) {
170
+ continue;
171
+ }
172
+ let library_path = part_of.uri.as_ref().and_then(|uri| {
173
+ resolve_local_uri(root, packages, part_path, uri)
174
+ .filter(|target| target.local)
175
+ .map(|target| target.path)
176
+ });
177
+ invalid_part_relationships.push(InvalidPartRelationship {
178
+ library_path,
179
+ part_path: part_path.clone(),
180
+ specifier: part_of
181
+ .uri
182
+ .clone()
183
+ .or_else(|| part_of.name.clone())
184
+ .unwrap_or_default(),
185
+ location: part_of.location,
186
+ reason: InvalidPartReason::OrphanPartOf {
187
+ actual_name: part_of.name.clone(),
188
+ actual_specifier: part_of.uri.clone(),
189
+ },
190
+ });
191
+ }
192
+ }
193
+
194
+ fn invalid_part_relationship(
195
+ root: &Path,
196
+ packages: &PackageMap,
197
+ library: &DartFile,
198
+ part: &DartFile,
199
+ specifier: &str,
200
+ ) -> Option<InvalidPartRelationship> {
201
+ let library_path = normalize_against(root, &library.path);
202
+ let part_path = normalize_against(root, &part.path);
203
+ let Some(part_of) = &part.part_of else {
204
+ return Some(InvalidPartRelationship {
205
+ library_path: Some(library_path),
206
+ part_path,
207
+ specifier: specifier.to_owned(),
208
+ location: Location { line: 1, column: 0 },
209
+ reason: InvalidPartReason::MissingPartOf,
210
+ });
211
+ };
212
+
213
+ let reason = if let Some(uri) = &part_of.uri {
214
+ match resolve_local_uri(root, packages, &part_path, uri) {
215
+ Some(target) if target.path == library_path => return None,
216
+ Some(target) => InvalidPartReason::PartOfUriMismatch {
217
+ expected_path: library_path.clone(),
218
+ actual_path: target.path,
219
+ actual_specifier: uri.clone(),
220
+ },
221
+ None => InvalidPartReason::PartOfUriUnresolved {
222
+ actual_specifier: uri.clone(),
223
+ },
224
+ }
225
+ } else if let Some(name) = &part_of.name {
226
+ let expected_name = library
227
+ .library
228
+ .as_ref()
229
+ .and_then(|library| library.name.clone());
230
+ if expected_name.as_deref() == Some(name.as_str()) {
231
+ return None;
232
+ }
233
+ InvalidPartReason::PartOfNameMismatch {
234
+ expected_name,
235
+ actual_name: name.clone(),
236
+ }
237
+ } else {
238
+ InvalidPartReason::EmptyPartOf
239
+ };
240
+
241
+ Some(InvalidPartRelationship {
242
+ library_path: Some(library_path),
243
+ part_path,
244
+ specifier: specifier.to_owned(),
245
+ location: part_of.location,
246
+ reason,
247
+ })
248
+ }