Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(salesforce): index flows and link them to Apex actions, subflows and screen components (#4414)
Raghav Chamadiya9bd746edb6bb
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex 78645d0f3..24da4297b 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -986,6 +986,14 @@ Salesforce CLI coverage names a class or trigger, never a file, so it maps tothe one `.cls` or `.trigger` file of that name, ignoring case. A name two filesshare, or no file has, stays unmapped.+Each flow (`.flow-meta.xml`, or a legacy `.flow` in a `flows/` directory) is+one symbol named by its API name, linked to the Apex invocable actions,+subflows, screen components and Apex-defined types it names. Apex+`Flow.Interview` references and LWC `<lightning-flow>` tags with a literal name+link back to it. Flexipages, quick actions, tabs, email services and Experience+sites mark what they name as live; names in another package's namespace are not+followed.+### Salesforce VisualforcePages and components link the Apex classes their `controller=` anddiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 33858ffa7..9a7605b86 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -79,6 +79,8 @@ resolved case-insensitively within each sfdx project's namespace, and isexcluded from dead-code claims the same way until triggers, annotations andplatform interfaces are modelled as entry points. Apex test coverage from theSalesforce CLI is read as a coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)).+Salesforce flows (`.flow-meta.xml`) are one symbol each, linked to the Apex+invocable actions, subflows and screen components they name.## How accurate is the graph per languagediff --git a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.pyindex 5f1adc98f..369d8d8d2 100644--- a/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py+++ b/packages/core/src/repowise/core/ingestion/framework_edges/__init__.py@@ -48,6 +48,7 @@ from . import (rails,remix,rust,+ salesforce_metadata,spring,test_path_strings,test_runner_setup,@@ -108,6 +109,8 @@ _HANDLERS: list[FrameworkHandler] = [*aura.HANDLERS,# Salesforce Visualforce: markup names its Apex controller and bound members.*visualforce.HANDLERS,+ # Last, so an LWC or Aura handler's own edge to the same file wins.+ *salesforce_metadata.HANDLERS,]diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/salesforce_metadata.py b/packages/core/src/repowise/core/ingestion/framework_edges/salesforce_metadata.pynew file mode 100644index 000000000..c60adfe47--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges/salesforce_metadata.py@@ -0,0 +1,452 @@+"""Salesforce flows and the metadata that places code.++A flow links to the Apex classes its actions name (and their one+``@InvocableMethod``), its subflows, its screen components and its Apex-defined+types. Apex ``Flow.Interview`` references and LWC ``<lightning-flow>`` tags+with a literal name link back to the flow.++Flexipages, quick actions, tabs, email services and Experience sites are read+from disk (as ``android_manifest`` is) for liveness only: each file they name is+anchored to ``framework:salesforce`` and marked an entry point.++Only own namespaces (``c``, sfdx-project.json, cumulusci.yml) are followed.+Apex and flow names fold case; component names match exactly. A name two+projects declare binds to the nearest by path, and to none on a tie.+"""++from __future__ import annotations++import re+from collections.abc import Iterator+from pathlib import Path, PurePosixPath+from typing import TYPE_CHECKING, Any++from repowise.core.fs_walk import glob_via++from ..framework_facts import SALESFORCE+from ..salesforce_flow import FlowRefs, read_flow+from ..type_names import bare_type_name, type_qualifier+from .base import (+ DetectionContext,+ FrameworkHandler,+ _add_edge_if_new,+ add_symbol_edge,+ anchor_edge,+ source_text,+)++if TYPE_CHECKING:+ import networkx as nx++ from ..resolvers import ResolverContext++_FLOW = "salesforce_flow"+_XML_COMMENT_RE = re.compile(r"<!--.*?(?:-->|\Z)", re.DOTALL)+# An Apex comment, or a string literal kept as-is so a `//` inside one is not a comment.+_APEX_COMMENT_OR_STRING_RE = re.compile(+ r"//[^\n]*|/\*.*?(?:\*/|\Z)|'(?:[^'\\\n]|\\.)*'", re.DOTALL+)+_INVOCABLE_RE = re.compile(r"@\s*InvocableMethod\b", re.IGNORECASE)+# `Flow.Interview.createInterview('Name', ...)` or `('ns', 'Name', ...)`.+_CREATE_INTERVIEW_RE = re.compile(+ r"\bFlow\s*\.\s*Interview\s*\.\s*createInterview\s*\(\s*'([^'\n]*)'(?:\s*,\s*'([^'\n]*)')?",+ re.IGNORECASE,+)+# `Flow.Interview.Name` and `Flow.Interview.ns.Name`.+_INTERVIEW_TYPE_RE = re.compile(+ r"\bFlow\s*\.\s*Interview\s*\.\s*(\w+)(?:\s*\.\s*(\w+))?", re.IGNORECASE+)+_LIGHTNING_FLOW_RE = re.compile(+ r"""<lightning-flow\b[^>]*?\bflow-api-name\s*=\s*["']([A-Za-z]\w*)["']""", re.IGNORECASE+)+_NS_UU_RE = re.compile(r"^([A-Za-z0-9]+)__(.+)$")+_SFDX_NS_RE = re.compile(r'"namespace"\s*:\s*"(\w+)"')+_CCI_NS_RE = re.compile(r"^\s+namespace:\s*['\"]?(\w+)", re.MULTILINE)++# Liveness metadata: glob -> (element names that hold a component, a flow, an Apex class).+_COMPONENT_TAGS = r"componentName|lightningComponent|lightningWebComponent|lwcComponent|auraComponent"+_TAG_VALUE_RE = re.compile(+ rf"<({_COMPONENT_TAGS}|flowDefinition|apexClass)>\s*([^<\s]+)\s*</\1>"+)+_PLACEMENT_SUFFIXES = (".flexipage-meta.xml", ".quickAction-meta.xml", ".tab-meta.xml")+# Metadata API names are bare suffixes (``.tab`` is also tab-separated data),+# so they count only in their metadata directory.+_MDAPI_PLACEMENT = {".flexipage": "flexipages", ".quickAction": "quickActions", ".tab": "tabs"}+# Placement metadata is small; a bigger file is not one.+_MAX_PLACEMENT_BYTES = 1_000_000+# The globs only narrow the walk; ``_is_placement_file`` decides what is read.+_LIVENESS_GLOBS = (+ *(f"*{s}" for s in (*_PLACEMENT_SUFFIXES, *_MDAPI_PLACEMENT)),+ "*.xml", # emailservices/<Name>.xml-meta.xml, mdapi emailservices/<Name>.xml+ "*.json", # Experience Builder views under experiences/+)+_EXPERIENCE_DEFINITION_RE = re.compile(r'"definition"\s*:\s*"(\w+:\w+)"')+++def _mask(text: str, pattern: re.Pattern[str], keep: str = "") -> str:+ def blank(m: re.Match[str]) -> str:+ s = m.group(0)+ return s if keep and s[0] in keep else re.sub(r"[^\n]", " ", s)++ return pattern.sub(blank, text)+++def _nearest(candidates: list[str], referrer: str) -> str | None:+ """The candidate sharing the longest directory prefix with *referrer*; None on a tie."""+ if len(candidates) == 1:+ return candidates[0]+ ref = PurePosixPath(referrer).parts++ def shared(path: str) -> int:+ n = 0+ for a, b in zip(PurePosixPath(path).parts, ref, strict=False):+ if a != b:+ break+ n += 1+ return n++ ranked = sorted(((shared(c), c) for c in candidates), reverse=True)+ if not ranked or (len(ranked) > 1 and ranked[0][0] == ranked[1][0]):+ return None+ return ranked[0][1]+++class _Index:+ """Name -> file maps for one repository, built from the parsed file set."""++ def __init__(self, parsed_files: dict[str, Any], ctx: ResolverContext) -> None:+ self.parsed_files = parsed_files+ self.apex: dict[str, list[str]] = {} # lowercased class name -> .cls paths+ self.flows: dict[str, list[str]] = {} # lowercased API name -> flow paths+ self.lwc: dict[str, list[str]] = {} # bundle name -> main module+ self.aura: dict[str, list[str]] = {} # bundle name -> markup (or controller JS)+ aura_files: dict[str, dict[str, str]] = {}+ for path in sorted(parsed_files):+ parsed = parsed_files[path]+ p = PurePosixPath(path)+ lang = parsed.file_info.language+ if lang == "apex" and p.suffix.lower() == ".cls":+ # Ceiling: a local case-folded index; use a shared Apex class index once one exists.+ self.apex.setdefault(p.stem.lower(), []).append(path)+ elif lang == _FLOW:+ sym = next(iter(parsed.symbols), None)+ if sym is not None:+ self.flows.setdefault(sym.name.lower(), []).append(path)+ elif len(p.parts) >= 3 and p.parts[-3] in ("lwc", "aura"):+ bundle = p.parts[-2]+ if p.parts[-3] == "lwc" and p.name in (f"{bundle}.js", f"{bundle}.ts"):+ self.lwc.setdefault(bundle, []).append(path)+ elif p.parts[-3] == "aura":+ aura_files.setdefault(str(p.parent), {})[p.name] = path+ for bundle_dir, files in aura_files.items():+ bundle = PurePosixPath(bundle_dir).name+ # The markup is the bundle; without the Aura markup indexed, its+ # controller is what the placement makes live.+ target = next(+ (files[f"{bundle}{s}"] for s in (".cmp", ".app") if f"{bundle}{s}" in files),+ files.get(f"{bundle}Controller.js"),+ )+ if target is not None:+ self.aura.setdefault(bundle, []).append(target)+ self.own_ns = _own_namespaces(ctx)++ # -- name resolution ------------------------------------------------++ def _strip_ns(self, raw: str, index: dict[str, list[str]]) -> str | None:+ """*raw* without an own-namespace prefix (``ns__X``, ``ns.X``); None if foreign."""+ name = raw.strip()+ if name.lower() in index:+ return name+ if "." in name:+ ns = type_qualifier(name)+ return bare_type_name(name) if ns.lower() in self.own_ns else None+ m = _NS_UU_RE.match(name)+ if m:+ return m.group(2) if m.group(1).lower() in self.own_ns else None+ return name++ def apex_class(self, raw: str, referrer: str) -> str | None:+ name = self._strip_ns(raw, self.apex)+ cands = self.apex.get(name.lower(), []) if name else []+ return _nearest(cands, referrer) if cands else None++ # Ceiling: two legacy versions of one flow in one directory (``Foo-1.flow``,+ # ``Foo-2.flow``) tie and bind neither; take the highest version if it matters.+ def flow(self, raw: str, referrer: str) -> str | None:+ name = self._strip_ns(raw, self.flows)+ cands = self.flows.get(name.lower(), []) if name else []+ return _nearest(cands, referrer) if cands else None++ def components(self, raw: str, referrer: str) -> list[str]:+ """The LWC main module and Aura bundle file ``c:name`` (or a bare name) means."""+ ns, sep, name = raw.strip().partition(":")+ if not sep:+ ns, name = "c", ns+ m = _NS_UU_RE.match(name)+ if m and name not in self.lwc and name not in self.aura:+ ns, name = m.group(1), m.group(2)+ if ns.lower() not in self.own_ns:+ return []+ found = (_nearest(index.get(name, []), referrer) for index in (self.lwc, self.aura))+ return [f for f in found if f is not None]++ def symbol_of(self, path: str) -> str | None:+ """The id of the flow's symbol, or the Apex file's class named like the file."""+ parsed = self.parsed_files.get(path)+ if parsed is None:+ return None+ stem = PurePosixPath(path).stem.lower()+ return next(+ (+ s.id+ for s in parsed.symbols+ if s.parent_name is None+ and (s.language == _FLOW or (s.kind == "class" and s.name.lower() == stem))+ ),+ None,+ )++ def invocable(self, cls_path: str) -> str | None:+ """The class's single ``@InvocableMethod``, or None."""+ parsed = self.parsed_files.get(cls_path)+ if parsed is None:+ return None+ stem = PurePosixPath(cls_path).stem.lower()+ ids = {+ s.id+ for s in parsed.symbols+ if s.kind == "method"+ and (s.parent_name or "").lower() == stem+ and any(_INVOCABLE_RE.search(d) for d in s.decorators)+ }+ return ids.pop() if len(ids) == 1 else None+++def _own_namespaces(ctx: ResolverContext) -> frozenset[str]:+ """``c`` plus the namespace each sfdx-project.json and cumulusci.yml declares."""+ names = {"c"}+ if ctx.repo_path is None:+ return frozenset(names)+ for cfg in glob_via(+ ctx.walk_snapshot,+ ctx.repo_path,+ ("sfdx-project.json", "cumulusci.yml"),+ prune_nested_git=ctx.prune_nested_git,+ ):+ try:+ text = cfg.read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ continue+ pattern = _SFDX_NS_RE if cfg.name.endswith(".json") else _CCI_NS_RE+ names.update(m.group(1).lower() for m in pattern.finditer(text))+ return frozenset(names)+++def _link(+ graph: nx.DiGraph, src: str, target: str, names: list[str], src_sym: str | None, target_sym: str | None+) -> int:+ added = _add_edge_if_new(graph, src, target, names)+ if src_sym is not None and target_sym is not None:+ added += add_symbol_edge(graph, src_sym, target_sym)+ return added+++# -- flows -----------------------------------------------------------------+++def _flow_edges(graph: nx.DiGraph, idx: _Index, ctx: ResolverContext) -> int:+ source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}+ count = 0+ for path, parsed in idx.parsed_files.items():+ if parsed.file_info.language != _FLOW:+ continue+ raw = source_map.get(path)+ refs = read_flow(raw if raw is not None else source_text(path, parsed, {}).encode())+ flow_sym = idx.symbol_of(path)+ if refs is not None and flow_sym is not None:+ count += _one_flow_edges(graph, idx, path, flow_sym, refs)+ return count+++def _one_flow_edges(graph: nx.DiGraph, idx: _Index, path: str, flow_sym: str, refs: FlowRefs) -> int:+ count = 0+ for cls in filter(None, (idx.apex_class(n, path) for n in refs.apex_actions)):+ target_sym = idx.invocable(cls) or idx.symbol_of(cls)+ count += _link(graph, path, cls, [PurePosixPath(cls).stem], flow_sym, target_sym)+ for cls in filter(None, (idx.apex_class(n, path) for n in refs.apex_types)):+ count += _add_edge_if_new(graph, path, cls, [PurePosixPath(cls).stem])+ for target in filter(None, (idx.flow(n, path) for n in refs.flows)):+ count += _link(graph, path, target, [], flow_sym, idx.symbol_of(target))+ for name in refs.components:+ count += sum(_add_edge_if_new(graph, path, t) for t in idx.components(name, path))+ return count+++def _enclosing(parsed: Any, line: int, path: str) -> str:+ """The innermost method (else class) declared around *line*, else the module."""+ spans = [+ (s.end_line - s.start_line, s.id)+ for s in parsed.symbols+ if s.kind in ("method", "class") and s.start_line <= line <= s.end_line+ ]+ return min(spans)[1] if spans else f"{path}::__module__"+++def _apex_flow_refs(graph: nx.DiGraph, idx: _Index, ctx: ResolverContext) -> int:+ """``Flow.Interview.<Name>`` and ``createInterview('<Name>')`` in Apex."""+ source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}+ count = 0+ for path, parsed in idx.parsed_files.items():+ if parsed.file_info.language != "apex":+ continue+ text = source_text(path, parsed, source_map)+ if "interview" not in text.lower():+ continue+ code = _mask(text, _APEX_COMMENT_OR_STRING_RE) # comments and strings blanked+ text = _mask(text, _APEX_COMMENT_OR_STRING_RE, keep="'") # comments only+ hits: list[tuple[int, str]] = []+ for m in _CREATE_INTERVIEW_RE.finditer(text):+ # The call must start in code; only its argument is read from a literal.+ if code[m.start()] == " ":+ continue+ ns, name = (m.group(1), m.group(2)) if m.group(2) is not None else ("", m.group(1))+ hits.append((m.start(), f"{ns}__{name}" if ns else name))+ for m in _INTERVIEW_TYPE_RE.finditer(code):+ first, second = m.group(1), m.group(2)+ if first.lower() == "createinterview":+ continue+ # `Flow.Interview.ns.Name`: the first part is a namespace only+ # when no flow has that name.+ if second is not None and idx.flow(first, path) is None:+ hits.append((m.start(), f"{first}.{second}"))+ else:+ hits.append((m.start(), first))+ for offset, name in hits:+ target = idx.flow(name, path)+ if target is None:+ continue+ caller = _enclosing(parsed, text.count("\n", 0, offset) + 1, path)+ count += _link(graph, path, target, [], caller, idx.symbol_of(target))+ return count+++def _lwc_flow_refs(graph: nx.DiGraph, idx: _Index, ctx: ResolverContext) -> int:+ """``<lightning-flow flow-api-name="Name">`` in an LWC template, literal only."""+ source_map: dict[str, bytes] = getattr(ctx, "source_map", None) or {}+ count = 0+ for path, parsed in idx.parsed_files.items():+ p = PurePosixPath(path)+ if p.suffix != ".html" or len(p.parts) < 3 or p.parts[-3] != "lwc":+ continue+ text = source_text(path, parsed, source_map)+ if "lightning-flow" not in text:+ continue+ text = _mask(text, _XML_COMMENT_RE)+ for m in _LIGHTNING_FLOW_RE.finditer(text):+ target = idx.flow(m.group(1), path)+ if target is not None:+ count += _link(graph, path, target, [], f"{path}::__module__", idx.symbol_of(target))+ return count+++# -- liveness metadata -------------------------------------------------------+++def _is_placement_file(rel: str) -> bool:+ """Whether *rel* is metadata that places code, so worth reading."""+ p = PurePosixPath(rel)+ if p.name.endswith(_PLACEMENT_SUFFIXES):+ return True+ if _MDAPI_PLACEMENT.get(p.suffix) == p.parent.name:+ return True+ if p.parent.name == "emailservices":+ return p.name.endswith(".xml")+ return p.suffix == ".json" and "experiences" in p.parts+++def _placed_names(rel: str, text: str) -> list[tuple[str, str]]:+ """``(kind, name)`` pairs a metadata file places: kind is component, flow or apex."""+ parent = PurePosixPath(rel).parent.name+ if rel.endswith(".json"):+ return [("component", m.group(1)) for m in _EXPERIENCE_DEFINITION_RE.finditer(text)]+ text = _mask(text, _XML_COMMENT_RE)+ out: list[tuple[str, str]] = []+ for m in _TAG_VALUE_RE.finditer(text):+ tag, value = m.group(1), m.group(2)+ if tag == "apexClass":+ # Permission sets grant class access with the same element; that+ # is no evidence of use, so only an email service counts.+ if parent == "emailservices":+ out.append(("apex", value))+ elif tag == "flowDefinition":+ out.append(("flow", value))+ else:+ out.append(("component", value))+ return out+++def _placement_texts(ctx: ResolverContext, root: Path) -> Iterator[tuple[str, str]]:+ """``(repo-relative path, text)`` of every placement metadata file."""+ for file in glob_via(+ ctx.walk_snapshot, root, _LIVENESS_GLOBS, prune_nested_git=ctx.prune_nested_git+ ):+ try:+ rel = file.relative_to(root).as_posix()+ except ValueError:+ continue+ if not _is_placement_file(rel):+ continue+ try:+ if file.stat().st_size <= _MAX_PLACEMENT_BYTES:+ yield rel, file.read_text(encoding="utf-8-sig", errors="replace")+ except OSError:+ continue+++def _placed_targets(idx: _Index, kind: str, value: str, rel: str) -> list[str]:+ if kind == "apex":+ return [t] if (t := idx.apex_class(value, rel)) else []+ if kind == "flow":+ return [t] if (t := idx.flow(value, rel)) else []+ return idx.components(value, rel)+++def _liveness_edges(graph: nx.DiGraph, idx: _Index, ctx: ResolverContext, path_set: set[str]) -> int:+ if ctx.repo_path is None:+ return 0+ count = 0+ for rel, text in _placement_texts(ctx, ctx.repo_path.resolve()):+ for kind, value in _placed_names(rel, text):+ for target in _placed_targets(idx, kind, value, rel):+ if target not in path_set:+ continue+ count += anchor_edge(graph, SALESFORCE, target)+ node = graph.nodes.get(target)+ if node is not None:+ node["is_entry_point"] = True+ return count+++class _SalesforceMetadataHandler:+ def detect(self, dctx: DetectionContext) -> bool:+ return any(+ p.file_info.language in ("apex", _FLOW) for p in dctx.parsed_files.values()+ ) or any(PurePosixPath(p).name == "sfdx-project.json" for p in dctx.path_set)++ def add_edges(+ self,+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+ ) -> int:+ idx = _Index(parsed_files, ctx)+ return (+ _flow_edges(graph, idx, ctx)+ + _apex_flow_refs(graph, idx, ctx)+ + _lwc_flow_refs(graph, idx, ctx)+ + _liveness_edges(graph, idx, ctx, path_set)+ )+++HANDLERS: list[FrameworkHandler] = [_SalesforceMetadataHandler()]diff --git a/packages/core/src/repowise/core/ingestion/framework_facts.py b/packages/core/src/repowise/core/ingestion/framework_facts.pyindex c9b440eee..bba7d3ba0 100644--- a/packages/core/src/repowise/core/ingestion/framework_facts.py+++ b/packages/core/src/repowise/core/ingestion/framework_facts.py@@ -124,6 +124,10 @@ def detect_php_framework(manifest: ComposerManifest) -> FrameworkFacts | None:return next((facts for facts in PHP_FRAMEWORKS if facts.matches(manifest)), None)+#: The Salesforce org, which places what flexipages, quick actions, tabs,+#: email services and Experience sites name.+SALESFORCE = FrameworkFacts(name="Salesforce", anchor="framework:salesforce")+#: The runtime that starts the components an ``AndroidManifest.xml`` registers.ANDROID = FrameworkFacts(name="Android", anchor="framework:android")diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.pyindex f71b1ea12..f207d1c6a 100644--- a/packages/core/src/repowise/core/ingestion/languages/registry.py+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py@@ -95,6 +95,10 @@ class LanguageRegistry:"""Return ``{ext: tag}`` for all registered extensions."""return dict(self._ext_map)+ def all_name_suffixes(self) -> dict[str, str]:+ """Return ``{lowercase name ending: tag}`` for multi-dot endings."""+ return {sfx: s.tag for s in self._specs.values() for sfx in s.name_suffixes}+def all_special_filenames(self) -> dict[str, str]:"""Return ``{filename: tag}`` for all special filenames."""return dict(self._filename_map)diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.pyindex 1bfd34a92..67f905e42 100644--- a/packages/core/src/repowise/core/ingestion/languages/spec.py+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py@@ -27,6 +27,8 @@ class LanguageSpec:# -- File matching ---------------------------------------------------extensions: frozenset[str] = field(default_factory=frozenset) # (".py", ".pyi")special_filenames: frozenset[str] = field(default_factory=frozenset) # ("Dockerfile",)+ # Lowercase multi-dot name endings (``.flow-meta.xml``), matched before the one-suffix lookup.+ name_suffixes: frozenset[str] = field(default_factory=frozenset)# -- Classification --------------------------------------------------is_code: bool = True # False for yaml, json, markdown, etc.diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex 37e3bcb1c..5ce33b3c9 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -56,6 +56,7 @@ from .r import SPEC as _Rfrom .razor import SPEC as _RAZORfrom .ruby import SPEC as _RUBYfrom .rust import SPEC as _RUST+from .salesforce_flow import SPEC as _SALESFORCE_FLOWfrom .scala import SPEC as _SCALAfrom .shell import SPEC as _SHELLfrom .sql import SPEC as _SQL@@ -150,6 +151,8 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (# Salesforce Aura markup, routed by path (aura/<bundle>/). Edges come from# framework_edges/aura.py. See the spec's docstring._AURA,+ # Salesforce flows. See the spec's docstring.+ _SALESFORCE_FLOW,# -----------------------------------------------------------------# Extra languages — git blame coverage only (passthrough + is_code)# These exist so git_indexer tracks their history even thoughdiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_flow.py b/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_flow.pynew file mode 100644index 000000000..a9b6ac726--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/salesforce_flow.py@@ -0,0 +1,27 @@+"""LanguageSpec for Salesforce flows.++Claims ``*.flow-meta.xml``, and a legacy ``flows/<ApiName>-<version>.flow`` by its+directory, since ``.flow`` alone is also Flow's (the JS type checker) ``*.js.flow``.+``is_code=False``: the org places every flow, so dead code never reports one.+"""++from pathlib import PurePosixPath++from ..spec import LanguageSpec+++def is_legacy_flow_path(path: str) -> bool:+ """True for a metadata API ``flows/<Name>-<version>.flow`` file."""+ p = PurePosixPath(path.replace("\\", "/"))+ # A flow API name has no dot, so ``flows/types.js.flow`` stays JavaScript's.+ return p.suffix.lower() == ".flow" and p.parent.name == "flows" and "." not in p.stem+++SPEC = LanguageSpec(+ tag="salesforce_flow",+ display_name="Salesforce Flow",+ name_suffixes=frozenset({".flow-meta.xml"}),+ is_code=False,+ is_passthrough=True,+ color_hex="#00A1E0",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex e4b8daf6e..d2fe77f29 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -93,6 +93,8 @@ LanguageTag = Literal[# aura/<bundle>/ dir): no symbols, but it names the bundle's controller# functions, Apex controller and child components."aura",+ # Salesforce flows: one symbol per flow.+ "salesforce_flow","unknown",]@@ -118,6 +120,12 @@ SPECIAL_FILENAMES: dict[str, LanguageTag] = {if tag in _LANGUAGE_TAG_VALUES}+NAME_SUFFIX_TO_LANGUAGE: dict[str, LanguageTag] = {+ sfx: tag # type: ignore[misc]+ for sfx, tag in _REGISTRY.all_name_suffixes().items()+ if tag in _LANGUAGE_TAG_VALUES+}+# ---------------------------------------------------------------------------# Symbol kinds# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/salesforce_flow.py b/packages/core/src/repowise/core/ingestion/salesforce_flow.pynew file mode 100644index 000000000..5603b6d8a--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/salesforce_flow.py@@ -0,0 +1,173 @@+"""Salesforce flow metadata: the flow's symbol and the names it reaches.++A flow file (``flows/<ApiName>.flow-meta.xml``, legacy+``flows/<ApiName>-<version>.flow``) is one ``<Flow>`` document. The API name is+the file stem, and it is what a subflow, ``Flow.Interview.<Name>``, a quick+action or ``<lightning-flow flow-api-name>`` calls the flow by. This module+reads the file once into a :class:`FlowRefs`: ``special_handlers`` turns it+into the flow's symbol and ``framework_edges/salesforce_metadata.py`` resolves+its names into edges.+"""++from __future__ import annotations++import re+import xml.etree.ElementTree as ET+from dataclasses import dataclass, field+from pathlib import PurePosixPath++from .models import FileInfo, ParsedFile, Symbol++# A legacy metadata API flow carries its version number: ``Foo-3.flow``.+_LEGACY_VERSION_RE = re.compile(r"-\d+$")+# Orchestrator stage steps run a flow; their other actionTypes are platform work.+_STEP_ACTION_TYPES = frozenset({"stepinteractive", "stepbackground", "stepapproval"})+++@dataclass+class FlowRefs:+ """The names one flow file reaches, as written (case kept)."""++ process_type: str = ""+ trigger_type: str = ""+ start_object: str = "" # record-triggered and platform-event flows+ label: str = ""+ description: str = ""+ apex_actions: list[str] = field(default_factory=list) # actionType apex, apexPluginCalls+ flows: list[str] = field(default_factory=list) # subflows, actionType flow, stage steps+ components: list[str] = field(default_factory=list) # screen fields, local actions (``c:comp``)+ apex_types: list[str] = field(default_factory=list) # Apex-defined variable types+++def flow_api_name(path: str) -> str:+ """The API name a flow file declares: its stem, legacy version dropped."""+ name = PurePosixPath(path).name+ if name.lower().endswith(".flow-meta.xml"):+ return name[: -len(".flow-meta.xml")]+ return _LEGACY_VERSION_RE.sub("", name.rpartition(".")[0])+++def _local(tag: str) -> str:+ return tag.rpartition("}")[2]+++def _child_text(el: ET.Element, name: str) -> str:+ for child in el:+ if _local(child.tag) == name:+ return (child.text or "").strip()+ return ""+++def _read_element(refs: FlowRefs, el: ET.Element) -> None:+ """Add the names one top-level flow element reaches to *refs*."""+ tag = _local(el.tag)+ if tag == "actionCalls":+ _read_action(refs, el)+ elif tag == "apexPluginCalls":+ # Legacy Process.Plugin: the class is the action, not a variable type.+ if name := _child_text(el, "apexClass"):+ refs.apex_actions.append(name)+ return+ elif tag == "subflows":+ if name := _child_text(el, "flowName"):+ refs.flows.append(name)+ elif tag == "start":+ refs.start_object = _child_text(el, "object")+ refs.trigger_type = _child_text(el, "triggerType")+ elif tag == "orchestratedStages":+ refs.flows.extend(_stage_step_flows(el))+ for sub in el.iter():+ sub_tag = _local(sub.tag)+ text = (sub.text or "").strip()+ if sub_tag == "extensionName" and text:+ refs.components.append(text)+ elif sub_tag == "apexClass" and text:+ refs.apex_types.append(text)+++def _read_action(refs: FlowRefs, el: ET.Element) -> None:+ name = _child_text(el, "actionName")+ if not name:+ return+ target = {+ "apex": refs.apex_actions,+ "flow": refs.flows,+ # A local action: an Aura bundle (``c:showToast``) the flow runs.+ "component": refs.components,+ }.get(_child_text(el, "actionType").lower())+ if target is not None:+ target.append(name)+++def _stage_step_flows(stage: ET.Element) -> list[str]:+ """The flows an Orchestrator stage's steps run."""+ return [+ name+ for step in stage.iter()+ if _local(step.tag) == "stageSteps"+ and _child_text(step, "actionType").lower() in _STEP_ACTION_TYPES+ and (name := _child_text(step, "actionName"))+ ]+++def read_flow(source: bytes) -> FlowRefs | None:+ """The names *source* reaches, or None when it is not a well-formed ``<Flow>``."""+ try:+ root = ET.fromstring(source)+ except ET.ParseError:+ return None+ if _local(root.tag) != "Flow":+ return None+ refs = FlowRefs(+ process_type=_child_text(root, "processType"),+ label=_child_text(root, "label"),+ description=_child_text(root, "description"),+ )+ for el in root:+ _read_element(refs, el)+ return refs+++def _signature(name: str, refs: FlowRefs) -> str:+ detail = [refs.process_type] if refs.process_type else []+ if refs.start_object:+ # The object is kept here until SObject metadata symbols can take an edge.+ trigger = refs.trigger_type or "triggered"+ detail.append(f"{trigger} on {refs.start_object}")+ return f"flow {name}" + (f" ({', '.join(detail)})" if detail else "")+++def parse_flow_file(file_info: FileInfo, source: bytes) -> ParsedFile:+ """One function-kind symbol for the flow, named by its API name."""+ refs = read_flow(source)+ if refs is None:+ return ParsedFile(+ file_info=file_info,+ symbols=[],+ imports=[],+ exports=[],+ docstring=None,+ parse_errors=["not a well-formed <Flow> document"],+ )+ name = flow_api_name(file_info.path)+ line_count = source.count(b"\n") + 1+ symbol = Symbol(+ id=f"{file_info.path}::{name}",+ name=name,+ qualified_name=name,+ kind="function",+ signature=_signature(name, refs),+ start_line=1,+ end_line=line_count,+ docstring=refs.description or refs.label or None,+ visibility="public",+ language="salesforce_flow",+ )+ return ParsedFile(+ file_info=file_info,+ symbols=[symbol],+ imports=[],+ exports=[name],+ docstring=refs.label or None,+ parse_errors=[],+ )diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.pyindex 64d453424..e1f9e8db8 100644--- a/packages/core/src/repowise/core/ingestion/special_handlers.py+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py@@ -18,13 +18,16 @@ from pathlib import Pathimport structlogfrom .models import FileInfo, Import, ParsedFile, Symbol+from .salesforce_flow import parse_flow_filelog = structlog.get_logger(__name__)# Language tags routed to parse_special by the parser. Kept here, next to# the handler table, so the two can't drift apart.-SPECIAL_HANDLER_LANGUAGES = frozenset({"openapi", "dockerfile", "makefile", "sql"})+SPECIAL_HANDLER_LANGUAGES = frozenset(+ {"openapi", "dockerfile", "makefile", "sql", "salesforce_flow"}+)# ---------------------------------------------------------------------------@@ -39,6 +42,7 @@ def parse_special(file_info: FileInfo, source: bytes, lang: str) -> ParsedFile:"dockerfile": _parse_dockerfile,"makefile": _parse_makefile,"sql": _parse_sql,+ "salesforce_flow": parse_flow_file,}.get(lang, _parse_unknown)try:return handler(file_info, source)diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex 2f762853e..e54e75f9f 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -54,8 +54,10 @@ from ..test_paths import is_test_related_pathfrom .languages.registry import REGISTRY as _LANG_REGISTRYfrom .languages.specs.aura import is_aura_markup_pathfrom .languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS+from .languages.specs.salesforce_flow import is_legacy_flow_pathfrom .models import (EXTENSION_TO_LANGUAGE,+ NAME_SUFFIX_TO_LANGUAGE,SPECIAL_FILENAMES,FileInfo,LanguageTag,@@ -1039,14 +1041,28 @@ def _language_from_name_or_ext(abs_path: Path) -> LanguageTag | None:filename = abs_path.nameif filename in SPECIAL_FILENAMES:return SPECIAL_FILENAMES[filename]- language = EXTENSION_TO_LANGUAGE.get(abs_path.suffix.lower())+ language = _language_from_name_suffix(filename) or 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"+ # ``.flow`` is also Flow's ``.js.flow``: a legacy Salesforce flow routes by its directory.+ if language is None and is_legacy_flow_path(abs_path.as_posix()):+ return "salesforce_flow"return language+def _language_from_name_suffix(filename: str) -> LanguageTag | None:+ """The language a multi-dot name ending (``.flow-meta.xml``) claims, if any."""+ lowered = filename.lower()+ for suffix, tag in NAME_SUFFIX_TO_LANGUAGE.items():+ if lowered.endswith(suffix):+ return tag+ return None++# A declaration or an import that opens its own line, matched after comments# are blanked because ``@interface`` is also a Doxygen command. ``#import``# covers umbrella headers, which declare nothing themselves.@@ -1805,7 +1821,7 @@ def is_candidate_source_path(return Falsename = parts[-1]- if name in SPECIAL_FILENAMES:+ if name in SPECIAL_FILENAMES or _language_from_name_suffix(name) or is_legacy_flow_path(posix):return Truesuffix = Path(name).suffix.lower()diff --git a/tests/unit/ingestion/test_salesforce_flow_edges.py b/tests/unit/ingestion/test_salesforce_flow_edges.pynew file mode 100644index 000000000..447fe9268--- /dev/null+++ b/tests/unit/ingestion/test_salesforce_flow_edges.py@@ -0,0 +1,271 @@+"""Salesforce flows and placement metadata: flow symbols, their edges, and liveness.++The end-to-end cases go 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+from repowise.core.ingestion.salesforce_flow import flow_api_name, read_flow++_D = "force-app/main/default"+_NS = 'xmlns="http://soap.sforce.com/2006/04/metadata"'+++def _flow(body: str) -> str:+ return f'<?xml version="1.0" encoding="UTF-8"?>\n<Flow {_NS}>\n{body}</Flow>\n'+++_MAIN_FLOW = _flow(+ " <actionCalls><name>Go</name><actionName>acme__Mailer</actionName>"+ "<actionType>apex</actionType></actionCalls>\n"+ " <actionCalls><name>Ext</name><actionName>other__Mailer</actionName>"+ "<actionType>apex</actionType></actionCalls>\n"+ " <actionCalls><name>Mail</name><actionName>emailSimple</actionName>"+ "<actionType>emailSimple</actionType></actionCalls>\n"+ " <apexPluginCalls><name>P</name><apexClass>LegacyPlugin</apexClass></apexPluginCalls>\n"+ " <!-- <subflows><flowName>Ghost</flowName></subflows> -->\n"+ " <subflows><name>S</name><flowName>child_flow</flowName></subflows>\n"+ " <processType>Flow</processType>\n"+ " <screens><name>Scr</name><fields><name>F</name>"+ "<extensionName>c:pickerLwc</extensionName><fieldType>ComponentInstance</fieldType></fields>"+ "<fields><name>G</name><extensionName>c:legacyAura</extensionName></fields>"+ "<fields><name>M</name><extensionName>c:markupAura</extensionName></fields>"+ "<fields><name>H</name><extensionName>flowruntime:fileUpload</extensionName></fields>"+ "</screens>\n"+ " <start><object>Account</object><triggerType>RecordAfterSave</triggerType></start>\n"+ " <variables><name>w</name><dataType>Apex</dataType><apexClass>Wrapper</apexClass></variables>\n"+)++_APP = {+ "sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "acme"}\n',+ f"{_D}/flows/Main_Flow.flow-meta.xml": _MAIN_FLOW,+ f"{_D}/flows/Child_Flow.flow-meta.xml": _flow(" <processType>AutoLaunchedFlow</processType>\n"),+ f"{_D}/classes/Mailer.cls": (+ "public with sharing class Mailer {\n"+ " @InvocableMethod(label='Send')\n"+ " public static void send(List<Id> ids) {}\n"+ " public static void helper() {}\n"+ "}\n"+ ),+ f"{_D}/classes/LegacyPlugin.cls": "global class LegacyPlugin implements Process.Plugin {}\n",+ f"{_D}/classes/Wrapper.cls": "public class Wrapper { @AuraEnabled public String name; }\n",+ f"{_D}/classes/Launcher.cls": (+ "public class Launcher {\n"+ " public void run(Map<String, Object> m) {\n"+ " Flow.Interview.Child_Flow f = new Flow.Interview.Child_Flow(m);\n"+ " // Flow.Interview.Main_Flow is only a comment\n"+ " Flow.Interview.createInterview('Main_Flow', m).start();\n"+ " }\n"+ "}\n"+ ),+ f"{_D}/flows/Quoted_Flow.flow-meta.xml": _flow(" <processType>Flow</processType>\n"),+ f"{_D}/classes/Quoter.cls": (+ "public class Quoter {\n"+ " public String text() {\n"+ " return 'Flow.Interview.createInterview(\\'Quoted_Flow\\', m)'\n"+ " + ' new Flow.Interview.Quoted_Flow(m)';\n"+ " }\n"+ "}\n"+ ),+ f"{_D}/classes/InboundHandler.cls": (+ "global class InboundHandler implements Messaging.InboundEmailHandler {}\n"+ ),+ f"{_D}/emailservices/Inbound.xml-meta.xml": (+ f"<EmailServicesFunction {_NS}><apexClass>InboundHandler</apexClass></EmailServicesFunction>\n"+ ),+ f"{_D}/permissionsets/All.permissionset-meta.xml": (+ f"<PermissionSet {_NS}><classAccesses><apexClass>Launcher</apexClass>"+ "</classAccesses></PermissionSet>\n"+ ),+ f"{_D}/lwc/pickerLwc/pickerLwc.js": (+ "import { LightningElement } from 'lwc';\nexport default class PickerLwc extends LightningElement {}\n"+ ),+ f"{_D}/lwc/host/host.js": (+ "import { LightningElement } from 'lwc';\nexport default class Host extends LightningElement {}\n"+ ),+ f"{_D}/lwc/host/host.html": (+ '<template><lightning-flow flow-api-name="Child_Flow"></lightning-flow>'+ "<lightning-flow flow-api-name={dynamicName}></lightning-flow></template>\n"+ ),+ f"{_D}/lwc/onPage/onPage.js": (+ "import { LightningElement } from 'lwc';\nexport default class OnPage extends LightningElement {}\n"+ ),+ f"{_D}/lwc/onTab/onTab.js": (+ "import { LightningElement } from 'lwc';\nexport default class OnTab extends LightningElement {}\n"+ ),+ f"{_D}/lwc/onAction/onAction.js": (+ "import { LightningElement } from 'lwc';\nexport default class OnAction extends LightningElement {}\n"+ ),+ f"{_D}/lwc/onSite/onSite.js": (+ "import { LightningElement } from 'lwc';\nexport default class OnSite extends LightningElement {}\n"+ ),+ f"{_D}/lwc/orphan/orphan.js": (+ "import { LightningElement } from 'lwc';\nexport default class Orphan extends LightningElement {}\n"+ ),+ f"{_D}/aura/legacyAura/legacyAuraController.js": "({ init: function (c, e, h) {} })\n",+ f"{_D}/aura/markupAura/markupAura.cmp": (+ '<aura:component implements="lightning:availableForFlowScreens"/>\n'+ ),+ f"{_D}/aura/markupAura/markupAuraController.js": "({ init: function (c, e, h) {} })\n",+ f"{_D}/flexipages/Home.flexipage-meta.xml": (+ f"<FlexiPage {_NS}><flexiPageRegions><itemInstances><componentInstance>"+ "<componentName>acme:onPage</componentName></componentInstance>"+ "<componentInstance><componentName>force:detailPanel</componentName></componentInstance>"+ "</itemInstances></flexiPageRegions></FlexiPage>\n"+ ),+ f"{_D}/tabs/On_Tab.tab-meta.xml": f"<CustomTab {_NS}><lwcComponent>onTab</lwcComponent></CustomTab>\n",+ f"{_D}/quickActions/Account.Do.quickAction-meta.xml": (+ f"<QuickAction {_NS}><lightningWebComponent>onAction</lightningWebComponent>"+ "<type>LightningWebComponent</type></QuickAction>\n"+ ),+ "site/experiences/portal1/views/home.json": (+ '{"components": [{"definition": "c:onSite"}, {"definition": "forceCommunity:tabset"}]}\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 _graph(repo: Path) -> tuple[object, set[tuple[str, str]]]:+ 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([])+ report = DeadCodeAnalyzer(+ builder.graph(), {}, parsed_files=builder._parsed_files, source_map=source_map, repo_root=repo+ ).analyze({"detect_unused_internals": True})+ dead = {(f.kind.value, f.file_path) for f in report.findings}+ return builder.graph(), dead+++def test_flow_api_name_drops_the_suffix_and_a_legacy_version() -> None:+ assert flow_api_name("a/flows/My_Flow.flow-meta.xml") == "My_Flow"+ assert flow_api_name("src/flows/churn-3.flow") == "churn"+++def test_read_flow_collects_names_and_skips_comments() -> None:+ refs = read_flow(_MAIN_FLOW.encode())+ assert refs is not None+ assert refs.apex_actions == ["acme__Mailer", "other__Mailer", "LegacyPlugin"]+ assert refs.flows == ["child_flow"]+ assert refs.components == [+ "c:pickerLwc", "c:legacyAura", "c:markupAura", "flowruntime:fileUpload"+ ] # fmt: skip+ assert refs.apex_types == ["Wrapper"]+ assert (refs.start_object, refs.trigger_type, refs.process_type) == (+ "Account", "RecordAfterSave", "Flow"+ ) # fmt: skip+ assert read_flow(b"<CustomObject/>") is None+ assert read_flow(b"<Flow><broken") is None+++def test_flows_are_symbols_linked_to_apex_flows_and_components(tmp_path: Path) -> None:+ repo = _write(tmp_path, _APP)+ graph, dead = _graph(repo)+ main = f"{_D}/flows/Main_Flow.flow-meta.xml"+ child = f"{_D}/flows/Child_Flow.flow-meta.xml"+ cls = f"{_D}/classes"+ lwc = f"{_D}/lwc"++ node = graph.nodes[f"{main}::Main_Flow"]+ assert node["language"] == "salesforce_flow"+ assert node["signature"] == "flow Main_Flow (Flow, RecordAfterSave on Account)"++ def edge(s: str, t: str) -> str | None:+ data = graph.get_edge_data(s, t)+ return data["edge_type"] if data else None++ # Apex action: file edge, and the flow binds the one @InvocableMethod.+ assert edge(main, f"{cls}/Mailer.cls") == "framework"+ assert edge(f"{main}::Main_Flow", f"{cls}/Mailer.cls::Mailer::send") == "framework_binds"+ # A plugin class with no invocable method binds the class itself.+ assert edge(f"{main}::Main_Flow", f"{cls}/LegacyPlugin.cls::LegacyPlugin") == "framework_binds"+ assert edge(main, f"{cls}/Wrapper.cls") == "framework"+ # Subflow: names fold case.+ assert edge(main, child) == "framework"+ assert edge(f"{main}::Main_Flow", f"{child}::Child_Flow") == "framework_binds"+ # Screen components: LWC main module; Aura controller while its markup is unindexed.+ assert edge(main, f"{lwc}/pickerLwc/pickerLwc.js") == "framework"+ assert edge(main, f"{_D}/aura/legacyAura/legacyAuraController.js") == "framework"+ # With its markup indexed, an Aura bundle is reached at the .cmp.+ assert edge(main, f"{_D}/aura/markupAura/markupAura.cmp") == "framework"++ # Apex names flows by static type and by literal; a comment does not count.+ launcher = f"{cls}/Launcher.cls"+ assert edge(f"{launcher}::Launcher::run", f"{child}::Child_Flow") == "framework_binds"+ assert edge(f"{launcher}::Launcher::run", f"{main}::Main_Flow") == "framework_binds"+ # A call written inside a string literal names nothing.+ quoted = f"{_D}/flows/Quoted_Flow.flow-meta.xml"+ assert not {t for _, t in graph.out_edges(f"{cls}/Quoter.cls")} & {quoted}+ assert not [s for s, _ in graph.in_edges(f"{quoted}::Quoted_Flow") if "Quoter" in s]+ # LWC <lightning-flow>, literal names only.+ assert edge(f"{lwc}/host/host.html", child) == "framework"+ targets = {t for _, t in graph.out_edges(f"{lwc}/host/host.html")}+ assert main not in targets++ # Placement metadata anchors what it names, and nothing it merely grants.+ anchored = {t for _, t in graph.out_edges("framework:salesforce")}+ assert anchored == {+ f"{lwc}/onPage/onPage.js",+ f"{lwc}/onTab/onTab.js",+ f"{lwc}/onAction/onAction.js",+ f"{lwc}/onSite/onSite.js",+ f"{cls}/InboundHandler.cls",+ }+ assert graph.nodes[f"{lwc}/onPage/onPage.js"]["is_entry_point"] is True++ unreachable = {p for kind, p in dead if kind == "unreachable_file"}+ assert f"{lwc}/orphan/orphan.js" in unreachable+ for live in ("pickerLwc/pickerLwc.js", "onPage/onPage.js", "onTab/onTab.js", "onSite/onSite.js"):+ assert f"{lwc}/{live}" not in unreachable+ # Flows are placed by the org and never reported.+ assert not {p for _, p in dead if "/flows/" in p}+++def test_a_legacy_flow_routes_by_directory_and_js_flow_does_not(tmp_path: Path) -> None:+ repo = _write(tmp_path, {+ "src/flows/Old_Flow-2.flow": _flow(" <processType>Flow</processType>\n"),+ "lib/types/index.js.flow": "// @flow\nexport type T = string;\n",+ "src/flows/types.js.flow": "// @flow\nexport type T = string;\n",+ }) # fmt: skip+ langs = {fi.path: fi.language for fi in FileTraverser(repo).traverse()}+ assert langs == {"src/flows/Old_Flow-2.flow": "salesforce_flow"}+ graph, _ = _graph(repo)+ assert "src/flows/Old_Flow-2.flow::Old_Flow" in graph+++def test_a_name_in_two_projects_binds_to_the_nearest_and_refuses_a_tie(tmp_path: Path) -> None:+ flow = _flow(+ " <actionCalls><name>A</name><actionName>Shared</actionName>"+ "<actionType>apex</actionType></actionCalls>\n"+ )+ cls = "public class Shared { @InvocableMethod public static void go(List<Id> x) {} }\n"+ repo = _write(tmp_path, {+ "one/force-app/flows/F.flow-meta.xml": flow,+ "one/force-app/classes/Shared.cls": cls,+ "two/force-app/classes/Shared.cls": cls,+ "top/flows/G.flow-meta.xml": flow,+ }) # fmt: skip+ graph, _ = _graph(repo)+ assert graph.has_edge("one/force-app/flows/F.flow-meta.xml", "one/force-app/classes/Shared.cls")+ assert not graph.has_edge("one/force-app/flows/F.flow-meta.xml", "two/force-app/classes/Shared.cls")+ assert not any(+ t.endswith("Shared.cls") for _, t in graph.out_edges("top/flows/G.flow-meta.xml")+ )