codiff 0.1.0__py3-none-any.whl
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.
- codiff/__init__.py +1 -0
- codiff/__main__.py +5 -0
- codiff/cli.py +247 -0
- codiff/db/__init__.py +16 -0
- codiff/db/engine.py +31 -0
- codiff/db/models.py +119 -0
- codiff/db/operations.py +238 -0
- codiff/diff/__init__.py +1 -0
- codiff/diff/analysis.py +145 -0
- codiff/diff/differ.py +45 -0
- codiff/diff/engine.py +80 -0
- codiff/diff/indexer.py +134 -0
- codiff/diff/snapshot.py +325 -0
- codiff/export/__init__.py +5 -0
- codiff/export/json.py +43 -0
- codiff/export/mermaid.py +475 -0
- codiff/export/terminal.py +866 -0
- codiff/languages/__init__.py +29 -0
- codiff/languages/parser.py +214 -0
- codiff/languages/python/__init__.py +0 -0
- codiff/languages/python/parser.py +927 -0
- codiff/languages/python/resolver.py +178 -0
- codiff/languages/repository.py +245 -0
- codiff/languages/resolver.py +582 -0
- codiff/languages/typescript/__init__.py +0 -0
- codiff/languages/typescript/parser.py +612 -0
- codiff/languages/typescript/resolver.py +95 -0
- codiff/mcp_server.py +83 -0
- codiff/schema/__init__.py +25 -0
- codiff/schema/diff.py +110 -0
- codiff/schema/parsing.py +76 -0
- codiff/setup.py +103 -0
- codiff/utils/__init__.py +0 -0
- codiff/utils/args.py +114 -0
- codiff/utils/files.py +62 -0
- codiff/utils/git.py +101 -0
- codiff/utils/instructions.py +14 -0
- codiff/utils/instructions.yaml +50 -0
- codiff/utils/terminal.py +10 -0
- codiff-0.1.0.dist-info/METADATA +487 -0
- codiff-0.1.0.dist-info/RECORD +45 -0
- codiff-0.1.0.dist-info/WHEEL +5 -0
- codiff-0.1.0.dist-info/entry_points.txt +3 -0
- codiff-0.1.0.dist-info/licenses/LICENSE +201 -0
- codiff-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
"""TypeScript and TSX parser implementations.
|
|
2
|
+
|
|
3
|
+
Implements LanguageParser for TypeScript (.ts) and TSX (.tsx) using
|
|
4
|
+
tree-sitter-typescript. Captures function_declaration, method_definition,
|
|
5
|
+
module-level arrow functions (const X = () => {}), factory-call consts
|
|
6
|
+
(const X = create(...)), object-property arrow functions (Zustand/Redux
|
|
7
|
+
patterns), and JSX component usage as function calls.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import tree_sitter_typescript as tsts
|
|
16
|
+
from tree_sitter import Language, Query
|
|
17
|
+
|
|
18
|
+
from codiff.languages.parser import LanguageParser
|
|
19
|
+
from codiff.schema.parsing import ClassChunk, FunctionChunk, Parameter
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TypeScriptParser(LanguageParser):
|
|
23
|
+
# ------------------------------------------------------------------
|
|
24
|
+
# LanguageParser interface
|
|
25
|
+
# ------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def language(self) -> Language:
|
|
29
|
+
return Language(tsts.language_typescript())
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def extension(self) -> str:
|
|
33
|
+
return ".ts"
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def resolver_class(self):
|
|
37
|
+
from codiff.languages.typescript.resolver import TypeScriptCallResolver
|
|
38
|
+
|
|
39
|
+
return TypeScriptCallResolver
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
super().__init__()
|
|
43
|
+
# List of (alias_prefix, target_prefix) where target_prefix is a
|
|
44
|
+
# slash-separated path relative to the repo root (may be empty for root).
|
|
45
|
+
# Populated by build_modules_dict from tsconfig.json; defaults handle
|
|
46
|
+
# the common @/ and ~/ conventions when no tsconfig is present so that
|
|
47
|
+
# tests calling parse_code() directly still work.
|
|
48
|
+
self._path_aliases: list[tuple[str, str]] = [("@/", ""), ("~/", "")]
|
|
49
|
+
|
|
50
|
+
# ------------------------------------------------------------------
|
|
51
|
+
# Module resolution
|
|
52
|
+
# ------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
def file_to_module_id(self, rel_path: str) -> str:
|
|
55
|
+
"""'src/api/user.ts' → 'src.api.user'"""
|
|
56
|
+
base, _ = os.path.splitext(rel_path)
|
|
57
|
+
return base.replace("/", ".")
|
|
58
|
+
|
|
59
|
+
def _is_package_init(self, filename: str) -> bool:
|
|
60
|
+
return filename in ("index.ts", "index.tsx")
|
|
61
|
+
|
|
62
|
+
def build_modules_dict(self, repo_path: Path, gitignore=None) -> dict[str, str]:
|
|
63
|
+
self._path_aliases = self._load_path_aliases(repo_path)
|
|
64
|
+
return super().build_modules_dict(repo_path, gitignore)
|
|
65
|
+
|
|
66
|
+
def build_package_exports(self, repo_path: Path, gitignore=None) -> dict[str, str]:
|
|
67
|
+
return {}
|
|
68
|
+
|
|
69
|
+
def _extra_exclude_dirs(self) -> set[str]:
|
|
70
|
+
return {".next", ".nuxt", ".cache", ".turbo", "coverage", ".jest-cache"}
|
|
71
|
+
|
|
72
|
+
# ------------------------------------------------------------------
|
|
73
|
+
# tsconfig.json path-alias loading
|
|
74
|
+
# ------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def _parse_tsconfig(text: str) -> dict:
|
|
78
|
+
"""Parse JSONC: tsconfig allows // line comments, /* */ block comments,
|
|
79
|
+
and trailing commas — none of which are valid JSON."""
|
|
80
|
+
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
|
|
81
|
+
text = re.sub(r"//[^\n]*", "", text)
|
|
82
|
+
text = re.sub(r",(\s*[}\]])", r"\1", text)
|
|
83
|
+
return json.loads(text)
|
|
84
|
+
|
|
85
|
+
def _load_path_aliases(self, repo_path: Path) -> list[tuple[str, str]]:
|
|
86
|
+
"""Scan all tsconfig*.json files under repo_path and return
|
|
87
|
+
(alias_prefix, target_prefix) pairs where target_prefix is a
|
|
88
|
+
slash-separated path relative to the repo root (empty = root).
|
|
89
|
+
|
|
90
|
+
Falls back to common @/ and ~/ conventions pointing at the repo root
|
|
91
|
+
when no tsconfig paths are found, which covers the majority of projects
|
|
92
|
+
that use default Vite/Next/Nuxt configs without explicit paths.
|
|
93
|
+
"""
|
|
94
|
+
aliases: list[tuple[str, str]] = []
|
|
95
|
+
repo_abs = repo_path.resolve()
|
|
96
|
+
|
|
97
|
+
for root, dirs, files in os.walk(str(repo_path)):
|
|
98
|
+
dirs[:] = sorted(d for d in dirs if d not in self.exclude_dirs)
|
|
99
|
+
for fname in sorted(files):
|
|
100
|
+
if not (fname.startswith("tsconfig") and fname.endswith(".json")):
|
|
101
|
+
continue
|
|
102
|
+
tsconfig_file = Path(root) / fname
|
|
103
|
+
try:
|
|
104
|
+
raw = tsconfig_file.read_text(encoding="utf-8")
|
|
105
|
+
data = self._parse_tsconfig(raw)
|
|
106
|
+
compiler_opts = data.get("compilerOptions", {})
|
|
107
|
+
paths = compiler_opts.get("paths", {})
|
|
108
|
+
if not paths:
|
|
109
|
+
continue
|
|
110
|
+
base_url = compiler_opts.get("baseUrl", ".")
|
|
111
|
+
tsconfig_dir = tsconfig_file.parent.resolve()
|
|
112
|
+
base_abs = (tsconfig_dir / base_url).resolve()
|
|
113
|
+
try:
|
|
114
|
+
base_rel = base_abs.relative_to(repo_abs)
|
|
115
|
+
except ValueError:
|
|
116
|
+
continue # base_url resolves outside the repo
|
|
117
|
+
|
|
118
|
+
for pattern, targets in paths.items():
|
|
119
|
+
if not targets:
|
|
120
|
+
continue
|
|
121
|
+
target = targets[0]
|
|
122
|
+
if pattern.endswith("/*") and target.endswith("/*"):
|
|
123
|
+
alias_prefix = pattern[:-1] # "@/*" → "@/"
|
|
124
|
+
target_sub = target[:-1] # "src/*" → "src/"
|
|
125
|
+
target_dir = os.path.normpath(str(base_rel / target_sub)).replace(
|
|
126
|
+
"\\", "/"
|
|
127
|
+
)
|
|
128
|
+
if target_dir == ".":
|
|
129
|
+
target_dir = ""
|
|
130
|
+
elif not target_dir.endswith("/"):
|
|
131
|
+
target_dir += "/"
|
|
132
|
+
aliases.append((alias_prefix, target_dir))
|
|
133
|
+
elif "*" not in pattern:
|
|
134
|
+
# Exact alias: "#lib": ["./src/lib"]
|
|
135
|
+
target_dir = os.path.normpath(str(base_rel / target)).replace("\\", "/")
|
|
136
|
+
if target_dir == ".":
|
|
137
|
+
target_dir = ""
|
|
138
|
+
aliases.append((pattern, target_dir))
|
|
139
|
+
except Exception:
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
if not aliases:
|
|
143
|
+
# No tsconfig paths found — fall back to common root conventions.
|
|
144
|
+
# @/ is used by Vite, Vue CLI, Next.js, Create React App.
|
|
145
|
+
# ~/ is used by Nuxt and some Webpack setups.
|
|
146
|
+
aliases = [("@/", ""), ("~/", "")]
|
|
147
|
+
|
|
148
|
+
return aliases
|
|
149
|
+
|
|
150
|
+
# ------------------------------------------------------------------
|
|
151
|
+
# Query initialisation
|
|
152
|
+
# ------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
def _init_queries(self) -> None:
|
|
155
|
+
lang = self.language
|
|
156
|
+
|
|
157
|
+
self.function_query = Query(
|
|
158
|
+
lang,
|
|
159
|
+
"""
|
|
160
|
+
[
|
|
161
|
+
(function_declaration
|
|
162
|
+
name: (identifier) @func_name
|
|
163
|
+
parameters: (formal_parameters) @params
|
|
164
|
+
return_type: (type_annotation)? @return_type
|
|
165
|
+
body: (statement_block) @body
|
|
166
|
+
) @function
|
|
167
|
+
(method_definition
|
|
168
|
+
name: (property_identifier) @func_name
|
|
169
|
+
parameters: (formal_parameters) @params
|
|
170
|
+
return_type: (type_annotation)? @return_type
|
|
171
|
+
body: (statement_block) @body
|
|
172
|
+
) @function
|
|
173
|
+
(lexical_declaration
|
|
174
|
+
(variable_declarator
|
|
175
|
+
name: (identifier) @func_name
|
|
176
|
+
value: (arrow_function
|
|
177
|
+
parameters: (formal_parameters)? @params
|
|
178
|
+
body: (statement_block) @body
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
) @function
|
|
182
|
+
(lexical_declaration
|
|
183
|
+
(variable_declarator
|
|
184
|
+
name: (identifier) @func_name
|
|
185
|
+
value: (call_expression
|
|
186
|
+
function: (identifier)
|
|
187
|
+
)
|
|
188
|
+
)
|
|
189
|
+
) @function
|
|
190
|
+
(pair
|
|
191
|
+
key: (property_identifier) @func_name
|
|
192
|
+
value: (arrow_function
|
|
193
|
+
parameters: (formal_parameters)? @params
|
|
194
|
+
body: (statement_block) @body
|
|
195
|
+
)
|
|
196
|
+
) @function
|
|
197
|
+
]
|
|
198
|
+
""",
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
self.class_query = Query(
|
|
202
|
+
lang,
|
|
203
|
+
"""
|
|
204
|
+
(class_declaration
|
|
205
|
+
name: (type_identifier) @class_name
|
|
206
|
+
body: (class_body) @body
|
|
207
|
+
) @class
|
|
208
|
+
""",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
# import_query is not used (parse_imports is overridden), but the
|
|
212
|
+
# LanguageParser base declares it, so set it to any valid query.
|
|
213
|
+
self.import_query = self.function_query
|
|
214
|
+
|
|
215
|
+
# ------------------------------------------------------------------
|
|
216
|
+
# Function extraction
|
|
217
|
+
# ------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
def _extract_function(self, captures_dict: dict, relative_path: str) -> FunctionChunk | None:
|
|
220
|
+
if "func_name" not in captures_dict or "function" not in captures_dict:
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
func_node = self.get_node(captures_dict, "function")
|
|
224
|
+
name_node = self.get_node(captures_dict, "func_name")
|
|
225
|
+
body_node = self.get_node(captures_dict, "body")
|
|
226
|
+
|
|
227
|
+
if func_node is None or name_node is None:
|
|
228
|
+
return None
|
|
229
|
+
|
|
230
|
+
func_name = name_node.text.decode("utf-8")
|
|
231
|
+
start_line = func_node.start_point[0] + 1
|
|
232
|
+
end_line = func_node.end_point[0] + 1
|
|
233
|
+
func_code = func_node.text.decode("utf-8")
|
|
234
|
+
|
|
235
|
+
params_node = self.get_node(captures_dict, "params")
|
|
236
|
+
parameters = self._extract_ts_parameters(params_node) if params_node else []
|
|
237
|
+
|
|
238
|
+
return_type = None
|
|
239
|
+
rt_node = self.get_node(captures_dict, "return_type")
|
|
240
|
+
if rt_node:
|
|
241
|
+
# Strip leading ': ' from the type_annotation text
|
|
242
|
+
rt_text = rt_node.text.decode("utf-8")
|
|
243
|
+
return_type = rt_text.lstrip(":").strip()
|
|
244
|
+
|
|
245
|
+
class_name = self._get_class_context(func_node)
|
|
246
|
+
nested = self._get_nested_context(func_node)
|
|
247
|
+
|
|
248
|
+
path_base = os.path.splitext(relative_path)[0] # strip .ts / .tsx
|
|
249
|
+
_id = path_base + "/" + class_name + "." if class_name else path_base + "/"
|
|
250
|
+
_id = _id + nested + "." if nested else _id
|
|
251
|
+
_id = _id + func_name
|
|
252
|
+
_id = _id.replace("/", ".")
|
|
253
|
+
|
|
254
|
+
var_types, _ = self._extract_ts_variable_assignments(body_node) if body_node else ({}, {})
|
|
255
|
+
calls = self._extract_ts_calls(body_node) if body_node else []
|
|
256
|
+
|
|
257
|
+
return FunctionChunk(
|
|
258
|
+
id=_id,
|
|
259
|
+
name=func_name,
|
|
260
|
+
code=func_code,
|
|
261
|
+
docstring=None,
|
|
262
|
+
start_line=start_line,
|
|
263
|
+
end_line=end_line,
|
|
264
|
+
parameters=parameters,
|
|
265
|
+
decorators=[],
|
|
266
|
+
file_path=relative_path,
|
|
267
|
+
class_name=class_name,
|
|
268
|
+
nested=nested,
|
|
269
|
+
return_type=return_type,
|
|
270
|
+
calls=calls,
|
|
271
|
+
var_types=var_types if var_types else None,
|
|
272
|
+
var_sources=None,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
def _get_class_context(self, func_node) -> str | None:
|
|
276
|
+
current = func_node.parent
|
|
277
|
+
depth = 0
|
|
278
|
+
while current and depth < 10:
|
|
279
|
+
if current.type == "class_declaration":
|
|
280
|
+
for child in current.named_children:
|
|
281
|
+
if child.type == "type_identifier":
|
|
282
|
+
return child.text.decode("utf-8")
|
|
283
|
+
depth += 1
|
|
284
|
+
current = current.parent
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
def _get_nested_context(self, func_node) -> str | None:
|
|
288
|
+
current = func_node.parent
|
|
289
|
+
depth = 0
|
|
290
|
+
while current and depth < 10:
|
|
291
|
+
if current.type in ("function_declaration", "method_definition"):
|
|
292
|
+
for child in current.named_children:
|
|
293
|
+
if child.type in ("identifier", "property_identifier"):
|
|
294
|
+
return child.text.decode("utf-8")
|
|
295
|
+
depth += 1
|
|
296
|
+
current = current.parent
|
|
297
|
+
return None
|
|
298
|
+
|
|
299
|
+
def _extract_ts_parameters(self, params_node) -> list[Parameter]:
|
|
300
|
+
parameters = []
|
|
301
|
+
for child in params_node.named_children:
|
|
302
|
+
if child.type in ("required_parameter", "optional_parameter", "rest_parameter"):
|
|
303
|
+
name, type_ = self._extract_ts_param_info(child)
|
|
304
|
+
if name:
|
|
305
|
+
parameters.append(Parameter(name=name, type=type_, value=None))
|
|
306
|
+
return parameters
|
|
307
|
+
|
|
308
|
+
def _extract_ts_param_info(self, param_node) -> tuple[str | None, str | None]:
|
|
309
|
+
name = None
|
|
310
|
+
type_ = None
|
|
311
|
+
for child in param_node.named_children:
|
|
312
|
+
if child.type == "accessibility_modifier":
|
|
313
|
+
continue
|
|
314
|
+
if child.type in ("identifier", "object_pattern", "array_pattern") and name is None:
|
|
315
|
+
if child.type == "identifier":
|
|
316
|
+
name = child.text.decode("utf-8")
|
|
317
|
+
else:
|
|
318
|
+
name = child.text.decode("utf-8")
|
|
319
|
+
elif child.type == "type_annotation" and type_ is None:
|
|
320
|
+
type_ = child.text.decode("utf-8").lstrip(":").strip()
|
|
321
|
+
return name, type_
|
|
322
|
+
|
|
323
|
+
# ------------------------------------------------------------------
|
|
324
|
+
# Call extraction
|
|
325
|
+
# ------------------------------------------------------------------
|
|
326
|
+
|
|
327
|
+
def _extract_ts_calls(self, body_node) -> list[str]:
|
|
328
|
+
calls: list[str] = []
|
|
329
|
+
|
|
330
|
+
def walk(node):
|
|
331
|
+
for child in node.children:
|
|
332
|
+
if child.type in (
|
|
333
|
+
"function_declaration",
|
|
334
|
+
"method_definition",
|
|
335
|
+
"arrow_function",
|
|
336
|
+
"function",
|
|
337
|
+
):
|
|
338
|
+
continue
|
|
339
|
+
walk(child)
|
|
340
|
+
|
|
341
|
+
if node.type == "call_expression":
|
|
342
|
+
call_str = self._parse_ts_call(node)
|
|
343
|
+
if call_str:
|
|
344
|
+
calls.append(call_str)
|
|
345
|
+
|
|
346
|
+
elif node.type == "new_expression":
|
|
347
|
+
ctor = self._parse_ts_new(node)
|
|
348
|
+
if ctor:
|
|
349
|
+
calls.append(ctor)
|
|
350
|
+
|
|
351
|
+
elif node.type in ("jsx_self_closing_element", "jsx_opening_element"):
|
|
352
|
+
name = self._parse_jsx_element_name(node)
|
|
353
|
+
# Emit unconditionally — HTML intrinsics (div, span…) won't be
|
|
354
|
+
# in any import dict so the resolver drops them silently.
|
|
355
|
+
if name:
|
|
356
|
+
calls.append(name)
|
|
357
|
+
|
|
358
|
+
walk(body_node)
|
|
359
|
+
return calls
|
|
360
|
+
|
|
361
|
+
def _parse_jsx_element_name(self, node) -> str | None:
|
|
362
|
+
"""Return the component name from a jsx_self_closing_element or jsx_opening_element."""
|
|
363
|
+
for child in node.children:
|
|
364
|
+
if child.type == "identifier":
|
|
365
|
+
return child.text.decode("utf-8")
|
|
366
|
+
if child.type == "member_expression":
|
|
367
|
+
return child.text.decode("utf-8")
|
|
368
|
+
return None
|
|
369
|
+
|
|
370
|
+
def _parse_ts_call(self, call_node) -> str | None:
|
|
371
|
+
"""Extract the call target string from a call_expression node."""
|
|
372
|
+
func_child = None
|
|
373
|
+
for child in call_node.children:
|
|
374
|
+
if child.type != "arguments":
|
|
375
|
+
func_child = child
|
|
376
|
+
break
|
|
377
|
+
|
|
378
|
+
if func_child is None:
|
|
379
|
+
return None
|
|
380
|
+
|
|
381
|
+
if func_child.type == "identifier":
|
|
382
|
+
return func_child.text.decode("utf-8")
|
|
383
|
+
|
|
384
|
+
if func_child.type == "super":
|
|
385
|
+
return "super"
|
|
386
|
+
|
|
387
|
+
if func_child.type == "member_expression":
|
|
388
|
+
obj = None
|
|
389
|
+
method = None
|
|
390
|
+
for child in func_child.named_children:
|
|
391
|
+
if obj is None:
|
|
392
|
+
obj = child.text.decode("utf-8")
|
|
393
|
+
else:
|
|
394
|
+
method = child.text.decode("utf-8")
|
|
395
|
+
if obj and method:
|
|
396
|
+
return f"{obj}.{method}"
|
|
397
|
+
return func_child.text.decode("utf-8")
|
|
398
|
+
|
|
399
|
+
if func_child.type == "call_expression":
|
|
400
|
+
# Chained call: e.g. getService().method()
|
|
401
|
+
inner = self._parse_ts_call(func_child)
|
|
402
|
+
return inner
|
|
403
|
+
|
|
404
|
+
return None
|
|
405
|
+
|
|
406
|
+
def _parse_ts_new(self, new_node) -> str | None:
|
|
407
|
+
"""Extract the constructor name from a new_expression node."""
|
|
408
|
+
for child in new_node.children:
|
|
409
|
+
if child.type in ("new", "arguments"):
|
|
410
|
+
continue
|
|
411
|
+
if child.type in ("identifier", "member_expression"):
|
|
412
|
+
return child.text.decode("utf-8")
|
|
413
|
+
return None
|
|
414
|
+
|
|
415
|
+
# ------------------------------------------------------------------
|
|
416
|
+
# Variable assignment extraction (new_expression only)
|
|
417
|
+
# ------------------------------------------------------------------
|
|
418
|
+
|
|
419
|
+
def _extract_ts_variable_assignments(self, body_node) -> tuple[dict, dict]:
|
|
420
|
+
var_types: dict = {}
|
|
421
|
+
|
|
422
|
+
def walk(node):
|
|
423
|
+
if node.type in (
|
|
424
|
+
"function_declaration",
|
|
425
|
+
"method_definition",
|
|
426
|
+
"arrow_function",
|
|
427
|
+
"function",
|
|
428
|
+
):
|
|
429
|
+
return
|
|
430
|
+
if node.type in ("lexical_declaration", "variable_declaration"):
|
|
431
|
+
for child in node.named_children:
|
|
432
|
+
if child.type == "variable_declarator":
|
|
433
|
+
self._handle_ts_declarator(child, var_types)
|
|
434
|
+
for child in node.children:
|
|
435
|
+
walk(child)
|
|
436
|
+
|
|
437
|
+
walk(body_node)
|
|
438
|
+
return var_types, {}
|
|
439
|
+
|
|
440
|
+
def _handle_ts_declarator(self, decl_node, var_types: dict) -> None:
|
|
441
|
+
var_name = None
|
|
442
|
+
for child in decl_node.named_children:
|
|
443
|
+
if child.type == "identifier" and var_name is None:
|
|
444
|
+
var_name = child.text.decode("utf-8")
|
|
445
|
+
elif child.type == "new_expression" and var_name is not None:
|
|
446
|
+
ctor = self._parse_ts_new(child)
|
|
447
|
+
if ctor:
|
|
448
|
+
var_types[var_name] = [ctor]
|
|
449
|
+
|
|
450
|
+
# ------------------------------------------------------------------
|
|
451
|
+
# Class extraction
|
|
452
|
+
# ------------------------------------------------------------------
|
|
453
|
+
|
|
454
|
+
def _extract_class(self, captures_dict: dict, relative_path: str) -> ClassChunk | None:
|
|
455
|
+
class_node = self.get_node(captures_dict, "class")
|
|
456
|
+
name_node = self.get_node(captures_dict, "class_name")
|
|
457
|
+
if class_node is None or name_node is None:
|
|
458
|
+
return None
|
|
459
|
+
|
|
460
|
+
class_name = name_node.text.decode("utf-8")
|
|
461
|
+
start_line = class_node.start_point[0] + 1
|
|
462
|
+
end_line = class_node.end_point[0] + 1
|
|
463
|
+
class_code = class_node.text.decode("utf-8")
|
|
464
|
+
|
|
465
|
+
# Extract superclasses from class_heritage → extends_clause
|
|
466
|
+
superclasses: list[str] = []
|
|
467
|
+
for child in class_node.children:
|
|
468
|
+
if child.type == "class_heritage":
|
|
469
|
+
for sub in child.children:
|
|
470
|
+
if sub.type == "extends_clause":
|
|
471
|
+
for val in sub.children:
|
|
472
|
+
if val.type in ("identifier", "type_identifier"):
|
|
473
|
+
superclasses.append(val.text.decode("utf-8"))
|
|
474
|
+
|
|
475
|
+
path_base = os.path.splitext(relative_path)[0]
|
|
476
|
+
_id = (path_base + "/" + class_name).replace("/", ".")
|
|
477
|
+
|
|
478
|
+
return ClassChunk(
|
|
479
|
+
id=_id,
|
|
480
|
+
name=class_name,
|
|
481
|
+
code=class_code,
|
|
482
|
+
docstring=None,
|
|
483
|
+
start_line=start_line,
|
|
484
|
+
end_line=end_line,
|
|
485
|
+
decorators=[],
|
|
486
|
+
superclasses=superclasses,
|
|
487
|
+
file_path=relative_path,
|
|
488
|
+
)
|
|
489
|
+
|
|
490
|
+
# ------------------------------------------------------------------
|
|
491
|
+
# Import extraction (override parse_imports; _extract_imports unused)
|
|
492
|
+
# ------------------------------------------------------------------
|
|
493
|
+
|
|
494
|
+
def _extract_imports(self, captures_dict: dict, all_modules: dict, path=None) -> dict:
|
|
495
|
+
return {} # parse_imports is overridden; this is never called
|
|
496
|
+
|
|
497
|
+
def parse_imports(
|
|
498
|
+
self, source_code: str, all_modules: dict, relative_path: "str | None" = None
|
|
499
|
+
) -> dict:
|
|
500
|
+
tree = self.parser.parse(bytes(source_code, "utf8"))
|
|
501
|
+
imports: dict = {}
|
|
502
|
+
for child in tree.root_node.children:
|
|
503
|
+
if child.type == "import_statement":
|
|
504
|
+
self._process_import_statement(child, all_modules, relative_path, imports)
|
|
505
|
+
return imports
|
|
506
|
+
|
|
507
|
+
def _process_import_statement(
|
|
508
|
+
self, stmt_node, all_modules: dict, current_file: "str | None", imports: dict
|
|
509
|
+
) -> None:
|
|
510
|
+
# Skip type-only imports (import type { ... })
|
|
511
|
+
for child in stmt_node.children:
|
|
512
|
+
if child.text == b"type":
|
|
513
|
+
return
|
|
514
|
+
|
|
515
|
+
source_node = None
|
|
516
|
+
import_clause_node = None
|
|
517
|
+
for child in stmt_node.named_children:
|
|
518
|
+
if child.type == "import_clause":
|
|
519
|
+
import_clause_node = child
|
|
520
|
+
elif child.type == "string":
|
|
521
|
+
source_node = child
|
|
522
|
+
|
|
523
|
+
if source_node is None or import_clause_node is None:
|
|
524
|
+
return
|
|
525
|
+
|
|
526
|
+
source_str = source_node.text.decode("utf-8")
|
|
527
|
+
module_path = self._resolve_ts_import_source(source_str, current_file, all_modules)
|
|
528
|
+
if module_path is None:
|
|
529
|
+
return
|
|
530
|
+
|
|
531
|
+
for child in import_clause_node.children:
|
|
532
|
+
if child.type == "identifier":
|
|
533
|
+
# Default import: import Foo from '...'
|
|
534
|
+
name = child.text.decode("utf-8")
|
|
535
|
+
imports[name] = f"{module_path}.{name}"
|
|
536
|
+
elif child.type == "named_imports":
|
|
537
|
+
for specifier in child.named_children:
|
|
538
|
+
if specifier.type == "import_specifier":
|
|
539
|
+
names = [n for n in specifier.named_children if n.type == "identifier"]
|
|
540
|
+
if len(names) >= 1:
|
|
541
|
+
orig = names[0].text.decode("utf-8")
|
|
542
|
+
alias = names[-1].text.decode("utf-8") # same as orig if no alias
|
|
543
|
+
imports[alias] = f"{module_path}.{orig}"
|
|
544
|
+
elif child.type == "namespace_import":
|
|
545
|
+
# import * as NS from '...'
|
|
546
|
+
for sub in child.named_children:
|
|
547
|
+
if sub.type == "identifier":
|
|
548
|
+
name = sub.text.decode("utf-8")
|
|
549
|
+
imports[name] = module_path
|
|
550
|
+
|
|
551
|
+
def _resolve_ts_import_source(
|
|
552
|
+
self, source_str: str, current_file: "str | None", all_modules: dict
|
|
553
|
+
) -> "str | None":
|
|
554
|
+
"""Resolve a TS import source string to a module path from all_modules."""
|
|
555
|
+
source = source_str.strip("'\"")
|
|
556
|
+
|
|
557
|
+
# Check path aliases loaded from tsconfig.json (e.g. @/, ~/, #lib, …).
|
|
558
|
+
for alias_prefix, target_prefix in self._path_aliases:
|
|
559
|
+
if source.startswith(alias_prefix):
|
|
560
|
+
remainder = source[len(alias_prefix) :]
|
|
561
|
+
raw = target_prefix + remainder
|
|
562
|
+
normalized = os.path.normpath(raw).replace("\\", "/")
|
|
563
|
+
mod_key = os.path.splitext(normalized)[0].replace("/", ".")
|
|
564
|
+
if mod_key in all_modules:
|
|
565
|
+
return all_modules[mod_key]
|
|
566
|
+
# Stem fallback within this alias
|
|
567
|
+
stem = Path(remainder).stem
|
|
568
|
+
for key, val in all_modules.items():
|
|
569
|
+
if key.endswith("." + stem) or key == stem:
|
|
570
|
+
return val
|
|
571
|
+
return None # Matched alias but module not in codebase
|
|
572
|
+
|
|
573
|
+
if not source.startswith("."):
|
|
574
|
+
return None # External npm package — not in codebase
|
|
575
|
+
|
|
576
|
+
if current_file is None:
|
|
577
|
+
return None
|
|
578
|
+
|
|
579
|
+
current_dir = Path(current_file).parent
|
|
580
|
+
# Resolve relative to current file; normpath handles ./ and ../ correctly.
|
|
581
|
+
# Strip any extension (imports rarely include .ts but handle it defensively).
|
|
582
|
+
resolved = os.path.normpath(str(current_dir / source)).replace("\\", "/")
|
|
583
|
+
mod_key = os.path.splitext(resolved)[0].replace("/", ".")
|
|
584
|
+
if mod_key in all_modules:
|
|
585
|
+
return all_modules[mod_key]
|
|
586
|
+
|
|
587
|
+
# Last resort: suffix match on stem (handles unusual path shapes)
|
|
588
|
+
source_stem = Path(source).stem
|
|
589
|
+
for key, val in all_modules.items():
|
|
590
|
+
if key.endswith("." + source_stem) or key == source_stem:
|
|
591
|
+
return val
|
|
592
|
+
|
|
593
|
+
return None
|
|
594
|
+
|
|
595
|
+
# ------------------------------------------------------------------
|
|
596
|
+
# Module docstring (TypeScript has no string-literal docstrings)
|
|
597
|
+
# ------------------------------------------------------------------
|
|
598
|
+
|
|
599
|
+
def _extract_module_docstring(self, source: str) -> "str | None":
|
|
600
|
+
return None
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
class TypeScriptXParser(TypeScriptParser):
|
|
604
|
+
"""Parser for .tsx files (React TypeScript)."""
|
|
605
|
+
|
|
606
|
+
@property
|
|
607
|
+
def language(self) -> Language:
|
|
608
|
+
return Language(tsts.language_tsx())
|
|
609
|
+
|
|
610
|
+
@property
|
|
611
|
+
def extension(self) -> str:
|
|
612
|
+
return ".tsx"
|