feat(introspect): routes, tokens and --json, over one query layer an MCP server can reuse #18
No files matched your search
@@ -9,6 +9,25 @@ green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8
|
|||||||
mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold
|
mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold
|
||||||
is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved.
|
is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`matcha routes` and `matcha tokens`.** `routes` lists every route with its transport and chain.
|
||||||
|
`tokens` lists every token, with who provides it and who needs it, handlers included. It is
|
||||||
|
the check to run before writing `@needs('x')`.
|
||||||
|
- **`--json` on `explain`, `routes` and `tokens`** (`graph --format json` already had it). It
|
||||||
|
prints one JSON document on stdout, so an agent inspecting an app reads the graph instead of
|
||||||
|
guessing it. A refused query (an unknown pattern) prints a structured error on stderr and
|
||||||
|
exits 1.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Introspection runs through one query layer (`src/introspect.rs`): every command asks one
|
||||||
|
question and gets one JSON document back, then renders it as text unless `--json` is passed.
|
||||||
|
Text output is unchanged. The layer is also the seam a future `matcha mcp` would serve over
|
||||||
|
MCP. It adds `serde_json` as a dependency.
|
||||||
|
|
||||||
## [26.9.0-beta.1] - 2026-09-24
|
## [26.9.0-beta.1] - 2026-09-24
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
Generated
+35
@@ -240,6 +240,12 @@ version = "1.70.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.186"
|
version = "0.2.186"
|
||||||
@@ -260,6 +266,7 @@ dependencies = [
|
|||||||
"clap",
|
"clap",
|
||||||
"include_dir",
|
"include_dir",
|
||||||
"predicates",
|
"predicates",
|
||||||
|
"serde_json",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tree-sitter",
|
"tree-sitter",
|
||||||
"tree-sitter-typescript",
|
"tree-sitter-typescript",
|
||||||
@@ -394,6 +401,15 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.228"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_core"
|
name = "serde_core"
|
||||||
version = "1.0.228"
|
version = "1.0.228"
|
||||||
@@ -414,6 +430,19 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_json"
|
||||||
|
version = "1.0.154"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||||
|
dependencies = [
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"zmij",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
@@ -511,3 +540,9 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zmij"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
@@ -15,6 +15,7 @@ path = "src/main.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
include_dir = "0.7"
|
include_dir = "0.7"
|
||||||
|
serde_json = "1"
|
||||||
tree-sitter = "0.22"
|
tree-sitter = "0.22"
|
||||||
tree-sitter-typescript = "0.21"
|
tree-sitter-typescript = "0.21"
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ matcha create plugin "Plugin Algo" # an in-app plugin, or --package for
|
|||||||
matcha add sse # add a capability to your controller
|
matcha add sse # add a capability to your controller
|
||||||
matcha graph # draw the dependency graph
|
matcha graph # draw the dependency graph
|
||||||
matcha explain /users/:id # one route's chain, in execution order
|
matcha explain /users/:id # one route's chain, in execution order
|
||||||
|
matcha routes # every route and the chain it runs
|
||||||
|
matcha tokens # every token: who provides it, who needs it
|
||||||
matcha openapi # structural OpenAPI 3.1 for the route table
|
matcha openapi # structural OpenAPI 3.1 for the route table
|
||||||
matcha doctor # check the project for confusing misconfigurations
|
matcha doctor # check the project for confusing misconfigurations
|
||||||
```
|
```
|
||||||
@@ -75,6 +77,9 @@ matcha graph --format dot # Graphviz
|
|||||||
matcha graph --format json # the raw GraphView
|
matcha graph --format json # the raw GraphView
|
||||||
matcha graph --out docs/graph.mmd # to a file instead of stdout
|
matcha graph --out docs/graph.mmd # to a file instead of stdout
|
||||||
matcha explain /users/:id # providers → steps → handler, with needs/provides
|
matcha explain /users/:id # providers → steps → handler, with needs/provides
|
||||||
|
matcha routes # every route: method, pattern, transport, chain
|
||||||
|
matcha tokens # every token, who provides it, who needs it
|
||||||
|
matcha explain /users/:id --json # any of explain/routes/tokens as JSON, for a program or an agent
|
||||||
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
|
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -90,6 +95,17 @@ be installed, since this runs your code under your runtime.
|
|||||||
`explain` takes the route **pattern** as declared, not a concrete URL:
|
`explain` takes the route **pattern** as declared, not a concrete URL:
|
||||||
`/users/:id`, not `/users/42`. A miss lists the patterns that are registered.
|
`/users/:id`, not `/users/42`. A miss lists the patterns that are registered.
|
||||||
|
|
||||||
|
`tokens` answers the question to ask before writing `@needs('x')`: does anything
|
||||||
|
provide `x`, and who else depends on it? A token nothing provides is listed with
|
||||||
|
`— (nothing provides it)`, which is the boot error you are about to get.
|
||||||
|
|
||||||
|
**For agents.** `--json` prints the same data the text is rendered from: exactly
|
||||||
|
one JSON document on stdout, so a program parses stdout and nothing else. When a
|
||||||
|
query is refused (an unknown route pattern), stderr carries
|
||||||
|
`{"error": {"code", "message", …}}` and the exit code is 1. Every query is one
|
||||||
|
self-contained document, so the same set can later be served over MCP without a
|
||||||
|
second implementation.
|
||||||
|
|
||||||
### `add` capabilities
|
### `add` capabilities
|
||||||
|
|
||||||
| | generates |
|
| | generates |
|
||||||
|
|||||||
+23
@@ -80,6 +80,29 @@ pub enum Command {
|
|||||||
entry: Option<String>,
|
entry: Option<String>,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
out: Option<String>,
|
out: Option<String>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
|
},
|
||||||
|
/// List every route, its transport, and the chain it runs
|
||||||
|
Routes {
|
||||||
|
#[arg(long)]
|
||||||
|
entry: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
out: Option<String>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
|
},
|
||||||
|
/// List every token: who provides it and who needs it
|
||||||
|
Tokens {
|
||||||
|
#[arg(long)]
|
||||||
|
entry: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
out: Option<String>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
},
|
},
|
||||||
/// Add a capability to a controller
|
/// Add a capability to a controller
|
||||||
Add {
|
Add {
|
||||||
|
|||||||
+227
-209
@@ -1,41 +1,36 @@
|
|||||||
//! `matcha graph` and `matcha explain <pattern>` — introspection of the
|
//! `matcha graph`, `routes`, `tokens`, `explain` and `openapi`: the CLI over
|
||||||
//! dependency graph the framework builds from `needs`/`provides`.
|
//! [`crate::introspect`].
|
||||||
//!
|
//!
|
||||||
//! Both work the same way: write a short script next to the project, import its
|
//! Each command asks one [`Query`] and renders the JSON that comes back, as
|
||||||
//! entry file, `await app.ready()`, print, delete the script. `ready()` is the
|
//! text for a person or, with `--json`, unchanged for a program. An agent
|
||||||
//! reason this is cheap and safe to run — it resolves the graph and is
|
//! inspecting an app uses the second form; the future `matcha mcp` serves the
|
||||||
//! documented as deliberately *not* running provider factories, so drawing a
|
//! same documents without going through this file at all.
|
||||||
//! diagram does not open your database connections. It is also required rather
|
|
||||||
//! than optional: on a mesh app the graph is not knowable until its teapots
|
|
||||||
//! have been asked, and `graph()`/`explain()` throw until then.
|
|
||||||
//!
|
|
||||||
//! The formatting lives in the generated script rather than here on purpose.
|
|
||||||
//! Rust would have to parse the JSON back to lay out a chain, and nothing about
|
|
||||||
//! that layout needs Rust — `console.log` already has the values.
|
|
||||||
|
|
||||||
use std::io::{Error, ErrorKind};
|
use std::io::{Error, ErrorKind};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
|
|
||||||
use crate::entry;
|
use serde_json::Value;
|
||||||
use crate::runtime::{self, Runtime};
|
|
||||||
|
|
||||||
/// Written into the project root so the runtime resolves `@green-tea/core` from
|
use crate::introspect::{self, Diagram, Query, Refusal, Target};
|
||||||
/// the project's own `node_modules`/import map, then removed. Dotted so it is
|
|
||||||
/// invisible to a `src/**` glob if a run dies before cleanup.
|
/// How a command prints its answer.
|
||||||
const SCRIPT_NAME: &str = ".matcha-introspect.ts";
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
pub enum Render {
|
||||||
|
Text,
|
||||||
|
Json,
|
||||||
|
}
|
||||||
|
|
||||||
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
|
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
|
||||||
pub fn graph(
|
pub fn graph(
|
||||||
dir: &Path,
|
dir: &Path,
|
||||||
format: &str,
|
format: &str,
|
||||||
entry_override: Option<&str>,
|
entry: Option<&str>,
|
||||||
out: Option<&str>,
|
out: Option<&str>,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
let print = match format {
|
let (query, render) = match format {
|
||||||
"mermaid" => "console.log(app.toMermaid());",
|
"mermaid" => (Query::Diagram(Diagram::Mermaid), Render::Text),
|
||||||
"dot" => "console.log(app.toDOT());",
|
"dot" => (Query::Diagram(Diagram::Dot), Render::Text),
|
||||||
"json" => "console.log(JSON.stringify(app.graph(), null, 2));",
|
"json" => (Query::Graph, Render::Json),
|
||||||
other => {
|
other => {
|
||||||
return Err(Error::new(
|
return Err(Error::new(
|
||||||
ErrorKind::InvalidInput,
|
ErrorKind::InvalidInput,
|
||||||
@@ -43,42 +38,54 @@ pub fn graph(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
emit(dir, entry_override, out, print)
|
answer(dir, entry, out, &query, render, |data| {
|
||||||
|
data.as_str().unwrap_or_default().to_string()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha routes` — every route, its transport, and the chain it runs.
|
||||||
|
pub fn routes(
|
||||||
|
dir: &Path,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
answer(dir, entry, out, &Query::Routes, render, routes_text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha tokens` — every token, who provides it and who needs it. The
|
||||||
|
/// question to ask before writing `@needs('x')`: does anything provide `x`?
|
||||||
|
pub fn tokens(
|
||||||
|
dir: &Path,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
answer(dir, entry, out, &Query::Tokens, render, tokens_text)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `matcha explain <pattern>` — one route's chain, in execution order, with
|
/// `matcha explain <pattern>` — one route's chain, in execution order, with
|
||||||
/// each node's needs and provides.
|
/// each node's needs and provides.
|
||||||
///
|
///
|
||||||
/// The argument is the route *pattern* as declared (`/users/:id`), not a
|
/// The argument is the route *pattern* as declared (`/users/:id`), not a
|
||||||
/// concrete URL: `explainRoute` matches the pattern string exactly. A miss
|
/// concrete URL: `explain` matches the pattern string exactly. A miss lists
|
||||||
/// therefore lists what is actually registered, which is the only useful thing
|
/// what is actually registered, which is the only useful thing to say to
|
||||||
/// to say to someone who just guessed wrong.
|
/// someone who just guessed wrong.
|
||||||
pub fn explain(
|
pub fn explain(
|
||||||
dir: &Path,
|
dir: &Path,
|
||||||
route: &str,
|
route: &str,
|
||||||
entry_override: Option<&str>,
|
entry: Option<&str>,
|
||||||
out: Option<&str>,
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
let route = js_string(route);
|
answer(
|
||||||
let body = format!(
|
dir,
|
||||||
r#"let explained;
|
entry,
|
||||||
try {{
|
out,
|
||||||
explained = app.explain({route});
|
&Query::Explain(route.to_string()),
|
||||||
}} catch {{
|
render,
|
||||||
const patterns = app.graph().routes.map((r) => ` ${{r.method.padEnd(6)}} ${{r.pattern}}`);
|
explain_text,
|
||||||
console.error(`no route matching pattern {route}\n\nregistered patterns:\n${{patterns.join('\n')}}`);
|
)
|
||||||
process.exit(1);
|
|
||||||
}}
|
|
||||||
const lines = [`${{explained.method}} ${{explained.pattern}} [${{explained.transport}}]`];
|
|
||||||
const width = Math.max(...explained.chain.map((n) => n.kind.length));
|
|
||||||
for (const node of explained.chain) {{
|
|
||||||
const needs = node.needs.length ? ` needs: ${{node.needs.join(', ')}}` : '';
|
|
||||||
const provides = node.provides.length ? ` provides: ${{node.provides.join(', ')}}` : '';
|
|
||||||
lines.push(` ${{node.kind.padEnd(width)}} ${{node.name}}${{needs}}${{provides}} (${{node.origin}})`);
|
|
||||||
}}
|
|
||||||
console.log(lines.join('\n'));"#
|
|
||||||
);
|
|
||||||
emit(dir, entry_override, out, &body)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `matcha openapi` — the structural OpenAPI 3.1 document for the route table.
|
/// `matcha openapi` — the structural OpenAPI 3.1 document for the route table.
|
||||||
@@ -91,198 +98,176 @@ pub fn openapi(
|
|||||||
dir: &Path,
|
dir: &Path,
|
||||||
title: Option<&str>,
|
title: Option<&str>,
|
||||||
version: Option<&str>,
|
version: Option<&str>,
|
||||||
entry_override: Option<&str>,
|
entry: Option<&str>,
|
||||||
out: Option<&str>,
|
out: Option<&str>,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
// `app.openapi()` takes an optional info object; passing nothing lets core
|
let query = Query::OpenApi {
|
||||||
// apply its own defaults rather than having the CLI invent a title.
|
title: title.map(str::to_string),
|
||||||
let info = match (title, version) {
|
version: version.map(str::to_string),
|
||||||
(None, None) => String::new(),
|
|
||||||
(t, v) => {
|
|
||||||
let mut fields = Vec::new();
|
|
||||||
if let Some(t) = t {
|
|
||||||
fields.push(format!("title: {}", js_string(t)));
|
|
||||||
}
|
|
||||||
if let Some(v) = v {
|
|
||||||
fields.push(format!("version: {}", js_string(v)));
|
|
||||||
}
|
|
||||||
format!("{{ {} }}", fields.join(", "))
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
emit(
|
answer(dir, entry, out, &query, Render::Json, |_| String::new())
|
||||||
dir,
|
|
||||||
entry_override,
|
|
||||||
out,
|
|
||||||
&format!("console.log(JSON.stringify(app.openapi({info}), null, 2));"),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves the entry, generates the script around `body`, runs it under the
|
/// Asks, renders, and writes to `out` or stdout. A refusal goes to stderr — as
|
||||||
/// detected runtime, and routes its stdout to a file or to ours.
|
/// JSON under `--json`, so a program reads the same shape either way — and
|
||||||
fn emit(
|
/// exits 1. A failed run has already printed its own diagnosis (the child's
|
||||||
|
/// stderr is inherited), so it exits with no second message on top.
|
||||||
|
fn answer(
|
||||||
dir: &Path,
|
dir: &Path,
|
||||||
entry_override: Option<&str>,
|
entry: Option<&str>,
|
||||||
out: Option<&str>,
|
out: Option<&str>,
|
||||||
body: &str,
|
query: &Query,
|
||||||
|
render: Render,
|
||||||
|
text: impl Fn(&Value) -> String,
|
||||||
) -> std::io::Result<()> {
|
) -> std::io::Result<()> {
|
||||||
let entry_path = match entry_override {
|
let target = Target { dir, entry };
|
||||||
Some(explicit) => {
|
let data = match introspect::query(&target, query) {
|
||||||
let p = dir.join(explicit);
|
Ok(Ok(data)) => data,
|
||||||
if !p.exists() {
|
Ok(Err(refusal)) => {
|
||||||
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
|
report_refusal(&refusal, render);
|
||||||
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
PathBuf::from(explicit)
|
Err(e) if e.kind() == ErrorKind::Other => std::process::exit(1),
|
||||||
}
|
Err(e) => return Err(e),
|
||||||
None => entry::find(dir).map(|p| p.strip_prefix(dir).unwrap_or(&p).to_path_buf()).ok_or_else(|| {
|
|
||||||
Error::new(
|
|
||||||
ErrorKind::NotFound,
|
|
||||||
format!(
|
|
||||||
"no {} found — pass --entry <file>. It must export the app: `export const app = createApp(...)`",
|
|
||||||
entry::candidates()
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})?,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let rt = runtime::detect(dir).ok_or_else(|| {
|
let mut printed = match render {
|
||||||
Error::new(
|
Render::Json => serde_json::to_string_pretty(&data).map_err(Error::other)?,
|
||||||
ErrorKind::NotFound,
|
Render::Text => text(&data),
|
||||||
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
};
|
||||||
)
|
if !printed.ends_with('\n') {
|
||||||
})?;
|
printed.push('\n');
|
||||||
|
|
||||||
let script_path = dir.join(SCRIPT_NAME);
|
|
||||||
std::fs::write(&script_path, script(&entry_path, body))?;
|
|
||||||
let result = run(rt, dir, SCRIPT_NAME);
|
|
||||||
std::fs::remove_file(&script_path).ok();
|
|
||||||
|
|
||||||
let output = result?;
|
|
||||||
// The child has already written its own diagnosis to the inherited stderr —
|
|
||||||
// a type error, a boot failure, or the script's own "no route matching
|
|
||||||
// pattern" with the registered ones listed. Wrapping that in a second
|
|
||||||
// `error: npx exited with 1` adds a line and no information, so the exit
|
|
||||||
// code is relayed and nothing is said on top of it.
|
|
||||||
if !output.status.success() {
|
|
||||||
std::process::exit(output.status.code().unwrap_or(1));
|
|
||||||
}
|
}
|
||||||
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
|
||||||
match out {
|
match out {
|
||||||
Some(file) => {
|
Some(file) => {
|
||||||
std::fs::write(dir.join(file), &stdout)?;
|
std::fs::write(dir.join(file), &printed)?;
|
||||||
println!("✓ {file}");
|
println!("✓ {file}");
|
||||||
}
|
}
|
||||||
None => print!("{stdout}"),
|
None => print!("{printed}"),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The generated script: import the app, resolve the graph, run `body`.
|
fn report_refusal(refusal: &Refusal, render: Render) {
|
||||||
fn script(entry_path: &Path, body: &str) -> String {
|
if render == Render::Json {
|
||||||
|
eprintln!("{}", serde_json::json!({ "error": refusal.0 }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eprintln!("{}", refusal.message());
|
||||||
|
if let Some(registered) = refusal.0["registered"].as_array() {
|
||||||
|
eprintln!("\nregistered patterns:");
|
||||||
|
for r in registered {
|
||||||
|
eprintln!(" {:<6} {}", str_of(&r["method"]), str_of(&r["pattern"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn str_of(v: &Value) -> &str {
|
||||||
|
v.as_str().unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_of(v: &Value) -> Vec<&str> {
|
||||||
|
v.as_array()
|
||||||
|
.map(|a| a.iter().map(str_of).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn routes_text(data: &Value) -> String {
|
||||||
|
let routes = data.as_array().cloned().unwrap_or_default();
|
||||||
|
let width = routes
|
||||||
|
.iter()
|
||||||
|
.map(|r| str_of(&r["method"]).len())
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
routes
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
let chain = list_of(&r["chain"]).join(" → ");
|
||||||
format!(
|
format!(
|
||||||
"// generated by matcha; safe to delete\nimport {{ app }} from {};\n\nif (!app) {{\n console.error('{} does not export `app` — matcha needs `export const app = createApp(...)`');\n process.exit(1);\n}}\nawait app.ready();\n{body}\n",
|
"{:<width$} {} [{}] {}",
|
||||||
js_string(&specifier(entry_path)),
|
str_of(&r["method"]),
|
||||||
entry_path.display(),
|
str_of(&r["pattern"]),
|
||||||
|
str_of(&r["transport"]),
|
||||||
|
chain
|
||||||
)
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `script` under `rt` in `dir`. The child's stderr is inherited rather
|
fn tokens_text(data: &Value) -> String {
|
||||||
/// than captured: a type error or a boot failure is the reason someone runs
|
let names = |v: &Value| {
|
||||||
/// this, and it should reach them as it happens.
|
v.as_array()
|
||||||
fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::Output> {
|
.map(|a| {
|
||||||
let (prog, args) = runner(rt, script);
|
a.iter()
|
||||||
let child = Command::new(prog)
|
.map(|n| match n["route"].as_str() {
|
||||||
.args(&args)
|
Some(route) => format!("{} ({route})", str_of(&n["name"])),
|
||||||
.current_dir(dir)
|
None => str_of(&n["name"]).to_string(),
|
||||||
.stdout(Stdio::piped())
|
})
|
||||||
.stderr(Stdio::inherit())
|
.collect::<Vec<_>>()
|
||||||
.spawn()
|
.join(", ")
|
||||||
.map_err(|e| Error::new(e.kind(), format!("could not run {prog}: {e}")))?;
|
})
|
||||||
child.wait_with_output()
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
data.as_array()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
let provided = names(&t["providedBy"]);
|
||||||
|
let needed = names(&t["neededBy"]);
|
||||||
|
format!(
|
||||||
|
"{}\n provided by: {}\n needed by: {}",
|
||||||
|
str_of(&t["token"]),
|
||||||
|
if provided.is_empty() {
|
||||||
|
if t["source"] == "request" {
|
||||||
|
"the request (built in)"
|
||||||
|
} else {
|
||||||
|
"— (nothing provides it)"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
&provided
|
||||||
|
},
|
||||||
|
if needed.is_empty() { "—" } else { &needed },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
|
fn explain_text(data: &Value) -> String {
|
||||||
let s = script.to_string();
|
let chain = data["chain"].as_array().cloned().unwrap_or_default();
|
||||||
match rt {
|
let width = chain
|
||||||
// Edge resolves its graph under node: `src/app.ts` imports core, never
|
.iter()
|
||||||
// `edgeHandler`, so nothing here needs workerd — and workerd could not
|
.map(|n| str_of(&n["kind"]).len())
|
||||||
// print to a terminal anyway.
|
.max()
|
||||||
Runtime::Node | Runtime::Edge => ("npx", vec!["tsx".into(), s]),
|
.unwrap_or(0);
|
||||||
// `ready()` opens no provider connections, but a mesh app does reach its
|
let mut lines = vec![format!(
|
||||||
// teapots there, so net is part of resolving the graph rather than extra.
|
"{} {} [{}]",
|
||||||
Runtime::Deno => (
|
str_of(&data["method"]),
|
||||||
"deno",
|
str_of(&data["pattern"]),
|
||||||
vec![
|
str_of(&data["transport"])
|
||||||
"run".into(),
|
)];
|
||||||
"--allow-read".into(),
|
for n in &chain {
|
||||||
"--allow-env".into(),
|
let needs = list_of(&n["needs"]);
|
||||||
"--allow-net".into(),
|
let provides = list_of(&n["provides"]);
|
||||||
s,
|
let mut line = format!(" {:<width$} {}", str_of(&n["kind"]), str_of(&n["name"]));
|
||||||
],
|
if !needs.is_empty() {
|
||||||
),
|
line.push_str(&format!(" needs: {}", needs.join(", ")));
|
||||||
Runtime::Bun => ("bun", vec!["run".into(), s]),
|
|
||||||
}
|
}
|
||||||
|
if !provides.is_empty() {
|
||||||
|
line.push_str(&format!(" provides: {}", provides.join(", ")));
|
||||||
}
|
}
|
||||||
|
line.push_str(&format!(" ({})", str_of(&n["origin"])));
|
||||||
/// A project-root-relative path as an ES module specifier: forward slashes,
|
lines.push(line);
|
||||||
/// always `./`-prefixed, extension kept so Deno resolves it without leaning on
|
|
||||||
/// `sloppy-imports`.
|
|
||||||
fn specifier(path: &Path) -> String {
|
|
||||||
let raw = path.to_string_lossy().replace('\\', "/");
|
|
||||||
format!("./{}", raw.strip_prefix("./").unwrap_or(&raw))
|
|
||||||
}
|
}
|
||||||
|
lines.join("\n")
|
||||||
/// Single-quoted JS string literal. Route patterns reach this from argv, so the
|
|
||||||
/// quote and the backslash have to be escaped rather than assumed absent.
|
|
||||||
fn js_string(value: &str) -> String {
|
|
||||||
let mut out = String::with_capacity(value.len() + 2);
|
|
||||||
out.push('\'');
|
|
||||||
for ch in value.chars() {
|
|
||||||
match ch {
|
|
||||||
'\\' => out.push_str("\\\\"),
|
|
||||||
'\'' => out.push_str("\\'"),
|
|
||||||
'\n' => out.push_str("\\n"),
|
|
||||||
'\r' => out.push_str("\\r"),
|
|
||||||
_ => out.push(ch),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.push('\'');
|
|
||||||
out
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
#[test]
|
|
||||||
fn specifier_is_dot_slash_prefixed_with_extension() {
|
|
||||||
assert_eq!(specifier(Path::new("src/app.ts")), "./src/app.ts");
|
|
||||||
assert_eq!(specifier(Path::new("./src/app.ts")), "./src/app.ts");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn js_string_escapes_quote_and_backslash() {
|
|
||||||
assert_eq!(js_string("a'b"), r"'a\'b'");
|
|
||||||
assert_eq!(js_string(r"a\b"), r"'a\\b'");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn script_imports_the_entry_and_awaits_ready() {
|
|
||||||
let out = script(Path::new("src/app.ts"), "console.log(1);");
|
|
||||||
assert!(out.contains("import { app } from './src/app.ts';"));
|
|
||||||
assert!(out.contains("await app.ready();"));
|
|
||||||
assert!(out.contains("console.log(1);"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn node_runs_through_tsx() {
|
|
||||||
assert_eq!(
|
|
||||||
runner(Runtime::Node, ".matcha-introspect.ts"),
|
|
||||||
(
|
|
||||||
"npx",
|
|
||||||
vec!["tsx".to_string(), ".matcha-introspect.ts".to_string()]
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn unknown_format_is_rejected() {
|
fn unknown_format_is_rejected() {
|
||||||
@@ -290,4 +275,37 @@ mod tests {
|
|||||||
let err = graph(d.path(), "svg", None, None).unwrap_err();
|
let err = graph(d.path(), "svg", None, None).unwrap_err();
|
||||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explain_text_keeps_the_layout_it_had() {
|
||||||
|
let data = json!({
|
||||||
|
"method": "GET", "pattern": "/users/:id", "transport": "http",
|
||||||
|
"chain": [
|
||||||
|
{ "kind": "provider", "name": "db", "needs": [], "provides": ["db"], "origin": "src/db.ts" },
|
||||||
|
{ "kind": "handler", "name": "Users.get", "needs": ["db"], "provides": [], "origin": "src/users.ts" }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
explain_text(&data),
|
||||||
|
"GET /users/:id [http]\n provider db provides: db (src/db.ts)\n handler Users.get needs: db (src/users.ts)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_text_names_the_request_for_its_built_in_tokens() {
|
||||||
|
let data = json!([{ "token": "req", "source": "request", "providedBy": [], "neededBy": [{ "kind": "step", "name": "user" }] }]);
|
||||||
|
assert_eq!(
|
||||||
|
tokens_text(&data),
|
||||||
|
"req\n provided by: the request (built in)\n needed by: user"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_text_says_when_nothing_provides_a_token() {
|
||||||
|
let data = json!([{ "token": "user", "providedBy": [], "neededBy": [{ "kind": "handler", "name": "Me.get", "route": "/me" }] }]);
|
||||||
|
assert_eq!(
|
||||||
|
tokens_text(&data),
|
||||||
|
"user\n provided by: — (nothing provides it)\n needed by: Me.get (/me)"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
//! Introspection queries against a project's app: one query in, one JSON
|
||||||
|
//! document out.
|
||||||
|
//!
|
||||||
|
//! This is the data layer under `matcha graph`, `routes`, `tokens`, `explain`
|
||||||
|
//! and `openapi`. The CLI renders what comes back, as text or with `--json` as
|
||||||
|
//! it is; a future `matcha mcp` serves the same documents as tools. Keeping the
|
||||||
|
//! JSON as the contract is what lets that server be a thin layer over
|
||||||
|
//! [`query`] rather than a second implementation, and it is why the human
|
||||||
|
//! formatting lives in Rust (`cmd_graph`) instead of in the generated script.
|
||||||
|
//!
|
||||||
|
//! How a query runs: write a short script next to the project, import its entry
|
||||||
|
//! file, `await app.ready()`, print one JSON envelope, delete the script.
|
||||||
|
//! `ready()` resolves the graph and is documented as *not* running provider
|
||||||
|
//! factories, so asking about the graph does not open database connections. It
|
||||||
|
//! is also required: on a mesh app the graph is not knowable until its teapots
|
||||||
|
//! have been asked, and `graph()`/`explain()` throw until then.
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::entry;
|
||||||
|
use crate::runtime::{self, Runtime};
|
||||||
|
|
||||||
|
/// Written into the project root so the runtime resolves `@green-tea/core` from
|
||||||
|
/// the project's own `node_modules`/import map, then removed. Dotted so it is
|
||||||
|
/// invisible to a `src/**` glob if a run dies before cleanup.
|
||||||
|
const SCRIPT_NAME: &str = ".matcha-introspect.ts";
|
||||||
|
|
||||||
|
/// What to ask the app. Each variant is one future MCP tool.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Query {
|
||||||
|
/// The whole graph as data: nodes and routes (`app.graph()`).
|
||||||
|
Graph,
|
||||||
|
/// The graph as a diagram string; `mermaid` or `dot`.
|
||||||
|
Diagram(Diagram),
|
||||||
|
/// Every route with its transport and the chain it runs.
|
||||||
|
Routes,
|
||||||
|
/// Every token: who provides it and who needs it.
|
||||||
|
Tokens,
|
||||||
|
/// One route's chain in execution order, by declared pattern.
|
||||||
|
Explain(String),
|
||||||
|
/// The structural OpenAPI 3.1 document.
|
||||||
|
OpenApi {
|
||||||
|
title: Option<String>,
|
||||||
|
version: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub enum Diagram {
|
||||||
|
Mermaid,
|
||||||
|
Dot,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A query the app answered with a refusal rather than data — a route pattern
|
||||||
|
/// that is not registered, say. Carried as JSON so a caller (a person, an agent,
|
||||||
|
/// an MCP client) gets the same machine-readable reason.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct Refusal(pub Value);
|
||||||
|
|
||||||
|
impl Refusal {
|
||||||
|
pub fn message(&self) -> &str {
|
||||||
|
self.0["message"].as_str().unwrap_or("query refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the app lives: the project directory and, optionally, an entry file
|
||||||
|
/// other than the default `src/app.ts` / `src/main.ts`.
|
||||||
|
pub struct Target<'a> {
|
||||||
|
pub dir: &'a Path,
|
||||||
|
pub entry: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `query` against the app in `target`. `Ok(Ok(data))` is the answer,
|
||||||
|
/// `Ok(Err(refusal))` is the app saying no in a structured way, and `Err` is
|
||||||
|
/// everything that stopped the question being asked — no entry, no runtime, a
|
||||||
|
/// type error or a failed boot. The child's stderr is inherited, so those reach
|
||||||
|
/// the terminal as they happen.
|
||||||
|
pub fn query(target: &Target, query: &Query) -> std::io::Result<Result<Value, Refusal>> {
|
||||||
|
let entry_path = resolve_entry(target)?;
|
||||||
|
let rt = runtime::detect(target.dir).ok_or_else(|| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let script_path = target.dir.join(SCRIPT_NAME);
|
||||||
|
std::fs::write(&script_path, script(&entry_path, &body(query)))?;
|
||||||
|
let result = run(rt, target.dir, SCRIPT_NAME);
|
||||||
|
std::fs::remove_file(&script_path).ok();
|
||||||
|
|
||||||
|
let output = result?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(Error::other(format!(
|
||||||
|
"the app could not be inspected (exit {})",
|
||||||
|
output.status.code().unwrap_or(1)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
parse_envelope(&String::from_utf8_lossy(&output.stdout))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The envelope is the script's last stdout line, so anything the app logs
|
||||||
|
/// while booting cannot be mistaken for the answer.
|
||||||
|
fn parse_envelope(stdout: &str) -> std::io::Result<Result<Value, Refusal>> {
|
||||||
|
let line = stdout
|
||||||
|
.lines()
|
||||||
|
.rev()
|
||||||
|
.find(|l| !l.trim().is_empty())
|
||||||
|
.unwrap_or("");
|
||||||
|
let envelope: Value = serde_json::from_str(line).map_err(|e| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
format!("the introspection script printed no answer ({e})"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
match envelope["ok"].as_bool() {
|
||||||
|
Some(true) => Ok(Ok(envelope["data"].clone())),
|
||||||
|
Some(false) => Ok(Err(Refusal(envelope["error"].clone()))),
|
||||||
|
None => Err(Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
"malformed introspection answer",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The JavaScript expression (or statements ending in `data = …`) that computes
|
||||||
|
/// the answer. Everything is plain data built from public `App` methods.
|
||||||
|
fn body(query: &Query) -> String {
|
||||||
|
match query {
|
||||||
|
Query::Graph => "data = app.graph();".into(),
|
||||||
|
Query::Diagram(Diagram::Mermaid) => "data = app.toMermaid();".into(),
|
||||||
|
Query::Diagram(Diagram::Dot) => "data = app.toDOT();".into(),
|
||||||
|
Query::Routes => "data = app.graph().routes;".into(),
|
||||||
|
Query::Tokens => TOKENS.into(),
|
||||||
|
Query::Explain(pattern) => format!(
|
||||||
|
r#"try {{
|
||||||
|
data = app.explain({pattern});
|
||||||
|
}} catch {{
|
||||||
|
refuse({{
|
||||||
|
code: 'route_not_found',
|
||||||
|
message: `no route matching pattern ${{{pattern}}}`,
|
||||||
|
registered: app.graph().routes.map((r) => ({{ method: r.method, pattern: r.pattern }})),
|
||||||
|
}});
|
||||||
|
}}"#,
|
||||||
|
pattern = js_string(pattern)
|
||||||
|
),
|
||||||
|
Query::OpenApi { title, version } => {
|
||||||
|
let mut fields = Vec::new();
|
||||||
|
if let Some(t) = title {
|
||||||
|
fields.push(format!("title: {}", js_string(t)));
|
||||||
|
}
|
||||||
|
if let Some(v) = version {
|
||||||
|
fields.push(format!("version: {}", js_string(v)));
|
||||||
|
}
|
||||||
|
// No info object at all lets core apply its own defaults rather than
|
||||||
|
// having the CLI invent a title.
|
||||||
|
let info = if fields.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("{{ {} }}", fields.join(", "))
|
||||||
|
};
|
||||||
|
format!("data = app.openapi({info});")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens, from the graph's nodes plus each route's handler (only `explain`
|
||||||
|
/// knows what a handler needs). Sorted, so the answer is stable across runs.
|
||||||
|
///
|
||||||
|
/// A token that something needs and no node provides is one the request itself
|
||||||
|
/// carries (`req`, `params`, `body`, …). That is an inference, and a sound one:
|
||||||
|
/// `app.ready()` has validated the graph, so a needed token with no producer
|
||||||
|
/// would already have failed it. Marking those `"source": "request"` keeps an
|
||||||
|
/// agent from reading "nothing provides it" and writing a provider for `req`.
|
||||||
|
const TOKENS: &str = r#"const tokens = new Map();
|
||||||
|
const entry = (t) => tokens.get(t) ?? tokens.set(t, { token: t, providedBy: [], neededBy: [] }).get(t);
|
||||||
|
const graph = app.graph();
|
||||||
|
for (const n of graph.nodes) {
|
||||||
|
for (const t of n.provides) entry(t).providedBy.push({ kind: n.kind, name: n.name, origin: n.origin });
|
||||||
|
for (const t of n.needs) entry(t).neededBy.push({ kind: n.kind, name: n.name, origin: n.origin });
|
||||||
|
}
|
||||||
|
for (const pattern of new Set(graph.routes.map((r) => r.pattern))) {
|
||||||
|
for (const n of app.explain(pattern).chain) {
|
||||||
|
if (n.kind !== 'handler') continue;
|
||||||
|
for (const t of n.needs) entry(t).neededBy.push({ kind: 'handler', name: n.name, origin: n.origin, route: pattern });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const t of tokens.values()) t.source = t.providedBy.length ? 'graph' : 'request';
|
||||||
|
data = [...tokens.values()].sort((a, b) => a.token.localeCompare(b.token));"#;
|
||||||
|
|
||||||
|
fn resolve_entry(target: &Target) -> std::io::Result<PathBuf> {
|
||||||
|
match target.entry {
|
||||||
|
Some(explicit) => {
|
||||||
|
if !target.dir.join(explicit).exists() {
|
||||||
|
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
|
||||||
|
}
|
||||||
|
Ok(PathBuf::from(explicit))
|
||||||
|
}
|
||||||
|
None => entry::find(target.dir)
|
||||||
|
.map(|p| p.strip_prefix(target.dir).unwrap_or(&p).to_path_buf())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
format!(
|
||||||
|
"no {} found — pass --entry <file>. It must export the app: `export const app = createApp(...)`",
|
||||||
|
entry::candidates()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The generated script: import the app, resolve the graph, run `body`, print
|
||||||
|
/// one envelope. `refuse` ends the script with a structured error instead of
|
||||||
|
/// data.
|
||||||
|
fn script(entry_path: &Path, body: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"// generated by matcha; safe to delete\n\
|
||||||
|
import {{ app }} from {};\n\n\
|
||||||
|
if (!app) {{\n console.error('{} does not export `app` — matcha needs `export const app = createApp(...)`');\n process.exit(1);\n}}\n\
|
||||||
|
const refuse = (error) => {{\n console.log(JSON.stringify({{ ok: false, error }}));\n process.exit(0);\n}};\n\
|
||||||
|
await app.ready();\n\
|
||||||
|
let data;\n\
|
||||||
|
{body}\n\
|
||||||
|
console.log(JSON.stringify({{ ok: true, data }}));\n",
|
||||||
|
js_string(&specifier(entry_path)),
|
||||||
|
entry_path.display(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `script` under `rt` in `dir`, stdout captured, stderr inherited.
|
||||||
|
fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::Output> {
|
||||||
|
let (prog, args) = runner(rt, script);
|
||||||
|
let child = Command::new(prog)
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::inherit())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| Error::new(e.kind(), format!("could not run {prog}: {e}")))?;
|
||||||
|
child.wait_with_output()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
|
||||||
|
let s = script.to_string();
|
||||||
|
match rt {
|
||||||
|
// Edge resolves its graph under node: `src/app.ts` imports core, never
|
||||||
|
// `edgeHandler`, so nothing here needs workerd — and workerd could not
|
||||||
|
// print to a terminal anyway.
|
||||||
|
Runtime::Node | Runtime::Edge => ("npx", vec!["tsx".into(), s]),
|
||||||
|
// `ready()` opens no provider connections, but a mesh app does reach its
|
||||||
|
// teapots there, so net is part of resolving the graph rather than extra.
|
||||||
|
Runtime::Deno => (
|
||||||
|
"deno",
|
||||||
|
vec![
|
||||||
|
"run".into(),
|
||||||
|
"--allow-read".into(),
|
||||||
|
"--allow-env".into(),
|
||||||
|
"--allow-net".into(),
|
||||||
|
s,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Runtime::Bun => ("bun", vec!["run".into(), s]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A project-root-relative path as an ES module specifier: forward slashes,
|
||||||
|
/// always `./`-prefixed, extension kept so Deno resolves it without leaning on
|
||||||
|
/// `sloppy-imports`.
|
||||||
|
fn specifier(path: &Path) -> String {
|
||||||
|
let raw = path.to_string_lossy().replace('\\', "/");
|
||||||
|
format!("./{}", raw.strip_prefix("./").unwrap_or(&raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-quoted JS string literal. Route patterns reach this from argv, so the
|
||||||
|
/// quote and the backslash have to be escaped rather than assumed absent.
|
||||||
|
pub(crate) fn js_string(value: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(value.len() + 2);
|
||||||
|
out.push('\'');
|
||||||
|
for ch in value.chars() {
|
||||||
|
match ch {
|
||||||
|
'\\' => out.push_str("\\\\"),
|
||||||
|
'\'' => out.push_str("\\'"),
|
||||||
|
'\n' => out.push_str("\\n"),
|
||||||
|
'\r' => out.push_str("\\r"),
|
||||||
|
_ => out.push(ch),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('\'');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn specifier_is_dot_slash_prefixed_with_extension() {
|
||||||
|
assert_eq!(specifier(Path::new("src/app.ts")), "./src/app.ts");
|
||||||
|
assert_eq!(specifier(Path::new("./src/app.ts")), "./src/app.ts");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn js_string_escapes_quote_and_backslash() {
|
||||||
|
assert_eq!(js_string("a'b"), r"'a\'b'");
|
||||||
|
assert_eq!(js_string(r"a\b"), r"'a\\b'");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn script_imports_the_entry_awaits_ready_and_prints_one_envelope() {
|
||||||
|
let out = script(Path::new("src/app.ts"), "data = 1;");
|
||||||
|
assert!(out.contains("import { app } from './src/app.ts';"));
|
||||||
|
assert!(out.contains("await app.ready();"));
|
||||||
|
assert!(out.contains("data = 1;"));
|
||||||
|
assert!(out.contains("JSON.stringify({ ok: true, data })"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn node_runs_through_tsx() {
|
||||||
|
assert_eq!(
|
||||||
|
runner(Runtime::Node, ".matcha-introspect.ts"),
|
||||||
|
(
|
||||||
|
"npx",
|
||||||
|
vec!["tsx".to_string(), ".matcha-introspect.ts".to_string()]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_envelope_is_the_last_line_so_boot_logs_cannot_pose_as_the_answer() {
|
||||||
|
let out = "{\"level\":\"info\",\"msg\":\"booted\"}\n{\"ok\":true,\"data\":[1]}\n";
|
||||||
|
assert_eq!(parse_envelope(out).unwrap(), Ok(serde_json::json!([1])));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refusal_comes_back_structured() {
|
||||||
|
let out =
|
||||||
|
"{\"ok\":false,\"error\":{\"code\":\"route_not_found\",\"message\":\"no route\"}}";
|
||||||
|
let refusal = parse_envelope(out).unwrap().unwrap_err();
|
||||||
|
assert_eq!(refusal.0["code"], "route_not_found");
|
||||||
|
assert_eq!(refusal.message(), "no route");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explain_escapes_the_pattern() {
|
||||||
|
assert!(body(&Query::Explain("/a'b".into())).contains(r"app.explain('/a\'b')"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
-1
@@ -9,6 +9,7 @@ mod cmd_new;
|
|||||||
mod cmd_plugin;
|
mod cmd_plugin;
|
||||||
mod cmd_run;
|
mod cmd_run;
|
||||||
mod entry;
|
mod entry;
|
||||||
|
mod introspect;
|
||||||
mod naming;
|
mod naming;
|
||||||
mod plugin_files;
|
mod plugin_files;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
@@ -121,12 +122,40 @@ fn main() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Command::Explain { route, entry, out } => {
|
Command::Explain {
|
||||||
|
route,
|
||||||
|
entry,
|
||||||
|
out,
|
||||||
|
json,
|
||||||
|
} => {
|
||||||
if let Err(e) = cmd_graph::explain(
|
if let Err(e) = cmd_graph::explain(
|
||||||
std::path::Path::new("."),
|
std::path::Path::new("."),
|
||||||
&route,
|
&route,
|
||||||
entry.as_deref(),
|
entry.as_deref(),
|
||||||
out.as_deref(),
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
|
) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Routes { entry, out, json } => {
|
||||||
|
if let Err(e) = cmd_graph::routes(
|
||||||
|
std::path::Path::new("."),
|
||||||
|
entry.as_deref(),
|
||||||
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
|
) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Tokens { entry, out, json } => {
|
||||||
|
if let Err(e) = cmd_graph::tokens(
|
||||||
|
std::path::Path::new("."),
|
||||||
|
entry.as_deref(),
|
||||||
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
) {
|
) {
|
||||||
eprintln!("error: {e}");
|
eprintln!("error: {e}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
@@ -143,3 +172,11 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render(json: bool) -> cmd_graph::Render {
|
||||||
|
if json {
|
||||||
|
cmd_graph::Render::Json
|
||||||
|
} else {
|
||||||
|
cmd_graph::Render::Text
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user