The CLI catches up with the framework: graph/explain/openapi/doctor, an edge target, and a scaffold that is not two releases behind #11
No files matched your search
@@ -36,7 +36,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
runtime: [node, deno, bun]
|
runtime: [node, deno, bun, edge]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ matcha create controller Users # generate + auto-wire into @Module
|
|||||||
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 doctor # check the project for confusing misconfigurations
|
||||||
```
|
```
|
||||||
|
|
||||||
### The starter
|
### The starter
|
||||||
@@ -102,16 +103,45 @@ and wire pieces into the right `@Module` array or controller. Edits are
|
|||||||
idempotent and revert themselves if they would break the file's syntax. Pass
|
idempotent and revert themselves if they would break the file's syntax. Pass
|
||||||
`--check` to `create` to type-check with your project's runtime afterward.
|
`--check` to `create` to type-check with your project's runtime afterward.
|
||||||
|
|
||||||
|
### `matcha doctor`
|
||||||
|
|
||||||
|
The checks whose failures are confusing rather than loud: `experimentalDecorators`
|
||||||
|
missing (every `@Route` becomes a syntax error, and the message blames the
|
||||||
|
decorator), a core pin that cannot resolve, an installed version that does not
|
||||||
|
match the manifest, an entry that does not export `app`, and `@Ws`/multipart
|
||||||
|
routes whose optional peer dependency is not installed — core lazy-loads `ws`
|
||||||
|
and `busboy`, so those compile and fail at the first request instead.
|
||||||
|
|
||||||
|
Every check is a file read: no runtime is spawned and nothing is fetched, so it
|
||||||
|
works before the project installs. Exits non-zero on a `✗`.
|
||||||
|
|
||||||
## Runtime detection
|
## Runtime detection
|
||||||
|
|
||||||
`matcha run` picks the runtime by precedence, first match wins:
|
`matcha run` picks the runtime by precedence, first match wins:
|
||||||
|
|
||||||
1. `matcha.toml` — `runtime = "node" | "deno" | "bun"`
|
1. `matcha.toml` — `runtime = "node" | "deno" | "bun" | "edge"`
|
||||||
2. `deno.json` / `deno.jsonc` → **deno**
|
2. `wrangler.toml` / `wrangler.jsonc` → **edge**
|
||||||
3. `bun.lockb` / `bun.lock` → **bun**
|
3. `deno.json` / `deno.jsonc` → **deno**
|
||||||
4. `package.json` → **node**
|
4. `bun.lockb` / `bun.lock` → **bun**
|
||||||
|
5. `package.json` → **node**
|
||||||
|
|
||||||
Edge is a deploy target, not a `matcha run` target.
|
`wrangler.toml` is checked before `package.json` because an edge project has both.
|
||||||
|
|
||||||
|
### Edge
|
||||||
|
|
||||||
|
`matcha new my-api --runtime edge` scaffolds a Cloudflare Worker: `wrangler.toml`
|
||||||
|
with `nodejs_compat`, `edgeHandler(app)` as the default export, and wrangler's
|
||||||
|
`[assets]` serving `./public` — so `/` is the same page as on the other runtimes
|
||||||
|
and `/zen` is the same stream, from the worker. `matcha run` is `wrangler dev`,
|
||||||
|
which boots real workerd locally.
|
||||||
|
|
||||||
|
Two differences the edge cannot hide. `@Html('file')`, `static` and multipart
|
||||||
|
uploads need a filesystem workerd does not have, and shutdown teardown never
|
||||||
|
runs — an isolate is discarded, not closed. And core is installed from **JSR**
|
||||||
|
here rather than npm: the npm ESM build carries a `createRequire(import.meta.url)`
|
||||||
|
banner that throws at load on workerd. The scaffolded `.npmrc` says so and links
|
||||||
|
[the issue](https://github.com/Expressive-Tea/green-tea/issues/93); both it and
|
||||||
|
the alias can go once that is fixed.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
# Usage: scripts/starter-smoke.sh <node|deno|bun>
|
# Usage: scripts/starter-smoke.sh <node|deno|bun>
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
RUNTIME="${1:?usage: starter-smoke.sh <node|deno|bun>}"
|
RUNTIME="${1:?usage: starter-smoke.sh <node|deno|bun|edge>}"
|
||||||
MATCHA="${MATCHA:-$PWD/target/debug/matcha}"
|
MATCHA="${MATCHA:-$PWD/target/debug/matcha}"
|
||||||
[ -x "$MATCHA" ] || { echo "no matcha binary at $MATCHA (cargo build first)" >&2; exit 2; }
|
[ -x "$MATCHA" ] || { echo "no matcha binary at $MATCHA (cargo build first)" >&2; exit 2; }
|
||||||
|
|
||||||
@@ -19,6 +19,7 @@ case "$RUNTIME" in
|
|||||||
node) TEMPLATE_PORT=3000; INSTALL=(npm install); CHECK=(npx --yes tsc --noEmit) ;;
|
node) TEMPLATE_PORT=3000; INSTALL=(npm install); CHECK=(npx --yes tsc --noEmit) ;;
|
||||||
deno) TEMPLATE_PORT=8000; INSTALL=(deno install); CHECK=(deno check src/main.ts) ;;
|
deno) TEMPLATE_PORT=8000; INSTALL=(deno install); CHECK=(deno check src/main.ts) ;;
|
||||||
bun) TEMPLATE_PORT=8000; INSTALL=(bun install); CHECK=(bunx --bun tsc --noEmit) ;;
|
bun) TEMPLATE_PORT=8000; INSTALL=(bun install); CHECK=(bunx --bun tsc --noEmit) ;;
|
||||||
|
edge) TEMPLATE_PORT=8787; INSTALL=(npm install); CHECK=(npx --yes tsc --noEmit) ;;
|
||||||
*) echo "unknown runtime: $RUNTIME" >&2; exit 2 ;;
|
*) echo "unknown runtime: $RUNTIME" >&2; exit 2 ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
@@ -39,7 +40,13 @@ cd "$WORK"
|
|||||||
echo "▸ matcha new demo --runtime $RUNTIME"
|
echo "▸ matcha new demo --runtime $RUNTIME"
|
||||||
"$MATCHA" new demo --runtime "$RUNTIME"
|
"$MATCHA" new demo --runtime "$RUNTIME"
|
||||||
cd demo
|
cd demo
|
||||||
sed -i.bak "s/$TEMPLATE_PORT/$PORT/g" src/main.ts && rm -f src/main.ts.bak
|
if [ "$RUNTIME" = edge ]; then
|
||||||
|
# The edge starter's port is wrangler's, not the app's — src/main.ts only
|
||||||
|
# exports a fetch handler.
|
||||||
|
printf '\n[dev]\nport = %s\n' "$PORT" >> wrangler.toml
|
||||||
|
else
|
||||||
|
sed -i.bak "s/$TEMPLATE_PORT/$PORT/g" src/main.ts && rm -f src/main.ts.bak
|
||||||
|
fi
|
||||||
|
|
||||||
echo "▸ ${INSTALL[*]}"
|
echo "▸ ${INSTALL[*]}"
|
||||||
"${INSTALL[@]}"
|
"${INSTALL[@]}"
|
||||||
@@ -57,6 +64,8 @@ done
|
|||||||
|
|
||||||
# The starter's two halves: the @Html page, and the @Sse stream that is the
|
# The starter's two halves: the @Html page, and the @Sse stream that is the
|
||||||
# reason the starter is alive rather than a JSON hello.
|
# reason the starter is alive rather than a JSON hello.
|
||||||
|
# On edge, `/` is answered by wrangler's [assets] rather than by the worker —
|
||||||
|
# the page is the same one, from the same public/index.html.
|
||||||
code=$(curl -fsS -o /dev/null -w '%{http_code}' "http://localhost:$PORT/" 2>/dev/null || echo 000)
|
code=$(curl -fsS -o /dev/null -w '%{http_code}' "http://localhost:$PORT/" 2>/dev/null || echo 000)
|
||||||
[ "$code" = 200 ] || { echo "GET / returned $code"; echo '--- server log ---'; cat "$WORK/server.log"; exit 1; }
|
[ "$code" = 200 ] || { echo "GET / returned $code"; echo '--- server log ---'; cat "$WORK/server.log"; exit 1; }
|
||||||
# Read one frame and stop. `head -1` closing the pipe kills curl with SIGPIPE,
|
# Read one frame and stop. `head -1` closing the pipe kills curl with SIGPIPE,
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
|||||||
match rt {
|
match rt {
|
||||||
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
||||||
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
||||||
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
Runtime::Node | Runtime::Edge => ("npx", vec!["tsc", "--noEmit"]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -14,7 +14,7 @@ pub enum Command {
|
|||||||
name: String,
|
name: String,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
template_url: Option<String>,
|
template_url: Option<String>,
|
||||||
#[arg(long, default_value = "node", value_parser = ["node", "deno", "bun"])]
|
#[arg(long, default_value = "node", value_parser = ["node", "deno", "bun", "edge"])]
|
||||||
runtime: String,
|
runtime: String,
|
||||||
},
|
},
|
||||||
/// Detect the runtime and run the project in watch mode
|
/// Detect the runtime and run the project in watch mode
|
||||||
@@ -27,6 +27,8 @@ pub enum Command {
|
|||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
check: bool,
|
check: bool,
|
||||||
},
|
},
|
||||||
|
/// Check the project for the misconfigurations that fail confusingly
|
||||||
|
Doctor,
|
||||||
/// Print the dependency graph (Mermaid, DOT, or JSON)
|
/// Print the dependency graph (Mermaid, DOT, or JSON)
|
||||||
Graph {
|
Graph {
|
||||||
#[arg(long, default_value = "mermaid", value_parser = ["mermaid", "dot", "json"])]
|
#[arg(long, default_value = "mermaid", value_parser = ["mermaid", "dot", "json"])]
|
||||||
|
|||||||
@@ -0,0 +1,443 @@
|
|||||||
|
//! `matcha doctor` — the checks whose failures are confusing rather than loud.
|
||||||
|
//!
|
||||||
|
//! Every check is a file read: no runtime is spawned and no network is touched,
|
||||||
|
//! so this stays usable on a machine where the project does not yet install.
|
||||||
|
//! The manifests are scanned rather than parsed, the way `runtime.rs` reads
|
||||||
|
//! `matcha.toml`, which keeps the CLI free of a JSON dependency for values that
|
||||||
|
//! are always written one per line by the tools that emit them.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::{entry, runtime, template};
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||||
|
pub enum Level {
|
||||||
|
Ok,
|
||||||
|
Warn,
|
||||||
|
Fail,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub struct Finding {
|
||||||
|
pub level: Level,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(message: impl Into<String>) -> Finding {
|
||||||
|
Finding {
|
||||||
|
level: Level::Ok,
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn warn(message: impl Into<String>) -> Finding {
|
||||||
|
Finding {
|
||||||
|
level: Level::Warn,
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn fail(message: impl Into<String>) -> Finding {
|
||||||
|
Finding {
|
||||||
|
level: Level::Fail,
|
||||||
|
message: message.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(dir: &Path) -> std::io::Result<()> {
|
||||||
|
let findings = diagnose(dir);
|
||||||
|
for finding in &findings {
|
||||||
|
let mark = match finding.level {
|
||||||
|
Level::Ok => "✓",
|
||||||
|
Level::Warn => "⚠",
|
||||||
|
Level::Fail => "✗",
|
||||||
|
};
|
||||||
|
println!("{mark} {}", finding.message);
|
||||||
|
}
|
||||||
|
if findings.iter().any(|f| f.level == Level::Fail) {
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All checks, in the order a reader wants them: what runtime, what core, can
|
||||||
|
/// it compile, can it be introspected, will it serve.
|
||||||
|
pub fn diagnose(dir: &Path) -> Vec<Finding> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let rt = runtime::detect(dir);
|
||||||
|
out.push(match rt {
|
||||||
|
Some(r) => ok(format!("runtime: {r:?}").to_lowercase()),
|
||||||
|
None => fail(
|
||||||
|
"no runtime detected — expected matcha.toml, deno.json, bun.lock or package.json"
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
out.extend(check_core(dir));
|
||||||
|
out.extend(check_decorators(dir));
|
||||||
|
out.extend(check_entry(dir));
|
||||||
|
out.extend(check_peers(dir));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the value of `"<key>": "<value>"` from a JSON-ish manifest.
|
||||||
|
///
|
||||||
|
/// Naive on purpose: it takes the first occurrence and the next quoted string
|
||||||
|
/// after the colon. Package manifests are machine-written one pair per line, so
|
||||||
|
/// the cases this would get wrong (the key inside a string, a value spanning
|
||||||
|
/// lines) do not occur in the files it is pointed at.
|
||||||
|
fn json_value(src: &str, key: &str) -> Option<String> {
|
||||||
|
let at = src.find(&format!("\"{key}\""))? + key.len() + 2;
|
||||||
|
let rest = &src[at..];
|
||||||
|
let colon = rest.find(':')?;
|
||||||
|
let after = &rest[colon + 1..];
|
||||||
|
let open = after.find('"')?;
|
||||||
|
let tail = &after[open + 1..];
|
||||||
|
let close = tail.find('"')?;
|
||||||
|
Some(tail[..close].to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The version out of a dependency specifier.
|
||||||
|
///
|
||||||
|
/// A plain range (`26.9.0-beta.1`, `^26.7.0`) is already the version. A
|
||||||
|
/// registry or alias specifier is not: the edge scaffold declares
|
||||||
|
/// `npm:@jsr/green-tea__core@26.9.0-beta.1` and the deno one
|
||||||
|
/// `jsr:@green-tea/core@26.9.0-beta.1`, and comparing either of those whole
|
||||||
|
/// against an installed version reports a mismatch that is not one. The `:`
|
||||||
|
/// is what tells the two apart — a bare semver range never has one.
|
||||||
|
fn version_of(spec: &str) -> String {
|
||||||
|
if spec.contains(':') {
|
||||||
|
spec.rsplit('@').next().unwrap_or(spec).to_string()
|
||||||
|
} else {
|
||||||
|
spec.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(dir: &Path, name: &str) -> Option<String> {
|
||||||
|
std::fs::read_to_string(dir.join(name)).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the project asks for versus what is on disk, and how both compare to
|
||||||
|
/// the version this CLI scaffolds against.
|
||||||
|
///
|
||||||
|
/// The installed version is read from the package's own `package.json`, never
|
||||||
|
/// from core's exported `VERSION` constant — that constant is stale in the
|
||||||
|
/// published artifact (Green-Tea/core#92), so it would report the wrong answer
|
||||||
|
/// for exactly the check that exists to catch a wrong version.
|
||||||
|
fn check_core(dir: &Path) -> Vec<Finding> {
|
||||||
|
let declared = read(dir, "package.json")
|
||||||
|
.and_then(|s| json_value(&s, "@green-tea/core"))
|
||||||
|
.or_else(|| read(dir, "deno.json").and_then(|s| json_value(&s, "@green-tea/core")))
|
||||||
|
.map(|spec| version_of(&spec));
|
||||||
|
|
||||||
|
let Some(declared) = declared else {
|
||||||
|
return vec![fail("no @green-tea/core dependency declared".to_string())];
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut out = vec![ok(format!("@green-tea/core declared: {declared}"))];
|
||||||
|
|
||||||
|
// Deno resolves through its own cache rather than node_modules, so absence
|
||||||
|
// there is not a finding — only a mismatch is, and only node and bun can
|
||||||
|
// show one.
|
||||||
|
if let Some(installed) = read(dir, "node_modules/@green-tea/core/package.json")
|
||||||
|
.and_then(|s| json_value(&s, "version"))
|
||||||
|
{
|
||||||
|
if installed != declared.trim_start_matches(['^', '~']) {
|
||||||
|
out.push(warn(format!(
|
||||||
|
"installed core is {installed}, the manifest asks for {declared} — run your package manager's install"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if declared.starts_with('^') || declared.starts_with('~') {
|
||||||
|
out.push(warn(format!(
|
||||||
|
"core is pinned with a range ({declared}) while it is prerelease-only — \
|
||||||
|
npm excludes a prerelease from a range whose comparators carry a different \
|
||||||
|
major.minor.patch, so this cannot resolve past its first match. Pin exactly."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if declared.trim_start_matches(['^', '~']) != template::CORE_VERSION {
|
||||||
|
out.push(warn(format!(
|
||||||
|
"this matcha scaffolds against {} — a project on {declared} may not match its generated code",
|
||||||
|
template::CORE_VERSION
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decorators are the whole surface. Without the compiler flag every `@Route`
|
||||||
|
/// is a syntax error, and the message points at the decorator rather than at
|
||||||
|
/// the setting that rejected it.
|
||||||
|
fn check_decorators(dir: &Path) -> Vec<Finding> {
|
||||||
|
let config = ["tsconfig.json", "deno.json", "deno.jsonc"]
|
||||||
|
.iter()
|
||||||
|
.find_map(|name| read(dir, name).map(|body| (*name, body)));
|
||||||
|
|
||||||
|
match config {
|
||||||
|
None => vec![warn("no tsconfig.json or deno.json — cannot confirm decorators are enabled".to_string())],
|
||||||
|
Some((name, body)) if body.contains("\"experimentalDecorators\": true") => {
|
||||||
|
vec![ok(format!("decorators enabled in {name}"))]
|
||||||
|
}
|
||||||
|
Some((name, _)) => vec![fail(format!(
|
||||||
|
"{name} does not set \"experimentalDecorators\": true — every @Route is a syntax error without it"
|
||||||
|
))],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha graph` and `matcha explain` import the app rather than serve it, so
|
||||||
|
/// they need it exported. A project that never exports it works perfectly and
|
||||||
|
/// simply cannot be introspected, which is worth saying before someone runs
|
||||||
|
/// `graph` and reads a module-resolution error.
|
||||||
|
fn check_entry(dir: &Path) -> Vec<Finding> {
|
||||||
|
let Some(path) = entry::find(dir) else {
|
||||||
|
return vec![warn(format!(
|
||||||
|
"no {} — matcha graph and matcha explain need an entry exporting the app",
|
||||||
|
entry::candidates()
|
||||||
|
))];
|
||||||
|
};
|
||||||
|
let name = path
|
||||||
|
.strip_prefix(dir)
|
||||||
|
.unwrap_or(&path)
|
||||||
|
.display()
|
||||||
|
.to_string();
|
||||||
|
match std::fs::read_to_string(&path) {
|
||||||
|
Ok(body) if body.contains("export const app") || body.contains("export { app") => {
|
||||||
|
vec![ok(format!("{name} exports the app"))]
|
||||||
|
}
|
||||||
|
Ok(_) => vec![warn(format!(
|
||||||
|
"{name} does not export `app` — matcha graph and matcha explain cannot import it"
|
||||||
|
))],
|
||||||
|
Err(e) => vec![warn(format!("could not read {name}: {e}"))],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Optional peer dependencies, matched to what the source actually uses.
|
||||||
|
///
|
||||||
|
/// A grep rather than an analysis: `@Ws(` and `MultipartBody` are the two
|
||||||
|
/// markers that are unambiguous in practice, and both dependencies are
|
||||||
|
/// lazy-required by core — so the project compiles either way and fails on the
|
||||||
|
/// first request that reaches the route. That gap is what this closes.
|
||||||
|
fn check_peers(dir: &Path) -> Vec<Finding> {
|
||||||
|
let sources = collect_sources(&dir.join("src"));
|
||||||
|
let manifest = read(dir, "package.json").unwrap_or_default();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
|
||||||
|
for (marker, package, why) in [
|
||||||
|
("@Ws(", "ws", "@Ws routes need it on Node"),
|
||||||
|
("MultipartBody", "busboy", "multipart uploads need it"),
|
||||||
|
] {
|
||||||
|
if !sources.contains(marker) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let installed = dir.join("node_modules").join(package).exists();
|
||||||
|
if installed || manifest.contains(&format!("\"{package}\"")) {
|
||||||
|
out.push(ok(format!("{package} present ({why})")));
|
||||||
|
} else {
|
||||||
|
out.push(warn(format!(
|
||||||
|
"src uses {marker} but '{package}' is not installed — {why}: npm i {package}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Concatenates every `.ts` file under `dir`, recursively. Small trees; the
|
||||||
|
/// alternative is a walker dependency for a grep.
|
||||||
|
fn collect_sources(dir: &Path) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
out.push_str(&collect_sources(&path));
|
||||||
|
} else if path.extension().is_some_and(|e| e == "ts") {
|
||||||
|
if let Ok(body) = std::fs::read_to_string(&path) {
|
||||||
|
out.push_str(&body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
fn write(dir: &Path, rel: &str, body: &str) {
|
||||||
|
let p = dir.join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, body).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn levels(findings: &[Finding], needle: &str) -> Vec<Level> {
|
||||||
|
findings
|
||||||
|
.iter()
|
||||||
|
.filter(|f| f.message.contains(needle))
|
||||||
|
.map(|f| f.level)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn json_value_reads_a_pair() {
|
||||||
|
let src = r#"{ "dependencies": { "@green-tea/core": "26.9.0-beta.1" } }"#;
|
||||||
|
assert_eq!(
|
||||||
|
json_value(src, "@green-tea/core").as_deref(),
|
||||||
|
Some("26.9.0-beta.1")
|
||||||
|
);
|
||||||
|
assert_eq!(json_value(src, "missing"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_decorators_is_a_failure_not_a_warning() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"tsconfig.json",
|
||||||
|
r#"{ "compilerOptions": { "strict": true } }"#,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
levels(&check_decorators(d.path()), "experimentalDecorators"),
|
||||||
|
vec![Level::Fail]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_caret_pin_on_a_prerelease_core_is_reported() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"package.json",
|
||||||
|
r#"{ "dependencies": { "@green-tea/core": "^26.7.0-beta.0" } }"#,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
levels(&check_core(d.path()), "pinned with a range"),
|
||||||
|
vec![Level::Warn]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_installed_version_that_differs_from_the_manifest_is_reported() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"package.json",
|
||||||
|
r#"{ "dependencies": { "@green-tea/core": "26.9.0-beta.1" } }"#,
|
||||||
|
);
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"node_modules/@green-tea/core/package.json",
|
||||||
|
r#"{ "version": "26.7.0-beta.0" }"#,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
levels(&check_core(d.path()), "installed core is"),
|
||||||
|
vec![Level::Warn]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_matching_install_reports_nothing_extra() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
let v = template::CORE_VERSION;
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"package.json",
|
||||||
|
&format!(r#"{{ "dependencies": {{ "@green-tea/core": "{v}" }} }}"#),
|
||||||
|
);
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"node_modules/@green-tea/core/package.json",
|
||||||
|
&format!(r#"{{ "version": "{v}" }}"#),
|
||||||
|
);
|
||||||
|
let findings = check_core(d.path());
|
||||||
|
assert!(
|
||||||
|
findings.iter().all(|f| f.level == Level::Ok),
|
||||||
|
"{findings:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn version_of_unwraps_registry_and_alias_specifiers() {
|
||||||
|
assert_eq!(version_of("26.9.0-beta.1"), "26.9.0-beta.1");
|
||||||
|
assert_eq!(version_of("^26.7.0-beta.0"), "^26.7.0-beta.0");
|
||||||
|
assert_eq!(
|
||||||
|
version_of("jsr:@green-tea/core@26.9.0-beta.1"),
|
||||||
|
"26.9.0-beta.1"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
version_of("npm:@jsr/green-tea__core@26.9.0-beta.1"),
|
||||||
|
"26.9.0-beta.1"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The edge scaffold installs core through an npm alias, and a doctor that
|
||||||
|
/// warned about it would cry wolf on the project it just generated.
|
||||||
|
#[test]
|
||||||
|
fn the_edge_alias_is_not_reported_as_a_mismatch() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
let v = template::CORE_VERSION;
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"package.json",
|
||||||
|
&format!(
|
||||||
|
r#"{{ "dependencies": {{ "@green-tea/core": "npm:@jsr/green-tea__core@{v}" }} }}"#
|
||||||
|
),
|
||||||
|
);
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"node_modules/@green-tea/core/package.json",
|
||||||
|
&format!(r#"{{ "name": "@jsr/green-tea__core", "version": "{v}" }}"#),
|
||||||
|
);
|
||||||
|
let findings = check_core(d.path());
|
||||||
|
assert!(
|
||||||
|
findings.iter().all(|f| f.level == Level::Ok),
|
||||||
|
"{findings:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deno_reads_its_pin_out_of_the_jsr_specifier() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
let v = template::CORE_VERSION;
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"deno.json",
|
||||||
|
&format!(r#"{{ "imports": {{ "@green-tea/core": "jsr:@green-tea/core@{v}" }} }}"#),
|
||||||
|
);
|
||||||
|
assert_eq!(levels(&check_core(d.path()), "declared"), vec![Level::Ok]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_ws_route_without_the_ws_package_is_reported() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(
|
||||||
|
d.path(),
|
||||||
|
"src/controllers/x.controller.ts",
|
||||||
|
"@Ws('/echo')\n",
|
||||||
|
);
|
||||||
|
write(d.path(), "package.json", "{}");
|
||||||
|
assert_eq!(
|
||||||
|
levels(&check_peers(d.path()), "'ws' is not installed"),
|
||||||
|
vec![Level::Warn]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The grep must not fire on a project that never uses the feature.
|
||||||
|
#[test]
|
||||||
|
fn no_peer_findings_without_the_features_that_need_them() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(d.path(), "src/controllers/x.controller.ts", "@Get('/')\n");
|
||||||
|
write(d.path(), "package.json", "{}");
|
||||||
|
assert!(check_peers(d.path()).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_entry_that_does_not_export_the_app_is_reported() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write(d.path(), "src/app.ts", "const app = createApp({});\n");
|
||||||
|
assert_eq!(
|
||||||
|
levels(&check_entry(d.path()), "does not export"),
|
||||||
|
vec![Level::Warn]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -167,7 +167,10 @@ fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::O
|
|||||||
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
|
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
|
||||||
let s = script.to_string();
|
let s = script.to_string();
|
||||||
match rt {
|
match rt {
|
||||||
Runtime::Node => ("npx", vec!["tsx".into(), s]),
|
// 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
|
// `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.
|
// teapots there, so net is part of resolving the graph rather than extra.
|
||||||
Runtime::Deno => (
|
Runtime::Deno => (
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
|||||||
Runtime::Deno => ("deno", vec!["task", "dev"]),
|
Runtime::Deno => ("deno", vec!["task", "dev"]),
|
||||||
Runtime::Bun => ("bun", vec!["run", "dev"]),
|
Runtime::Bun => ("bun", vec!["run", "dev"]),
|
||||||
Runtime::Node => ("npm", vec!["run", "dev"]),
|
Runtime::Node => ("npm", vec!["run", "dev"]),
|
||||||
|
// The scaffold's `dev` script is `wrangler dev`, which boots real
|
||||||
|
// workerd locally — so edge is a `matcha run` target after all.
|
||||||
|
Runtime::Edge => ("npm", vec!["run", "dev"]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,6 +44,10 @@ mod tests {
|
|||||||
assert_eq!(command_for(Runtime::Bun), ("bun", vec!["run", "dev"]));
|
assert_eq!(command_for(Runtime::Bun), ("bun", vec!["run", "dev"]));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
fn edge_runs_wrangler_through_the_dev_script() {
|
||||||
|
assert_eq!(command_for(Runtime::Edge), ("npm", vec!["run", "dev"]));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
fn node_watch() {
|
fn node_watch() {
|
||||||
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ mod check;
|
|||||||
mod cli;
|
mod cli;
|
||||||
mod cmd_add;
|
mod cmd_add;
|
||||||
mod cmd_create;
|
mod cmd_create;
|
||||||
|
mod cmd_doctor;
|
||||||
mod cmd_graph;
|
mod cmd_graph;
|
||||||
mod cmd_new;
|
mod cmd_new;
|
||||||
mod cmd_run;
|
mod cmd_run;
|
||||||
@@ -38,6 +39,12 @@ fn main() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Command::Doctor => {
|
||||||
|
if let Err(e) = cmd_doctor::run(std::path::Path::new(".")) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
Command::Graph { format, entry, out } => {
|
Command::Graph { format, entry, out } => {
|
||||||
if let Err(e) = cmd_graph::graph(
|
if let Err(e) = cmd_graph::graph(
|
||||||
std::path::Path::new("."),
|
std::path::Path::new("."),
|
||||||
|
|||||||
@@ -5,6 +5,11 @@ pub enum Runtime {
|
|||||||
Node,
|
Node,
|
||||||
Deno,
|
Deno,
|
||||||
Bun,
|
Bun,
|
||||||
|
/// Cloudflare Workers. Unlike the other three this is a deploy target as
|
||||||
|
/// much as a local one — `wrangler dev` runs it in real workerd, but the
|
||||||
|
/// graph is resolved under node, since introspection never touches the
|
||||||
|
/// edge handler.
|
||||||
|
Edge,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
@@ -13,6 +18,7 @@ impl Runtime {
|
|||||||
"node" => Some(Runtime::Node),
|
"node" => Some(Runtime::Node),
|
||||||
"deno" => Some(Runtime::Deno),
|
"deno" => Some(Runtime::Deno),
|
||||||
"bun" => Some(Runtime::Bun),
|
"bun" => Some(Runtime::Bun),
|
||||||
|
"edge" => Some(Runtime::Edge),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,6 +45,10 @@ pub fn detect(dir: &Path) -> Option<Runtime> {
|
|||||||
if let Some(r) = override_from_toml(dir) {
|
if let Some(r) = override_from_toml(dir) {
|
||||||
return Some(r);
|
return Some(r);
|
||||||
}
|
}
|
||||||
|
// Before package.json, which an edge project also has.
|
||||||
|
if exists(dir, "wrangler.toml") || exists(dir, "wrangler.jsonc") {
|
||||||
|
return Some(Runtime::Edge);
|
||||||
|
}
|
||||||
if exists(dir, "deno.json") || exists(dir, "deno.jsonc") {
|
if exists(dir, "deno.json") || exists(dir, "deno.jsonc") {
|
||||||
return Some(Runtime::Deno);
|
return Some(Runtime::Deno);
|
||||||
}
|
}
|
||||||
@@ -92,6 +102,14 @@ mod tests {
|
|||||||
assert_eq!(detect(d.path()), Some(Runtime::Bun));
|
assert_eq!(detect(d.path()), Some(Runtime::Bun));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrangler_toml_wins_over_package_json() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
touch(d.path(), "package.json");
|
||||||
|
fs::write(d.path().join("wrangler.toml"), "name = \"x\"\n").unwrap();
|
||||||
|
assert_eq!(detect(d.path()), Some(Runtime::Edge));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn nothing_detected() {
|
fn nothing_detected() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
|
|||||||
+4
-2
@@ -20,12 +20,14 @@ pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
|
|||||||
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
|
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
|
||||||
pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node");
|
pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node");
|
||||||
pub static RUNTIME_BUN: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/bun");
|
pub static RUNTIME_BUN: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/bun");
|
||||||
|
pub static RUNTIME_EDGE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/edge");
|
||||||
|
|
||||||
fn overlay_for(runtime: Runtime) -> &'static Dir<'static> {
|
fn overlay_for(runtime: Runtime) -> &'static Dir<'static> {
|
||||||
match runtime {
|
match runtime {
|
||||||
Runtime::Deno => &RUNTIME_DENO,
|
Runtime::Deno => &RUNTIME_DENO,
|
||||||
Runtime::Node => &RUNTIME_NODE,
|
Runtime::Node => &RUNTIME_NODE,
|
||||||
Runtime::Bun => &RUNTIME_BUN,
|
Runtime::Bun => &RUNTIME_BUN,
|
||||||
|
Runtime::Edge => &RUNTIME_EDGE,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +74,7 @@ mod tests {
|
|||||||
/// import the former; breaking the split breaks both.
|
/// import the former; breaking the split breaks both.
|
||||||
#[test]
|
#[test]
|
||||||
fn every_runtime_exports_the_app_from_its_own_module() {
|
fn every_runtime_exports_the_app_from_its_own_module() {
|
||||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun] {
|
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
write_starter(d.path(), "my-api", rt).unwrap();
|
write_starter(d.path(), "my-api", rt).unwrap();
|
||||||
|
|
||||||
@@ -100,7 +102,7 @@ mod tests {
|
|||||||
/// may carry a range.
|
/// may carry a range.
|
||||||
#[test]
|
#[test]
|
||||||
fn no_runtime_scaffolds_a_caret_range_for_core() {
|
fn no_runtime_scaffolds_a_caret_range_for_core() {
|
||||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun] {
|
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
write_starter(d.path(), "my-api", rt).unwrap();
|
write_starter(d.path(), "my-api", rt).unwrap();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# core is installed from JSR here, and from npm on every other runtime.
|
||||||
|
#
|
||||||
|
# Not a preference: the npm ESM build carries tsup's
|
||||||
|
# `createRequire(import.meta.url)` banner at module scope, and `import.meta.url`
|
||||||
|
# is undefined on workerd — so `@green-tea/core/edge` throws at load, before any
|
||||||
|
# of its own code runs. JSR publishes transpiled source with no bundler and no
|
||||||
|
# banner, and boots clean. See Green-Tea/core#93; once that is fixed this file
|
||||||
|
# and the `npm:@jsr/...` alias in package.json can both go.
|
||||||
|
@jsr:registry=https://npm.jsr.io
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
runtime = "edge"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"name": "{{project_name}}",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy" },
|
||||||
|
"dependencies": { "@green-tea/core": "npm:@jsr/green-tea__core@{{core_version}}" },
|
||||||
|
"devDependencies": { "tsx": "^4", "typescript": "^5", "wrangler": "^4" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Route, Sse } from '@green-tea/core';
|
||||||
|
|
||||||
|
const ZEN = [
|
||||||
|
'Simplicity is the ultimate sophistication.',
|
||||||
|
'The obstacle is the path.',
|
||||||
|
'When you let go, you have two hands to work.',
|
||||||
|
'Make it work, make it right, make it fast.',
|
||||||
|
'Less, but better.',
|
||||||
|
];
|
||||||
|
|
||||||
|
@Route('/')
|
||||||
|
export class HomeController {
|
||||||
|
// No @Html('public/index.html') here: workerd has no filesystem to read it
|
||||||
|
// from. wrangler.toml's [assets] serves ./public instead, and the worker is
|
||||||
|
// reached for everything the assets do not answer.
|
||||||
|
@Sse('/zen')
|
||||||
|
zen() {
|
||||||
|
return (async function* () {
|
||||||
|
for (let i = 0; ; i++) {
|
||||||
|
yield { zen: ZEN[i % ZEN.length] };
|
||||||
|
await new Promise((r) => setTimeout(r, 30_000));
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { edgeHandler } from '@green-tea/core/edge';
|
||||||
|
|
||||||
|
import { app } from './app';
|
||||||
|
|
||||||
|
export default { fetch: edgeHandler(app) };
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "esnext",
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
name = "{{project_name}}"
|
||||||
|
main = "src/main.ts"
|
||||||
|
compatibility_date = "2024-11-01"
|
||||||
|
# green-tea reaches node builtins on every runtime that has them; workerd only
|
||||||
|
# provides them behind this flag.
|
||||||
|
compatibility_flags = ["nodejs_compat"]
|
||||||
|
|
||||||
|
# The edge has no filesystem, so @Html('public/index.html') cannot serve the
|
||||||
|
# starter page the way it does on node, deno and bun. Wrangler serves ./public
|
||||||
|
# itself and hands the worker everything it does not match — so '/' is the same
|
||||||
|
# page and '/zen' is the same stream.
|
||||||
|
[assets]
|
||||||
|
directory = "./public"
|
||||||
Reference in new issue
Block a user