ast-bro 2.2.0

Fast, AST-based code-navigation: shape, public API, deps & call graphs, hybrid semantic search, structural rewrite. MCP server included.
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
//! TypeScript / JavaScript public-surface resolver.
//!
//! Algorithm:
//! 1. Resolve the entry file via `package.json` (`exports` w/ conditional
//!    resolution, then `module`/`main`/`types`) or `index.{ts,tsx,...}`.
//! 2. For each loaded file, run [`extract_ts_exports`] to enumerate
//!    every export form (the existing TS adapter only catches the
//!    inline `export class/fn/const/...` forms; barrels and rename
//!    re-exports come from here).
//! 3. BFS through `export ... from './x'` chains, expanding namespace
//!    re-exports and `export * from` globs.
//!
//! Module resolution is the small subset of Node we actually need:
//! relative paths only, with extension probing (`.ts` → `.tsx` → `.js`
//! → ... → `.d.ts`) and directory `index.*` fallback. Bare specifiers
//! (`react`, `lodash`, etc.) are recorded as external hops but not
//! followed.

use crate::core::{Declaration, DeclarationKind};
use crate::parse_file;
use crate::surface::entry::{ReExportHop, SurfaceEntry};
use crate::surface::entry_point::EntryPoint;
use crate::surface::imports::{self, NamedBinding, TsExportItem, TsKind};
use crate::surface::options::{SurfaceError, SurfaceOptions};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

pub fn resolve(
    entry: &EntryPoint,
    opts: &SurfaceOptions,
) -> Result<Vec<SurfaceEntry>, SurfaceError> {
    let (root_file, pkg_name) = match entry {
        EntryPoint::TsPackage { root_file, pkg_name } => (root_file.clone(), pkg_name.clone()),
        _ => {
            return Err(SurfaceError::NoEntryPoint {
                path: PathBuf::from("."),
                hint: "typescript::resolve called with non-TS entry point".into(),
            });
        }
    };

    let mut walker = Walker {
        max_depth: opts.max_depth,
        loaded: HashMap::new(),
        entries: Vec::new(),
        seen_qualified: HashSet::new(),
    };
    walker.walk_file(&root_file, &[pkg_name], 0, vec![]);
    Ok(walker.entries)
}

struct Walker {
    max_depth: usize,
    loaded: HashMap<PathBuf, FileSnapshot>,
    entries: Vec<SurfaceEntry>,
    seen_qualified: HashSet<String>,
}

struct FileSnapshot {
    decls: Vec<Declaration>,
    exports: Vec<TsExportItem>,
}

impl Walker {
    fn walk_file(
        &mut self,
        file: &Path,
        prefix: &[String],
        depth: usize,
        chain: Vec<ReExportHop>,
    ) {
        if depth > self.max_depth {
            return;
        }
        let snap = match self._load(file) {
            Some(s) => s,
            None => return,
        };
        let decls = snap.decls.clone();
        let exports = snap.exports.clone();

        // 1. Pick up every inline-exported declaration. The TS adapter
        //    already filters non-`export` decls, so anything in `decls`
        //    is part of the module's namespace.
        //    We restrict to ones the imports.rs scan also flagged, so
        //    bare locals aren't surfaced.
        let inline_names: HashSet<String> = exports
            .iter()
            .filter_map(|e| match e {
                TsExportItem::Local { name, .. } => Some(name.clone()),
                TsExportItem::Default { name, .. } => Some(name.clone()),
                _ => None,
            })
            .collect();

        for d in &decls {
            if inline_names.contains(&d.name) {
                self._emit(prefix, &d.name, d, file, chain.clone(), false);
            }
        }

        // 2. Process named re-exports of locals (`export { local }`).
        for ex in &exports {
            if let TsExportItem::Named { bindings, .. } = ex {
                for b in bindings {
                    if let Some(d) = decls.iter().find(|d| d.name == b.name) {
                        let exposed = b.alias.clone().unwrap_or_else(|| b.name.clone());
                        self._emit(prefix, &exposed, d, file, chain.clone(), false);
                    }
                }
            }
        }

        // 3. Follow re-exports from other files.
        for ex in &exports {
            match ex {
                TsExportItem::NamedFrom {
                    from,
                    bindings,
                    line,
                    statement,
                } => {
                    if let Some(target) = _resolve_module(file, from) {
                        let hop = ReExportHop {
                            file: file.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        self._follow_named(
                            &target,
                            prefix,
                            bindings,
                            depth + 1,
                            _push(chain.clone(), hop),
                        );
                    }
                }
                TsExportItem::StarFrom {
                    from,
                    line,
                    statement,
                } => {
                    if let Some(target) = _resolve_module(file, from) {
                        let hop = ReExportHop {
                            file: file.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        self._follow_star(
                            &target,
                            prefix,
                            depth + 1,
                            _push(chain.clone(), hop),
                            true,
                        );
                    }
                }
                TsExportItem::NamespaceFrom {
                    ns,
                    from,
                    line,
                    statement,
                } => {
                    if let Some(target) = _resolve_module(file, from) {
                        let hop = ReExportHop {
                            file: file.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        let mut ns_prefix = prefix.to_vec();
                        ns_prefix.push(ns.clone());
                        self._follow_star(
                            &target,
                            &ns_prefix,
                            depth + 1,
                            _push(chain.clone(), hop),
                            false,
                        );
                    }
                }
                _ => {}
            }
        }
    }

    fn _follow_named(
        &mut self,
        target: &Path,
        prefix: &[String],
        bindings: &[NamedBinding],
        depth: usize,
        chain: Vec<ReExportHop>,
    ) {
        if depth > self.max_depth {
            return;
        }
        let snap = match self._load(target) {
            Some(s) => s,
            None => return,
        };
        let decls = snap.decls.clone();
        let exports = snap.exports.clone();
        for b in bindings {
            let exposed = b.alias.clone().unwrap_or_else(|| b.name.clone());
            // Defined in target?
            if let Some(d) = decls.iter().find(|d| d.name == b.name) {
                self._emit(prefix, &exposed, d, target, chain.clone(), false);
                continue;
            }
            // Re-exported by target?
            self._chase_indirect(target, prefix, &b.name, &exposed, &exports, depth, chain.clone());
        }
    }

    fn _chase_indirect(
        &mut self,
        from_file: &Path,
        prefix: &[String],
        source_name: &str,
        exposed: &str,
        exports: &[TsExportItem],
        depth: usize,
        chain: Vec<ReExportHop>,
    ) {
        for ex in exports {
            match ex {
                TsExportItem::NamedFrom {
                    from,
                    bindings,
                    line,
                    statement,
                } => {
                    let hit = bindings.iter().find(|b| {
                        let local = b.alias.as_deref().unwrap_or(&b.name);
                        local == source_name
                    });
                    if let Some(b) = hit {
                        if let Some(target) = _resolve_module(from_file, from) {
                            let hop = ReExportHop {
                                file: from_file.to_path_buf(),
                                line: *line,
                                module_path: prefix.join("."),
                                statement: statement.clone(),
                            };
                            self._follow_named(
                                &target,
                                prefix,
                                &[NamedBinding {
                                    name: b.name.clone(),
                                    alias: Some(exposed.to_string()),
                                }],
                                depth + 1,
                                _push(chain.clone(), hop),
                            );
                            return;
                        }
                    }
                }
                TsExportItem::StarFrom { from, line, statement } => {
                    if let Some(target) = _resolve_module(from_file, from) {
                        let hop = ReExportHop {
                            file: from_file.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        // Star may transit any name; recurse looking for it.
                        let snap = self._load(&target);
                        if let Some(s) = snap {
                            if let Some(d) = s.decls.iter().find(|d| d.name == source_name).cloned()
                            {
                                self._emit(prefix, exposed, &d, &target, _push(chain.clone(), hop), true);
                                return;
                            }
                            let exports2 = s.exports.clone();
                            self._chase_indirect(
                                &target,
                                prefix,
                                source_name,
                                exposed,
                                &exports2,
                                depth + 1,
                                _push(chain.clone(), hop),
                            );
                        }
                    }
                }
                _ => {}
            }
        }
    }

    fn _follow_star(
        &mut self,
        target: &Path,
        prefix: &[String],
        depth: usize,
        chain: Vec<ReExportHop>,
        skip_default: bool,
    ) {
        if depth > self.max_depth {
            return;
        }
        let snap = match self._load(target) {
            Some(s) => s,
            None => return,
        };
        let decls = snap.decls.clone();
        let exports = snap.exports.clone();

        // Names locally defined and exported.
        for ex in &exports {
            match ex {
                TsExportItem::Local { name, .. } => {
                    if let Some(d) = decls.iter().find(|d| &d.name == name) {
                        self._emit(prefix, name, d, target, chain.clone(), true);
                    }
                }
                TsExportItem::Default { name, .. } => {
                    if skip_default {
                        // Per Node.js semantics, `export *` skips default.
                        continue;
                    }
                    if let Some(d) = decls.iter().find(|d| &d.name == name) {
                        self._emit(prefix, "default", d, target, chain.clone(), true);
                    }
                }
                TsExportItem::Named { bindings, .. } => {
                    for b in bindings {
                        let exposed = b.alias.clone().unwrap_or_else(|| b.name.clone());
                        if let Some(d) = decls.iter().find(|d| d.name == b.name) {
                            self._emit(prefix, &exposed, d, target, chain.clone(), true);
                        }
                    }
                }
                _ => {}
            }
        }
        // Recurse through `export *` and `export { ... } from`.
        for ex in &exports {
            match ex {
                TsExportItem::StarFrom {
                    from,
                    line,
                    statement,
                } => {
                    if let Some(t2) = _resolve_module(target, from) {
                        let hop = ReExportHop {
                            file: target.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        self._follow_star(&t2, prefix, depth + 1, _push(chain.clone(), hop), true);
                    }
                }
                TsExportItem::NamedFrom {
                    from,
                    bindings,
                    line,
                    statement,
                } => {
                    if let Some(t2) = _resolve_module(target, from) {
                        let hop = ReExportHop {
                            file: target.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        self._follow_named(
                            &t2,
                            prefix,
                            bindings,
                            depth + 1,
                            _push(chain.clone(), hop),
                        );
                    }
                }
                TsExportItem::NamespaceFrom {
                    ns,
                    from,
                    line,
                    statement,
                } => {
                    if let Some(t2) = _resolve_module(target, from) {
                        let hop = ReExportHop {
                            file: target.to_path_buf(),
                            line: *line,
                            module_path: prefix.join("."),
                            statement: statement.clone(),
                        };
                        let mut ns_prefix = prefix.to_vec();
                        ns_prefix.push(ns.clone());
                        self._follow_star(
                            &t2,
                            &ns_prefix,
                            depth + 1,
                            _push(chain.clone(), hop),
                            false,
                        );
                    }
                }
                _ => {}
            }
        }
    }

    fn _load(&mut self, file: &Path) -> Option<&FileSnapshot> {
        if !self.loaded.contains_key(file) {
            let parse = parse_file(file)?;
            let src = std::str::from_utf8(&parse.source).ok()?.to_string();
            let kind = TsKind::from_path(file).unwrap_or(TsKind::TypeScript);
            let exports = imports::extract_ts_exports(&src, kind).items;
            self.loaded.insert(
                file.to_path_buf(),
                FileSnapshot {
                    decls: parse.declarations,
                    exports,
                },
            );
        }
        self.loaded.get(file)
    }

    fn _emit(
        &mut self,
        prefix: &[String],
        exposed: &str,
        decl: &Declaration,
        source: &Path,
        chain: Vec<ReExportHop>,
        via_glob: bool,
    ) {
        if exposed.is_empty() {
            return;
        }
        let qpath = format!("{}.{}", prefix.join("."), exposed);
        if !self.seen_qualified.insert(qpath.clone()) {
            return;
        }
        // Lift class methods so `pkg.Foo.bar` shows up too. Skip private.
        let kind_lifts = matches!(
            decl.kind,
            DeclarationKind::Class | DeclarationKind::Interface | DeclarationKind::Enum
        );
        self.entries.push(SurfaceEntry {
            qualified_path: qpath.clone(),
            kind: decl.kind,
            signature: decl.signature.clone(),
            source_path: source.to_path_buf(),
            source_line: decl.start_line,
            source_name: decl.name.clone(),
            re_export_chain: chain.clone(),
            via_glob,
            docs: decl.docs.clone(),
        });
        if kind_lifts {
            for child in &decl.children {
                if child.visibility == "private" || child.visibility == "protected" {
                    continue;
                }
                if child.name.is_empty() {
                    continue;
                }
                let child_q = format!("{}.{}", qpath, child.name);
                if !self.seen_qualified.insert(child_q.clone()) {
                    continue;
                }
                self.entries.push(SurfaceEntry {
                    qualified_path: child_q,
                    kind: child.kind,
                    signature: child.signature.clone(),
                    source_path: source.to_path_buf(),
                    source_line: child.start_line,
                    source_name: child.name.clone(),
                    re_export_chain: chain.clone(),
                    via_glob,
                    docs: child.docs.clone(),
                });
            }
        }
    }
}

/// Resolve a relative module specifier (`./foo`, `../bar/baz`) to a file
/// on disk. Bare specifiers (`react`, `@scope/pkg`) are intentionally
/// returned as `None` — we can't follow them without traversing
/// `node_modules`, and that's out of scope.
fn _resolve_module(from_file: &Path, spec: &str) -> Option<PathBuf> {
    if !spec.starts_with('.') {
        return None;
    }
    let parent = from_file.parent()?;
    let base = parent.join(spec);

    // Strip an explicit `.js`/`.mjs`/`.cjs` extension and try `.ts` first
    // (TS source for compiled JS imports — common pattern).
    if let Some(stem_path) = _strip_js_extension(&base) {
        if let Some(p) = _probe_extensions(&stem_path) {
            return Some(p);
        }
    }

    // Direct file with one of the source extensions.
    if let Some(p) = _probe_extensions(&base) {
        return Some(p);
    }

    // Directory with index.*
    if base.is_dir() {
        if let Some(p) = _probe_extensions(&base.join("index")) {
            return Some(p);
        }
    }

    None
}

fn _strip_js_extension(p: &Path) -> Option<PathBuf> {
    let ext = p.extension().and_then(|s| s.to_str())?;
    if matches!(ext, "js" | "jsx" | "mjs" | "cjs") {
        let stem = p.file_stem()?.to_str()?;
        return Some(p.with_file_name(stem));
    }
    None
}

fn _probe_extensions(stem: &Path) -> Option<PathBuf> {
    // If the path already exists as a file, take it.
    if stem.is_file() {
        return Some(stem.to_path_buf());
    }
    for ext in ["ts", "tsx", "mts", "cts", "d.ts", "js", "jsx", "mjs", "cjs"] {
        let cand = stem.with_extension(ext);
        if cand.is_file() {
            return Some(cand);
        }
    }
    None
}

fn _push(mut v: Vec<ReExportHop>, h: ReExportHop) -> Vec<ReExportHop> {
    v.push(h);
    v
}