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 NestJS routes, Node HTTP clients and Node ORM tables (#2527)
Raghav Chamadiya4377a54c3c0a
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex eb02f94d7..1a36a6fcf 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -328,7 +328,7 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. Symbol ids take the same `"path/to/file.py::Name"` form `get_symbol` accepts, with the same `::` / `.` / `/` separator normalisation, so an id from either tool works in the other. || `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens), `"health"` (code-health score and biomarkers), `"doc_drift"` (the documents that name this file, and whether those documents carry drift of their own). An empty `callers`, `callees` or `used_by` list sits beside a `*_basis` object: the language, how many call edges the index resolved for it, the share of those that are guesses, and a note that unbound call sites are not counted, so an empty list means no resolved edge, not proof of none || `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |-| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |+| `repo` | string | No | *(workspace only)* Target repo alias; `"all"` is not supported |**Returns per target:** Documentation summary, symbols defined, ownership percentages, freshness score, co-change partners, architectural decisions governing the file. With `include` options: source code, call graph, graph metrics, community membership.@@ -494,7 +494,8 @@ matches or resolving a `symbol_id`, read `results`.Tombstoned and `exclude_patterns`-excluded results are filtered. In workspacemode, structural and concept searches both federate across repos and merge-(this is the one tool where `repo="all"` is fully supported).+(with `get_overview`, `get_dead_code` and `get_why` with a query, one of the+four tools that accept `repo="all"`).**When to use:** Locating a function/class/method by name, resolving apath-shaped query, or discovering pages by topic: the symbol/file shapes pipediff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex a4aec649a..4591c5481 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -1035,11 +1035,11 @@ workspace/extractors/dialect.py # build_provider/consumer_contractpaths.py # normalize_http_path + URL helpersclient_calls.py # ClientCallMatch + consumer_contracts- express.py fastapi.py spring.py laravel.py go.py aspnet.py … # providers- js_clients.py python_clients.py php_clients.py … # consumers+ express.py nestjs.py fastapi.py spring.py laravel.py go.py … # providers+ js_clients.py node_clients.py python_clients.py php_clients.py # consumers__init__.py # HttpExtractor (adds router mounts + index passes)grpc/ # proto.py + languages.py (one table of stub shapes)- calls.py # call_sites / call_chain: the table reader topic and socket share+ calls.py # call_sites / call_chain / decorated_member: the table reader every type sharestopic/ # dialect.py (TopicCall table) + kafka.py rabbitmq.py nats.py redis.py# bullmq.py aws.py nestjs.py laravel.py (a repo pass: dispatch <-> job class)socket/ # dialect.py (SocketCall table) + dotnet.py python.py socketio.py broadcasting.py@@ -1062,11 +1062,11 @@ subscription) registers its extra passes, or its own `keys`, in| Contract | Providers | Consumers ||----------|-----------|-----------|-| **HTTP** | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal), Rust (Axum routes, Actix/Rocket attribute macros) | `fetch` / `axios` / URL-literal wrappers (JS/TS), `requests` / `httpx` (Python), `HttpClient` / `UnityWebRequest` / Best.HTTP (C#), `reqwest` (Rust) |+| **HTTP** | Express, Hono, Fastify, Koa, Elysia, NestJS, Next.js, Remix, FastAPI, Flask, Django, Spring, JAX-RS, Micronaut, Laravel, Go, ASP.NET, Axum/Actix/Rocket, OpenAPI 3.x | Client calls in JS/TS, Python, PHP, Java, Kotlin, Go, C#, Ruby and Rust; JS/TS client instances carry their base URL across files || **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# || **Topic** | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub, BullMQ / Bull, SQS / SNS, NestJS `ClientProxy`, Laravel job dispatch | The same libraries' consumers (including pattern subscriptions and Laravel `ShouldQueue` classes), plus RabbitMQ queue bindings || **Socket** | SignalR `MapHub`, FastAPI `@app.websocket`, `ws`, NestJS gateways; socket.io `emit`, Laravel broadcast events, Pusher `trigger` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp, `new WebSocket(url)`; socket.io `on`, Laravel Echo, pusher-js |-| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, ORM entities (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table` |+| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, Knex migrations, ORM models (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent, Prisma, TypeORM, Sequelize, Drizzle) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table`, Knex queries |See [docs/scale/WORKSPACES.md](../scale/WORKSPACES.md) for the user-facingworkspace guide.diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex b58c5a068..448b287b2 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -79,6 +79,10 @@ meaningless for a script invoked by name. See[Beyond code files](#beyond-code-files), along with[config and data formats](#config-and-data).+Cross-repo contracts (HTTP routes and calls, database tables, queues, sockets)+are listed per language and framework in+[WORKSPACES.md](../scale/WORKSPACES.md#api-contract-extraction).+## What the pipeline gives each tier| Stage | Full | Good | Partial | Lightweight | Structural |@@ -289,8 +293,8 @@ than tree-sitter.import edges, so model-level lineage, hotspots, co-change, ownership andcommunities all fall out free.- **App-to-database contracts** (workspace mode), table *providers* (DDL,- Alembic, ORM entities) pair with table *consumers* (SQL literals in app code)- on the Live System Map. See [WORKSPACES.md](../scale/WORKSPACES.md).+ migrations, ORM models) pair with table *consumers* (SQL literals and query+ builders in app code) on the Live System Map. See [WORKSPACES.md](../scale/WORKSPACES.md).- **Health markers**: stored routines get cyclomatic complexity, plus`sql_select_star`, `sql_update_delete_without_where` and `sql_cartesian_join`.All of them are **uncalibrated by construction** (no defect corpus coversdiff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.mdindex faa3f5517..8ba47b587 100644--- a/docs/scale/WORKSPACES.md+++ b/docs/scale/WORKSPACES.md@@ -225,15 +225,40 @@ Useful for:### API Contract Extraction-Scans source files for HTTP route handlers, gRPC service definitions, and message topic publishers/subscribers. Then matches providers (servers) with consumers (clients) across repos.--**Supported patterns:**+Scans source files for HTTP routes, gRPC services, database tables, message topics and socket events. Then matches providers (servers) with consumers (clients) across repos.++**HTTP routes and calls:**++| Language | Providers (routes served) | Consumers (calls made) |+|----------|---------------------------|------------------------|+| JS / TS | Express, Hono, Fastify, Koa, Elysia; NestJS controllers; Next.js App Router; Remix | `fetch`; axios, ky, got, ofetch and their instances; HTTP-named wrappers |+| Python | FastAPI, Flask, Django | requests, httpx (aiohttp through wrappers the index confirms) |+| PHP | Laravel | Guzzle, Laravel `Http` |+| Java / Kotlin | Spring, JAX-RS, Micronaut | Feign, `java.net.http`, `RestTemplate`, Ktor (Kotlin) |+| Go | gin, echo, chi, net/http | net/http |+| C# | ASP.NET (attribute and minimal API) | HttpClient, UnityWebRequest, Best.HTTP |+| Ruby | | HTTParty, RestClient, Faraday, Net::HTTP |+| Rust | Axum, Actix, Rocket | reqwest |+| Any | OpenAPI 3.x documents | |++**Database tables:**++| Language | Providers (tables declared) | Consumers (tables queried) |+|----------|-----------------------------|----------------------------|+| SQL | `CREATE TABLE` / `VIEW` / `MATERIALIZED VIEW`, `ALTER TABLE` | |+| JS / TS | Prisma, TypeORM, Sequelize, Drizzle, Knex migrations | SQL strings, Knex queries |+| Python | SQLAlchemy, SQLModel, Django, Alembic | SQL strings |+| PHP | Eloquent, Laravel migrations | SQL strings, `DB::table` |+| Java / Kotlin | JPA | SQL strings |+| Go | | SQL strings |+| C# | EF Core | SQL strings |+| Ruby | ActiveRecord | SQL strings |++**gRPC, topics and sockets:**| Type | Providers | Consumers ||------|-----------|-----------|-| HTTP | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal API), Rust (Axum routes, Actix/Rocket attribute macros) | fetch/axios/URL-literal wrappers (JS/TS), requests/httpx (Python), HttpClient/UnityWebRequest/Best.HTTP (C#), reqwest (Rust) || gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs |-| Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), Alembic `op.create_table`, Laravel migrations (`Schema::create` / `Schema::table`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`), Laravel `DB::table(...)` || Topics | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika, php-amqplib), NATS, Redis pub/sub (ioredis/node-redis, redis-py, Laravel `Redis::publish`), BullMQ / Bull (`new Queue`, `@InjectQueue`, flows), SQS and SNS (AWS SDK v2/v3, boto3), NestJS `ClientProxy.emit`/`send`, Laravel job dispatch (`X::dispatch()->onQueue()`, `dispatch()`, `Queue::push*`, scheduled jobs) | The corresponding consumers (`new Worker`, `@Processor`, `ReceiveMessageCommand`, sqs-consumer, `subscribe`/`psubscribe`, `@EventPattern`/`@MessagePattern`, Laravel `ShouldQueue` classes on the queues they run on), plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) || Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")`, `ws` `WebSocketServer({ path })`, NestJS `@WebSocketGateway`; events: socket.io `emit` (server and client), Laravel broadcast events (`broadcastOn` / `broadcastAs`), `Broadcast::on`, Pusher `trigger` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)`, browser/Node `new WebSocket(url)`; events: socket.io `on` / `@SubscribeMessage`, Laravel Echo `listen` and `useEcho`, pusher-js `bind` |@@ -270,14 +295,18 @@ nothing). Such a link carries the exchange as its `contract_id` and the queue asbinding site itself is linked. A publish to the default exchange(`publish('', 'jobs')`) is a publish to the queue `jobs`.-Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). A service that only models a table (an ORM class, no migration) is linked to the service whose migration or DDL defines that table's schema, when exactly one service defines it; two services that each migrate a table of one name are read as separate databases and not linked. The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.+Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). An ORM model with no explicit table name takes its library's default: the Prisma model name, the TypeORM class name in snake case, the Sequelize model name pluralized, the Eloquent class name in snake case and plural. A service that only models a table (an ORM class, no migration) is linked to the service whose migration or DDL defines that table's schema, when exactly one service defines it; two services that each migrate a table of one name are read as separate databases and not linked. The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.HTTP routes are matched on their **full** path: a router mount prefix(`APIRouter(prefix=...)`, `include_router(prefix=...)`, Express `app.use('/x', router)`,Go route groups, Laravel `Route::prefix(...)->group(...)` and `Route::group(['prefix' => ...])`)is stitched onto each handler path before matching. Laravel's `routes/api.php` isserved under `/api` unless `bootstrap/app.php` (`apiPrefix`) or a route provider says-otherwise, and `Route::resource` / `apiResource` expand into the routes they register. A client call+otherwise, and `Route::resource` / `apiResource` expand into the routes they register. A NestJS+route is served at the app's `setGlobalPrefix` (unless its `exclude` list names the route), then+its URI version (`enableVersioning`, `@Version`), then the `@Controller` prefix. A call through an+axios, ky, got or ofetch instance is read with the instance's `baseURL` / `prefixUrl`, also when+another file imports the instance. A client callwhose base URL is an unresolved placeholder (`fetch(\`${API_BASE}/users\`)`) matcheson the host-relative path; the link is **exact** when exactly one workspace serviceprovides that path and a lower-confidence **candidate** when the target is ambiguous.@@ -611,7 +640,7 @@ Workspace init automatically registers MCP servers with Claude Desktop and Claud- **Default repo context**, queries go to the primary repo unless you specify otherwise- **Cross-repo tools**, MCP tools can query across repos and return enriched context with co-change and contract data; `get_blast_radius` answers cross-repo downstream impact (see [Cross-Repo Blast Radius](#cross-repo-blast-radius)); `get_conformance` answers architecture rule violations and dependency cycles (see [Architecture Conformance](#architecture-conformance)); `get_architecture` answers whole-system coupling, the cyclic core, and the architecture score (see [Architecture Metrics](#architecture-metrics))-- **Repo parameter**, most tools accept an optional `repo` parameter to target a specific repo, or `"all"` to query across the workspace+- **Repo parameter**, most tools accept an optional `repo` parameter to target a specific repo. Four also accept `"all"` to query across the workspace: `get_overview` (workspace topology and a summary per repo), `search_codebase` (results from every repo), `get_dead_code` (findings from every repo) and `get_why` with a query (decisions from every repo). The other tools answer about one repo at a time---diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex c8e791b7f..7b163af77 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -401,6 +401,9 @@ class FileTraverser:repos (common when a workspace root is itself versioned) wouldbe walked end-to-end, pulling in hundreds of thousands of filesthat belong to the nested repos.+ keep_unparsed: Extensions yielded (as language ``unknown``) although no+ language parses them, for a caller reading their text itself: the+ contract walk reads ``schema.prisma``. The index never passes it."""def __init__(@@ -412,8 +415,10 @@ class FileTraverser:extra_exclude_patterns: list[str] | None = None,include_submodules: bool = False,include_nested_repos: bool = False,+ keep_unparsed: frozenset[str] = frozenset(),) -> None:self.repo_root = repo_root.resolve()+ self._keep_unparsed = keep_unparsedself.max_file_size_bytes = max_file_size_kb * 1024self._extra_ignore_filename = extra_ignore_filenameself._gitignore = load_gitignore_spec(self.repo_root)@@ -768,7 +773,7 @@ class FileTraverser:self.stats.skipped_binary += 1return Nonelanguage = _detect_by_shebang(abs_path)- if language == "unknown":+ if language == "unknown" and abs_path.suffix.lower() not in self._keep_unparsed:with self._count_lock:self.stats.skipped_unknown_language += 1# Keep the path even though nothing here can parse it. Adiff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex aa74a95d5..a9aafd38e 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -58,7 +58,9 @@ CONTRACTS_FILENAME = "contracts.json"# Version 11 adds Laravel queues, BullMQ, SQS/SNS, Redis pub/sub, NestJS# microservices, php-amqplib, pattern subscriptions, and socket.io, ws and# Laravel broadcasting sockets; JS/TS constants fold.-CONTRACTS_VERSION = 11+# Version 12 adds NestJS controllers, axios/ky/got/ofetch instances with their+# base, and Prisma, TypeORM, Sequelize, Drizzle and Knex tables.+CONTRACTS_VERSION = 12#: ``meta["kind"]`` of a topic contract: the destination a broker call names.#: A queue is read by one consumer group; a topic, subject or channel fansdiff --git a/packages/core/src/repowise/core/workspace/extractors/base.py b/packages/core/src/repowise/core/workspace/extractors/base.pyindex da1e64396..a0795e844 100644--- a/packages/core/src/repowise/core/workspace/extractors/base.py+++ b/packages/core/src/repowise/core/workspace/extractors/base.py@@ -99,8 +99,9 @@ class ScanContext:``rel_path`` is POSIX-relative to the repo root; ``suffix`` is thelower-cased file extension (including the dot); ``content`` is the decoded- file text. ``mounts`` is the repo-wide ``router-variable -> mount-prefix``- map a provider dialect uses to recover cross-file route prefixes (see+ file text. ``mounts`` is the repo-wide map the HTTP dialects collect+ before extraction: router mount prefixes, where each app serves its+ routes, and client instances other files import (see:mod:`.http.mounts`); empty for single-file extraction.``index`` is the repo's read-only symbol table, when the repo has one.@@ -170,7 +171,8 @@ def iter_source_files(if not root.is_dir():return- traverser = FileTraverser(root)+ # A contract format no language parses (`schema.prisma`) is still read here.+ traverser = FileTraverser(root, keep_unparsed=extensions)for info in traverser.traverse():suffix = os.path.splitext(info.path)[1].lower()if suffix not in extensions:diff --git a/packages/core/src/repowise/core/workspace/extractors/calls.py b/packages/core/src/repowise/core/workspace/extractors/calls.pyindex 8a11f87ff..6ea9b3ad0 100644--- a/packages/core/src/repowise/core/workspace/extractors/calls.py+++ b/packages/core/src/repowise/core/workspace/extractors/calls.py@@ -1,9 +1,9 @@"""Call sites as a table-driven dialect reads them.-A topic or socket recogniser is a table of call shapes: a *head* regex ending-at the call's opening parenthesis, the extensions it applies to, and the-substrings one of which the file must contain (the library's import) before-the head is tried at all. :func:`call_sites` walks one file through such a+A recogniser (topic, socket, HTTP, data) is a table of call shapes: a *head*+regex ending at the call's opening parenthesis, the extensions it applies to,+and the substrings one of which the file must contain (the library's import)+before the head is tried at all. :func:`call_sites` walks one file through such atable and yields each call's argument list with the file's:class:`FileStrings`, which reads the file's constants once, on first use.:func:`call_chain` reads the calls chained onto one (``X::dispatch(...)@@ -20,6 +20,7 @@ from .strings import (call_arguments,match_paren,resolve_argument,+ resolve_string,string_constants,syntax_for_suffix,)@@ -39,6 +40,15 @@ class CallShape(Protocol):requires: tuple[str, ...]+@dataclass(frozen=True)+class Call:+ """A table row for :func:`call_sites` with nothing but the shape."""++ head: re.Pattern[str]+ extensions: frozenset[str]+ requires: tuple[str, ...] = ()++class FileStrings:"""One file's string syntax, and its constants, read the first time they are needed."""@@ -62,6 +72,17 @@ class FileStrings:""":func:`..strings.resolve_argument` against this file's constants."""return resolve_argument(args, arg, self.syntax, self.constants, normalize)+ def text(self, expr: str) -> str | None:+ """:func:`..strings.resolve_string` for *expr*, holes allowed.++ The constants are read only when the expression alone leaves a hole+ or does not resolve, so a plain literal never pays for them.+ """+ text = resolve_string(expr, self.syntax)+ if text is None or "${" in text:+ text = resolve_string(expr, self.syntax, self.constants)+ return text+def file_strings(ctx: ScanContext) -> FileStrings | None:"""The :class:`FileStrings` for *ctx*, or ``None`` for a language with no string syntax."""@@ -70,12 +91,17 @@ def file_strings(ctx: ScanContext) -> FileStrings | None:def call_sites(- ctx: ScanContext, calls: Iterable[CallShape], strings: FileStrings | None = None+ ctx: ScanContext,+ calls: Iterable[CallShape],+ strings: FileStrings | None = None,+ *,+ empty: bool = False,) -> Iterator[tuple[CallShape, list[str], re.Match[str], FileStrings]]:- """Each call in *ctx* one of *calls* recognises, with its non-empty argument list.+ """Each call in *ctx* one of *calls* recognises, with its argument list.- Pass *strings* when the caller already holds the file's, so its constants- are read once.+ A call with no arguments is skipped unless *empty* is set: for a decorator+ such as ``@Get()`` the missing argument is the answer. Pass *strings* when+ the caller already holds the file's, so its constants are read once."""present: dict[tuple[str, ...], bool] = {} # rows of one library share a gatefor call in calls:@@ -88,7 +114,7 @@ def call_sites(continuefor m in call.head.finditer(ctx.content):args = call_arguments(ctx.content, m.end() - 1)- if not args:+ if args is None or not (args or empty):continueif strings is None:strings = file_strings(ctx)@@ -125,11 +151,61 @@ def call_chain(content: str, close: int) -> Iterator[ChainLink]:pos = end + 1+def receiver_at(content: str, start: int, qualifiers: re.Pattern[str] | None = None) -> bool:+ """Whether a name matched at *start* stands alone rather than ending another name.++ Read here rather than by a lookbehind, which would cost a head regex its+ literal start. A ``x.name`` member counts only when *qualifiers* matches+ the text before the dot (``this.``, ``window.``).+ """+ if start == 0:+ return True+ before = content[start - 1]+ if before.isalnum() or before in "_$":+ return False+ head = content[max(0, start - 16) : start]+ if not head.rstrip().endswith("."):+ return True+ return qualifiers is not None and qualifiers.search(head) is not None+++# Whitespace and comments between decorators and the member they decorate.+_GAP_RE = re.compile(r"(?:\s+|//[^\n]*|/\*.*?\*/)*", re.DOTALL)+_DECORATOR_NAME_RE = re.compile(r"@[\w$.]+")+_MEMBER_RE = re.compile(+ r"(?:(?:export|default|declare|abstract|public|private|protected|static|async|readonly"+ r"|override)\s+)*(?:(?P<cls>class)\s+)?(?P<name>[A-Za-z_$][\w$]*)"+)+++def decorated_member(content: str, pos: int) -> re.Match[str] | None:+ """The TypeScript class or method a decorator run continuing at *pos* decorates.++ Further decorators, their arguments and comments are stepped over. The+ match names the member (``name``) and says whether it is a class (``cls``).+ TypeScript only: Java annotation runs are read by ``framework_routes``.+ """+ while True:+ pos = _GAP_RE.match(content, pos).end()+ name = _DECORATOR_NAME_RE.match(content, pos)+ if name is None:+ return _MEMBER_RE.match(content, pos)+ pos = _GAP_RE.match(content, name.end()).end()+ if content.startswith("(", pos):+ close = match_paren(content, pos)+ if close < 0:+ return None+ pos = close + 1++__all__ = [+ "Call","CallShape","ChainLink","FileStrings","call_chain","call_sites",+ "decorated_member","file_strings",+ "receiver_at",]diff --git a/packages/core/src/repowise/core/workspace/extractors/data/__init__.py b/packages/core/src/repowise/core/workspace/extractors/data/__init__.pyindex d255c7889..e8550830f 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/__init__.py@@ -13,6 +13,8 @@ from __future__ import annotationsfrom ..dialect import ContractDialect, DialectExtractorfrom .ddl import DdlDialect+from .drizzle import DrizzleDialect+from .knex import KnexDialectfrom .laravel import EloquentDialect, LaravelMigrationDialect, LaravelQueryDialectfrom .names import normalize_table_namefrom .orm_models import (@@ -21,7 +23,10 @@ from .orm_models import (JpaDialect,SqlAlchemyDjangoDialect,)+from .prisma import PrismaDialect+from .sequelize import SequelizeDialectfrom .sql_strings import SqlStringsDialect+from .typeorm import TypeOrmDialect# Table-ownership recognisers (DDL + one per ORM family).PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (@@ -32,10 +37,20 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (ActiveRecordDialect(),EloquentDialect(),LaravelMigrationDialect(),+ PrismaDialect(),+ TypeOrmDialect(),+ SequelizeDialect(),+ DrizzleDialect(),)# Table-access recognisers.-CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (SqlStringsDialect(), LaravelQueryDialect())+# Knex reads both sides (its migrations and its query builder), so it is+# registered once, here.+CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (+ SqlStringsDialect(),+ LaravelQueryDialect(),+ KnexDialect(),+)class DataExtractor(DialectExtractor):diff --git a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py b/packages/core/src/repowise/core/workspace/extractors/data/dialect.pyindex 67c288e21..4438b4394 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/dialect.py@@ -85,6 +85,23 @@ def build_table_consumer()+def dedup_consumers(+ ctx: ScanContext, client: str, found: list[tuple[str, str, int]]+) -> list[Contract]:+ """One consumer per table and verb in *found*, ``(raw_table, verb, line)``."""+ out: list[Contract] = []+ seen: set[tuple[str, str]] = set()+ for raw, verb, line in found:+ key = (raw.lower(), verb)+ if key in seen:+ continue+ seen.add(key)+ contract = build_table_consumer(ctx, table_raw=raw, verb=verb, client=client, line=line)+ if contract is not None:+ out.append(contract)+ return out++EXPLICIT_CONFIDENCE = 0.85CONVENTION_CONFIDENCE = 0.6# A declaration that evolves a table (``ALTER TABLE``, ``Schema::table``).diff --git a/packages/core/src/repowise/core/workspace/extractors/data/drizzle.py b/packages/core/src/repowise/core/workspace/extractors/data/drizzle.pynew file mode 100644index 000000000..53376d79b--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/data/drizzle.py@@ -0,0 +1,66 @@+"""Drizzle tables: ``pgTable('users', ...)``, ``mysqlTable``, ``sqliteTable``, ``singlestoreTable``.++The first argument is the table's name. A table declared on a schema object+(``const auth = pgSchema('auth'); auth.table('users', ...)``) is qualified by+it. A table creator (``pgTableCreator(name => `app_${name}`)``) rewrites the+name in a function this does not read, so its tables are not read either.+"""++from __future__ import annotations++import re+from functools import lru_cache+from typing import TYPE_CHECKING++from ..base import ScanContext, line_at+from ..calls import Call, call_sites, receiver_at+from ..langs import JS_TS+from ..strings import Arg+from .dialect import EXPLICIT_CONFIDENCE, dedup_emit++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++_DRIZZLE = "drizzle-orm"+_FIRST = Arg(pos=0)+_TABLE = Call(re.compile(r"(?:pg|mysql|sqlite|singlestore)Table\s*\("), JS_TS)+_SCHEMA = Call(re.compile(r"(?:pg|mysql|singlestore)Schema\s*\("), JS_TS)+# The name a schema object is bound to, read back from the call.+_BINDING_RE = re.compile(r"(?P<name>[A-Za-z_$][\w$]*)\s*=\s*$")+++@lru_cache(maxsize=64)+def _schema_tables(names: tuple[str, ...]) -> tuple[Call, ...]:+ alts = "|".join(re.escape(n) for n in names)+ return (Call(re.compile(rf"(?P<schema>{alts})\s*\.\s*table\s*\("), JS_TS),)+++class DrizzleDialect:+ name = "drizzle"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if _DRIZZLE not in content:+ return []+ found: list[tuple[str, float, int]] = []+ schemas: dict[str, str] = {}+ for call, args, m, strings in call_sites(ctx, (_TABLE, _SCHEMA)):+ if not receiver_at(content, m.start()):+ continue # `pgTableCreator`'s product, or a longer name+ names, refused = strings.resolve(args[:1], _FIRST)+ if refused or not names:+ continue+ if call is _SCHEMA:+ bound = _BINDING_RE.search(content, max(0, m.start() - 80), m.start())+ if bound is not None:+ schemas[bound.group("name")] = names[0]+ else:+ found.append((names[0], EXPLICIT_CONFIDENCE, line_at(content, m.start())))+ if schemas:+ for _call, args, m, strings in call_sites(ctx, _schema_tables(tuple(sorted(schemas)))):+ names, refused = strings.resolve(args[:1], _FIRST)+ if names and not refused and receiver_at(content, m.start()):+ table = f"{schemas[m.group('schema')]}.{names[0]}"+ found.append((table, EXPLICIT_CONFIDENCE, line_at(content, m.start())))+ return dedup_emit(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/knex.py b/packages/core/src/repowise/core/workspace/extractors/data/knex.pynew file mode 100644index 000000000..c77c07a57--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/data/knex.py@@ -0,0 +1,128 @@+"""Knex: schema builder migrations (providers) and the query builder (consumers).++* **Migrations**: ``knex.schema.createTable('x', ...)`` declares a table and+ ``alterTable('x')`` / ``table('x', ...)`` evolve it, both marked with+ ``meta['schema']`` as the owner's; ``withSchema('s')`` qualifies them.+* **Queries**: ``knex('x')``, ``knex.from('x')`` / ``.table`` / ``.into``, and+ ``knex.select(...).from('x')``, on ``knex`` itself or on a name the file+ binds to a Knex instance (``const db = knex(config)``). The statement's own+ chain says whether it inserts, updates or deletes; anything else reads.++Ceiling: an instance imported from another module under another name+(``import { db } from './db'``) is not followed; the client instances of the+HTTP layer travel between files through the mount pass, and this could too.+"""++from __future__ import annotations++import re+from functools import lru_cache+from typing import TYPE_CHECKING++from ..base import ScanContext, line_at+from ..calls import Call, call_chain, call_sites, receiver_at+from ..langs import JS_TS+from ..strings import Arg, match_paren+from .dialect import ALTER_CONFIDENCE, EXPLICIT_CONFIDENCE, dedup_consumers, dedup_emit++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++_FIRST = Arg(pos=0)+_THIS_RE = re.compile(r"this\s*\.\s*$")++_SCHEMA_OPS = {+ "createTable": "create",+ "createTableIfNotExists": "create",+ "alterTable": "alter",+ "table": "alter",+}+_SCHEMA_CALL = Call(+ re.compile(+ r"\.\s*schema\s*(?:\.\s*withSchema\s*\((?P<schema>[^()]*)\)\s*)?"+ rf"\.\s*(?P<op>{'|'.join(_SCHEMA_OPS)})\s*\("+ ),+ JS_TS,+ (".schema",),+)+# `const db = knex({...})`, `= Knex(config)`, `= require('knex')(config)`.+_INSTANCE_RE = re.compile(+ r"(?:const|let|var)\s+(?P<name>[A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*"+ r"""(?:knex|Knex|require\s*\(\s*['"]knex['"]\s*\))\s*\("""+)+_TABLE_METHODS = ("from", "table", "into")+_WRITES = {+ "insert": "insert",+ "upsert": "insert",+ "update": "update",+ "increment": "update",+ "decrement": "update",+ "del": "delete",+ "delete": "delete",+ "truncate": "delete",+}+_ALIAS_RE = re.compile(r"\s+as\s+\w+$", re.IGNORECASE)+++@lru_cache(maxsize=64)+def _queries(names: tuple[str, ...]) -> tuple[Call, ...]:+ """``x('t')``, ``x.from('t')`` and ``x.select(...)`` (read on to its ``from``) on *names*."""+ alts = "|".join(re.escape(n) for n in names)+ methods = "|".join((*_TABLE_METHODS, "select", "distinct", "count", "max", "min", "sum", "avg"))+ return (Call(re.compile(rf"(?:{alts})\s*(?:\.\s*(?P<method>{methods})\s*)?\("), JS_TS),)+++def _verb(links: list[str]) -> str:+ return next((_WRITES[name] for name in links if name in _WRITES), "select")+++class KnexDialect:+ name = "knex"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if "knex" not in content and "Knex" not in content:+ return []+ return self._migrations(ctx) + self._queries(ctx)++ def _migrations(self, ctx: ScanContext) -> list[Contract]:+ found: dict[str, list[tuple[str, float, int]]] = {"create": [], "alter": []}+ for _call, args, m, strings in call_sites(ctx, (_SCHEMA_CALL,)):+ names, refused = strings.resolve(args[:1], _FIRST)+ if refused or not names:+ continue+ table = names[0]+ if m.group("schema") is not None:+ schemas, refused = strings.resolve([m.group("schema")], _FIRST)+ if refused or not schemas:+ continue+ table = f"{schemas[0]}.{table}"+ kind = _SCHEMA_OPS[m.group("op")]+ confidence = EXPLICIT_CONFIDENCE if kind == "create" else ALTER_CONFIDENCE+ found[kind].append((table, confidence, line_at(ctx.content, m.start())))+ return dedup_emit(ctx, self.name, found["create"], schema="create") + dedup_emit(+ ctx, self.name, found["alter"], schema="alter"+ )++ def _queries(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ names = {"knex", *(m.group("name") for m in _INSTANCE_RE.finditer(content))}+ found: list[tuple[str, str, int]] = []+ for _call, args, m, strings in call_sites(ctx, _queries(tuple(sorted(names)))):+ if not receiver_at(content, m.start(), _THIS_RE):+ continue+ close = match_paren(content, m.end() - 1)+ links = list(call_chain(content, close)) if close >= 0 else []+ method = m.group("method")+ if method is None or method in _TABLE_METHODS:+ table_args = args+ else:+ # `knex.select(...)` names columns; the table is its chain's `from`.+ table_args = next((link.args for link in links if link.name in _TABLE_METHODS), [])+ tables, refused = strings.resolve(table_args[:1], _FIRST)+ if refused or not tables:+ continue+ verb = _verb([link.name for link in links])+ found.append((_ALIAS_RE.sub("", tables[0]), verb, line_at(content, m.start())))+ return dedup_consumers(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/laravel.py b/packages/core/src/repowise/core/workspace/extractors/data/laravel.pyindex c8e0813d9..d5c3ea778 100644--- a/packages/core/src/repowise/core/workspace/extractors/data/laravel.py+++ b/packages/core/src/repowise/core/workspace/extractors/data/laravel.py@@ -24,7 +24,7 @@ from .dialect import (ALTER_CONFIDENCE,CONVENTION_CONFIDENCE,EXPLICIT_CONFIDENCE,- build_table_consumer,+ dedup_consumers,dedup_emit,found_names,)@@ -128,23 +128,10 @@ class LaravelQueryDialect:return "update" # increment / decrementdef extract(self, ctx: ScanContext) -> list[Contract]:- out: list[Contract] = []if "DB::" not in ctx.content:- return out- seen: set[tuple[str, str]] = set()- for m in self._TABLE_RE.finditer(ctx.content):- verb = self._verb(ctx.content, m.end())- key = (m.group("table").lower(), verb)- if key in seen:- continue- seen.add(key)- contract = build_table_consumer(- ctx,- table_raw=m.group("table"),- verb=verb,- client=self.name,- line=line_at(ctx.content, m.start()),- )- if contract is not None:- out.append(contract)- return out+ return []+ found = [+ (m.group("table"), self._verb(ctx.content, m.end()), line_at(ctx.content, m.start()))+ for m in self._TABLE_RE.finditer(ctx.content)+ ]+ return dedup_consumers(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/prisma.py b/packages/core/src/repowise/core/workspace/extractors/data/prisma.pynew file mode 100644index 000000000..0126efc4c--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/data/prisma.py@@ -0,0 +1,46 @@+"""Prisma schema models: ``model User { ... }`` in a ``.prisma`` file.++A model's table is its ``@@map("users")`` name, else the model's own name+(Prisma does not pluralize); ``@@schema("x")`` qualifies it. Views, enums and+types declare no table. The schema models its tables: whether it also creates+them (``prisma migrate``) or reads a database another service migrated+(``prisma db pull``) is not in the file, and the migration SQL Prisma writes+is the DDL dialect's.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from ..base import ScanContext, line_at+from .dialect import EXPLICIT_CONFIDENCE, dedup_emit++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++_MODEL_RE = re.compile(r"^[ \t]*model[ \t]+(\w+)[ \t]*\{", re.MULTILINE)+# A block closes on its own line; attribute arguments hold no braces.+_BLOCK_END_RE = re.compile(r"^[ \t]*\}", re.MULTILINE)+# Block attributes open their own line, so a commented-out one does not count.+_MAP_RE = re.compile(r"""^[ \t]*@@map\(\s*(?:name\s*:\s*)?"([^"]+)"\s*\)""", re.MULTILINE)+_SCHEMA_RE = re.compile(r"""^[ \t]*@@schema\(\s*"([^"]+)"\s*\)""", re.MULTILINE)+++class PrismaDialect:+ name = "prisma"+ extensions = frozenset({".prisma"})++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ found: list[tuple[str, float, int]] = []+ for m in _MODEL_RE.finditer(content):+ end = _BLOCK_END_RE.search(content, m.end())+ body = content[m.end() : end.start() if end else len(content)]+ mapped = _MAP_RE.search(body)+ schema = _SCHEMA_RE.search(body)+ table = mapped.group(1) if mapped else m.group(1)+ if schema:+ table = f"{schema.group(1)}.{table}"+ found.append((table, EXPLICIT_CONFIDENCE, line_at(content, m.start(1))))+ return dedup_emit(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/data/sequelize.py b/packages/core/src/repowise/core/workspace/extractors/data/sequelize.pynew file mode 100644index 000000000..574013415--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/data/sequelize.py@@ -0,0 +1,127 @@+"""Sequelize models: ``sequelize.define``, ``Model.init`` and sequelize-typescript ``@Table``.++A ``tableName`` option names the table. Without one Sequelize derives it+from the model name (``define``'s first argument, ``modelName``, else the+class): kept as is under ``freezeTableName``, otherwise pluralized (a name+already ending in ``s`` is left alone) and snake-cased when ``underscored``+is set. ``define`` counts only on a Sequelize connection: a receiver named+for it, or one the file binds to ``new Sequelize(...)``.++Ceiling: a connection-wide ``define: { freezeTableName: true }`` set in+another file is not seen, so those models read as pluralized.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from ..base import ScanContext, line_at+from ..calls import Call, call_sites, decorated_member, file_strings+from ..langs import JS_TS+from ..strings import Arg, call_arguments, match_paren, on_comment_line, select_argument+from .dialect import CONVENTION_CONFIDENCE, EXPLICIT_CONFIDENCE, dedup_emit+from .names import pluralize, snake_case++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..calls import FileStrings++_SEQUELIZE = ("sequelize",)+_DEFINE = Call(re.compile(r"\.\s*define\s*\("), JS_TS, _SEQUELIZE)+# `User.init(attributes, { sequelize, ... })`: the options name the connection.+_INIT = Call(re.compile(r"\.\s*init\s*\("), JS_TS, _SEQUELIZE)+# The receiver a `.define(` / `.init(` is called on, read back from the dot.+_RECEIVER_RE = re.compile(r"(?<![\w$.])(?:this\s*\.\s*)?(?P<name>[A-Za-z_$][\w$]*)\s*$")+_CONNECTION_RE = re.compile(r"(?<![\w$])sequelize(?![\w$])")+_BOUND_RE = re.compile(r"(?P<name>[A-Za-z_$][\w$]*)\s*=\s*new\s+Sequelize\s*\(")+_CLASS_RE = re.compile(r"\bclass\s+(?P<name>[A-Za-z_$][\w$]*)")+# sequelize-typescript: `@Table` bare or with options, above the model class.+_TABLE_DECORATOR_RE = re.compile(r"@Table\b\s*(?P<paren>\()?")+_FIRST = Arg(pos=0)+++def _flag(options: list[str], key: str) -> bool:+ return select_argument(options, Arg(keys=(key,))) == ["true"]+++def _table(model: str, options: list[str], strings: FileStrings) -> tuple[str, float] | None:+ """The table a model's options give it, with how sure; ``None`` when unreadable."""+ names, refused = strings.resolve(options, Arg(keys=("tableName",)))+ if refused:+ return None+ if names:+ return names[0], EXPLICIT_CONFIDENCE+ modelled, refused = strings.resolve(options, Arg(keys=("modelName",)))+ if refused:+ return None+ name = modelled[0] if modelled else model+ if not _flag(options, "freezeTableName"):+ if not name.endswith("s"):+ name = pluralize(name)+ if _flag(options, "underscored"):+ name = snake_case(name)+ return name, CONVENTION_CONFIDENCE+++def _receiver(content: str, dot: int) -> str | None:+ m = _RECEIVER_RE.search(content, max(0, dot - 80), dot)+ return m.group("name") if m else None+++class SequelizeDialect:+ name = "sequelize"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if _SEQUELIZE[0] not in content:+ return []+ connections = {"sequelize", *(m.group("name") for m in _BOUND_RE.finditer(content))}+ found: list[tuple[str, float, int]] = []+ for call, args, m, strings in call_sites(ctx, (_DEFINE, _INIT)):+ receiver = _receiver(content, m.start())+ if receiver is None:+ continue+ if call is _DEFINE:+ if receiver not in connections:+ continue # `customElements.define`, an i18n `define`+ models, refused = strings.resolve(args[:1], _FIRST)+ if refused or not models:+ continue+ table = _table(models[0], args[2:3], strings)+ else:+ if len(args) < 2 or not _CONNECTION_RE.search(args[1]):+ continue # some other `init`+ if receiver in ("super", "this"):+ # `static init(s) { return super.init(attrs, { sequelize: s }) }`+ classes = list(_CLASS_RE.finditer(content, 0, m.start()))+ if not classes:+ continue+ receiver = classes[-1].group("name")+ table = _table(receiver, args[1:2], strings)+ if table is not None:+ found.append((*table, line_at(content, m.start())))+ if "sequelize-typescript" in content:+ found.extend(self._decorated(ctx))+ return dedup_emit(ctx, self.name, found)++ def _decorated(self, ctx: ScanContext) -> list[tuple[str, float, int]]:+ content = ctx.content+ strings = file_strings(ctx)+ out: list[tuple[str, float, int]] = []+ for m in _TABLE_DECORATOR_RE.finditer(content):+ member = decorated_member(content, m.start())+ if member is None or member.group("cls") is None or strings is None:+ continue+ if on_comment_line(content, m.start()):+ continue+ options: list[str] = []+ if m.group("paren"):+ close = match_paren(content, m.start("paren"))+ options = (call_arguments(content, m.start("paren"), close) or [])[:1] if close >= 0 else []+ table = _table(member.group("name"), options, strings)+ if table is not None:+ out.append((*table, line_at(content, m.start())))+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/data/typeorm.py b/packages/core/src/repowise/core/workspace/extractors/data/typeorm.pynew file mode 100644index 000000000..67826cc16--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/data/typeorm.py@@ -0,0 +1,61 @@+"""TypeORM entities: ``@Entity('users')``, ``@Entity({ name, schema })`` or ``@Entity()``.++With no name the table is TypeORM's default naming, its ``snakeCase`` of the+class name (``PhotoMetadata`` -> ``photo_metadata``, ``APIKey`` -> ``api_key``).+A ``schema`` option qualifies it; one this cannot read refuses the entity.+``@ViewEntity`` is a view and ``@ChildEntity`` shares its parent's table, so+neither is read.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++from ..base import ScanContext, line_at+from ..calls import Call, call_sites, decorated_member+from ..langs import JS_TS+from ..strings import Arg, on_comment_line+from .dialect import CONVENTION_CONFIDENCE, EXPLICIT_CONFIDENCE, dedup_emit+from .names import snake_case++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++_ENTITY = Call(re.compile(r"@Entity\s*\("), JS_TS, ("typeorm",))+_NAME = Arg(keys=("name",), pos=0)+_OPTION_NAME = Arg(keys=("name",))+_SCHEMA = Arg(keys=("schema",))+# TypeORM splits an acronym from the word after it before the camel case split.+_ACRONYM_RE = re.compile(r"([A-Z])([A-Z])([a-z])")+++def _default_table(cls: str) -> str:+ return snake_case(_ACRONYM_RE.sub(r"\1_\2\3", cls))+++class TypeOrmDialect:+ name = "typeorm"+ extensions = JS_TS++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if "@Entity" not in content:+ return []+ found: list[tuple[str, float, int]] = []+ for _shape, args, m, strings in call_sites(ctx, (_ENTITY,), empty=True):+ member = decorated_member(content, m.start())+ if member is None or member.group("cls") is None or on_comment_line(content, m.start()):+ continue+ # `@Entity('users', { schema })` or `@Entity({ name, schema })`.+ options = args[:1] if args[:1] and args[0].startswith("{") else args[1:2]+ names, refused = strings.resolve(args[:1], _OPTION_NAME if options == args[:1] else _NAME)+ schemas, schema_refused = strings.resolve(options, _SCHEMA)+ if refused or schema_refused:+ continue # a name this file cannot read+ table = names[0] if names else _default_table(member.group("name"))+ if schemas:+ table = f"{schemas[0]}.{table}"+ confidence = EXPLICIT_CONFIDENCE if names else CONVENTION_CONFIDENCE+ found.append((table, confidence, line_at(content, m.start())))+ return dedup_emit(ctx, self.name, found)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex cd837250b..d3f827500 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -33,6 +33,7 @@ from .kotlin_clients import KotlinClientsDialectfrom .laravel import LaravelDialectfrom .micronaut import MicronautDialectfrom .mounts import merge_mount_maps+from .nestjs import NestDialectfrom .next_app import NextAppDialectfrom .paths import normalize_http_pathfrom .php_clients import PhpClientsDialect@@ -55,6 +56,7 @@ if TYPE_CHECKING:# Route-declaration recognisers (one framework each).PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (ExpressDialect(),+ NestDialect(),FastApiDialect(),FlaskDialect(),SpringDialect(),@@ -137,7 +139,7 @@ class HttpExtractor:these contracts states its own denominator."""scanned = select_files(repo_path, self.source_extensions(), exclude, files)- mounts = self._collect_mounts(scanned)+ mounts = self._collect_mounts(scanned, repo_alias)from ..from_index import (CONSUMER_INDEX_SUFFIXES,@@ -204,19 +206,26 @@ class HttpExtractor:contracts.extend(found)return contracts- def _collect_mounts(self, files: list[tuple[str, str, str]]) -> dict[str, str]:+ def _collect_mounts(self, files: list[SourceFile], repo_alias: str) -> dict[str, str]:"""Build the unambiguous repo-wide ``router-var -> mount-prefix`` map.- Each provider dialect may expose ``collect_mounts(content)``; results are- merged across every file, dropping any router name mounted at conflicting- prefixes (see :func:`merge_mount_maps`).+ Any dialect may expose ``collect_mounts(ctx)``: a router mount, where+ an app serves its routes, or a client instance another file imports.+ Results are merged across every file, dropping any key two files+ disagree on (see :func:`merge_mount_maps`)."""+ collectors = [+ d+ for d in self.provider_dialects + self.consumer_dialects+ if hasattr(d, "collect_mounts")+ ]per_file: list[dict[str, str]] = []- for _rel, suffix, content in files:- for dialect in self.provider_dialects:- collect = getattr(dialect, "collect_mounts", None)- if collect is not None and suffix in dialect.extensions:- found = collect(content)+ for rel_path, suffix, content in files:+ ctx: ScanContext | None = None+ for dialect in collectors:+ if suffix in dialect.extensions:+ ctx = ctx or ScanContext(repo_alias, rel_path, suffix, content)+ found = dialect.collect_mounts(ctx)if found:per_file.append(found)return merge_mount_maps(per_file)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/django.py b/packages/core/src/repowise/core/workspace/extractors/http/django.pyindex 4085dde62..7a4a65c95 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/django.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/django.py@@ -49,11 +49,11 @@ class DjangoDialect:name = "django"extensions = PYTHON- def collect_mounts(self, content: str) -> dict[str, str]:- """``include("api.urls")`` mounts declared in *content*, keyed by module."""- if not any(mod in content for mod in _DJANGO_URLS_IMPORT):+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ """``include("api.urls")`` mounts declared in the file, keyed by module."""+ if not any(mod in ctx.content for mod in _DJANGO_URLS_IMPORT):return {}- return {_MOUNT_PREFIX + module: prefix for prefix, module in django_includes(content)}+ return {_MOUNT_PREFIX + module: prefix for prefix, module in django_includes(ctx.content)}def extract(self, ctx: ScanContext) -> list[Contract]:if not any(mod in ctx.content for mod in _DJANGO_URLS_IMPORT):diff --git a/packages/core/src/repowise/core/workspace/extractors/http/express.py b/packages/core/src/repowise/core/workspace/extractors/http/express.pyindex 04e26c8ba..33d7fe757 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/express.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/express.py@@ -42,10 +42,10 @@ class ExpressDialect:name = "express"extensions = JS_TS- def collect_mounts(self, content: str) -> dict[str, str]:- """Find ``app.use('/prefix', router)`` mounts declared in *content*."""+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ """Find ``app.use('/prefix', router)`` mounts declared in the file."""out: dict[str, str] = {}- for m in _APP_USE_RE.finditer(content):+ for m in _APP_USE_RE.finditer(ctx.content):out[m.group(2).split(".")[-1]] = m.group(1)return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.pyindex 064d6cffb..6be28e8c8 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/fastapi.py@@ -46,17 +46,17 @@ class FastApiDialect:name = "fastapi"extensions = PYTHON- def collect_mounts(self, content: str) -> dict[str, str]:- """Find ``include_router(var, prefix=...)`` mounts declared in *content*.+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ """Find ``include_router(var, prefix=...)`` mounts declared in the file.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):+ if flask_file(ctx.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 '('+ for m in _INCLUDE_ROUTER_RE.finditer(ctx.content):+ args = balanced_args(ctx.content, m.end() - 1) # m.end()-1 is the '('var_m = _FIRST_ARG_RE.match(args)pm = _PREFIX_KW_RE.search(args)if var_m and pm:diff --git a/packages/core/src/repowise/core/workspace/extractors/http/flask.py b/packages/core/src/repowise/core/workspace/extractors/http/flask.pyindex 0de0962a1..205998d06 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/flask.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/flask.py@@ -80,8 +80,8 @@ class FlaskDialect:name = "flask"extensions = PYTHON- def collect_mounts(self, content: str) -> dict[str, str]:- """``register_blueprint(bp, url_prefix=...)`` mounts declared in *content*.+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ """``register_blueprint(bp, url_prefix=...)`` mounts declared in the file.Keyed by the blueprint expression's final name segment (``views.bp`` ->``bp``), which is the name its own file binds. Only registrations@@ -89,10 +89,10 @@ class FlaskDialect:own ``url_prefix`` in charge. A prefix the registration names but thiscannot read is recorded as unknown, which refuses the routes below it."""- if not flask_file(content):+ if not flask_file(ctx.content):return {}out: dict[str, str] = {}- for mount in flask_blueprints(content):+ for mount in flask_blueprints(ctx.content):if mount.prefix is None:out[_MOUNT_PREFIX + mount.var.split(".")[-1]] = _UNKNOWN_MOUNTelif mount.prefix:diff --git a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.pyindex 1a2952695..439a6ef98 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py@@ -37,7 +37,6 @@ from ..strings import (JS_SYNTAX,PYTHON_SYNTAX,match_paren,- resolve_string,split_first_arg,)from .client_calls import VERBS, is_rooted_url@@ -97,10 +96,7 @@ def _first_arg_url(arg: str, strings: FileStrings) -> str | None:not a path this layer may claim to know. The result then faces the sameconcreteness test in every language."""- url = resolve_string(arg, strings.syntax)- if url is None or "${" in url:- # Only an expression that is not a plain literal reads the constants.- url = resolve_string(arg, strings.syntax, strings.constants)+ url = strings.text(arg)return url if url is not None and is_rooted_url(url) else Nonediff --git a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.pyindex 8a6e3e3b4..41e9f09a7 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/js_clients.py@@ -1,6 +1,7 @@"""JavaScript / TypeScript HTTP consumer dialect.-Covers direct ``fetch`` / ``axios`` calls plus wrapper calls whose first+Covers direct ``fetch`` calls, the client libraries of :mod:`.node_clients`+(axios, ky, got, ofetch and their instances), plus wrapper calls whose firstargument is a concrete URL literal, e.g. ``fetchJSON(`${BASE}/path`, { method:"POST" })``. Wrapper detection is signal-gated (the callee name looks HTTP-ish,or the call carries a ``method:`` option) so ordinary `/`-prefixed string@@ -16,7 +17,7 @@ from typing import TYPE_CHECKINGfrom ..langs import JS_TSfrom ..strings import JS_SYNTAX, literal_span, string_constantsfrom .client_calls import ClientCallMatch, consumer_contracts, matches_in-from .dialect import METHODS+from .node_clients import client_calls, client_mountsif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -32,12 +33,6 @@ _FETCH_METHOD_RE = re.compile(re.DOTALL,)-# axios.get('/api/users')-_AXIOS_RE = re.compile(- rf"""axios\.({METHODS})\s*\(\s*['"]([^'"]+)['"]""",- re.IGNORECASE,-)-# Wrapper call: IDENT("<url>" | `<url>`, ...) where the URL literal is concrete,# i.e. starts with `/`, a `${...}` base placeholder, or a scheme._WRAPPER_CALL_RE = re.compile(@@ -50,8 +45,8 @@ _HTTP_NAME_RE = re.compile(r"(?i)fetch|request|http|api|ajax|rest|rpc")# A `method: "POST"` option inside the call's argument list._METHOD_OPT_RE = re.compile(r"""method\s*:\s*['"](\w+)['"]""")-# Callees already handled elsewhere, or never an HTTP wrapper.-_WRAPPER_SKIP = frozenset({"fetch", "if", "for", "while", "switch", "catch", "return"})+# Callees already handled elsewhere (`ofetch(` is a fetch call), or never an HTTP wrapper.+_WRAPPER_SKIP = frozenset({"fetch", "ofetch", "if", "for", "while", "switch", "catch", "return"})def fetch_calls(content: str) -> Iterator[ClientCallMatch]:@@ -70,15 +65,21 @@ def fetch_calls(content: str) -> Iterator[ClientCallMatch]:)-def axios_calls(content: str) -> Iterator[ClientCallMatch]:- yield from matches_in(content, _AXIOS_RE, client="axios", url_group=2, method_group=1)+def _callee(content: str, start: int, end: int) -> str:+ """The whole identifier around ``content[start:end]``, a leading ``$`` included."""+ while start > 0 and (content[start - 1].isalnum() or content[start - 1] in "_$"):+ start -= 1+ return content[start:end]++def wrapper_calls(content: str, clients: frozenset[str]) -> Iterator[ClientCallMatch]:+ """``fetchJSON(`${BASE}/path`, { method: "POST" })`` and its relatives.-def wrapper_calls(content: str) -> Iterator[ClientCallMatch]:- """``fetchJSON(`${BASE}/path`, { method: "POST" })`` and its relatives."""+ *clients* are the client names the file calls, read with their base elsewhere.+ """for m in _WRAPPER_CALL_RE.finditer(content):callee = m.group(1)- if callee in _WRAPPER_SKIP:+ if callee in _WRAPPER_SKIP or _callee(content, m.start(1), m.end(1)) in clients:continuenl = content.find("\n", m.end())window = content[m.end() :] if nl == -1 else content[m.end() : nl]@@ -102,9 +103,15 @@ class JsClientsDialect:name = "js-clients"extensions = JS_TS+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ return client_mounts(ctx)+def extract(self, ctx: ScanContext) -> list[Contract]:content = ctx.content- matches = [*fetch_calls(content), *axios_calls(content), *wrapper_calls(content)]+ from_clients, clients = client_calls(ctx)+ # A client named like `apifetch` is read with its base above, not as `fetch`.+ fetches = [m for m in fetch_calls(content) if _callee(content, m.offset, m.offset + 5) not in clients]+ matches = [*fetches, *wrapper_calls(content, clients)]# A `${BASE}` interpolation folds when the file binds BASE to a constant.constants = string_constants(content, JS_SYNTAX) if any("${" in m.url for m in matches) else {}- return consumer_contracts(ctx, matches, JS_SYNTAX, constants=constants)+ return from_clients + consumer_contracts(ctx, matches, JS_SYNTAX, constants=constants)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py b/packages/core/src/repowise/core/workspace/extractors/http/laravel.pyindex ec336294d..fa0748671 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/laravel.py@@ -21,6 +21,7 @@ from repowise.core.ingestion.framework_routes import (from ..base import line_atfrom ..langs import PHPfrom .dialect import build_provider_contract+from .mounts import declare_mount, declared_mountif TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -28,31 +29,24 @@ if TYPE_CHECKING:from ..base import ScanContext_MOUNT_KEY = "laravel-route-file:"-# The mount merge drops a key two files disagree on. This second key, always-# the same value, survives it, so a declared-but-dropped file reads as-# ambiguous (refused) rather than undeclared (served at the default).-_DECLARED_KEY = "laravel-route-file-declared:"-# Mount values are strings; a declared prefix this cannot read travels as this.-_UNREADABLE = "\0"class LaravelDialect:name = "laravel"extensions = PHP- def collect_mounts(self, content: str) -> dict[str, str]:+ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:out: dict[str, str] = {}- for name, prefix in laravel_route_file_prefixes(content).items():- out[f"{_MOUNT_KEY}{name}"] = _UNREADABLE if prefix is None else prefix- out[f"{_DECLARED_KEY}{name}"] = ""+ for name, prefix in laravel_route_file_prefixes(ctx.content).items():+ out.update(declare_mount(f"{_MOUNT_KEY}{name}", prefix))return outdef extract(self, ctx: ScanContext) -> list[Contract]:name = ctx.rel_path.rpartition("/")[2]declared: dict[str, str | None] = {}- if f"{_DECLARED_KEY}{name}" in ctx.mounts:- value = ctx.mounts.get(f"{_MOUNT_KEY}{name}", _UNREADABLE)- declared[name] = None if value == _UNREADABLE else value+ found, value = declared_mount(ctx.mounts, f"{_MOUNT_KEY}{name}")+ if found:+ declared[name] = valueprefix = laravel_route_prefix(ctx.rel_path, declared)if prefix is None:return [] # served under a prefix this cannot readdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/mounts.py b/packages/core/src/repowise/core/workspace/extractors/http/mounts.pyindex b1f1f8c66..703c3ff1d 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/mounts.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/mounts.py@@ -20,7 +20,7 @@ collected per dialect and merged by the orchestrator.from __future__ import annotationsimport re-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom repowise.core.ingestion.framework_routes import GroupMatch@@ -77,12 +77,14 @@ def compose_prefix(prefix: str, path: str) -> str:def merge_mount_maps(maps: list[dict[str, str]]) -> dict[str, str]:- """Merge per-file cross-file mount maps into one unambiguous ``var -> prefix``.-- A router variable mounted at two *different* prefixes anywhere in the repo is- ambiguous (the common case being a generic name like ``router`` reused across- files), so it is dropped rather than guessed. Only names with a single- distinct prefix survive.+ """Merge per-file mount maps into one unambiguous map.++ A key two files give *different* values anywhere in the repo is ambiguous+ (the common case being a generic router name like ``router`` reused across+ files), so it is dropped rather than guessed. Only keys with a single+ distinct value survive. Keys are router variables, and prefixed names for+ everything else a dialect shares (``laravel-route-file:``, ``nest-prefix:``,+ ``http-client:``)."""collected: dict[str, set[str]] = {}for m in maps:@@ -91,6 +93,33 @@ def merge_mount_maps(maps: list[dict[str, str]]) -> dict[str, str]:return {var: next(iter(prefixes)) for var, prefixes in collected.items() if len(prefixes) == 1}+# Mount values are strings; a declared value this cannot read travels as this.+_UNREADABLE = "\0"+# The merge above drops a key two files disagree on. A second key, always the+# same value, survives it, so a declared-but-dropped value reads as ambiguous+# (refused) rather than undeclared (the default).+_DECLARED = "declared:"+++def declare_mount(key: str, value: str | None) -> dict[str, str]:+ """The mount entries declaring *key* as *value* (``None``: unreadable)."""+ return {key: _UNREADABLE if value is None else value, _DECLARED + key: ""}+++def declared_mount(mounts: Mapping[str, str], key: str) -> tuple[bool, str | None]:+ """``(declared, value)`` for *key*; ``value`` is ``None`` when unreadable or ambiguous."""+ if _DECLARED + key not in mounts:+ return False, None+ value = mounts.get(key, _UNREADABLE)+ return True, None if value == _UNREADABLE else value+++def declared_names(mounts: Mapping[str, str], prefix: str) -> list[str]:+ """The names declared under *prefix*, agreed on or not."""+ head = _DECLARED + prefix+ return [key[len(head) :] for key in mounts if key.startswith(head)]++def group_prefixes(groups: Iterable[GroupMatch]) -> dict[str, str]:"""Resolve each router-group variable to its transitively composed prefix.diff --git a/packages/core/src/repowise/core/workspace/extractors/http/nestjs.py b/packages/core/src/repowise/core/workspace/extractors/http/nestjs.pynew file mode 100644index 000000000..54134b4e6--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/nestjs.py@@ -0,0 +1,312 @@+"""NestJS HTTP provider dialect: ``@Controller`` classes and their verb decorators.++``@Get(':id')`` names the verb and the sub-path; the ``@Controller('cats')``+above it names the prefix (a string, an array of them, or ``{ path }``).+Where the app serves them comes from its bootstrap: ``app.setGlobalPrefix``+(with its ``exclude`` list) and URI versioning (``app.enableVersioning``,+``@Version``, ``@Controller({ version })``). Those calls sit in ``main.ts`` or+a helper it calls, so they travel through the orchestrator's mount pass keyed+by the app's root: the path above the declaring file's first ``src``+directory, else its directory. A ``NestFactory.create`` file marks a root too,+so an app with no prefix of its own does not inherit one from a root above it.+A controller takes the nearest root above it; one under no root (an Nx+library) takes the setting every app in the repo shares, and is refused when+they differ.++Ceilings: an ``exclude`` list this cannot read (an imported array) excludes+nothing, so those few routes read as prefixed; ``RouterModule`` paths are not+read.+"""++from __future__ import annotations++import json+import re+from dataclasses import dataclass+from typing import TYPE_CHECKING++from ..base import line_at+from ..calls import Call, call_sites, decorated_member, file_strings+from ..langs import JS_TS+from ..strings import Arg, on_comment_line, select_argument+from .dialect import build_provider_contract+from .mounts import compose_prefix, declare_mount, declared_mount, declared_names+from .paths import normalize_http_path++if TYPE_CHECKING:+ from collections.abc import Mapping++ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+ from ..calls import FileStrings++_NEST_COMMON = ("@nestjs/common",)+_FIRST = Arg(pos=0)+_PATH_KEY = Arg(keys=("path",))+_NEUTRAL = "VERSION_NEUTRAL"++_APP_MOUNT = "nest-app:"+_PREFIX_MOUNT = "nest-prefix:"+_VERSION_MOUNT = "nest-version:"++# `@Sse('events')` serves a GET. `@All`, `@Head`, `@Options` and `@Search`+# name no verb the contract layer records.+_VERBS = {"Get": "GET", "Post": "POST", "Put": "PUT", "Delete": "DELETE", "Patch": "PATCH", "Sse": "GET"}++_CONTROLLER = Call(re.compile(r"@Controller\s*\("), JS_TS, _NEST_COMMON)+_ROUTE = Call(re.compile(rf"@(?P<verb>{'|'.join(_VERBS)})\s*\("), JS_TS, _NEST_COMMON)+_VERSION = Call(re.compile(r"@Version\s*\("), JS_TS, _NEST_COMMON)+_GLOBAL_PREFIX = Call(re.compile(r"\.setGlobalPrefix\s*\("), JS_TS, ("setGlobalPrefix",))+_VERSIONING = Call(re.compile(r"\.enableVersioning\s*\("), JS_TS, ("enableVersioning",))+_FACTORY = "NestFactory.create"++# `exclude: ['admin/(.*)']` and `'files/*'` cover what is below a path; Nest+# 11's `'files/{*splat}'` covers the path itself too.+_WILDCARD_TAIL_RE = re.compile(r"/?(?:\(\.\*\)|\*[\w$]*|(?P<splat>\{\*[\w$]*\}))$")+++@dataclass(frozen=True)+class _Controller:+ offset: int+ name: str+ paths: list[str] | None # None: unreadable+ member: int # offset of the class name, which a class `@Version` decorates+ version: list[str] | None | bool # False: not given+++@dataclass(frozen=True)+class _Route:+ offset: int+ verb: str+ paths: list[str] | None+ handler: str | None+ member: int+++def _paths(args: list[str], strings: FileStrings) -> list[str] | None:+ """The paths a decorator's first argument names, ``[""]`` for none; ``None`` if unreadable.++ ``{ path, host, version }`` carries its path under a key; an object with+ no ``path`` serves at the root, as no argument does.+ """+ if not args:+ return [""]+ values, refused = strings.resolve(args[:1], _PATH_KEY if args[0].startswith("{") else _FIRST)+ return None if refused else values or [""]+++def _versions(raws: list[str], strings: FileStrings) -> list[str] | None:+ """The versions *raws* name (``""``: version-neutral), or ``None`` if unreadable."""+ out: list[str] = []+ for raw in raws:+ if raw.endswith(_NEUTRAL):+ out.append("")+ continue+ values, refused = strings.resolve([raw], _FIRST)+ if refused or not values:+ return None+ out.extend(values)+ return out+++def _app_root(rel_path: str) -> str:+ parts = rel_path.split("/")[:-1]+ if "src" in parts:+ parts = parts[: parts.index("src")]+ return "/".join(parts)+++def _root_setting(mounts: Mapping[str, str], root: str) -> tuple[str | None, str | None] | None:+ """The ``(prefix, versioning)`` mount values *root* declares (``None``: not declared).++ ``None`` overall when one it declares cannot be read, or two files disagree.+ """+ out: list[str | None] = []+ for kind in (_PREFIX_MOUNT, _VERSION_MOUNT):+ declared, value = declared_mount(mounts, kind + root)+ if declared and value is None:+ return None+ out.append(value)+ return out[0], out[1]+++def _is_root(mounts: Mapping[str, str], root: str) -> bool:+ if _APP_MOUNT + root in mounts:+ return True+ return any(declared_mount(mounts, kind + root)[0] for kind in (_PREFIX_MOUNT, _VERSION_MOUNT))+++def _app_settings(mounts: Mapping[str, str], rel_path: str) -> tuple[str | None, str | None] | None:+ """The ``(prefix, versioning)`` of the app serving *rel_path*; ``None`` to refuse it."""+ parts = rel_path.split("/")[:-1]+ for depth in range(len(parts), -1, -1):+ root = "/".join(parts[:depth])+ if _is_root(mounts, root):+ return _root_setting(mounts, root)+ roots = {k[len(_APP_MOUNT) :] for k in mounts if k.startswith(_APP_MOUNT)}+ roots.update(declared_names(mounts, _PREFIX_MOUNT), declared_names(mounts, _VERSION_MOUNT))+ if not roots:+ return None, None+ settings = {_root_setting(mounts, root) for root in roots}+ return settings.pop() if len(settings) == 1 else None+++def _excluded(route: str, method: str, exclude: list[list[str]]) -> bool:+ """Whether the global prefix's ``exclude`` list names *route*."""+ norm = normalize_http_path(route)+ for verb, pattern in exclude:+ if verb and verb != method:+ continue+ tail = _WILDCARD_TAIL_RE.search(pattern)+ if tail is None:+ if normalize_http_path(pattern) == norm:+ return True+ continue+ head = normalize_http_path(pattern[: tail.start()])+ below = head == "/" or norm.startswith(head + "/")+ if below or (tail.group("splat") and norm == head):+ return True+ return False+++def _global_prefix(args: list[str], strings: FileStrings) -> str | None:+ """``setGlobalPrefix(args)`` as mount JSON: the prefix and its readable excludes."""+ values, refused = strings.resolve(args[:1], _FIRST)+ if refused or len(values) != 1:+ return None+ exclude: list[list[str]] = []+ for raw in select_argument(args[1:], Arg(keys=("exclude",))):+ # `{ path, method: RequestMethod.GET }` or a bare path.+ paths, _ = strings.resolve([raw], _PATH_KEY if raw.startswith("{") else _FIRST)+ method = select_argument([raw], Arg(keys=("method",))) if raw.startswith("{") else []+ verb = method[0].rpartition(".")[2].upper() if method else ""+ exclude.extend([verb if verb != "ALL" else "", p] for p in paths)+ return json.dumps({"prefix": values[0], "exclude": exclude})+++def _versioning(args: list[str], strings: FileStrings) -> str | None:+ """``enableVersioning(args)`` as mount JSON when it versions by URI.++ ``""`` when it versions by header or media type, which leaves paths alone;+ ``None`` when what shapes the path cannot be read (options held in a variable).+ """+ if args and not args[0].startswith("{"):+ return None+ kind = select_argument(args, Arg(keys=("type",)))+ if kind and not kind[0].endswith("URI"):+ return ""+ prefix = select_argument(args, Arg(keys=("prefix",)))+ segment: str | None = "v"+ if prefix:+ values, refused = strings.resolve(prefix, _FIRST)+ segment = "" if prefix[0] == "false" else None if refused or not values else values[0]+ default = _versions(select_argument(args, Arg(keys=("defaultVersion",))), strings)+ if segment is None or default is None:+ return None+ return json.dumps({"prefix": segment, "default": default})+++def _route_versions(+ route: _Route, owner: _Controller, decorated: dict[int, list[str] | None], default: list[str]+) -> list[str] | None:+ """The versions a route serves: its own ``@Version``, else its controller's, else the default."""+ if route.member in decorated:+ return decorated[route.member]+ if owner.member in decorated:+ return decorated[owner.member]+ return default if owner.version is False else owner.version+++class NestDialect:+ name = "nestjs"+ extensions = JS_TS++ def collect_mounts(self, ctx: ScanContext) -> dict[str, str]:+ out: dict[str, str] = {}+ root = _app_root(ctx.rel_path)+ if _FACTORY in ctx.content:+ out[_APP_MOUNT + root] = ""+ for shape, args, _m, strings in call_sites(ctx, (_GLOBAL_PREFIX, _VERSIONING), empty=True):+ if shape is _GLOBAL_PREFIX:+ out.update(declare_mount(_PREFIX_MOUNT + root, _global_prefix(args, strings)))+ elif (setting := _versioning(args, strings)) != "":+ out.update(declare_mount(_VERSION_MOUNT + root, setting))+ return out++ def extract(self, ctx: ScanContext) -> list[Contract]:+ content = ctx.content+ if "@Controller" not in content or _NEST_COMMON[0] not in content:+ return []+ settings = _app_settings(ctx.mounts, ctx.rel_path)+ strings = file_strings(ctx)+ if settings is None or strings is None:+ return [] # the app declares where it serves, and this cannot read it+ prefix = json.loads(settings[0]) if settings[0] is not None else None+ versioning = json.loads(settings[1]) if settings[1] is not None else None++ controllers: list[_Controller] = []+ routes: list[_Route] = []+ decorated: dict[int, list[str] | None] = {} # member offset -> its `@Version`+ for shape, args, m, _ in call_sites(ctx, (_CONTROLLER, _ROUTE, _VERSION), strings, empty=True):+ member = decorated_member(content, m.start())+ if member is None or on_comment_line(content, m.start()):+ continue+ if shape is _ROUTE:+ routes.append(+ _Route(+ m.start(),+ _VERBS[m.group("verb")],+ _paths(args, strings),+ None if member.group("cls") else member.group("name"),+ member.start("name"),+ )+ )+ elif shape is _VERSION:+ decorated[member.start("name")] = _versions(select_argument(args, _FIRST), strings)+ elif member.group("cls"):+ version = select_argument(args[:1], Arg(keys=("version",)))+ controllers.append(+ _Controller(+ m.start(),+ member.group("name"),+ _paths(args, strings),+ member.start("name"),+ _versions(version, strings) if version else False,+ )+ )+ controllers.sort(key=lambda c: c.offset)++ out: list[Contract] = []+ for route in routes:+ owner = next((c for c in reversed(controllers) if c.offset < route.offset), None)+ # No controller above, or a path this cannot read.+ if owner is None or owner.paths is None or route.paths is None:+ continue+ segments = [""]+ if versioning is not None:+ versions = _route_versions(route, owner, decorated, versioning["default"])+ if versions is None:+ continue+ segments = [versioning["prefix"] + v if v else "" for v in versions] or [""]+ line = line_at(content, route.offset)+ handler = f"{owner.name}.{route.handler}" if route.handler else None+ for base in owner.paths:+ for sub in route.paths:+ path = compose_prefix(base, sub)+ head = ""+ if prefix is not None and not _excluded(path, route.verb, prefix["exclude"]):+ head = prefix["prefix"]+ for segment in segments:+ full = compose_prefix(compose_prefix(head, segment), path)+ c = build_provider_contract(+ ctx,+ method=route.verb,+ path_raw=full if full.startswith("/") else "/" + full,+ framework=self.name,+ line=line,+ handler=handler,+ )+ if c is not None:+ out.append(c)+ return outdiff --git a/packages/core/src/repowise/core/workspace/extractors/http/node_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/node_clients.pynew file mode 100644index 000000000..a0001897b--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/node_clients.py@@ -0,0 +1,352 @@+"""Node HTTP client libraries: axios, ky, got and ofetch.++A call goes straight through the library (``axios.post(url)``, ``ky.get(url)``,+``got(url, { method })``) or through an instance created with a base+(``axios.create({ baseURL })``, ``ky.create({ prefixUrl })``,+``got.extend({ prefixUrl })``, ``ofetch.create({ baseURL })``). An instance is+read in the file creating it and in every file importing it from that module,+by name or as its default export: the key is the module's name (what an import+specifier ends with) and the export's, so an instance travels through the+orchestrator's mount pass, and two different instances one key names are read+as neither. A package import (``import http from 'http'``) names no module of+the repo and is never looked up.++A base resolves through the strings layer. One it cannot read+(``process.env.API_URL``) stays a ``${...}`` placeholder, which the consumer+builder records as the call's base token, exactly as for a hand-written+``${API_URL}/users``. ``ofetch(url)`` itself is the ``fetch`` reader's.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from functools import lru_cache+from typing import TYPE_CHECKING++from ..base import line_at+from ..calls import Call, call_sites, file_strings, receiver_at+from ..langs import JS_TS+from ..strings import NAME_RE, Arg, call_arguments, select_argument+from .client_calls import VERBS, is_rooted_url, method_from_argument+from .dialect import build_consumer_contract+from .wrappers import GENERIC_ARGS++if TYPE_CHECKING:+ from repowise.core.workspace.contracts import Contract++ from ..base import ScanContext+ from ..calls import FileStrings+++@dataclass(frozen=True)+class _Library:+ name: str+ factories: tuple[str, ...]+ base_key: str+ verbs: bool # `client.get(url)`; ofetch has none+ exports: tuple[str, ...] = ("default",) # what an import of the client names+++_LIBRARIES = {+ lib.name: lib+ for lib in (+ _Library("axios", ("create",), "baseURL", True),+ _Library("ky", ("create", "extend"), "prefixUrl", True),+ _Library("got", ("extend",), "prefixUrl", True),+ _Library("ofetch", ("create",), "baseURL", False, ("ofetch", "$fetch")),+ )+}+# A library's specifier in quotes, so `ky` is not read out of every word holding it.+_SPECIFIERS = tuple(f"{q}{name}{q}" for name in _LIBRARIES for q in "'\"")+# axios is also a global (a script tag, Laravel's `window.axios`, Nuxt's `$axios`).+_AXIOS_GLOBALS = ("axios.", "axios(")+# Qualifiers a client is called through: its own class, the browser global, Vue.+_QUALIFIER_RE = re.compile(r"(?:this|window|Vue)\s*\.\s*$")++_URL_KEY = Arg(keys=("url",))+_METHOD_KEY = Arg(keys=("method",))++_MOUNT_NAMED = "http-client:"+_MOUNT_DEFAULT = "http-client-default:"+# Present when any file of the repo exports an instance, so a file importing+# none of the libraries is only read for imports then.+_MOUNT_ANY = "http-client-exports"+++@dataclass(frozen=True)+class _Client:+ library: _Library+ base: str # "" for none; an unreadable base is a `${...}` placeholder+ direct: bool = False # the library itself, not an instance of it+++# `import x from 'm'`, `import x, { a, b as c } from 'm'`, `import { a } from 'm'`.+_IMPORT_RE = re.compile(+ r"""import(?<![\w$]import)\s+(?:type\s+)?(?:(?P<default>[A-Za-z_$][\w$]*)\s*,?\s*)?"""+ r"""(?:\{(?P<named>[^{}]*)\}\s*)?from\s*['"](?P<spec>[^'"]+)['"]"""+)+# `const x = require('m')`, the binding read back from the `require`.+_REQUIRE_RE = re.compile(r"""require(?<![\w$]require)\s*\(\s*['"](?P<spec>[^'"]+)['"]\s*\)""")+_REQUIRE_BIND_RE = re.compile(r"(?:const|let|var)\s+(?P<default>[A-Za-z_$][\w$]*)\s*=\s*$")+# What `<client>.create(` is assigned to, read back from the call on its line.+_FACTORY_BIND_RE = re.compile(+ r"(?:(?P<default>export\s+default)|(?P<export>export\s+)?(?:const|let|var)\s+(?P<name>[A-Za-z_$][\w$]*)"+ r"|this\s*\.\s*(?P<field>[A-Za-z_$][\w$]*)"+ r"|(?:(?:private|public|protected|readonly|static)\s+)+(?P<member>[A-Za-z_$][\w$]*))"+ r"(?:\s*:[^=\n]+)?\s*=?\s*(?:await\s+)?$"+)+# `export { api, v2 as client }` and `export default api`.+_EXPORT_LIST_RE = re.compile(r"export(?<![\w$]export)\s*\{(?P<names>[^{}]*)\}")+_EXPORT_DEFAULT_RE = re.compile(+ r"export(?<![\w$]export)\s+default\s+(?P<name>[A-Za-z_$][\w$]*)\s*;?\s*$", re.MULTILINE+)+_EXTENSION_RE = re.compile(r"\.(?:[cm]?[jt]sx?)$")+++def _named(entries: str) -> list[tuple[str, str]]:+ """``(name, alias)`` per ``a`` / ``a as b`` entry of an import or export list."""+ out: list[tuple[str, str]] = []+ for entry in entries.split(","):+ parts = entry.split()+ if parts and parts[0] == "type":+ parts = parts[1:]+ if len(parts) == 1:+ out.append((parts[0], parts[0]))+ elif len(parts) == 3 and parts[1] == "as":+ out.append((parts[0], parts[2]))+ return out+++def _imports(content: str) -> list[tuple[str, str, str]]:+ """``(local, imported, specifier)`` per binding; ``imported`` is ``default`` for a default."""+ out: list[tuple[str, str, str]] = []+ if "import" in content:+ for m in _IMPORT_RE.finditer(content):+ if m.group("default"):+ out.append((m.group("default"), "default", m.group("spec")))+ out.extend((alias, name, m.group("spec")) for name, alias in _named(m.group("named") or ""))+ if "require" in content:+ for m in _REQUIRE_RE.finditer(content):+ line_start = content.rfind("\n", 0, m.start()) + 1+ bound = _REQUIRE_BIND_RE.search(content, line_start, m.start())+ if bound is not None:+ out.append((bound.group("default"), "default", m.group("spec")))+ return out+++def _is_package(spec: str) -> bool:+ """Whether *spec* names an npm package (``http``, ``@scope/sdk``) rather than a module here."""+ if spec.startswith((".", "/", "~", "#", "@/")):+ return False+ parts = spec.split("/")+ return len(parts) == 1 or (spec.startswith("@") and len(parts) == 2)+++def _module_name(path: str) -> str:+ """What a specifier naming *path* ends with: its stem, or its directory's for an index."""+ parts = _EXTENSION_RE.sub("", path).rstrip("/").split("/")+ if parts[-1] == "index" and len(parts) > 1:+ return parts[-2]+ return parts[-1]+++def _key(module: str, export: str) -> str:+ return _MOUNT_DEFAULT + module if export == "default" else f"{_MOUNT_NAMED}{module}:{export}"+++def _encode(client: _Client) -> str:+ return f"{client.library.name}\n{client.base}"+++def _decode(value: str) -> _Client:+ name, _, base = value.partition("\n")+ return _Client(_LIBRARIES[name], base)+++def _alternation(names: tuple[str, ...]) -> str:+ # Longest first, so `$api` is not read as `api` behind a `$`.+ return "|".join(re.escape(n) for n in sorted(names, key=len, reverse=True))+++@lru_cache(maxsize=256)+def _factory_re(names: tuple[str, ...]) -> re.Pattern[str]:+ """``<client>.create(`` / ``.extend(`` on *names*, led by the names so it has a literal start."""+ return re.compile(rf"(?P<parent>{_alternation(names)})\s*\.\s*(?P<factory>create|extend)\s*\(")+++@lru_cache(maxsize=256)+def _calls_for(names: tuple[str, ...]) -> tuple[Call, ...]:+ """``x.get(url)``, ``x.request(config)`` and ``x(url)`` on *names*."""+ verbs = "|".join(sorted(VERBS | {"request"}))+ head = re.compile(+ rf"(?P<recv>{_alternation(names)})\s*(?:\.\s*(?P<verb>{verbs})\s*)?{GENERIC_ARGS}\("+ )+ return (Call(head, JS_TS),)+++def _base(args: list[str], library: _Library, strings: FileStrings) -> str | None:+ """The base a factory call's options name; ``None`` when they name none."""+ raws = select_argument(args, Arg(keys=(library.base_key,)))+ if not raws:+ return None+ text = strings.text(raws[0])+ if text is not None:+ return text+ name = NAME_RE.match(raws[0])+ return f"${{{name.group(0) if name else 'base'}}}"+++@dataclass+class _FileClients:+ callable: dict[str, _Client] # every client this file can call, by local name+ exported: dict[str, _Client] # what it exports, by exported name (`default` too)+++def _file_clients(ctx: ScanContext) -> _FileClients:+ content = ctx.content+ clients: dict[str, _Client] = {}+ for local, imported, spec in _imports(content):+ library = _LIBRARIES.get(spec)+ if library is not None:+ if imported in library.exports:+ clients[local] = _Client(library, "", direct=True)+ elif not _is_package(spec):+ value = ctx.mounts.get(_key(_module_name(spec), imported))+ if value is not None:+ clients[local] = _decode(value)+ axios = _LIBRARIES["axios"]+ if "axios" not in clients and any(g in content for g in _AXIOS_GLOBALS):+ clients["axios"] = _Client(axios, "", direct=True)+ if "$axios" in content:+ clients.setdefault("$axios", _Client(axios, "", direct=True))+ exported: dict[str, _Client] = {}+ if not clients or (".create" not in content and ".extend" not in content):+ return _FileClients(clients, exported)++ strings = file_strings(ctx)+ locals_: dict[str, _Client] = {}+ for m in _factory_re(tuple(clients)).finditer(content):+ parent = clients[m.group("parent")]+ if not receiver_at(content, m.start(), _QUALIFIER_RE) or m.group("factory") not in parent.library.factories:+ continue+ args = call_arguments(content, m.end() - 1)+ if args is None or strings is None:+ continue+ bound = _FACTORY_BIND_RE.search(content, content.rfind("\n", 0, m.start()) + 1, m.start())+ if bound is None:+ continue+ base = _base(args, parent.library, strings)+ client = _Client(parent.library, parent.base if base is None else base)+ name = bound.group("name") or bound.group("field") or bound.group("member")+ if bound.group("default"):+ exported["default"] = client+ elif name:+ locals_[name] = client+ if bound.group("export"):+ exported[name] = client+ if locals_:+ for m in _EXPORT_LIST_RE.finditer(content):+ for name, alias in _named(m.group("names")):+ if name in locals_:+ exported[alias] = locals_[name]+ named = _EXPORT_DEFAULT_RE.search(content)+ if named is not None and named.group("name") in locals_:+ exported.setdefault("default", locals_[named.group("name")])+ clients.update(locals_)+ return _FileClients(clients, exported)+++def client_mounts(ctx: ScanContext) -> dict[str, str]:+ """The client instances *ctx* exports, as mount entries."""+ content = ctx.content+ if ".create" not in content and ".extend" not in content:+ return {}+ if not any(s in content for s in _SPECIFIERS) and "axios.create" not in content:+ return {} # no library here, so no instance of one (imported ones are not re-read)+ exported = _file_clients(ctx).exported+ module = _module_name(ctx.rel_path)+ out = {_key(module, name): _encode(client) for name, client in exported.items()}+ if out:+ out[_MOUNT_ANY] = ""+ return out+++# axios verbs that take a body before their options.+_BODY_VERBS = frozenset({"post", "put", "patch"})+++def _request(+ verb: str | None, args: list[str], client: _Client, strings: FileStrings+) -> tuple[str, str] | None:+ """``(method, url)`` a call names: ``x.post(url)``, ``x(url, { method })``, ``x({ url, method })``.++ A base in the call's own options (``axios.get(url, { baseURL })``) wins over+ the client's, as it does at run time.+ """+ if not args:+ return None+ if verb is not None and verb != "request":+ url_raws, method = args[:1], verb.upper()+ body = client.library.name == "axios" and verb in _BODY_VERBS+ options = args[2:3] if body else args[1:2]+ else:+ config = args[0].startswith("{")+ if verb == "request" and not config:+ return None # `request` takes a config object+ url_raws = select_argument(args[:1], _URL_KEY) if config else args[:1]+ options = args[:1] if config else args[1:2]+ methods = select_argument(options, _METHOD_KEY)+ method = (method_from_argument(methods[0]) if methods else None) or "GET"+ url = strings.text(url_raws[0]) if url_raws else None+ if url is None:+ return None+ base = _base(options, client.library, strings)+ return method, _join(client.base if base is None else base, url)+++def _join(base: str, url: str) -> str:+ if not base or url.startswith(("http://", "https://", "//")):+ return url+ return base.rstrip("/") + "/" + url.lstrip("/") if url else base+++def client_calls(ctx: ScanContext) -> tuple[list[Contract], frozenset[str]]:+ """Consumer contracts for the library and instance calls in *ctx*, and the names read."""+ content = ctx.content+ if not (+ any(s in content for s in _SPECIFIERS)+ or "axios" in content+ or (_MOUNT_ANY in ctx.mounts and ("import" in content or "require" in content))+ ):+ return [], frozenset()+ clients = _file_clients(ctx).callable+ # `ofetch(url)` is a fetch call the fetch reader already reads.+ names = tuple(n for n, c in clients.items() if not (c.direct and not c.library.verbs))+ if not names:+ return [], frozenset()+ out: list[Contract] = []+ for _call, args, m, strings in call_sites(ctx, _calls_for(names)):+ if not receiver_at(content, m.start(), _QUALIFIER_RE):+ continue+ client = clients[m.group("recv")]+ verb = m.group("verb")+ if verb in VERBS and not client.library.verbs:+ continue+ if verb == "request" and client.library.name != "axios":+ continue+ request = _request(verb, args, client, strings)+ if request is None:+ continue+ method, url = request+ if not is_rooted_url(url):+ continue # relative to a base this cannot see+ c = build_consumer_contract(+ ctx, method=method, url=url, client=client.library.name, line=line_at(content, m.start())+ )+ if c is not None:+ out.append(c)+ return out, frozenset(names)+++__all__ = ["client_calls", "client_mounts"]diff --git a/packages/core/src/repowise/core/workspace/extractors/strings.py b/packages/core/src/repowise/core/workspace/extractors/strings.pyindex d83944482..9c1c5ed67 100644--- a/packages/core/src/repowise/core/workspace/extractors/strings.py+++ b/packages/core/src/repowise/core/workspace/extractors/strings.py@@ -404,7 +404,7 @@ def string_constants(text = content if code is None else codeseen: dict[str, str | None] = {}for m in syntax.assignment.finditer(text):- if code is None and _on_comment_line(content, m.start()):+ if code is None and on_comment_line(content, m.start()):continue # an example in a doc comment is not a bindingname = m.group("name")rhs = content[m.start("rhs") : m.end("rhs")].strip()@@ -415,7 +415,7 @@ def string_constants(seen[name] = None if name in seen or resolve_string(rhs, syntax) is None else rhsif syntax.members is not None:for m in syntax.members.finditer(text):- if code is None and _on_comment_line(content, m.start()):+ if code is None and on_comment_line(content, m.start()):continue_fold_members(content, m.end() - 1, m.group("name"), syntax, seen)# `x += "/v1"` and `x, err = f()` rebind a name without the plain form.@@ -499,7 +499,7 @@ _MULTI_ASSIGN_RE = re.compile()-def _on_comment_line(content: str, offset: int) -> bool:+def on_comment_line(content: str, offset: int) -> bool:"""True when the line holding *offset* starts as a line or block comment."""start = max(content.rfind("\n", 0, offset) + 1, offset - 200)return content[start:offset].lstrip().startswith(("//", "#", "*", "/*"))@@ -777,6 +777,7 @@ __all__ = ["literal_span","map_entry","match_paren",+ "on_comment_line","resolve_argument","resolve_string","select_argument",diff --git a/tests/unit/workspace/test_nestjs_routes.py b/tests/unit/workspace/test_nestjs_routes.pynew file mode 100644index 000000000..3e5d23ddd--- /dev/null+++ b/tests/unit/workspace/test_nestjs_routes.py@@ -0,0 +1,309 @@+"""NestJS controllers as HTTP providers.++The served path is the global prefix (unless excluded), the URI version, the+controller prefix and the route's own path, in that order. The prefix and the+versioning are declared in the app's bootstrap, usually another file, so every+test here extracts a whole repo.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.extractors.http import HttpExtractor++_COMMON = "import { Controller, Get, Post, Delete, Version } from '@nestjs/common';\n"+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _routes(repo: Path) -> set[tuple[str, str]]:+ return {+ (c.meta["method"], c.meta["path"])+ for c in HttpExtractor().extract(repo, "api")+ if c.role == "provider" and c.meta.get("framework") == "nestjs"+ }+++def _controller(body: str, head: str = "@Controller('cats')") -> str:+ return f"{_COMMON}{head}\nexport class CatsController {{\n{body}\n}}\n"+++class TestControllers:+ def test_verbs_under_the_controller_prefix(self, tmp_path: Path) -> None:+ body = (+ " @Get()\n findAll() {}\n"+ " @Get(':id')\n findOne() {}\n"+ " @Post()\n create() {}\n"+ " @Delete(':id/toys/:toy')\n remove() {}\n"+ )+ repo = _write(tmp_path, {"src/cats/cats.controller.ts": _controller(body)})+ assert _routes(repo) == {+ ("GET", "/cats"),+ ("GET", "/cats/{param}"),+ ("POST", "/cats"),+ ("DELETE", "/cats/{param}/toys/{param}"),+ }++ def test_path_arrays_object_prefix_and_constants(self, tmp_path: Path) -> None:+ body = " @Get(['a', PATH])\n many() {}\n"+ head = "const PATH = 'b';\n@Controller({ path: 'v', host: 'x.io' })"+ repo = _write(tmp_path, {"src/c.controller.ts": _controller(body, head)})+ assert _routes(repo) == {("GET", "/v/a"), ("GET", "/v/b")}++ def test_a_controller_with_no_path_serves_at_the_root(self, tmp_path: Path) -> None:+ body = " @Get('health')\n health() {}\n"+ repo = _write(+ tmp_path,+ {+ "a.controller.ts": _controller(body, "@Controller()"),+ "b.controller.ts": _controller(body.replace("health", "ping"), "@Controller({ host: 'h' })"),+ },+ )+ assert _routes(repo) == {("GET", "/health"), ("GET", "/ping")}++ def test_sse_is_a_get_and_all_head_options_are_not_recorded(self, tmp_path: Path) -> None:+ body = " @Sse('events')\n s() {}\n @All('any')\n a() {}\n @Head('h')\n h() {}\n"+ repo = _write(tmp_path, {"c.controller.ts": _controller(body)})+ assert _routes(repo) == {("GET", "/cats/events")}++ def test_stacked_decorators_and_comments_reach_the_handler(self, tmp_path: Path) -> None:+ body = (+ " @Get(':id')\n @UseGuards(AuthGuard('jwt'))\n // cached\n"+ " @Header('Cache-Control', 'none')\n async findOne(@Param('id') id: string) {}\n"+ )+ repo = _write(tmp_path, {"c.controller.ts": _controller(body)})+ (row,) = [c for c in HttpExtractor().extract(repo, "api") if c.role == "provider"]+ assert row.meta["handler"] == "CatsController.findOne"+ assert row.line == 4++ def test_an_unreadable_path_is_refused(self, tmp_path: Path) -> None:+ body = " @Get(routes.one)\n one() {}\n @Get('two')\n two() {}\n"+ repo = _write(+ tmp_path,+ {+ "a.controller.ts": _controller(body),+ "b.controller.ts": _controller(" @Get('x')\n x() {}\n", "@Controller(prefixFor('b'))"),+ },+ )+ assert _routes(repo) == {("GET", "/cats/two")}++ def test_without_the_nest_import_nothing_is_read(self, tmp_path: Path) -> None:+ text = "@Controller('cats')\nclass C {\n @Get(':id')\n one() {}\n}\n"+ repo = _write(tmp_path, {"c.ts": text})+ assert _routes(repo) == set()+++class TestGlobalPrefix:+ _MAIN = (+ "import { NestFactory } from '@nestjs/core';\n"+ "async function bootstrap() {\n const app = await NestFactory.create(AppModule);\n"+ " app.setGlobalPrefix({args});\n await app.listen(3000);\n}\n"+ )++ def _app(self, tmp_path: Path, args: str, body: str = " @Get(':id')\n one() {}\n") -> Path:+ return _write(+ tmp_path,+ {+ "src/main.ts": self._MAIN.replace("{args}", args),+ "src/cats/cats.controller.ts": _controller(body),+ },+ )++ def test_the_prefix_from_the_bootstrap_file(self, tmp_path: Path) -> None:+ assert _routes(self._app(tmp_path, "'api/v1'")) == {("GET", "/api/v1/cats/{param}")}++ def test_excluded_routes_keep_their_own_path(self, tmp_path: Path) -> None:+ body = " @Get('health')\n h() {}\n @Get(':id')\n one() {}\n @Post('health')\n p() {}\n"+ args = "'api', { exclude: [{ path: 'cats/health', method: RequestMethod.GET }] }"+ assert _routes(self._app(tmp_path, args, body)) == {+ ("GET", "/cats/health"),+ ("GET", "/api/cats/{param}"),+ ("POST", "/api/cats/health"),+ }++ def test_a_wildcard_exclude_covers_everything_below_it(self, tmp_path: Path) -> None:+ body = " @Get('a')\n a() {}\n"+ assert _routes(self._app(tmp_path, "'api', { exclude: ['cats/(.*)'] }", body)) == {+ ("GET", "/cats/a")+ }++ def test_an_unread_exclude_list_excludes_nothing(self, tmp_path: Path) -> None:+ assert _routes(self._app(tmp_path, "'api', { exclude: excludePaths }")) == {+ ("GET", "/api/cats/{param}")+ }++ def test_an_unreadable_prefix_refuses_the_app(self, tmp_path: Path) -> None:+ assert _routes(self._app(tmp_path, "config.prefix")) == set()++ def test_each_app_of_a_monorepo_takes_its_own_prefix(self, tmp_path: Path) -> None:+ main = self._MAIN+ repo = _write(+ tmp_path,+ {+ "apps/api/src/main.ts": main.replace("{args}", "'api'"),+ "apps/api/src/cats.controller.ts": _controller(" @Get()\n a() {}\n"),+ "apps/api-admin/src/main.ts": main.replace("{args}", "'admin'"),+ "apps/api-admin/src/cats.controller.ts": _controller(" @Post()\n b() {}\n"),+ # A bootstrap of its own with no prefix: nothing inherited.+ "apps/plain/src/main.ts": "const app = await NestFactory.create(M);\n",+ "apps/plain/src/cats.controller.ts": _controller(" @Delete()\n c() {}\n"),+ # A library shared by apps that disagree is served where this cannot tell.+ "libs/users/src/users.controller.ts": _controller(" @Patch()\n d() {}\n"),+ },+ )+ assert _routes(repo) == {("GET", "/api/cats"), ("POST", "/admin/cats"), ("DELETE", "/cats")}++ def test_a_library_controller_takes_the_one_apps_prefix(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "apps/api/src/main.ts": self._MAIN.replace("{args}", "'api'"),+ "libs/users/src/lib/users.controller.ts": _controller(" @Get()\n a() {}\n"),+ },+ )+ assert _routes(repo) == {("GET", "/api/cats")}++ def test_two_disagreeing_declarations_refuse_the_app(self, tmp_path: Path) -> None:+ repo = self._app(tmp_path, "'api'")+ _write(repo, {"src/other.ts": "app.setGlobalPrefix('v2');\n"})+ assert _routes(repo) == set()+++class TestVersioning:+ def _app(self, tmp_path: Path, versioning: str, controllers: dict[str, str]) -> Path:+ main = f"app.setGlobalPrefix('api');\napp.enableVersioning({versioning});\n"+ return _write(tmp_path, {"src/main.ts": main, **controllers})++ def test_uri_versions_sit_between_the_prefix_and_the_controller(self, tmp_path: Path) -> None:+ body = (+ " @Get()\n all() {}\n"+ " @Version('2')\n @Get(':id')\n one() {}\n"+ " @Get('n')\n @Version(VERSION_NEUTRAL)\n n() {}\n"+ )+ head = "@Controller({ path: 'cats', version: ['1', '3'] })"+ repo = self._app(+ tmp_path,+ "{ type: VersioningType.URI }",+ {"src/c.controller.ts": _controller(body, head)},+ )+ assert _routes(repo) == {+ ("GET", "/api/v1/cats"),+ ("GET", "/api/v3/cats"),+ ("GET", "/api/v2/cats/{param}"),+ ("GET", "/api/cats/n"),+ }++ def test_the_default_version_and_a_custom_prefix(self, tmp_path: Path) -> None:+ repo = self._app(+ tmp_path,+ "{ type: VersioningType.URI, prefix: 'version', defaultVersion: '1' }",+ {"src/c.controller.ts": _controller(" @Get()\n all() {}\n")},+ )+ assert _routes(repo) == {("GET", "/api/version1/cats")}++ def test_a_class_version_decorator(self, tmp_path: Path) -> None:+ text = f"{_COMMON}@Version('4')\n@Controller('cats')\nexport class C {{\n @Get()\n a() {{}}\n}}\n"+ repo = self._app(tmp_path, "", {"src/c.controller.ts": text})+ assert _routes(repo) == {("GET", "/api/v4/cats")}++ def test_header_versioning_leaves_paths_alone(self, tmp_path: Path) -> None:+ repo = self._app(+ tmp_path,+ "{ type: VersioningType.HEADER, header: 'X-Version' }",+ {"src/c.controller.ts": _controller(" @Version('2')\n @Get()\n a() {}\n")},+ )+ assert _routes(repo) == {("GET", "/api/cats")}+++class TestReviewedEdges:+ def test_two_controllers_in_one_file_and_a_commented_route(self, tmp_path: Path) -> None:+ text = (+ f"{_COMMON}@Controller('a')\nexport class A {{\n // @Get('old')\n @Get('new')\n n() {{}}\n}}\n"+ "@Controller('b')\nexport class B {\n @Get()\n m() {}\n}\n"+ )+ repo = _write(tmp_path, {"c.controller.ts": text})+ rows = sorted(+ (c.meta["path"], c.meta["handler"])+ for c in HttpExtractor().extract(repo, "api")+ if c.role == "provider"+ )+ assert rows == [("/a/new", "A.n"), ("/b", "B.m")]++ def test_neutral_inside_version_arrays(self, tmp_path: Path) -> None:+ body = " @Version(['1', VERSION_NEUTRAL])\n @Get()\n a() {}\n"+ repo = _write(+ tmp_path,+ {+ "src/main.ts": "app.setGlobalPrefix('api');\napp.enableVersioning({ defaultVersion: [VERSION_NEUTRAL, '2'] });\n",+ "src/c.controller.ts": _controller(body + " @Get('d')\n d() {}\n"),+ },+ )+ assert _routes(repo) == {+ ("GET", "/api/v1/cats"),+ ("GET", "/api/cats"),+ ("GET", "/api/cats/d"),+ ("GET", "/api/v2/cats/d"),+ }++ def test_an_unreadable_version_drops_only_its_route(self, tmp_path: Path) -> None:+ body = " @Version(V)\n @Get('x')\n x() {}\n @Get('y')\n y() {}\n"+ repo = _write(+ tmp_path,+ {"src/main.ts": "app.enableVersioning({ prefix: false, defaultVersion: '1' });\n", "src/c.controller.ts": _controller(body)},+ )+ assert _routes(repo) == {("GET", "/1/cats/y")}++ def test_versioning_options_in_a_variable_refuse_the_app(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {"src/main.ts": "app.enableVersioning(versioningOptions);\n", "src/c.controller.ts": _controller(" @Get()\n a() {}\n")},+ )+ assert _routes(repo) == set()++ def test_exclude_wildcards_and_methods(self, tmp_path: Path) -> None:+ body = (+ " @Get()\n base() {}\n @Get('x/y')\n deep() {}\n"+ " @Post('h')\n h() {}\n"+ )+ main = "app.setGlobalPrefix('api', { exclude: ['cats/*', { path: 'cats/h', method: RequestMethod.ALL }] });\n"+ repo = _write(tmp_path, {"src/main.ts": main, "src/c.controller.ts": _controller(body)})+ assert _routes(repo) == {("GET", "/api/cats"), ("GET", "/cats/x/y"), ("POST", "/cats/h")}++ def test_a_splat_exclude_covers_the_path_itself(self, tmp_path: Path) -> None:+ main = "app.setGlobalPrefix('api', { exclude: ['cats/{*splat}'] });\n"+ repo = _write(tmp_path, {"src/main.ts": main, "src/c.controller.ts": _controller(" @Get()\n a() {}\n")})+ assert _routes(repo) == {("GET", "/cats")}++ def test_only_the_disagreeing_app_is_refused(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "apps/a/src/main.ts": "app.setGlobalPrefix('api');\n",+ "apps/a/src/other.ts": "app.setGlobalPrefix('v2');\n",+ "apps/a/src/c.controller.ts": _controller(" @Get()\n a() {}\n"),+ "apps/b/src/main.ts": "app.setGlobalPrefix('b');\n",+ "apps/b/src/c.controller.ts": _controller(" @Post()\n b() {}\n"),+ },+ )+ assert _routes(repo) == {("POST", "/b/cats")}+++def test_a_declared_mount_two_files_disagree_on_reads_as_ambiguous() -> None:+ from repowise.core.workspace.extractors.http.mounts import (+ declare_mount,+ declared_mount,+ merge_mount_maps,+ )++ merged = merge_mount_maps([declare_mount("k", "a"), declare_mount("k", "b"), declare_mount("j", None)])+ assert declared_mount(merged, "k") == (True, None)+ assert declared_mount(merged, "j") == (True, None)+ assert declared_mount(merge_mount_maps([declare_mount("k", "a")]), "k") == (True, "a")+ assert declared_mount(merged, "other") == (False, None)diff --git a/tests/unit/workspace/test_node_clients.py b/tests/unit/workspace/test_node_clients.pynew file mode 100644index 000000000..ff6e7f585--- /dev/null+++ b/tests/unit/workspace/test_node_clients.py@@ -0,0 +1,242 @@+"""axios, ky, got and ofetch consumers, directly and through instances with a base.++An instance is usually created in one module and called from many, so every+test here extracts a whole repo: the base travels with the instance's export.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.workspace.extractors.http import HttpExtractor+from repowise.core.workspace.matching import match_contracts+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _calls(repo: Path) -> set[tuple[str, str, str, str]]:+ return {+ (c.meta["client"], c.meta["method"], c.meta["path"], c.meta.get("base_token", ""))+ for c in HttpExtractor().extract(repo, "web")+ if c.role == "consumer"+ }+++class TestDirectCalls:+ def test_axios_verbs_config_and_folded_urls(self, tmp_path: Path) -> None:+ text = (+ "import axios from 'axios';\n"+ "const USERS = '/api/users';\n"+ "axios.post('/api/tickets/refund', body);\n"+ "axios.get<User[]>(USERS);\n"+ "axios.delete(`${USERS}/${id}`);\n"+ "axios({ url: '/api/orders', method: 'put' });\n"+ "axios.request({ url: '/api/sync', method: 'POST' });\n"+ "axios('/api/ping');\n"+ )+ assert _calls(_write(tmp_path, {"a.ts": text})) == {+ ("axios", "POST", "/api/tickets/refund", ""),+ ("axios", "GET", "/api/users", ""),+ ("axios", "DELETE", "/api/users/{param}", ""),+ ("axios", "PUT", "/api/orders", ""),+ ("axios", "POST", "/api/sync", ""),+ ("axios", "GET", "/api/ping", ""),+ }++ def test_ky_and_got_need_their_import(self, tmp_path: Path) -> None:+ text = (+ "import ky from 'ky';\nimport got from 'got';\n"+ "ky.post('/api/a');\nky('/api/b', { method: 'patch' });\ngot.delete('/api/c');\n"+ )+ repo = _write(tmp_path, {"a.ts": text, "b.ts": "ky.post('/api/x');\ngot('/api/y');\n"})+ assert _calls(repo) == {+ ("ky", "POST", "/api/a", ""),+ ("ky", "PATCH", "/api/b", ""),+ ("got", "DELETE", "/api/c", ""),+ }++ def test_a_direct_ofetch_call_is_read_once(self, tmp_path: Path) -> None:+ text = "import { ofetch } from 'ofetch';\nofetch('/api/a');\n"+ assert _calls(_write(tmp_path, {"a.ts": text})) == {("fetch", "GET", "/api/a", "")}+++class TestInstances:+ _HTTP = (+ "import axios from 'axios';\n"+ "export const api = axios.create({ baseURL: '/api/v2' });\n"+ "export const remote = axios.create({ baseURL: process.env.API_URL });\n"+ "const internal = axios.create({ baseURL: 'http://svc:8000/internal' });\n"+ "export { internal as svc };\n"+ "export default api;\n"+ )++ def test_a_base_composes_in_the_creating_file(self, tmp_path: Path) -> None:+ text = self._HTTP + "api.get('/users');\ninternal.post('jobs');\n"+ assert _calls(_write(tmp_path, {"src/lib/http.ts": text})) == {+ ("axios", "GET", "/api/v2/users", ""),+ ("axios", "POST", "/internal/jobs", ""),+ }++ def test_named_aliased_and_default_imports(self, tmp_path: Path) -> None:+ caller = (+ "import http, { remote as r, svc } from '@/lib/http';\n"+ "export const a = () => http.get(`/users/${id}`);\n"+ "export const b = () => r.post('orders');\n"+ "export const c = () => svc.delete('/jobs/1');\n"+ )+ repo = _write(tmp_path, {"src/lib/http.ts": self._HTTP, "src/api/users.ts": caller})+ assert _calls(repo) == {+ ("axios", "GET", "/api/v2/users/{param}", ""),+ ("axios", "POST", "/orders", "API_URL"),+ ("axios", "DELETE", "/internal/jobs/1", ""),+ }++ def test_a_default_export_from_an_index_module(self, tmp_path: Path) -> None:+ index = "import ky from 'ky';\nexport default ky.create({ prefixUrl: '/api' });\n"+ caller = "import client from '../client';\nclient.get('things');\n"+ repo = _write(tmp_path, {"src/client/index.ts": index, "src/pages/p.ts": caller})+ assert _calls(repo) == {("ky", "GET", "/api/things", "")}++ def test_got_extend_ofetch_create_and_class_fields(self, tmp_path: Path) -> None:+ text = (+ "import got from 'got';\nimport { ofetch } from 'ofetch';\n"+ "const g = got.extend({ prefixUrl: 'https://billing.internal/v1' });\n"+ "const f = ofetch.create({ baseURL: '/api' });\n"+ "g.post('invoices');\nf('/carts', { method: 'DELETE' });\n"+ "class Svc {\n private http = axios.create({ baseURL: '/svc' });\n"+ " run() { return this.http.get('/run'); }\n}\n"+ )+ assert _calls(_write(tmp_path, {"a.ts": text})) == {+ ("got", "POST", "/v1/invoices", ""),+ ("ofetch", "DELETE", "/api/carts", ""),+ ("axios", "GET", "/svc/run", ""),+ }++ def test_an_instance_call_is_not_also_a_wrapper_call(self, tmp_path: Path) -> None:+ text = "import axios from 'axios';\nconst apiClient = axios.create({ baseURL: '/api' });\napiClient('/users');\n"+ assert _calls(_write(tmp_path, {"a.ts": text})) == {("axios", "GET", "/api/users", "")}++ def test_two_instances_exported_under_one_name_are_neither(self, tmp_path: Path) -> None:+ make = "import axios from 'axios';\nexport const api = axios.create({{ baseURL: '{}' }});\n"+ repo = _write(+ tmp_path,+ {+ "a/http.ts": make.format("/a"),+ "b/http.ts": make.format("/b"),+ "c.ts": "import { api } from './a/http';\napi.get('/users');\n",+ "d/client.ts": make.format("/d"),+ "e.ts": "import { api } from './d/client';\napi.get('/users');\n",+ },+ )+ assert _calls(repo) == {("axios", "GET", "/d/users", "")}++ def test_a_relative_path_without_a_base_and_non_calls_are_skipped(self, tmp_path: Path) -> None:+ text = (+ "import axios from 'axios';\nconst api = axios.create({ timeout: 5 });\n"+ "api.get('users');\napi.interceptors.request.use(fn);\naxios.defaults.baseURL = '/x';\n"+ "axios.get('/api/ok');\n"+ )+ assert _calls(_write(tmp_path, {"a.ts": text})) == {("axios", "GET", "/api/ok", "")}+++def test_an_instance_call_links_to_a_nest_controller(tmp_path: Path) -> None:+ api = _write(+ tmp_path / "api",+ {+ "src/main.ts": "app.setGlobalPrefix('api');\n",+ "src/users.controller.ts": (+ "import { Controller, Get } from '@nestjs/common';\n"+ "@Controller('users')\nexport class UsersController {\n @Get(':id')\n one() {}\n}\n"+ ),+ },+ )+ web = _write(+ tmp_path / "web",+ {+ "src/http.ts": "import axios from 'axios';\nexport const api = axios.create({ baseURL: '/api' });\n",+ "src/users.ts": "import { api } from './http';\napi.get(`/users/${id}`);\n",+ },+ )+ contracts = HttpExtractor().extract(api, "api") + HttpExtractor().extract(web, "web")+ links = {(link.provider_repo, link.consumer_repo, link.contract_id) for link in match_contracts(contracts)}+ assert links == {("api", "web", "http::GET::/api/users/{param}")}+++class TestReviewedEdges:+ _HTTP = "import axios from 'axios';\nexport default axios.create({ baseURL: '/api' });\nexport const client = axios.create({ baseURL: '/c' });\n"++ def test_package_imports_and_other_modules_are_not_instances(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "src/lib/http.ts": self._HTTP,+ "src/server.ts": "import http from 'http';\nimport { client } from './redis';\nhttp.get('/health');\nclient.get('/x');\n",+ "src/ok.ts": "import http from './lib/http';\nhttp.get('/users');\n",+ },+ )+ assert sorted(_calls(repo)) == [("axios", "GET", "/api/users", "")]++ def test_global_and_injected_axios(self, tmp_path: Path) -> None:+ text = "window.axios.get('/api/users');\nthis.$axios.get('/api/items');\nVue.axios.post('/api/v');\nfoo.axios.get('/nope');\n"+ assert _calls(_write(tmp_path, {"a.js": text})) == {+ ("axios", "GET", "/api/users", ""),+ ("axios", "GET", "/api/items", ""),+ ("axios", "POST", "/api/v", ""),+ }++ def test_dollar_and_fetch_named_instances_are_read_once(self, tmp_path: Path) -> None:+ text = (+ "import { ofetch } from 'ofetch';\nimport axios from 'axios';\n"+ "export const $api = ofetch.create({ baseURL: '/api' });\n"+ "const apifetch = ofetch.create({ baseURL: '/f' });\n"+ "const $http = axios.create({ baseURL: '/h' });\n"+ "$api('/users');\napifetch('/x');\n$http('/y');\n"+ )+ rows = [+ (c.meta["client"], c.meta["path"])+ for c in HttpExtractor().extract(_write(tmp_path, {"a.ts": text}), "web")+ if c.role == "consumer"+ ]+ assert sorted(rows) == [("axios", "/h/y"), ("ofetch", "/api/users"), ("ofetch", "/f/x")]++ def test_factories_each_library_has(self, tmp_path: Path) -> None:+ text = (+ "import axios from 'axios';\nimport ky from 'ky';\nimport got from 'got';\n"+ "const a = axios.extend({ baseURL: '/a' });\nconst g = got.create({ prefixUrl: '/g' });\n"+ "const k = ky.extend({ prefixUrl: '/k' });\n"+ "a.get('/1');\ng.get('2');\nk.get('3');\nk.request({ url: '/4' });\n"+ )+ assert _calls(_write(tmp_path, {"a.ts": text})) == {("ky", "GET", "/k/3", "")}++ def test_an_instance_extended_from_an_import_keeps_its_base(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "src/http.js": "const axios = require('axios');\nconst api = axios.create({ baseURL: '/api' });\nexport { api as default };\n",+ "src/b.ts": "import api from './http';\nconst slow = api.create({ timeout: 5 });\nslow.get('/users');\napi.get('https://ext.io/x');\n",+ },+ )+ assert _calls(repo) == {("axios", "GET", "/api/users", ""), ("axios", "GET", "/x", "")}++ def test_an_ofetch_instance_has_no_verb_methods(self, tmp_path: Path) -> None:+ text = "import { ofetch } from 'ofetch';\nconst f = ofetch.create({ baseURL: '/api' });\nf.get('/x');\nf('/y');\n"+ assert _calls(_write(tmp_path, {"a.ts": text})) == {("ofetch", "GET", "/api/y", "")}+++def test_a_base_in_the_calls_own_options_wins(tmp_path: Path) -> None:+ text = (+ "import axios from 'axios';\nconst api = axios.create({ baseURL: '/api' });\n"+ "axios.get<T>('/ui-settings', { baseURL: this.getBaseUrl() });\n"+ "api.post('/jobs', body, { baseURL: '/v2' });\napi.get('/users', { timeout: 5 });\n"+ )+ assert _calls(_write(tmp_path, {"a.ts": text})) == {+ ("axios", "GET", "/ui-settings", "getBaseUrl"),+ ("axios", "POST", "/v2/jobs", ""),+ ("axios", "GET", "/api/users", ""),+ }diff --git a/tests/unit/workspace/test_node_orm.py b/tests/unit/workspace/test_node_orm.pynew file mode 100644index 000000000..d7e56a37b--- /dev/null+++ b/tests/unit/workspace/test_node_orm.py@@ -0,0 +1,296 @@+"""Node ORM tables: Prisma, TypeORM, Sequelize, Drizzle and Knex.++Each library names a table explicitly or derives it from a model by its own+rule; the rows here pin both, and the refusals where a name cannot be read.+Rows are compared as sorted lists, so a table read twice shows up.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.ingestion.traverser import FileTraverser+from repowise.core.workspace.extractors.base import iter_source_files+from repowise.core.workspace.extractors.data import DataExtractor+from repowise.core.workspace.matching import match_contracts+++def _write(repo: Path, files: dict[str, str]) -> Path:+ for rel, text in files.items():+ path = repo / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return repo+++def _rows(repo: Path, framework: str) -> list[tuple[str, str, str]]:+ """``(role, table, schema-or-verb)`` for *framework*'s rows, sorted."""+ return sorted(+ (c.role, c.meta["table"], c.meta.get("schema") or c.meta.get("verb") or "")+ for c in DataExtractor().extract(repo, "app")+ if c.meta.get("framework", c.meta.get("client")) == framework+ )+++def _tables(repo: Path, framework: str) -> list[str]:+ return [table for _role, table, _ in _rows(repo, framework)]+++def _links(*repos: tuple[Path, str]) -> set[tuple[str, str, str]]:+ contracts = [c for path, alias in repos for c in DataExtractor().extract(path, alias)]+ return {(lk.provider_repo, lk.consumer_repo, lk.contract_id) for lk in match_contracts(contracts)}+++class TestPrisma:+ _SCHEMA = """// Don't edit: generated by hand+datasource db {+ provider = "postgresql"+ schemas = ["public", "billing"]+}++model User {+ id Int @id @default(autoincrement())+ teamId Int @map("team_id")+ site String @default("https://x.io//a")+ posts Post[]+ // @@map("legacy_users")+}++model Post {+ id Int @id+ @@map("blog_posts")+}++model Invoice {+ id Int @id+ @@map(name: "invoices")+ @@schema("billing")+}++view Summary {+ id Int @unique+}++type Address {+ street String+}++enum Role {+ ADMIN+}+"""++ def test_models_maps_and_schemas(self, tmp_path: Path) -> None:+ repo = _write(tmp_path, {"prisma/schema.prisma": self._SCHEMA})+ assert _rows(repo, "prisma") == [+ ("provider", "billing.invoices", ""),+ ("provider", "blog_posts", ""),+ ("provider", "user", ""),+ ]++ def test_the_contract_walk_reads_a_file_the_index_skips(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "prisma/schema.prisma": self._SCHEMA,+ "notes.txt": "x",+ ".gitignore": "generated/\n",+ "generated/client/schema.prisma": self._SCHEMA,+ },+ )+ assert [info.path for info in FileTraverser(repo).traverse()] == []+ walked = [rel for rel, _, _ in iter_source_files(repo, frozenset({".prisma"}))]+ assert walked == ["prisma/schema.prisma"]+++class TestTypeOrm:+ def test_names_options_and_the_snake_case_default(self, tmp_path: Path) -> None:+ text = (+ "import { Entity, ViewEntity, ChildEntity } from 'typeorm';\n"+ "const TABLE = 'accounts';\n"+ "@Entity()\nexport class PhotoMetadata {}\n"+ "@Entity()\nexport class APIKey {}\n"+ "@Entity('users')\nexport class User {}\n"+ "@Entity({ name: 'orders', schema: 'sales' })\nexport class Order {}\n"+ "@Entity(TABLE, { schema: 'auth' })\nexport class Account {}\n"+ "@Entity({ schema: 'audit' })\nexport class AuditLog {}\n"+ "@ViewEntity({ name: 'totals' })\nexport class Totals {}\n"+ "@ChildEntity()\nexport class Admin extends User {}\n"+ "@Entity(config.name)\nexport class Unknown {}\n"+ "@Entity('ledger', { schema: SCHEMA })\nexport class Ledger {}\n"+ "// @Entity('old_things')\n@Entity('things')\nexport class Thing {}\n"+ )+ repo = _write(tmp_path, {"src/entities.ts": text})+ assert _tables(repo, "typeorm") == [+ "api_key",+ "audit.audit_log",+ "auth.accounts",+ "photo_metadata",+ "sales.orders",+ "things",+ "users",+ ]++ def test_another_librarys_entity_decorator_is_not_read(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "b.ts": "import { Entity } from '@mikro-orm/core';\n@Entity()\nexport class Book {}\n",+ "c.ts": "import { Entity } from 'typeorm';\n@Entity()\nexport class Cover {}\n",+ },+ )+ assert _tables(repo, "typeorm") == ["cover"]+++class TestSequelize:+ def test_define_and_init(self, tmp_path: Path) -> None:+ text = (+ "const { Sequelize, Model, DataTypes } = require('sequelize');\n"+ "const sequelize = new Sequelize('sqlite::memory:');\n"+ "const db = new Sequelize(url);\n"+ "sequelize.define('Category', {});\n"+ "sequelize.define('Tag', {}, { tableName: 'labels' });\n"+ "db.define('Person', {}, { freezeTableName: true });\n"+ "sequelize.define('OrderLine', {}, { underscored: true });\n"+ "sequelize.define('UserProfile', {}, { freezeTableName: true, underscored: true });\n"+ "sequelize.define('users', {});\n"+ "sequelize.define('Secret', {}, { tableName: config.table });\n"+ "customElements.define('app-root', AppRoot);\n"+ "class Project extends Model {}\n"+ "Project.init({}, { sequelize, modelName: 'workItem' });\n"+ "class Task extends Model {}\n"+ "Task.init({}, { sequelize: db });\n"+ "class Member extends Model {\n"+ " static init(s) { return super.init({}, { sequelize: s }); }\n}\n"+ "Chart.init(el, { theme: 'dark' });\n"+ )+ assert _tables(_write(tmp_path, {"models.js": text}), "sequelize") == [+ "categories",+ "labels",+ "members",+ "order_lines",+ "person",+ "tasks",+ "userprofile",+ "users",+ "workitems",+ ]++ def test_sequelize_typescript_tables(self, tmp_path: Path) -> None:+ text = (+ "import { Column, Model, Table } from 'sequelize-typescript';\n"+ "@Table\nexport class User extends Model {}\n"+ "@Table({ tableName: 'pets', timestamps: false })\nexport class Dog extends Model {}\n"+ "// @Table({ tableName: 'gone' })\n"+ )+ assert _tables(_write(tmp_path, {"m.ts": text}), "sequelize") == ["pets", "users"]+++class TestDrizzle:+ def test_tables_and_schema_tables(self, tmp_path: Path) -> None:+ text = (+ "import { pgTable, pgSchema, pgTableCreator, serial } from 'drizzle-orm/pg-core';\n"+ "const USERS = 'users';\n"+ "export const users = pgTable(USERS, { id: serial('id') });\n"+ "export const auth = pgSchema('auth');\n"+ "export const sessions = auth.table('sessions', {});\n"+ "export const t = mysqlTable('things', {});\n"+ "export const k = sqliteTable(`kv`, {});\n"+ "export const s = singlestoreTable('events', {});\n"+ "export const x = pgTable(name, {});\n"+ "const createTable = pgTableCreator((n) => `app_${n}`);\n"+ "export const p = createTable('posts', {});\n"+ "export const q = mySchema.table('nope', {});\n"+ )+ assert _tables(_write(tmp_path, {"schema.ts": text}), "drizzle") == [+ "auth.sessions",+ "events",+ "kv",+ "things",+ "users",+ ]++ def test_without_the_import_nothing_is_read(self, tmp_path: Path) -> None:+ repo = _write(+ tmp_path,+ {+ "a.ts": "pgTable('users', {});\n",+ "b.ts": "import { pgTable } from 'drizzle-orm/pg-core';\npgTable('teams', {});\n",+ },+ )+ assert _tables(repo, "drizzle") == ["teams"]+++class TestKnex:+ def test_migrations_create_and_alter(self, tmp_path: Path) -> None:+ text = (+ "exports.up = async function (knex) {\n"+ " await knex.schema.createTable('todos', (t) => { t.increments(); });\n"+ " await knex.schema.createTableIfNotExists('tags', (t) => {});\n"+ " await knex.schema.withSchema('audit').createTable('events', (t) => {});\n"+ " await knex.schema.withSchema(SCHEMA).createTable('hidden', (t) => {});\n"+ " await knex.schema.alterTable('users', (t) => {});\n"+ " await knex.schema.table('orders', (t) => {});\n"+ "};\n"+ )+ assert _rows(_write(tmp_path, {"migrations/1_init.js": text}), "knex") == [+ ("provider", "audit.events", "create"),+ ("provider", "orders", "alter"),+ ("provider", "tags", "create"),+ ("provider", "todos", "create"),+ ("provider", "users", "alter"),+ ]++ def test_queries_and_their_verbs(self, tmp_path: Path) -> None:+ text = (+ "import knex from 'knex';\n"+ "const db = knex({ client: 'pg' });\n"+ "const pg = require('knex')(config);\n"+ "await db('todos').where({ id }).first();\n"+ "await db('todos').where({ done: true });\n"+ "await db('todos').insert(row);\n"+ "await knex('users as u').where('u.id', id).update({ name });\n"+ "await this.knex('sessions').where({ id }).del();\n"+ "await knex.select('id').from('orders');\n"+ "await knex.from('audit.events');\n"+ "await pg.into('logs').insert(entry);\n"+ "await db.count('*').from('carts');\n"+ "await other('nope');\n"+ "await supabase.from('profiles');\n"+ "await mydb('nope');\n"+ )+ assert _rows(_write(tmp_path, {"repo.ts": text}), "knex") == [+ ("consumer", "audit.events", "select"),+ ("consumer", "carts", "select"),+ ("consumer", "logs", "insert"),+ ("consumer", "orders", "select"),+ ("consumer", "sessions", "delete"),+ ("consumer", "todos", "insert"),+ ("consumer", "todos", "select"),+ ("consumer", "users", "update"),+ ]+++def test_a_knex_query_links_to_a_prisma_model(tmp_path: Path) -> None:+ owner = _write(tmp_path / "api", {"prisma/schema.prisma": 'model Order {\n id Int @id\n @@map("orders")\n}\n'})+ reader = _write(tmp_path / "reports", {"q.ts": "import knex from 'knex';\nknex('orders').count();\n"})+ assert _links((owner, "api"), (reader, "reports")) == {("api", "reports", "data::orders")}+++def test_a_knex_migration_owns_the_table_other_services_model(tmp_path: Path) -> None:+ owner = _write(+ tmp_path / "api",+ {"migrations/1.js": "exports.up = (knex) => knex.schema.createTable('invoices', (t) => {});\n"},+ )+ model = _write(+ tmp_path / "billing",+ {"e.ts": "import { Entity } from 'typeorm';\n@Entity('invoices')\nexport class Invoice {}\n"},+ )+ alter_only = _write(+ tmp_path / "ops",+ {"migrations/2.js": "exports.up = (knex) => knex.schema.alterTable('invoices', (t) => {});\n"},+ )+ links = _links((owner, "api"), (model, "billing"), (alter_only, "ops"))+ # Two services define the table's schema (a create and an alter), so no one owner.+ assert links == set()+ assert _links((owner, "api"), (model, "billing")) == {("api", "billing", "data::invoices")}