dart-decimate 0.0.28 → 0.0.30

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 (70) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +36 -60
  4. package/npm/bin/runner.js +26 -14
  5. package/npm/scripts/postinstall.js +89 -63
  6. package/package.json +6 -5
  7. package/src/baseline.rs +38 -0
  8. package/src/cli/health_args.rs +36 -7
  9. package/src/cli/html_open.rs +4 -0
  10. package/src/cli/issue_filter_args.rs +1 -0
  11. package/src/cli/security_summary_run.rs +1 -0
  12. package/src/config/health.rs +22 -2
  13. package/src/config/rule_aliases.rs +43 -0
  14. package/src/config/rules.rs +46 -1
  15. package/src/config.rs +2 -1
  16. package/src/dart_parser/test_support.rs +51 -0
  17. package/src/dart_parser.rs +8 -0
  18. package/src/dependencies/analyze.rs +3 -1
  19. package/src/dependencies/tests.rs +111 -7
  20. package/src/dependencies/usage.rs +5 -1
  21. package/src/dependencies.rs +7 -3
  22. package/src/explain/flutter_style.rs +43 -0
  23. package/src/explain/misc.rs +72 -0
  24. package/src/explain.rs +23 -67
  25. package/src/flutter_style/scanner.rs +883 -0
  26. package/src/flutter_style/types.rs +90 -0
  27. package/src/flutter_style/usage.rs +349 -0
  28. package/src/flutter_style.rs +72 -0
  29. package/src/generated.rs +154 -0
  30. package/src/health/large_units.rs +49 -0
  31. package/src/health/tests.rs +212 -1
  32. package/src/health/threshold_types.rs +31 -1
  33. package/src/health/thresholds.rs +49 -0
  34. package/src/health/types.rs +35 -0
  35. package/src/health.rs +72 -6
  36. package/src/inspect.rs +8 -0
  37. package/src/lib.rs +17 -5
  38. package/src/manifest.rs +7 -3
  39. package/src/output/dependency_findings.rs +14 -1
  40. package/src/output/flutter_style.rs +189 -0
  41. package/src/output/health_findings.rs +93 -10
  42. package/src/output/health_inventory.rs +121 -0
  43. package/src/output/html/tests.rs +20 -0
  44. package/src/output/html.rs +10 -1
  45. package/src/output/human.rs +85 -1
  46. package/src/output/human_details.rs +93 -12
  47. package/src/output/scope.rs +62 -2
  48. package/src/output/security_findings.rs +101 -76
  49. package/src/output/security_sarif.rs +24 -13
  50. package/src/output/suppressions.rs +4 -0
  51. package/src/output/types.rs +38 -2
  52. package/src/output/verdict.rs +12 -0
  53. package/src/output.rs +77 -74
  54. package/src/report_schema/inventory.rs +268 -4
  55. package/src/report_schema.rs +94 -60
  56. package/src/security/catalogue.rs +103 -0
  57. package/src/security/detect/weak_randomness.rs +762 -0
  58. package/src/security/detect.rs +1535 -221
  59. package/src/security/security_matchers.toml +172 -0
  60. package/src/security/tests.rs +336 -2
  61. package/src/security.rs +292 -56
  62. package/src/security_gate.rs +28 -0
  63. package/src/semantic.rs +276 -0
  64. package/src/symbols/semantic_evidence.rs +342 -0
  65. package/src/symbols.rs +20 -10
  66. package/src/trace/rendering.rs +54 -0
  67. package/src/trace/semantic.rs +126 -0
  68. package/src/trace.rs +54 -62
  69. package/src/widgets/inheritance.rs +63 -0
  70. package/src/widgets.rs +33 -3
@@ -0,0 +1,90 @@
1
+ use std::path::PathBuf;
2
+
3
+ use serde::{Deserialize, Serialize};
4
+
5
+ use crate::Location;
6
+
7
+ /// Opt-in Flutter style advisory category.
8
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
9
+ #[serde(rename_all = "kebab-case")]
10
+ pub enum FlutterStyleFindingKind {
11
+ /// A raw theme-able value has a resolvable project token.
12
+ RawFlutterStyleValue,
13
+ /// Two custom color tokens are close enough to merit consolidation review.
14
+ NearDuplicateThemeToken,
15
+ /// A custom `ThemeExtension` field has no observed member access.
16
+ UnusedThemeExtensionToken,
17
+ }
18
+
19
+ impl FlutterStyleFindingKind {
20
+ /// Stable rule identifier.
21
+ #[must_use]
22
+ pub const fn rule_id(self) -> &'static str {
23
+ match self {
24
+ Self::RawFlutterStyleValue => "dart-decimate/raw-flutter-style-value",
25
+ Self::NearDuplicateThemeToken => "dart-decimate/near-duplicate-theme-token",
26
+ Self::UnusedThemeExtensionToken => "dart-decimate/unused-theme-extension-token",
27
+ }
28
+ }
29
+ }
30
+
31
+ /// Theme-able value category.
32
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
33
+ #[serde(rename_all = "kebab-case")]
34
+ pub enum FlutterStyleValueKind {
35
+ /// Flutter `Color` value.
36
+ Color,
37
+ /// Flutter `TextStyle` value.
38
+ TextStyle,
39
+ }
40
+
41
+ /// Exact source evidence for a known theme token.
42
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43
+ pub struct ThemeTokenEvidence {
44
+ /// Stable field/role name.
45
+ pub name: String,
46
+ /// Source file containing the token definition.
47
+ pub path: PathBuf,
48
+ /// Token declaration or configured-value location.
49
+ pub location: Location,
50
+ /// Token value category.
51
+ pub value_kind: FlutterStyleValueKind,
52
+ /// Normalized source value when supported.
53
+ pub value: Option<String>,
54
+ /// Whether this token belongs to a custom `ThemeExtension`.
55
+ pub custom: bool,
56
+ #[serde(skip)]
57
+ pub(super) argb: Option<u32>,
58
+ #[serde(skip)]
59
+ pub(super) owner: Option<String>,
60
+ #[serde(skip)]
61
+ pub(super) declared_field: bool,
62
+ }
63
+
64
+ /// One advisory Flutter style row.
65
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66
+ pub struct FlutterStyleFinding {
67
+ /// Advisory category.
68
+ pub kind: FlutterStyleFindingKind,
69
+ /// Source file containing the candidate.
70
+ pub path: PathBuf,
71
+ /// Candidate source location.
72
+ pub location: Location,
73
+ /// Theme-able value category.
74
+ pub value_kind: FlutterStyleValueKind,
75
+ /// Normalized raw value when supported.
76
+ pub value: Option<String>,
77
+ /// Primary token for token-pair and unused-token rows.
78
+ pub token: Option<ThemeTokenEvidence>,
79
+ /// Deterministically selected nearest token.
80
+ pub nearest_token: Option<ThemeTokenEvidence>,
81
+ /// Deterministic ARGB distance formatted to two decimal places.
82
+ pub distance: Option<String>,
83
+ }
84
+
85
+ /// Opt-in Flutter style advisory report.
86
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
87
+ pub struct FlutterStyleReport {
88
+ /// Deterministically sorted advisory rows.
89
+ pub findings: Vec<FlutterStyleFinding>,
90
+ }
@@ -0,0 +1,349 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+
3
+ use tree_sitter::Node;
4
+
5
+ use super::ParsedSourceUnit;
6
+
7
+ #[derive(Clone)]
8
+ struct ExtensionAlias {
9
+ name: String,
10
+ owner: Option<String>,
11
+ declaration: usize,
12
+ scope_start: usize,
13
+ scope_end: usize,
14
+ }
15
+
16
+ pub(super) fn used_extension_properties(
17
+ units: &[ParsedSourceUnit<'_>],
18
+ extension_names: &BTreeSet<String>,
19
+ ) -> BTreeSet<(String, String)> {
20
+ let factories = extension_factories(units, extension_names);
21
+ let mut used = BTreeSet::new();
22
+ for parsed_unit in units {
23
+ let parsed = &parsed_unit.parsed;
24
+ let aliases = extension_aliases(
25
+ parsed.tree().root_node(),
26
+ parsed.source(),
27
+ extension_names,
28
+ &factories,
29
+ );
30
+ walk(parsed.tree().root_node(), &mut |node| {
31
+ collect_usage(
32
+ node,
33
+ parsed.source(),
34
+ extension_names,
35
+ &factories,
36
+ &aliases,
37
+ &mut used,
38
+ );
39
+ });
40
+ }
41
+ used
42
+ }
43
+
44
+ fn extension_factories(
45
+ units: &[ParsedSourceUnit<'_>],
46
+ extension_names: &BTreeSet<String>,
47
+ ) -> BTreeMap<String, String> {
48
+ let mut candidates = BTreeMap::<String, Vec<Option<String>>>::new();
49
+ for parsed_unit in units {
50
+ let parsed = &parsed_unit.parsed;
51
+ walk(parsed.tree().root_node(), &mut |node| {
52
+ if !matches!(
53
+ node.kind(),
54
+ "function_declaration" | "getter_declaration" | "method_declaration"
55
+ ) {
56
+ return;
57
+ }
58
+ let Some(name) = callable_name(node, parsed.source()) else {
59
+ return;
60
+ };
61
+ let mut returns = Vec::new();
62
+ walk(node, &mut |candidate| {
63
+ if candidate.kind() == "return_statement" && belongs_to_callable(candidate, node) {
64
+ returns.push(direct_extension_owner(
65
+ node_text(candidate, parsed.source()),
66
+ extension_names,
67
+ ));
68
+ }
69
+ });
70
+ if returns.is_empty() {
71
+ let body = first_descendant(node, "function_body")
72
+ .map(|body| node_text(body, parsed.source()))
73
+ .unwrap_or_default();
74
+ if body.trim_start().starts_with("=>") {
75
+ returns.push(direct_extension_owner(body, extension_names));
76
+ }
77
+ }
78
+ let key = enclosing_class_name(node, parsed.source())
79
+ .map_or(name.clone(), |class| format!("{class}.{name}"));
80
+ candidates
81
+ .entry(key)
82
+ .or_default()
83
+ .push(one_proven_owner(&returns));
84
+ });
85
+ }
86
+ candidates
87
+ .into_iter()
88
+ .filter_map(|(key, owners)| one_proven_owner(&owners).map(|owner| (key, owner)))
89
+ .collect()
90
+ }
91
+
92
+ fn extension_aliases(
93
+ root: Node<'_>,
94
+ source: &str,
95
+ extension_names: &BTreeSet<String>,
96
+ factories: &BTreeMap<String, String>,
97
+ ) -> Vec<ExtensionAlias> {
98
+ let mut aliases = Vec::new();
99
+ walk(root, &mut |node| {
100
+ if !matches!(
101
+ node.kind(),
102
+ "initialized_identifier" | "initialized_variable_definition"
103
+ ) {
104
+ return;
105
+ }
106
+ let Some(name) = field_text(node, "name", source) else {
107
+ return;
108
+ };
109
+ let Some(value) = node.child_by_field_name("value") else {
110
+ return;
111
+ };
112
+ let owner =
113
+ extension_owner_from_expression(node_text(value, source), extension_names, factories);
114
+ let scope = lexical_scope(node).unwrap_or(root);
115
+ aliases.push(ExtensionAlias {
116
+ name,
117
+ owner,
118
+ declaration: node.start_byte(),
119
+ scope_start: scope.start_byte(),
120
+ scope_end: scope.end_byte(),
121
+ });
122
+ });
123
+ aliases.sort_by_key(|alias| (alias.declaration, alias.scope_start, alias.scope_end));
124
+ aliases
125
+ }
126
+
127
+ fn collect_usage(
128
+ node: Node<'_>,
129
+ source: &str,
130
+ extension_names: &BTreeSet<String>,
131
+ factories: &BTreeMap<String, String>,
132
+ aliases: &[ExtensionAlias],
133
+ used: &mut BTreeSet<(String, String)>,
134
+ ) {
135
+ if !matches!(
136
+ node.kind(),
137
+ "member_expression" | "null_aware_member_expression"
138
+ ) || has_extension_class_ancestor(node, source, extension_names)
139
+ {
140
+ return;
141
+ }
142
+ let Some(property) = field_text(node, "property", source) else {
143
+ return;
144
+ };
145
+ let Some(receiver) = field_text(node, "object", source) else {
146
+ return;
147
+ };
148
+ let owner =
149
+ extension_owner_from_expression(&receiver, extension_names, factories).or_else(|| {
150
+ let receiver = receiver.trim();
151
+ is_identifier(receiver).then(|| {
152
+ aliases
153
+ .iter()
154
+ .rev()
155
+ .find(|alias| {
156
+ alias.name == receiver
157
+ && alias.declaration < node.start_byte()
158
+ && alias.scope_start <= node.start_byte()
159
+ && alias.scope_end >= node.end_byte()
160
+ })
161
+ .and_then(|alias| alias.owner.clone())
162
+ })?
163
+ });
164
+ if let Some(owner) = owner {
165
+ used.insert((owner, property));
166
+ }
167
+ }
168
+
169
+ fn extension_owner_from_expression(
170
+ expression: &str,
171
+ extension_names: &BTreeSet<String>,
172
+ factories: &BTreeMap<String, String>,
173
+ ) -> Option<String> {
174
+ if let Some(owner) = direct_extension_owner(expression, extension_names) {
175
+ return Some(owner);
176
+ }
177
+ let compact = expression.split_whitespace().collect::<String>();
178
+ let owners = factories
179
+ .iter()
180
+ .filter(|(factory, _)| contains_call(&compact, factory))
181
+ .map(|(_, owner)| owner.clone())
182
+ .collect::<BTreeSet<_>>();
183
+ (owners.len() == 1)
184
+ .then(|| owners.into_iter().next())
185
+ .flatten()
186
+ }
187
+
188
+ fn direct_extension_owner(expression: &str, extension_names: &BTreeSet<String>) -> Option<String> {
189
+ let compact = expression.split_whitespace().collect::<String>();
190
+ let owners = compact
191
+ .match_indices("extension<")
192
+ .filter_map(|(index, _)| {
193
+ let rest = compact.get(index + "extension<".len()..)?;
194
+ let generic = rest.split('>').next()?;
195
+ let owner = generic.rsplit('.').next()?;
196
+ extension_names.contains(owner).then(|| owner.to_owned())
197
+ })
198
+ .collect::<BTreeSet<_>>();
199
+ (owners.len() == 1)
200
+ .then(|| owners.into_iter().next())
201
+ .flatten()
202
+ }
203
+
204
+ fn one_proven_owner(returns: &[Option<String>]) -> Option<String> {
205
+ if returns.is_empty() || returns.iter().any(Option::is_none) {
206
+ return None;
207
+ }
208
+ let owners = returns.iter().flatten().cloned().collect::<BTreeSet<_>>();
209
+ (owners.len() == 1)
210
+ .then(|| owners.into_iter().next())
211
+ .flatten()
212
+ }
213
+
214
+ fn contains_call(expression: &str, callee: &str) -> bool {
215
+ let mut offset = 0usize;
216
+ while let Some(relative) = expression.get(offset..).and_then(|rest| rest.find(callee)) {
217
+ let index = offset + relative;
218
+ let before = index
219
+ .checked_sub(1)
220
+ .and_then(|position| expression.as_bytes().get(position));
221
+ let after = expression.as_bytes().get(index + callee.len());
222
+ if before.is_none_or(|byte| !is_identifier_byte(*byte)) && after == Some(&b'(') {
223
+ return true;
224
+ }
225
+ offset = index + callee.len();
226
+ }
227
+ false
228
+ }
229
+
230
+ fn lexical_scope(mut node: Node<'_>) -> Option<Node<'_>> {
231
+ while let Some(parent) = node.parent() {
232
+ if matches!(
233
+ parent.kind(),
234
+ "block"
235
+ | "catch_clause"
236
+ | "class_body"
237
+ | "compilation_unit"
238
+ | "do_statement"
239
+ | "for_element"
240
+ | "for_statement"
241
+ | "if_element"
242
+ | "if_statement"
243
+ | "switch_expression_case"
244
+ | "switch_statement_case"
245
+ | "while_statement"
246
+ ) {
247
+ return Some(parent);
248
+ }
249
+ node = parent;
250
+ }
251
+ None
252
+ }
253
+
254
+ fn belongs_to_callable(mut node: Node<'_>, callable: Node<'_>) -> bool {
255
+ while let Some(parent) = node.parent() {
256
+ if parent.id() == callable.id() {
257
+ return true;
258
+ }
259
+ if matches!(
260
+ parent.kind(),
261
+ "function_declaration"
262
+ | "function_expression"
263
+ | "getter_declaration"
264
+ | "method_declaration"
265
+ ) {
266
+ return false;
267
+ }
268
+ node = parent;
269
+ }
270
+ false
271
+ }
272
+
273
+ fn enclosing_class_name(mut node: Node<'_>, source: &str) -> Option<String> {
274
+ while let Some(parent) = node.parent() {
275
+ if parent.kind() == "class_declaration" {
276
+ return field_text(parent, "name", source);
277
+ }
278
+ node = parent;
279
+ }
280
+ None
281
+ }
282
+
283
+ fn callable_name(node: Node<'_>, source: &str) -> Option<String> {
284
+ if matches!(
285
+ node.kind(),
286
+ "function_signature" | "getter_signature" | "setter_signature"
287
+ ) {
288
+ return field_text(node, "name", source);
289
+ }
290
+ let mut cursor = node.walk();
291
+ node.named_children(&mut cursor)
292
+ .find_map(|child| callable_name(child, source))
293
+ }
294
+
295
+ fn first_descendant<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
296
+ if node.kind() == kind {
297
+ return Some(node);
298
+ }
299
+ let mut cursor = node.walk();
300
+ node.named_children(&mut cursor)
301
+ .find_map(|child| first_descendant(child, kind))
302
+ }
303
+
304
+ fn has_extension_class_ancestor(
305
+ mut node: Node<'_>,
306
+ source: &str,
307
+ extension_names: &BTreeSet<String>,
308
+ ) -> bool {
309
+ while let Some(parent) = node.parent() {
310
+ if parent.kind() == "class_declaration" {
311
+ return field_text(parent, "name", source)
312
+ .is_some_and(|name| extension_names.contains(&name));
313
+ }
314
+ node = parent;
315
+ }
316
+ false
317
+ }
318
+
319
+ fn field_text(node: Node<'_>, field: &str, source: &str) -> Option<String> {
320
+ node.child_by_field_name(field)
321
+ .and_then(|child| child.utf8_text(source.as_bytes()).ok())
322
+ .map(str::to_owned)
323
+ }
324
+
325
+ fn node_text<'source>(node: Node<'_>, source: &'source str) -> &'source str {
326
+ node.utf8_text(source.as_bytes()).unwrap_or_default()
327
+ }
328
+
329
+ fn is_identifier(value: &str) -> bool {
330
+ let mut characters = value.chars();
331
+ characters
332
+ .next()
333
+ .is_some_and(|character| character == '_' || character.is_ascii_alphabetic())
334
+ && characters.all(|character| {
335
+ character == '_' || character == '$' || character.is_ascii_alphanumeric()
336
+ })
337
+ }
338
+
339
+ fn is_identifier_byte(byte: u8) -> bool {
340
+ byte == b'_' || byte == b'$' || byte.is_ascii_alphanumeric()
341
+ }
342
+
343
+ fn walk(node: Node<'_>, visit: &mut impl FnMut(Node<'_>)) {
344
+ visit(node);
345
+ let mut cursor = node.walk();
346
+ for child in node.named_children(&mut cursor) {
347
+ walk(child, visit);
348
+ }
349
+ }
@@ -0,0 +1,72 @@
1
+ use std::fs;
2
+ use std::path::PathBuf;
3
+
4
+ use crate::generated::is_generated_dart_path;
5
+ use crate::graph::normalize_against;
6
+ use crate::{HealthError, ScannedProject};
7
+
8
+ mod scanner;
9
+ mod types;
10
+ mod usage;
11
+ pub use types::{
12
+ FlutterStyleFinding, FlutterStyleFindingKind, FlutterStyleReport, FlutterStyleValueKind,
13
+ ThemeTokenEvidence,
14
+ };
15
+
16
+ struct SourceUnit {
17
+ path: PathBuf,
18
+ source: String,
19
+ }
20
+
21
+ struct ParsedSourceUnit<'source> {
22
+ unit: &'source SourceUnit,
23
+ parsed: crate::dart_parser::ParsedDart<'source>,
24
+ }
25
+
26
+ /// Analyze opt-in Flutter theme usage with conservative syntax evidence.
27
+ ///
28
+ /// # Errors
29
+ ///
30
+ /// Returns [`HealthError`] when an included source file cannot be read or parsed.
31
+ pub fn analyze_flutter_style(project: &ScannedProject) -> Result<FlutterStyleReport, HealthError> {
32
+ let mut units = Vec::new();
33
+ for file in &project.files {
34
+ let path = normalize_against(&project.root, &file.path);
35
+ if !path.starts_with(&project.root) || ignored_style_path(&path) {
36
+ continue;
37
+ }
38
+ let source = fs::read_to_string(&path).map_err(|source| HealthError::ReadFile {
39
+ path: path.clone(),
40
+ source,
41
+ })?;
42
+ units.push(SourceUnit { path, source });
43
+ }
44
+ scanner::analyze(&units)
45
+ }
46
+
47
+ fn ignored_style_path(path: &std::path::Path) -> bool {
48
+ is_generated_dart_path(path)
49
+ || path.components().any(|component| {
50
+ matches!(
51
+ component.as_os_str().to_str(),
52
+ Some(
53
+ "test"
54
+ | "integration_test"
55
+ | "test_driver"
56
+ | "__tests__"
57
+ | "__mocks__"
58
+ | "example"
59
+ )
60
+ )
61
+ })
62
+ }
63
+
64
+ fn style_parse_error(error: crate::dart_parser::DartParseError) -> HealthError {
65
+ match error {
66
+ crate::dart_parser::DartParseError::Language(source) => HealthError::Language(source),
67
+ crate::dart_parser::DartParseError::ParseCancelled { path }
68
+ | crate::dart_parser::DartParseError::Syntax { path } => {
69
+ HealthError::ParseCancelled { path }
70
+ }
71
+ }
72
+ }