Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): read Ktor server routing and Javalin routes as HTTP providers (#4644)
Yunus Ozend649f398d091
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex 82f8e9aad..d19423d96 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -141,7 +141,7 @@ Scans source files for HTTP routes, gRPC services, database tables, message topi| JS / TS | Express, Hono, Fastify, Koa, hapi, Elysia; NestJS controllers; Next.js App Router and `pages/api`; Remix | `fetch`; axios, ky, got, ofetch and their instances; Angular `HttpClient`; AngularJS `$http`; request, superagent, needle; HTTP-named wrappers || Python | FastAPI, Flask, Django | requests, httpx (aiohttp through wrappers the index confirms); Locust user `client` calls || PHP | Laravel | Guzzle, Laravel `Http` |-| Java / Kotlin | Spring, JAX-RS, Micronaut | Feign (`@RequestLine`, and `@FeignClient` with Spring MVC annotations, its `name` read as the host), Spring `@HttpExchange` interfaces, Spring `WebClient` and `RestClient`, `RestTemplate` (also through a getter or a `RequestEntity`), `java.net.http`, Apache HttpClient (`new HttpPost(url)`, with a base URL passed to a helper's constructor in another file), MicroProfile `@RegisterRestClient` interfaces, Ktor (Kotlin) |+| Java / Kotlin | Spring, JAX-RS, Micronaut, Ktor server routing (Kotlin), Javalin (`app.get`, v7 `config.routes`, `ApiBuilder` paths) | Feign (`@RequestLine`, and `@FeignClient` with Spring MVC annotations, its `name` read as the host), Spring `@HttpExchange` interfaces, Spring `WebClient` and `RestClient`, `RestTemplate` (also through a getter or a `RequestEntity`), `java.net.http`, Apache HttpClient (`new HttpPost(url)`, with a base URL passed to a helper's constructor in another file), MicroProfile `@RegisterRestClient` interfaces, Ktor (Kotlin) || Go | gin, echo, chi, fiber, gorilla/mux, net/http (Go 1.22 method patterns) | net/http || C# | ASP.NET (attribute and minimal API) | HttpClient (`GetAsync`, `GetFromJsonAsync`, `PostAsJsonAsync`, `GetStringAsync`, `new HttpRequestMessage(HttpMethod.X, url)`; a URL held in a local or a `const` / `readonly` field; `new Uri(base, path)` and `CombineUri` joins; typed, named and Refit client `BaseAddress`; HttpClient wrapper methods), Refit attributes, YARP `MapForwarder`, UnityWebRequest, Best.HTTP || Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex 61c6258bc..61cafe7d7 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -33,10 +33,12 @@ from .go import GoDialectfrom .go_clients import GoClientsDialectfrom .hapi import HapiDialectfrom .java_clients import JavaClientsDialect, MicroProfileClientsDialect, SpringClientsDialect+from .javalin import JavalinDialectfrom .jaxrs import JaxRsDialectfrom .js_clients import JsClientsDialectfrom .koa import KoaDialectfrom .kotlin_clients import KotlinClientsDialect+from .ktor_server import KtorServerDialectfrom .laravel import LaravelDialectfrom .micronaut import MicronautDialectfrom .mounts import merge_mount_maps@@ -75,6 +77,8 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (DjangoDialect(),JaxRsDialect(),MicronautDialect(),+ KtorServerDialect(),+ JavalinDialect(),NextAppDialect(),RemixDialect(),ApexRestDialect(),@@ -174,9 +178,7 @@ class HttpExtractor:indexed = suffix in CONSUMER_INDEX_SUFFIXES# Only spans that can still describe this file's text supersede the# regex; a missing or overrun entry leaves the dialect in charge.- symbols = (- symbols_for_content(ctx, content.count("\n") + 1) if indexed else []- )+ symbols = symbols_for_content(ctx, content.count("\n") + 1) if indexed else []lines = content.split("\n") if symbols else []# Run the index pass first: it only supersedes the text dialect for# a file it actually produced routes for. A file that yielded no@@ -184,9 +186,7 @@ class HttpExtractor:# shape the queries do not capture) must not silently delete the# routes the regex can still see in the file's text.from_parse = (- extract_http_providers(ctx, symbols, lines)- if symbols and suffix in PYTHON- else []+ extract_http_providers(ctx, symbols, lines) if symbols and suffix in PYTHON else [])contracts.extend(from_parse)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/javalin.py b/packages/core/src/repowise/core/workspace/extractors/http/javalin.pynew file mode 100644index 000000000..09a4f65b8--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/javalin.py@@ -0,0 +1,213 @@+"""Javalin HTTP provider dialect, Java and Kotlin.++Javalin registers a route in three shapes, all read here:++* a verb on the app, Express style: ``app.get("/orders/{id}", ctx -> ...)``+ (v5/v6), where ``app`` is bound to ``Javalin.create(...)`` or typed+ ``Javalin``, or chained straight off ``Javalin.create(...)``;+* a verb on the config's routes (v7): ``config.routes.get("/x", ctx -> ...)``;+* ``ApiBuilder``'s static calls, nested in ``path`` blocks:+ ``path("/api", () -> { get("/x", h); get(h); })``. A verb with no path+ serves the enclosing ``path``, by lambda scope.++A route needs a handler, which is what tells it from a lookup: a path and a+handler argument, or a path and a trailing Kotlin lambda. A dotted verb on any+other receiver (a map, the test client) is not a route, and the bare+``ApiBuilder`` calls are read only in a file that imports it.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from repowise.core.ingestion.framework_routes import HTTP_METHODS++from ..base import line_at+from ..calls import FileStrings, code_matches+from ..langs import JAVA, KOTLIN+from ..strings import JAVA_SYNTAX, KOTLIN_SYNTAX, call_arguments, match_paren+from .dialect import build_provider_contract+from .lambda_routes import (+ PrefixScope,+ block_end,+ enclosing_prefix,+ is_call_site,+ trailing_block,+)+from .mounts import compose_prefix++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++_JAVALIN = "io.javalin"+_API_BUILDER = "io.javalin.apibuilder"++_VERBS = r"get|post|put|patch|delete|head|options"++# `Javalin.create(` / `Javalin.create {`: the head of a chain of routes.+_CREATE_RE = re.compile(r"\bJavalin\s*\.\s*create\s*([({])")+# Names bound to a Javalin app: `app = Javalin.create`, `Javalin app`, `app: Javalin`.+_BINDING_RES = (+ re.compile(r"\b([A-Za-z_]\w*)\s*=\s*Javalin\s*\.\s*create\b"),+ re.compile(r"\bJavalin\s+([A-Za-z_]\w*)\b"),+ re.compile(r"\b([A-Za-z_]\w*)\s*:\s*Javalin\b"),+)+# `app.get(` / `config.routes.get(`.+_DOTTED_RE = re.compile(rf"(?<![\w.])([A-Za-z_]\w*)((?:\s*\.\s*routes)?)\s*\.\s*({_VERBS})\s*\(")+# A link of the chain after `Javalin.create(...)`: `.get(`, `.start(`.+_CHAIN_LINK_RE = re.compile(r"\s*\.\s*([A-Za-z_]\w*)\s*\(")+# ApiBuilder's bare calls: `path("/api", ...)`, `get("/x", h)`, `get(h)`, `get {`.+_BARE_RE = re.compile(rf"(?<![\w.])(path|{_VERBS})\s*([({{])")+++def _is_handler(arg: str) -> bool:+ """A lambda or method reference, the handler a path-less verb takes."""+ return "->" in arg or "::" in arg+++class _Reader:+ """The routes one file registers, by the offset of their verb."""++ def __init__(self, ctx: ScanContext) -> None:+ self.ctx = ctx+ self.content = ctx.content+ syntax = KOTLIN_SYNTAX if ctx.suffix in KOTLIN else JAVA_SYNTAX+ self.strings = FileStrings(self.content, syntax)+ self.routes: dict[int, tuple[str, str]] = {}++ def add(self, offset: int, verb: str, path: str) -> None:+ if verb.upper() in HTTP_METHODS and path:+ self.routes[offset] = (verb.upper(), path)++ def read(self, offset: int, verb: str, paren: int, scopes: list[PrefixScope] | None) -> int:+ """Record the route whose argument list opens at *paren*; return where it ends.++ *scopes* are the enclosing ``path`` blocks of an ``ApiBuilder`` call,+ ``None`` for a verb on the app.+ """+ content = self.content+ close = match_paren(content, paren)+ if close < 0:+ return -1+ args = call_arguments(content, paren, close) or []+ block = trailing_block(content, close + 1)+ path = self._own_path(args, block >= 0, scopes is not None)+ prefix = "" if scopes is None else enclosing_prefix(scopes, offset)+ if path is not None and prefix is not None:+ self.add(offset, verb, compose_prefix(prefix, path))+ return block_end(content, block) if block >= 0 else close++ def _own_path(self, args: list[str], has_block: bool, api_builder: bool) -> str | None:+ """The path a route names, ``""`` for a path-less handler, ``None`` for no route."""+ path = self.strings.text(args[0]) if args else None+ if path is not None:+ # An interpolated path, or a path with no handler (a lookup), is no route.+ has_handler = len(args) >= 2 or has_block+ return path if has_handler and "${" not in path else None+ if not api_builder:+ return None+ if (len(args) == 1 and _is_handler(args[0])) or (not args and has_block):+ return ""+ return None++ def read_app_verbs(self) -> None:+ """``app.get(...)`` on a bound app, and ``config.routes.get(...)``."""+ bindings = {m.group(1) for r in _BINDING_RES for m in r.finditer(self.content)}+ for m in code_matches(self.ctx, _DOTTED_RE):+ if m.group(2) or m.group(1) in bindings:+ self.read(m.start(3), m.group(3), m.end() - 1, None)++ def read_chains(self) -> None:+ """Verbs chained straight off ``Javalin.create(...)``."""+ for m in code_matches(self.ctx, _CREATE_RE):+ closer = "}" if m.group(1) == "{" else ")"+ self._follow_chain(match_paren(self.content, m.end() - 1, closer=closer))++ def _follow_chain(self, pos: int) -> None:+ content = self.content+ while pos >= 0:+ block = trailing_block(content, pos + 1)+ if block >= 0:+ pos = block_end(content, block)+ continue+ link = _CHAIN_LINK_RE.match(content, pos + 1)+ if link is None:+ return+ if re.fullmatch(_VERBS, link.group(1)):+ pos = self.read(link.start(1), link.group(1), link.end() - 1, None)+ else:+ pos = match_paren(content, link.end() - 1)++ def read_api_builder(self) -> None:+ """``ApiBuilder``'s bare calls, nested in ``path`` blocks."""+ if _API_BUILDER not in self.content:+ return+ scopes: list[PrefixScope] = []+ bare: list[tuple[int, str, int]] = []+ for m in code_matches(self.ctx, _BARE_RE):+ if not is_call_site(self.content, m.start()):+ continue+ if m.group(1) != "path":+ bare.append((m.start(), m.group(1), m.end() - 1))+ elif m.group(2) == "(":+ scope = self._path_scope(m.end() - 1)+ if scope is not None:+ scopes.append(scope)+ for offset, verb, opener in bare:+ if offset not in self.routes:+ self._read_bare(offset, verb, opener, scopes)++ def _path_scope(self, paren: int) -> PrefixScope | None:+ """The scope of the ``path(...)`` call whose argument list opens at *paren*."""+ content = self.content+ close = match_paren(content, paren)+ if close < 0:+ return None+ args = call_arguments(content, paren, close) or []+ path = self.strings.text(args[0]) if args else None+ if path is not None and "${" in path:+ path = None+ block = trailing_block(content, close + 1)+ if block >= 0:+ return PrefixScope(block, block_end(content, block), path)+ return PrefixScope(paren, close, path)++ def _read_bare(self, offset: int, verb: str, opener: int, scopes: list[PrefixScope]) -> None:+ if self.content[opener] == "(":+ self.read(offset, verb, opener, scopes)+ return+ # `get { ctx -> }`: Kotlin's trailing handler, no path.+ prefix = enclosing_prefix(scopes, offset)+ if prefix:+ self.add(offset, verb, prefix)++ def contracts(self) -> list[Contract]:+ out: list[Contract] = []+ for offset in sorted(self.routes):+ method, path = self.routes[offset]+ c = build_provider_contract(+ self.ctx,+ method=method,+ path_raw=path,+ framework="javalin",+ line=line_at(self.content, offset),+ )+ if c is not None:+ out.append(c)+ return out+++class JavalinDialect:+ name = "javalin"+ extensions = JAVA | KOTLIN+ requires = (_JAVALIN,)++ def extract(self, ctx: ScanContext) -> list[Contract]:+ reader = _Reader(ctx)+ reader.read_app_verbs()+ reader.read_chains()+ reader.read_api_builder()+ return reader.contracts()diff --git a/packages/core/src/repowise/core/workspace/extractors/http/ktor_server.py b/packages/core/src/repowise/core/workspace/extractors/http/ktor_server.pynew file mode 100644index 000000000..95c4a99d9--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/ktor_server.py@@ -0,0 +1,137 @@+"""Ktor server HTTP provider dialect — ``routing { route("/api") { get("{id}") { } } }``.++A Ktor route is a bare call with a trailing handler block: ``get("/x") { }``,+or ``get { }`` with no path, which serves the enclosing route. ``route("/p")``+blocks nest prefixes, and the prefix a verb serves under is every ``route``+block around it, by lambda scope. Only a verb inside ``routing { }`` or+``install(Routing) { }`` has a known root; a verb with no path straight under+it serves ``/``. In an extension function such as ``fun Route.users()``, even+inside a ``route`` block, the prefix is wherever that function is called,+which this file cannot see, so it is refused.++The receiver is what keeps the Ktor client out: a request is a dotted call on+a client value (``client.get("/x")``), a route is a bare call on the implicit+``Route`` receiver. Ktor's typed ``get<Resource> { }`` names no path and is+skipped by the same shape, as is a ``route(path, HttpMethod.X)`` block whose+verb sits in an inner ``handle { }``.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import TYPE_CHECKING++from repowise.core.ingestion.framework_routes import HTTP_METHODS++from ..base import line_at+from ..calls import FileStrings, code_matches+from ..langs import KOTLIN+from ..strings import KOTLIN_SYNTAX, call_arguments, match_paren+from .dialect import build_provider_contract+from .lambda_routes import (+ PrefixScope,+ block_end,+ enclosing_prefix,+ is_call_site,+ trailing_block,+)+from .mounts import compose_prefix++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext++# The routing DSL's package. A file that never names it declares no routes.+_KTOR_ROUTING = "io.ktor.server.routing"++# A bare call of the DSL: `routing {`, `route("/p") {`, `get("/x") {`, `get {`.+# The look-behind drops a dotted call, which is a client request or a map read.+_CALL_RE = re.compile(r"(?<![\w.])(routing|route|get|post|put|patch|delete|head|options)\s*([({])")+# The plugin form of `routing { }`.+_INSTALL_RE = re.compile(r"(?<![\w.])install\s*\(\s*Routing\s*\)\s*\{")+++@dataclass(frozen=True)+class _Call:+ """One DSL call and the block it opens.++ *path* is ``""`` when the call names none, and ``None`` when it names one+ this file cannot read.+ """++ name: str+ offset: int+ path: str | None+ n_args: int+ scope: PrefixScope+++def _read_call(content: str, strings: FileStrings, m: re.Match[str]) -> _Call | None:+ """The call *m* opens, or ``None`` when it is not one that opens a block."""+ if not is_call_site(content, m.start()):+ return None+ args: list[str] = []+ block = m.end() - 1+ if m.group(2) == "(":+ close = match_paren(content, block)+ if close < 0:+ return None+ args = call_arguments(content, block, close) or []+ block = trailing_block(content, close + 1)+ end = block_end(content, block) if block >= 0 else -1+ if end < 0:+ return None # a route always opens its handler or nested block+ path = strings.text(args[0]) if args else ""+ if path is not None and "${" in path:+ path = None+ return _Call(m.group(1), m.start(), path, len(args), PrefixScope(block, end, path))+++def _within(scopes: list[PrefixScope], offset: int) -> bool:+ return any(s.start < offset < s.end for s in scopes)+++def _served_path(call: _Call, routes: list[PrefixScope], routing: list[PrefixScope]) -> str | None:+ """The path *call* serves, or ``None`` when it is not a route this file can place."""+ if call.path is None or call.n_args > 1 or call.name.upper() not in HTTP_METHODS:+ return None+ if not _within(routing, call.offset):+ return None # not under routing { } or install(Routing) { }: the prefix is the call site's+ prefix = enclosing_prefix(routes, call.offset)+ if prefix is None:+ return None+ # `get { }` straight under `routing { }` serves the root.+ return compose_prefix(prefix, call.path) or "/"+++class KtorServerDialect:+ name = "ktor-server"+ extensions = KOTLIN+ requires = (_KTOR_ROUTING,)++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ strings = FileStrings(content, KOTLIN_SYNTAX)+ calls = [c for m in code_matches(ctx, _CALL_RE) if (c := _read_call(content, strings, m))]+ routes = [c.scope for c in calls if c.name == "route"]+ routing = [c.scope for c in calls if c.name == "routing"]+ for m in code_matches(ctx, _INSTALL_RE):+ routing.append(PrefixScope(m.end() - 1, block_end(content, m.end() - 1), ""))++ out: list[Contract] = []+ for call in calls:+ path = _served_path(call, routes, routing)+ if path is None:+ continue+ c = build_provider_contract(+ ctx,+ method=call.name.upper(),+ path_raw=path,+ framework="ktor",+ line=line_at(content, call.offset),+ )+ if c is not None:+ out.append(c)+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/lambda_routes.py b/packages/core/src/repowise/core/workspace/extractors/http/lambda_routes.pynew file mode 100644index 000000000..432e635f6--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/lambda_routes.py@@ -0,0 +1,74 @@+"""Shared reading for route DSLs that nest paths in lambdas (Ktor, Javalin).++Both frameworks declare a route as a bare call that opens a block, and nest+prefixes the same way: ``route("/api") { get("/x") { } }`` in Ktor,+``path("/api", () -> { get("/x", h); })`` in Javalin's ``ApiBuilder``. The+prefix a route serves under is every enclosing prefix block, by lambda scope+rather than by line order, so a route after a closed block does not inherit it.+"""++from __future__ import annotations++from dataclasses import dataclass++from ..strings import match_paren+from .mounts import compose_prefix+++@dataclass(frozen=True)+class PrefixScope:+ """A block that prefixes the routes inside it.++ *prefix* is ``None`` when the block's path could not be read: a route+ inside it is not served at the path written on it, so it is refused.+ """++ start: int+ end: int+ prefix: str | None+++def trailing_block(content: str, offset: int) -> int:+ """Index of the ``{`` opening a block right after *offset*, or -1."""+ i, n = offset, len(content)+ while i < n and content[i] in " \t\r\n":+ i += 1+ return i if i < n and content[i] == "{" else -1+++def block_end(content: str, open_idx: int) -> int:+ """Index of the ``}`` closing the block opened at *open_idx*, or -1."""+ return match_paren(content, open_idx, closer="}")+++def is_call_site(content: str, offset: int) -> bool:+ """True when the name at *offset* is called rather than declared.++ A declaration names a type or ``fun`` before the name (``void get(``,+ ``String get(``, ``fun get(``); a call follows a statement boundary, a+ bracket, an operator, a lambda arrow or a line break.+ """+ i = offset - 1+ while i >= 0 and content[i] in " \t":+ i -= 1+ if i < 0:+ return True+ prev = content[i]+ if prev == ">":+ # `List<String> get(` declares; `() -> get(` calls, in an expression lambda.+ return content[i - 1 : i + 1] == "->"+ return not (prev.isalnum() or prev in "_]")+++def enclosing_prefix(scopes: list[PrefixScope], offset: int) -> str | None:+ """The prefix every scope around *offset* composes to, outermost first.++ ``None`` when one of them could not be read.+ """+ prefix = ""+ for scope in sorted(scopes, key=lambda s: s.start):+ if scope.start < offset < scope.end:+ if scope.prefix is None:+ return None+ prefix = compose_prefix(prefix, scope.prefix)+ return prefixdiff --git a/tests/fixtures/workspace_http/javalin/App.java b/tests/fixtures/workspace_http/javalin/App.javanew file mode 100644index 000000000..8075b8398--- /dev/null+++ b/tests/fixtures/workspace_http/javalin/App.java@@ -0,0 +1,42 @@+package com.example;++import static io.javalin.apibuilder.ApiBuilder.delete;+import static io.javalin.apibuilder.ApiBuilder.get;+import static io.javalin.apibuilder.ApiBuilder.path;+import static io.javalin.apibuilder.ApiBuilder.post;++import io.javalin.Javalin;+import java.util.HashMap;+import java.util.Map;++public class App {+ public static void main(String[] args) {+ Javalin app = Javalin.create(config -> {+ config.router.apiBuilder(() -> {+ path("/api", () -> {+ path("users", () -> {+ get(UserController::getAll);+ post(UserController::create);+ path("{id}", () -> {+ get(UserController::getOne);+ delete(ctx -> UserController.delete(ctx));+ });+ });+ });+ get("/version", ctx -> ctx.result("1.0"));+ });+ })+ .get("/health", ctx -> ctx.result("ok"))+ .start(7070);++ app.post("/orders", ctx -> ctx.status(201));+ app.get("/orders/{id}", OrderController::getOne);++ Map<String, String> cache = new HashMap<>();+ cache.get("/orders/cached");+ }++ public String get(String key) {+ return key;+ }+}diff --git a/tests/fixtures/workspace_http/javalin/KotlinApp.kt b/tests/fixtures/workspace_http/javalin/KotlinApp.ktnew file mode 100644index 000000000..5bb936810--- /dev/null+++ b/tests/fixtures/workspace_http/javalin/KotlinApp.kt@@ -0,0 +1,17 @@+package com.example++import io.javalin.Javalin+import io.javalin.apibuilder.ApiBuilder.get+import io.javalin.apibuilder.ApiBuilder.path++fun main() {+ val app = Javalin.create { config ->+ config.router.apiBuilder {+ path("/kt") {+ get { ctx -> ctx.result("root") }+ get("/items") { ctx -> ctx.result("items") }+ }+ }+ }.start(7070)+ app.put("/kt/items/{id}") { ctx -> ctx.status(204) }+}diff --git a/tests/fixtures/workspace_http/javalin/V7App.java b/tests/fixtures/workspace_http/javalin/V7App.javanew file mode 100644index 000000000..8c7f1f91b--- /dev/null+++ b/tests/fixtures/workspace_http/javalin/V7App.java@@ -0,0 +1,12 @@+package com.example;++import io.javalin.Javalin;++public class V7App {+ public static void main(String[] args) {+ Javalin.create(config -> {+ config.routes.get("/v7/ping", ctx -> ctx.result("pong"));+ config.routes.post("/v7/items", ItemController::create);+ }).start(7070);+ }+}diff --git a/tests/fixtures/workspace_http/ktor/Application.kt b/tests/fixtures/workspace_http/ktor/Application.ktnew file mode 100644index 000000000..f1e20e1ad--- /dev/null+++ b/tests/fixtures/workspace_http/ktor/Application.kt@@ -0,0 +1,55 @@+package com.example++import io.ktor.resources.Resource+import io.ktor.server.application.Application+import io.ktor.server.resources.get+import io.ktor.server.response.respondText+import io.ktor.server.routing.Route+import io.ktor.server.routing.delete+import io.ktor.server.routing.get+import io.ktor.server.routing.post+import io.ktor.server.routing.route+import io.ktor.server.routing.routing++@Resource("/articles")+class Articles++fun Application.module() {+ routing {+ get {+ call.respondText("home")+ }+ route("/api") {+ route("/users") {+ get {+ call.respondText("all users")+ }+ get("{id}") {+ call.respondText("one user")+ }+ post {+ call.respondText("created")+ }+ }+ get("/status") {+ call.respondText("ok")+ }+ }+ get<Articles> {+ call.respondText("typed")+ }+ customerRoutes()+ }+}++fun Route.customerRoutes() {+ route("/customers") {+ delete("{id}") {+ call.respondText("deleted")+ }+ }+ // The prefix is wherever customerRoutes() is called.+ get {+ call.respondText("unknown prefix")+ }+}diff --git a/tests/fixtures/workspace_http/ktor/ApplicationTest.kt b/tests/fixtures/workspace_http/ktor/ApplicationTest.ktnew file mode 100644index 000000000..196ed5bc2--- /dev/null+++ b/tests/fixtures/workspace_http/ktor/ApplicationTest.kt@@ -0,0 +1,17 @@+package com.example++import io.ktor.client.request.get+import io.ktor.server.routing.get+import io.ktor.server.routing.routing+import io.ktor.server.testing.testApplication++class ApplicationTest {+ fun testRoot() = testApplication {+ routing {+ get("/test-only") {+ call.respondText("test route")+ }+ }+ val response = client.get("/api/users")+ }+}diff --git a/tests/unit/workspace/test_jvm_route_dialects.py b/tests/unit/workspace/test_jvm_route_dialects.pynew file mode 100644index 000000000..1946d6498--- /dev/null+++ b/tests/unit/workspace/test_jvm_route_dialects.py@@ -0,0 +1,206 @@+"""Ktor server and Javalin provider contracts.++Both frameworks declare routes as calls nested in lambdas rather than as+annotations, so a Ktor or Javalin service published no endpoints and the calls+the Ktor client reader found stayed unmatched. The claims under test are that+nested prefixes follow lambda scope, that a verb with no path serves the+enclosing path, that a client request or a map lookup stays out, and that the+contracts carry the route-registration origin.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from repowise.core.workspace.extractors.http import PROVIDER_DIALECTS, HttpExtractor+from repowise.core.workspace.extractors.http.javalin import JavalinDialect+from repowise.core.workspace.extractors.http.kotlin_clients import KotlinClientsDialect+from repowise.core.workspace.extractors.http.ktor_server import KtorServerDialect+from repowise.core.workspace.origins import ContractOrigin++_FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "workspace_http"+++class _Extractor(HttpExtractor):+ # A class attribute because `source_extensions` is a classmethod.+ provider_dialects = (KtorServerDialect(), JavalinDialect())+ consumer_dialects = (KotlinClientsDialect(),)+++def _contracts(repo: Path, role: str) -> dict[str, Any]:+ return {c.contract_id: c for c in _Extractor().extract(repo, "svc") if c.role == role}+++def _write(tmp_path: Path, name: str, text: str) -> Path:+ (tmp_path / name).write_text(text, encoding="utf-8")+ return tmp_path+++class TestKtorServer:+ def test_nested_routes_compose_their_prefixes(self) -> None:+ ids = _contracts(_FIXTURES / "ktor", "provider")+ assert "http::GET::/api/users/{param}" in ids+ assert "http::GET::/api/status" in ids++ def test_a_verb_with_no_path_serves_the_enclosing_route(self) -> None:+ ids = _contracts(_FIXTURES / "ktor", "provider")+ assert "http::GET::/api/users" in ids+ assert "http::POST::/api/users" in ids+ # Straight under `routing { }`, the root.+ assert "http::GET::/" in ids++ def test_exactly_the_declared_routes(self) -> None:+ ids = _contracts(_FIXTURES / "ktor", "provider")+ # The typed `get<Articles>` and every route in the extension function,+ # whose prefix is its call site, are not among them.+ assert set(ids) == {+ "http::GET::/",+ "http::GET::/api/users",+ "http::GET::/api/users/{param}",+ "http::POST::/api/users",+ "http::GET::/api/status",+ "http::GET::/test-only",+ }++ def test_a_client_call_stays_a_consumer(self) -> None:+ consumers = _contracts(_FIXTURES / "ktor", "consumer")+ assert "http::GET::/api/users" in consumers+ # The test's own `routing { }` serves one route; its client call adds none.+ providers = _contracts(_FIXTURES / "ktor", "provider")+ from_test = {i for i, c in providers.items() if c.file_path == "ApplicationTest.kt"}+ assert from_test == {"http::GET::/test-only"}++ def test_origin_framework_and_line(self) -> None:+ contract = _contracts(_FIXTURES / "ktor", "provider")["http::GET::/api/users/{param}"]+ assert contract.origin == ContractOrigin.ROUTE_REGISTRATION+ assert contract.meta["framework"] == "ktor"+ lines = (_FIXTURES / "ktor" / "Application.kt").read_text(encoding="utf-8").splitlines()+ assert 'get("{id}")' in lines[contract.line - 1]++ def test_a_route_after_a_closed_block_does_not_inherit_its_prefix(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ "Routes.kt",+ "import io.ktor.server.routing.*\n"+ "fun Application.module() {\n"+ " routing {\n"+ ' route("/a") { get("/x") { } }\n'+ ' get("/y") { }\n'+ " }\n"+ "}\n",+ )+ assert set(_contracts(repo, "provider")) == {"http::GET::/a/x", "http::GET::/y"}++ def test_a_prefix_it_cannot_read_refuses_the_routes_below(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ "Routes.kt",+ "import io.ktor.server.routing.*\n"+ "fun Route.items() {\n"+ " route(Paths.ITEMS) {\n"+ ' get("{id}") { }\n'+ " }\n"+ ' // get("/commented") { }\n'+ "}\n",+ )+ assert _contracts(repo, "provider") == {}++ def test_a_verb_outside_routing_is_refused(self, tmp_path: Path) -> None:+ # In an extension function, inside a `route` block or not, the path is+ # served under the call site's prefix.+ repo = _write(+ tmp_path,+ "Routes.kt",+ "import io.ktor.server.routing.*\n"+ "fun Route.items() {\n"+ ' get("/x") { }\n'+ ' route("/p") { get("/y") { } }\n'+ "}\n",+ )+ assert _contracts(repo, "provider") == {}++ def test_install_routing_serves_like_routing(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ "Routes.kt",+ "import io.ktor.server.routing.*\n"+ "fun Application.module() {\n"+ " install(Routing) {\n"+ ' get("/x") { }\n'+ " get { }\n"+ " }\n"+ "}\n",+ )+ assert set(_contracts(repo, "provider")) == {"http::GET::/x", "http::GET::/"}++ def test_a_file_without_the_routing_package_is_not_read(self, tmp_path: Path) -> None:+ repo = _write(tmp_path, "Other.kt", 'fun f() { get("/x") { } }\n')+ assert _contracts(repo, "provider") == {}+++class TestJavalin:+ def test_api_builder_paths_nest_by_scope(self) -> None:+ ids = _contracts(_FIXTURES / "javalin", "provider")+ assert "http::GET::/api/users" in ids+ assert "http::POST::/api/users" in ids+ assert "http::GET::/api/users/{param}" in ids+ assert "http::DELETE::/api/users/{param}" in ids+ # Outside every `path`, a route keeps its own path.+ assert "http::GET::/version" in ids++ def test_app_verbs_chains_and_v7_routes(self) -> None:+ ids = _contracts(_FIXTURES / "javalin", "provider")+ assert "http::GET::/health" in ids # chained off Javalin.create(...)+ assert "http::POST::/orders" in ids+ assert "http::GET::/orders/{param}" in ids+ assert "http::GET::/v7/ping" in ids+ assert "http::POST::/v7/items" in ids++ def test_kotlin_trailing_lambdas(self) -> None:+ ids = _contracts(_FIXTURES / "javalin", "provider")+ assert "http::GET::/kt" in ids+ assert "http::GET::/kt/items" in ids+ assert "http::PUT::/kt/items/{param}" in ids++ def test_a_lookup_or_a_method_declaration_is_not_a_route(self) -> None:+ ids = _contracts(_FIXTURES / "javalin", "provider")+ assert "http::GET::/orders/cached" not in ids+ assert len(ids) == 13++ def test_origin_and_framework(self) -> None:+ contract = _contracts(_FIXTURES / "javalin", "provider")["http::POST::/orders"]+ assert contract.origin == ContractOrigin.ROUTE_REGISTRATION+ assert contract.meta["framework"] == "javalin"++ def test_an_expression_lambda_verb_is_read(self, tmp_path: Path) -> None:+ # `() -> get(...)`: the arrow before the verb is a call, not a return type.+ repo = _write(+ tmp_path,+ "Routes.java",+ "import static io.javalin.apibuilder.ApiBuilder.*;\n"+ "class Routes {\n"+ ' void routes() { path("/api", () -> get("/x", ctx -> ctx.result("x"))); }\n'+ " List<String> get(String key) { return null; }\n"+ "}\n",+ )+ assert set(_contracts(repo, "provider")) == {"http::GET::/api/x"}++ def test_a_verb_on_an_unknown_receiver_is_not_a_route(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ "ClientTest.java",+ "import io.javalin.testtools.JavalinTest;\n"+ "class ClientTest {\n"+ " void run() {\n"+ ' client.get("/users", req -> req.header("A", "b"));\n'+ ' get("/bare", ctx -> ctx.result("no ApiBuilder import"));\n'+ " }\n"+ "}\n",+ )+ assert _contracts(repo, "provider") == {}+++def test_both_dialects_are_registered() -> None:+ names = {d.name for d in PROVIDER_DIALECTS}+ assert {"ktor-server", "javalin"} <= names