Navegador

navegador / navegador / ingestion / typescript.py
Source Blame History 369 lines
5e4b8e4… anonymous 1 """
e52aae0… lmata 2 TypeScript/JavaScript AST parser — extracts classes, interfaces, functions
e52aae0… lmata 3 (including const arrow functions), methods, imports, and call edges.
e52aae0… lmata 4
e52aae0… lmata 5 Supports:
e52aae0… lmata 6 - .ts / .tsx → tree-sitter-typescript (TypeScript grammar)
e52aae0… lmata 7 - .js / .jsx → tree-sitter-javascript (JavaScript grammar)
5e4b8e4… anonymous 8 """
5e4b8e4… anonymous 9
5e4b8e4… anonymous 10 import logging
5e4b8e4… anonymous 11 from pathlib import Path
5e4b8e4… anonymous 12
5e4b8e4… anonymous 13 from navegador.graph.schema import EdgeType, NodeLabel
5e4b8e4… anonymous 14 from navegador.graph.store import GraphStore
5e4b8e4… anonymous 15 from navegador.ingestion.parser import LanguageParser
5e4b8e4… anonymous 16
5e4b8e4… anonymous 17 logger = logging.getLogger(__name__)
5e4b8e4… anonymous 18
5e4b8e4… anonymous 19
5e4b8e4… anonymous 20 def _get_ts_language(language: str):
5e4b8e4… anonymous 21 try:
5e4b8e4… anonymous 22 if language == "typescript":
5e4b8e4… anonymous 23 import tree_sitter_typescript as tsts # type: ignore[import]
5e4b8e4… anonymous 24 from tree_sitter import Language
758c6b7… lmata 25
5e4b8e4… anonymous 26 return Language(tsts.language_typescript())
5e4b8e4… anonymous 27 else:
5e4b8e4… anonymous 28 import tree_sitter_javascript as tsjs # type: ignore[import]
5e4b8e4… anonymous 29 from tree_sitter import Language
758c6b7… lmata 30
5e4b8e4… anonymous 31 return Language(tsjs.language())
5e4b8e4… anonymous 32 except ImportError as e:
5e4b8e4… anonymous 33 raise ImportError(
5e4b8e4… anonymous 34 f"Install tree-sitter-{language}: pip install tree-sitter-{language}"
5e4b8e4… anonymous 35 ) from e
5e4b8e4… anonymous 36
5e4b8e4… anonymous 37
e52aae0… lmata 38 def _node_text(node, source: bytes) -> str:
758c6b7… lmata 39 return source[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
e52aae0… lmata 40
e52aae0… lmata 41
e52aae0… lmata 42 def _jsdoc(node, source: bytes) -> str:
e52aae0… lmata 43 """Return the JSDoc comment (/** ... */) preceding a node, if any."""
e52aae0… lmata 44 parent = node.parent
e52aae0… lmata 45 if not parent:
e52aae0… lmata 46 return ""
e52aae0… lmata 47 siblings = list(parent.children)
e52aae0… lmata 48 idx = next((i for i, c in enumerate(siblings) if c.id == node.id), -1)
e52aae0… lmata 49 if idx <= 0:
e52aae0… lmata 50 return ""
e52aae0… lmata 51 prev = siblings[idx - 1]
e52aae0… lmata 52 if prev.type == "comment":
e52aae0… lmata 53 raw = _node_text(prev, source).strip()
e52aae0… lmata 54 if raw.startswith("/**"):
e52aae0… lmata 55 return raw.strip("/**").strip("*/").strip()
e52aae0… lmata 56 return ""
e52aae0… lmata 57
e52aae0… lmata 58
5e4b8e4… anonymous 59 class TypeScriptParser(LanguageParser):
e52aae0… lmata 60 """Parses TypeScript/JavaScript source files into the navegador graph."""
e52aae0… lmata 61
5e4b8e4… anonymous 62 def __init__(self, language: str = "typescript") -> None:
5e4b8e4… anonymous 63 from tree_sitter import Parser # type: ignore[import]
758c6b7… lmata 64
5e4b8e4… anonymous 65 self._parser = Parser(_get_ts_language(language))
5e4b8e4… anonymous 66 self._language = language
5e4b8e4… anonymous 67
5e4b8e4… anonymous 68 def parse_file(self, path: Path, repo_root: Path, store: GraphStore) -> dict[str, int]:
5e4b8e4… anonymous 69 source = path.read_bytes()
5e4b8e4… anonymous 70 tree = self._parser.parse(source)
5e4b8e4… anonymous 71 rel_path = str(path.relative_to(repo_root))
5e4b8e4… anonymous 72
758c6b7… lmata 73 store.create_node(
758c6b7… lmata 74 NodeLabel.File,
758c6b7… lmata 75 {
758c6b7… lmata 76 "name": path.name,
758c6b7… lmata 77 "path": rel_path,
758c6b7… lmata 78 "language": self._language,
758c6b7… lmata 79 "line_count": source.count(b"\n"),
758c6b7… lmata 80 },
758c6b7… lmata 81 )
5e4b8e4… anonymous 82
5e4b8e4… anonymous 83 stats = {"functions": 0, "classes": 0, "edges": 0}
5e4b8e4… anonymous 84 self._walk(tree.root_node, source, rel_path, store, stats, class_name=None)
5e4b8e4… anonymous 85 return stats
5e4b8e4… anonymous 86
e52aae0… lmata 87 # ── AST walker ────────────────────────────────────────────────────────────
e52aae0… lmata 88
758c6b7… lmata 89 def _walk(
758c6b7… lmata 90 self,
758c6b7… lmata 91 node,
758c6b7… lmata 92 source: bytes,
758c6b7… lmata 93 file_path: str,
758c6b7… lmata 94 store: GraphStore,
758c6b7… lmata 95 stats: dict,
758c6b7… lmata 96 class_name: str | None,
758c6b7… lmata 97 ) -> None:
5e4b8e4… anonymous 98 if node.type in ("class_declaration", "abstract_class_declaration"):
5e4b8e4… anonymous 99 self._handle_class(node, source, file_path, store, stats)
5e4b8e4… anonymous 100 return
e52aae0… lmata 101 if node.type in ("interface_declaration", "type_alias_declaration"):
e52aae0… lmata 102 self._handle_interface(node, source, file_path, store, stats)
e52aae0… lmata 103 return
e52aae0… lmata 104 if node.type == "function_declaration":
e52aae0… lmata 105 self._handle_function(node, source, file_path, store, stats, class_name)
e52aae0… lmata 106 return
e52aae0… lmata 107 if node.type == "method_definition":
5e4b8e4… anonymous 108 self._handle_function(node, source, file_path, store, stats, class_name)
e52aae0… lmata 109 return
e52aae0… lmata 110 if node.type in ("lexical_declaration", "variable_declaration"):
e52aae0… lmata 111 self._handle_lexical(node, source, file_path, store, stats)
5e4b8e4… anonymous 112 return
5e4b8e4… anonymous 113 if node.type in ("import_statement", "import_declaration"):
5e4b8e4… anonymous 114 self._handle_import(node, source, file_path, store, stats)
e52aae0… lmata 115 return
e52aae0… lmata 116 if node.type == "export_statement":
e52aae0… lmata 117 # Recurse into exported declarations
e52aae0… lmata 118 for child in node.children:
e52aae0… lmata 119 if child.type not in ("export", "default", "from"):
e52aae0… lmata 120 self._walk(child, source, file_path, store, stats, class_name)
e52aae0… lmata 121 return
5e4b8e4… anonymous 122
5e4b8e4… anonymous 123 for child in node.children:
5e4b8e4… anonymous 124 self._walk(child, source, file_path, store, stats, class_name)
5e4b8e4… anonymous 125
e52aae0… lmata 126 # ── Handlers ──────────────────────────────────────────────────────────────
e52aae0… lmata 127
758c6b7… lmata 128 def _handle_class(
758c6b7… lmata 129 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 130 ) -> None:
758c6b7… lmata 131 name_node = next((c for c in node.children if c.type == "type_identifier"), None)
5e4b8e4… anonymous 132 if not name_node:
5e4b8e4… anonymous 133 return
e52aae0… lmata 134 name = _node_text(name_node, source)
e52aae0… lmata 135 docstring = _jsdoc(node, source)
e52aae0… lmata 136
758c6b7… lmata 137 store.create_node(
758c6b7… lmata 138 NodeLabel.Class,
758c6b7… lmata 139 {
758c6b7… lmata 140 "name": name,
758c6b7… lmata 141 "file_path": file_path,
758c6b7… lmata 142 "line_start": node.start_point[0] + 1,
758c6b7… lmata 143 "line_end": node.end_point[0] + 1,
758c6b7… lmata 144 "docstring": docstring,
758c6b7… lmata 145 },
758c6b7… lmata 146 )
5e4b8e4… anonymous 147 store.create_edge(
758c6b7… lmata 148 NodeLabel.File,
758c6b7… lmata 149 {"path": file_path},
5e4b8e4… anonymous 150 EdgeType.CONTAINS,
758c6b7… lmata 151 NodeLabel.Class,
758c6b7… lmata 152 {"name": name, "file_path": file_path},
5e4b8e4… anonymous 153 )
5e4b8e4… anonymous 154 stats["classes"] += 1
5e4b8e4… anonymous 155 stats["edges"] += 1
e52aae0… lmata 156
e52aae0… lmata 157 # Inheritance: extends clause
e52aae0… lmata 158 heritage = next((c for c in node.children if c.type == "class_heritage"), None)
e52aae0… lmata 159 if heritage:
e52aae0… lmata 160 for child in heritage.children:
e52aae0… lmata 161 if child.type == "extends_clause":
e52aae0… lmata 162 for c in child.children:
e52aae0… lmata 163 if c.type == "identifier":
e52aae0… lmata 164 parent_name = _node_text(c, source)
e52aae0… lmata 165 store.create_edge(
758c6b7… lmata 166 NodeLabel.Class,
758c6b7… lmata 167 {"name": name, "file_path": file_path},
e52aae0… lmata 168 EdgeType.INHERITS,
758c6b7… lmata 169 NodeLabel.Class,
758c6b7… lmata 170 {"name": parent_name, "file_path": file_path},
e52aae0… lmata 171 )
e52aae0… lmata 172 stats["edges"] += 1
5e4b8e4… anonymous 173
5e4b8e4… anonymous 174 body = next((c for c in node.children if c.type == "class_body"), None)
5e4b8e4… anonymous 175 if body:
5e4b8e4… anonymous 176 for child in body.children:
5e4b8e4… anonymous 177 if child.type == "method_definition":
758c6b7… lmata 178 self._handle_function(child, source, file_path, store, stats, class_name=name)
758c6b7… lmata 179
758c6b7… lmata 180 def _handle_interface(
758c6b7… lmata 181 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 182 ) -> None:
758c6b7… lmata 183 name_node = next((c for c in node.children if c.type == "type_identifier"), None)
e52aae0… lmata 184 if not name_node:
e52aae0… lmata 185 return
e52aae0… lmata 186 name = _node_text(name_node, source)
e52aae0… lmata 187 docstring = _jsdoc(node, source)
e52aae0… lmata 188 kind = "interface" if node.type == "interface_declaration" else "type"
e52aae0… lmata 189
758c6b7… lmata 190 store.create_node(
758c6b7… lmata 191 NodeLabel.Class,
758c6b7… lmata 192 {
758c6b7… lmata 193 "name": name,
758c6b7… lmata 194 "file_path": file_path,
758c6b7… lmata 195 "line_start": node.start_point[0] + 1,
758c6b7… lmata 196 "line_end": node.end_point[0] + 1,
758c6b7… lmata 197 "docstring": f"{kind}: {docstring}".strip(": "),
758c6b7… lmata 198 },
758c6b7… lmata 199 )
e52aae0… lmata 200 store.create_edge(
758c6b7… lmata 201 NodeLabel.File,
758c6b7… lmata 202 {"path": file_path},
e52aae0… lmata 203 EdgeType.CONTAINS,
758c6b7… lmata 204 NodeLabel.Class,
758c6b7… lmata 205 {"name": name, "file_path": file_path},
e52aae0… lmata 206 )
e52aae0… lmata 207 stats["classes"] += 1
e52aae0… lmata 208 stats["edges"] += 1
e52aae0… lmata 209
758c6b7… lmata 210 def _handle_function(
758c6b7… lmata 211 self,
758c6b7… lmata 212 node,
758c6b7… lmata 213 source: bytes,
758c6b7… lmata 214 file_path: str,
758c6b7… lmata 215 store: GraphStore,
758c6b7… lmata 216 stats: dict,
758c6b7… lmata 217 class_name: str | None,
758c6b7… lmata 218 ) -> None:
5e4b8e4… anonymous 219 name_node = next(
758c6b7… lmata 220 (c for c in node.children if c.type in ("identifier", "property_identifier")), None
5e4b8e4… anonymous 221 )
5e4b8e4… anonymous 222 if not name_node:
5e4b8e4… anonymous 223 return
e52aae0… lmata 224 name = _node_text(name_node, source)
e52aae0… lmata 225 if name in ("constructor", "get", "set", "static", "async"):
e52aae0… lmata 226 # These are keywords, not useful names — look for next identifier
e52aae0… lmata 227 name_node = next(
758c6b7… lmata 228 (
758c6b7… lmata 229 c
758c6b7… lmata 230 for c in node.children
758c6b7… lmata 231 if c.type in ("identifier", "property_identifier") and c != name_node
758c6b7… lmata 232 ),
e52aae0… lmata 233 None,
e52aae0… lmata 234 )
e52aae0… lmata 235 if not name_node:
e52aae0… lmata 236 return
e52aae0… lmata 237 name = _node_text(name_node, source)
5e4b8e4… anonymous 238
e52aae0… lmata 239 docstring = _jsdoc(node, source)
5e4b8e4… anonymous 240 label = NodeLabel.Method if class_name else NodeLabel.Function
e52aae0… lmata 241
758c6b7… lmata 242 store.create_node(
758c6b7… lmata 243 label,
758c6b7… lmata 244 {
758c6b7… lmata 245 "name": name,
758c6b7… lmata 246 "file_path": file_path,
758c6b7… lmata 247 "line_start": node.start_point[0] + 1,
758c6b7… lmata 248 "line_end": node.end_point[0] + 1,
758c6b7… lmata 249 "docstring": docstring,
758c6b7… lmata 250 "class_name": class_name or "",
758c6b7… lmata 251 },
758c6b7… lmata 252 )
5e4b8e4… anonymous 253
5e4b8e4… anonymous 254 container_label = NodeLabel.Class if class_name else NodeLabel.File
5e4b8e4… anonymous 255 container_key = (
758c6b7… lmata 256 {"name": class_name, "file_path": file_path} if class_name else {"path": file_path}
5e4b8e4… anonymous 257 )
3c74e66… lmata 258 store.create_edge(
758c6b7… lmata 259 container_label,
758c6b7… lmata 260 container_key,
e52aae0… lmata 261 EdgeType.CONTAINS,
758c6b7… lmata 262 label,
758c6b7… lmata 263 {"name": name, "file_path": file_path},
3c74e66… lmata 264 )
5e4b8e4… anonymous 265 stats["functions"] += 1
5e4b8e4… anonymous 266 stats["edges"] += 1
e52aae0… lmata 267
e52aae0… lmata 268 self._extract_calls(node, source, file_path, name, label, store, stats)
e52aae0… lmata 269
758c6b7… lmata 270 def _handle_lexical(
758c6b7… lmata 271 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 272 ) -> None:
e52aae0… lmata 273 """Handle: const foo = () => {} and const bar = function() {}"""
e52aae0… lmata 274 for child in node.children:
e52aae0… lmata 275 if child.type != "variable_declarator":
e52aae0… lmata 276 continue
e52aae0… lmata 277 name_node = child.child_by_field_name("name")
e52aae0… lmata 278 value_node = child.child_by_field_name("value")
e52aae0… lmata 279 if not name_node or not value_node:
e52aae0… lmata 280 continue
758c6b7… lmata 281 if value_node.type not in ("arrow_function", "function_expression", "function"):
e52aae0… lmata 282 continue
e52aae0… lmata 283 name = _node_text(name_node, source)
e52aae0… lmata 284 docstring = _jsdoc(node, source)
e52aae0… lmata 285
758c6b7… lmata 286 store.create_node(
758c6b7… lmata 287 NodeLabel.Function,
758c6b7… lmata 288 {
758c6b7… lmata 289 "name": name,
758c6b7… lmata 290 "file_path": file_path,
758c6b7… lmata 291 "line_start": node.start_point[0] + 1,
758c6b7… lmata 292 "line_end": node.end_point[0] + 1,
758c6b7… lmata 293 "docstring": docstring,
758c6b7… lmata 294 "class_name": "",
758c6b7… lmata 295 },
758c6b7… lmata 296 )
e52aae0… lmata 297 store.create_edge(
758c6b7… lmata 298 NodeLabel.File,
758c6b7… lmata 299 {"path": file_path},
e52aae0… lmata 300 EdgeType.CONTAINS,
758c6b7… lmata 301 NodeLabel.Function,
758c6b7… lmata 302 {"name": name, "file_path": file_path},
e52aae0… lmata 303 )
e52aae0… lmata 304 stats["functions"] += 1
e52aae0… lmata 305 stats["edges"] += 1
e52aae0… lmata 306
758c6b7… lmata 307 self._extract_calls(
758c6b7… lmata 308 value_node, source, file_path, name, NodeLabel.Function, store, stats
758c6b7… lmata 309 )
e52aae0… lmata 310
758c6b7… lmata 311 def _handle_import(
758c6b7… lmata 312 self, node, source: bytes, file_path: str, store: GraphStore, stats: dict
758c6b7… lmata 313 ) -> None:
e52aae0… lmata 314 for child in node.children:
e52aae0… lmata 315 if child.type == "string":
e52aae0… lmata 316 module = _node_text(child, source).strip("'\"")
758c6b7… lmata 317 store.create_node(
758c6b7… lmata 318 NodeLabel.Import,
758c6b7… lmata 319 {
758c6b7… lmata 320 "name": module,
758c6b7… lmata 321 "file_path": file_path,
758c6b7… lmata 322 "line_start": node.start_point[0] + 1,
758c6b7… lmata 323 "module": module,
758c6b7… lmata 324 },
758c6b7… lmata 325 )
e52aae0… lmata 326 store.create_edge(
758c6b7… lmata 327 NodeLabel.File,
758c6b7… lmata 328 {"path": file_path},
e52aae0… lmata 329 EdgeType.IMPORTS,
758c6b7… lmata 330 NodeLabel.Import,
758c6b7… lmata 331 {"name": module, "file_path": file_path},
e52aae0… lmata 332 )
e52aae0… lmata 333 stats["edges"] += 1
e52aae0… lmata 334 break
e52aae0… lmata 335
758c6b7… lmata 336 def _extract_calls(
758c6b7… lmata 337 self,
758c6b7… lmata 338 fn_node,
758c6b7… lmata 339 source: bytes,
758c6b7… lmata 340 file_path: str,
758c6b7… lmata 341 fn_name: str,
758c6b7… lmata 342 fn_label: str,
758c6b7… lmata 343 store: GraphStore,
758c6b7… lmata 344 stats: dict,
758c6b7… lmata 345 ) -> None:
e52aae0… lmata 346 def walk(node):
e52aae0… lmata 347 if node.type == "call_expression":
e52aae0… lmata 348 func = node.child_by_field_name("function")
e52aae0… lmata 349 if func:
e52aae0… lmata 350 text = _node_text(func, source)
e52aae0… lmata 351 callee = text.split(".")[-1]
e52aae0… lmata 352 store.create_edge(
758c6b7… lmata 353 fn_label,
758c6b7… lmata 354 {"name": fn_name, "file_path": file_path},
e52aae0… lmata 355 EdgeType.CALLS,
758c6b7… lmata 356 NodeLabel.Function,
758c6b7… lmata 357 {"name": callee, "file_path": file_path},
e52aae0… lmata 358 )
e52aae0… lmata 359 stats["edges"] += 1
e52aae0… lmata 360 for child in node.children:
e52aae0… lmata 361 walk(child)
e52aae0… lmata 362
e52aae0… lmata 363 # Body is statement_block for functions, expression for arrow fns
e52aae0… lmata 364 body = next(
758c6b7… lmata 365 (c for c in fn_node.children if c.type in ("statement_block", "expression_statement")),
e52aae0… lmata 366 None,
e52aae0… lmata 367 )
e52aae0… lmata 368 if body:
e52aae0… lmata 369 walk(body)

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button