blast-radius 0.7.2

Analyze the transitive blast radius of code changes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};

use crate::cli::{Cli, Command};
use crate::fs::RepoContext;
use crate::graph::{
    AnalysisMode, AnalysisResult, AnalysisTarget, EdgeKind, GraphEdge, GraphNode, ModuleState,
    NodeKind, Summary,
};
use crate::parse::{ExportKind, ModuleFacts, ReexportTarget, parse_module};
use crate::resolve::{Resolution, Resolver};

mod walk;
use walk::{ConsumerLink, build_reverse_links, compute_root_impacts, import_edge_kind, run_bfs};

mod result;
use result::{ResultMetadata, build_result, collect_workspaces};

mod diagnostics;
use diagnostics::unresolved_import_diagnostics;

struct AnalysisData<'a> {
    context: &'a RepoContext,
    modules: &'a BTreeMap<PathBuf, ModuleFacts>,
    module_states: &'a BTreeMap<PathBuf, ModuleState>,
    reverse: &'a BTreeMap<PathBuf, Vec<ConsumerLink>>,
}

/// Run-level diagnostics gathered before the graph walk, folded into the result.
struct RunDiagnostics {
    warnings: Vec<String>,
    parse_failures: usize,
    unresolved_imports: usize,
    skipped_inputs: usize,
}

pub(super) struct ResolutionCache<'a> {
    resolver: &'a Resolver,
    entries: BTreeMap<(PathBuf, String), Resolution>,
}

impl<'a> ResolutionCache<'a> {
    fn new(resolver: &'a Resolver) -> Self {
        Self {
            resolver,
            entries: BTreeMap::new(),
        }
    }

    pub(super) fn resolve(&mut self, importer: &Path, specifier: &str) -> Resolution {
        let key = (importer.to_path_buf(), specifier.to_string());
        if let Some(resolution) = self.entries.get(&key) {
            return resolution.clone();
        }

        let resolution = self.resolver.resolve(importer, specifier);
        self.entries.insert(key, resolution.clone());
        resolution
    }

    pub(super) fn is_internal_specifier(&self, importer: &Path, specifier: &str) -> bool {
        self.resolver.is_internal_specifier(importer, specifier)
    }
}

pub fn run(cli: &Cli, context: &RepoContext) -> Result<AnalysisResult> {
    let resolver = Resolver::new(context)?;
    let mut resolution_cache = ResolutionCache::new(&resolver);
    let (modules, mut warnings, parse_failures) = load_modules(context);
    warnings.splice(0..0, context.warnings.iter().cloned());
    let module_states = build_module_states(&modules);
    let reverse = build_reverse_links(&modules, &module_states, &mut resolution_cache);
    let unresolved = unresolved_import_diagnostics(
        &modules,
        &mut resolution_cache,
        &context.ignore_unresolved,
        &context.repo_root,
        cli.explain_unresolved,
    );
    warnings.extend(unresolved.warnings);
    let analysis_data = AnalysisData {
        context,
        modules: &modules,
        module_states: &module_states,
        reverse: &reverse,
    };

    match &cli.command {
        // Handled in main before analysis ever runs.
        Command::Completions { .. } => bail!("completions does not run analysis"),
        Command::Graph => Ok(build_graph_result(
            context,
            &modules,
            &mut resolution_cache,
            warnings,
            parse_failures,
            unresolved.count,
        )),
        Command::Export { file, export_name } => {
            let file = normalize_input_path(&context.repo_root, file)?;
            if !modules.contains_key(&file) {
                bail!(
                    "source file not found in repository index: {}",
                    file.display()
                );
            }
            validate_export_name(
                &file,
                export_name,
                &modules,
                &module_states,
                &context.repo_root,
                &mut warnings,
            )?;
            let exports =
                expanded_exports_for_root(&file, std::slice::from_ref(export_name), &module_states);

            analyze_from_roots(
                AnalysisMode::Export,
                AnalysisTarget::Export {
                    file: file.clone(),
                    export_name: export_name.clone(),
                },
                &analysis_data,
                RunDiagnostics {
                    warnings,
                    parse_failures,
                    unresolved_imports: unresolved.count,
                    skipped_inputs: 0,
                },
                vec![(file, exports)],
            )
        }
        Command::File { file } => {
            let file = normalize_input_path(&context.repo_root, file)?;
            if !modules.contains_key(&file) {
                bail!(
                    "source file not found in repository index: {}",
                    file.display()
                );
            }

            let exports = file_root_exports(&file, &module_states);

            analyze_from_roots(
                AnalysisMode::File,
                AnalysisTarget::File { file: file.clone() },
                &analysis_data,
                RunDiagnostics {
                    warnings,
                    parse_failures,
                    unresolved_imports: unresolved.count,
                    skipped_inputs: 0,
                },
                vec![(file, exports)],
            )
        }
        Command::Files { files } => {
            let mut roots = Vec::new();
            let mut normalized = Vec::new();
            let mut skipped_inputs = 0;
            // `files` mode is the entry point hook managers (lint-staged, Husky,
            // Lefthook) pipe changed paths into. Those batches can include
            // deleted/renamed files and non-source paths, so skip-and-warn on
            // anything we can't analyze rather than failing the whole run.
            let mut seen = BTreeSet::new();
            for file in files {
                let input = file.display().to_string();
                let Ok(file) = normalize_input_path(&context.repo_root, file) else {
                    skipped_inputs += 1;
                    warnings.push(format!("skipped input {input}: not found on disk"));
                    continue;
                };
                if !seen.insert(file.clone()) {
                    continue;
                }
                if !modules.contains_key(&file) {
                    skipped_inputs += 1;
                    warnings.push(format!(
                        "skipped input {}: not a recognized source file",
                        relative_label(&context.repo_root, &file)
                    ));
                    continue;
                }
                let exports = file_root_exports(&file, &module_states);
                roots.push((file.clone(), exports));
                normalized.push(file);
            }

            if normalized.is_empty() {
                warnings.push(format!(
                    "no recognized source files among {} input path{}",
                    files.len(),
                    if files.len() == 1 { "" } else { "s" }
                ));
            }

            analyze_from_roots(
                AnalysisMode::Files,
                AnalysisTarget::Files { files: normalized },
                &analysis_data,
                RunDiagnostics {
                    warnings,
                    parse_failures,
                    unresolved_imports: unresolved.count,
                    skipped_inputs,
                },
                roots,
            )
        }
    }
}

/// Reject an export name the target file provably does not expose. When the
/// file's exports are not statically enumerable (star re-exports, whole-module
/// CommonJS assignment, or no parsed exports at all), proceed with a warning
/// instead of failing the run.
fn validate_export_name(
    file: &Path,
    export_name: &str,
    modules: &BTreeMap<PathBuf, ModuleFacts>,
    module_states: &BTreeMap<PathBuf, ModuleState>,
    repo_root: &Path,
    warnings: &mut Vec<String>,
) -> Result<()> {
    let known = module_states.get(file).map(|state| &state.public_exports);
    if known.is_some_and(|exports| exports.contains(export_name)) {
        return Ok(());
    }

    let module = modules.get(file);
    let has_star_reexport = module.is_some_and(|module| {
        module
            .reexports
            .iter()
            .any(|reexport| matches!(reexport.imported, ReexportTarget::All))
    });
    let has_opaque_commonjs = module.is_some_and(|module| {
        module
            .exports
            .iter()
            .any(|export| export.kind == ExportKind::CommonJs && export.local.is_none())
    });
    let enumerable = known.is_some_and(|exports| !exports.is_empty());

    if has_star_reexport || has_opaque_commonjs || !enumerable {
        warnings.push(format!(
            "export '{export_name}' is not a statically-known export of {}; \
             continuing because the file's exports are not fully enumerable",
            relative_label(repo_root, file)
        ));
        return Ok(());
    }

    let available = known
        .into_iter()
        .flatten()
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(", ");
    bail!(
        "export '{export_name}' not found in {}; available exports: {available}",
        relative_label(repo_root, file)
    );
}

fn file_root_exports(
    file: &Path,
    module_states: &BTreeMap<PathBuf, ModuleState>,
) -> BTreeSet<String> {
    module_states
        .get(file)
        .map(|state| {
            if state.public_exports.is_empty() {
                BTreeSet::from([String::from("*file*")])
            } else {
                state.public_exports.clone()
            }
        })
        .unwrap_or_else(|| BTreeSet::from([String::from("*file*")]))
}

fn load_modules(context: &RepoContext) -> (BTreeMap<PathBuf, ModuleFacts>, Vec<String>, usize) {
    use rayon::prelude::*;

    // Parsing each file is independent, so fan the parses out across cores. The
    // results are collected in source order and folded sequentially below, so
    // the module map, warning order, and failure count are identical regardless
    // of how many threads ran — tests and the accuracy oracle depend on that.
    let parsed: Vec<(PathBuf, Result<ModuleFacts>)> = context
        .source_files
        .par_iter()
        .map(|file| (file.clone(), parse_module(file)))
        .collect();

    let mut modules = BTreeMap::new();
    let mut warnings = Vec::new();
    let mut parse_failures = 0;
    for (file, result) in parsed {
        match result {
            Ok(facts) => {
                let relative = file.strip_prefix(&context.repo_root).unwrap_or(&file);
                warnings.extend(
                    facts
                        .warnings
                        .iter()
                        .map(|warning| format!("{}: {warning}", relative.display())),
                );
                modules.insert(file, facts);
            }
            Err(error) => {
                parse_failures += 1;
                warnings.push(format!(
                    "skipped {}: {}",
                    file.strip_prefix(&context.repo_root)
                        .unwrap_or(&file)
                        .display(),
                    error
                ));
            }
        }
    }
    (modules, warnings, parse_failures)
}

/// The `graph` command: dump the whole-repo import graph in one pass. Every
/// indexed source file is a node; every resolved import/re-export is an edge
/// `from` the depended-upon file `to` the consumer — the same direction as
/// impact-query edges, so consumers flip it the same way to read import
/// direction. `summary`/`risk_tier` carry their defaults and are not meaningful
/// here (`mode` is `graph`).
fn build_graph_result(
    context: &RepoContext,
    modules: &BTreeMap<PathBuf, ModuleFacts>,
    resolution_cache: &mut ResolutionCache<'_>,
    mut warnings: Vec<String>,
    parse_failures: usize,
    unresolved_imports: usize,
) -> AnalysisResult {
    if parse_failures > 0 {
        warnings.insert(
            0,
            format!(
                "{} source file{} could not be parsed and {} skipped",
                parse_failures,
                if parse_failures == 1 { "" } else { "s" },
                if parse_failures == 1 { "was" } else { "were" }
            ),
        );
    }

    let nodes: Vec<GraphNode> = context
        .source_files
        .iter()
        .map(|file| GraphNode {
            id: file_id(file),
            label: relative_label(&context.repo_root, file),
            file: file.clone(),
            symbol: None,
            kind: NodeKind::File,
            depth: 0,
        })
        .collect();

    let mut edges = Vec::new();
    let mut seen = BTreeSet::new();
    let mut push_edge = |from: &Path, to: &Path, kind: EdgeKind| {
        if from == to {
            return;
        }
        let from_id = file_id(from);
        let to_id = file_id(to);
        if seen.insert((from_id.clone(), to_id.clone(), kind)) {
            edges.push(GraphEdge {
                from: from_id,
                to: to_id,
                kind,
                is_ambiguous: false,
            });
        }
    };

    for module in modules.values() {
        for import in &module.imports {
            if let Resolution::Resolved(target) =
                resolution_cache.resolve(&module.file, &import.source)
            {
                push_edge(
                    &target,
                    &module.file,
                    import_edge_kind(&import.imported, import.kind),
                );
            }
        }
        for reexport in &module.reexports {
            if let Resolution::Resolved(target) =
                resolution_cache.resolve(&module.file, &reexport.source)
            {
                let kind = match reexport.imported {
                    ReexportTarget::All => EdgeKind::ReexportsStar,
                    _ => EdgeKind::ReexportsNamed,
                };
                push_edge(&target, &module.file, kind);
            }
        }
    }

    AnalysisResult {
        schema_version: crate::graph::SCHEMA_VERSION,
        mode: AnalysisMode::Graph,
        target: AnalysisTarget::Graph,
        repo_root: context.repo_root.clone(),
        source_file_count: context.source_files.len(),
        summary: Summary {
            unresolved_imports,
            parse_failures,
            ..Summary::default()
        },
        workspaces: result::collect_workspaces(context),
        roots: Vec::new(),
        nodes,
        edges,
        warnings,
    }
}

fn build_module_states(modules: &BTreeMap<PathBuf, ModuleFacts>) -> BTreeMap<PathBuf, ModuleState> {
    let mut states = BTreeMap::new();

    for module in modules.values() {
        let mut state = ModuleState::new(module.file.clone());
        for export in &module.exports {
            state.add_export(export.exported.clone(), export.local.clone());
            if export.kind == ExportKind::Default {
                state.public_exports.insert("default".to_string());
            }
        }
        for reexport in &module.reexports {
            if reexport.exported != "*" {
                state.add_export(reexport.exported.clone(), None);
            }
        }
        states.insert(module.file.clone(), state);
    }

    states
}

fn analyze_from_roots(
    mode: AnalysisMode,
    target: AnalysisTarget,
    data: &AnalysisData<'_>,
    diagnostics: RunDiagnostics,
    roots: Vec<(PathBuf, BTreeSet<String>)>,
) -> Result<AnalysisResult> {
    let RunDiagnostics {
        mut warnings,
        parse_failures,
        unresolved_imports,
        skipped_inputs,
    } = diagnostics;
    let ambiguous_edges = data
        .modules
        .values()
        .map(|module| {
            let star_reexport_count = module
                .reexports
                .iter()
                .filter(|fact| matches!(fact.imported, ReexportTarget::All))
                .count();
            module
                .reexports
                .iter()
                .filter(|fact| match fact.imported {
                    ReexportTarget::All => star_reexport_count > 1,
                    _ => fact.is_ambiguous,
                })
                .count()
        })
        .sum::<usize>();
    if parse_failures > 0 {
        warnings.insert(
            0,
            format!(
                "{} source file{} could not be parsed and {} skipped",
                parse_failures,
                if parse_failures == 1 { "" } else { "s" },
                if parse_failures == 1 { "was" } else { "were" }
            ),
        );
    }
    let workspaces = collect_workspaces(data.context);

    let (states, reasons) = run_bfs(&roots, data.modules, data.module_states, data.reverse);

    // For a multi-file run, also compute each file's blast radius on its own so
    // the report can break impact down per file.
    let root_impacts = if roots.len() > 1 {
        compute_root_impacts(
            &roots,
            data.modules,
            data.module_states,
            data.reverse,
            &workspaces,
            &data.context.repo_root,
        )
    } else {
        Vec::new()
    };

    let metadata = ResultMetadata {
        mode,
        target,
        warnings,
        parse_failures,
        unresolved_imports,
        ambiguous_edges,
        skipped_inputs,
        workspaces,
        root_impacts,
    };

    let result = build_result(data.context, data.module_states, states, reasons, metadata);

    Ok(result)
}

fn expanded_exports_for_root(
    file: &Path,
    names: &[String],
    module_states: &BTreeMap<PathBuf, ModuleState>,
) -> BTreeSet<String> {
    let mut expanded: BTreeSet<String> = names.iter().cloned().collect();
    let Some(module_state) = module_states.get(file) else {
        return expanded;
    };

    let mut locals = BTreeSet::new();
    for name in names {
        if let Some(related) = module_state.export_to_locals.get(name) {
            locals.extend(related.iter().cloned());
        }
    }

    for local in locals {
        if let Some(exports) = module_state.local_to_exports.get(&local) {
            expanded.extend(exports.iter().cloned());
        }
    }

    expanded
}

fn normalize_input_path(repo_root: &Path, path: &Path) -> Result<PathBuf> {
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        repo_root.join(path)
    };
    joined
        .canonicalize()
        .with_context(|| format!("failed to resolve input path {}", joined.display()))
}

/// Node ids embed absolute paths; normalize separators so JSON output (edge
/// `from`/`to`, node ids) is stable across platforms. Consumers that rebuild
/// ids from paths (e.g. the cascade renderer) must normalize the same way.
pub(super) fn file_id(path: &Path) -> String {
    crate::graph::normalize_separators(format!("file:{}", path.display()))
}

pub(super) fn export_id(path: &Path, export: &str) -> String {
    crate::graph::normalize_separators(format!("export:{}#{export}", path.display()))
}

/// Render a path relative to the repo root, always with `/` separators —
/// `Path::display()` yields `\` on Windows, which would break the `/`-based
/// package and directory grouping downstream.
pub(super) fn relative_label(repo_root: &Path, path: &Path) -> String {
    crate::graph::normalize_separators(
        path.strip_prefix(repo_root)
            .unwrap_or(path)
            .display()
            .to_string(),
    )
}