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): classify a TS/JS binding by its value, not only its name (#1469)

Raghav Chamadiya0aa4b1d7ff81
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
index e7a28e13f..c84206de2 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
@@ -264,6 +264,72 @@ def declarator_value_is_module_ref(declarator: Node, src: str) -> bool:
return fn.type == "import" or (fn.type == "identifier" and node_text(fn, src) == "require")
+_CALLABLE_VALUE_NODE_TYPES = frozenset({"arrow_function", "function_expression"})
+
+# Wrappers whose RESULT is callable, keyed on the last segment of the callee
+# (``React.forwardRef`` and a bare imported ``forwardRef`` both match).
+#
+# A structural rule cannot do this job, and trying one is how this list was
+# arrived at. "The call receives a function" looks like it separates
+# ``forwardRef(fn)`` from ``z.object({…})``, but measured against real
+# TypeScript it also promotes ``[...a, ...b].filter(key => …)`` and
+# ``z.preprocess(val => …, schema)`` — both hand over a function and both bind
+# data. Whether a call returns something callable is a fact about the callee,
+# not about its arguments, so the only honest options are to name the callees
+# or to say nothing.
+#
+# Ceiling: incomplete by construction, and deliberately biased. An unlisted
+# wrapper falls back to the naming rule and is classified as data, which is
+# the pre-existing behaviour; nothing is newly mislabelled by an omission.
+# Upgrade path is to add names here as they show up.
+_CALLABLE_RETURNING_CALLEES = frozenset(
+ {
+ # React and friends: wrappers that return a component.
+ "forwardRef",
+ "memo",
+ "lazy",
+ "observer",
+ "useCallback",
+ # Firebase Cloud Functions: handler factories.
+ "onCall",
+ "onRequest",
+ }
+)
+
+
+def declarator_binds_callable(declarator: Node, src: str) -> str | None:
+ """Kind for a ``const x = …`` that binds something callable.
+
+ Returns ``"class"``, ``"function"``, or None to leave the naming-based
+ constant/variable rule in place. Only meaningful for TS/JS module-anchored
+ declarators, and only after the module-reference guard has run.
+
+ Two cases. A value that literally *is* a function or a class
+ (``const f = function(){}``, ``const C = class {}``, a parenthesised
+ arrow) is unambiguous. A call is not: ``const C = forwardRef(fn)`` binds a
+ component and ``const schema = z.object({…})`` binds data, and only the
+ callee says which. Hence ``_CALLABLE_RETURNING_CALLEES``.
+ """
+ value = declarator.child_by_field_name("value")
+ while value is not None and value.type in _VALUE_WRAPPER_NODE_TYPES:
+ value = value.named_children[0] if value.named_children else None
+ if value is None:
+ return None
+
+ if value.type == "class":
+ return "class"
+ if value.type in _CALLABLE_VALUE_NODE_TYPES:
+ return "function"
+ if value.type != "call_expression":
+ return None
+
+ fn = value.child_by_field_name("function")
+ if fn is None:
+ return None
+ callee = node_text(fn, src).rsplit(".", 1)[-1].strip()
+ return "function" if callee in _CALLABLE_RETURNING_CALLEES else None
+
+
def cjs_statement_is_reexport(stmt_node: Node, src: str) -> bool:
"""True when a CJS require statement re-exports through ``module.exports``.
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 698026381..560fa3a29 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -43,7 +43,10 @@ from .extractors import (
refine_kotlin_class_kind,
)
from .extractors.bindings.python import expand_bare_relative_imports
-from .extractors.bindings.ts_js import declarator_value_is_module_ref
+from .extractors.bindings.ts_js import (
+ declarator_binds_callable,
+ declarator_value_is_module_ref,
+)
from .extractors.synthetic_symbols import extract_synthetic_symbols
from .extractors.visibility import (
refine_cpp_visibility,
@@ -531,7 +534,17 @@ class ASTParser:
def_node, src
):
continue
- kind = "constant" if name.isupper() else "variable"
+ # A declarator whose value is structurally callable is not
+ # data, whatever its name looks like: `const C =
+ # forwardRef(fn)` and `const f = function(){}` are a component
+ # and a function. Naming decides only for the rest, which is
+ # what it was ever able to answer.
+ callable_kind = (
+ declarator_binds_callable(def_node, src)
+ if file_info.language in _TS_JS_LANGUAGES
+ else None
+ )
+ kind = callable_kind or ("constant" if name.isupper() else "variable")
# Params signature text
params_text = _node_text(params_nodes[0], src) if params_nodes else ""
diff --git a/tests/unit/ingestion/parser/test_typescript.py b/tests/unit/ingestion/parser/test_typescript.py
index 6bccaf89f..e9012d448 100644
--- a/tests/unit/ingestion/parser/test_typescript.py
+++ b/tests/unit/ingestion/parser/test_typescript.py
@@ -526,6 +526,86 @@ function outer() {
assert self._names(parser, "src/accordion.ts") == self._names(parser)
+class TestTypeScriptCallBindingKinds:
+ """A call binding is classified by its value, not by its name.
+
+ ``constant``/``variable`` is a naming rule, and it is the wrong answer for
+ a component or a handler: kind drives page-selection weight (0.3 for a
+ variable against 1.0 for a function), Key Concepts eligibility and symbol
+ ranking, so a forwardRef component indexed as data gets scored as data.
+
+ A value that literally is a function or a class settles itself. A call
+ does not, and only the callee settles it: whether a call returns something
+ callable is a fact about the callee, not about its arguments.
+ """
+
+ SOURCE = b"""
+const AccordionItem = React.forwardRef((props, ref) => null);
+const Memoized = React.memo(function Inner() { return null; });
+const cb = useCallback(() => {}, []);
+const KlassExpr = class Foo {};
+const fnExpr = function named() { return 1; };
+const parenArrow = ((x) => x);
+export const myFunction = onCall(async (req) => 1);
+export const schema = z.object({ a: 1 });
+export const Button = styled.button`color: red;`;
+const Ctx = createContext(null);
+const KEYS = [...a, ...b].filter((key) => key !== "x");
+const prepared = z.preprocess((val) => val, rawSchema);
+const MAX_ITEMS = 100;
+const apiBase = "https://api.example.com";
+"""
+
+ def _kinds(self, parser: ASTParser) -> dict[str, str]:
+ fi = _make_file_info("src/kinds.tsx", "typescript")
+ return {s.name: s.kind for s in parser.parse_file(fi, self.SOURCE).symbols}
+
+ def test_hoc_wrapped_component_is_a_function(self, parser: ASTParser) -> None:
+ kinds = self._kinds(parser)
+ assert kinds["AccordionItem"] == "function"
+ assert kinds["Memoized"] == "function"
+
+ def test_handler_factory_binding_is_a_function(self, parser: ASTParser) -> None:
+ kinds = self._kinds(parser)
+ assert kinds["myFunction"] == "function"
+ assert kinds["cb"] == "function"
+
+ def test_class_expression_is_a_class(self, parser: ASTParser) -> None:
+ assert self._kinds(parser)["KlassExpr"] == "class"
+
+ def test_function_expression_and_wrapped_arrow_are_functions(self, parser: ASTParser) -> None:
+ kinds = self._kinds(parser)
+ assert kinds["fnExpr"] == "function"
+ # A parenthesised arrow misses the bare-arrow pattern, so without the
+ # value check it would land as data purely for having brackets.
+ assert kinds["parenArrow"] == "function"
+
+ def test_value_shaped_factories_are_not_functions(self, parser: ASTParser) -> None:
+ kinds = self._kinds(parser)
+ assert kinds["schema"] == "variable"
+ assert kinds["Ctx"] == "variable"
+ # Known ceiling: an unlisted callee falls back to the naming rule, so
+ # a tagged-template component stays data.
+ assert kinds["Button"] == "variable"
+
+ def test_a_call_taking_a_function_can_still_bind_data(self, parser: ASTParser) -> None:
+ """Why the callee decides and the arguments do not.
+
+ Both of these hand a function to the call and both bind data. A rule
+ keyed on "the call receives a function" promotes them, which is how
+ this one was corrected — these two shapes were found mislabelled in a
+ real TypeScript tree.
+ """
+ kinds = self._kinds(parser)
+ assert kinds["KEYS"] == "constant"
+ assert kinds["prepared"] == "variable"
+
+ def test_naming_rule_still_decides_the_rest(self, parser: ASTParser) -> None:
+ kinds = self._kinds(parser)
+ assert kinds["MAX_ITEMS"] == "constant"
+ assert kinds["apiBase"] == "variable"
+
+
class TestJavaScriptCallExpressionBindings:
"""JavaScript was strictly worse than TypeScript: its allowlist also
omitted ``member_expression``, so even a plain alias yielded no symbol."""