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(workspace): provider contracts for Flask, Micronaut and Remix (#2115)

Raghav Chamadiya843d778a6ad9
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/flask.py b/packages/core/src/repowise/core/ingestion/framework_edges/flask.py
index 84ec527b0..52ebcee0b 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/flask.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/flask.py
@@ -1,13 +1,14 @@
"""Flask ``register_blueprint`` convention edges.
-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move.
+The registration is recognised by ``ingestion.framework_routes``, shared with
+the contract dialect that reads the same call for its ``url_prefix``.
"""
from __future__ import annotations
-import re
from typing import TYPE_CHECKING, Any
+from ..framework_routes import flask_blueprints
from ..resolvers import ResolverContext, resolve_import
from .base import (
DetectionContext,
@@ -43,13 +44,14 @@ def _add_flask_edges(
if resolved and resolved in path_set:
var_to_file[name] = resolved
- bp_re = re.compile(r"register_blueprint\s*\(\s*(\w+)")
for path, parsed in parsed_files.items():
if parsed.file_info.language != "python":
continue
source = read_text(parsed)
- for match in bp_re.finditer(source):
- var_name = match.group(1)
+ for mount in flask_blueprints(source):
+ # The import map is keyed on the name this file bound, so a dotted
+ # `views.bp` is resolved through its head, as the module it names.
+ var_name = mount.var.split(".")[0]
target = var_to_file.get(var_name)
if target and target in path_set and _add_edge_if_new(graph, path, target):
count += 1
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py b/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py
index 3f8f79bb2..f2551ea8a 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/micronaut.py
@@ -5,6 +5,9 @@ but ships its own routing verbs (``@Get`` / ``@Post`` / …) and DI
qualifiers (``@Factory`` / ``@Replaces`` / ``@Primary``). Annotation
short-names collide with Spring's ``@Controller``; we disambiguate by
the import set (``io.micronaut.*``).
+
+``@Controller`` itself is recognised by ``ingestion.framework_routes``, shared
+with the contract dialect that reads the same annotation for its route prefix.
"""
from __future__ import annotations
@@ -12,6 +15,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
+from ..framework_routes import micronaut_class_paths
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -25,8 +29,9 @@ if TYPE_CHECKING:
import networkx as nx
+# ``@Controller`` is not here: it is read through the shared recogniser below,
+# which the contract dialect reads its route prefix from.
_MICRONAUT_STEREOTYPE_ANNOT = (
- "@Controller",
"@Filter",
"@Singleton",
"@Prototype",
@@ -98,7 +103,11 @@ def _add_micronaut_edges(
text = read_text(parsed)
if not text:
continue
- has_stereotype = any(annot in text for annot in _MICRONAUT_STEREOTYPE_ANNOT)
+ # Any controller entry counts, prefix or not: a `@Controller(PREFIX)`
+ # is as much a component as one written with a literal path.
+ has_stereotype = bool(micronaut_class_paths(text)) or any(
+ annot in text for annot in _MICRONAUT_STEREOTYPE_ANNOT
+ )
if not has_stereotype:
continue
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/remix.py b/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
index 4c0b3592c..e71c47dc7 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
+from ..framework_routes import remix_route_file
from ..resolvers import ResolverContext
from .base import (
DetectionContext,
@@ -26,7 +27,6 @@ if TYPE_CHECKING:
import networkx as nx
-_REMIX_ROUTE_RE = re.compile(r"(?:^|/)(?:app/)?routes/")
_SVELTE_ROUTE_RE = re.compile(r"/\+(?:page|layout|server|error)[.\w]*\.(ts|tsx|js|mjs|svelte)$")
_ASTRO_PAGE_RE = re.compile(r"(?:^|/)src/pages/")
@@ -38,9 +38,7 @@ _ROUTE_LANGUAGES = ("typescript", "javascript", "svelte")
def _is_convention_route(path: str) -> bool:
if _SVELTE_ROUTE_RE.search(path):
return True
- if _REMIX_ROUTE_RE.search(path) and any(
- path.endswith(ext) for ext in (".ts", ".tsx", ".js", ".jsx")
- ):
+ if remix_route_file(path):
return True
return bool(_ASTRO_PAGE_RE.search(path))
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index 69ef208d2..71166d0ec 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -44,11 +44,16 @@ class RouteMatch:
@dataclass(frozen=True)
class GroupMatch:
- """One router-group binding — ``var v1 = api.MapGroup("/v1")``."""
+ """One router-group binding — ``var v1 = api.MapGroup("/v1")``.
+
+ ``prefix`` is ``None`` when the call declares one this cannot read, which is
+ not the same as declaring none: a consumer must refuse the routes under such
+ a group rather than serve them at the group's own prefix.
+ """
var: str
parent: str | None
- prefix: str
+ prefix: str | None
def _opt(value: str | None) -> str | None:
@@ -453,12 +458,13 @@ def _django_path(raw: str, verb: str) -> str:
"""A URLconf pattern as a path.
Both spellings of a capture become ``{name}``: ``path()``'s
- ``<converter:name>`` and ``re_path()``'s ``(?P<name>...)``, whose anchors go
- with it. ``normalize_http_path`` reads neither, so a path left as written
- would carry the converter into the contract id.
+ ``<converter:name>``, which is Flask's rule and shares its rewrite, and
+ ``re_path()``'s ``(?P<name>...)``, whose anchors go with it.
+ ``normalize_http_path`` reads neither, so a path left as written would carry
+ the converter into the contract id.
"""
if verb == "path":
- return re.sub(r"<(?:\w+:)?(\w+)>", r"{\1}", raw)
+ return flask_path(raw)
raw = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"{\1}", raw)
return raw.strip("^$")
@@ -585,11 +591,33 @@ _NEXT_INERT_SEG_RE = re.compile(r"\(.*\)|@.*|_.*")
# `[id]`, `[...slug]`, `[[...slug]]` -> `{id}` / `{slug}`.
_NEXT_DYNAMIC_SEG_RE = re.compile(r"^\[+\.{0,3}(?P<name>[^\]]+)\]+$")
+# A named export opening its own line. Only whitespace may precede it, so a
+# commented-out handler declares nothing. Shared with Remix, which reads the
+# same declaration for a different set of names.
+_EXPORT_HEAD = r"^[^\S\n]*(?P<export>export)\s+(?:async\s+)?(?:function\s+|const\s+|let\s+|var\s+)"
+
+
+def _exported_names(content: str, pattern: re.Pattern[str]) -> list[tuple[str, int]]:
+ """``(name, offset)`` per exported handler, first declaration of each.
+
+ *offset* is the ``export`` keyword, which is where the declaration starts
+ and so the line a contract binds to.
+ """
+ out: list[tuple[str, int]] = []
+ seen: set[str] = set()
+ for m in pattern.finditer(content):
+ name = m.group("name")
+ if name not in seen:
+ seen.add(name)
+ out.append((name, m.start("export")))
+ return out
+
+
# The App Router takes the verb from the exported name and the path from the
# file's location, so a route handler's text holds no path literal at all.
_NEXT_HANDLER_RE = re.compile(
- r"export\s+(?:async\s+)?(?:function\s+|const\s+|let\s+|var\s+)"
- r"(?P<verb>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b"
+ _EXPORT_HEAD + r"(?P<name>GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\b",
+ re.MULTILINE,
)
@@ -627,11 +655,494 @@ def next_route_path(rel_path: str) -> str | None:
def next_route_verbs(content: str) -> list[tuple[str, int]]:
"""``(verb, offset)`` per exported handler, in declaration order."""
- out: list[tuple[str, int]] = []
- seen: set[str] = set()
- for m in _NEXT_HANDLER_RE.finditer(content):
- verb = m.group("verb")
- if verb not in seen:
- seen.add(verb)
- out.append((verb, m.start("verb")))
+ return _exported_names(content, _NEXT_HANDLER_RE)
+
+
+# ---------------------------------------------------------------------------
+# Flask
+# ---------------------------------------------------------------------------
+
+# @app.route("/users/<int:id>", methods=["GET", "POST"]) plus Flask 2's
+# verb-named shortcuts. `route` carries its verbs in the call rather than in the
+# decorator name, so the verb is read from the argument text for that spelling.
+# The decorator must open its own line: only whitespace may precede it, so a
+# commented-out route and one written in a trailing comment are both inert.
+_FLASK_ROUTE_RE = re.compile(
+ r"^[^\S\n]*(?P<at>@)(?P<receiver>\w+)\s*\.\s*"
+ r"(?P<verb>route|get|post|put|patch|delete)\s*(?P<paren>\()"
+ r"""\s*(?:r|rb|b)?(?P<q>['"])(?P<path>[^'"]*)(?P=q)""",
+ re.MULTILINE,
+)
+
+# `methods=["GET", "POST"]`, in either bracket style Flask accepts.
+_FLASK_METHODS_RE = re.compile(r"methods\s*=\s*[\[(](?P<verbs>[^\])]*)[\])]")
+_FLASK_METHOD_LITERAL_RE = re.compile(r"""['"](\w+)['"]""")
+
+# The keyword itself, whatever its value. Seeing one the literal pattern above
+# could not read means the route serves verbs this file does not spell.
+_FLASK_METHODS_KW_RE = re.compile(r"\bmethods\s*=")
+
+# app.register_blueprint(bp, url_prefix="/users"). The receiver is captured
+# because Flask 2 lets a blueprint register another blueprint under itself.
+_FLASK_REGISTER_RE = re.compile(
+ r"(?:(?P<parent>\w+)\s*\.\s*)?register_blueprint\s*(?P<paren>\()\s*(?P<var>\w[\w.]*)"
+)
+_FLASK_URL_PREFIX_RE = re.compile(r"""url_prefix\s*=\s*['"](?P<prefix>[^'"]*)['"]""")
+
+# The keyword itself, whatever its value: one the literal pattern above could
+# not read mounts the blueprint somewhere this file does not spell.
+_FLASK_URL_PREFIX_KW_RE = re.compile(r"\burl_prefix\s*=")
+
+# A converter, with or without arguments: `<int:id>`, `<id>`, `<path:rest>`,
+# `<string(minlength=2):code>`.
+_FLASK_CONVERTER_RE = re.compile(r"<(?:[^<>]*:)?(\w+)>")
+
+# The decorated function. Only further decorators, comments and blank lines may
+# sit between the route call and it; anything else means the decorator was not
+# on a function, and the next `def` in the file belongs to somebody else.
+_FLASK_DEF_RE = re.compile(r"^[^\S\n]*(?:async[^\S\n]+)?def[^\S\n]+(?P<name>\w+)", re.MULTILINE)
+_FLASK_BETWEEN_RE = re.compile(r"(?:[^\S\n]*(?:@[^\n]*|#[^\n]*)?\n)*[^\S\n]*")
+
+# A docstring, so a route in a usage example is not read as a route. Flask's own
+# helpers document themselves with `@app.route("/uploads/<path:name>")` blocks,
+# and those endpoints do not exist anywhere.
+_TRIPLE_QUOTE_RE = re.compile(r'"""|\'\'\'')
+
+
+def _docstring_spans(content: str) -> list[tuple[int, int]]:
+ """``(start, end)`` of every triple-quoted string in *content*, in order.
+
+ A span is closed by its own delimiter, so a ``'''`` written inside a
+ ``\"\"\"`` block does not end it. An unterminated opener ends the walk rather
+ than swallowing the rest of the file.
+ """
+ spans: list[tuple[int, int]] = []
+ pos = 0
+ while (m := _TRIPLE_QUOTE_RE.search(content, pos)) is not None:
+ close = content.find(m.group(), m.end())
+ if close == -1:
+ break
+ pos = close + 3
+ spans.append((m.start(), pos))
+ return spans
+
+
+def flask_path(raw: str) -> str:
+ """A Flask rule as a path: every converter spelling becomes ``{name}``.
+
+ ``normalize_http_path`` reads ``<...>`` as ordinary text and would carry the
+ converter into the contract id, so the rewrite happens here, as it does for
+ Django's ``<converter:name>``.
+ """
+ return _FLASK_CONVERTER_RE.sub(r"{\1}", raw)
+
+
+def _flask_handler(content: str, after: int) -> str | None:
+ """The name of the function decorated by a route call ending at *after*."""
+ m = _FLASK_DEF_RE.search(content, after)
+ if m is None or not _FLASK_BETWEEN_RE.fullmatch(content, after, m.start()):
+ return None
+ return m.group("name")
+
+
+def _flask_verbs(args: str, verb: str) -> list[str]:
+ """The methods a route decorator declares, in the order written.
+
+ Empty when the call names its methods through a variable
+ (``methods=HTTP_METHODS``): the route serves verbs the file does not spell,
+ and defaulting to GET would publish one of them as the whole endpoint.
+ """
+ if verb != "route":
+ return [verb.upper()]
+ m = _FLASK_METHODS_RE.search(args)
+ if m is None:
+ # Flask serves GET when `methods=` is absent.
+ return [] if _FLASK_METHODS_KW_RE.search(args) else ["GET"]
+ return [v.upper() for v in _FLASK_METHOD_LITERAL_RE.findall(m.group("verbs"))]
+
+
+def _flask_call_end(content: str, paren_offset: int) -> int:
+ """Index just past the call opened at *paren_offset*, or the text's end."""
+ close = match_paren(content, paren_offset, quotes="\"'", hash_comments=True)
+ return len(content) if close == -1 else close + 1
+
+
+def flask_routes(content: str) -> Iterator[RouteMatch]:
+ """Route decorators in *content*, one match per declared method.
+
+ ``receiver`` is the decorated variable as written; whether it holds an app or
+ a blueprint is the consumer's question, because the answer needs the file's
+ bindings. ``handler`` is the function directly below. A decorator inside a
+ docstring is documentation, not a route.
+ """
+ matches = list(_FLASK_ROUTE_RE.finditer(content))
+ # Paid for only once a candidate exists, and walked alongside the matches:
+ # both are in ascending offset order, so neither is rescanned.
+ spans = _docstring_spans(content) if matches else []
+ span = 0
+ for m in matches:
+ at = m.start("at")
+ while span < len(spans) and spans[span][1] <= at:
+ span += 1
+ if span < len(spans) and spans[span][0] < at:
+ continue
+ paren_offset = m.start("paren")
+ end = _flask_call_end(content, paren_offset)
+ handler = _flask_handler(content, end)
+ path = flask_path(m.group("path"))
+ for verb in _flask_verbs(content[paren_offset:end], m.group("verb").lower()):
+ yield RouteMatch(
+ verb=verb,
+ path=path,
+ receiver=m.group("receiver"),
+ handler=handler,
+ offset=at,
+ paren_offset=paren_offset,
+ )
+
+
+def flask_blueprints(content: str) -> Iterator[GroupMatch]:
+ """``register_blueprint(...)`` mounts in *content*.
+
+ ``var`` is the registered expression as written, dotted where the call names
+ one (``views.bp``): the graph consumer resolves its head against the file's
+ imports, the contract consumer keys the prefix on its final segment.
+ ``prefix`` is empty when the call carries no ``url_prefix=`` and ``None``
+ when it carries one this cannot read (``url_prefix=PREFIX``), which is where
+ the blueprint is mounted and the routes on it are not served.
+ """
+ if "register_blueprint" not in content:
+ return
+ for m in _FLASK_REGISTER_RE.finditer(content):
+ paren_offset = m.start("paren")
+ args = content[paren_offset : _flask_call_end(content, paren_offset)]
+ pm = _FLASK_URL_PREFIX_RE.search(args)
+ if pm is None and _FLASK_URL_PREFIX_KW_RE.search(args):
+ prefix: str | None = None
+ else:
+ prefix = pm.group("prefix") if pm else ""
+ yield GroupMatch(
+ var=m.group("var"),
+ parent=_opt(m.group("parent")),
+ prefix=prefix,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Micronaut
+# ---------------------------------------------------------------------------
+
+# `@Controller("/users")` names the class prefix and `@Get("/{id}")` the
+# sub-path: the two-level shape JAX-RS spells with two annotations, written
+# with the verb in the annotation's own name. The graph side recognised
+# `@Controller` as a substring only, to stamp a role; nothing read the paths.
+_MICRONAUT_VERBS = "Get|Post|Put|Delete|Patch|Head|Options"
+
+_MICRONAUT_VERB_RE = re.compile(rf"@(?P<verb>{_MICRONAUT_VERBS})\b")
+_MICRONAUT_CONTROLLER_RE = re.compile(r"@Controller\b")
+
+# A declarative HTTP client, written with the same verb annotations as a
+# controller: its routes are calls out, not endpoints served.
+_MICRONAUT_CLIENT_RE = re.compile(r"@Client\b")
+
+# An argument list follows, or the annotation stands alone.
+_MICRONAUT_OPEN_RE = re.compile(r"\s*\(")
+
+# The path argument: positional, or named `uri =` (Micronaut's spelling) or
+# `value =` (its alias).
+_MICRONAUT_ARG_RE = re.compile(r"""\s*\(\s*(?:(?:uri|value)\s*=\s*)?["'](?P<path>[^"']*)["']""")
+
+# The first argument's keyword, when it has one. An annotation whose arguments
+# are all named and none of them a path key carries no path at all, so
+# `@Get(produces = ...)` serves the class prefix exactly as a bare `@Get` does.
+_MICRONAUT_NAMED_ARG_RE = re.compile(r"\(\s*\w+\s*=")
+
+# A keyword that does name the path: seeing one this could not read means the
+# route has a path and it is not the class prefix.
+_MICRONAUT_PATH_KEY_RE = re.compile(r"\b(?:uri|uris|value)\s*=")
+
+# A type declaration, unanchored because a Micronaut controller is routinely
+# written on one line (`@Controller("/hi") public class Hi {}`), which a
+# line-anchored match reads as no declaration at all. Java's `record` and `enum`
+# count: both carry controller annotations, and a spelling left out here is a
+# controller the graph reads as an ordinary file.
+_MICRONAUT_TYPE_RE = re.compile(r"\b(?:class|interface|object|record|enum)\s+\w+")
+
+# An RFC 6570 query or fragment expansion. Micronaut route templates carry
+# their query parameters in the path string (`/list{?args*}`), where
+# `normalize_http_path` reads them as a path parameter rather than dropping
+# them the way it drops a plain `?query`.
+_MICRONAUT_QUERY_EXPANSION_RE = re.compile(r"\{[?#&][^}]*\}")
+
+# The annotated method's name: the first identifier opening a parameter list
+# that is not itself an annotation, so an annotation run carrying calls of its
+# own (`@Produces(...)`, a nested `@Schema(...)`) is stepped over.
+_MICRONAUT_METHOD_RE = re.compile(r"(?<![@\w])(?P<name>\w+)\s*\(")
+
+
+def micronaut_annotations(content: str) -> set[int]:
+ """Offsets of every ``@`` written as code in *content*.
+
+ An annotation quoted in a doc comment or a string is documentation, not a
+ route: the guides ship whole controllers inside asciidoc snippets, and the
+ routes in them are served by nothing.
+
+ The scan reads the whole file, so a consumer wanting more than one of the
+ three readers below computes this once and hands it to each of them.
+ """
+ return {i for i, c, _ in scan_code(content, quotes='"', text_blocks=True) if c == "@"}
+
+
+def micronaut_path(raw: str) -> str:
+ """A Micronaut route template as a path, without its query expansion."""
+ return _MICRONAUT_QUERY_EXPANSION_RE.sub("", raw)
+
+
+def _micronaut_annotation_path(content: str, at: int) -> str | None:
+ """The path the annotation ending at *at* declares.
+
+ ``""`` when it names no path, which Micronaut serves at the class prefix:
+ a bare ``@Get``, and equally ``@Get(produces = ...)``, whose arguments are
+ all named and none of them the path. ``None`` when it does name one this
+ cannot read: ``uris = {…}`` names several and a constant names none, and in
+ neither case is the class prefix on its own the route.
+ """
+ opened = _MICRONAUT_OPEN_RE.match(content, at)
+ if opened is None:
+ return ""
+ m = _MICRONAUT_ARG_RE.match(content, at)
+ if m is not None:
+ return m.group("path")
+ close = match_paren(content, opened.end() - 1, quotes='"')
+ args = content[opened.end() - 1 : len(content) if close == -1 else close]
+ if _MICRONAUT_PATH_KEY_RE.search(args) or not _MICRONAUT_NAMED_ARG_RE.match(args):
+ return None
+ return ""
+
+
+def _micronaut_annotated_types(
+ content: str, pattern: re.Pattern[str], annotations: set[int] | None = None
+) -> Iterator[tuple[int, str | None]]:
+ """``(offset, path)`` per type-level match of *pattern*, ascending.
+
+ The declaration scan is JAX-RS's: an annotation run reaching a type is the
+ same shape in both. ``path`` is ``None`` when the annotation carries an
+ argument this cannot read.
+ """
+ code = micronaut_annotations(content) if annotations is None else annotations
+ for m in pattern.finditer(content):
+ if m.start() not in code:
+ continue
+ end = _jaxrs_decl_end(content, m.start())
+ if not _MICRONAUT_TYPE_RE.search(content, m.end(), end):
+ continue
+ yield m.start(), _micronaut_annotation_path(content, m.end())
+
+
+def micronaut_class_paths(
+ content: str, annotations: set[int] | None = None
+) -> list[tuple[int, str | None]]:
+ """``(offset, prefix)`` per type-level ``@Controller``, ascending.
+
+ A controller whose prefix is a constant keeps its entry with a ``None``
+ prefix. It is still a controller, which is what the graph reads, and the
+ routes under it are refused by the contract consumer rather than published
+ at a path nothing serves.
+ """
+ if "@Controller" not in content:
+ return []
+ return [
+ (offset, None if path is None else micronaut_path(path).rstrip("/"))
+ for offset, path in _micronaut_annotated_types(
+ content, _MICRONAUT_CONTROLLER_RE, annotations
+ )
+ ]
+
+
+def micronaut_client_types(content: str, annotations: set[int] | None = None) -> list[int]:
+ """Offsets of every type-level ``@Client``, ascending.
+
+ A declarative client declares the endpoints it calls with the annotations a
+ controller declares the ones it serves with, so the two are told apart only
+ by which of them the verb annotation sits under.
+ """
+ if "@Client" not in content:
+ return []
+ return [
+ offset
+ for offset, _path in _micronaut_annotated_types(content, _MICRONAUT_CLIENT_RE, annotations)
+ ]
+
+
+def _micronaut_route_path(content: str, at: int) -> str | None:
+ """The sub-path an annotation ending at *at* declares, as a path."""
+ raw = _micronaut_annotation_path(content, at)
+ return None if raw is None else micronaut_path(raw)
+
+
+def micronaut_routes(content: str, annotations: set[int] | None = None) -> Iterator[RouteMatch]:
+ """Verb-annotated controller methods in *content*.
+
+ ``path`` is the method's own sub-path, ``""`` when the annotation carries
+ none and the class prefix is the whole route; the prefix is stitched on by
+ the consumer, the only side that knows how to compose one. ``handler`` is
+ the method the annotation is written above.
+ """
+ code = micronaut_annotations(content) if annotations is None else annotations
+ for m in _MICRONAUT_VERB_RE.finditer(content):
+ if m.start() not in code:
+ continue
+ end = _jaxrs_decl_end(content, m.start())
+ name = _MICRONAUT_METHOD_RE.search(content, m.end(), end)
+ yield RouteMatch(
+ verb=m.group("verb").upper(),
+ path=_micronaut_route_path(content, m.end()),
+ receiver=None,
+ handler=name.group("name") if name is not None else None,
+ offset=m.start(),
+ paren_offset=m.start(),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Remix
+# ---------------------------------------------------------------------------
+
+# Remix serves what it finds under `app/routes/`, so no route call exists to
+# read: the path is the file's name read as a grammar and the verb is the name
+# of each exported handler. `app/` is optional because the app directory is
+# configurable and a repo that moves it still writes `routes/` under it.
+_REMIX_ROUTES_DIR_RE = re.compile(r"(?:^|/)(?:app/)?routes/")
+
+REMIX_ROUTE_EXTS: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx")
+
+# A test written beside the route it exercises. `routes/` holds both.
+_REMIX_TEST_RE = re.compile(r"\.(?:test|spec)\.")
+
+# `loader` answers a GET. `action` answers every verb that is not a GET and the
+# file never says which, so the route is recorded with the unknown-verb marker
+# the URLconf dialects use rather than a guessed POST.
+_REMIX_EXPORT_RE = re.compile(_EXPORT_HEAD + r"(?P<name>loader|action)\b", re.MULTILINE)
+
+#: The HTTP method each exported handler answers.
+REMIX_HANDLER_VERBS: dict[str, str] = {"loader": "GET", "action": "*"}
+
+
+def remix_route_file(rel_path: str) -> bool:
+ """True when *rel_path* is a route Remix loads by filesystem convention."""
+ if not _REMIX_ROUTES_DIR_RE.search(rel_path):
+ return False
+ name = rel_path.rsplit("/", 1)[-1]
+ if _REMIX_TEST_RE.search(name):
+ return False
+ return name.endswith(REMIX_ROUTE_EXTS)
+
+
+def _remix_strip_ext(name: str) -> str:
+ for ext in REMIX_ROUTE_EXTS:
+ if name.endswith(ext):
+ return name[: -len(ext)]
+ return name
+
+
+#: Written before a character the route name escaped, so the grammar below can
+#: tell ``.`` from ``[.]`` without a second pass over the name.
+_REMIX_ESCAPE_MARK = "\x00"
+
+
+def _remix_split(part: str) -> list[str]:
+ """The segments of one dotted route name, escapes marked.
+
+ ``.`` separates segments, and inside ``[...]`` every character is literal:
+ that is how a route serves a file name (``sitemap[.]xml``). The escape
+ covers the bracketed characters and no more, so each one is marked rather
+ than the segment holding it: ``$id[.]json`` is still a parameter.
+ """
+ segments: list[str] = []
+ current = ""
+ in_escape = False
+ for ch in part:
+ if ch == "[" and not in_escape:
+ in_escape = True
+ elif ch == "]" and in_escape:
+ in_escape = False
+ elif ch == "." and not in_escape:
+ segments.append(current)
+ current = ""
+ else:
+ current += _REMIX_ESCAPE_MARK + ch if in_escape else ch
+ segments.append(current)
+ return segments
+
+
+def _remix_chars(segment: str) -> list[tuple[str, bool]]:
+ """``(character, escaped)`` pairs, reading the marker back off *segment*."""
+ out: list[tuple[str, bool]] = []
+ marked = False
+ for ch in segment:
+ if ch == _REMIX_ESCAPE_MARK and not marked:
+ marked = True
+ continue
+ out.append((ch, marked))
+ marked = False
return out
+
+
+def _remix_segment_path(segment: str) -> str | None:
+ """The URL segment a route-name segment names, or None when it names none.
+
+ Every rule reads unescaped characters only: a ``$`` or a ``_`` written
+ inside brackets is part of the name the route serves, not grammar.
+ """
+ chars = _remix_chars(segment)
+ if chars and chars[0] == ("_", False):
+ # `_index` and every other pathless layout: nesting, not a URL segment.
+ return None
+ # A trailing underscore opts the route out of its parent's layout, which
+ # changes what renders and not what is served.
+ while chars and chars[-1] == ("_", False):
+ chars.pop()
+ if len(chars) > 1 and chars[0] == ("(", False) and chars[-1] == (")", False):
+ # Optional. Recorded in its present form: the absent form is a second
+ # path, and emitting both would publish an endpoint per combination.
+ chars = chars[1:-1]
+ if chars == [("$", False)]:
+ return "*"
+ text = "".join(ch for ch, _esc in chars)
+ if chars and chars[0] == ("$", False):
+ return ":" + text[1:]
+ return text or None
+
+
+def remix_route_path(rel_path: str) -> str | None:
+ """The URL the Remix route file *rel_path* serves, else None.
+
+ Directories separate segments exactly as ``.`` does, so the nested form
+ (``routes/users/$id.tsx``) and the flat form (``routes/users.$id.tsx``)
+ read alike. A directory whose file is named ``route`` carries the route's
+ name itself, and a trailing ``index`` is the parent's index route.
+ """
+ if not remix_route_file(rel_path):
+ return None
+ end = 0
+ for m in _REMIX_ROUTES_DIR_RE.finditer(rel_path):
+ end = m.end()
+ parts = rel_path[end:].split("/")
+ parts[-1] = _remix_strip_ext(parts[-1])
+ if len(parts) > 1 and parts[-1] == "route":
+ parts.pop()
+ raw: list[str] = []
+ for part in parts:
+ raw.extend(_remix_split(part))
+ if raw and raw[-1] == "index":
+ raw.pop()
+ segments = [seg for text in raw if (seg := _remix_segment_path(text)) is not None]
+ return "/" + "/".join(segments)
+
+
+def remix_route_verbs(content: str) -> list[tuple[str, int]]:
+ """``(verb, offset)`` per exported route handler, in declaration order."""
+ return [
+ (REMIX_HANDLER_VERBS[name], offset)
+ for name, offset in _exported_names(content, _REMIX_EXPORT_RE)
+ ]
diff --git a/packages/core/src/repowise/core/workspace/extractors/from_index.py b/packages/core/src/repowise/core/workspace/extractors/from_index.py
index bc906e8aa..c86e3443d 100644
--- a/packages/core/src/repowise/core/workspace/extractors/from_index.py
+++ b/packages/core/src/repowise/core/workspace/extractors/from_index.py
@@ -35,6 +35,7 @@ import re
from typing import TYPE_CHECKING
from .http.dialect import build_provider_contract
+from .http.flask import flask_file
from .http.mounts import compose_prefix, router_prefixes
from .langs import JS_TS, PYTHON
@@ -245,6 +246,11 @@ def extract_http_providers(
the whole file text (see the module docstring), so ``ctx.content`` is read
as well.
"""
+ # A Flask file's routes come from the Flask dialect, whose prefix rule this
+ # path cannot apply: the registration that overrides a blueprint's own
+ # prefix is keyed on a mount map only that dialect writes and reads.
+ if flask_file(ctx.content):
+ return []
# Routes before prefixes: ``router_prefixes`` scans the whole file, so it
# is worth paying for only once a route exists to stitch a prefix onto.
routes = [
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
index bb54df44f..a126cc147 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py
@@ -20,6 +20,7 @@ from .dialect import HttpDialect
from .django import DjangoDialect
from .express import ExpressDialect
from .fastapi import FastApiDialect
+from .flask import FlaskDialect
from .go import GoDialect
from .go_clients import GoClientsDialect
from .java_clients import JavaClientsDialect
@@ -27,11 +28,13 @@ from .jaxrs import JaxRsDialect
from .js_clients import JsClientsDialect
from .kotlin_clients import KotlinClientsDialect
from .laravel import LaravelDialect
+from .micronaut import MicronautDialect
from .mounts import merge_mount_maps
from .next_app import NextAppDialect
from .paths import normalize_http_path
from .php_clients import PhpClientsDialect
from .python_clients import PythonClientsDialect
+from .remix import RemixDialect
from .ruby_clients import RubyClientsDialect
from .rust_axum import RustAxumDialect
from .rust_clients import RustClientsDialect
@@ -50,6 +53,7 @@ if TYPE_CHECKING:
PROVIDER_DIALECTS: tuple[HttpDialect, ...] = (
ExpressDialect(),
FastApiDialect(),
+ FlaskDialect(),
SpringDialect(),
LaravelDialect(),
GoDialect(),
@@ -57,7 +61,9 @@ PROVIDER_DIALECTS: tuple[HttpDialect, ...] = (
RustAxumDialect(),
DjangoDialect(),
JaxRsDialect(),
+ MicronautDialect(),
NextAppDialect(),
+ RemixDialect(),
)
# HTTP-client call recognisers (one client/language each).
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py
index 349aa089c..064d6cffb 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py
@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING
from ..base import line_at
from ..langs import PYTHON
from .dialect import METHODS, build_provider_contract
+from .flask import flask_file
from .mounts import balanced_args, compose_prefix, router_prefixes
if TYPE_CHECKING:
@@ -51,6 +52,8 @@ class FastApiDialect:
Keyed by the router variable's final name segment (``pkg.router`` ->
``router``); only mounts that carry an explicit ``prefix=`` are recorded.
"""
+ if flask_file(content):
+ return {}
out: dict[str, str] = {}
for m in _INCLUDE_ROUTER_RE.finditer(content):
args = balanced_args(content, m.end() - 1) # m.end()-1 is the '('
@@ -61,6 +64,11 @@ class FastApiDialect:
return out
def extract(self, ctx: ScanContext) -> list[Contract]:
+ # `@app.get` is spelled the same in both frameworks and `app` is a
+ # conventional name in both, so a Flask file read here would publish
+ # every one of its routes a second time, labelled FastAPI.
+ if flask_file(ctx.content):
+ return []
prefixes = router_prefixes(ctx.content, "APIRouter|FastAPI")
known = set(prefixes) | _DEFAULT_ROUTER_NAMES
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/flask.py b/packages/core/src/repowise/core/workspace/extractors/http/flask.py
new file mode 100644
index 000000000..0de0962a1
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/flask.py
@@ -0,0 +1,127 @@
+"""Flask HTTP provider dialect: ``@app.route('/users/<int:id>')``.
+
+The decorator is recognised by ``ingestion.framework_routes``, shared with the
+graph-edge builder that reads the same ``register_blueprint`` call.
+
+The real path is three segments stitched together, the same two-level shape
+FastAPI has: a cross-file ``register_blueprint(bp, url_prefix=...)`` mount, the
+in-file ``Blueprint(..., url_prefix=...)`` binding, and the decorator path.
+Flask lets the registration override the blueprint's own prefix, so the mount
+wins wherever both are present.
+
+Ceilings, both stated rather than guessed at:
+
+- ``add_url_rule('/x', view_func=...)`` registers a route without a decorator.
+ It is not read, so a repo that registers that way publishes fewer endpoints
+ than it serves.
+- ``MethodView`` classes, which reach the route table through ``as_view()`` on
+ that same call, follow from it and are equally out.
+- A ``methods=`` list or a ``url_prefix=`` naming a constant rather than a
+ literal refuses the route: the verbs, or the mount, are spelled in another
+ file, and serving the decorator's own path would publish an endpoint nothing
+ answers.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ flask_blueprints,
+ flask_routes,
+)
+
+from ..base import line_at
+from ..langs import PYTHON
+from .dialect import build_provider_contract
+from .mounts import compose_prefix, router_prefixes
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+# Namespaced so a blueprint name cannot collide with a FastAPI router variable
+# in the one mount map every provider dialect shares.
+_MOUNT_PREFIX = "flask:"
+
+# `route`, `get` and `post` are ordinary attribute names, so the file has to
+# prove its decorators are Flask's before they become endpoints: without this
+# an `@app.route` on any other object is read as a route.
+_FLASK_IMPORT_RE = re.compile(
+ r"^[^\S\n]*(?:from\s+flask(?:\.[\w.]+)?\s+import\b|import\s+flask\b)|flask\.Blueprint",
+ re.MULTILINE,
+)
+
+#: Names conventionally holding an app or a blueprint where the binding is in
+#: another file (an application factory, a package ``__init__``).
+_DEFAULT_APP_NAMES = frozenset({"app", "bp", "blueprint", "api"})
+
+#: Recorded for a blueprint registered at a prefix this cannot read
+#: (``url_prefix=PREFIX``). The blueprint is mounted somewhere, and not at the
+#: prefix it declares itself, so its routes are refused rather than published at
+#: a path nothing serves.
+_UNKNOWN_MOUNT = "?unresolved"
+
+
+def flask_file(content: str) -> bool:
+ """True when *content* is a Flask module, so its decorators are routes.
+
+ Every other reader of a Python file asks this before treating ``@x.route``
+ or ``@x.get`` as an endpoint: both are ordinary attribute names, and the
+ import is the only thing in the text that says otherwise.
+ """
+ return "flask" in content and _FLASK_IMPORT_RE.search(content) is not None
+
+
+class FlaskDialect:
+ name = "flask"
+ extensions = PYTHON
+
+ def collect_mounts(self, content: str) -> dict[str, str]:
+ """``register_blueprint(bp, url_prefix=...)`` mounts declared in *content*.
+
+ Keyed by the blueprint expression's final name segment (``views.bp`` ->
+ ``bp``), which is the name its own file binds. Only registrations
+ carrying an explicit prefix are recorded; the rest leave the blueprint's
+ own ``url_prefix`` in charge. A prefix the registration names but this
+ cannot read is recorded as unknown, which refuses the routes below it.
+ """
+ if not flask_file(content):
+ return {}
+ out: dict[str, str] = {}
+ for mount in flask_blueprints(content):
+ if mount.prefix is None:
+ out[_MOUNT_PREFIX + mount.var.split(".")[-1]] = _UNKNOWN_MOUNT
+ elif mount.prefix:
+ out[_MOUNT_PREFIX + mount.var.split(".")[-1]] = mount.prefix
+ return out
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ if not flask_file(ctx.content):
+ return []
+ prefixes = router_prefixes(ctx.content, "Blueprint|Flask")
+ known = set(prefixes) | _DEFAULT_APP_NAMES
+
+ out: list[Contract] = []
+ for route in flask_routes(ctx.content):
+ if route.receiver not in known or route.verb not in HTTP_METHODS:
+ continue
+ # A registration prefix replaces the blueprint's own, as Flask does.
+ mount = ctx.mounts.get(_MOUNT_PREFIX + route.receiver)
+ if mount == _UNKNOWN_MOUNT:
+ continue
+ prefix = prefixes.get(route.receiver, "") if mount is None else mount
+ c = build_provider_contract(
+ ctx,
+ method=route.verb,
+ path_raw=compose_prefix(prefix, route.path or ""),
+ framework="flask",
+ line=line_at(ctx.content, route.offset),
+ handler=route.handler,
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/micronaut.py b/packages/core/src/repowise/core/workspace/extractors/http/micronaut.py
new file mode 100644
index 000000000..ac9164b2f
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/micronaut.py
@@ -0,0 +1,102 @@
+"""Micronaut HTTP provider dialect.
+
+``@Get`` names the verb and its argument the sub-path; the nearest
+``@Controller`` above it is the prefix. That is the two-level shape Spring and
+JAX-RS also serve, written with the verb in the annotation's own name and no
+``Mapping`` suffix, so the import is what tells the three apart: ``@Get`` and
+``@Controller`` are spelled the same in Spring's annotation set, on files this
+dialect reads too.
+
+The annotations are recognised by ``ingestion.framework_routes``, shared with
+the graph-edge builder that reads ``@Controller`` to stamp a component role.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ micronaut_annotations,
+ micronaut_class_paths,
+ micronaut_client_types,
+ micronaut_routes,
+)
+
+from ..base import line_at
+from ..langs import JAVA, KOTLIN
+from .dialect import build_provider_contract
+from .mounts import compose_prefix
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+#: The package every routing annotation this dialect reads comes from.
+_MICRONAUT_ANNOTATIONS = "io.micronaut.http.annotation"
+
+
+def _nearest(offsets: list[int], pos: int) -> int:
+ """The last offset declared before *pos*, or -1."""
+ return max((o for o in offsets if o < pos), default=-1)
+
+
+def _nearest_controller(
+ class_paths: list[tuple[int, str | None]], pos: int
+) -> tuple[int, str | None] | None:
+ """The last ``(offset, prefix)`` controller declared before *pos*, or None.
+
+ The prefix travels with the offset because a controller whose prefix could
+ not be read is still the type a route sits under: dropping it would hand
+ the route to whatever was declared above.
+ """
+ found: tuple[int, str | None] | None = None
+ for offset, prefix in class_paths:
+ if offset >= pos:
+ break
+ found = (offset, prefix)
+ return found
+
+
+class MicronautDialect:
+ name = "micronaut"
+ extensions = JAVA | KOTLIN
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ content = ctx.content
+ if _MICRONAUT_ANNOTATIONS not in content:
+ return []
+ # One scan of the file's annotations, read by all three recognisers.
+ annotations = micronaut_annotations(content)
+ class_paths = micronaut_class_paths(content, annotations)
+ clients = micronaut_client_types(content, annotations)
+ out: list[Contract] = []
+ for route in micronaut_routes(content, annotations):
+ # HEAD and OPTIONS are Micronaut verbs the contract layer does not
+ # record; a path it could not read is refused rather than served at
+ # the class prefix.
+ if route.verb not in HTTP_METHODS or route.path is None:
+ continue
+ # A verb annotation under a `@Client` type is a call this repo
+ # makes, and one under no type-level annotation at all is the
+ # interface such a client implements. Only a `@Controller` serves.
+ controller = _nearest_controller(class_paths, route.offset)
+ if controller is None or controller[0] <= _nearest(clients, route.offset):
+ continue
+ # A prefix named by a constant is not this file's to read, and the
+ # sub-path on its own is not where the route is served.
+ if controller[1] is None:
+ continue
+ path = compose_prefix(controller[1], route.path)
+ c = build_provider_contract(
+ ctx,
+ method=route.verb,
+ path_raw=path,
+ framework="micronaut",
+ line=line_at(content, route.offset),
+ handler=route.handler,
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/remix.py b/packages/core/src/repowise/core/workspace/extractors/http/remix.py
new file mode 100644
index 000000000..0d1b49f9a
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/http/remix.py
@@ -0,0 +1,73 @@
+"""Remix HTTP provider dialect: ``app/routes/`` loaders and actions.
+
+Remix serves a route because of where its file sits, so, as in the Next.js App
+Router, the source text holds no path literal: the path is the file's name read
+as a grammar and the verb is the name of each exported handler. Both come from
+``ingestion.framework_routes``, shared with the graph-edge builder that uses the
+same convention test to find files loaded without an import.
+
+``action`` handles every verb that is not a GET and the file never says which,
+so its route is recorded as ``*``, the marker the Django and Go dialects use for
+a registration that names no method.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import (
+ remix_route_path,
+ remix_route_verbs,
+)
+
+from ..base import line_at
+from ..langs import JS_TS
+from .dialect import build_provider_contract
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from ..base import ScanContext
+
+# `routes/` is an ordinary directory name and `loader`/`action` are ordinary
+# export names, so the framework import is what says these files are served
+# rather than imported. React Router v7's framework mode is Remix v2 renamed and
+# uses the same convention, so both packages count. `react-router` matches as a
+# whole specifier only: `react-router-dom` is the client-side router, and a
+# single-page app built on it serves nothing.
+_REMIX_IMPORT_RE = re.compile(r"""@remix-run/|react-router(?=["'/])""")
+
+# The export each verb was read from, for the symbol the contract binds to.
+_HANDLER_FOR_VERB = {"GET": "loader", "*": "action"}
+
+
+class RemixDialect:
+ name = "remix"
+ extensions = JS_TS
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ # The path gate is the convention test: `remix_route_path` returns None
+ # for anything that is not a route file, so the content is read only for
+ # a file whose name already names a URL.
+ path = remix_route_path(ctx.rel_path)
+ if path is None:
+ return []
+ if not _REMIX_IMPORT_RE.search(ctx.content):
+ return []
+ out: list[Contract] = []
+ for verb, offset in remix_route_verbs(ctx.content):
+ # Bound by line, not by handler name: every route file in the repo
+ # exports the same two names, so a repo-wide lookup by name would
+ # bind to whichever one it reached first.
+ c = build_provider_contract(
+ ctx,
+ method=verb,
+ path_raw=path,
+ framework="remix",
+ line=line_at(ctx.content, offset),
+ handler=_HANDLER_FOR_VERB[verb],
+ )
+ if c is not None:
+ out.append(c)
+ return out
diff --git a/tests/unit/ingestion/test_ts_framework_edges.py b/tests/unit/ingestion/test_ts_framework_edges.py
index 7c6be9112..cfcfc0334 100644
--- a/tests/unit/ingestion/test_ts_framework_edges.py
+++ b/tests/unit/ingestion/test_ts_framework_edges.py
@@ -102,6 +102,23 @@ class TestRemixConvention:
add_framework_edges(graph, parsed, ctx, tech_stack=["remix"])
assert graph.has_edge("app/routes/_index.tsx", "utils/auth.ts")
+ def test_a_test_beside_a_route_is_not_a_convention_route(self, tmp_path: Path) -> None:
+ # A test file publishes no endpoint, so it is not loaded by convention
+ # and gets no edge of its own.
+ (tmp_path / "utils").mkdir()
+ (tmp_path / "utils" / "auth.ts").write_text("export const auth = {};\n")
+ (tmp_path / "app" / "routes").mkdir(parents=True)
+ (tmp_path / "app" / "routes" / "foo.test.tsx").write_text(
+ "import { auth } from '../../utils/auth';\nexport function loader() { return auth; }\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["remix"])
+ assert not graph.has_edge("app/routes/foo.test.tsx", "utils/auth.ts")
+
class TestTrpc:
def test_procedure_query_links_handler(self, tmp_path: Path) -> None:
diff --git a/tests/unit/workspace/test_flask_dialect.py b/tests/unit/workspace/test_flask_dialect.py
new file mode 100644
index 000000000..4a1710aef
--- /dev/null
+++ b/tests/unit/workspace/test_flask_dialect.py
@@ -0,0 +1,404 @@
+"""Flask provider contracts, from the declaration the graph already read.
+
+``register_blueprint`` had a graph edge and nothing read ``@app.route``, so a
+Flask repo published no endpoints at all: cross-repo links, breaking-change
+detection and schema recovery had nothing to attach to. The claims under test
+are that the decorator's every spelling becomes a contract with the path Flask
+actually serves, that the blueprint prefix and the registration that can
+override it both reach it, that the graph consumer still forms its edge from the
+same recognition, and that a decorator on something other than a Flask object
+stays out.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.framework_routes import flask_blueprints, flask_routes
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.workspace.extractors.http.fastapi import FastApiDialect
+from repowise.core.workspace.extractors.http.flask import FlaskDialect
+from repowise.core.workspace.extractors.http_extractor import HttpExtractor
+
+APP_PY = """\
+from flask import Flask
+from .users import bp
+
+app = Flask(__name__)
+app.register_blueprint(bp, url_prefix="/v2/users")
+
+
[email protected]("/healthz")
+def healthz():
+ return ""
+
+
[email protected]("/orders/<int:order_id>", methods=["GET", "POST"])
+def order_detail(order_id):
+ return ""
+
+
[email protected]("/version")
+def version():
+ return ""
+"""
+
+USERS_PY = """\
+from flask import Blueprint
+
+bp = Blueprint("users", __name__, url_prefix="/users")
+
+
[email protected]("/<user_id>/profile", methods=["PUT"])
+@login_required
+def profile(user_id):
+ return ""
+"""
+
+FASTAPI_PY = """\
+from fastapi import APIRouter
+
+router = APIRouter(prefix="/items")
+
+
[email protected]("/{item_id}")
+def read_item(item_id: int):
+ return {}
+"""
+
+
+class _Extractor(HttpExtractor):
+ # Class attributes because `source_extensions` is a classmethod: set on an
+ # instance they would leave the file walk reading the whole registry's set.
+ provider_dialects = (FastApiDialect(), FlaskDialect())
+ consumer_dialects = ()
+
+
+def _providers(repo: Path, alias: str = "api") -> dict[str, Any]:
+ return {c.contract_id: c for c in _Extractor().extract(repo, alias) if c.role == "provider"}
+
+
+class TestFlaskRecognition:
+ def test_every_decorator_spelling_is_read(self) -> None:
+ assert [(r.verb, r.path, r.receiver, r.handler) for r in flask_routes(APP_PY)] == [
+ ("GET", "/healthz", "app", "healthz"),
+ ("GET", "/orders/{order_id}", "app", "order_detail"),
+ ("POST", "/orders/{order_id}", "app", "order_detail"),
+ ("GET", "/version", "app", "version"),
+ ]
+
+ def test_a_converter_and_a_bare_capture_read_alike(self) -> None:
+ source = '@app.route("/a/<int:x>/<y>/<path:rest>")\ndef f(): ...\n'
+ assert [r.path for r in flask_routes(source)] == ["/a/{x}/{y}/{rest}"]
+
+ def test_the_handler_is_found_under_a_second_decorator(self) -> None:
+ (route,) = list(flask_routes(USERS_PY))
+ assert (route.verb, route.handler) == ("PUT", "profile")
+
+ def test_a_decorator_on_no_function_names_no_handler(self) -> None:
+ # Without the run check the next `def` anywhere below is captured, and
+ # an unrelated function is bound as this route's handler.
+ source = '@app.route("/x")\nvalue = 1\n\n\ndef unrelated():\n return None\n'
+ assert [r.handler for r in flask_routes(source)] == [None]
+
+ def test_a_multiline_call_keeps_its_methods_and_its_handler(self) -> None:
+ source = '@app.route(\n "/x",\n methods=["GET", "DELETE"],\n)\ndef f(): ...\n'
+ assert [(r.verb, r.handler) for r in flask_routes(source)] == [
+ ("GET", "f"),
+ ("DELETE", "f"),
+ ]
+
+ def test_a_route_in_a_docstring_is_documentation(self) -> None:
+ # Flask's own `send_from_directory` documents itself with a route block,
+ # and three endpoints that exist nowhere came out of `src/flask` alone.
+ source = (
+ "def send_it(path):\n"
+ ' """Send a file.\n\n'
+ " .. code-block:: python\n\n"
+ ' @app.route("/uploads/<path:name>")\n'
+ " def download_file(name):\n"
+ " return None\n"
+ ' """\n\n\n'
+ '@app.route("/real")\ndef real(): ...\n'
+ )
+ assert [r.path for r in flask_routes(source)] == ["/real"]
+
+ def test_a_registration_carries_its_prefix_and_its_receiver(self) -> None:
+ assert [(m.var, m.parent, m.prefix) for m in flask_blueprints(APP_PY)] == [
+ ("bp", "app", "/v2/users")
+ ]
+
+ def test_a_dotted_registration_keeps_both_of_its_segments(self) -> None:
+ # The graph consumer resolves the head, the contract consumer keys the
+ # prefix on the tail, so neither may be discarded here.
+ (mount,) = list(flask_blueprints('app.register_blueprint(views.bp, url_prefix="/v")'))
+ assert (mount.var, mount.prefix) == ("views.bp", "/v")
+
+ def test_a_registration_without_a_prefix_reads_as_empty(self) -> None:
+ (mount,) = list(flask_blueprints("bp.register_blueprint(child)"))
+ assert (mount.var, mount.parent, mount.prefix) == ("child", "bp", "")
+
+ def test_a_registration_prefix_named_by_a_variable_is_unread(self) -> None:
+ # Not the same as carrying no prefix: the blueprint is mounted, and
+ # where is spelled in a file this call does not show.
+ (mount,) = list(flask_blueprints("app.register_blueprint(bp, url_prefix=PREFIX)"))
+ assert (mount.var, mount.prefix) == ("bp", None)
+
+ def test_a_decorator_that_does_not_open_its_line_is_not_a_route(self) -> None:
+ # `@app.route` written after code or behind a `#` is a mention of a
+ # route, not a declaration of one.
+ source = (
+ '# @app.route("/ghost")\n'
+ 'x = 1 # @app.route("/trailing")\n'
+ '@app.route("/real")\ndef real(): ...\n'
+ )
+ assert [r.path for r in flask_routes(source)] == ["/real"]
+
+ def test_an_indented_decorator_is_still_a_route(self) -> None:
+ # A route registered inside an application factory is indented and is
+ # served exactly as a module-level one is.
+ source = 'def create_app(app):\n @app.route("/inner")\n def inner(): ...\n'
+ assert [r.path for r in flask_routes(source)] == ["/inner"]
+
+ def test_a_methods_list_named_by_a_variable_declares_no_verb(self) -> None:
+ # `methods=HTTP_METHODS` serves verbs this file does not spell, and
+ # Flask's GET default does not apply once the keyword is present.
+ source = '@app.route("/x", methods=HTTP_METHODS)\ndef f(): ...\n'
+ assert list(flask_routes(source)) == []
+
+ def test_a_literal_methods_list_still_reads_in_either_bracket(self) -> None:
+ source = '@app.route("/x", methods=("GET", "PUT"))\ndef f(): ...\n'
+ assert [r.verb for r in flask_routes(source)] == ["GET", "PUT"]
+
+
+class TestFlaskContracts:
+ def _extract(self, tmp_path: Path) -> dict[str, Any]:
+ (tmp_path / "app.py").write_text(APP_PY, encoding="utf-8")
+ (tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
+ return _providers(tmp_path)
+
+ def test_a_route_becomes_a_contract(self, tmp_path: Path) -> None:
+ contract = self._extract(tmp_path)["http::GET::/healthz"]
+ assert contract.meta["framework"] == "flask"
+ assert contract.meta["handler"] == "healthz"
+
+ def test_a_methods_list_becomes_one_contract_per_verb(self, tmp_path: Path) -> None:
+ ids = set(self._extract(tmp_path))
+ assert "http::GET::/orders/{param}" in ids
+ assert "http::POST::/orders/{param}" in ids
+
+ def test_a_verb_shortcut_is_a_route(self, tmp_path: Path) -> None:
+ assert "http::GET::/version" in self._extract(tmp_path)
+
+ def test_the_registration_prefix_beats_the_blueprint_prefix(self, tmp_path: Path) -> None:
+ # Flask lets `register_blueprint(url_prefix=...)` override the value the
+ # Blueprint was built with, so "/users" must not be the path served.
+ ids = set(self._extract(tmp_path))
+ assert "http::PUT::/v2/users/{param}/profile" in ids
+ assert "http::PUT::/users/{param}/profile" not in ids
+
+ def test_the_blueprint_prefix_stands_when_nothing_overrides_it(self, tmp_path: Path) -> None:
+ (tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
+ assert "http::PUT::/users/{param}/profile" in _providers(tmp_path)
+
+ def test_a_fastapi_file_yields_no_flask_contract(self, tmp_path: Path) -> None:
+ (tmp_path / "api.py").write_text(FASTAPI_PY, encoding="utf-8")
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"fastapi"}
+
+ def test_a_route_names_the_line_it_was_declared_on(self, tmp_path: Path) -> None:
+ # The line is what binds a contract to its handler symbol, and every
+ # route in a Flask file shares the file.
+ contract = self._extract(tmp_path)["http::GET::/version"]
+ assert contract.line == APP_PY.split("\n").index('@app.get("/version")') + 1
+
+ def test_a_flask_file_carries_one_framework_label(self, tmp_path: Path) -> None:
+ # `app` is a conventional router name in both frameworks, so a Flask
+ # file read by the FastAPI dialect too would publish every route twice.
+ (tmp_path / "app.py").write_text(APP_PY, encoding="utf-8")
+ (tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
+ contracts = list(_providers(tmp_path).values())
+ assert {c.meta["framework"] for c in contracts} == {"flask"}
+ assert len(contracts) == len({(c.contract_id, c.file_path) for c in contracts})
+
+ def test_the_route_spelling_is_flasks_alone(self, tmp_path: Path) -> None:
+ # `@app.get` is spelled the same in both frameworks, so `@app.route` is
+ # the only decorator that tells them apart, and FastAPI reads none of it.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ '@app.route("/only")\ndef only(): ...\n',
+ encoding="utf-8",
+ )
+ assert [c.meta["framework"] for c in _providers(tmp_path).values()] == ["flask"]
+
+
+DOTTED_APP_PY = """\
+from flask import Flask
+import blueprints
+
+app = Flask(__name__)
+app.register_blueprint(blueprints.bp, url_prefix="/v1")
+"""
+
+DOTTED_BLUEPRINTS_PY = """\
+from flask import Blueprint
+
+bp = Blueprint("views", __name__)
+
+
+def items():
+ return ""
+"""
+
+
+class TestFlaskGraphConsumer:
+ def test_a_registration_still_links_the_app_to_the_blueprint(self, tmp_path: Path) -> None:
+ (tmp_path / "app.py").write_text(APP_PY, encoding="utf-8")
+ (tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
+ graph = _graph(tmp_path, "*.py", "python", ["flask"])
+ # The same call the mount prefix above came from.
+ assert graph.has_edge("app.py", "users.py")
+
+ def test_a_dotted_registration_serves_both_consumers(self, tmp_path: Path) -> None:
+ # `blueprints.bp` is keyed on its tail by the contract side and resolved
+ # through its head by the graph side, so one recognition owes both.
+ (tmp_path / "app.py").write_text(DOTTED_APP_PY, encoding="utf-8")
+ (tmp_path / "blueprints.py").write_text(DOTTED_BLUEPRINTS_PY, encoding="utf-8")
+ assert "http::GET::/v1/items" in _providers(tmp_path)
+ graph = _graph(tmp_path, "*.py", "python", ["flask"])
+ assert graph.has_edge("app.py", "blueprints.py")
+
+
+class TestFlaskRefusals:
+ def test_a_route_decorator_outside_flask_is_not_an_endpoint(self, tmp_path: Path) -> None:
+ # `route` and `get` are ordinary attribute names, and the dialect reads
+ # every .py file, so without the import gate any repo with an object of
+ # that shape gained fabricated endpoints.
+ (tmp_path / "cache.py").write_text(
+ '@cache.get("/entries/<key>")\ndef read(key): ...\n', encoding="utf-8"
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_decorator_on_an_unknown_receiver_is_not_a_route(self, tmp_path: Path) -> None:
+ # The file is Flask's, but `limiter` is bound to nothing that serves
+ # routes, so its decorator names no endpoint.
+ (tmp_path / "app.py").write_text(
+ 'from flask import Flask\n\[email protected]("/burst")\ndef burst(): ...\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_non_http_method_is_not_a_contract(self, tmp_path: Path) -> None:
+ # Flask accepts OPTIONS and HEAD; the contract layer records neither.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ '@app.route("/probe", methods=["OPTIONS"])\ndef probe(): ...\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_add_url_rule_registers_nothing(self, tmp_path: Path) -> None:
+ # A stated ceiling: the rule carries a path but its view arrives through
+ # `view_func=`, which is where MethodView classes enter too.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n"
+ 'app.add_url_rule("/items", view_func=ItemAPI.as_view("items"),'
+ ' methods=["GET"])\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_methods_list_naming_a_variable_publishes_nothing(self, tmp_path: Path) -> None:
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ '@app.route("/x", methods=HTTP_METHODS)\ndef f(): ...\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_mount_prefix_naming_a_variable_refuses_the_routes(self, tmp_path: Path) -> None:
+ # The blueprint's own prefix is not where these routes are served: the
+ # registration replaces it, with a value only another file spells.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\nfrom .users import bp\n\n"
+ "app = Flask(__name__)\napp.register_blueprint(bp, url_prefix=PREFIX)\n",
+ encoding="utf-8",
+ )
+ (tmp_path / "users.py").write_text(USERS_PY, encoding="utf-8")
+ assert _providers(tmp_path) == {}
+
+ def test_a_bare_slash_route_is_not_a_contract(self, tmp_path: Path) -> None:
+ # A path that normalises to bare `/` carries nothing to match on, and
+ # the shared builder drops it for every framework.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ '@app.route("/")\ndef home(): ...\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_commented_out_route_is_not_an_endpoint(self, tmp_path: Path) -> None:
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ '# @app.route("/ghost")\ndef ghost(): ...\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_route_built_from_a_variable_is_refused(self, tmp_path: Path) -> None:
+ # No literal, so no path; guessing one would fabricate an endpoint.
+ (tmp_path / "app.py").write_text(
+ "from flask import Flask\n\napp = Flask(__name__)\n\n"
+ "@app.route(PREFIX + '/x')\ndef f(): ...\n",
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+
+# ---------------------------------------------------------------------------
+# Fixtures built from real parser output, never hand-written ids
+# ---------------------------------------------------------------------------
+
+
+def _parse_repo(repo: Path, glob: str, language: str) -> dict[str, Any]:
+ parser = ASTParser()
+ out: dict[str, Any] = {}
+ for src in repo.rglob(glob):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(src.resolve()),
+ language=language,
+ size_bytes=src.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _graph(repo: Path, glob: str, language: str, stack: list[str]) -> nx.DiGraph:
+ parsed = _parse_repo(repo, glob, language)
+ graph = nx.DiGraph()
+ for path in parsed:
+ graph.add_node(path)
+ ctx = ResolverContext(
+ path_set=set(parsed),
+ stem_map={Path(p).stem.lower(): [p] for p in parsed},
+ graph=graph,
+ repo_path=repo,
+ )
+ add_framework_edges(graph, parsed, ctx, stack)
+ return graph
diff --git a/tests/unit/workspace/test_from_index.py b/tests/unit/workspace/test_from_index.py
index acd0fe6b1..a3622f81c 100644
--- a/tests/unit/workspace/test_from_index.py
+++ b/tests/unit/workspace/test_from_index.py
@@ -240,7 +240,13 @@ EXAMPLE = "@router.delete('/fabricated')"'''
class TestFlaskIsInherited:
- """Flask providers via the index path — no Flask dialect module exists."""
+ """Flask providers via the index path, for a file that names no framework.
+
+ A file that imports Flask is left to the Flask dialect, which owns the
+ ``register_blueprint`` prefix rule this path cannot apply. What is inherited
+ here is the decorator shape: a ``@x.route`` above an indexed handler is read
+ as a route wherever the framework is not spelled out.
+ """
PRELUDE = 'app = Flask(__name__)\nbp = Blueprint("api", __name__)'
@@ -272,12 +278,11 @@ class TestFlaskIsInherited:
ids = _ids(_extract(prelude, ("listing", ['@bp.route("/items")'])))
assert ids == {"http::GET::/api/items"}
- def test_the_regex_layer_has_no_flask_dialect(self) -> None:
- # Guards the claim in this class's docstring: if a Flask dialect is
- # added later, this test should be deleted along with the claim.
- from repowise.core.workspace.extractors.http import PROVIDER_DIALECTS
-
- assert "flask" not in {d.name for d in PROVIDER_DIALECTS}
+ def test_a_flask_file_is_left_to_the_flask_dialect(self) -> None:
+ # One layer per file: this one cannot read a `register_blueprint`
+ # prefix, so a route it published would be served somewhere else.
+ prelude = "from flask import Flask\n\n" + self.PRELUDE
+ assert _extract(prelude, ("index", ['@app.route("/health")'])) == []
def test_no_index_on_the_context_means_no_symbols() -> None:
diff --git a/tests/unit/workspace/test_micronaut_dialect.py b/tests/unit/workspace/test_micronaut_dialect.py
new file mode 100644
index 000000000..4a2ecbc6d
--- /dev/null
+++ b/tests/unit/workspace/test_micronaut_dialect.py
@@ -0,0 +1,551 @@
+"""Micronaut provider contracts, from the annotation the graph already read.
+
+``@Controller`` was a presence check that stamped a component role, and nothing
+read the paths, so a Micronaut repo published no endpoints at all: cross-repo
+links, breaking-change detection and schema recovery had nothing to attach to.
+The claims under test are that every spelling of the verb annotation becomes a
+contract with the path Micronaut actually serves, that the class prefix reaches
+it, that the graph consumer still stamps its role and forms its injection edges
+from the same recognition, and that Spring's and JAX-RS's identically spelled
+annotations stay out.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.framework_routes import (
+ micronaut_annotations,
+ micronaut_class_paths,
+ micronaut_client_types,
+ micronaut_routes,
+)
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.workspace.extractors.http.jaxrs import JaxRsDialect
+from repowise.core.workspace.extractors.http.micronaut import MicronautDialect
+from repowise.core.workspace.extractors.http.spring import SpringDialect
+from repowise.core.workspace.extractors.http_extractor import HttpExtractor
+
+USER_CONTROLLER_JAVA = """\
+package com.example;
+
+import io.micronaut.http.HttpResponse;
+import io.micronaut.http.annotation.Body;
+import io.micronaut.http.annotation.Controller;
+import io.micronaut.http.annotation.Delete;
+import io.micronaut.http.annotation.Get;
+import io.micronaut.http.annotation.Head;
+import io.micronaut.http.annotation.Post;
+import jakarta.inject.Inject;
+
+@Controller("/v1/users")
+public class UserController {
+
+ @Inject
+ private UserService users;
+
+ @Get("/{id}")
+ public HttpResponse<String> show(String id) {
+ return HttpResponse.ok(id);
+ }
+
+ @Get
+ public List<String> list() {
+ return users.all();
+ }
+
+ @Post(uri = "/")
+ @Produces(MediaType.APPLICATION_JSON)
+ public HttpResponse<String> create(@Body String name) {
+ return HttpResponse.created(name);
+ }
+
+ @Delete(value = "/{id}")
+ public void remove(String id) {
+ }
+
+ @Head("/{id}/probe")
+ public void probe(String id) {
+ }
+
+ @Get(produces = {MediaType.TEXT_HTML}, consumes = {MediaType.TEXT_HTML})
+ public String page() {
+ return "";
+ }
+
+ @Get("/search{?q,sort}")
+ public List<String> search(String q) {
+ return List.of();
+ }
+}
+"""
+
+BOOK_CLIENT_JAVA = """\
+package com.example;
+
+import io.micronaut.http.annotation.Get;
+import io.micronaut.http.client.annotation.Client;
+
+@Client("http://localhost:8082")
+public interface BookInventoryClient {
+
+ @Get("/books/stock/{isbn}")
+ Boolean stock(String isbn);
+}
+"""
+
+CLIENT_BESIDE_CONTROLLER_JAVA = """\
+package com.example;
+
+import io.micronaut.http.annotation.Controller;
+import io.micronaut.http.annotation.Get;
+import io.micronaut.http.client.annotation.Client;
+
+public class AvailabilityTest {
+
+ @Client("/")
+ interface AvailabilityClient {
+ @Get("/called")
+ String called();
+ }
+
+ @Controller("/availability")
+ static class AvailabilityController {
+ @Get
+ String index() {
+ return "";
+ }
+ }
+}
+"""
+
+USER_SERVICE_JAVA = """\
+package com.example;
+
+import jakarta.inject.Singleton;
+
+@Singleton
+public class UserService {
+ public List<String> all() {
+ return List.of();
+ }
+}
+"""
+
+GREET_CONTROLLER_KT = """\
+package com.example
+
+import io.micronaut.http.annotation.Controller
+import io.micronaut.http.annotation.Get
+
+@Controller("/greet")
+class GreetController {
+
+ @Get("/{name}")
+ fun greet(name: String): String = "hello ${name}"
+
+ @Get
+ fun index(): String = "hi"
+}
+"""
+
+SPRING_CONTROLLER_JAVA = """\
+package com.example;
+
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/spring")
+public class SpringController {
+
+ @GetMapping("/items")
+ public String items() {
+ return "";
+ }
+}
+"""
+
+JAXRS_RESOURCE_JAVA = """\
+package com.example;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+
+@Path("/jaxrs")
+public class JaxRsResource {
+
+ @GET
+ @Path("/items")
+ public String items() {
+ return "";
+ }
+}
+"""
+
+
+class _Extractor(HttpExtractor):
+ # A class attribute because `source_extensions` is a classmethod: set on an
+ # instance it would leave the file walk reading the whole registry's set.
+ provider_dialects = (JaxRsDialect(), SpringDialect(), MicronautDialect())
+ consumer_dialects = ()
+
+
+def _providers(repo: Path, alias: str = "api") -> dict[str, Any]:
+ return {c.contract_id: c for c in _Extractor().extract(repo, alias) if c.role == "provider"}
+
+
+class TestMicronautRecognition:
+ def test_the_class_prefix_is_told_from_the_method_paths(self) -> None:
+ assert [p for _off, p in micronaut_class_paths(USER_CONTROLLER_JAVA)] == ["/v1/users"]
+
+ def test_every_annotation_spelling_is_read(self) -> None:
+ assert [(r.verb, r.path, r.handler) for r in micronaut_routes(USER_CONTROLLER_JAVA)] == [
+ ("GET", "/{id}", "show"),
+ ("GET", "", "list"),
+ ("POST", "/", "create"),
+ ("DELETE", "/{id}", "remove"),
+ ("HEAD", "/{id}/probe", "probe"),
+ ("GET", "", "page"),
+ ("GET", "/search", "search"),
+ ]
+
+ def test_arguments_that_name_no_path_leave_the_class_prefix(self) -> None:
+ # `@Get(produces = ...)` names no path at all, so Micronaut serves it
+ # exactly where a bare `@Get` is served. Reading it as unreadable cost
+ # 42 real endpoints in one sample corpus.
+ source = "@Get(produces = MediaType.TEXT_PLAIN)\npublic String page() { return null; }\n"
+ assert [r.path for r in micronaut_routes(source)] == [""]
+
+ def test_a_query_expansion_is_not_path_text(self) -> None:
+ # `{?q,sort}` is a query template. Left in, it reaches the contract id
+ # as a path parameter, because the normaliser only drops a plain `?`.
+ source = '@Get("/list{?args*}")\npublic String list() { return null; }\n'
+ assert [r.path for r in micronaut_routes(source)] == ["/list"]
+
+ def test_a_client_interface_is_told_from_a_controller(self) -> None:
+ assert micronaut_client_types(BOOK_CLIENT_JAVA) == [BOOK_CLIENT_JAVA.index("@Client")]
+ assert micronaut_class_paths(BOOK_CLIENT_JAVA) == []
+
+ def test_a_controller_written_on_one_line_is_a_controller(self) -> None:
+ # How the guides and the generated app both write a small controller,
+ # and what a declaration match anchored to the line start reads as no
+ # class at all.
+ source = '@Controller("/hi") public class Hi {\n @Get String hi() { return ""; }\n}\n'
+ assert [p for _off, p in micronaut_class_paths(source)] == ["/hi"]
+
+ def test_an_annotation_carrying_parens_does_not_hide_the_method(self) -> None:
+ source = (
+ '@Get("/r")\n@Produces({"application/json"})\n'
+ '@ApiResponse(content = @Content(schema = @Schema(name = "R")))\n'
+ "public Report report() { return null; }\n"
+ )
+ assert [r.handler for r in micronaut_routes(source)] == ["report"]
+
+ def test_a_controller_prefix_named_by_a_constant_keeps_its_entry(self) -> None:
+ # The prefix is unreadable, but the type is still a controller: the
+ # graph reads the entry, the contract side refuses the routes under it.
+ assert [p for _off, p in micronaut_class_paths(CONST_CONTROLLER_JAVA)] == [None]
+
+ def test_a_record_and_an_enum_are_controllers_too(self) -> None:
+ # Both are ordinary Micronaut controller spellings, and a declaration
+ # form left out here reads as no type at all.
+ assert [p for _off, p in micronaut_class_paths(RECORD_CONTROLLER_JAVA)] == ["/points"]
+ source = '@Controller("/modes") enum Mode { A }\n'
+ assert [p for _off, p in micronaut_class_paths(source)] == ["/modes"]
+
+ def test_one_annotation_scan_serves_all_three_readers(self) -> None:
+ # The offsets are the file's `@` positions written as code, so passing
+ # them in must read exactly as computing them per call did.
+ offsets = micronaut_annotations(USER_CONTROLLER_JAVA)
+ assert micronaut_class_paths(USER_CONTROLLER_JAVA, offsets) == micronaut_class_paths(
+ USER_CONTROLLER_JAVA
+ )
+ assert list(micronaut_routes(USER_CONTROLLER_JAVA, offsets)) == list(
+ micronaut_routes(USER_CONTROLLER_JAVA)
+ )
+ clients = micronaut_client_types(BOOK_CLIENT_JAVA)
+ assert (
+ micronaut_client_types(BOOK_CLIENT_JAVA, micronaut_annotations(BOOK_CLIENT_JAVA))
+ == clients
+ )
+
+ def test_a_kotlin_controller_reads_the_same(self) -> None:
+ assert [p for _off, p in micronaut_class_paths(GREET_CONTROLLER_KT)] == ["/greet"]
+ assert [(r.verb, r.path, r.handler) for r in micronaut_routes(GREET_CONTROLLER_KT)] == [
+ ("GET", "/{name}", "greet"),
+ ("GET", "", "index"),
+ ]
+
+ def test_a_uri_list_names_no_single_path(self) -> None:
+ # `uris = {...}` serves several paths from one method. None of them is
+ # readable here, and the class prefix on its own is not one of them.
+ source = '@Get(uris = {"/a", "/b"})\npublic String many() { return null; }\n'
+ assert [r.path for r in micronaut_routes(source)] == [None]
+
+
+CONST_CONTROLLER_JAVA = """\
+package com.example;
+
+import io.micronaut.http.annotation.Controller;
+import io.micronaut.http.annotation.Get;
+import jakarta.inject.Inject;
+
+@Controller(ApiPaths.USERS)
+public class ConstController {
+
+ @Inject
+ private UserService users;
+
+ @Get("/{id}")
+ public String show(String id) {
+ return id;
+ }
+}
+"""
+
+RECORD_CONTROLLER_JAVA = """\
+package com.example;
+
+import io.micronaut.http.annotation.Controller;
+import io.micronaut.http.annotation.Get;
+
+@Controller("/points")
+public record PointController(PointService points) {
+
+ @Get("/{id}")
+ public String show(String id) {
+ return id;
+ }
+}
+"""
+
+OPERATIONS_INTERFACE_JAVA = """\
+package com.example;
+
+import io.micronaut.http.annotation.Get;
+
+public interface BookOperations {
+
+ @Get("/books/{isbn}")
+ String find(String isbn);
+}
+"""
+
+
+class TestMicronautContracts:
+ def _extract(self, tmp_path: Path) -> dict[str, Any]:
+ (tmp_path / "UserController.java").write_text(USER_CONTROLLER_JAVA, encoding="utf-8")
+ (tmp_path / "GreetController.kt").write_text(GREET_CONTROLLER_KT, encoding="utf-8")
+ return _providers(tmp_path)
+
+ def test_the_class_prefix_is_stitched_onto_each_method(self, tmp_path: Path) -> None:
+ contract = self._extract(tmp_path)["http::GET::/v1/users/{param}"]
+ assert contract.meta["framework"] == "micronaut"
+ assert contract.meta["handler"] == "show"
+
+ def test_a_verb_with_no_path_serves_the_class_prefix(self, tmp_path: Path) -> None:
+ assert "http::GET::/v1/users" in self._extract(tmp_path)
+
+ def test_the_named_uri_form_is_a_path(self, tmp_path: Path) -> None:
+ assert "http::POST::/v1/users" in self._extract(tmp_path)
+
+ def test_the_value_alias_is_a_path(self, tmp_path: Path) -> None:
+ assert "http::DELETE::/v1/users/{param}" in self._extract(tmp_path)
+
+ def test_a_kotlin_controller_yields_the_same_contracts(self, tmp_path: Path) -> None:
+ ids = self._extract(tmp_path)
+ assert "http::GET::/greet/{param}" in ids
+ assert "http::GET::/greet" in ids
+
+ def test_a_path_parameter_normalizes_like_every_other_dialect(self, tmp_path: Path) -> None:
+ # `{id}` and `{name}` are two names for one position, so a consumer
+ # calling either must land on the same contract id.
+ ids = self._extract(tmp_path)
+ assert "http::GET::/v1/users/{id}" not in ids
+ assert "http::GET::/v1/users/{param}" in ids
+
+ def test_arguments_that_name_no_path_serve_the_class_prefix(self, tmp_path: Path) -> None:
+ assert "http::GET::/v1/users" in self._extract(tmp_path)
+
+ def test_a_query_expansion_stays_out_of_the_contract_id(self, tmp_path: Path) -> None:
+ ids = self._extract(tmp_path)
+ assert "http::GET::/v1/users/search" in ids
+ assert not any(id_.startswith("http::GET::/v1/users/search{") for id_ in ids)
+
+ def test_the_three_java_dialects_do_not_double_emit(self, tmp_path: Path) -> None:
+ (tmp_path / "UserController.java").write_text(USER_CONTROLLER_JAVA, encoding="utf-8")
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"micronaut"}
+
+
+class TestMicronautGraphConsumer:
+ def test_a_controller_is_still_an_entry_point_with_its_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "UserController.java").write_text(USER_CONTROLLER_JAVA, encoding="utf-8")
+ (tmp_path / "UserService.java").write_text(USER_SERVICE_JAVA, encoding="utf-8")
+ graph = _graph(tmp_path, "*.java", "java", ["micronaut"])
+ # The same annotation the contracts above came from: `@Controller` is
+ # the file's only Micronaut stereotype, so the role and the injection
+ # edge below it both hang off recognising it.
+ node = graph.nodes["UserController.java"]
+ assert node["is_entry_point"] is True
+ assert node["framework_role"] == "micronaut_component"
+ assert graph.has_edge("UserController.java", "UserService.java")
+
+
+class TestMicronautRefusals:
+ def test_a_spring_controller_yields_no_micronaut_contract(self, tmp_path: Path) -> None:
+ (tmp_path / "SpringController.java").write_text(SPRING_CONTROLLER_JAVA, encoding="utf-8")
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"spring"}
+
+ def test_a_jaxrs_resource_yields_no_micronaut_contract(self, tmp_path: Path) -> None:
+ (tmp_path / "JaxRsResource.java").write_text(JAXRS_RESOURCE_JAVA, encoding="utf-8")
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"jaxrs"}
+
+ def test_a_spring_annotation_set_is_not_micronauts(self, tmp_path: Path) -> None:
+ # Spring spells `@Controller` the same way, so without the import gate
+ # every Spring MVC class gained a fabricated Micronaut prefix.
+ (tmp_path / "Legacy.java").write_text(
+ "import org.springframework.stereotype.Controller;\n\n"
+ '@Controller("/legacy")\npublic class Legacy {\n'
+ ' @Get("/x")\n public String x() { return ""; }\n}\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_an_annotation_in_a_comment_is_documentation(self, tmp_path: Path) -> None:
+ (tmp_path / "Doc.java").write_text(
+ "import io.micronaut.http.annotation.Controller;\n\n"
+ '/**\n * @Controller("/docs")\n * @Get("/example")\n */\n'
+ "public class Doc {\n}\n",
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_an_annotation_in_a_string_is_not_a_route(self, tmp_path: Path) -> None:
+ (tmp_path / "Doc.java").write_text(
+ "import io.micronaut.http.annotation.Controller;\n\n"
+ '@Controller("/real")\npublic class Doc {\n'
+ ' String sample = "@Get(\\"/quoted\\")";\n}\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_uri_list_is_not_served_at_the_class_prefix(self, tmp_path: Path) -> None:
+ # A stated ceiling: several paths from one method, and reading the
+ # prefix alone would publish an endpoint Micronaut does not serve.
+ (tmp_path / "Many.java").write_text(
+ "import io.micronaut.http.annotation.Controller;\n\n"
+ '@Controller("/many")\npublic class Many {\n'
+ ' @Get(uris = {"/a", "/b"})\n public String many() { return ""; }\n}\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_declarative_client_is_not_a_provider(self, tmp_path: Path) -> None:
+ # `@Client` interfaces carry the same verb annotations as a controller
+ # and describe calls out. 403 of one sample corpus's files hold one, and
+ # reading them as endpoints published services that serve nothing.
+ (tmp_path / "BookInventoryClient.java").write_text(BOOK_CLIENT_JAVA, encoding="utf-8")
+ assert _providers(tmp_path) == {}
+
+ def test_a_client_beside_a_controller_takes_only_its_own_routes(self, tmp_path: Path) -> None:
+ # One file, both annotations: only the type each route sits under can
+ # tell them apart.
+ (tmp_path / "AvailabilityTest.java").write_text(
+ CLIENT_BESIDE_CONTROLLER_JAVA, encoding="utf-8"
+ )
+ assert set(_providers(tmp_path)) == {"http::GET::/availability"}
+
+ def test_a_constant_class_prefix_publishes_nothing(self, tmp_path: Path) -> None:
+ # The sub-path on its own is not where the route is served, so the
+ # route is refused rather than published under a guessed prefix.
+ (tmp_path / "ConstController.java").write_text(CONST_CONTROLLER_JAVA, encoding="utf-8")
+ assert _providers(tmp_path) == {}
+
+ def test_a_constant_class_prefix_is_still_a_component(self, tmp_path: Path) -> None:
+ # The graph reads the same annotation for a role and its injection
+ # edges, and neither depends on the prefix being readable.
+ (tmp_path / "ConstController.java").write_text(CONST_CONTROLLER_JAVA, encoding="utf-8")
+ (tmp_path / "UserService.java").write_text(USER_SERVICE_JAVA, encoding="utf-8")
+ graph = _graph(tmp_path, "*.java", "java", ["micronaut"])
+ node = graph.nodes["ConstController.java"]
+ assert node["is_entry_point"] is True
+ assert node["framework_role"] == "micronaut_component"
+ assert graph.has_edge("ConstController.java", "UserService.java")
+
+ def test_a_constant_method_path_publishes_nothing(self, tmp_path: Path) -> None:
+ (tmp_path / "Const.java").write_text(
+ "import io.micronaut.http.annotation.Controller;\n\n"
+ '@Controller("/const")\npublic class Const {\n'
+ ' @Get(ApiPaths.SHOW)\n public String show() { return ""; }\n}\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_an_operations_interface_serves_nothing(self, tmp_path: Path) -> None:
+ # The interface a `@Client` implements carries the verb annotations and
+ # no type-level annotation at all; only a `@Controller` serves.
+ (tmp_path / "BookOperations.java").write_text(OPERATIONS_INTERFACE_JAVA, encoding="utf-8")
+ assert _providers(tmp_path) == {}
+
+ def test_head_and_options_are_not_contracts(self, tmp_path: Path) -> None:
+ (tmp_path / "Probe.java").write_text(
+ "import io.micronaut.http.annotation.Controller;\n\n"
+ '@Controller("/probe")\npublic class Probe {\n'
+ ' @Head("/a")\n public void a() {}\n'
+ ' @Options("/b")\n public void b() {}\n}\n',
+ encoding="utf-8",
+ )
+ assert _providers(tmp_path) == {}
+
+
+# ---------------------------------------------------------------------------
+# Fixtures built from real parser output, never hand-written ids
+# ---------------------------------------------------------------------------
+
+
+def _parse_repo(repo: Path, glob: str, language: str) -> dict[str, Any]:
+ parser = ASTParser()
+ out: dict[str, Any] = {}
+ for src in repo.rglob(glob):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(src.resolve()),
+ language=language,
+ size_bytes=src.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _graph(repo: Path, glob: str, language: str, stack: list[str]) -> nx.DiGraph:
+ parsed = _parse_repo(repo, glob, language)
+ graph = nx.DiGraph()
+ for path in parsed:
+ graph.add_node(path)
+ ctx = ResolverContext(
+ path_set=set(parsed),
+ stem_map={Path(p).stem.lower(): [p] for p in parsed},
+ graph=graph,
+ repo_path=repo,
+ )
+ add_framework_edges(graph, parsed, ctx, stack)
+ return graph
diff --git a/tests/unit/workspace/test_remix_dialect.py b/tests/unit/workspace/test_remix_dialect.py
new file mode 100644
index 000000000..bfb56e28f
--- /dev/null
+++ b/tests/unit/workspace/test_remix_dialect.py
@@ -0,0 +1,301 @@
+"""Remix provider contracts, from the convention the graph already recognised.
+
+The graph side knew a file under ``routes/`` was loaded without an import, and
+stopped there: nothing read the name as a path or the exports as verbs, so a
+Remix repo published no endpoints at all. The claims under test are that every
+rule of the file-name grammar reaches the contract, that ``loader`` and
+``action`` become the verbs Remix actually answers, that the graph consumer
+still forms its edge from the same recognition, and that a ``routes/`` folder
+belonging to some other framework stays out.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import networkx as nx
+import pytest
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.framework_routes import (
+ remix_route_file,
+ remix_route_path,
+ remix_route_verbs,
+)
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.workspace.extractors.http.express import ExpressDialect
+from repowise.core.workspace.extractors.http.next_app import NextAppDialect
+from repowise.core.workspace.extractors.http.remix import RemixDialect
+from repowise.core.workspace.extractors.http_extractor import HttpExtractor
+
+NOTE_ROUTE_TSX = """\
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ return json({ note: params.noteId });
+};
+
+export const action = async ({ request }: ActionFunctionArgs) => {
+ return redirect("/notes");
+};
+
+export default function NoteDetail() {
+ return useLoaderData<typeof loader>().note;
+}
+"""
+
+HEALTHCHECK_TSX = """\
+import type { LoaderFunctionArgs } from "@remix-run/node";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ return new Response("OK");
+}
+"""
+
+EXPRESS_ROUTE_JS = """\
+const express = require("express");
+const router = express.Router();
+router.get("/reports", listReports);
+module.exports = router;
+"""
+
+NEXT_ROUTE_TS = """\
+export async function GET(request: Request) {
+ return Response.json({});
+}
+"""
+
+
+class _Extractor(HttpExtractor):
+ """The three filesystem-and-router dialects that could collide, together."""
+
+ provider_dialects = (NextAppDialect(), ExpressDialect(), RemixDialect())
+ consumer_dialects = ()
+
+
+def _providers(repo: Path, alias: str = "web") -> dict[str, Any]:
+ return {c.contract_id: c for c in _Extractor().extract(repo, alias) if c.role == "provider"}
+
+
+def _write(repo: Path, rel: str, content: str) -> None:
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+
+
+class TestRemixRecognition:
+ @pytest.mark.parametrize(
+ ("rel_path", "expected"),
+ [
+ # A dot separates segments and `$name` is a parameter.
+ ("app/routes/notes.$noteId.tsx", "/notes/:noteId"),
+ # `_index` is the index of what precedes it, and names nothing.
+ ("app/routes/notes._index.tsx", "/notes"),
+ ("app/routes/_index.tsx", "/"),
+ # A leading underscore is a pathless layout.
+ ("app/routes/_auth.login.tsx", "/login"),
+ # A trailing underscore leaves a layout, not the URL.
+ ("app/routes/app.projects_.$id.tsx", "/app/projects/:id"),
+ # An optional segment, recorded in its present form.
+ ("app/routes/($lang).about.tsx", "/:lang/about"),
+ ("app/routes/(admin).users.tsx", "/admin/users"),
+ # Brackets escape: the dot is served, not a separator.
+ ("app/routes/sitemap[.]xml.tsx", "/sitemap.xml"),
+ # The escape covers the bracketed characters and no more, so the
+ # parameter beside one is still a parameter.
+ ("app/routes/notes.$id[.]json.tsx", "/notes/:id.json"),
+ # A bare `$` is the splat.
+ ("app/routes/files.$.tsx", "/files/*"),
+ # Directories separate segments exactly as dots do.
+ ("app/routes/users/$id.tsx", "/users/:id"),
+ ("app/routes/notes.$noteId/route.tsx", "/notes/:noteId"),
+ ("routes/reports/index.jsx", "/reports"),
+ # The app directory is configurable, `routes/` is not.
+ ("src/app/routes/healthcheck.ts", "/healthcheck"),
+ ],
+ )
+ def test_the_path_comes_from_the_file_name(self, rel_path: str, expected: str) -> None:
+ assert remix_route_path(rel_path) == expected
+
+ def test_only_files_under_routes_are_routes(self) -> None:
+ assert remix_route_file("app/routes/notes.tsx")
+ assert not remix_route_file("app/models/note.server.ts")
+ assert not remix_route_file("app/routes/notes.test.tsx")
+ assert not remix_route_file("app/routes/notes.spec.ts")
+ assert not remix_route_file("app/routes/styles.css")
+ assert remix_route_path("app/models/note.server.ts") is None
+
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "export const loader = async () => null;\n",
+ "export let loader = () => null;\n",
+ "export function loader() {}\n",
+ "export async function loader({ request }) {}\n",
+ ],
+ )
+ def test_every_loader_spelling_answers_a_get(self, source: str) -> None:
+ assert [verb for verb, _off in remix_route_verbs(source)] == ["GET"]
+
+ def test_an_action_answers_an_unnamed_verb(self) -> None:
+ # Remix routes every non-GET request to the one `action`, and the file
+ # never says which of them it serves.
+ assert [v for v, _off in remix_route_verbs(NOTE_ROUTE_TSX)] == ["GET", "*"]
+
+ def test_an_export_that_does_not_open_its_line_is_not_a_handler(self) -> None:
+ # A commented-out `export const loader` declares nothing, and reading
+ # it publishes an endpoint the route does not answer.
+ assert remix_route_verbs("// export const loader = () => null;\n") == []
+
+ def test_the_exports_are_read_in_declaration_order(self) -> None:
+ source = "export const action = () => null;\nexport const loader = () => null;\n"
+ assert [v for v, _off in remix_route_verbs(source)] == ["*", "GET"]
+
+ def test_an_offset_lands_on_its_own_export(self) -> None:
+ offsets = [off for _v, off in remix_route_verbs(NOTE_ROUTE_TSX)]
+ assert [NOTE_ROUTE_TSX[o:].startswith("export") for o in offsets] == [True, True]
+
+
+class TestRemixContracts:
+ def test_a_loader_and_an_action_are_two_contracts(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/notes.$noteId.tsx", NOTE_ROUTE_TSX)
+ ids = _providers(tmp_path)
+ assert set(ids) == {"http::GET::/notes/{param}", "http::*::/notes/{param}"}
+ assert ids["http::GET::/notes/{param}"].meta["framework"] == "remix"
+
+ def test_each_verb_names_the_export_it_came_from(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/notes.$noteId.tsx", NOTE_ROUTE_TSX)
+ ids = _providers(tmp_path)
+ assert ids["http::GET::/notes/{param}"].meta["handler"] == "loader"
+ assert ids["http::*::/notes/{param}"].meta["handler"] == "action"
+
+ def test_a_contract_points_at_its_own_export(self, tmp_path: Path) -> None:
+ # Both exports live in one file, so the line is the only thing that can
+ # tell the two contracts apart when they are bound to symbols.
+ _write(tmp_path, "app/routes/notes.$noteId.tsx", NOTE_ROUTE_TSX)
+ ids = _providers(tmp_path)
+ assert ids["http::GET::/notes/{param}"].line == 4
+ assert ids["http::*::/notes/{param}"].line == 8
+
+ def test_a_route_with_only_a_loader_is_one_contract(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/healthcheck.tsx", HEALTHCHECK_TSX)
+ assert set(_providers(tmp_path)) == {"http::GET::/healthcheck"}
+
+ def test_a_nested_route_directory_reaches_the_contract(self, tmp_path: Path) -> None:
+ # Directories separate segments exactly as dots do, and the flat form
+ # is already covered, so this is the other half of the same grammar.
+ _write(tmp_path, "app/routes/users/$id.tsx", HEALTHCHECK_TSX)
+ assert set(_providers(tmp_path)) == {"http::GET::/users/{param}"}
+
+ def test_the_file_name_grammar_reaches_the_contract(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/_auth.($lang).users.$id.tsx", HEALTHCHECK_TSX)
+ assert set(_providers(tmp_path)) == {"http::GET::/{param}/users/{param}"}
+
+
+class TestRemixGraphConsumer:
+ def test_a_route_file_still_links_to_its_helper(self, tmp_path: Path) -> None:
+ # The convention test moved onto the shared recogniser; the edge that
+ # gives an imported helper its reachability has to survive the move.
+ _write(tmp_path, "app/utils/auth.ts", "export const auth = {};\n")
+ _write(
+ tmp_path,
+ "app/routes/notes.$noteId.tsx",
+ "import { auth } from '../utils/auth';\nexport function loader() { return auth; }\n",
+ )
+ graph = _graph(tmp_path, "*.ts*", "typescript", ["remix"])
+ assert graph.has_edge("app/routes/notes.$noteId.tsx", "app/utils/auth.ts")
+
+
+class TestRemixRefusals:
+ def test_an_express_routes_folder_yields_no_remix_row(self, tmp_path: Path) -> None:
+ # `routes/` is an ordinary directory name, so without the framework
+ # import every Express router file gained a fabricated file-name route.
+ _write(tmp_path, "routes/reports.js", EXPRESS_ROUTE_JS)
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"express"}
+
+ def test_a_next_route_is_not_a_remix_route(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/api/posts/route.ts", NEXT_ROUTE_TS)
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"next-app"}
+
+ def test_a_remix_route_is_not_a_next_route(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/healthcheck.tsx", HEALTHCHECK_TSX)
+ frameworks = {c.meta["framework"] for c in _providers(tmp_path).values()}
+ assert frameworks == {"remix"}
+
+ def test_a_test_beside_a_route_is_not_a_route(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/routes/notes.test.tsx", NOTE_ROUTE_TSX)
+ assert _providers(tmp_path) == {}
+
+ def test_a_route_file_exporting_no_handler_serves_no_endpoint(self, tmp_path: Path) -> None:
+ # A page renders through its parent's loader; it publishes no endpoint
+ # of its own.
+ _write(
+ tmp_path,
+ "app/routes/about.tsx",
+ 'import { Link } from "@remix-run/react";\nexport default function About() {}\n',
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_a_client_side_router_publishes_no_endpoint(self, tmp_path: Path) -> None:
+ # `react-router-dom` is the single-page router: its `routes/` folder
+ # holds components, and the app it belongs to serves nothing.
+ _write(
+ tmp_path,
+ "src/routes/notes.tsx",
+ 'import { useParams } from "react-router-dom";\nexport const loader = () => null;\n',
+ )
+ assert _providers(tmp_path) == {}
+
+ def test_the_root_route_is_not_a_contract(self, tmp_path: Path) -> None:
+ # A stated ceiling: a path that normalises to bare `/` carries nothing
+ # to match on, and the shared builder drops it for every framework.
+ _write(tmp_path, "app/routes/_index.tsx", HEALTHCHECK_TSX)
+ assert _providers(tmp_path) == {}
+
+
+# ---------------------------------------------------------------------------
+# Fixtures built from real parser output, never hand-written ids
+# ---------------------------------------------------------------------------
+
+
+def _parse_repo(repo: Path, glob: str, language: str) -> dict[str, Any]:
+ parser = ASTParser()
+ out: dict[str, Any] = {}
+ for src in repo.rglob(glob):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = FileInfo(
+ path=rel,
+ abs_path=str(src.resolve()),
+ language=language,
+ size_bytes=src.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _graph(repo: Path, glob: str, language: str, stack: list[str]) -> nx.DiGraph:
+ parsed = _parse_repo(repo, glob, language)
+ graph = nx.DiGraph()
+ for path in parsed:
+ graph.add_node(path)
+ ctx = ResolverContext(
+ path_set=set(parsed),
+ stem_map={Path(p).stem.lower(): [p] for p in parsed},
+ graph=graph,
+ repo_path=repo,
+ )
+ add_framework_edges(graph, parsed, ctx, stack)
+ return graph