Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(ingestion): support comments in tsconfig.json and jsconfig.json (#3067)

Rishabh Mishra68bff75fae56
diff --git a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
index 02338400c..4d9543fce 100644
--- a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
@@ -448,20 +448,59 @@ class TsconfigResolver:
@staticmethod
def _parse_json_lenient(config_path: Path) -> dict[str, Any] | None:
- """Parse JSON with trailing-comma tolerance (common in tsconfig)."""
+ """Parse JSON with comment and trailing-comma tolerance (common in tsconfig)."""
try:
text = config_path.read_text(encoding="utf-8", errors="ignore")
try:
data = json.loads(text)
except json.JSONDecodeError:
- cleaned = re.sub(r",\s*([}\]])", r"\1", text)
+ stripped = _strip_jsonc_comments(text)
+ cleaned = re.sub(r",\s*([}\]])", r"\1", stripped)
data = json.loads(cleaned)
return data if isinstance(data, dict) else None
except Exception as exc:
- log.debug("tsconfig_parse_failed", path=str(config_path), error=str(exc))
+ log.warning("tsconfig_parse_failed", path=str(config_path), error=str(exc))
return None
+def _strip_jsonc_comments(text: str) -> str:
+ """Strip // and /* */ comments from JSONC text while preserving string literals."""
+ out: list[str] = []
+ i = 0
+ n = len(text)
+ in_string = False
+
+ while i < n:
+ c = text[i]
+ if in_string:
+ out.append(c)
+ if c == "\\":
+ if i + 1 < n:
+ i += 1
+ out.append(text[i])
+ elif c == '"':
+ in_string = False
+ i += 1
+ else:
+ if c == '"':
+ in_string = True
+ out.append(c)
+ i += 1
+ elif c == "/" and i + 1 < n and text[i + 1] == "/":
+ i += 2
+ while i < n and text[i] != "\n":
+ i += 1
+ elif c == "/" and i + 1 < n and text[i + 1] == "*":
+ i += 2
+ while i + 1 < n and not (text[i] == "*" and text[i + 1] == "/"):
+ i += 1
+ i += 2
+ else:
+ out.append(c)
+ i += 1
+ return "".join(out)
+
+
def wire_tsconfig_resolver(
graph_builder: Any,
repo_path: str | Path,
diff --git a/tests/unit/ingestion/test_tsconfig_cli_repro.py b/tests/unit/ingestion/test_tsconfig_cli_repro.py
index 82a442330..bcf69fe52 100644
--- a/tests/unit/ingestion/test_tsconfig_cli_repro.py
+++ b/tests/unit/ingestion/test_tsconfig_cli_repro.py
@@ -94,3 +94,90 @@ def test_tsconfig_alias_cli_rebuild(tmp_path: Path) -> None:
# 4. Assert SensorProvider is reached
assert graph_builder.graph().has_edge(layout_path, sensor_path)
assert graph_builder.graph().in_degree(sensor_path) > 0
+
+
+def test_tsconfig_with_comments_alias_cli_rebuild(tmp_path: Path) -> None:
+ # 1. Setup commented tsconfig.json (Issue #3058)
+ tsconfig_file = tmp_path / "tsconfig.json"
+ tsconfig_file.write_text(
+ """\
+ {
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ // aliases for app code
+ "@/*": ["./*"]
+ }
+ }
+ }
+ """,
+ encoding="utf-8",
+ )
+
+ # 2. Setup mock files: app/page.tsx -> components/ui/button.tsx
+ page_path = "app/page.tsx"
+ button_path = "components/ui/button.tsx"
+
+ page_import = Import(
+ raw_statement="import { Button } from '@/components/ui/button'",
+ module_path="@/components/ui/button",
+ imported_names=["Button"],
+ is_relative=False,
+ resolved_file=None,
+ )
+ page_parsed = ParsedFile(
+ file_info=FileInfo(
+ path=page_path,
+ abs_path=str(tmp_path / page_path),
+ language="typescript",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=True,
+ ),
+ symbols=[],
+ imports=[page_import],
+ exports=[],
+ docstring=None,
+ parse_errors=[],
+ content_hash="",
+ )
+
+ button_parsed = ParsedFile(
+ file_info=FileInfo(
+ path=button_path,
+ abs_path=str(tmp_path / button_path),
+ language="typescript",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ ),
+ symbols=[],
+ imports=[],
+ exports=[],
+ docstring=None,
+ parse_errors=[],
+ content_hash="",
+ )
+
+ # 3. Build graph
+ graph_builder = GraphBuilder(repo_path=tmp_path)
+ graph_builder.add_file(page_parsed)
+ graph_builder.add_file(button_parsed)
+
+ wire_tsconfig_resolver(
+ graph_builder, tmp_path, include_submodules=False, include_nested_repos=False
+ )
+ graph_builder.build()
+
+ # 4. Assert button is reached
+ assert graph_builder.graph().has_edge(page_path, button_path)
+ assert graph_builder.graph().in_degree(button_path) > 0
+
diff --git a/tests/unit/ingestion/test_tsconfig_resolver.py b/tests/unit/ingestion/test_tsconfig_resolver.py
index e8ec41f20..a3cfd7121 100644
--- a/tests/unit/ingestion/test_tsconfig_resolver.py
+++ b/tests/unit/ingestion/test_tsconfig_resolver.py
@@ -558,3 +558,62 @@ class TestMtsCtsAliasResolution:
resolver = self._resolver(tmp_path, {"src/pkg/index.mts"})
result = resolver.resolve("@/pkg", _importer(tmp_path, "src/app.ts"))
assert result == "src/pkg/index.mts"
+
+
+# ---------------------------------------------------------------------------
+# Commented tsconfig.json (JSONC) support
+# ---------------------------------------------------------------------------
+
+
+class TestCommentedTsconfig:
+ def test_single_line_and_block_comments_in_tsconfig(self, tmp_path: Path) -> None:
+ """TypeScript allows // and /* */ comments in tsconfig.json."""
+ config_content = """\
+ {
+ // Top-level comment
+ "compilerOptions": {
+ "baseUrl": ".",
+ /* Multi-line
+ block comment */
+ "paths": {
+ // aliases for app code
+ "@/*": ["./src/*"],
+ },
+ },
+ }
+ """
+ tsconfig = tmp_path / "tsconfig.json"
+ tsconfig.write_text(config_content, encoding="utf-8")
+
+ resolver = TsconfigResolver(
+ repo_path=tmp_path,
+ path_set={"src/components/ui/button.tsx", "src/app/page.tsx"},
+ )
+ result = resolver.resolve("@/components/ui/button", _importer(tmp_path, "src/app/page.tsx"))
+ assert result == "src/components/ui/button.tsx"
+
+ def test_wildcards_and_string_literals_with_slashes_preserved(self, tmp_path: Path) -> None:
+ """String literals with /* or // (like @/* or http://) must not be corrupted."""
+ config_content = """\
+ {
+ "$schema": "https://json.schemastore.org/tsconfig",
+ "compilerOptions": {
+ "baseUrl": ".",
+ "paths": {
+ "@/*": ["./src/*"],
+ "lib/*": ["./packages/*"], // inline comment
+ }
+ }
+ }
+ """
+ tsconfig = tmp_path / "tsconfig.json"
+ tsconfig.write_text(config_content, encoding="utf-8")
+
+ data = TsconfigResolver._parse_json_lenient(tsconfig)
+ assert data is not None
+ assert data["$schema"] == "https://json.schemastore.org/tsconfig"
+ assert data["compilerOptions"]["paths"] == {
+ "@/*": ["./src/*"],
+ "lib/*": ["./packages/*"],
+ }
+