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): markup and flows reach Apex by the sfdx project rules, and record-triggered flows link their object (#4441)

Raghav Chamadiya2ce0bd163b0c
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 5af0ccfa9..41610f774 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -930,18 +930,12 @@ 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.
+Markup directly inside `aura/<bundle>/` is Aura, and each `key: function` of the
+bundle's Controller, Helper and Renderer JavaScript is a function symbol. Markup
+and JavaScript link to the Apex controller and its methods, to controller and helper
+functions (inherited through `extends`), and to the Aura or LWC bundles that tags,
+events and `$A.createComponent` literals name. Aura names match by exact case, and a
+name with two candidate bundles binds to neither.
### VB.NET
@@ -961,13 +955,10 @@ arguments, and some multi-line LINQ layouts, each recovered from locally.
### Apex
-The grammar is the language pack's `apex`, loaded as COBOL's is. It keeps
-Java's node and field names, so `apex.scm`, heritage and type heads follow Java;
-inline SOQL/SOSL and DML are their own nodes and never produce call sites.
-Keywords and type names are case-insensitive: visibility and heritage read the
-AST rather than keyword text, and builtin types are compared folded, while
-declared names keep their written case. CumulusCI `%%%NAMESPACE%%%` tokens are
-blanked byte for byte before parsing.
+The language pack's `apex` grammar keeps Java's node names, so queries, heritage
+and type heads follow Java; inline SOQL/SOSL and DML never produce call sites.
+Keywords and builtin types compare case-insensitively, declared names keep their
+written case, and CumulusCI `%%%NAMESPACE%%%` tokens are blanked before parsing.
Apex has no imports, so a type name resolves to the top-level class its own
sfdx project declares, compared without case, then to an un-namespaced package
@@ -977,6 +968,13 @@ inner-class, typed, chained, inherited and `super` calls follow Java's tiers,
and a bare name never reaches another class's method. Ceiling: a call site does
not record `new`, so a constructor written in lower case is missed.
+LWC, Aura, Visualforce and flows reach Apex classes by the same rules from the
+project they sit in, and also reach a class that exactly one other, un-namespaced
+project declares: they name action classes of packages installed separately in the
+same org. A name two projects declare binds nothing. Ceiling: two copies outside
+every package directory of one project (an mdapi export) tie and bind nothing, as
+they do for Apex.
+
A `@RestResource` class's `@Http*` methods are HTTP providers at
`/services/apexrest` plus its `urlMapping`, and are entry points in the graph.
An `HttpRequest` callout is a consumer when its endpoint and verb are literal
@@ -1003,16 +1001,10 @@ literal-bound loops) and on calls that run once, such as a lazily filled cache.
Ceiling: `while` loops, `Database.executeBatch` and `System.schedule` are not
reported, and untested complexity needs measured coverage or a test the graph sees.
-Extract Method reads Apex as Java plus its own rules: names are
-case-insensitive, inline SOQL reads only its `:bind` expressions, and
-`switch on ... when` arms and `System.runAs` blocks are understood. Helpers are
-written as Apex methods, static when the host method is. A `break` or
-`continue` inside a `when` arm is modelled conservatively, as a read of the
-loop's names at the switch.
-
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
+subflows, screen components and Apex-defined types it names, and a
+record-triggered flow references its object's metadata symbol. 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
@@ -1034,7 +1026,7 @@ to a public member (property, `getX`, or `setX` for inputs) of the controller,
then each extension, up the `extends` chain. Custom component tags, included
pages and Apex `Page.X` references link pages and components; a
`PageReference('/apex/X')` literal is a `dynamic_uses` edge. Names fold case,
-and a name two equally near files declare binds nothing.
+and a page or component two equally near files declare binds nothing.
### QML
@@ -1064,7 +1056,7 @@ Inside an `lwc/<name>/` bundle, `c/<name>` imports resolve to that bundle's
main module and `@salesforce/apex/Cls.method` imports to the Apex method.
Templates link to child components by tag and to their own class's members by
`{binding}`, `@wire` binds its Apex method, and an exposed bundle is an entry
-point. A name two sfdx projects declare goes to the nearer one; a tie gets no edge.
+point. A bundle two sfdx projects declare goes to the nearer one; a tie gets no edge.
### Known gaps per language
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 7da9c340b..d02a0a73b 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -83,7 +83,7 @@ findings are review-only. Apex test coverage from the Salesforce CLI is read as
coverage report ([formats](TEST_INTELLIGENCE.md#supported-formats)). Health covers Apex
complexity, class cohesion, and SOQL, DML and callouts inside loops.
Salesforce flows (`.flow-meta.xml`) are one symbol each, linked to the Apex
-invocable actions, subflows and screen components they name.
+invocable actions, subflows, screen components and triggering objects they name.
Salesforce object and field metadata become symbols that Apex SOQL, DML and
triggers reference.
@@ -255,7 +255,6 @@ This table is why a language is Full and not Good.
- Dart, F# and Objective-C report class size, method count and CCN (supporting
detectors like God Class), but do not compute cohesion metrics (LCOM4).
- An unmapped language produces no findings, never guessed ones.
-- Apex has Extract Method: helpers are written as Apex methods, static where the host is.
- The two test-quality markers (mock saturation, assertion-free test) are
advisory and never deduct from a score.
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 1c8203ad1..75896ae06 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
@@ -195,10 +195,7 @@ 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.
+ # The Lightning runtime loads a whole Aura bundle, so an uncalled function may be load-bearing.
if aura_bundle(norm) is not None:
factors.add("aura")
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/aura.py b/packages/core/src/repowise/core/ingestion/framework_edges/aura.py
index e4759aebb..e9f488d17 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/aura.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/aura.py
@@ -1,53 +1,34 @@
"""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.
+An Aura bundle ``aura/<name>/`` (markup plus ``<name>Controller.js``,
+``Helper.js``, ``Renderer.js``) is wired by name, not imports. Edges:
+
+* ``controller="Cls"`` -> the Apex class; ``get("c.m")`` in bundle JS -> its
+ method ``m``, or the Controller.js function when the class has none.
+* ``{!c.h}`` and other ``"c.h"`` literals -> Controller.js functions;
+ ``helper.x(`` -> Helper.js functions. Both inherit through ``extends``.
+* Own-namespace ``<c:X>``, ``extends``, ``implements`` and event types -> the
+ Aura bundle ``X``, else the LWC bundle; ``$A.createComponent(s)`` literals
+ -> ``dynamic_uses``.
+
+Aura names match by exact case; Apex names fold case and follow the Apex reach
+rules (``languages.apex_namespace``). A name with two candidates binds neither.
+An ``.app`` and a component implementing a placement interface are entry
+points, and a Renderer's overrides are bound from the markup.
"""
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.apex_namespace import apex_namespaces
from ..languages.specs.aura import aura_bundle
-from ..type_names import bare_type_name, type_qualifier
+from ..resolvers.lwc import lwc_namespaces, nearest
+from ..type_names import bare_type_name
from .base import (
DetectionContext,
FrameworkHandler,
@@ -73,24 +54,18 @@ _JS_COMMENT_OR_STRING_RE = re.compile(
_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.
+# Formatters reflow `{!c.h}` and append a `;`. Ceiling: `{!v.x ? c.a : c.b}` is not read.
_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.
+# Inside a helper, `this` is the (inherited) helper object.
_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.
+# Interfaces that let an admin place the component without any source naming it.
_ENTRY_INTERFACE_PREFIXES = ("flexipage:", "forcecommunity:", "lightningsnapin:")
_ENTRY_INTERFACES = frozenset(
{
@@ -168,30 +143,15 @@ def _call_span_end(text: str, open_paren: int) -> int:
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.own_ns = lwc_namespaces(ctx)
+ self.apex = apex_namespaces(ctx)
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]] = {}
@@ -202,12 +162,6 @@ class _AuraIndex:
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
@@ -252,18 +206,15 @@ class _AuraIndex:
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, []))
+ return nearest(mains + self.lwc_by_name.get(name, []), src)
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(), []))
+ """The Apex file of ``controller="[ns.]Cls"`` written in *src*."""
+ return self.apex.referred_file(src, written)
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, []))
+ return nearest(self.aura_by_name.get(name, []), src)
def chain(self, bdir: str) -> list[str]:
"""The bundle and the bundles it ``extends``, nearest first.
@@ -356,30 +307,6 @@ class _AuraIndex:
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:
@@ -467,9 +394,7 @@ def _root_edges(idx: _AuraIndex, bdir: str, main: str, edges: _Edges) -> None:
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.
+ # The framework calls these: renderer overrides and interface-named controller functions.
module = f"{main}::__module__"
platform = {
m
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py b/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py
index bf7fbc29a..9cab6b5f4 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/lwc.py
@@ -140,10 +140,7 @@ def _template_edges(graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: Resolv
def _apex_method(apex: Any, cls: str, method: str) -> str | None:
- """The id of *cls*.*method* in a parsed Apex file, matched case-insensitively.
-
- Ceiling: a local lookup; use a shared case-insensitive Apex index once one exists.
- """
+ """The id of *cls*.*method* in a parsed Apex file, matched case-insensitively."""
cls, method = cls.lower(), method.lower()
found = [
s
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.py
index c60adfe47..fed3fcbd0 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/salesforce_metadata.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/salesforce_metadata.py
@@ -10,8 +10,9 @@ 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.
+Apex and flow names fold case; component names match exactly. An Apex class is
+one an Apex file of the referrer's sfdx project reaches; a flow or component
+two projects declare binds to the nearest by path, and to none on a tie.
"""
from __future__ import annotations
@@ -24,6 +25,8 @@ from typing import TYPE_CHECKING, Any
from repowise.core.fs_walk import glob_via
from ..framework_facts import SALESFORCE
+from ..languages.apex_namespace import apex_namespaces
+from ..resolvers.lwc import lwc_bundles, nearest
from ..salesforce_flow import FlowRefs, read_flow
from ..type_names import bare_type_name, type_qualifier
from .base import (
@@ -91,53 +94,26 @@ def _mask(text: str, pattern: re.Pattern[str], keep: str = "") -> str:
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.apex = apex_namespaces(ctx)
self.flows: dict[str, list[str]] = {} # lowercased API name -> flow paths
- self.lwc: dict[str, list[str]] = {} # bundle name -> main module
+ self.lwc = lwc_bundles(ctx) # bundle name -> main modules
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:
+ if 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
+ elif len(p.parts) >= 3 and 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
@@ -166,16 +142,19 @@ class _Index:
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
+ m = _NS_UU_RE.match(raw.strip())
+ found = self.apex.referred_file(referrer, f"{m.group(1)}.{m.group(2)}" if m else raw)
+ prefix, name = (m.group(1), m.group(2)) if m else (type_qualifier(raw), bare_type_name(raw))
+ # A namespace only cumulusci.yml declares is still this repository's own.
+ if found is None and prefix and prefix.lower() in self.own_ns:
+ found = self.apex.referred_file(referrer, name)
+ return found
# 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
+ return nearest(self.flows.get(name.lower(), []), referrer) if name 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."""
@@ -187,7 +166,7 @@ class _Index:
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))
+ 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:
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py b/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py
index acc60da67..93bea7799 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/visualforce.py
@@ -9,7 +9,8 @@
Apex ``Page.X`` -> the page, a ``PageReference('/apex/X')`` literal as
``dynamic_uses``.
-Names fold case; two equally near candidates bind neither. Pages are entry points.
+Names fold case; Apex classes are those an Apex file of the same sfdx project
+reaches, and two equally near pages or components bind neither. Pages are entry points.
"""
from __future__ import annotations
@@ -19,9 +20,11 @@ from pathlib import PurePosixPath
from typing import TYPE_CHECKING, Any
from ...analysis.security_scan import mask_comments_and_strings
+from ..languages.apex_namespace import apex_namespaces
+from ..resolvers.lwc import lwc_namespaces, nearest
from ..return_types import signature_parameter_count
-from ..type_names import bare_type_name, type_qualifier
-from .aura import _file_edge, _mask_xml, _nearest, _own_namespaces
+from ..type_names import bare_type_name
+from .aura import _file_edge, _mask_xml
from .base import DetectionContext, FrameworkHandler, add_symbol_edge, source_text
if TYPE_CHECKING:
@@ -60,18 +63,6 @@ def _attrs(blob: str) -> dict[str, str]:
}
-def _apex_class_files(parsed_files: dict[str, Any]) -> dict[str, list[str]]:
- """Lowercased Apex class name -> its ``.cls`` files.
-
- Ceiling: local index; replace with the Apex resolution pass's class index when it lands.
- """
- out: dict[str, list[str]] = {}
- for path in sorted(parsed_files):
- if parsed_files[path].file_info.language == "apex" and path.lower().endswith(".cls"):
- out.setdefault(PurePosixPath(path).stem.lower(), []).append(path)
- return out
-
-
class _VfIndex:
def __init__(
self, graph: nx.DiGraph, parsed_files: dict[str, Any], ctx: ResolverContext
@@ -79,8 +70,10 @@ class _VfIndex:
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.apex = _apex_class_files(parsed_files)
+ self.own_ns = lwc_namespaces(ctx)
+ self.apex = apex_namespaces(ctx)
+ # A repository class named Page would shadow the platform's.
+ self.shadows_page = any(name == "page" for _, name in self.apex.top_level)
self.pages: dict[str, list[str]] = {}
self.components: dict[str, list[str]] = {}
for path in sorted(parsed_files):
@@ -103,19 +96,15 @@ class _VfIndex:
def page(self, written: str, src: str) -> str | None:
name = self._own_name(written)
- return _nearest(src, self.pages.get(name.lower(), [])) if name else None
+ return nearest(self.pages.get(name.lower(), []), src) if name else None
def component(self, name: str, src: str) -> str | None:
- return _nearest(src, self.components.get(name.lower(), []))
+ return nearest(self.components.get(name.lower(), []), src)
def apex_class(self, written: str, src: str) -> tuple[str, str] | None:
- """``(class file, class name)`` for ``[ns.]Cls`` written in *src*, own namespace only."""
- written = written.strip()
- head, tail = type_qualifier(written), bare_type_name(written)
- if not tail or (head and head.lower() not in self.own_ns):
- return None
- path = _nearest(src, self.apex.get(tail.lower(), []))
- return (path, tail) if path else None
+ """``(class file, class name)`` for ``[ns.]Cls`` written in *src*."""
+ path = self.apex.referred_file(src, written)
+ return (path, bare_type_name(written)) if path else None
def chain(self, cls_file: str, cls: str) -> list[tuple[str, str]]:
"""The class and its ``extends`` ancestors the repository declares, nearest first."""
@@ -340,8 +329,7 @@ def _bind_member(
def _apex_edges(idx: _VfIndex, path: str, edges: _Edges) -> None:
raw = idx.text(path)
- # A repository class named Page would shadow the platform's.
- if "page" not in idx.apex:
+ if not idx.shadows_page:
code = mask_comments_and_strings(raw, hash_comments=False)
for m in _APEX_PAGE_RE.finditer(code):
target = idx.page(m.group(1), path)
diff --git a/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py b/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py
index 057d27c03..10816f00d 100644
--- a/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py
+++ b/packages/core/src/repowise/core/ingestion/lang_helpers/source_prep.py
@@ -119,9 +119,7 @@ def prepare_objectivec_source(source: bytes) -> bytes:
return _blank_objc_trailing_macros(_blank_matches(source, _OBJC_BARE_MACRO_LINE_RE))
-# CumulusCI namespace-injection tokens (``%%%NAMESPACE%%%``,
-# ``%%%NAMESPACE_DOT%%%``) that the build rewrites before deploy. The source
-# is not Apex until then, and the grammar errors on them.
+# CumulusCI ``%%%NAMESPACE%%%`` tokens, rewritten at deploy; the grammar errors on them.
_APEX_NAMESPACE_TOKEN_RE = re.compile(rb"%%%[A-Z_]+%%%")
diff --git a/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
index fa3c19f5f..b42d4aef1 100644
--- a/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
+++ b/packages/core/src/repowise/core/ingestion/languages/apex_namespace.py
@@ -12,7 +12,10 @@ projects (LightningFlowComponents ships 192) declares the same class name in
several of them, and a name is looked up in the caller's own project, then in
the un-namespaced packages it declares a dependency on. A namespace prefix
(``npsp.Foo``, ``usf3.Foo``) names the repo project of that namespace; any
-other prefix names a managed package's class. A
+other prefix names a managed package's class. Markup and metadata (LWC, Aura,
+Visualforce, flows) reach Apex by the same rules from the project they sit in,
+then any class exactly one un-namespaced project declares: they name action
+classes of packages installed separately in the same org. A
project may also keep a second copy of its classes outside its package
directories (a legacy ``mdapi/`` export); a name declared in both is read in the
copy the caller is deployed with.
@@ -29,12 +32,12 @@ import json
import re
from collections import defaultdict
from collections.abc import Iterable
-from dataclasses import dataclass, replace
+from dataclasses import dataclass, field, replace
from pathlib import Path, PurePosixPath
from typing import Any
from ..symbol_identity import outer_scope, symbol_id_path
-from ..type_names import bare_type_name, dotted_type_segments
+from ..type_names import bare_type_name, dotted_type_segments, type_qualifier
_SFDX_PROJECT = "sfdx-project.json"
_TYPE_KINDS = frozenset({"class", "interface", "enum"})
@@ -66,9 +69,50 @@ class ApexNamespaces:
dependencies: dict[str, tuple[str, ...]]
#: lowercased namespace -> the projects declaring it.
by_namespace: dict[str, tuple[str, ...]]
+ #: lowercased top-level type name -> the projects declaring it.
+ declarers: dict[str, tuple[str, ...]] = field(default_factory=dict)
+ #: Places files the index was not built over (markup, metadata).
+ finder: _ProjectFinder = field(default_factory=lambda: _ProjectFinder(), compare=False)
+ #: Non-Apex file -> its project, as placed so far.
+ placed: dict[str, str] = field(default_factory=dict, compare=False)
def top_level_type(self, file_path: str, name: str) -> str | None:
- """The one top-level type *name* means from *file_path*, or None.
+ """The one top-level type *name* means from Apex file *file_path*, or None."""
+ project = self.project_of.get(file_path)
+ return None if project is None else self._top_level(project, file_path, name)
+
+ def referred_file(self, path: str, written: str) -> str | None:
+ """The file of the top-level type ``[ns.]Name`` means from any repo file.
+
+ *path* belongs to the project whose ``sfdx-project.json`` is nearest
+ above it; ``c.`` names that project, like no prefix. A non-Apex file
+ reaches what an Apex file there would, else a name its project does not
+ declare and exactly one un-namespaced project does.
+ """
+ project = self._place(path)
+ prefix, name = type_qualifier(written), bare_type_name(written)
+ if project is None or not name:
+ return None
+ if prefix and prefix.lower() != "c":
+ found = self._prefixed(project, path, prefix, name)
+ else:
+ found = self._top_level(project, path, name)
+ if found is None and path not in self.project_of:
+ found = self._unique_elsewhere(project, name)
+ return symbol_id_path(found) if found else None
+
+ def _unique_elsewhere(self, project: str, name: str) -> str | None:
+ """The one type *name* names when one other, un-namespaced project declares it once."""
+ declarers = self.declarers.get(name.lower(), ())
+ if len(declarers) != 1 or declarers[0] == project:
+ return None
+ if self.manifests[declarers[0]].namespace:
+ return None
+ found = self._declared(declarers[0], name)
+ return found[0] if len(found) == 1 else None
+
+ def _top_level(self, project: str, file_path: str, name: str) -> str | None:
+ """The one top-level type *name* means from *file_path* in *project*, or None.
Looked up in the caller's own project, else in the un-namespaced
projects it declares a dependency on (a namespaced one is reached only
@@ -77,9 +121,6 @@ class ApexNamespaces:
package directory, or outside them all for a caller outside them. Any
other pair is a tie, and neither is chosen.
"""
- project = self.project_of.get(file_path)
- if project is None:
- return None
if (project, name.lower()) in self.top_level:
found = self._declared(project, name, self._deploy_unit(project, file_path))
else:
@@ -95,6 +136,9 @@ class ApexNamespaces:
project = self.project_of.get(file_path)
if project is None or not prefix:
return None
+ return self._prefixed(project, file_path, prefix, name)
+
+ def _prefixed(self, project: str, file_path: str, prefix: str, name: str) -> str | None:
if prefix.lower() == self.manifests[project].namespace:
found = self._declared(project, name, self._deploy_unit(project, file_path))
return found[0] if len(found) == 1 else None
@@ -143,6 +187,18 @@ class ApexNamespaces:
(d for d in self.manifests[project].package_dirs if path.startswith(f"{d}/")), None
)
+ def _place(self, path: str) -> str | None:
+ """*path*'s project, registering a project that holds no Apex; None with no Apex at all."""
+ project = self.project_of.get(path, self.placed.get(path))
+ if project is not None or self.finder.root is None:
+ return project
+ project = self.finder.project_of(path, str(self.finder.root / path))
+ self.placed[path] = project
+ if project not in self.manifests:
+ self.manifests[project] = self.finder.manifests.get(project, _Manifest())
+ self.dependencies[project] = _dependencies(project, self.manifests)
+ return project
+
def build_apex_namespaces(parsed_files: dict[str, Any]) -> ApexNamespaces:
@@ -175,21 +231,34 @@ def build_apex_namespaces(parsed_files: dict[str, Any]) -> ApexNamespaces:
by_namespace={ns: tuple(found) for ns, found in by_namespace.items()},
top_level={key: tuple(ids) for key, ids in top_level.items()},
members=members,
+ declarers=_declarers(top_level),
+ finder=projects,
)
+def apex_namespaces(ctx: Any) -> ApexNamespaces:
+ """The index for a resolver context's parsed files, built once per context."""
+ index = getattr(ctx, "_apex_namespaces", None)
+ if index is None:
+ index = build_apex_namespaces(ctx.parsed_files or {})
+ ctx._apex_namespaces = index
+ return index
+
+
class _ProjectFinder:
"""The nearest ``sfdx-project.json`` above a file, each directory asked once."""
def __init__(self) -> None:
self._dirs: dict[str, str] = {}
self.manifests: dict[str, _Manifest] = {}
+ self.root: Path | None = None # the repository root, once a file was placed
def project_of(self, path: str, abs_path: str) -> str:
rel = PurePosixPath(path)
root = Path(abs_path)
for _ in rel.parts:
root = root.parent
+ self.root = root
return self._project_of_dir(rel.parent.as_posix(), root)
def _project_of_dir(self, directory: str, root: Path) -> str:
@@ -229,6 +298,14 @@ def _read_manifest(manifest: Path, project: str) -> _Manifest:
)
+def _declarers(top_level: Iterable[tuple[str, str]]) -> dict[str, tuple[str, ...]]:
+ """Lowercased type name -> the projects declaring it."""
+ found: dict[str, list[str]] = defaultdict(list)
+ for project, name in top_level:
+ found[name].append(project)
+ return {name: tuple(projects) for name, projects in found.items()}
+
+
def _dependencies(project: str, manifests: dict[str, _Manifest]) -> tuple[str, ...]:
"""The un-namespaced projects building a package *project* depends on."""
wanted = manifests[project].dependencies
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/apex.py b/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
index adf9df430..07de0306e 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/apex.py
@@ -7,9 +7,7 @@ SPEC = LanguageSpec(
display_name="Apex",
# .apex is an anonymous-Apex script: top-level statements, no class.
extensions=frozenset({".cls", ".trigger", ".apex"}),
- # The language pack ships the aheber/tree-sitter-sfapex Apex grammar
- # (inline SOQL/SOSL and DML are structured nodes in it), loaded the same
- # way as COBOL.
+ # tree-sitter-sfapex from the language pack, loaded as COBOL's is.
grammar_package="tree_sitter_language_pack",
grammar_loader="get_language",
grammar_loader_args=("apex",),
@@ -25,9 +23,7 @@ SPEC = LanguageSpec(
test_camel_suffixes=("Test", "Tests"),
manifest_files=("sfdx-project.json",),
blocked_dirs=(".sfdx", ".sf"),
- # Platform types written as a constructor target (``new Map<..>`` and
- # ``new List<..>`` are generic and never captured as one). Matched as
- # written; the parser drops the call site.
+ # Platform types written as a constructor target; the parser drops the call site.
builtin_calls=frozenset(
{
"System", "Database", "Schema", "Test", "Limits", "Math", "JSON",
@@ -41,15 +37,9 @@ SPEC = LanguageSpec(
"SelectOption", "Url", "Version", "Savepoint",
}
),
- # Only the root exception type. Platform interfaces (Queueable, Batchable,
- # Schedulable, Comparable, ...) stay in the heritage list on purpose: they
- # are what marks a class's contract methods as runtime-invoked.
+ # Platform interfaces stay in heritage: they mark contract methods as runtime-invoked.
builtin_parents=frozenset({"Exception"}),
- # Primitives, collections and the System, Database and Schema types that
- # never resolve to a class the repository declares. Apex type names are
- # case-insensitive, so readers compare these folded (see type_heads).
- # Standard sObjects (Account, Contact, ...) are absent: they are schema
- # references, not platform classes.
+ # Platform types no repo class can be; compared folded. sObjects are schema, not here.
builtin_types=frozenset(
{
# Primitives and the root types
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 2311c8d60..3d6e578b9 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -89,9 +89,7 @@ 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.
+ # Salesforce Aura markup: no symbols, read for the names it wires.
"aura",
# Salesforce flows: one symbol per flow.
"salesforce_flow",
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/lwc.py b/packages/core/src/repowise/core/ingestion/resolvers/lwc.py
index 85afff82b..78fe4fcbb 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/lwc.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/lwc.py
@@ -4,14 +4,17 @@ An LWC bundle is ``.../lwc/<name>/`` with main module ``<name>.js`` (or ``.ts``)
JS imports reach it as ``c/<name>`` (or the sfdx namespace), templates as
``<c-kebab-name>``, looked up in a reverse index of ``kebab(name)`` because
camelCase cannot be recovered from a tag. ``@salesforce/apex/[ns.]Cls.method``
-resolves to the Apex class file. A name two bundles declare goes to the one
-sharing the longest directory prefix with the referrer; a tie resolves nothing.
+resolves to the Apex class file the importer's sfdx project reaches. A bundle
+name two bundles declare goes to the one sharing the longest directory prefix
+with the referrer; a tie resolves nothing. Aura, Visualforce and flow edges
+share :func:`nearest`, :func:`lwc_namespaces` and :func:`lwc_bundles`.
"""
from __future__ import annotations
import json
import re
+from collections.abc import Sequence
from typing import TYPE_CHECKING
from ...test_paths import is_test_related_path
@@ -87,10 +90,15 @@ def lwc_namespaces(ctx: ResolverContext) -> frozenset[str]:
return result
-def nearest(candidates: tuple[str, ...], referrer: str) -> str | None:
- """The candidate sharing the most leading directories with *referrer*; None on a tie."""
- if len(candidates) == 1:
- return candidates[0]
+def nearest(candidates: Sequence[str], referrer: str) -> str | None:
+ """The candidate sharing the most leading directories with *referrer*; None on a tie or none.
+
+ A repository can hold several sfdx projects, or a source and an mdapi copy
+ of one, declaring the same names; the nearest copy stands for the one
+ deployed with the referrer.
+ """
+ if len(candidates) <= 1:
+ return candidates[0] if candidates else None
ref = referrer.split("/")
def shared(path: str) -> int:
@@ -107,23 +115,6 @@ def nearest(candidates: tuple[str, ...], referrer: str) -> str | None:
return scored[0][1]
-def _apex_classes(ctx: ResolverContext) -> dict[str, tuple[str, ...]]:
- """Lowercased Apex class name -> ``.cls`` paths (Apex names are case-insensitive).
-
- Ceiling: a local index; use a shared case-insensitive Apex index once one exists.
- """
- cached = getattr(ctx, "_lwc_apex_classes", None)
- if cached is None:
- found: dict[str, list[str]] = {}
- for path in ctx.sorted_paths:
- if path[-4:].lower() == ".cls":
- stem = path.rpartition("/")[2][:-4].lower()
- found.setdefault(stem, []).append(path)
- cached = {name: tuple(paths) for name, paths in found.items()}
- ctx._lwc_apex_classes = cached # type: ignore[attr-defined]
- return cached
-
-
def apex_specifier(module_path: str) -> tuple[str | None, str, str] | None:
"""``(ns, Cls, method)`` for ``@salesforce/apex/[ns.]Cls.method``, else None.
@@ -142,12 +133,11 @@ def apex_specifier(module_path: str) -> tuple[str | None, str, str] | None:
def _resolve_apex_module(
spec: tuple[str | None, str, str], importer_path: str, ctx: ResolverContext
) -> str | None:
- """The class file; another package's namespace stays external."""
+ """The class file, by the Apex reach rules; another package's namespace stays external."""
+ from ..languages.apex_namespace import apex_namespaces
+
ns, cls, _ = spec
- if ns is not None and ns.lower() not in lwc_namespaces(ctx):
- return None
- candidates = _apex_classes(ctx).get(cls.lower())
- return nearest(candidates, importer_path) if candidates else None
+ return apex_namespaces(ctx).referred_file(importer_path, f"{ns}.{cls}" if ns else cls)
def resolve_lwc_module(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
diff --git a/packages/core/src/repowise/core/ingestion/salesforce_flow.py b/packages/core/src/repowise/core/ingestion/salesforce_flow.py
index 5603b6d8a..804d8e484 100644
--- a/packages/core/src/repowise/core/ingestion/salesforce_flow.py
+++ b/packages/core/src/repowise/core/ingestion/salesforce_flow.py
@@ -6,7 +6,8 @@ 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.
+its names into edges. A triggering object is a schema reference
+(``salesforce_schema``).
"""
from __future__ import annotations
@@ -16,7 +17,7 @@ import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import PurePosixPath
-from .models import FileInfo, ParsedFile, Symbol
+from .models import FileInfo, ParsedFile, SchemaReference, Symbol
# A legacy metadata API flow carries its version number: ``Foo-3.flow``.
_LEGACY_VERSION_RE = re.compile(r"-\d+$")
@@ -131,7 +132,6 @@ def read_flow(source: bytes) -> FlowRefs | None:
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 "")
@@ -163,6 +163,10 @@ def parse_flow_file(file_info: FileInfo, source: bytes) -> ParsedFile:
visibility="public",
language="salesforce_flow",
)
+ schema_refs = []
+ if refs.start_object:
+ line = source.count(b"\n", 0, max(source.find(b"<start>"), 0)) + 1
+ schema_refs.append(SchemaReference(symbol.id, refs.start_object, line))
return ParsedFile(
file_info=file_info,
symbols=[symbol],
@@ -170,4 +174,5 @@ def parse_flow_file(file_info: FileInfo, source: bytes) -> ParsedFile:
exports=[name],
docstring=refs.label or None,
parse_errors=[],
+ schema_refs=schema_refs,
)
diff --git a/tests/unit/ingestion/test_salesforce_flow_edges.py b/tests/unit/ingestion/test_salesforce_flow_edges.py
index 447fe9268..65c6aadba 100644
--- a/tests/unit/ingestion/test_salesforce_flow_edges.py
+++ b/tests/unit/ingestion/test_salesforce_flow_edges.py
@@ -251,21 +251,80 @@ def test_a_legacy_flow_routes_by_directory_and_js_flow_does_not(tmp_path: Path)
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>"
+def _action_flow(name: str) -> str:
+ return _flow(
+ f" <actionCalls><name>A</name><actionName>{name}</actionName>"
"<actionType>apex</actionType></actionCalls>\n"
)
- cls = "public class Shared { @InvocableMethod public static void go(List<Id> x) {} }\n"
+
+
+_ACTION_CLS = "public class {} {{ @InvocableMethod public static void go(List<Id> x) {{}} }}\n"
+_PROJECT = '{"packageDirectories": [{"path": "force-app"}]}\n'
+
+
+def test_a_flow_binds_its_own_projects_copy_of_a_name_two_projects_declare(tmp_path: Path) -> None:
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,
+ "one/sfdx-project.json": _PROJECT,
+ "one/force-app/flows/F.flow-meta.xml": _action_flow("Shared"),
+ "one/force-app/classes/Shared.cls": _ACTION_CLS.format("Shared"),
+ "two/sfdx-project.json": _PROJECT,
+ "two/force-app/classes/Shared.cls": _ACTION_CLS.format("Shared"),
+ "three/sfdx-project.json": _PROJECT,
+ "three/force-app/flows/G.flow-meta.xml": _action_flow("Shared"),
}) # 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")
+ # Two other projects declare it and neither is a dependency: no edge.
assert not any(
- t.endswith("Shared.cls") for _, t in graph.out_edges("top/flows/G.flow-meta.xml")
+ t.endswith("Shared.cls") for _, t in graph.out_edges("three/force-app/flows/G.flow-meta.xml")
+ )
+
+
+def test_a_flow_reaches_a_class_only_one_other_project_declares(tmp_path: Path) -> None:
+ repo = _write(tmp_path, {
+ "app/sfdx-project.json": _PROJECT,
+ "app/force-app/flows/F.flow-meta.xml": _action_flow("PostToTeams"),
+ "teams/sfdx-project.json": _PROJECT,
+ "teams/force-app/classes/PostToTeams.cls": _ACTION_CLS.format("PostToTeams"),
+ "ns/sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "zz"}\n',
+ "ns/force-app/classes/Prefixed.cls": _ACTION_CLS.format("Prefixed"),
+ "app/force-app/flows/G.flow-meta.xml": _action_flow("Prefixed"),
+ }) # fmt: skip
+ graph, _ = _graph(repo)
+ assert graph.has_edge("app/force-app/flows/F.flow-meta.xml", "teams/force-app/classes/PostToTeams.cls")
+ # A namespaced project's class is reached only through its prefix.
+ assert not graph.has_edge("app/force-app/flows/G.flow-meta.xml", "ns/force-app/classes/Prefixed.cls")
+
+
+def test_a_flow_prefix_from_cumulusci_yml_is_the_repositorys_own(tmp_path: Path) -> None:
+ repo = _write(tmp_path, {
+ "sfdx-project.json": _PROJECT,
+ "cumulusci.yml": "project:\n package:\n namespace: npsp\n",
+ "force-app/flows/F.flow-meta.xml": _action_flow("npsp__Mailer"),
+ "force-app/classes/Mailer.cls": _ACTION_CLS.format("Mailer"),
+ }) # fmt: skip
+ graph, _ = _graph(repo)
+ assert graph.has_edge("force-app/flows/F.flow-meta.xml", "force-app/classes/Mailer.cls")
+
+
+def _trigger_flow(obj: str) -> str:
+ return _flow(
+ f" <start><object>{obj}</object><triggerType>RecordAfterSave</triggerType></start>\n"
)
+
+
+def test_a_record_triggered_flow_references_its_object(tmp_path: Path) -> None:
+ obj = f'<?xml version="1.0"?>\n<CustomObject {_NS}>\n <label>L</label>\n</CustomObject>\n'
+ repo = _write(tmp_path, {
+ "sfdx-project.json": '{"packageDirectories": [{"path": "force-app"}], "namespace": "acme"}\n',
+ f"{_D}/objects/Job__c/Job__c.object-meta.xml": obj,
+ f"{_D}/flows/On_Job.flow-meta.xml": _trigger_flow("acme__JOB__c"),
+ f"{_D}/flows/On_Case.flow-meta.xml": _trigger_flow("Case"),
+ }) # fmt: skip
+ graph, _ = _graph(repo)
+ flow, target = f"{_D}/flows/On_Job.flow-meta.xml", f"{_D}/objects/Job__c/Job__c.object-meta.xml"
+ assert graph.get_edge_data(f"{flow}::On_Job", f"{target}::Job__c")["edge_type"] == "references"
+ assert graph.has_edge(flow, target)
+ # No metadata for the object: nothing to bind.
+ assert not list(graph.successors(f"{_D}/flows/On_Case.flow-meta.xml::On_Case"))