tokensafe 3.2.0 → 4.0.1
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.
- package/README.md +60 -28
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +234 -2
- package/src/command_sanitizer.py +2 -0
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +202 -0
package/src/graph_engine.py
CHANGED
|
@@ -19,6 +19,7 @@ import hashlib
|
|
|
19
19
|
import json
|
|
20
20
|
import os
|
|
21
21
|
import re
|
|
22
|
+
import sqlite3
|
|
22
23
|
import stat
|
|
23
24
|
import tempfile
|
|
24
25
|
import time
|
|
@@ -50,7 +51,76 @@ _SKIP_CALLS = {
|
|
|
50
51
|
"true", "false", "null", "undefined", "None", "True", "False",
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
_CACHE_SCHEMA_VERSION =
|
|
54
|
+
_CACHE_SCHEMA_VERSION = 3
|
|
55
|
+
|
|
56
|
+
_STATIC_ASSET_EXTS = {
|
|
57
|
+
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
|
|
58
|
+
".css", ".scss", ".sass", ".less",
|
|
59
|
+
".woff", ".woff2", ".ttf", ".eot",
|
|
60
|
+
".map", ".pdf", ".mp4", ".mp3",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
_BACKEND_ROUTE_PATTERNS = [
|
|
64
|
+
# Python: @app.get("/users"), @router.post('/login'), @bp.route('/data')
|
|
65
|
+
re.compile(r'@(?:app|router|api|bp)\.(?:get|post|put|delete|patch|route)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
|
|
66
|
+
# JS/TS: app.get("/users", ...), router.post('/login', ...)
|
|
67
|
+
re.compile(r'(?<!@)\b(?:app|router|server|fastify)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']', re.IGNORECASE),
|
|
68
|
+
# Java/Kotlin Spring: @GetMapping("/users"), @PostMapping(value = "/login"), @RequestMapping("/api")
|
|
69
|
+
re.compile(r'@(?:Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']', re.IGNORECASE),
|
|
70
|
+
# Go Gin/Echo/Fiber: r.GET("/users", ...), router.POST('/login', ...)
|
|
71
|
+
re.compile(r'\b(?:r|router|g|e|app)\.(?:GET|POST|PUT|DELETE|PATCH)\(\s*["\']([^"\']+)["\']'),
|
|
72
|
+
# Go net/http: http.HandleFunc("/users", ...)
|
|
73
|
+
re.compile(r'http\.HandleFunc\(\s*["\']([^"\']+)["\']'),
|
|
74
|
+
# C# ASP.NET Core: [HttpGet("/users")], [Route("api/users")]
|
|
75
|
+
re.compile(r'\[(?:Http(?:Get|Post|Put|Delete|Patch)|Route)\(\s*["\']([^"\']+)["\']'),
|
|
76
|
+
# PHP Laravel: Route::get('/users', ...), Route::post('/login', ...)
|
|
77
|
+
re.compile(r'Route::(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)["\']'),
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
_FRONTEND_CALL_PATTERNS = [
|
|
81
|
+
# fetch("/api/users") or fetch(`/api/users/${id}`)
|
|
82
|
+
re.compile(r'\bfetch\(\s*[`"\']([^`"\'?#]+)'),
|
|
83
|
+
# axios.get("/api/users"), api.post(`/api/users/${id}`), client.get, etc.
|
|
84
|
+
re.compile(r'\b(?:axios|api|client|httpClient|ky)\.(?:get|post|put|delete|patch)\(\s*[`"\']([^`"\'?#]+)'),
|
|
85
|
+
# useSWR("/api/users")
|
|
86
|
+
re.compile(r'\buseSWR\(\s*[`"\']([^`"\'?#]+)'),
|
|
87
|
+
# axios("/api/users")
|
|
88
|
+
re.compile(r'\baxios\(\s*[`"\']([^`"\'?#]+)'),
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
_NEXT_APP_ROUTE_RE = re.compile(r'^(?:src/)?app/(api/.+?)/route\.[a-zA-Z0-9]+$')
|
|
92
|
+
_NEXT_PAGES_ROUTE_RE = re.compile(r'^(?:src/)?pages/(api/.+?)\.[a-zA-Z0-9]+$')
|
|
93
|
+
_CONTROLLER_PREFIX_RE = re.compile(r'@RequestMapping\(\s*(?:value\s*=\s*)?["\']([^"\']+)["\']|\[Route\(\s*["\']([^"\']+)["\']\)', re.IGNORECASE)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _normalize_route_path(p: str) -> str:
|
|
97
|
+
if not p or not isinstance(p, str):
|
|
98
|
+
return ""
|
|
99
|
+
p = p.strip()
|
|
100
|
+
if not p:
|
|
101
|
+
return ""
|
|
102
|
+
p = re.sub(r'^https?://[^/]+', '', p).strip()
|
|
103
|
+
p = p.split('?')[0].split('#')[0].strip()
|
|
104
|
+
if not p:
|
|
105
|
+
return ""
|
|
106
|
+
if not p.startswith('/'):
|
|
107
|
+
p = '/' + p
|
|
108
|
+
# Replace template expressions ${...} or {param}
|
|
109
|
+
p = re.sub(r'\$?\{[^}]+\}', '*', p)
|
|
110
|
+
# Replace Next.js / bracket params [...param] or [param]
|
|
111
|
+
p = re.sub(r'\[[^]]+\]', '*', p)
|
|
112
|
+
# Replace Express / path params :param
|
|
113
|
+
p = re.sub(r':[a-zA-Z_][a-zA-Z0-9_]*', '*', p)
|
|
114
|
+
# Collapse multiple slashes
|
|
115
|
+
p = re.sub(r'/+', '/', p)
|
|
116
|
+
if len(p) > 1 and p.endswith('/'):
|
|
117
|
+
p = p[:-1]
|
|
118
|
+
_, ext = os.path.splitext(p)
|
|
119
|
+
if ext.lower() in _STATIC_ASSET_EXTS:
|
|
120
|
+
return ""
|
|
121
|
+
if p in ("/", "*", "/*"):
|
|
122
|
+
return ""
|
|
123
|
+
return p
|
|
54
124
|
|
|
55
125
|
|
|
56
126
|
def _is_test_file(rel_path: str) -> bool:
|
|
@@ -125,6 +195,8 @@ class CodeGraph:
|
|
|
125
195
|
self.file_mtimes: Dict[str, float] = {} # file_rel_path -> mtime
|
|
126
196
|
self.file_stats: Dict[str, Tuple[float, int]] = {} # file_rel_path -> (mtime, size)
|
|
127
197
|
self.file_imports: Dict[str, Set[str]] = {} # file_rel_path -> raw imported modules
|
|
198
|
+
self.file_endpoints: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
|
|
199
|
+
self.file_api_calls: Dict[str, List[Tuple[str, Optional[str]]]] = {} # rel_path -> [(norm_route, sym_key)]
|
|
128
200
|
self.last_scanned: float = 0.0
|
|
129
201
|
self.backend: str = self._detect_backend()
|
|
130
202
|
|
|
@@ -142,46 +214,129 @@ class CodeGraph:
|
|
|
142
214
|
return "stdlib"
|
|
143
215
|
|
|
144
216
|
def _cache_path(self) -> str:
|
|
217
|
+
cache_dir = os.path.join(resolve_data_dir(), "graph_cache")
|
|
218
|
+
key = hashlib.md5(self.root_dir.encode("utf-8")).hexdigest()[:12]
|
|
219
|
+
return os.path.join(cache_dir, f"{key}.db")
|
|
220
|
+
|
|
221
|
+
def _legacy_json_cache_path(self) -> str:
|
|
145
222
|
cache_dir = os.path.join(resolve_data_dir(), "graph_cache")
|
|
146
223
|
key = hashlib.md5(self.root_dir.encode("utf-8")).hexdigest()[:12]
|
|
147
224
|
return os.path.join(cache_dir, f"{key}.json")
|
|
148
225
|
|
|
226
|
+
def _clear_graph_state(self) -> None:
|
|
227
|
+
self.symbols.clear()
|
|
228
|
+
self.file_symbols.clear()
|
|
229
|
+
self.edges.clear()
|
|
230
|
+
self.rev_edges.clear()
|
|
231
|
+
self.file_stats.clear()
|
|
232
|
+
self.file_mtimes.clear()
|
|
233
|
+
self.file_imports.clear()
|
|
234
|
+
self.file_endpoints.clear()
|
|
235
|
+
self.file_api_calls.clear()
|
|
236
|
+
|
|
149
237
|
def _load_disk_cache(self) -> bool:
|
|
150
238
|
path = self._cache_path()
|
|
151
|
-
if
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
239
|
+
if os.path.exists(path):
|
|
240
|
+
try:
|
|
241
|
+
con = sqlite3.connect(path, timeout=5.0)
|
|
242
|
+
try:
|
|
243
|
+
cur = con.cursor()
|
|
244
|
+
meta = dict(cur.execute("SELECT key, val FROM graph_meta").fetchall())
|
|
245
|
+
if (
|
|
246
|
+
int(meta.get("version", 0)) != _CACHE_SCHEMA_VERSION
|
|
247
|
+
or meta.get("root_dir") != self.root_dir
|
|
248
|
+
or meta.get("backend") != self.backend
|
|
249
|
+
):
|
|
250
|
+
return False
|
|
251
|
+
|
|
252
|
+
self.symbols = {}
|
|
253
|
+
for row in cur.execute("SELECT sym_key, rel_path, name, kind, line_start, line_end, signature FROM symbols").fetchall():
|
|
254
|
+
self.symbols[row[0]] = CodeSymbol(
|
|
255
|
+
name=row[2],
|
|
256
|
+
kind=row[3],
|
|
257
|
+
file_path=row[1],
|
|
258
|
+
line_start=int(row[4]),
|
|
259
|
+
line_end=int(row[5]),
|
|
260
|
+
signature=row[6],
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
self.file_symbols = {}
|
|
264
|
+
for row in cur.execute("SELECT rel_path, sym_key FROM file_symbols ORDER BY rel_path, idx").fetchall():
|
|
265
|
+
self.file_symbols.setdefault(row[0], []).append(row[1])
|
|
266
|
+
|
|
267
|
+
self.file_stats = {
|
|
268
|
+
row[0]: (float(row[1]), int(row[2]))
|
|
269
|
+
for row in cur.execute("SELECT rel_path, mtime, size FROM file_stats").fetchall()
|
|
270
|
+
}
|
|
271
|
+
self.file_mtimes = {k: v[0] for k, v in self.file_stats.items()}
|
|
272
|
+
|
|
273
|
+
self.file_imports = {}
|
|
274
|
+
for row in cur.execute("SELECT rel_path, imported FROM file_imports").fetchall():
|
|
275
|
+
self.file_imports.setdefault(row[0], set()).add(row[1])
|
|
276
|
+
|
|
277
|
+
self.edges = {}
|
|
278
|
+
self.rev_edges = {}
|
|
279
|
+
for row in cur.execute("SELECT source, target FROM edges").fetchall():
|
|
280
|
+
s, t = row[0], row[1]
|
|
281
|
+
self.edges.setdefault(s, set()).add(t)
|
|
282
|
+
self.rev_edges.setdefault(t, set()).add(s)
|
|
283
|
+
|
|
284
|
+
self.file_endpoints = {}
|
|
285
|
+
try:
|
|
286
|
+
for row in cur.execute("SELECT rel_path, route, sym_key FROM api_endpoints").fetchall():
|
|
287
|
+
self.file_endpoints.setdefault(row[0], []).append((row[1], row[2]))
|
|
288
|
+
except sqlite3.OperationalError:
|
|
289
|
+
pass
|
|
290
|
+
|
|
291
|
+
self.file_api_calls = {}
|
|
292
|
+
try:
|
|
293
|
+
for row in cur.execute("SELECT rel_path, route, sym_key FROM api_calls").fetchall():
|
|
294
|
+
self.file_api_calls.setdefault(row[0], []).append((row[1], row[2]))
|
|
295
|
+
except sqlite3.OperationalError:
|
|
296
|
+
pass
|
|
297
|
+
|
|
298
|
+
self.last_scanned = float(meta.get("last_scanned", 0.0))
|
|
299
|
+
return True
|
|
300
|
+
finally:
|
|
301
|
+
con.close()
|
|
302
|
+
except Exception:
|
|
303
|
+
self._clear_graph_state()
|
|
161
304
|
return False
|
|
162
305
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
306
|
+
# Fallback to legacy JSON cache if present
|
|
307
|
+
legacy_path = self._legacy_json_cache_path()
|
|
308
|
+
if os.path.exists(legacy_path):
|
|
309
|
+
try:
|
|
310
|
+
with open(legacy_path, "r", encoding="utf-8") as f:
|
|
311
|
+
data = json.load(f)
|
|
312
|
+
if (
|
|
313
|
+
data.get("root_dir") == self.root_dir
|
|
314
|
+
and data.get("backend") == self.backend
|
|
315
|
+
):
|
|
316
|
+
self.symbols = {k: CodeSymbol.from_dict(v) for k, v in data.get("symbols", {}).items()}
|
|
317
|
+
self.file_symbols = {k: list(v) for k, v in data.get("file_symbols", {}).items()}
|
|
318
|
+
self.edges = {k: set(v) for k, v in data.get("edges", {}).items()}
|
|
319
|
+
self.rev_edges = {k: set(v) for k, v in data.get("rev_edges", {}).items()}
|
|
320
|
+
self.file_stats = {
|
|
321
|
+
k: (float(v[0]), int(v[1]))
|
|
322
|
+
for k, v in data.get("file_stats", {}).items()
|
|
323
|
+
if isinstance(v, (list, tuple)) and len(v) == 2
|
|
324
|
+
}
|
|
325
|
+
self.file_mtimes = {k: v[0] for k, v in self.file_stats.items()}
|
|
326
|
+
self.file_imports = {k: set(v) for k, v in data.get("file_imports", {}).items()}
|
|
327
|
+
self.last_scanned = float(data.get("last_scanned", 0.0))
|
|
328
|
+
# Migrate to SQLite format
|
|
329
|
+
self._save_disk_cache()
|
|
330
|
+
try:
|
|
331
|
+
os.remove(legacy_path)
|
|
332
|
+
except OSError:
|
|
333
|
+
pass
|
|
334
|
+
return True
|
|
335
|
+
except Exception:
|
|
336
|
+
self._clear_graph_state()
|
|
337
|
+
return False
|
|
338
|
+
|
|
339
|
+
return False
|
|
185
340
|
|
|
186
341
|
def _save_disk_cache(self) -> None:
|
|
187
342
|
if not self.use_disk_cache or os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") == "0":
|
|
@@ -190,22 +345,68 @@ class CodeGraph:
|
|
|
190
345
|
cache_dir = os.path.dirname(path)
|
|
191
346
|
try:
|
|
192
347
|
os.makedirs(cache_dir, exist_ok=True)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
"root_dir": self.root_dir,
|
|
196
|
-
"backend": self.backend,
|
|
197
|
-
"last_scanned": self.last_scanned,
|
|
198
|
-
"file_stats": {k: [v[0], v[1]] for k, v in self.file_stats.items()},
|
|
199
|
-
"file_symbols": self.file_symbols,
|
|
200
|
-
"file_imports": {k: sorted(v) for k, v in self.file_imports.items()},
|
|
201
|
-
"symbols": {k: v.to_dict() for k, v in self.symbols.items()},
|
|
202
|
-
"edges": {k: sorted(v) for k, v in self.edges.items()},
|
|
203
|
-
"rev_edges": {k: sorted(v) for k, v in self.rev_edges.items()},
|
|
204
|
-
}
|
|
205
|
-
fd, tmp_path = tempfile.mkstemp(prefix="graph_", suffix=".tmp", dir=cache_dir)
|
|
348
|
+
fd, tmp_path = tempfile.mkstemp(prefix="graph_", suffix=".db.tmp", dir=cache_dir)
|
|
349
|
+
os.close(fd)
|
|
206
350
|
try:
|
|
207
|
-
|
|
208
|
-
|
|
351
|
+
con = sqlite3.connect(tmp_path, timeout=5.0)
|
|
352
|
+
try:
|
|
353
|
+
cur = con.cursor()
|
|
354
|
+
cur.execute("PRAGMA journal_mode = OFF")
|
|
355
|
+
cur.execute("PRAGMA synchronous = OFF")
|
|
356
|
+
cur.execute("CREATE TABLE graph_meta (key TEXT PRIMARY KEY, val TEXT)")
|
|
357
|
+
cur.execute("CREATE TABLE file_stats (rel_path TEXT PRIMARY KEY, mtime REAL, size INTEGER)")
|
|
358
|
+
cur.execute("CREATE TABLE symbols (sym_key TEXT PRIMARY KEY, rel_path TEXT, name TEXT, kind TEXT, line_start INTEGER, line_end INTEGER, signature TEXT)")
|
|
359
|
+
cur.execute("CREATE TABLE file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
|
|
360
|
+
cur.execute("CREATE TABLE file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
|
|
361
|
+
cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
|
|
362
|
+
cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT)")
|
|
363
|
+
cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT)")
|
|
364
|
+
|
|
365
|
+
cur.executemany(
|
|
366
|
+
"INSERT INTO graph_meta VALUES (?, ?)",
|
|
367
|
+
[
|
|
368
|
+
("version", str(_CACHE_SCHEMA_VERSION)),
|
|
369
|
+
("root_dir", self.root_dir),
|
|
370
|
+
("backend", self.backend),
|
|
371
|
+
("last_scanned", str(self.last_scanned)),
|
|
372
|
+
],
|
|
373
|
+
)
|
|
374
|
+
cur.executemany(
|
|
375
|
+
"INSERT INTO file_stats VALUES (?, ?, ?)",
|
|
376
|
+
[(k, v[0], v[1]) for k, v in self.file_stats.items()],
|
|
377
|
+
)
|
|
378
|
+
cur.executemany(
|
|
379
|
+
"INSERT INTO symbols VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
380
|
+
[
|
|
381
|
+
(k, s.file_path, s.name, s.kind, s.line_start, s.line_end, s.signature)
|
|
382
|
+
for k, s in self.symbols.items()
|
|
383
|
+
],
|
|
384
|
+
)
|
|
385
|
+
fs_rows = []
|
|
386
|
+
for rel_path, sym_keys in self.file_symbols.items():
|
|
387
|
+
for idx, sym_key in enumerate(sym_keys):
|
|
388
|
+
fs_rows.append((rel_path, sym_key, idx))
|
|
389
|
+
cur.executemany("INSERT INTO file_symbols VALUES (?, ?, ?)", fs_rows)
|
|
390
|
+
|
|
391
|
+
cur.executemany(
|
|
392
|
+
"INSERT INTO file_imports VALUES (?, ?)",
|
|
393
|
+
[(rel_path, imp) for rel_path, imps in self.file_imports.items() for imp in imps],
|
|
394
|
+
)
|
|
395
|
+
cur.executemany(
|
|
396
|
+
"INSERT INTO edges VALUES (?, ?)",
|
|
397
|
+
[(src, tgt) for src, tgts in self.edges.items() for tgt in tgts],
|
|
398
|
+
)
|
|
399
|
+
cur.executemany(
|
|
400
|
+
"INSERT INTO api_endpoints VALUES (?, ?, ?)",
|
|
401
|
+
[(rel, ep[0], ep[1]) for rel, eps in self.file_endpoints.items() for ep in eps],
|
|
402
|
+
)
|
|
403
|
+
cur.executemany(
|
|
404
|
+
"INSERT INTO api_calls VALUES (?, ?, ?)",
|
|
405
|
+
[(rel, call[0], call[1]) for rel, calls in self.file_api_calls.items() for call in calls],
|
|
406
|
+
)
|
|
407
|
+
con.commit()
|
|
408
|
+
finally:
|
|
409
|
+
con.close()
|
|
209
410
|
os.replace(tmp_path, path)
|
|
210
411
|
except Exception:
|
|
211
412
|
try:
|
|
@@ -290,6 +491,7 @@ class CodeGraph:
|
|
|
290
491
|
|
|
291
492
|
if reindexed > 0 or deleted or force:
|
|
292
493
|
self._resolve_local_imports()
|
|
494
|
+
self._link_api_routes()
|
|
293
495
|
|
|
294
496
|
self.last_scanned = time.time()
|
|
295
497
|
if reindexed > 0 or deleted:
|
|
@@ -300,6 +502,8 @@ class CodeGraph:
|
|
|
300
502
|
"""Removes symbols, imports, and edges belonging to a file."""
|
|
301
503
|
sym_keys = self.file_symbols.pop(rel_path, [])
|
|
302
504
|
self.file_imports.pop(rel_path, None)
|
|
505
|
+
self.file_endpoints.pop(rel_path, None)
|
|
506
|
+
self.file_api_calls.pop(rel_path, None)
|
|
303
507
|
for k in sym_keys:
|
|
304
508
|
self.symbols.pop(k, None)
|
|
305
509
|
targets = self.edges.pop(k, set())
|
|
@@ -340,6 +544,7 @@ class CodeGraph:
|
|
|
340
544
|
ext = ext.lower()
|
|
341
545
|
|
|
342
546
|
if self._try_index_treesitter(content, rel_path, file_node, ext):
|
|
547
|
+
self._extract_api_routes_and_calls(content, rel_path)
|
|
343
548
|
return
|
|
344
549
|
|
|
345
550
|
if ext == ".py":
|
|
@@ -349,6 +554,143 @@ class CodeGraph:
|
|
|
349
554
|
elif ext in SUPPORTED_EXTS:
|
|
350
555
|
self._parse_braces(content, rel_path, file_node, ext)
|
|
351
556
|
|
|
557
|
+
self._extract_api_routes_and_calls(content, rel_path)
|
|
558
|
+
|
|
559
|
+
def _find_enclosing_symbol(self, rel_path: str, line_no: int) -> Optional[str]:
|
|
560
|
+
sym_keys = self.file_symbols.get(rel_path, [])
|
|
561
|
+
if not sym_keys:
|
|
562
|
+
return None
|
|
563
|
+
candidates = []
|
|
564
|
+
for sk in sym_keys:
|
|
565
|
+
s = self.symbols.get(sk)
|
|
566
|
+
if s and s.line_start <= line_no <= s.line_end:
|
|
567
|
+
candidates.append((sk, s))
|
|
568
|
+
if candidates:
|
|
569
|
+
candidates.sort(key=lambda item: (0 if item[1].kind in ("function", "method") else 1, item[1].line_end - item[1].line_start))
|
|
570
|
+
return candidates[0][0]
|
|
571
|
+
|
|
572
|
+
for sk in sym_keys:
|
|
573
|
+
s = self.symbols.get(sk)
|
|
574
|
+
if s and 0 <= s.line_start - line_no <= 4:
|
|
575
|
+
return sk
|
|
576
|
+
return None
|
|
577
|
+
|
|
578
|
+
def _extract_api_routes_and_calls(self, content: str, rel_path: str) -> None:
|
|
579
|
+
self.file_endpoints[rel_path] = []
|
|
580
|
+
self.file_api_calls[rel_path] = []
|
|
581
|
+
|
|
582
|
+
norm_rel = rel_path.replace("\\", "/")
|
|
583
|
+
|
|
584
|
+
class_prefix = ""
|
|
585
|
+
m_prefix = _CONTROLLER_PREFIX_RE.search(content)
|
|
586
|
+
if m_prefix:
|
|
587
|
+
class_prefix = m_prefix.group(1) or m_prefix.group(2) or ""
|
|
588
|
+
|
|
589
|
+
# 1. Next.js file-based API routes
|
|
590
|
+
m_app = _NEXT_APP_ROUTE_RE.match(norm_rel)
|
|
591
|
+
m_pages = _NEXT_PAGES_ROUTE_RE.match(norm_rel)
|
|
592
|
+
if m_app or m_pages:
|
|
593
|
+
route_raw = "/" + (m_app.group(1) if m_app else m_pages.group(1))
|
|
594
|
+
norm_route = _normalize_route_path(route_raw)
|
|
595
|
+
if norm_route:
|
|
596
|
+
sym_keys = self.file_symbols.get(rel_path, [])
|
|
597
|
+
matched_any = False
|
|
598
|
+
for sk in sym_keys:
|
|
599
|
+
s = self.symbols.get(sk)
|
|
600
|
+
if s and s.name.upper() in {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "HANDLER", "DEFAULT"}:
|
|
601
|
+
self.file_endpoints[rel_path].append((norm_route, sk))
|
|
602
|
+
matched_any = True
|
|
603
|
+
if not matched_any:
|
|
604
|
+
self.file_endpoints[rel_path].append((norm_route, None))
|
|
605
|
+
|
|
606
|
+
# 2. Backend route definitions
|
|
607
|
+
for rx in _BACKEND_ROUTE_PATTERNS:
|
|
608
|
+
for match in rx.finditer(content):
|
|
609
|
+
route_raw = match.group(1)
|
|
610
|
+
if class_prefix and not route_raw.startswith(class_prefix):
|
|
611
|
+
full_route = class_prefix.rstrip("/") + "/" + route_raw.lstrip("/")
|
|
612
|
+
else:
|
|
613
|
+
full_route = route_raw
|
|
614
|
+
norm_route = _normalize_route_path(full_route)
|
|
615
|
+
if not norm_route:
|
|
616
|
+
continue
|
|
617
|
+
line_no = content[:match.start()].count("\n") + 1
|
|
618
|
+
sym_key = self._find_enclosing_symbol(rel_path, line_no)
|
|
619
|
+
self.file_endpoints[rel_path].append((norm_route, sym_key))
|
|
620
|
+
|
|
621
|
+
# 3. Frontend API call sites
|
|
622
|
+
for rx in _FRONTEND_CALL_PATTERNS:
|
|
623
|
+
for match in rx.finditer(content):
|
|
624
|
+
route_raw = match.group(1)
|
|
625
|
+
norm_route = _normalize_route_path(route_raw)
|
|
626
|
+
if not norm_route:
|
|
627
|
+
continue
|
|
628
|
+
line_no = content[:match.start()].count("\n") + 1
|
|
629
|
+
sym_key = self._find_enclosing_symbol(rel_path, line_no)
|
|
630
|
+
self.file_api_calls[rel_path].append((norm_route, sym_key))
|
|
631
|
+
|
|
632
|
+
@staticmethod
|
|
633
|
+
def _route_matches(path: str, pattern_route: str) -> bool:
|
|
634
|
+
if not path or not pattern_route:
|
|
635
|
+
return False
|
|
636
|
+
if path == pattern_route:
|
|
637
|
+
return True
|
|
638
|
+
try:
|
|
639
|
+
pattern = "^" + re.escape(pattern_route).replace(r"\*", r"[^/]+") + "$"
|
|
640
|
+
if re.match(pattern, path):
|
|
641
|
+
return True
|
|
642
|
+
except re.error:
|
|
643
|
+
pass
|
|
644
|
+
try:
|
|
645
|
+
pattern2 = "^" + re.escape(path).replace(r"\*", r"[^/]+") + "$"
|
|
646
|
+
if re.match(pattern2, pattern_route):
|
|
647
|
+
return True
|
|
648
|
+
except re.error:
|
|
649
|
+
pass
|
|
650
|
+
return False
|
|
651
|
+
|
|
652
|
+
def _link_api_routes(self) -> None:
|
|
653
|
+
"""
|
|
654
|
+
Cross-boundary semantic linking between frontend client API calls
|
|
655
|
+
and backend route endpoints across languages and frameworks.
|
|
656
|
+
"""
|
|
657
|
+
try:
|
|
658
|
+
endpoint_map: Dict[str, List[Tuple[str, Optional[str]]]] = {}
|
|
659
|
+
for rel_path, endpoints in self.file_endpoints.items():
|
|
660
|
+
for norm_route, sym_key in endpoints:
|
|
661
|
+
if norm_route:
|
|
662
|
+
endpoint_map.setdefault(norm_route, []).append((rel_path, sym_key))
|
|
663
|
+
|
|
664
|
+
if not endpoint_map:
|
|
665
|
+
return
|
|
666
|
+
|
|
667
|
+
for caller_rel, calls in self.file_api_calls.items():
|
|
668
|
+
caller_file_node = f"file:{caller_rel}"
|
|
669
|
+
for norm_route, caller_sym in calls:
|
|
670
|
+
if not norm_route:
|
|
671
|
+
continue
|
|
672
|
+
matched_endpoints: List[Tuple[str, Optional[str]]] = []
|
|
673
|
+
if norm_route in endpoint_map:
|
|
674
|
+
matched_endpoints.extend(endpoint_map[norm_route])
|
|
675
|
+
|
|
676
|
+
for ep_route, eps in endpoint_map.items():
|
|
677
|
+
if ep_route != norm_route and ("*" in ep_route or "*" in norm_route):
|
|
678
|
+
if self._route_matches(norm_route, ep_route):
|
|
679
|
+
matched_endpoints.extend(eps)
|
|
680
|
+
|
|
681
|
+
for ep_rel, ep_sym in matched_endpoints:
|
|
682
|
+
if ep_rel == caller_rel:
|
|
683
|
+
continue
|
|
684
|
+
ep_file_node = f"file:{ep_rel}"
|
|
685
|
+
self.add_edge(caller_file_node, ep_file_node)
|
|
686
|
+
|
|
687
|
+
src = caller_sym or caller_file_node
|
|
688
|
+
dst = ep_sym or ep_file_node
|
|
689
|
+
if src != dst:
|
|
690
|
+
self.add_edge(src, dst)
|
|
691
|
+
except Exception:
|
|
692
|
+
pass
|
|
693
|
+
|
|
352
694
|
def _register_symbol(self, rel_path: str, file_node: str, symbol: CodeSymbol, sym_key: str):
|
|
353
695
|
self.symbols[sym_key] = symbol
|
|
354
696
|
if sym_key not in self.file_symbols[rel_path]:
|
|
@@ -878,6 +1220,11 @@ class CodeGraph:
|
|
|
878
1220
|
elif len(fallback_callers) <= 3:
|
|
879
1221
|
found.update(fallback_callers)
|
|
880
1222
|
|
|
1223
|
+
# Direct incoming edges (e.g. cross-boundary API caller symbols)
|
|
1224
|
+
for caller in self.rev_edges.get(tk, set()):
|
|
1225
|
+
if caller in self.symbols and caller != tk:
|
|
1226
|
+
found.add(caller)
|
|
1227
|
+
|
|
881
1228
|
found.discard(tk)
|
|
882
1229
|
return found
|
|
883
1230
|
|