From a8f1658e4d46b197cef237a5541da9a39f17e84b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 30 Oct 2026 21:00:58 -0500 Subject: [PATCH] fix(create,starters): safe names and no overwrite in create; node starter awaits listen and declares engines matcha create derives the class name and its token from what was typed: current-user becomes CurrentUserStep providing currentUser, where it used to write a file that did not parse. It refuses names that cannot be a class, and step or provider names whose token core already provides. It also refuses to replace an existing file instead of silently discarding edits. The node starter awaits app.listen so boot and bind failures stop the process with their own error, and the node and edge starters declare engines node >=22 to match core. Signed-off-by: Diego Resendez --- CHANGELOG.md | 18 ++++++++ src/cmd_create.rs | 69 ++++++++++++++++++++++++++--- template/runtimes/edge/package.json | 1 + template/runtimes/node/package.json | 1 + template/runtimes/node/src/main.ts | 4 +- tests/create.rs | 51 +++++++++++++++++++++ 6 files changed, 136 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a7828e..88cfcae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,24 @@ is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says w 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. +- **The node starter awaits `app.listen(3000)`.** A port already in use, or a provider that fails at + boot, now stops the process with its own error rather than an unhandled rejection. +- **The node and edge starters declare `engines: { node: ">=22" }`**, matching `@green-tea/core`, + which no longer supports Node 18 or 20. +- **`matcha create step|provider` derives the token from the class name in camelCase.** + `create step current-user` writes `CurrentUserStep` providing `currentUser`. It used to write + `current-userStep` and `return { current-user: null }`, which does not parse. A single word is + unchanged (`Users` still provides `users`). + +### Fixed + +- **`matcha create` no longer overwrites a file that already exists.** Running it twice with the same + name silently replaced the first file, edits included. Now it refuses and names the file. +- **`matcha create` rejects names that cannot become a class** (`2fast`, `us.ers`) instead of + writing a file that does not compile. For a step or provider, it also rejects names whose token + core already provides (`logger`, `rooms`, `events`, `bus`, and the request tokens `req`, + `params`, `query`, `body`, `headers`, `cookies`, `inbound`, `abort`). `createApp` would refuse the + first group, and the second would shadow what every route reads. ## [26.9.0-beta.1] - 2026-09-24 diff --git a/src/cmd_create.rs b/src/cmd_create.rs index d4a6bc1..65fabee 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -5,7 +5,7 @@ use std::io::{Error, ErrorKind}; use std::path::Path; -use crate::{entry, wire}; +use crate::{entry, naming, wire}; /// A piece that lives inside a module: a file under `src//` plus an /// entry in one of `@Module`'s arrays. @@ -60,7 +60,64 @@ pub fn kinds() -> Vec<&'static str> { .collect() } +/// Tokens core already owns. A step or provider that provides one fails `createApp` (the framework +/// tokens) or shadows what every route reads from the request (the request tokens). +const TAKEN_TOKENS: &[&str] = &[ + "logger", "rooms", "events", "bus", "req", "params", "query", "body", "headers", "cookies", + "inbound", "abort", +]; + +/// `Users` stays `Users`; `current-user`, `current_user` and `current user` become `CurrentUser`. +/// `None` for anything that cannot become a TypeScript class name. +fn class_name(name: &str) -> Option { + let name = name.trim(); + if name.starts_with(|c: char| c.is_ascii_alphabetic()) + && name.chars().all(|c| c.is_ascii_alphanumeric()) + { + let (first, rest) = name.split_at(1); + return Some(first.to_ascii_uppercase() + rest); + } + naming::slug(name).map(|s| naming::pascal(&s)) +} + +/// The token a step or provider named `CurrentUser` provides: `currentUser`. +fn token(class: &str) -> String { + let (first, rest) = class.split_at(1); + first.to_ascii_lowercase() + rest +} + +/// Refuses to replace a file the person may already have edited. +fn write_new(file: &Path, contents: String) -> std::io::Result<()> { + if file.exists() { + return Err(Error::new( + ErrorKind::AlreadyExists, + format!( + "{} already exists; matcha create does not overwrite it", + file.display() + ), + )); + } + std::fs::create_dir_all(file.parent().unwrap())?; + std::fs::write(file, contents) +} + pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> { + let Some(class) = class_name(name) else { + return Err(Error::new( + ErrorKind::InvalidInput, + format!("'{name}' cannot name a class: use letters and digits, starting with a letter (Users, CurrentUser, current-user)"), + )); + }; + let name = class.as_str(); + if (kind == "step" || kind == "provider") && TAKEN_TOKENS.contains(&token(name).as_str()) { + return Err(Error::new( + ErrorKind::InvalidInput, + format!( + "a {kind} named {name} would provide '{}', which core already provides; pick another name", + token(name) + ), + )); + } if kind == "module" { return create_module(name, check); } @@ -87,8 +144,7 @@ fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> { let file = Path::new("src") .join(subdir) .join(format!("{lower}.{ext}.ts")); - std::fs::create_dir_all(file.parent().unwrap())?; - std::fs::write(&file, (piece.stub)(name))?; + write_new(&file, (piece.stub)(name))?; println!("✓ {}", file.display()); let symbol = format!("{name}{suffix}"); @@ -117,8 +173,7 @@ fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> { fn create_module(name: &str, check: bool) -> std::io::Result<()> { let lower = name.to_lowercase(); let file = Path::new("src").join(format!("{lower}.module.ts")); - std::fs::create_dir_all(file.parent().unwrap())?; - std::fs::write(&file, module_stub(name))?; + write_new(&file, module_stub(name))?; println!("✓ {}", file.display()); let symbol = format!("{name}Module"); @@ -164,14 +219,14 @@ fn controller_stub(name: &str) -> String { } fn step_stub(name: &str) -> String { - let lower = name.to_lowercase(); + let lower = token(name); format!( "import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record) {{\n return {{ {lower}: null }};\n }}\n}}\n" ) } fn provider_stub(name: &str) -> String { - let lower = name.to_lowercase(); + let lower = token(name); format!( "import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n" ) diff --git a/template/runtimes/edge/package.json b/template/runtimes/edge/package.json index e36b9d8..6dc08ad 100644 --- a/template/runtimes/edge/package.json +++ b/template/runtimes/edge/package.json @@ -2,6 +2,7 @@ "name": "{{project_name}}", "type": "module", "private": true, + "engines": { "node": ">=22" }, "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" } diff --git a/template/runtimes/node/package.json b/template/runtimes/node/package.json index e40cc7c..fb0565b 100644 --- a/template/runtimes/node/package.json +++ b/template/runtimes/node/package.json @@ -2,6 +2,7 @@ "name": "{{project_name}}", "type": "module", "private": true, + "engines": { "node": ">=22" }, "scripts": { "dev": "tsx watch src/main.ts" }, "dependencies": { "@green-tea/core": "{{core_version}}" }, "devDependencies": { "tsx": "^4", "typescript": "^5" } diff --git a/template/runtimes/node/src/main.ts b/template/runtimes/node/src/main.ts index 175253c..8ba57a0 100644 --- a/template/runtimes/node/src/main.ts +++ b/template/runtimes/node/src/main.ts @@ -1,4 +1,6 @@ import { app } from './app'; -app.listen(3000); +// Awaited, so a boot or bind failure stops the process with its own error instead of surfacing +// later as an unhandled rejection. +await app.listen(3000); console.log('🍵 green-tea running on http://localhost:3000'); diff --git a/tests/create.rs b/tests/create.rs index 48c37d1..966f7d5 100644 --- a/tests/create.rs +++ b/tests/create.rs @@ -119,3 +119,54 @@ fn create_module_prefers_app_ts_over_main_ts() { let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); assert!(!main.contains("UsersModule"), "main.ts was edited: {main}"); } + +fn create(dir: &std::path::Path, kind: &str, name: &str) -> assert_cmd::assert::Assert { + Command::cargo_bin("matcha") + .unwrap() + .current_dir(dir) + .args(["create", kind, name]) + .assert() +} + +#[test] +fn create_step_keeps_camel_case_in_the_token_and_reads_kebab_input() { + let d = tempdir().unwrap(); + seed_module(d.path()); + create(d.path(), "step", "current-user").success(); + let step = std::fs::read_to_string(d.path().join("src/steps/currentuser.step.ts")).unwrap(); + assert!(step.contains("class CurrentUserStep"), "{step}"); + assert!(step.contains("provides: 'currentUser'"), "{step}"); + assert!(step.contains("return { currentUser: null }"), "{step}"); +} + +#[test] +fn create_refuses_a_token_core_already_provides() { + let d = tempdir().unwrap(); + seed_module(d.path()); + create(d.path(), "provider", "Logger") + .failure() + .stderr(predicates::str::contains("core already provides")); + create(d.path(), "step", "req").failure(); + assert!(!d.path().join("src/providers/logger.provider.ts").exists()); +} + +#[test] +fn create_refuses_a_name_that_cannot_be_a_class() { + let d = tempdir().unwrap(); + seed_module(d.path()); + create(d.path(), "controller", "2fast").failure(); + create(d.path(), "controller", "us.ers").failure(); +} + +#[test] +fn create_does_not_overwrite_an_existing_file() { + let d = tempdir().unwrap(); + seed_module(d.path()); + create(d.path(), "controller", "Users").success(); + let file = d.path().join("src/controllers/users.controller.ts"); + std::fs::write(&file, "// edited\n").unwrap(); + create(d.path(), "controller", "Users") + .failure() + .stderr(predicates::str::contains("already exists")); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "// edited\n"); +}