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.

feat(salesforce): index Aura bundles and link markup, controllers, helpers and child components (#4405)

Raghav Chamadiya64879ed9408b
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 6debf88c4..e625c67f5 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -928,6 +928,21 @@ separate node-path forms, so the pair fails), and a bare call to a function name
position for the GDScript 3 declaration forms. Error recovery keeps both to the
enclosing statement.
+### Salesforce Aura
+
+Aura markup is routed to the `aura` passthrough tag by its folder, a markup suffix
+directly inside `aura/<bundle>/`, because `.app` and `.tokens` are not Aura's alone.
+Bundle JavaScript stays `javascript`; a synthetic-symbol provider makes each
+`key: function` of a `<bundle>Controller.js`, `Helper.js` or `Renderer.js` object
+literal a function symbol. `framework_edges/aura.py` then binds `controller=` to the
+Apex class, `get("c.m")` to the Apex method (through `extends` when the bundle
+declares no controller), `{!c.h}` and other `"c.h"` literals to controller functions,
+`helper.x(` to helper functions (both inherited through `extends`), and own-namespace
+tags, `extends`, `implements` and event types to the Aura bundle, or the LWC bundle of
+that name. `$A.createComponent(s)` string literals become `dynamic_uses` edges. Aura
+names match by exact case, Apex names fold case, and a name with two candidates binds
+to neither.
+
### VB.NET
VB.NET shares the .NET project graph with C# rather than resolving on file stems.
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 8492f2f4f..26ec48bc2 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -211,6 +211,9 @@ invoked by name.
Lambda handler edges.
- Godot resource files (`.tscn`, `.tres`, `.escn`, `project.godot`,
`plugin.cfg`) carry no symbols but are read for the script paths they name.
+- Salesforce Aura markup (`.cmp`, `.app`, `.evt`, `.intf`, `.design`, `.tokens` in
+ an `aura/<bundle>/` folder) carries no symbols but is read for the Apex
+ controller, controller functions, child components and events it names.
## Code-health coverage
diff --git a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
index f47f3ae0c..1c8203ad1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
@@ -33,6 +33,8 @@ from __future__ import annotations
import re
from pathlib import PurePosixPath
+from repowise.core.ingestion.languages.specs.aura import aura_bundle
+
# Findings at or above this confidence, with no risk factors, are presented as
# deletion-ready ("safe to delete"). Anything below — or anything carrying a
# risk factor — is a review candidate. Kept here as the single source of truth
@@ -152,6 +154,7 @@ _FACTOR_BLURB: dict[str, str] = {
"database": "database/schema",
"script": "script/task",
"asset": "runtime-loaded web asset",
+ "aura": "Salesforce Aura bundle",
}
_SPLIT_RE = re.compile(r"[._\-]+")
@@ -192,6 +195,13 @@ def path_risk_factors(file_path: str) -> tuple[str, ...]:
if tag:
factors.add(tag)
+ # A file of a Salesforce Aura bundle (directly inside `aura/<bundle>/`):
+ # the Lightning runtime loads the whole bundle and also reads its
+ # JavaScript for `$Label` and component references, so a function nothing
+ # calls can still be load-bearing.
+ if aura_bundle(norm) is not None:
+ factors.add("aura")
+
return tuple(sorted(factors))
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
index d48f39821..9cb046223 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
@@ -25,6 +25,7 @@ from collections.abc import Callable
from typing import TYPE_CHECKING
from ...models import FileInfo, Symbol
+from .aura_bundle_js import aura_bundle_js_symbols
from .cpp_macros import cpp_macro_synthetic_symbols
from .csharp_extension_blocks import csharp_extension_block_symbols
from .csharp_mvvm import csharp_synthetic_symbols
@@ -59,6 +60,9 @@ _SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {
# A .razor/.cshtml file *is* the component: the name comes from the
# filename (PascalCase by convention), same as Svelte/Vue.
"razor": [sfc_component_symbols],
+ # Aura bundle JS is an object literal of handlers; path-gated to
+ # aura/<b>/<b>{Controller,Helper,Renderer}.js inside the provider.
+ "javascript": [aura_bundle_js_symbols],
}
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/aura_bundle_js.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/aura_bundle_js.py
new file mode 100644
index 000000000..7caa9e198
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/aura_bundle_js.py
@@ -0,0 +1,93 @@
+"""The handler functions of an Aura bundle's controller, helper and renderer.
+
+An Aura bundle's JavaScript is one parenthesised object literal::
+
+ ({
+ doInit : function(component, event, helper) { ... },
+ save : function(component, event, helper) { ... },
+ })
+
+The JavaScript query has no symbol for a ``key: function`` pair (a general
+object literal's values are data, not declarations), so every handler in the
+file is invisible: markup's ``{!c.doInit}``, a controller's ``helper.load(...)``
+and a ``component.get("c.save")`` call have no symbol to land on or start
+from. This provider mints one function symbol per function-valued key of that
+top-level object, and only in files named ``<bundle>Controller.js``,
+``<bundle>Helper.js`` or ``<bundle>Renderer.js`` inside ``aura/<bundle>/``.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ...languages.specs.aura import aura_bundle
+from ...models import FileInfo, Symbol
+from ..helpers import node_text
+from ._helpers import build_synthetic_symbol
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+AURA_JS_ROLES = ("Controller", "Helper", "Renderer")
+_FUNCTION_VALUES = frozenset({"function_expression", "function", "arrow_function"})
+
+
+def aura_js_role(path: str) -> str | None:
+ """``Controller`` / ``Helper`` / ``Renderer`` for an Aura bundle JS file, else None."""
+ bundle = aura_bundle(path)
+ if bundle is None:
+ return None
+ _bundle_dir, name = bundle
+ # The platform pairs these files case-insensitively (NPSP ships
+ # HH_AutoComplete/HH_AutocompleteHelper.js).
+ base = path.rsplit("/", 1)[-1].lower()
+ for role in AURA_JS_ROLES:
+ if base == f"{name}{role}.js".lower():
+ return role
+ return None
+
+
+def _bundle_object(root: Node) -> Node | None:
+ """The object literal of a ``({ ... })`` program, else None."""
+ for stmt in root.named_children:
+ if stmt.type != "expression_statement" or not stmt.named_children:
+ continue
+ expr = stmt.named_children[0]
+ while expr.type == "parenthesized_expression" and expr.named_children:
+ expr = expr.named_children[0]
+ if expr.type == "object":
+ return expr
+ return None
+
+
+def aura_bundle_js_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:
+ """One function symbol per handler of an Aura controller, helper or renderer."""
+ if file_info.language != "javascript" or aura_js_role(file_info.path) is None:
+ return []
+ obj = _bundle_object(root)
+ if obj is None:
+ return []
+ out: list[Symbol] = []
+ for pair in obj.named_children:
+ if pair.type != "pair":
+ continue
+ key = pair.child_by_field_name("key")
+ value = pair.child_by_field_name("value")
+ if key is None or value is None or value.type not in _FUNCTION_VALUES:
+ continue
+ name = node_text(key, src).strip().strip("'\"")
+ if not name.isidentifier():
+ continue
+ params = value.child_by_field_name("parameters")
+ out.append(
+ build_synthetic_symbol(
+ name=name,
+ kind="function",
+ signature=f"{name}: function{node_text(params, src) if params else '()'}",
+ start_line=pair.start_point[0] + 1,
+ end_line=pair.end_point[0] + 1,
+ file_info=file_info,
+ parent_name=None,
+ )
+ )
+ return out
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
index 47f252d46..cc908f099 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py
@@ -24,6 +24,7 @@ from . import (
android_manifest,
angular,
aspnet,
+ aura,
aws_lambda,
django,
dotnet_discovery,
@@ -97,6 +98,9 @@ _HANDLERS: list[FrameworkHandler] = [
*rust.HANDLERS,
*typo3.HANDLERS,
*aws_lambda.HANDLERS,
+ # Salesforce Aura bundles: markup names its Apex controller, controller
+ # functions and child components; nothing is an import.
+ *aura.HANDLERS,
]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/aura.py b/packages/core/src/repowise/core/ingestion/framework_edges/aura.py
new file mode 100644
index 000000000..e4759aebb
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/aura.py
@@ -0,0 +1,611 @@
+"""Salesforce Aura bundle edges.
+
+An Aura component is a directory ``aura/<name>/``: markup (``<name>.cmp``,
+``.app``, ``.evt``, ``.intf``, ``.design``, ``.tokens``) plus
+``<name>Controller.js`` / ``Helper.js`` / ``Renderer.js``. Nothing in it is an
+import. The platform wires the pieces by name, and this handler reads those
+names:
+
+* ``controller="Cls"`` on ``aura:component`` / ``aura:application`` -> the Apex
+ class file.
+* ``component.get("c.m")`` (any receiver) in bundle JS -> Apex method ``m`` of
+ the bundle's controller class, found through ``extends="c:Base"`` when the
+ bundle declares none. When the class has no ``m`` but the bundle's
+ Controller.js does, it is a client-side action and binds there instead;
+ ``getReference("c.m")`` always does.
+* ``{!c.h}`` in markup -> function ``h`` of the bundle's Controller.js.
+* ``helper.x(`` in bundle JS, and ``this.x(`` in Helper.js -> function ``x`` of the
+ bundle's Helper.js, inherited through ``extends`` like the controller.
+* ``<c:X>``, ``extends="c:X"``, ``implements="c:X"`` and the event ``type`` /
+ ``event`` of ``aura:registerEvent`` / ``aura:handler`` -> bundle ``X``,
+ Aura first, else the LWC bundle's ``X.js``. Only the own namespaces (``c``
+ and the sfdx-project.json ``namespace``) are followed; ``force:``,
+ ``lightning:``, ``flexipage:`` and the rest are the platform's.
+* ``$A.createComponent("c:X", ...)`` and the ``["c:X", {...}]`` entries of
+ ``$A.createComponents`` -> bundle ``X`` as a ``dynamic_uses`` edge, string
+ literals only. A name built at run time is never guessed.
+
+Aura names match by exact case (every reference in the validation corpora
+does); Apex names fold case, as the platform does. A name with two candidate
+bundles or classes binds to neither.
+
+Entry points: an ``.app`` and a component implementing a platform placement
+interface (App Builder, tabs, quick actions, communities, URL addressable)
+are placed from outside the source tree, so the markup node is marked
+``is_entry_point``; a Renderer's ``render`` / ``rerender`` / ``afterRender`` /
+``unrender`` overrides are bound from the bundle's markup because the
+framework calls them.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING, Any
+
+from ..extractors.synthetic_symbols.aura_bundle_js import aura_js_role
+from ..languages.specs.aura import aura_bundle
+from ..type_names import bare_type_name, type_qualifier
+from .base import (
+ DetectionContext,
+ FrameworkHandler,
+ _add_edge_if_new,
+ add_symbol_edge,
+ source_text,
+)
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers import ResolverContext
+
+# The bundle's defining markup, in the order the platform allows one of them.
+_MAIN_MARKUP = (".cmp", ".app", ".evt", ".intf")
+
+_XML_COMMENT_RE = re.compile(r"<!--.*?(?:-->|\Z)", re.DOTALL)
+# A JS comment, or a string literal kept as-is so a `//` inside one is not a comment.
+_JS_COMMENT_OR_STRING_RE = re.compile(
+ r"//[^\n]*|/\*.*?(?:\*/|\Z)|'(?:[^'\\\n]|\\.)*'|\"(?:[^\"\\\n]|\\.)*\"|`(?:[^`\\]|\\.)*`",
+ re.DOTALL,
+)
+_TAG_RE = re.compile(r"""<([A-Za-z]\w*):([A-Za-z_]\w*)((?:[^>"']|"[^"]*"|'[^']*')*)>""")
+_ATTR_RE = re.compile(r"""([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')""")
+_QUALIFIED_RE = re.compile(r"^\s*(\w+):(\w+)\s*$")
+# Formatters reflow `{!c.h}` across lines and append a `;` (NebulaLogger ships one).
+# A handler inside a larger expression (`{!v.x ? c.a : c.b}`) is not read;
+# none of the validation corpora writes one.
+_MARKUP_HANDLER_RE = re.compile(r"\{\s*[!#]\s*c\.([A-Za-z_]\w*)\s*;?\s*\}")
+# A "c.x" string literal; group 1 is set when it is the argument of `.get(`.
+_ACTION_RE = re.compile(r"""(\.get\(\s*)?(["'])c\.([A-Za-z_]\w*)\2""")
+_HELPER_CALL_RE = re.compile(r"(?<![\w.$])helper\s*\.\s*([A-Za-z_$][\w$]*)\s*\(")
+# Inside a helper, `this` is the (inherited) helper object. A `this.x(` in a
+# nested non-arrow callback is read the same way; its target must still be a
+# helper function, which bounds the cost.
+_THIS_CALL_RE = re.compile(r"(?<![\w.$])this\s*\.\s*([A-Za-z_$][\w$]*)\s*\(")
+_CREATE_ONE_RE = re.compile(r"""\$A\s*\.\s*createComponent\s*\(\s*(["'`])(\w+):(\w+)\1""")
+_CREATE_MANY_RE = re.compile(r"\$A\s*\.\s*createComponents\s*\(")
+_CREATE_MANY_ITEM_RE = re.compile(r"""\[\s*(["'`])(\w+):(\w+)\1""")
+
+# Interfaces that let an admin place the component without any source naming
+# it: App Builder pages, tabs, quick actions, overrides, communities, flows
+# and URL navigation.
+_ENTRY_INTERFACE_PREFIXES = ("flexipage:", "forcecommunity:", "lightningsnapin:")
+_ENTRY_INTERFACES = frozenset(
+ {
+ "force:apphostable",
+ "force:lightningquickaction",
+ "force:lightningquickactionwithoutheader",
+ "lightning:actionoverride",
+ "lightning:isurladdressable",
+ "lightning:availableforflowscreens",
+ "lightning:availableforflowactions",
+ "lightning:hometemplate",
+ "lightning:apphometemplate",
+ "lightning:recordhometemplate",
+ "lightning:utilityitem",
+ "lightning:backgroundutilityitem",
+ "clients:availableformailappapppage",
+ }
+)
+_RENDERER_OVERRIDES = ("render", "rerender", "afterRender", "unrender")
+# Controller functions a platform interface obliges the component to define:
+# the flow runtime runs a local action's `invoke`.
+_PLATFORM_INTERFACE_METHODS = {"lightning:availableforflowactions": ("invoke",)}
+_EXTENDS_DEPTH = 6
+
+
+@dataclass
+class _Bundle:
+ name: str
+ markup: dict[str, str] = field(default_factory=dict) # suffix -> path
+ js: dict[str, str] = field(default_factory=dict) # role -> path
+
+ @property
+ def main(self) -> str | None:
+ return next((self.markup[s] for s in _MAIN_MARKUP if s in self.markup), None)
+
+
+def _mask_xml(text: str) -> str:
+ return _XML_COMMENT_RE.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), text)
+
+
+def _mask_js_comments(text: str) -> str:
+ def blank(m: re.Match[str]) -> str:
+ s = m.group(0)
+ return s if s[0] in "'\"`" else re.sub(r"[^\n]", " ", s)
+
+ return _JS_COMMENT_OR_STRING_RE.sub(blank, text)
+
+
+def _attrs(blob: str) -> dict[str, str]:
+ return {m.group(1): m.group(2) if m.group(2) is not None else m.group(3) for m in _ATTR_RE.finditer(blob)}
+
+
+def _line_of(text: str, offset: int) -> int:
+ return text.count("\n", 0, offset) + 1
+
+
+def _call_span_end(text: str, open_paren: int) -> int:
+ """Offset just past the ``)`` closing the call whose ``(`` is at *open_paren*."""
+ depth = 0
+ i = open_paren
+ n = len(text)
+ while i < n:
+ ch = text[i]
+ if ch in "'\"`":
+ m = _JS_COMMENT_OR_STRING_RE.match(text, i)
+ i = m.end() if m else i + 1
+ continue
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if depth == 0:
+ return i + 1
+ i += 1
+ return n
+
+
+def _own_namespaces(parsed_files: dict[str, Any], source_map: dict[str, bytes]) -> frozenset[str]:
+ """``c`` plus every ``namespace`` an sfdx-project.json declares, lowercased."""
+ names = {"c"}
+ for path, parsed in parsed_files.items():
+ if PurePosixPath(path).name != "sfdx-project.json":
+ continue
+ try:
+ ns = json.loads(source_text(path, parsed, source_map, "utf-8-sig")).get("namespace")
+ except (ValueError, AttributeError):
+ continue
+ if isinstance(ns, str) and ns.strip():
+ names.add(ns.strip().lower())
+ return frozenset(names)
+
+
+class _AuraIndex:
+ def __init__(self, graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext) -> None:
+ self.graph = graph
+ self.parsed_files = parsed_files
+ self.source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}
+ self.own_ns = _own_namespaces(parsed_files, self.source_map)
+ self.bundles: dict[str, _Bundle] = {} # bundle dir -> bundle
+ self.lwc_by_name: dict[str, list[str]] = {}
+ self.apex_by_name: dict[str, list[str]] = {}
+ for path in sorted(parsed_files):
+ self._add_file(path, parsed_files[path].file_info.language)
+ self.aura_by_name: dict[str, list[str]] = {}
+ for bdir, b in self.bundles.items():
+ if b.main is not None:
+ self.aura_by_name.setdefault(b.name, []).append(bdir)
+ self._root_attrs: dict[str, dict[str, str]] = {}
+ self._functions: dict[str, dict[str, str]] = {}
+
+ def _add_file(self, path: str, lang: str) -> None:
+ if lang == "apex" and path.endswith(".cls"):
+ # Apex names fold case and a class file is named after its class.
+ # Deliberately local: the case-insensitive Apex class index the
+ # Apex resolution pass builds should replace this once it lands.
+ self.apex_by_name.setdefault(PurePosixPath(path).stem.lower(), []).append(path)
+ return
+ bundle = aura_bundle(path)
+ if bundle is None:
+ parts = PurePosixPath(path).parts
+ # LWC main module: lwc/<name>/<name>.js. Only the location is read
+ # here; the LWC surface itself is not this module's.
+ if lang == "javascript" and len(parts) >= 3 and parts[-3] == "lwc" and parts[-1] == f"{parts[-2]}.js":
+ self.lwc_by_name.setdefault(parts[-2], []).append(path)
+ return
+ bdir, name = bundle
+ if lang == "aura":
+ self.bundles.setdefault(bdir, _Bundle(name)).markup[PurePosixPath(path).suffix.lower()] = path
+ elif lang == "javascript" and (role := aura_js_role(path)) is not None:
+ self.bundles.setdefault(bdir, _Bundle(name)).js[role] = path
+
+ # -- lookups -----------------------------------------------------------
+
+ def text(self, path: str) -> str:
+ return source_text(path, self.parsed_files[path], self.source_map, "utf-8-sig")
+
+ def root_attrs(self, bdir: str) -> dict[str, str]:
+ """Attributes of the bundle's root ``<aura:*>`` tag."""
+ if bdir not in self._root_attrs:
+ attrs: dict[str, str] = {}
+ main = self.bundles[bdir].main
+ if main is not None:
+ for m in _TAG_RE.finditer(_mask_xml(self.text(main))):
+ if m.group(1) == "aura" and m.group(2) in (
+ "component", "application", "interface", "event"
+ ):
+ attrs = _attrs(m.group(3))
+ break
+ self._root_attrs[bdir] = attrs
+ return self._root_attrs[bdir]
+
+ def own_name(self, qualified: str) -> str | None:
+ """``X`` for an own-namespace ``ns:X``, else None."""
+ m = _QUALIFIED_RE.match(qualified)
+ if m is None or m.group(1).lower() not in self.own_ns:
+ return None
+ return m.group(2)
+
+ def bundle_target(self, name: str, src: str) -> str | None:
+ """The file a ``c:name`` reference from *src* lands on: Aura main markup, else LWC main js."""
+ mains = [m for d in self.aura_by_name.get(name, []) if (m := self.bundles[d].main)]
+ return _nearest(src, mains + self.lwc_by_name.get(name, []))
+
+ def apex_class(self, written: str, src: str) -> str | None:
+ """The Apex file of ``controller="[ns.]Cls"`` written in *src*, own namespace only."""
+ head, tail = type_qualifier(written), bare_type_name(written)
+ if head and head.lower() not in self.own_ns:
+ return None
+ return _nearest(src, self.apex_by_name.get(tail.lower(), []))
+
+ def aura_bundle_dir(self, name: str, src: str) -> str | None:
+ """The bundle dir an own-namespace ``extends``/``implements`` name from *src* means."""
+ return _nearest(src, self.aura_by_name.get(name, []))
+
+ def chain(self, bdir: str) -> list[str]:
+ """The bundle and the bundles it ``extends``, nearest first.
+
+ A sub-component inherits its parent's Apex controller, client-side
+ controller functions and helper, so a name the bundle does not declare
+ is looked up the chain. Stops at a platform base, an ambiguous name or
+ a cycle.
+ """
+ out = [bdir]
+ while len(out) < _EXTENDS_DEPTH:
+ base = self.own_name(self.root_attrs(out[-1]).get("extends", ""))
+ parent = self.aura_bundle_dir(base, out[-1]) if base else None
+ if parent is None or parent in out:
+ break
+ out.append(parent)
+ return out
+
+ def controller_class(self, bdir: str) -> tuple[str, str] | None:
+ """``(written name, class file)`` of the bundle's Apex controller, via ``extends``."""
+ for b in self.chain(bdir):
+ written = self.root_attrs(b).get("controller")
+ if written:
+ cls_file = self.apex_class(written, b)
+ return (written.strip(), cls_file) if cls_file else None
+ return None
+
+ def bundle_function(self, bdir: str, role: str, name: str) -> tuple[str, str, str] | None:
+ """``(file, symbol id, name)`` of function *name* in the *role* JS up the extends chain."""
+ for b in self.chain(bdir):
+ path = self.bundles[b].js.get(role)
+ sym = self.functions(path).get(name)
+ if path is not None and sym is not None:
+ return path, sym, name
+ return None
+
+ def interface_methods(self, bdir: str) -> set[str]:
+ """``aura:method`` names declared with no ``action`` by the bundle's own interfaces."""
+ names: set[str] = set()
+ for b in self.chain(bdir):
+ written = self.root_attrs(b).get("implements", "")
+ for item in written.split(","):
+ intf = self.own_name(item)
+ idir = self.aura_bundle_dir(intf, b) if intf else None
+ if idir is not None:
+ main = self.bundles[idir].main
+ if main is not None:
+ names |= _default_action_methods(_mask_xml(self.text(main)))
+ return names
+
+ def functions(self, path: str | None) -> dict[str, str]:
+ """``{name: symbol id}`` of a JS file's (or Apex class's) functions and methods."""
+ if path is None or path not in self.parsed_files:
+ return {}
+ if path not in self._functions:
+ self._functions[path] = {
+ s.name: s.id
+ for s in self.parsed_files[path].symbols
+ if s.kind in ("function", "method")
+ }
+ return self._functions[path]
+
+ def apex_method(self, cls_file: str, written_cls: str, method: str) -> str | None:
+ """Symbol id of *method* declared directly on the controller class (case folded)."""
+ cls = bare_type_name(written_cls).lower()
+ hits = [
+ s
+ for s in self.parsed_files[cls_file].symbols
+ if s.kind == "method"
+ and s.name.lower() == method.lower()
+ and (s.parent_name or "").lower() == cls
+ ]
+ # An Aura action is public or global, so a private overload of the same
+ # name is never the one the component calls.
+ hits.sort(key=lambda s: s.visibility == "private")
+ return hits[0].id if hits else None
+
+ def enclosing(self, path: str, line: int) -> str:
+ """Innermost symbol of *path* spanning *line*, else its ``__module__``.
+
+ Line granularity: in a one-line bundle with several handlers the later
+ one is credited. Bundle JS is written one handler per line block.
+ """
+ best: Any = None
+ for s in self.parsed_files[path].symbols:
+ if s.start_line <= line <= s.end_line and (
+ best is None or s.start_line >= best.start_line
+ ):
+ best = s
+ return best.id if best is not None else f"{path}::__module__"
+
+
+def _nearest(src: str, candidates: list[str]) -> str | None:
+ """The one candidate sharing the longest directory prefix with *src*, else None.
+
+ A repository can hold several Salesforce projects, or a source and an
+ mdapi copy of one, each declaring the same names; the platform resolves a
+ name inside the package being deployed, which the nearest copy stands for.
+ Two candidates equally near is a collision we do not break by guessing.
+ """
+ if len(candidates) <= 1:
+ return candidates[0] if candidates else None
+ src_parts = PurePosixPath(src).parts
+
+ def shared(c: str) -> int:
+ n = 0
+ for a, b in zip(src_parts, PurePosixPath(c).parts, strict=False):
+ if a != b:
+ break
+ n += 1
+ return n
+
+ scores = sorted(((shared(c), c) for c in candidates), reverse=True)
+ return scores[0][1] if scores[0][0] > scores[1][0] else None
+
+
+def _file_edge(graph: nx.DiGraph, src: str, dst: str, names: set[str]) -> int:
+ """A ``framework`` file edge vouching for *names*, merged into an earlier one."""
+ if src == dst or src not in graph or dst not in graph:
+ return 0
+ existing = graph.get_edge_data(src, dst)
+ # An edge with no names already vouches for every member; one of another
+ # type is left alone (first wins, as in `_add_edge_if_new`).
+ if existing is not None:
+ if existing.get("edge_type") == "framework" and existing.get("imported_names"):
+ merged = set(existing["imported_names"]) | names
+ existing["imported_names"] = sorted(merged)
+ return 0
+ return int(_add_edge_if_new(graph, src, dst, sorted(names)))
+
+
+def _dynamic_edge(graph: nx.DiGraph, src: str, dst: str) -> int:
+ if src == dst or src not in graph or dst not in graph or graph.has_edge(src, dst):
+ return 0
+ # Literal but runtime-built: the dynamic tier, never `framework`.
+ graph.add_edge(
+ src,
+ dst,
+ edge_type="dynamic_uses",
+ hint_source="aura_create_component",
+ weight=1.0,
+ imported_names=[],
+ )
+ return 1
+
+
+def _default_action_methods(text: str) -> set[str]:
+ """``aura:method`` names with no ``action``: those run the controller function of that name."""
+ out: set[str] = set()
+ for m in _TAG_RE.finditer(text):
+ if m.group(1) == "aura" and m.group(2) == "method":
+ attrs = _attrs(m.group(3))
+ if "action" not in attrs and attrs.get("name"):
+ out.add(attrs["name"])
+ return out
+
+
+class _Edges:
+ """File edges gathered per (source, target) so each carries every name it vouches for."""
+
+ def __init__(self, graph: nx.DiGraph) -> None:
+ self.graph = graph
+ self.names: dict[tuple[str, str], set[str]] = {}
+ self.count = 0
+
+ def file(self, src: str, dst: str, names: set[str] | None = None) -> None:
+ self.names.setdefault((src, dst), set()).update(names or ())
+
+ def bind(self, src: str, target: tuple[str, str, str], src_file: str) -> None:
+ """Bind symbol *src* to ``(file, symbol, name)`` *target* and note the file edge."""
+ path, sym, name = target
+ self.count += add_symbol_edge(self.graph, src, sym)
+ self.file(src_file, path, {name})
+
+ def flush(self) -> int:
+ for (src, dst), names in sorted(self.names.items()):
+ self.count += _file_edge(self.graph, src, dst, names)
+ return self.count
+
+
+def _is_placeable(main: str, implements: list[str]) -> bool:
+ """An ``.app``, or a component an admin can place without any source naming it."""
+ return main.endswith(".app") or any(
+ i.lower() in _ENTRY_INTERFACES or i.lower().startswith(_ENTRY_INTERFACE_PREFIXES)
+ for i in implements
+ )
+
+
+def _root_edges(idx: _AuraIndex, bdir: str, main: str, edges: _Edges) -> None:
+ """Edges the root tag of the bundle's main markup declares."""
+ attrs = idx.root_attrs(bdir)
+ cls = attrs.get("controller")
+ cls_file = idx.apex_class(cls, main) if cls else None
+ if cls_file is not None:
+ edges.file(main, cls_file, {bare_type_name(cls)})
+ implements = [i.strip() for i in attrs.get("implements", "").split(",") if i.strip()]
+ if _is_placeable(main, implements):
+ idx.graph.nodes[main]["is_entry_point"] = True
+ for written in [attrs.get("extends", ""), *implements]:
+ name = idx.own_name(written)
+ target = idx.bundle_target(name, main) if name else None
+ if target is not None:
+ edges.file(main, target)
+ # The framework calls these: renderer overrides, the controller function an
+ # action-less `aura:method` of an implemented interface names, and the
+ # functions a platform interface obliges the component to define.
+ module = f"{main}::__module__"
+ platform = {
+ m
+ for b_dir in idx.chain(bdir)
+ for i in idx.root_attrs(b_dir).get("implements", "").split(",")
+ for m in _PLATFORM_INTERFACE_METHODS.get(i.strip().lower(), ())
+ }
+ wanted = [("Renderer", n) for n in _RENDERER_OVERRIDES]
+ wanted += [("Controller", n) for n in sorted(idx.interface_methods(bdir) | platform)]
+ for role, n in wanted:
+ hit = idx.bundle_function(bdir, role, n)
+ if hit is not None:
+ edges.bind(module, hit, main)
+
+
+def _markup_file_edges(idx: _AuraIndex, bdir: str, path: str, edges: _Edges) -> None:
+ """Handler, tag and event edges of one markup file of the bundle."""
+ text = _mask_xml(idx.text(path))
+ module = f"{path}::__module__"
+ handlers = {m.group(1) for m in _MARKUP_HANDLER_RE.finditer(text)}
+ for n in sorted(handlers | _default_action_methods(text)):
+ hit = idx.bundle_function(bdir, "Controller", n)
+ if hit is not None:
+ edges.bind(module, hit, path)
+ for m in _TAG_RE.finditer(text):
+ name = _referenced_bundle(idx, m)
+ target = idx.bundle_target(name, path) if name else None
+ if target is not None:
+ edges.file(path, target)
+
+
+def _referenced_bundle(idx: _AuraIndex, m: re.Match[str]) -> str | None:
+ """The own-namespace bundle a tag names: as the tag itself, or as its event type."""
+ ns, tag, blob = m.group(1), m.group(2), m.group(3)
+ if ns == "aura" and tag in ("registerEvent", "handler"):
+ return idx.own_name(_attrs(blob).get("type" if tag == "registerEvent" else "event", ""))
+ return tag if ns.lower() in idx.own_ns else None
+
+
+def _markup_edges(idx: _AuraIndex, bdir: str, b: _Bundle, edges: _Edges) -> None:
+ if b.main is not None:
+ _root_edges(idx, bdir, b.main, edges)
+ for path in sorted(b.markup.values()):
+ _markup_file_edges(idx, bdir, path, edges)
+
+
+class _ApexController:
+ """The bundle's Apex controller, resolved on first use."""
+
+ def __init__(self, idx: _AuraIndex, bdir: str) -> None:
+ self.idx, self.bdir = idx, bdir
+ self._resolved = False
+ self._value: tuple[str, str] | None = None
+
+ def get(self) -> tuple[str, str] | None:
+ if not self._resolved:
+ self._value, self._resolved = self.idx.controller_class(self.bdir), True
+ return self._value
+
+
+def _action_edge(
+ idx: _AuraIndex, bdir: str, path: str, m: re.Match[str], apex: _ApexController, edges: _Edges
+) -> None:
+ """Bind one "c.x" literal: the Apex action for `get(`, else a client controller function."""
+ name = m.group(3)
+ source = idx.enclosing(path, _line_of(m.string, m.start()))
+ client = idx.bundle_function(bdir, "Controller", name)
+ controller = apex.get() if m.group(1) else None
+ if controller is not None:
+ method_sym = idx.apex_method(controller[1], controller[0], name)
+ if method_sym is not None or client is None:
+ # The Apex action. A method the class does not declare itself may
+ # be inherited, so the class edge stands alone.
+ edges.file(path, controller[1], {name})
+ if method_sym is not None:
+ edges.count += add_symbol_edge(idx.graph, source, method_sym)
+ return
+ # Any other "c.x" literal (getReference, addHandler, enqueue of a client
+ # action) names a client-side controller function.
+ if client is not None:
+ edges.bind(source, client, path)
+
+
+def _js_edges(idx: _AuraIndex, bdir: str, b: _Bundle, edges: _Edges) -> None:
+ apex = _ApexController(idx, bdir)
+ for path in sorted(b.js.values()):
+ text = _mask_js_comments(idx.text(path))
+ for m in _ACTION_RE.finditer(text):
+ _action_edge(idx, bdir, path, m, apex, edges)
+ helper_calls = list(_HELPER_CALL_RE.finditer(text))
+ if path == b.js.get("Helper"):
+ helper_calls += _THIS_CALL_RE.finditer(text)
+ for m in helper_calls:
+ hit = idx.bundle_function(bdir, "Helper", m.group(1))
+ if hit is not None:
+ edges.bind(idx.enclosing(path, _line_of(text, m.start())), hit, path)
+ for written in _created_components(text):
+ name = idx.own_name(written)
+ target = idx.bundle_target(name, path) if name else None
+ if target is not None:
+ edges.count += _dynamic_edge(idx.graph, path, target)
+
+
+def _created_components(text: str) -> list[str]:
+ """The ``ns:X`` string literals ``$A.createComponent(s)`` is called with."""
+ out: list[str] = []
+ for m in _CREATE_ONE_RE.finditer(text):
+ out.append(f"{m.group(2)}:{m.group(3)}")
+ for m in _CREATE_MANY_RE.finditer(text):
+ span = text[m.end() - 1 : _call_span_end(text, m.end() - 1)]
+ out.extend(f"{x.group(2)}:{x.group(3)}" for x in _CREATE_MANY_ITEM_RE.finditer(span))
+ return out
+
+
+def _add_aura_edges(graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext) -> int:
+ idx = _AuraIndex(graph, parsed_files, ctx)
+ edges = _Edges(graph)
+ for bdir in sorted(idx.bundles):
+ b = idx.bundles[bdir]
+ _markup_edges(idx, bdir, b, edges)
+ _js_edges(idx, bdir, b, edges)
+ return edges.flush()
+
+
+class _AuraHandler:
+ def detect(self, dctx: DetectionContext) -> bool:
+ return any(p.file_info.language == "aura" for p in dctx.parsed_files.values())
+
+ def add_edges(
+ self,
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+ ) -> int:
+ return _add_aura_edges(graph, parsed_files, ctx)
+
+
+HANDLERS: list[FrameworkHandler] = [_AuraHandler()]
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
index 856c280be..9bf010e4f 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
@@ -14,6 +14,7 @@ from ..spec import LanguageSpec
from .apex import SPEC as _APEX
from .asciidoc import SPEC as _ASCIIDOC
from .astro import SPEC as _ASTRO
+from .aura import SPEC as _AURA
from .c import SPEC as _C
from .clojure import SPEC as _CLOJURE
from .cobol import SPEC as _COBOL
@@ -143,6 +144,9 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (
# by another script, so these files carry nearly every inbound edge the
# .gd graph has. See the spec's docstring.
_GODOT_RESOURCE,
+ # Salesforce Aura markup, routed by path (aura/<bundle>/). Edges come from
+ # framework_edges/aura.py. See the spec's docstring.
+ _AURA,
# -----------------------------------------------------------------
# Extra languages — git blame coverage only (passthrough + is_code)
# These exist so git_indexer tracks their history even though
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/aura.py b/packages/core/src/repowise/core/ingestion/languages/specs/aura.py
new file mode 100644
index 000000000..af6933c9b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/aura.py
@@ -0,0 +1,54 @@
+"""LanguageSpec for Salesforce Aura component markup, an edge-only tag.
+
+An Aura component is a bundle directory ``aura/<name>/`` holding markup
+(``<name>.cmp``, ``.app``, ``.evt``, ``.intf``, ``.design``, ``.tokens``) and
+JavaScript (``<name>Controller.js``, ``<name>Helper.js``,
+``<name>Renderer.js``). The JavaScript stays ``javascript``. The markup is
+what names everything else: the Apex ``controller=`` class, the ``{!c.h}``
+controller functions, the ``<c:child>`` bundles, ``extends=``, ``implements=``
+and the ``.evt`` event types. Without the markup indexed, a bundle's
+JavaScript and its Apex controller have no inbound edge at all.
+
+``is_code=False`` for the same reason as ``html`` and ``godot_resource``:
+markup declares no symbols, and the classification keeps dead code from
+*reporting* a component nobody instances (flexipages, tabs, quick actions and
+App Builder place components from outside the source tree) while its
+outbound edges still anchor everything it names. The edges come from
+``framework_edges/aura.py``; there are no imports for a resolver to read.
+
+No extension claim. ``.app``, ``.design``, ``.tokens`` (ANTLR writes
+``Lexer.tokens``) and ``.evt`` are not Aura's alone, and one extension maps to
+one language for the whole repository, so the traverser routes a file here by
+path instead: one of these suffixes directly inside ``aura/<bundle>/``.
+"""
+
+from pathlib import PurePosixPath
+
+from ..spec import LanguageSpec
+
+AURA_MARKUP_SUFFIXES = frozenset({".cmp", ".app", ".evt", ".intf", ".design", ".tokens"})
+
+
+def aura_bundle(path: str) -> tuple[str, str] | None:
+ """``(bundle_dir, bundle_name)`` for a file directly inside ``aura/<bundle>/``."""
+ parts = PurePosixPath(path.replace("\\", "/")).parts
+ if len(parts) < 3 or parts[-3] != "aura":
+ return None
+ return "/".join(parts[:-1]), parts[-2]
+
+
+def is_aura_markup_path(path: str) -> bool:
+ """True for an Aura markup file: a markup suffix inside an ``aura/<bundle>/`` dir."""
+ return PurePosixPath(path).suffix.lower() in AURA_MARKUP_SUFFIXES and aura_bundle(path) is not None
+
+
+SPEC = LanguageSpec(
+ tag="aura",
+ display_name="Aura",
+ # Routed by path, not by extension; see the module docstring.
+ extensions=frozenset(),
+ is_code=False,
+ is_passthrough=True,
+ # Salesforce blue, the same as the Apex spec.
+ color_hex="#1797C0",
+)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index c8407ff28..c5a98ad30 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -87,6 +87,10 @@ LanguageTag = Literal[
# [ext_resource path=...] and [autoload] are how a Godot project reaches
# its scripts at all.
"godot_resource",
+ # Salesforce Aura markup (.cmp/.app/.evt/.intf/.design/.tokens in an
+ # aura/<bundle>/ dir): no symbols, but it names the bundle's controller
+ # functions, Apex controller and child components.
+ "aura",
"unknown",
]
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index 1990d19d9..2f762853e 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -52,6 +52,7 @@ from ..pytest_roots import (
)
from ..test_paths import is_test_related_path
from .languages.registry import REGISTRY as _LANG_REGISTRY
+from .languages.specs.aura import is_aura_markup_path
from .languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS
from .models import (
EXTENSION_TO_LANGUAGE,
@@ -1038,7 +1039,12 @@ def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None:
filename = abs_path.name
if filename in SPECIAL_FILENAMES:
return SPECIAL_FILENAMES[filename]
- return EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())
+ language = EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())
+ # Aura markup suffixes are generic (`.app`, `.tokens`), so they route by
+ # their bundle directory rather than by a repository-wide extension claim.
+ if language is None and is_aura_markup_path(abs_path.as_posix()):
+ return "aura"
+ return language
# A declaration or an import that opens its own line, matched after comments
@@ -1807,7 +1813,7 @@ def is_candidate_source_path(
return False
if _BLOCKED_FILENAME_SPEC.match_file(name):
return False
- return suffix in EXTENSION_TO_LANGUAGE
+ return suffix in EXTENSION_TO_LANGUAGE or is_aura_markup_path(posix)
def _compile_gitignore(lines: Iterable[str]) -> pathspec.PathSpec:
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.ts
index dbaaec624..1c7dab845 100644
--- a/packages/types/src/dead-code.ts
+++ b/packages/types/src/dead-code.ts
@@ -64,6 +64,7 @@ export const DEAD_CODE_RISK_FACTOR_LABELS: Record<string, string> = {
database: "database/schema",
script: "script/task",
asset: "runtime-loaded web asset",
+ aura: "Salesforce Aura bundle",
};
/** Label for one risk factor, falling back to the raw slug for an unknown tag. */
diff --git a/tests/unit/ingestion/test_aura_framework_edges.py b/tests/unit/ingestion/test_aura_framework_edges.py
new file mode 100644
index 000000000..b53431882
--- /dev/null
+++ b/tests/unit/ingestion/test_aura_framework_edges.py
@@ -0,0 +1,243 @@
+"""Salesforce Aura bundles: markup routing, handler symbols and bundle edges.
+
+End to end through traverse -> parse -> graph -> framework edges -> dead code,
+the path a real index takes.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+_A = "force-app/main/default/aura"
+
+_REPO = {
+ "sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "acme"}',
+ # A tab-placeable component with a controller, helper and renderer.
+ f"{_A}/accountList/accountList.cmp": (
+ '<aura:component implements="force:appHostable,c:selectable" extends="c:base">\n'
+ ' <aura:registerEvent name="picked" type="c:accountPicked"/>\n'
+ ' <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>\n'
+ ' <!-- <c:retired/> {!c.commentedOut} -->\n'
+ ' <c:accountRow onclick="{!c.onRow}"/>\n'
+ ' <acme:accountTile/>\n'
+ ' <lightning:button onclick="{!c.missing}"/>\n'
+ ' <other:thing/>\n'
+ "</aura:component>\n"
+ ),
+ f"{_A}/accountList/accountListController.js": (
+ "({\n"
+ " doInit : function(component, event, helper) {\n"
+ " helper.load(component);\n"
+ " helper.shared(component);\n"
+ ' component.find("in").addHandler("keyup", component, "c.onKey");\n'
+ " },\n"
+ " onRow : function(cmp, evt, helper) {\n"
+ ' var x = cmp.getReference("c.unbound");\n'
+ " // helper.notCalled(cmp);\n"
+ ' $A.createComponent("c:accountTile", {}, function() {});\n'
+ " },\n"
+ " unbound : function(cmp) {},\n"
+ " onKey : function(cmp) {},\n"
+ " pick : function(cmp) {},\n"
+ " orphan : function(cmp) {},\n"
+ "})\n"
+ ),
+ f"{_A}/accountList/accountListHelper.js": (
+ "({\n"
+ " load : function(component) {\n"
+ ' var action = component.get("c.getAccounts");\n'
+ ' var client = component.get("c.unbound");\n'
+ ' $A.createComponents([["c:accountRow", {}], ["lightning:card", {}]], function() {});\n'
+ " },\n"
+ " notCalled : function(component) {},\n"
+ "})\n"
+ ),
+ f"{_A}/accountList/accountListRenderer.js": (
+ "({\n"
+ " afterRender : function(cmp, helper) { this.superAfterRender(); },\n"
+ "})\n"
+ ),
+ f"{_A}/base/base.cmp": (
+ '<aura:component extensible="true" abstract="true" controller="acme.AccountCtrl">'
+ "{!v.body}</aura:component>\n"
+ ),
+ "force-app/main/default/classes/AccountCtrl.cls": (
+ "public with sharing class AccountCtrl {\n"
+ " @AuraEnabled public static List<Account> getAccounts() { return null; }\n"
+ " private static void getAccounts(Integer n) {}\n"
+ "}\n"
+ ),
+ # Same name in another project: the nearer copy wins.
+ "other-app/classes/AccountCtrl.cls": "public class AccountCtrl {}\n",
+ # A sub-component inherits its parent's helper.
+ f"{_A}/base/baseHelper.js": (
+ "({\n shared : function(component) { this.inner(component); },\n"
+ " inner : function(component) {},\n})\n"
+ ),
+ # An action-less aura:method runs the implementer's controller function of that name.
+ f"{_A}/selectable/selectable.intf": '<aura:interface><aura:method name="pick"/></aura:interface>\n',
+ f"{_A}/accountPicked/accountPicked.evt": '<aura:event type="COMPONENT"/>\n',
+ f"{_A}/accountRow/accountRow.cmp": "<aura:component/>\n",
+ f"{_A}/accountRow/accountRow.design": "<design:component/>\n",
+ # A flow local action: the flow runtime runs its controller's `invoke`, and a
+ # formatter has reflowed one handler expression across lines.
+ f"{_A}/goNext/goNext.cmp": (
+ '<aura:component implements="lightning:availableForFlowActions">\n'
+ ' <lightning:button onclick="\n {\n !c.onClick;\n }\n "/>\n'
+ "</aura:component>\n"
+ ),
+ f"{_A}/goNext/goNextController.js": (
+ "({\n invoke : function(cmp, event, helper) {},\n onClick : function(cmp) {},\n})\n"
+ ),
+ f"{_A}/main/main.app": '<aura:application extends="force:slds"><c:accountList/></aura:application>\n',
+ # An LWC bundle reached by an Aura tag, by its camelCase name.
+ "force-app/main/default/lwc/accountTile/accountTile.js": (
+ "import { LightningElement } from 'lwc';\nexport default class AccountTile extends LightningElement {}\n"
+ ),
+ # Generic suffixes outside an aura/<bundle>/ dir stay unclaimed.
+ "grammar/Lexer.tokens": "ID=1\n",
+ "aura/Loose.app": "<aura:application/>\n",
+}
+
+
+def _write(repo: Path, files: dict[str, str]) -> Path:
+ for rel, text in files.items():
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return repo
+
+
+def _build(repo: Path):
+ builder = GraphBuilder(repo)
+ parser = ASTParser()
+ source_map: dict[str, bytes] = {}
+ for fi in FileTraverser(repo).traverse():
+ src = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, src))
+ source_map[fi.path] = src
+ builder.set_source_map(source_map)
+ builder.build()
+ builder.add_framework_edges([])
+ return builder, source_map
+
+
+def _edges(graph, edge_type: str) -> set[tuple[str, str]]:
+ return {(s, t) for s, t, d in graph.edges(data=True) if d.get("edge_type") == edge_type}
+
+
+def test_markup_is_routed_by_bundle_dir_only(tmp_path: Path) -> None:
+ builder, _ = _build(_write(tmp_path, _REPO))
+ langs = {p: pf.file_info.language for p, pf in builder._parsed_files.items()}
+ assert langs[f"{_A}/accountList/accountList.cmp"] == "aura"
+ assert langs[f"{_A}/accountRow/accountRow.design"] == "aura"
+ assert langs[f"{_A}/main/main.app"] == "aura"
+ assert "grammar/Lexer.tokens" not in langs
+ assert "aura/Loose.app" not in langs
+
+
+def test_bundle_js_handlers_are_symbols(tmp_path: Path) -> None:
+ builder, _ = _build(_write(tmp_path, _REPO))
+ ctrl = builder._parsed_files[f"{_A}/accountList/accountListController.js"]
+ assert [s.name for s in ctrl.symbols] == ["doInit", "onRow", "unbound", "onKey", "pick", "orphan"]
+ assert all(s.kind == "function" for s in ctrl.symbols)
+
+
+def test_bundle_edges(tmp_path: Path) -> None:
+ builder, _ = _build(_write(tmp_path, _REPO))
+ g = builder.graph()
+ cmp_ = f"{_A}/accountList/accountList.cmp"
+ ctrl = f"{_A}/accountList/accountListController.js"
+ helper = f"{_A}/accountList/accountListHelper.js"
+ renderer = f"{_A}/accountList/accountListRenderer.js"
+ tile = "force-app/main/default/lwc/accountTile/accountTile.js"
+ framework = _edges(g, "framework")
+ assert {
+ (cmp_, f"{_A}/base/base.cmp"),
+ (cmp_, f"{_A}/selectable/selectable.intf"),
+ (cmp_, f"{_A}/accountPicked/accountPicked.evt"),
+ (cmp_, f"{_A}/accountRow/accountRow.cmp"),
+ (cmp_, tile), # own namespace from sfdx-project.json, LWC target
+ (cmp_, ctrl),
+ (cmp_, renderer),
+ (ctrl, helper),
+ (f"{_A}/main/main.app", cmp_),
+ } <= framework
+ assert g.edges[cmp_, ctrl]["imported_names"] == ["doInit", "onRow", "pick"]
+ assert all(t != f"{_A}/retired/retired.cmp" for _, t in framework)
+ assert (ctrl, f"{_A}/base/baseHelper.js") in framework
+ binds = _edges(g, "framework_binds")
+ assert {
+ (f"{cmp_}::__module__", f"{ctrl}::doInit"),
+ (f"{cmp_}::__module__", f"{ctrl}::onRow"),
+ (f"{cmp_}::__module__", f"{renderer}::afterRender"),
+ (f"{ctrl}::doInit", f"{helper}::load"),
+ (f"{ctrl}::onRow", f"{ctrl}::unbound"),
+ (f"{ctrl}::doInit", f"{ctrl}::onKey"),
+ (f"{ctrl}::doInit", f"{_A}/base/baseHelper.js::shared"),
+ (f"{cmp_}::__module__", f"{ctrl}::pick"),
+ (f"{_A}/base/baseHelper.js::shared", f"{_A}/base/baseHelper.js::inner"),
+ } <= binds
+ assert (f"{ctrl}::onRow", f"{helper}::notCalled") not in binds
+ cls = "force-app/main/default/classes/AccountCtrl.cls"
+ assert (f"{_A}/base/base.cmp", cls) in framework
+ assert g.edges[helper, cls]["imported_names"] == ["getAccounts"]
+ getter = [t for s, t in binds if s == f"{helper}::load" and t.startswith(f"{cls}::")]
+ assert getter == [f"{cls}::AccountCtrl::getAccounts#0"]
+ # `get("c.x")` naming no Apex method but a controller function is a client action.
+ assert (f"{helper}::load", f"{ctrl}::unbound") in binds
+ go = f"{_A}/goNext/goNext"
+ assert (f"{go}.cmp::__module__", f"{go}Controller.js::invoke") in binds
+ assert (f"{go}.cmp::__module__", f"{go}Controller.js::onClick") in binds
+ dynamic = _edges(g, "dynamic_uses")
+ assert (ctrl, tile) in dynamic
+ assert (helper, f"{_A}/accountRow/accountRow.cmp") in dynamic
+ assert g.nodes[cmp_].get("is_entry_point") is True
+ assert g.nodes[f"{_A}/main/main.app"].get("is_entry_point") is True
+ assert not g.nodes[f"{_A}/base/base.cmp"].get("is_entry_point")
+
+
+def test_dead_code_keeps_bound_handlers_and_reports_unbound_ones(tmp_path: Path) -> None:
+ repo = _write(tmp_path, _REPO)
+ builder, source_map = _build(repo)
+ report = DeadCodeAnalyzer(
+ builder.graph(), {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=repo
+ ).analyze({"detect_unused_internals": True})
+ dead = {(f.file_path, f.symbol_name or "") for f in report.findings}
+ # A bundle's JS is loaded and read by the Lightning runtime: never deletion-ready.
+ assert not any(f.safe_to_delete for f in report.findings if "/aura/" in f.file_path)
+ ctrl = f"{_A}/accountList/accountListController.js"
+ for live in (
+ (ctrl, ""),
+ (ctrl, "doInit"),
+ (ctrl, "onRow"),
+ (ctrl, "unbound"),
+ (ctrl, "onKey"),
+ (ctrl, "pick"),
+ (f"{_A}/base/baseHelper.js", "shared"),
+ (f"{_A}/base/baseHelper.js", "inner"),
+ (f"{_A}/accountList/accountListHelper.js", "load"),
+ (f"{_A}/accountList/accountListRenderer.js", "afterRender"),
+ ):
+ assert live not in dead
+ assert not any(path.endswith((".cmp", ".app", ".evt", ".intf")) for path, _ in dead)
+ assert (ctrl, "orphan") in dead
+ assert (f"{_A}/accountList/accountListHelper.js", "notCalled") in dead
+
+
+def test_change_sources_see_aura_markup() -> None:
+ from repowise.core.ingestion.traverser import is_candidate_source_path
+
+ assert is_candidate_source_path(f"{_A}/accountList/accountList.cmp")
+ assert is_candidate_source_path(f"{_A}/main/main.app")
+ assert not is_candidate_source_path("grammar/Lexer.tokens")
+
+
+def test_only_aura_bundle_files_carry_the_aura_risk_factor() -> None:
+ from repowise.core.analysis.dead_code.risk_factors import path_risk_factors
+
+ assert path_risk_factors(f"{_A}/accountList/accountListHelper.js") == ("aura",)
+ assert path_risk_factors("src/aura/util.js") == ()