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(workspace): read .NET client bases, HttpClient wrapper methods, Refit interfaces and YARP forwarders (#4550)
Raghav Chamadiya9eaaf250d01d
diff --git a/docs/reference/WORKSPACE_CONTRACTS.md b/docs/reference/WORKSPACE_CONTRACTS.mdindex 4dd44efb6..8b3a2b438 100644--- a/docs/reference/WORKSPACE_CONTRACTS.md+++ b/docs/reference/WORKSPACE_CONTRACTS.md@@ -106,7 +106,12 @@ another file imports the instance. An Angular `HttpClient` call is read on any ror injected as `HttpClient`, with `environment.apiUrl` folded from `src/environments/` and classfields built on it; a base an interceptor prepends is not read. A Node `request` call reads a URLor an options object held in a local (`var options = { uri, method }`), and a base from a-`module.exports = { ... }` module it requires (`endpoints.cartsUrl`). A client call+`module.exports = { ... }` module it requires (`endpoints.cartsUrl`). A C# `HttpClient` call takes+the `BaseAddress` its typed (`AddHttpClient<T>`), named (`AddHttpClient("name")` with+`CreateClient("name")`) or Refit (`AddRefitClient<T>`, `RestService.For<T>`) registration sets in+the same repo; a type registered twice with different or unreadable bases takes none. A call to a+method whose body sends its string parameter through `HttpClient` is read with the URL that body+builds. A client callwhose base URL is an unresolved placeholder (`fetch(\`${API_BASE}/users\`)`) matcheson the host-relative path; the link is **exact** when exactly one workspace serviceprovides that path (`unique_path`) and a lower-confidence **candidate** when the targetdiff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 86fa14389..1bbcc0f37 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -143,7 +143,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi| PHP | Laravel | Guzzle, Laravel `Http` || Java / Kotlin | Spring, JAX-RS, Micronaut | Feign (`@RequestLine`, and `@FeignClient` with Spring MVC annotations, its `name` read as the host), Spring `@HttpExchange` interfaces, Spring `WebClient` and `RestClient`, `RestTemplate` (also through a getter or a `RequestEntity`), `java.net.http`, Apache HttpClient (`new HttpPost(url)`, with a base URL passed to a helper's constructor in another file), MicroProfile `@RegisterRestClient` interfaces, Ktor (Kotlin) || Go | gin, echo, chi, fiber, gorilla/mux, net/http (Go 1.22 method patterns) | net/http |-| C# | ASP.NET (attribute and minimal API) | HttpClient (`GetAsync`, `GetFromJsonAsync`, `PostAsJsonAsync`, `GetStringAsync`, `new HttpRequestMessage(HttpMethod.X, url)`; a URL held in a local or a `const` / `readonly` field), UnityWebRequest, Best.HTTP |+| C# | ASP.NET (attribute and minimal API) | HttpClient (`GetAsync`, `GetFromJsonAsync`, `PostAsJsonAsync`, `GetStringAsync`, `new HttpRequestMessage(HttpMethod.X, url)`; a URL held in a local or a `const` / `readonly` field; `new Uri(base, path)` and `CombineUri` joins; typed, named and Refit client `BaseAddress`; HttpClient wrapper methods), Refit attributes, YARP `MapForwarder`, UnityWebRequest, Best.HTTP || Ruby | | HTTParty, RestClient, Faraday, Net::HTTP || Rust | Axum, Actix, Rocket | reqwest || Apex | `@RestResource` classes (`/services/apexrest` + `urlMapping`) | `HttpRequest` callouts (literal endpoint and verb) |diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex cd6c1cc8f..798470209 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -42,6 +42,7 @@ from .next_app import NextAppDialectfrom .paths import normalize_http_pathfrom .php_clients import PhpClientsDialectfrom .python_clients import PythonClientsDialect+from .refit import RefitDialectfrom .remix import RemixDialectfrom .ruby_clients import RubyClientsDialectfrom .rust_axum import RustAxumDialect@@ -91,6 +92,7 @@ CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (ApexCalloutsDialect(),SpringClientsDialect(),MicroProfileClientsDialect(),+ RefitDialect(),)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/client_calls.py b/packages/core/src/repowise/core/workspace/extractors/http/client_calls.pyindex 85fff052a..821033539 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/client_calls.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/client_calls.py@@ -15,7 +15,7 @@ it moves under ``ingestion`` the day one does.from __future__ import annotationsimport re-from collections.abc import Iterable, Iterator+from collections.abc import Callable, Iterable, Iteratorfrom dataclasses import dataclassfrom typing import TYPE_CHECKING@@ -44,6 +44,9 @@ class ClientCallMatch:argument, a builder terminal, an explicit option) and ``None`` when onlythe callee's name carries it, in which case :func:`method_from_callee`reads ``callee``. ``offset`` is where the call starts, for its line.+ ``compose``, when set, rewrites the resolved URL text before it is read:+ the base a client instance carries, or the template a wrapper method+ builds around its argument."""client: str@@ -52,6 +55,7 @@ class ClientCallMatch:callee: str = ""method: str | None = Noneorigin: ContractOrigin = ContractOrigin.CLIENT_CALL+ compose: Callable[[str], str] | None = None# ---------------------------------------------------------------------------@@ -125,7 +129,9 @@ def consumer_contracts(continueurl = resolve_string(m.url, syntax, constants)if url is None or (path_only and "/" not in url):- continue+ continue # judged on what the call itself names, before a base joins it+ if m.compose is not None:+ url = m.compose(url)if rooted_only and not is_rooted_url(url):continuemethod = m.method or method_from_callee(m.callee)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/csharp_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/csharp_clients.pynew file mode 100644index 000000000..3cf922e60--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/csharp_clients.py@@ -0,0 +1,426 @@+"""Where a C# HttpClient call's URL is completed: client registrations and wrapper methods.++A C# call rarely names its whole URL. The client's ``BaseAddress`` is set where+it is registered (``AddHttpClient<CatalogService>(o => o.BaseAddress =+new("http://catalog-api"))``, a named ``AddHttpClient("catalog", ...)``, a Refit+``AddRefitClient<ICatalogApi>()`` or ``RestService.For<ICatalogApi>(url)``),+usually in another file. A service often calls HttpClient through methods of+its own (``_http.HttpGet<T>("catalog-items")``), also in another file. Both are+read once per file in the HTTP mounts pass and reach every file of the repo+through ``ScanContext.mounts``:++* ``csharp-client:<Type>``: the base of a typed client or Refit interface;+* ``csharp-named-client:<name>``: the base of a named client;+* ``csharp-wrapper:<Type>.<Method>``: ``<VERB> <index> <template>`` for a method+ whose body calls HttpClient with a URL built from its string parameter+ *index*; the template is that URL with the parameter as :data:`ARG`. Keyed by+ the declaring type and each interface it lists, since callers hold the+ interface.++A base counts only when it is absolute, so the host can place the call. A key+two files give different values is dropped by the mounts merge.++Ceiling: a registration is read in the repo that holds it, so a typed client+another repo registers (a shared component library) keeps its relative path and+is matched on that; a workspace-wide registration table is the upgrade.+"""++from __future__ import annotations++import re+from bisect import bisect_right+from typing import TYPE_CHECKING++from ..strings import CSHARP_SYNTAX, call_arguments, match_paren, resolve_string+from .mounts import declare_mount, declared_mount+from .paths import absolute_host++if TYPE_CHECKING:+ from collections.abc import Mapping++ from .csharp_http import _FileNames++# A generic type argument, two levels of nesting (`<List<Item>>`).+GENERIC = r"<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>"++# HttpClient + wrapper calls, ending at the argument list. Method verbs are+# PascalCase (C# convention); the `Async`/`Request` suffix is required so we+# don't match unrelated `Get("key")` lookups. Group 2 holds the+# `System.Net.Http.Json` and `GetStringAsync` forms.+VERB_CALL_RE = re.compile(+ r"\b(Get|Post|Put|Delete|Patch)(FromJson|AsJson|String|ByteArray|Stream)?(?:Async|Request)"+ rf"\s*(?:{GENERIC})?\s*\("+)+# Extension methods only HttpClient has; `GetStringAsync` is also a cache's.+JSON_FORMS = frozenset({"FromJson", "AsJson"})++TYPED_CLIENT_KEY = "csharp-client:"+NAMED_CLIENT_KEY = "csharp-named-client:"+WRAPPER_KEY = "csharp-wrapper:"+#: Where a wrapper template takes its caller's argument.+ARG = "\x01"++_TYPED_REGISTRATION_RE = re.compile(+ r"\bAdd(?:HttpClient|RefitClient)\s*<\s*(?:[\w.]+\s*,\s*)?(?P<type>[\w.]+)\s*>\s*\("+)+_NAMED_REGISTRATION_RE = re.compile(+ r"\bAddHttpClient\s*\(\s*(?P<name>\"[^\"\n]*\"|nameof\s*\(\s*[\w.]+\s*\)|[A-Za-z_][\w.]*\s*[,)])"+)+_REFIT_FOR_RE = re.compile(r"\bRestService\s*\.\s*For\s*<\s*(?P<type>[\w.]+)\s*>\s*\(")+# One more call in a registration's fluent chain (`.ConfigureHttpClient(...)`).+_CHAIN_LINK_RE = re.compile(r"\s*\.\s*\w+\s*(?:<[^<>()]*>)?\s*\(")+_MAX_CHAIN = 8+_BASE_ADDRESS_RE = re.compile(+ r"\bBaseAddress\s*=\s*(?:new\s*(?:(?:System\s*\.\s*)?Uri\s*)?(?P<paren>\()|(?P<name>[A-Za-z_][\w.]*))"+)+_NAMEOF_RE = re.compile(r"nameof\s*\(\s*([\w.]+)\s*\)")++# A type declaration and the base list after its `:`, up to its body.+_TYPE_DECL_RE = re.compile(+ r"(?<![\w-])(?:record\s+(?:class|struct)|class|record|struct|interface)\s+"+ r"(?!(?:public|private|protected|internal|static|sealed|abstract|partial)\b)"+ r"(?P<name>[A-Za-z_]\w*)[^{;]*?(?::(?P<bases>[^{;]*))?\{"+)+_INTERFACE_NAME_RE = re.compile(r"(?<![\w.])I[A-Z]\w*")+# A method with a block body; `new X(...) {` is an object initializer.+_METHOD_DECL_RE = re.compile(+ r"(?<!new )\b(?P<name>[A-Z]\w*)\s*(?:<[^<>()]*>)?\s*\((?P<params>[^()]*)\)\s*(?:where\b[^{;]*)?\{"+)+_STRING_PARAM_RE = re.compile(r"\s*(?:\[[^\]]*\]\s*)?string\??\s+(\w+)\b")+_RECEIVER_RE = re.compile(r"(?<![\w.])(?:this\s*\.\s*)?([A-Za-z_]\w*)\s*\.\s*$")+_RECEIVER_WINDOW = 120+++def client_name(token: str, names: _FileNames, offset: int) -> str | None:+ """A named client's name: ``"catalog"``, ``nameof(CatalogClient)``, or a constant holding one."""+ token = token.strip().rstrip(",)").strip()+ m = _NAMEOF_RE.fullmatch(token)+ if m is not None:+ return m.group(1).rsplit(".", 1)[-1]+ name = names.resolve(token, offset)+ return name if name and "${" not in name else None+++def absolute_base(url: str | None) -> str | None:+ """*url* when it names a host, else ``None``."""+ return url if url is not None and absolute_host(url) is not None else None+++_AUTHORITY_RE = re.compile(r"^[A-Za-z][\w+.-]*://[^/]*")+++def with_base(base: str, url: str) -> str:+ """*url* resolved against an HttpClient ``BaseAddress``, as .NET resolves it.++ An absolute URL or one with its own leading base keeps it; ``/x`` replaces+ the base's path; ``x`` replaces the base's last segment unless the base+ ends in ``/`` (``http://h/api`` + ``x`` is ``http://h/x``).+ """+ if "://" in url or url.startswith(("//", "${")):+ return url+ authority = _AUTHORITY_RE.match(base)+ if authority is None:+ return url+ if url.startswith("/"):+ return authority.group(0) + url+ if authority.end() < len(base):+ base = base[: base.rfind("/") + 1]+ return base.rstrip("/") + "/" + url+++def _in_code(names: _FileNames, offset: int) -> bool:+ """True when *offset* is code, not a comment or a string body."""+ return names.code[offset] == names.content[offset]+++def _chain_end(content: str, paren: int) -> int:+ close = match_paren(content, paren)+ for _ in range(_MAX_CHAIN):+ link = _CHAIN_LINK_RE.match(content, close + 1) if close >= 0 else None+ if link is None:+ break+ nxt = match_paren(content, link.end() - 1)+ if nxt < 0:+ break+ close = nxt+ return close+++def _base_address(names: _FileNames, start: int, end: int) -> str | None:+ content = names.content+ m = _BASE_ADDRESS_RE.search(content, start, end)+ if m is None:+ return None+ if m.group("paren") is not None:+ args = call_arguments(content, m.start("paren"))+ if not args or len(args) > 2:+ return None+ expr = args[0] if len(args) == 1 else f"new Uri({args[0]}, {args[1]})"+ else:+ expr = m.group("name")+ return absolute_base(names.resolve(expr, m.start()))+++def _declare(out: dict[str, str], key: str, base: str | None) -> None:+ """Record a registration; one whose base is unread or disagrees still counts.++ A type registered twice, once with a base this cannot read, has no base+ the reader can trust, so the merge leaves it declared but unreadable.+ """+ entries = declare_mount(key, base)+ if key in out and out[key] != entries[key]:+ entries = declare_mount(key, None)+ out.update(entries)+++def registrations(names: _FileNames) -> dict[str, str]:+ """The typed, named and Refit client bases this file registers, as mount entries."""+ content = names.content+ out: dict[str, str] = {}+ if "AddHttpClient" not in content and "AddRefitClient" not in content and "RestService" not in content:+ return out+ for m in _TYPED_REGISTRATION_RE.finditer(content):+ if _in_code(names, m.start()):+ base = _base_address(names, m.end() - 1, _chain_end(content, m.end() - 1) + 1)+ _declare(out, TYPED_CLIENT_KEY + m.group("type").rsplit(".", 1)[-1], base)+ for m in _NAMED_REGISTRATION_RE.finditer(content):+ name = client_name(m.group("name"), names, m.start())+ if name is not None and _in_code(names, m.start()):+ paren = content.index("(", m.start())+ base = _base_address(names, paren, _chain_end(content, paren) + 1)+ _declare(out, NAMED_CLIENT_KEY + name, base)+ if "RestService" in content:+ for m in _REFIT_FOR_RE.finditer(content):+ args = call_arguments(content, m.end() - 1)+ if args and _in_code(names, m.start()):+ base = absolute_base(names.resolve(args[0], m.start()))+ _declare(out, TYPED_CLIENT_KEY + m.group("type").rsplit(".", 1)[-1], base)+ return out+++def client_base(mounts: Mapping[str, str], key: str) -> str | None:+ """The base registered under *key*, ``None`` when undeclared, unread or ambiguous."""+ return declared_mount(mounts, key)[1]+++def declared_types(code: str) -> tuple[list[int], list[tuple[str, tuple[str, ...]]]]:+ """Each type declaration's offset, and its name with the interfaces it lists."""+ starts: list[int] = []+ types: list[tuple[str, tuple[str, ...]]] = []+ for m in _TYPE_DECL_RE.finditer(code):+ bases = re.sub(GENERIC, "", m.group("bases") or "")+ starts.append(m.start())+ types.append((m.group("name"), tuple(_INTERFACE_NAME_RE.findall(bases))))+ return starts, types+++def type_at(+ declared: tuple[list[int], list[tuple[str, tuple[str, ...]]]], offset: int+) -> tuple[str, tuple[str, ...]] | None:+ """The type whose declaration is nearest above *offset*.++ Ceiling: a member after a nested type's body reads as the nested type's;+ a brace-depth walk is the upgrade if that shape turns up.+ """+ i = bisect_right(declared[0], offset) - 1+ return declared[1][i] if i >= 0 else None+++#: What :func:`receiver_at` returns for a call on a member chain or a call+#: result (``o.Client.GetAsync``, ``Pick().GetAsync``): a receiver, not one named.+CHAINED = ""+++def receiver_at(content: str, offset: int) -> str | None:+ """The name a member call at *offset* is made on (``client`` in ``client.GetAsync``).++ ``None`` for a call with no receiver; :data:`CHAINED` when the receiver is+ not a plain name.+ """+ start = max(0, offset - _RECEIVER_WINDOW)+ m = _RECEIVER_RE.search(content, start, offset)+ if m is not None:+ return m.group(1)+ return CHAINED if content[start:offset].rstrip().endswith(".") else None+++def _nearest(sites: list[tuple[int, str]], offset: int) -> str | None:+ """The value of the site nearest above *offset*, else the one value every site agrees on."""+ above = [value for start, value in sites if start < offset]+ if above:+ return above[-1]+ values = {value for _, value in sites}+ return values.pop() if len(values) == 1 else None+++# Words that stand before a name without declaring it (`return client;`).+_NOT_TYPES = frozenset(+ {"return", "await", "yield", "throw", "else", "case", "in", "out", "ref", "is", "as", "new", "using"}+)+# What a `var` local is bound to: `new T(...)`, or a call whose name ends in+# the type it returns (`GetOrCreateHttpClient()`).+_VAR_RHS_RE = re.compile(r"[ \t]*(?:await\s+)?(?:new\s+(?:\w+\.)*(\w+)\b|[\w.]*?(HttpClient)\s*\()")+++def _site_type(code: str, m: re.Match[str]) -> str | None:+ found = m.group(1)+ if found in _NOT_TYPES:+ return None+ if found == "var" and code[m.end() - 1] == "=":+ rhs = _VAR_RHS_RE.match(code, m.end())+ return (rhs.group(1) or rhs.group(2)) if rhs else "var"+ return found+++def declared_type(names: _FileNames, name: str, offset: int) -> str | None:+ """The type *name* is declared with (a field, parameter or local) as seen from *offset*.++ The declaration nearest above the use wins, so the same name in two methods+ reads as each method's own; a field declared below its uses counts when the+ file gives the name one type. A ``var`` local takes the type it is bound to+ with ``new``, or ``HttpClient`` from a call named for one. Read once per+ name and file.+ """+ key = ("type", name)+ sites = names.memo.get(key)+ if sites is None:+ n = re.escape(name)+ pattern = rf"(?<![\w.])(?:\w+\.)*(\w+)(?:{GENERIC})?\??[ \t]+{n}[ \t]*[;=,)]"+ code = names.code+ sites = names.memo[key] = [+ (m.start(), t) for m in re.finditer(pattern, code) if (t := _site_type(code, m)) is not None+ ]+ return _nearest(sites, offset)+++def created_client(names: _FileNames, name: str, offset: int) -> str | None:+ """The name token of the factory client *name* is bound to at *offset*, else ``None``.++ ``var client = _factory.CreateClient("catalog")`` gives ``"catalog"``; a+ client created with no name gives an empty token. The binding counts only+ when no declaration of *name* sits between it and the use, so another+ method's ``HttpClient client`` does not take this one's base.+ """+ key = ("client", name)+ sites = names.memo.get(key)+ if sites is None:+ n = re.escape(name)+ pattern = rf"\b{n}\s*=\s*(?:await\s+)?[\w.]*CreateClient\s*\((?P<arg>[^()]*)\)"+ sites = names.memo[key] = [+ (m.start(), m.group("arg")) for m in re.finditer(pattern, names.content)+ ]+ # Only a binding above the use: a later `client = CreateClient(...)` is another client.+ above = [(start, value) for start, value in sites if start < offset]+ if not above:+ return None+ bound_at, token = above[-1]+ declared_type(names, name, offset) # fills the declaration sites+ if any(bound_at < start < offset for start, _ in names.memo[("type", name)]):+ return None+ return token+++def is_http_client(names: _FileNames, receiver: str | None, offset: int) -> bool:+ """True when *receiver* is declared an ``HttpClient`` or bound to a factory client."""+ if not receiver:+ return False+ if declared_type(names, receiver, offset) == "HttpClient":+ return True+ return created_client(names, receiver, offset) is not None+++def _params(text: str) -> list[str]:+ out: list[str] = []+ depth, start = 0, 0+ for i, ch in enumerate(text):+ if ch in "<([":+ depth += 1+ elif ch in ">)]":+ depth -= 1+ elif ch == "," and depth == 0:+ out.append(text[start:i])+ start = i + 1+ out.append(text[start:])+ return out+++def _template(names: _FileNames, start: int, end: int, params: dict[str, int]) -> str | None:+ """The one ``<VERB> <index> <template>`` the body between *start* and *end* calls, else ``None``."""+ content = names.content+ found: set[str] = set()+ for v in VERB_CALL_RE.finditer(content, start, end):+ receiver = receiver_at(content, v.start())+ if v.group(2) not in JSON_FORMS and not is_http_client(names, receiver, v.start()):+ continue # a cache's `GetStringAsync(key)` does not make its caller a URL+ args = call_arguments(content, v.end() - 1)+ if not args:+ continue+ url = names.url(args[0], v.start())+ used = [p for p in params if re.search(rf"(?<![\w.]){re.escape(p)}\b", url)]+ if len(used) != 1:+ continue+ hole = "${" + used[0] + "}"+ if url.strip() == used[0]:+ text: str | None = hole+ else:+ text = resolve_string(url, CSHARP_SYNTAX, names.fields([url]))+ if text is None or text.count(hole) != 1:+ continue+ found.add(f"{v.group(1).upper()} {params[used[0]]} {text.replace(hole, ARG)}")+ return found.pop() if len(found) == 1 else None+++def wrappers(names: _FileNames) -> dict[str, str]:+ """This file's HttpClient wrapper methods, as mount entries.++ A value is ``<VERB> <index> <min> <max> <template>``: a call site must pass+ between *min* and *max* arguments, so an overload of another arity is not+ read as this one. Two overloads the file declares differently drop the key.+ """+ if "HttpClient" not in names.content:+ return {}+ code = names.code+ found: dict[str, set[str]] = {}+ for m in _METHOD_DECL_RE.finditer(code):+ declared = _params(m.group("params"))+ params = {pm.group(1): i for i, p in enumerate(declared) if (pm := _STRING_PARAM_RE.match(p))}+ if not params:+ continue+ close = match_paren(code, m.end() - 1, closer="}")+ if close < 0:+ continue+ template = _template(names, m.end(), close, params)+ owner = type_at(names.types, m.start()) if template is not None else None+ if owner is None:+ continue+ verb, index, text = template.split(" ", 2)+ required = sum(1 for p in declared if p.strip() and "=" not in p)+ value = f"{verb} {index} {required} {len(declared)} {text}"+ type_name, interfaces = owner+ for t in (type_name, *interfaces):+ found.setdefault(f"{WRAPPER_KEY}{t}.{m.group('name')}", set()).add(value)+ return {key: values.pop() for key, values in found.items() if len(values) == 1}+++__all__ = [+ "ARG",+ "CHAINED",+ "GENERIC",+ "JSON_FORMS",+ "NAMED_CLIENT_KEY",+ "TYPED_CLIENT_KEY",+ "VERB_CALL_RE",+ "WRAPPER_KEY",+ "absolute_base",+ "client_base",+ "client_name",+ "created_client",+ "declared_type",+ "declared_types",+ "is_http_client",+ "receiver_at",+ "registrations",+ "type_at",+ "with_base",+ "wrappers",+]diff --git a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.pyindex 1a779821b..3f8288b5c 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/csharp_http.py@@ -22,8 +22,9 @@ is read, so a hole there the strings layer refuses costs nothing.from __future__ import annotationsimport re-from collections.abc import Iterator+from collections.abc import Iterator, Mappingfrom dataclasses import replace+from functools import lru_cache, partialfrom typing import TYPE_CHECKINGfrom repowise.core.analysis.security.masking import mask_comments_and_strings, mask_dialect@@ -36,9 +37,30 @@ from ..strings import (NAME_RE,call_arguments,enclosing_local,+ match_paren,+ resolve_string,string_constants,)from .client_calls import ClientCallMatch, consumer_contracts, matches_in, method_from_argument+from .csharp_clients import (+ ARG,+ GENERIC,+ JSON_FORMS,+ NAMED_CLIENT_KEY,+ TYPED_CLIENT_KEY,+ VERB_CALL_RE,+ WRAPPER_KEY,+ client_base,+ client_name,+ created_client,+ declared_type,+ declared_types,+ receiver_at,+ registrations,+ type_at,+ with_base,+ wrappers,+)if TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -49,20 +71,6 @@ if TYPE_CHECKING:# (`@`) prefix: capture group 1 = prefix, group 2 = the inner text._STR = r"""(\$?@?)"([^"]*)\""""-# A generic type argument, two levels of nesting (`<List<Item>>`).-_GENERIC = r"<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>"--# HttpClient + wrapper calls, ending at the argument list. Method verbs are-# PascalCase (C# convention); the `Async`/`Request` suffix is required so we-# don't match unrelated `Get("key")` lookups. Group 2 holds the-# `System.Net.Http.Json` and `GetStringAsync` forms.-_VERB_CALL_RE = re.compile(- r"\b(Get|Post|Put|Delete|Patch)(FromJson|AsJson|String|ByteArray|Stream)?(?:Async|Request)"- rf"\s*(?:{_GENERIC})?\s*\("-)-# Extension methods only HttpClient has; `GetStringAsync` is also a cache's.-_JSON_FORMS = frozenset({"FromJson", "AsJson"})-_REQUEST_MESSAGE_RE = re.compile(r"\bnew\s+HttpRequestMessage\s*\(")# UnityWebRequest.Get(...) / .Post(...) — only when the first arg is a string.@@ -75,6 +83,9 @@ _BESTHTTP_RE = re.compile(re.IGNORECASE,)+# The enum every Best.HTTP match names, searched once before the costlier regex.+_BESTHTTP_GATE_RE = re.compile("httpmethods", re.IGNORECASE)+# HttpClient calls are read off any receiver; its type is not confirmed._ORIGIN = ContractOrigin.NAME_HEURISTIC@@ -150,8 +161,18 @@ class _FileNames:def __init__(self, content: str) -> None:self.content = content+ #: Per-name lookups the client readers make, read once per file.+ self.memo: dict[tuple[str, str], list[tuple[int, str]]] = {}self._code: str | None = Noneself._fields: dict[str, str] | None = None+ self._types: tuple[list[int], list[tuple[str, tuple[str, ...]]]] | None = None++ @property+ def types(self) -> tuple[list[int], list[tuple[str, tuple[str, ...]]]]:+ """The file's type declarations, for :func:`.csharp_clients.type_at`."""+ if self._types is None:+ self._types = declared_types(self.code)+ return self._types@propertydef code(self) -> str:@@ -193,27 +214,97 @@ class _FileNames:local = enclosing_local(self.content, self.code, expr, offset)if local is not None:expr = local- return without_query(expr)+ return sole_hole(without_query(expr))+ def resolve(self, expr: str, offset: int) -> str | None:+ """The text *expr* at *offset* denotes, through locals and fields, else ``None``."""+ url = self.url(expr, offset)+ return resolve_string(url, CSHARP_SYNTAX, self.fields([url]))-def httpclient_calls(content: str, names: _FileNames) -> Iterator[ClientCallMatch]:- for m in _VERB_CALL_RE.finditer(content):++_SOLE_HOLE_RE = re.compile(r'(?:\$@|@\$|\$)"\{(?!\{)')+++def sole_hole(expr: str) -> str:+ """``$"{x}"`` as ``x``: a literal that interpolates one value and nothing else.++ The value may hold quotes of its own (``$"{Combine(b, $"{p}/x")}"``), which+ the strings layer refuses inside a literal but reads as an expression.+ """+ m = _SOLE_HOLE_RE.match(expr)+ if m is None or not expr.endswith('}"'):+ return expr+ close = match_paren(expr, m.end() - 1, closer="}")+ return expr[m.end() : close] if close == len(expr) - 2 else expr+++def _base_for(+ names: _FileNames, mounts: Mapping[str, str], offset: int, receiver: str | None+) -> str | None:+ """The ``BaseAddress`` a call at *offset* on *receiver* resolves against, else ``None``.++ A receiver bound to ``CreateClient("name")`` takes that named client's base;+ a name the file declares ``HttpClient`` takes the base registered for the+ type holding the call. A call with no receiver, or on a member chain, is+ not known to be the client's and takes none.+ """+ if not receiver:+ return None+ token = created_client(names, receiver, offset)+ if token is not None:+ name = client_name(token, names, offset)+ return client_base(mounts, NAMED_CLIENT_KEY + name) if name else None+ if declared_type(names, receiver, offset) != "HttpClient":+ return None+ return _owner_base(names, mounts, offset)+++def _owner_base(names: _FileNames, mounts: Mapping[str, str], offset: int) -> str | None:+ owner = type_at(names.types, offset)+ return client_base(mounts, TYPED_CLIENT_KEY + owner[0]) if owner else None+++def _has_bases(mounts: Mapping[str, str]) -> bool:+ return any(k.startswith((TYPED_CLIENT_KEY, NAMED_CLIENT_KEY)) for k in mounts)+++def httpclient_calls(+ content: str,+ names: _FileNames,+ mounts: Mapping[str, str] | None = None,+ skip: frozenset[int] = frozenset(),+) -> Iterator[ClientCallMatch]:+ """Verb calls; one at an offset in *skip* was already read as a wrapper call."""+ mounts = mounts or {}+ bases = _has_bases(mounts)+ for m in VERB_CALL_RE.finditer(content):+ if m.start() in skip:+ continueargs = call_arguments(content, m.end() - 1)if not args:continue- json_form = m.group(2) in _JSON_FORMS+ json_form = m.group(2) in JSON_FORMS+ origin = ContractOrigin.CLIENT_CALL if json_form else _ORIGIN+ base = _base_for(names, mounts, m.start(), receiver_at(content, m.start())) if bases else None+ if base is not None and origin is _ORIGIN:+ origin = ContractOrigin.INSTANCE_BASE # the registration types the receiveryield ClientCallMatch(client="httpclient",url=names.url(args[0], m.start()),offset=m.start(),method=m.group(1).upper(),- origin=ContractOrigin.CLIENT_CALL if json_form else _ORIGIN,+ origin=origin,+ compose=partial(with_base, base) if base is not None else None,)-def request_message_calls(content: str, names: _FileNames) -> Iterator[ClientCallMatch]:+def request_message_calls(+ content: str, names: _FileNames, mounts: Mapping[str, str] | None = None+) -> Iterator[ClientCallMatch]:if "HttpRequestMessage" not in content:return+ mounts = mounts or {}+ bases = _has_bases(mounts)for m in _REQUEST_MESSAGE_RE.finditer(content):args = call_arguments(content, m.end() - 1)if not args or len(args) != 2:@@ -221,16 +312,86 @@ def request_message_calls(content: str, names: _FileNames) -> Iterator[ClientCalmethod = method_from_argument(args[0])if method is None:continue # a verb held in a variable is not one we know+ base = _owner_base(names, mounts, m.start()) if bases else Noneyield ClientCallMatch(client="httpclient",url=names.url(args[1], m.start()),offset=m.start(),method=method,origin=ContractOrigin.CLIENT_CALL,+ compose=partial(with_base, base) if base is not None else None,+ )+++def _fill(template: str, url: str) -> str:+ return template.replace(ARG, url)+++@lru_cache(maxsize=32)+def _wrapper_call_re(methods: frozenset[str]) -> re.Pattern[str]:+ # Led by the method names, so a file pays one literal-prefixed scan.+ alts = "|".join(sorted(re.escape(m) for m in methods))+ return re.compile(rf"\.\s*(?P<name>{alts})\s*(?:{GENERIC})?\s*\(")+++def wrapper_calls(+ content: str, names: _FileNames, mounts: Mapping[str, str]+) -> Iterator[ClientCallMatch]:+ """Calls to a wrapper method the repo declares, through a receiver of its type."""+ methods = frozenset(k.rpartition(".")[2] for k in mounts if k.startswith(WRAPPER_KEY))+ if not methods:+ return+ for m in _wrapper_call_re(methods).finditer(content):+ offset = m.start("name")+ receiver = receiver_at(content, offset)+ rtype = declared_type(names, receiver, offset) if receiver else None+ value = mounts.get(f"{WRAPPER_KEY}{rtype}.{m.group('name')}") if rtype else None+ if value is None:+ continue+ verb, index, least, most, template = value.split(" ", 4)+ args = call_arguments(content, m.end() - 1)+ if not args or not int(least) <= len(args) <= int(most):+ continue # another overload+ yield ClientCallMatch(+ client=m.group("name"),+ url=names.url(args[int(index)], offset),+ offset=offset,+ method=verb,+ origin=ContractOrigin.DATAFLOW,+ # A body that sends its argument as is adds nothing to compose.+ compose=partial(_fill, template) if template != ARG else None,+ )+++_FORWARDER_RE = re.compile(r"\.\s*MapForwarder\s*\(")+++def forwarder_calls(content: str, names: _FileNames) -> Iterator[ClientCallMatch]:+ """YARP ``MapForwarder(pattern, destinationPrefix[, path])``: every method, forwarded.++ The destination receives the third argument's path when it is a string,+ else the matched request's own path (the pattern).+ """+ if "MapForwarder" not in content:+ return+ for m in _FORWARDER_RE.finditer(content):+ args = call_arguments(content, m.end() - 1)+ if not args or len(args) < 2:+ continue+ target = args[2] if len(args) > 2 and _LITERAL_OPEN_RE.match(args[2].strip()) else args[0]+ prefix = names.url(args[1], m.start())+ yield ClientCallMatch(+ client="yarp-forwarder",+ url=f"new Uri({prefix}, {names.url(target, m.start())})",+ offset=m.start(),+ method="*",+ origin=ContractOrigin.CLIENT_CALL,)def unitywebrequest_calls(content: str) -> Iterator[ClientCallMatch]:+ if "UnityWebRequest" not in content:+ returnyield from matches_in(content,_UNITY_RE,@@ -243,6 +404,8 @@ def unitywebrequest_calls(content: str) -> Iterator[ClientCallMatch]:def besthttp_calls(content: str) -> Iterator[ClientCallMatch]:+ if _BESTHTTP_GATE_RE.search(content) is None:+ returnyield from matches_in(content,_BESTHTTP_RE,@@ -254,25 +417,48 @@ def besthttp_calls(content: str) -> Iterator[ClientCallMatch]:)+# What a client call itself needs; the rest of the gate admits registrations+# and wrapper call sites.+_CALL_TOKENS = ("Async", "Request", "request", "REQUEST", "MapForwarder")++class CSharpHttpDialect:name = "csharp-http"extensions = CSHARP# `GetAsync`, `GetRequest`, `HttpRequestMessage`, `UnityWebRequest`,- # `HTTPRequest` in any case.- requires = ("Async", "Request", "request", "REQUEST")+ # `HTTPRequest` in any case; client registrations and YARP forwarders; and+ # `Task`, which a call to a wrapper method returning one sits beside.+ requires = (*_CALL_TOKENS, "AddHttpClient", "AddRefitClient", "RestService", "Task")++ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ """Client bases this file registers and the HttpClient wrappers it declares."""+ names = _FileNames(ctx.content)+ return registrations(names) | wrappers(names)def extract(self, ctx: ScanContext) -> list[Contract]:content = ctx.contentnames = _FileNames(content)- matches = [- *httpclient_calls(content, names),- *request_message_calls(content, names),- *unitywebrequest_calls(content),- *besthttp_calls(content),- ]- if not matches:+ wrapped = list(wrapper_calls(content, names, ctx.mounts))+ matches = (+ [+ *httpclient_calls(content, names, ctx.mounts, frozenset(m.offset for m in wrapped)),+ *request_message_calls(content, names, ctx.mounts),+ *forwarder_calls(content, names),+ *unitywebrequest_calls(content),+ *besthttp_calls(content),+ ]+ if ctx.has_any(_CALL_TOKENS)+ else []+ )+ if not matches and not wrapped:return []# A plain literal never pays for the file's fields.- fields = names.fields([m.url for m in matches if not m.url.startswith('"')])- # A slash-free string is a key or a name, not a route.- return consumer_contracts(ctx, matches, CSHARP_SYNTAX, constants=fields, path_only=True)+ fields = names.fields([m.url for m in (*matches, *wrapped) if not m.url.startswith('"')])+ # A slash-free string is a key or a name, not a route, unless a wrapper+ # builds a URL around it; one that passes it through proves nothing.+ built = [m for m in wrapped if m.compose is not None]+ passed = [m for m in wrapped if m.compose is None]+ return [+ *consumer_contracts(ctx, [*matches, *passed], CSHARP_SYNTAX, constants=fields, path_only=True),+ *consumer_contracts(ctx, built, CSHARP_SYNTAX, constants=fields),+ ]diff --git a/packages/core/src/repowise/core/workspace/extractors/http/refit.py b/packages/core/src/repowise/core/workspace/extractors/http/refit.pynew file mode 100644index 000000000..b4fe78467--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/refit.py@@ -0,0 +1,69 @@+"""Refit typed clients: an interface whose methods carry the request as attributes.++``[Get("/api/catalog/items/{id}")] Task<Item> GetItem(int id);`` on an+interface is a call to that route each time the generated client method is+invoked, so the attribute is the consumer. The interface's base comes from its+registration (``AddRefitClient<ICatalogApi>().ConfigureHttpClient(c =>+c.BaseAddress = ...)`` or ``RestService.For<ICatalogApi>(url)``), which the C#+HTTP dialect collects into the mounts (:mod:`.csharp_clients`).+"""++from __future__ import annotations++import re+from functools import partial+from typing import TYPE_CHECKING++from repowise.core.workspace.origins import ContractOrigin++from ..langs import CSHARP+from ..strings import CSHARP_SYNTAX+from .client_calls import ClientCallMatch, consumer_contracts+from .csharp_clients import TYPED_CLIENT_KEY, client_base, type_at+from .csharp_http import _FileNames++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# `[Get("/path")]`, `[Post(@"/path")]`; the attribute's whole argument is the path.+_ATTRIBUTE_RE = re.compile(+ r"\[\s*(?:Refit\s*\.\s*)?(Get|Post|Put|Delete|Patch|Head|Options)\s*\(\s*(@?\"[^\"\n]*\")\s*\)"+)+_REFIT_RE = re.compile(r"\busing\s+Refit\s*;|\bRefit\s*\.")+++def _under_base(base: str, path: str) -> str:+ """Refit keeps the base's own path: ``http://h/api`` + ``/items`` is ``http://h/api/items``."""+ return base.rstrip("/") + "/" + path.lstrip("/")+++class RefitDialect:+ name = "refit"+ extensions = CSHARP+ requires = ("Refit",)++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ # `Refit` alone could be a word in a comment or another library's name.+ if _REFIT_RE.search(content) is None:+ return []+ declared = _FileNames(content).types+ matches: list[ClientCallMatch] = []+ for m in _ATTRIBUTE_RE.finditer(content):+ owner = type_at(declared, m.start())+ if owner is None:+ continue+ base = client_base(ctx.mounts, TYPED_CLIENT_KEY + owner[0])+ matches.append(+ ClientCallMatch(+ client="refit",+ url=m.group(2),+ offset=m.start(),+ method=m.group(1).upper(),+ origin=ContractOrigin.CLIENT_CALL,+ compose=partial(_under_base, base) if base is not None else None,+ )+ )+ return consumer_contracts(ctx, matches, CSHARP_SYNTAX, path_only=True)diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.pyindex fa8a89f39..419ac49d9 100644--- a/packages/core/src/repowise/core/workspace/extractors/strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py@@ -46,7 +46,8 @@ class StringSyntax:``format_heads`` name calls whose first argument is a template with``placeholder`` holes; ``format_method`` is a method called on such atemplate (Python's ``"/x/{}".format(id)``). ``unwrap_heads`` name calls whose single argument- *is* the value. ``concat`` is the string-concatenation operator, empty when+ *is* the value. ``join_heads`` name calls that join their arguments as URL+ segments (``Url.Combine(base, "items")``). ``concat`` is the string-concatenation operator, empty whenthe language's dialects do not fold concatenation. ``assignment`` locates``name = rhs`` statements for constant folding; ``assignment_strip`` drops atrailing decoration from the right-hand side (Ruby's ``.freeze``).@@ -68,6 +69,7 @@ class StringSyntax:placeholder: re.Pattern[str] | None = Noneformat_method: str = ""unwrap_heads: tuple[str, ...] = ()+ join_heads: tuple[str, ...] = ()concat: str = ""assignment: re.Pattern[str] | None = Noneassignment_strip: re.Pattern[str] | None = None@@ -371,6 +373,39 @@ def _unwrap(text: str, syntax: StringSyntax) -> str | None:return args[0] if args and len(args) == 1 else None+# A run of slashes a segment join leaves (`"api/catalog/" + "/items"`), not a scheme's.+_SLASH_RUN_RE = re.compile(r"(?<!:)/{2,}")+++def _join(text: str, syntax: StringSyntax, constants: dict[str, str]) -> str | None:+ """``Url.Combine(base, "items")`` as ``${base}/items``, or ``None``.++ Each argument is a segment that must resolve, except the first: a bare+ name there is the base and becomes a ``${name}`` hole. A later name the+ file does not settle (``new Uri(url, UriKind.Relative)``) refuses the call.+ """+ if not syntax.join_heads:+ return None # `_head_re(())` would match any text opening with `(`+ m = _head_re(syntax.join_heads).match(text)+ if m is None:+ return None+ args = _whole_call_arguments(text, m.end() - 1)+ if not args or len(args) < 2:+ return None+ parts: list[str] = []+ for i, arg in enumerate(a.strip() for a in args):+ value = resolve_string(arg, syntax, constants)+ if value is None:+ if i or not NAME_RE.fullmatch(arg):+ return None+ value = _fold(arg, syntax, constants)+ parts.append(value)+ joined = parts[0]+ for part in parts[1:]:+ joined = joined.rstrip("/") + "/" + part.lstrip("/")+ return _SLASH_RUN_RE.sub("/", joined)++def _concat(text: str, syntax: StringSyntax, constants: dict[str, str]) -> str | None:"""``a + "/x"`` as template text, or ``None`` when a piece is not readable."""if not syntax.concat or syntax.concat not in text:@@ -409,7 +444,7 @@ def resolve_string(parsed = _parse_literal(text, syntax)if parsed is not None:return _literal_text(parsed, syntax, constants)- for fold in (_format_template, _format_method, _concat):+ for fold in (_format_template, _format_method, _join, _concat):folded = fold(text, syntax, constants)if folded is not None:return folded@@ -983,7 +1018,12 @@ CSHARP_SYNTAX = StringSyntax(template_prefixes="$",interpolation=_BRACE_INTERP_RE,refuse=_ESCAPED_BRACE_RE,- unwrap_heads=("new Uri",),+ # `new(...)` is target-typed: `Uri BaseAddress = new("http://x/")`.+ unwrap_heads=("new Uri", "new"),+ # `new Uri(baseUri, "items")`, Flurl's `Url.Combine`, and the `CombineUri`+ # helper eShop-style clients define. Ceiling: a helper is known by name only;+ # reading a same-repo helper's body is the upgrade if other names turn up.+ join_heads=("new Uri", "Url.Combine", "UriHelper.CombineUri", "CombineUri"),concat="+",)diff --git a/tests/unit/workspace/test_csharp_clients.py b/tests/unit/workspace/test_csharp_clients.pynew file mode 100644index 000000000..04a581aaa--- /dev/null+++ b/tests/unit/workspace/test_csharp_clients.py@@ -0,0 +1,318 @@+"""C# client bases and wrappers read across a repo's files, YARP forwarders and Refit."""++from __future__ import annotations++import textwrap+from pathlib import Path++from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.extractors.http.csharp_clients import with_base+from repowise.core.workspace.extractors.strings import CSHARP_SYNTAX, resolve_string+from repowise.core.workspace.origins import ContractOrigin+++def _consumers(files: dict[str, str]) -> dict[tuple[str, int], tuple[str, str | None, str]]:+ walked = [(path, ".cs", textwrap.dedent(text)) for path, text in files.items()]+ contracts = HttpExtractor().extract(Path("."), "web", files=walked)+ return {+ (c.file_path, c.line): (c.contract_id, c.meta.get("host"), c.origin)+ for c in contracts+ if c.role == "consumer"+ }+++def test_typed_and_named_client_bases_place_the_host() -> None:+ found = _consumers({+ "Extensions.cs": """+ public static class Extensions+ {+ private const string Catalog = "catalog";++ public static void AddApplicationServices(this IHostApplicationBuilder builder)+ {+ builder.Services.AddHttpClient<OrderingService>(o => o.BaseAddress = new("https+http://ordering-api"))+ .AddApiVersion(1.0);+ builder.Services.AddHttpClient(Catalog)+ .ConfigureHttpClient(c => c.BaseAddress = new Uri("http://catalog-api/api/"));+ }+ }+ """,+ "OrderingService.cs": """+ public class OrderingService(HttpClient httpClient, IDistributedCache cache)+ {+ public Task<OrderRecord[]> GetOrders() => httpClient.GetFromJsonAsync<OrderRecord[]>("/api/Orders/")!;+ public Task<string?> Cached() => cache.GetStringAsync("orders/last");+ }+ """,+ "CatalogReader.cs": """+ public class CatalogReader(IHttpClientFactory factory)+ {+ private const string Catalog = "catalog";++ public async Task<string> Items()+ {+ var client = factory.CreateClient(Catalog);+ return await client.GetStringAsync("items/all");+ }+ }+ """,+ })+ assert found[("OrderingService.cs", 4)] == (+ "http::GET::/api/orders", "ordering-api", ContractOrigin.CLIENT_CALL+ )+ # A cache in the same typed client is not the HttpClient: no base.+ assert found[("OrderingService.cs", 5)] == (+ "http::GET::/orders/last", None, ContractOrigin.NAME_HEURISTIC+ )+ assert found[("CatalogReader.cs", 9)] == (+ "http::GET::/api/items/all", "catalog-api", ContractOrigin.INSTANCE_BASE+ )+++def test_a_type_registered_with_an_unread_base_takes_none() -> None:+ found = _consumers({+ "WebApp.cs": """+ class WebApp { void Add(IServiceCollection s) {+ s.AddHttpClient<CatalogService>(o => o.BaseAddress = new("http://catalog-api"));+ } }+ """,+ "Hybrid.cs": """+ class Hybrid { void Add(IServiceCollection s) {+ s.AddHttpClient<CatalogService>(o => o.BaseAddress = new(MobileBffHost));+ } }+ """,+ "CatalogService.cs": """+ public class CatalogService(HttpClient httpClient)+ {+ public Task<Item[]?> Items() => httpClient.GetFromJsonAsync<Item[]>("api/catalog/items");+ }+ """,+ })+ assert found[("CatalogService.cs", 4)][:2] == ("http::GET::/api/catalog/items", None)+++def test_wrapper_methods_are_confirmed_by_their_body() -> None:+ found = _consumers({+ "HttpService.cs": """+ public class HttpService : IHttpService+ {+ private readonly HttpClient _httpClient;+ private readonly string _apiUrl;++ public async Task<T> HttpGet<T>(string uri) where T : class+ {+ var result = await _httpClient.GetAsync($"{_apiUrl}{uri}");+ return await Read<T>(result);+ }++ public async Task<T> HttpDelete<T>(string uri, int id) where T : class+ {+ var result = await _httpClient.DeleteAsync($"{_apiUrl}{uri}/{id}");+ return await Read<T>(result);+ }+ }+ """,+ "LocalStore.cs": """+ public class LocalStore+ {+ private readonly IDistributedCache _cache;++ public Task<string?> Lookup(string key)+ {+ return _cache.GetStringAsync(key);+ }+ }+ """,+ "CatalogItemService.cs": """+ public class CatalogItemService(IHttpService httpService, LocalStore store)+ {+ public Task<Items> List() => httpService.HttpGet<Items>("catalog-items");+ public Task<Item> Get(int id) => httpService.HttpGet<Item>($"catalog-items/{id}");+ public Task<Status> Delete(int id) => httpService.HttpDelete<Status>("catalog-items", id);+ public Task<string?> Note() => store.Lookup("notes");+ }+ """,+ })+ rows = {k: v for k, v in found.items() if k[0] == "CatalogItemService.cs"}+ assert rows == {+ ("CatalogItemService.cs", 4): ("http::GET::/catalog-items", None, ContractOrigin.DATAFLOW),+ ("CatalogItemService.cs", 5): ("http::GET::/catalog-items/{param}", None, ContractOrigin.DATAFLOW),+ ("CatalogItemService.cs", 6): ("http::DELETE::/catalog-items/{param}", None, ContractOrigin.DATAFLOW),+ }+++def test_combined_uris_through_a_request_provider() -> None:+ found = _consumers({+ "RequestProvider.cs": """+ public class RequestProvider : IRequestProvider+ {+ public async Task<TResult?> GetAsync<TResult>(string uri, string token = "")+ {+ var httpClient = GetOrCreateHttpClient(token);+ using var response = await httpClient.GetAsync(uri).ConfigureAwait(false);+ return await response.Content.ReadFromJsonAsync<TResult>();+ }+ }+ """,+ "OrderService.cs": """+ public class OrderService(IRequestProvider requestProvider, ISettingsService settings)+ {+ private const string ApiUrlBase = "api/orders";+ private const string ApiVersion = "api-version=1.0";++ public async Task<Order> GetOrderAsync(int orderId)+ {+ var uri = $"{UriHelper.CombineUri(settings.GatewayOrdersEndpointBase, $"{ApiUrlBase}/{orderId}")}?{ApiVersion}";+ return await requestProvider.GetAsync<Order>(uri);+ }++ public async Task<Item[]> Items(int type)+ {+ var uri = UriHelper.CombineUri(settings.GatewayCatalogEndpointBase, $"api/catalog//items?type={type}");+ return await requestProvider.GetAsync<Item[]>(uri);+ }+ }+ """,+ })+ assert found[("OrderService.cs", 10)] == (+ "http::GET::/api/orders/{param}", None, ContractOrigin.DATAFLOW+ )+ assert found[("OrderService.cs", 16)] == ("http::GET::/api/catalog/items", None, ContractOrigin.DATAFLOW)+++def test_map_forwarder_names_the_destination() -> None:+ found = _consumers({+ "Program.cs": """+ app.MapForwarder("/product-images/{id}", "https+http://catalog-api", "/api/catalog/items/{id}/pic");+ app.MapForwarder("/basket/{**rest}", "http://basket-api", transformBuilder => { });+ """,+ })+ assert found[("Program.cs", 2)] == (+ "http::*::/api/catalog/items/{param}/pic", "catalog-api", ContractOrigin.CLIENT_CALL+ )+ # A transform in place of a path forwards the request's own path.+ assert found[("Program.cs", 3)] == ("http::*::/basket/{param}", "basket-api", ContractOrigin.CLIENT_CALL)+++def test_refit_attributes_under_their_registered_base() -> None:+ found = _consumers({+ "ICatalogApi.cs": """+ using Refit;++ public interface ICatalogApi+ {+ [Get("/items/{id}")]+ Task<Item> GetItem(int id);++ [Post("/items")]+ Task Create([Body] Item item);+ }+ """,+ "Program.cs": """+ builder.Services.AddRefitClient<ICatalogApi>()+ .ConfigureHttpClient(c => c.BaseAddress = new Uri("http://catalog-api/api/catalog"));+ """,+ "Controller.cs": """+ public class ItemsController : ControllerBase+ {+ [Get("/not-refit")]+ public IActionResult Get() => Ok();+ }+ """,+ })+ assert found == {+ ("ICatalogApi.cs", 6): ("http::GET::/api/catalog/items/{param}", "catalog-api", ContractOrigin.CLIENT_CALL),+ ("ICatalogApi.cs", 9): ("http::POST::/api/catalog/items", "catalog-api", ContractOrigin.CLIENT_CALL),+ }+++def test_with_base_follows_dotnet_resolution() -> None:+ assert with_base("http://h/api/", "items") == "http://h/api/items"+ assert with_base("http://h/api", "items") == "http://h/items"+ assert with_base("http://h/api/", "/items") == "http://h/items"+ assert with_base("http://h", "items") == "http://h/items"+ assert with_base("http://h/", "https://other/x") == "https://other/x"+ assert with_base("http://h/", "${Base}/x") == "${Base}/x"+++def test_segment_joins_resolve_and_refuse() -> None:+ def text(expr: str) -> str | None:+ return resolve_string(expr, CSHARP_SYNTAX, {"Root": '"api/catalog/"'})++ assert text('new Uri(baseUri, "items")') == "${baseUri}/items"+ assert text('Url.Combine("http://h/", Root, "/items")') == "http://h/api/catalog/items"+ assert text('new("http://h/")') == "http://h/"+ # A later piece the file does not settle is not a URL segment.+ assert text('new Uri("http://h/", UriKind.Absolute)') is None+++def test_review_shapes_that_must_not_take_a_base_or_a_wrapper() -> None:+ found = _consumers({+ "Program.cs": """+ class Setup { void Add(IServiceCollection s) {+ s.AddHttpClient<Svc>(c => c.BaseAddress = new Uri("http://catalog"));+ } }+ """,+ "Svc.cs": """+ public record class Svc(HttpClient http, Holder o)+ {+ public Task<string> A() => o.Client.GetStringAsync("/other/path");+ public Task<string> B() => http.GetStringAsync("/items/all");+ }+ """,+ "Api.cs": """+ public class Api+ {+ private readonly HttpClient _h;+ public Task<T> Get<T>(string id) { return _h.GetFromJsonAsync<T>($"api/a/{id}"); }+ public Task<T> Fetch<T>(string key) { return _h.GetFromJsonAsync<T>(key); }+ }+ """,+ "Use.cs": """+ public class Use+ {+ public async Task Run(Api api, Other other)+ {+ await api.Get<X>("5", "q");+ await api.Fetch<X>("cache-key");+ await api.Get<X>("7");+ }++ public async Task Later(Other api) { await api.Get<X>("zz"); }+ }+ """,+ })+ assert found[("Svc.cs", 4)][1] is None # a member chain is not the typed client+ assert found[("Svc.cs", 5)] == ("http::GET::/items/all", "catalog", ContractOrigin.INSTANCE_BASE)+ use = {line: row[0] for (path, line), row in found.items() if path == "Use.cs"}+ # Another overload's arity, a pass-through of a slash-free key, and a+ # parameter of another type with the same name are not wrapper calls.+ assert use == {8: "http::GET::/api/a/7"}+++def test_a_factory_binding_does_not_reach_another_methods_client() -> None:+ found = _consumers({+ "Setup.cs": """+ class Setup { void Add(IServiceCollection s) {+ s.AddHttpClient("catalog", c => c.BaseAddress = new Uri("http://catalog-api"));+ s.AddHttpClient<Reader>(c => c.BaseAddress = new Uri("http://orders-api"));+ } }+ """,+ "Reader.cs": """+ public class Reader(IHttpClientFactory factory)+ {+ public Task<string> A()+ {+ var client = factory.CreateClient("catalog");+ return client.GetStringAsync("/items/all");+ }++ public Task<string> B(HttpClient client)+ {+ return client.GetStringAsync("/orders/all");+ }+ }+ """,+ })+ assert found[("Reader.cs", 7)][1] == "catalog-api"+ assert found[("Reader.cs", 12)][1] == "orders-api"