Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04a45a7765 | ||
|
|
87cf3eac82 | ||
|
|
88090f34a2 | ||
|
|
5c8f72b409 | ||
|
|
a3250da225 | ||
|
|
0a2713d377 | ||
|
|
827e6863ad | ||
|
|
8910fe22ee | ||
|
|
95b7b92fdf | ||
|
|
3e6fa7797b | ||
|
|
f88c11ac0b | ||
|
|
bee7580ab4 | ||
|
|
b8aac3bb6a | ||
|
|
88dd2035c4 | ||
|
|
dfba02a7ce | ||
|
|
cc943079a4 | ||
|
|
beaba7ce80 | ||
|
|
0427c89752 | ||
|
|
c9cad458bc | ||
|
|
7b632e5170 | ||
|
|
59004c4b5e | ||
|
|
17a3936733 | ||
|
|
a112235ca6 | ||
|
|
f77bd4d774 | ||
|
|
060f135eb4 | ||
|
|
756dbed5d9 | ||
|
|
6841a2102d | ||
|
|
112f8da22c | ||
|
|
274b40c13a | ||
|
|
03597499cd | ||
|
|
5ac79e91c0 | ||
|
|
787890e5c9 | ||
|
|
8c515a30a2 | ||
|
|
98394ceb8a | ||
|
|
3ad7ac0dea | ||
|
|
ee7eccc0de | ||
|
|
832fbbb943 | ||
|
|
ca27e31648 | ||
|
|
1b438278c6 | ||
|
|
78e7d9b15b | ||
|
|
e6ee9e84e8 | ||
|
|
1b5922c4de | ||
|
|
e8cd20b7ec | ||
|
|
c63c121787 | ||
|
|
a2610fa019 | ||
|
|
2f9b656692 | ||
|
|
65ecba05d1 | ||
|
|
0aee29478b | ||
|
|
4fe5b53e7f | ||
|
|
72e984d35c | ||
|
|
81af7c1c2a | ||
|
|
49909ed821 | ||
|
|
6de9b56b82 | ||
|
|
1cc6f35b90 | ||
|
|
8d31faa27e | ||
|
|
c382602ca7 | ||
|
|
7044e50982 | ||
|
|
dba24aa50a | ||
|
|
281e8ccc17 | ||
|
|
c5d874a360 | ||
|
|
75d7684636 | ||
|
|
fbb9282f7e | ||
|
|
eb392baf68 |
No files matched your search
@@ -1,79 +0,0 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
# Gitea's delete-asset API differs from GitHub's (it requires the release id in the
|
||||
# path), so softprops' delete-then-reupload 404s when re-releasing an existing tag.
|
||||
# Delete the whole release first so every run's uploads are fresh. Portable: the
|
||||
# get-by-tag + delete-by-id endpoints exist on both Gitea and GitHub, and deleting
|
||||
# first is harmless on GitHub (softprops just recreates it).
|
||||
prepare:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Delete existing release for this tag
|
||||
env:
|
||||
GT_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag="$GITHUB_REF_NAME"
|
||||
api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
|
||||
id=$(curl -sSL -H "Authorization: token $GT_TOKEN" "$api/releases/tags/$tag" \
|
||||
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
|
||||
if [ -n "${id:-}" ]; then
|
||||
echo "deleting existing release id=$id for $tag"
|
||||
curl -sS -X DELETE -H "Authorization: token $GT_TOKEN" "$api/releases/$id" || true
|
||||
else
|
||||
echo "no existing release for $tag — nothing to delete"
|
||||
fi
|
||||
|
||||
build:
|
||||
needs: prepare
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: aarch64-apple-darwin
|
||||
os: macos-14
|
||||
- target: x86_64-apple-darwin
|
||||
os: macos-14
|
||||
- target: x86_64-unknown-linux-musl
|
||||
os: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Add target + musl tooling
|
||||
run: |
|
||||
rustup target add ${{ matrix.target }}
|
||||
if [ "${{ matrix.target }}" = "x86_64-unknown-linux-musl" ]; then
|
||||
sudo apt-get update && sudo apt-get install -y musl-tools
|
||||
fi
|
||||
|
||||
- name: Build
|
||||
run: cargo build --release --locked --target ${{ matrix.target }}
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
TAR="matcha-${{ matrix.target }}.tar.gz"
|
||||
tar -czf "$TAR" -C "target/${{ matrix.target }}/release" matcha
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "$TAR" > "$TAR.sha256"
|
||||
else
|
||||
shasum -a 256 "$TAR" > "$TAR.sha256"
|
||||
fi
|
||||
|
||||
- name: Upload to release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |
|
||||
matcha-${{ matrix.target }}.tar.gz
|
||||
matcha-${{ matrix.target }}.tar.gz.sha256
|
||||
@@ -0,0 +1,103 @@
|
||||
name: CI
|
||||
|
||||
# Rust gate. Lives in .github/workflows so both Gitea and GitHub run it.
|
||||
on:
|
||||
pull_request:
|
||||
branches: [develop, main]
|
||||
push:
|
||||
branches: [develop, main]
|
||||
# Weekly, so a core release that breaks the starter or leaves the pin behind
|
||||
# shows up here rather than in somebody's `matcha new`.
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- name: Add clippy + rustfmt
|
||||
run: rustup component add clippy rustfmt
|
||||
- run: cargo fmt --check
|
||||
- run: cargo clippy --all-targets -- -D warnings
|
||||
- run: cargo test --locked
|
||||
|
||||
# `cargo test` proves the CLI writes the files it means to write. It cannot
|
||||
# prove those files describe a project the current @green-tea/core will run —
|
||||
# which is how the templates sat two core releases behind for two months with
|
||||
# a green build the whole time. This job scaffolds, installs, type-checks,
|
||||
# boots and introspects a real starter, per runtime.
|
||||
starter:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runtime: [node, deno, bun, edge]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- run: cargo build
|
||||
- name: Install Deno
|
||||
if: matrix.runtime == 'deno'
|
||||
run: |
|
||||
curl -fsSL https://deno.land/install.sh | sh -s -- --yes
|
||||
echo "$HOME/.deno/bin" >> "$GITHUB_PATH"
|
||||
- name: Install Bun
|
||||
if: matrix.runtime == 'bun'
|
||||
run: |
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
echo "$HOME/.bun/bin" >> "$GITHUB_PATH"
|
||||
- run: scripts/starter-smoke.sh ${{ matrix.runtime }}
|
||||
|
||||
# The pin in src/template.rs is exact because core is prerelease-only and no
|
||||
# caret range can move off its first matching prerelease. Exact pins go stale
|
||||
# silently, so this is the thing that notices. Scheduled only: a core release
|
||||
# should nag on Monday, not redden an unrelated pull request.
|
||||
core-freshness:
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Compare the scaffold pin against the beta dist-tag
|
||||
run: |
|
||||
pinned=$(grep -oP 'CORE_VERSION: &str = "\K[^"]+' src/template.rs)
|
||||
latest=$(npm view @green-tea/core dist-tags.beta)
|
||||
echo "pinned=$pinned latest=$latest"
|
||||
if [ "$pinned" != "$latest" ]; then
|
||||
echo "::error::matcha scaffolds @green-tea/core@$pinned but the beta tag is $latest."
|
||||
echo "Bump CORE_VERSION in src/template.rs and let the starter job prove it still boots."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# install.sh has had a test since the installer landed, and no workflow ever
|
||||
# ran it. It exercises the script against a file:// fixture — no network — and
|
||||
# checks both halves that matter: a good archive installs, and a bad checksum
|
||||
# aborts without leaving a binary behind.
|
||||
installer:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-14]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Lint the installer
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: |
|
||||
# GitHub's hosted image ships shellcheck. The act image Gitea's
|
||||
# `ubuntu-latest` maps to (catthehacker/ubuntu:act-22.04) does not, so
|
||||
# bare `shellcheck` was a step that passed on one forge and failed on
|
||||
# the other — the exact forge-dependent break this file's own header
|
||||
# comment exists to avoid.
|
||||
if ! command -v shellcheck >/dev/null; then
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
|
||||
fi
|
||||
shellcheck install.sh test_install.sh
|
||||
- run: ./test_install.sh
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Promote → GitHub
|
||||
|
||||
# Runs on GITEA ONLY. Mirrors only main + version tags to the public GitHub repo.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
push-github:
|
||||
if: ${{ github.server_url != 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Push main + tags to GitHub
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }}
|
||||
run: |
|
||||
git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/matcha.git"
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
git push github "refs/tags/${{ github.ref_name }}"
|
||||
else
|
||||
git push github "HEAD:refs/heads/main"
|
||||
git push github --tags
|
||||
fi
|
||||
@@ -0,0 +1,195 @@
|
||||
name: Release
|
||||
|
||||
# On a version tag: build cross-platform binaries and attach them to the release (on
|
||||
# whichever forge fired — the release API calls are portable). ADDITIONALLY, on GitHub
|
||||
# only (production), publish the crate to crates.io.
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
# Gitea's delete-asset API differs from GitHub's (it requires the release id in the
|
||||
# path), so softprops' delete-then-reupload 404s when re-releasing an existing tag.
|
||||
# Delete the whole release first so every run's uploads are fresh. Portable: the
|
||||
# get-by-tag + delete-by-id endpoints exist on both Gitea and GitHub, and deleting
|
||||
# first is harmless on GitHub (softprops just recreates it).
|
||||
prepare:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Delete existing release for this tag
|
||||
env:
|
||||
GT_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag="$GITHUB_REF_NAME"
|
||||
api="$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
|
||||
id=$(curl -sSL -H "Authorization: token $GT_TOKEN" "$api/releases/tags/$tag" \
|
||||
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
|
||||
if [ -n "${id:-}" ]; then
|
||||
echo "deleting existing release id=$id for $tag"
|
||||
curl -sS -X DELETE -H "Authorization: token $GT_TOKEN" "$api/releases/$id" || true
|
||||
else
|
||||
echo "no existing release for $tag — nothing to delete"
|
||||
fi
|
||||
|
||||
build:
|
||||
needs: prepare
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- target: aarch64-apple-darwin
|
||||
os: macos-14
|
||||
- target: x86_64-apple-darwin
|
||||
os: macos-14
|
||||
- target: x86_64-unknown-linux-musl
|
||||
os: ubuntu-latest
|
||||
- target: aarch64-unknown-linux-musl
|
||||
os: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Add target
|
||||
run: rustup target add ${{ matrix.target }}
|
||||
|
||||
# Both Linux targets go through zig rather than through apt's musl-tools.
|
||||
# `tree-sitter` and `tree-sitter-typescript` compile C with the `cc` crate,
|
||||
# so `rustup target add` alone cannot produce an aarch64 binary — a real
|
||||
# cross C toolchain is required, and Ubuntu ships none for aarch64 musl.
|
||||
# zig is one, for both arches, which is also why the x86_64 leg moved onto
|
||||
# it: one toolchain for Linux beats a working one plus a second one.
|
||||
- name: Install zig cross toolchain
|
||||
if: contains(matrix.target, 'linux')
|
||||
run: |
|
||||
# `--break-system-packages` is required from pip 23 (PEP 668) and is an
|
||||
# unknown flag before it, so try the plain form first.
|
||||
python3 -m pip install --user ziglang \
|
||||
|| python3 -m pip install --user --break-system-packages ziglang
|
||||
cargo install --locked cargo-zigbuild
|
||||
|
||||
- name: Build (Linux, cross via zig)
|
||||
if: contains(matrix.target, 'linux')
|
||||
run: cargo zigbuild --release --locked --target ${{ matrix.target }}
|
||||
|
||||
- name: Build (macOS)
|
||||
if: contains(matrix.target, 'darwin')
|
||||
run: cargo build --release --locked --target ${{ matrix.target }}
|
||||
|
||||
# Run the artifact wherever the runner can actually execute it, and say so
|
||||
# where it cannot. A binary that links and will not start is the failure a
|
||||
# release pipeline must not leave for a user's terminal to find.
|
||||
#
|
||||
# A matching architecture always can. An x86_64 macOS binary on the arm64
|
||||
# macOS runners can too — through Rosetta, which is a system component
|
||||
# shared by every user on the host, so the runner account inherits it. It
|
||||
# is probed rather than assumed: a hosted runner may not have it, and a
|
||||
# smoke that hard-failed there would block a release over the runner's
|
||||
# configuration rather than over the binary.
|
||||
#
|
||||
# Across the two forges that leaves nothing unexecuted. Gitea's
|
||||
# `ubuntu-latest` is arm64 Linux (containers in a colima VM on the macOS
|
||||
# host), so it runs the aarch64 binary; GitHub's is x86_64 and runs the
|
||||
# other. Both macOS binaries run on either forge's arm64 macOS runner.
|
||||
- name: Smoke the binary
|
||||
shell: bash
|
||||
run: |
|
||||
target='${{ matrix.target }}'
|
||||
arch='${{ runner.arch }}'
|
||||
bin="./target/$target/release/matcha"
|
||||
runnable=no
|
||||
case "$target:$arch" in
|
||||
aarch64-*:ARM64|x86_64-*:X64) runnable=yes ;;
|
||||
x86_64-apple-darwin:ARM64)
|
||||
# An `if` rather than `[ … ] && …`: under `set -e` the AND-list's
|
||||
# failure is the case branch's exit status, and whether that ends
|
||||
# the step is a subtlety of the shell rather than a decision. A
|
||||
# missing Rosetta must skip the smoke, never fail the release.
|
||||
if [ -d /Library/Apple/usr/libexec/oah ]; then runnable=yes; fi ;;
|
||||
esac
|
||||
if [ "$runnable" = yes ]; then
|
||||
"$bin" --version
|
||||
else
|
||||
echo "::notice::smoke skipped: this $arch runner cannot execute $target"
|
||||
fi
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
TAR="matcha-${{ matrix.target }}.tar.gz"
|
||||
tar -czf "$TAR" -C "target/${{ matrix.target }}/release" matcha
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "$TAR" > "$TAR.sha256"
|
||||
else
|
||||
shasum -a 256 "$TAR" > "$TAR.sha256"
|
||||
fi
|
||||
|
||||
- name: Upload to release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
# A tag with a hyphen is a prerelease (26.9.0-beta.1). Unflagged, it
|
||||
# would answer /releases/latest — which is what install.sh resolves
|
||||
# with no MATCHA_VERSION — so the first stable release would be
|
||||
# displaced by the next beta published after it.
|
||||
prerelease: ${{ contains(github.ref_name, '-') }}
|
||||
files: |
|
||||
matcha-${{ matrix.target }}.tar.gz
|
||||
matcha-${{ matrix.target }}.tar.gz.sha256
|
||||
|
||||
# Guarantees the arm64 Linux binary is executed before it reaches anyone.
|
||||
#
|
||||
# The `Smoke the binary` step above runs each artifact only where the runner
|
||||
# can, which depends on what `ubuntu-latest` resolves to on the forge that
|
||||
# fired — so whether the aarch64 Linux binary gets started is a property of the
|
||||
# runner pool rather than of the pipeline. This job removes that dependency:
|
||||
# it pins an arm64 Linux runner, so the answer is the same on every release.
|
||||
#
|
||||
# GitHub offers such runners and Gitea does not, and a job pinned to a label a
|
||||
# forge lacks would queue there forever — hence the same `server_url` guard
|
||||
# `publish-crate` below already uses, which skips the job before a runner is
|
||||
# ever looked for.
|
||||
#
|
||||
# It goes through `install.sh` rather than running the binary directly, so the
|
||||
# same job also covers the installer's arm64 branch and its checksum
|
||||
# verification against the release assets exactly as a user receives them.
|
||||
verify-linux-arm64:
|
||||
needs: build
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install the published arm64 binary and run it
|
||||
run: |
|
||||
set -eu
|
||||
test "$(uname -m)" = aarch64 || { echo "expected an arm64 runner, got $(uname -m)"; exit 1; }
|
||||
MATCHA_VERSION="$GITHUB_REF_NAME" MATCHA_INSTALL_DIR="$PWD/.bin" sh ./install.sh
|
||||
"$PWD/.bin/matcha" --version
|
||||
"$PWD/.bin/matcha" --help > /dev/null
|
||||
|
||||
# crates.io = production only.
|
||||
# crates.io = production only, via OIDC Trusted Publishing (no CARGO_TOKEN).
|
||||
# Requires a trusted publisher configured on crates.io (Expressive-Tea/matcha, release.yml).
|
||||
publish-crate:
|
||||
if: ${{ github.server_url == 'https://github.com' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
# Exchanges the OIDC id-token for a short-lived crates.io token.
|
||||
- uses: rust-lang/crates-io-auth-action@v1
|
||||
id: auth
|
||||
- name: cargo publish
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
|
||||
run: cargo publish --locked
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to `matcha-cli` are documented here.
|
||||
|
||||
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
matcha uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, matching
|
||||
green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8 does not
|
||||
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.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **`matcha graph` and `matcha explain <pattern>`.** green-tea derives execution order from
|
||||
what each node declares it `needs` and `provides`, which makes the graph a real artifact
|
||||
rather than a diagram someone drew — and the CLI could not draw any of it, though
|
||||
`toMermaid`, `toDOT`, `graph` and `explain` had been exported all along. `graph` prints
|
||||
Mermaid, Graphviz DOT or the raw `GraphView` (`--format`, `--out`); `explain` prints one
|
||||
route's chain in execution order with each node's needs and provides.
|
||||
|
||||
Both import the app and call `app.ready()`, which resolves the graph and is documented as
|
||||
deliberately *not* running provider factories — asking for a diagram must not open your
|
||||
database connections. `explain` takes the route pattern as declared (`/users/:id`, not
|
||||
`/users/42`), and a miss lists the patterns that are registered.
|
||||
|
||||
- **`matcha doctor`** — the misconfigurations that fail confusingly rather than loudly:
|
||||
`experimentalDecorators` missing, which turns every `@Route` into a syntax error that
|
||||
blames the decorator; a core pin that cannot resolve, or that does not match what is
|
||||
installed; an entry that does not export `app`; and `@Ws` or multipart routes whose
|
||||
lazy-loaded peer dependency is absent, which compile and then fail at the first request.
|
||||
Every check is a file read — no runtime spawned, nothing fetched — so it works before the
|
||||
project installs. Exits non-zero on a failure.
|
||||
|
||||
- **`matcha new --runtime edge`** — 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 three runtimes and `/zen` the
|
||||
same stream from the worker. `matcha run` is `wrangler dev`, which boots real workerd, so
|
||||
edge stops being a deploy-only target. Detection puts `wrangler.toml` ahead of
|
||||
`package.json`, since an edge project has both.
|
||||
|
||||
Core is installed from **JSR** on this runtime alone. 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` from npm throws before any of its own code runs
|
||||
([green-tea#93](https://github.com/Expressive-Tea/green-tea/issues/93)). The scaffolded
|
||||
`.npmrc` says so; it and the alias can both go once that is fixed.
|
||||
|
||||
- **`matcha add ws` and `matcha add upload`**, and **`--controller <path>`**. `add` used to
|
||||
refuse outright when a project had more than one controller; it still declines to guess,
|
||||
but it lists the candidates and the flag picks. Both new capabilities name the optional
|
||||
peer dependency they need on success — core lazy-requires `ws` and `busboy`, so a missing
|
||||
one is an error at the first request rather than at boot, and the moment to mention it is
|
||||
when the handler is written.
|
||||
|
||||
- **`scripts/starter-smoke.sh`** — scaffolds, installs, type-checks, boots, curls `/` and the
|
||||
`/zen` stream, introspects, and adds every capability, per runtime. CI runs it on a matrix
|
||||
of all four, and a weekly job fails when the scaffold's core pin falls behind the `beta`
|
||||
dist-tag.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The scaffold composes its graph in `src/app.ts`.** `src/main.ts` now holds only the
|
||||
runtime's serve call and imports the app from it. The split is what lets `graph`, `explain`
|
||||
and `doctor` read an application without binding a port. `create module` follows, preferring
|
||||
`src/app.ts` and falling back to `src/main.ts` so projects scaffolded before the split keep
|
||||
working.
|
||||
|
||||
- **`add sse` generates a resumable stream.** The stub predates green-tea 26.9: it yielded
|
||||
bare values, so an `EventSource` reconnect restarted the iterable from its beginning and
|
||||
lost the gap in silence. It now tags each event with `sse(data, { id })` and reads
|
||||
`@header('last-event-id')` to resume from it.
|
||||
|
||||
- **`add buffer` demonstrates `@Transformer`.** It used to return `Buffer.from('hello')`,
|
||||
which is not what the capability's name means — "buffer" is the *transport*, the whole
|
||||
response at once — and never worked: `TransformerFn` returns `body: string` and the default
|
||||
`JsonTransformer` is `JSON.stringify`, so the route answered
|
||||
`{"type":"Buffer","data":[104,...]}`. It now shapes a `text/csv` response through the
|
||||
extension point that actually governs one.
|
||||
|
||||
- **Types in a decorated signature are imported with `import type`.** `wire`'s import
|
||||
handling became type-aware in both directions: merging a value symbol into an
|
||||
`import type` line would erase the decorator at runtime, and merging a type into a value
|
||||
line is TS1272 under `isolatedModules` with `emitDecoratorMetadata` — which node's and
|
||||
bun's `tsc` accept and Deno rejects, so the same generated handler compiled on two runtimes
|
||||
and failed on the third.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The scaffold no longer pins `@green-tea/core` two releases behind.** Every runtime
|
||||
overlay carried `^26.7.0-beta.0`. Core is prerelease-only, and npm's semver excludes a
|
||||
prerelease from any range whose comparators carry a different `major.minor.patch` — so that
|
||||
caret was not a loose pin but a pin to the oldest matching prerelease that nothing could
|
||||
move off. Every project `matcha new` produced since July installed 26.7.0-beta.0 and could
|
||||
not upgrade to it: no logger, no request budget, no resumable `@Sse` id, and none of the
|
||||
crashes 26.9 fixed. The pin is exact now, lives in one `CORE_VERSION` constant, and the
|
||||
scaffold is on **26.9.0-beta.1**.
|
||||
|
||||
- **The Deno scaffold resolves core through JSR** rather than `npm:`. JSR is core's native
|
||||
path for Deno and the one green-tea 26.9 repaired; the npm build's `createRequire` banner
|
||||
never existed there, which is what used to break `@Html` and multipart at boot.
|
||||
|
||||
- **The bun scaffold type-checks.** Its `tsconfig.json` declared no Bun types, so `Bun.serve`
|
||||
was `TS2868: Cannot find name 'Bun'` — meaning `tsc --noEmit`, and therefore
|
||||
`matcha create --check`, failed on every bun project the CLI has ever scaffolded.
|
||||
|
||||
- **A prebuilt binary for Linux arm64.** The installer used to refuse that platform and
|
||||
send you to `cargo install --git` — so Graviton, a Raspberry Pi, an ARM CI runner and
|
||||
Docker on Apple Silicon all needed a Rust toolchain. `rustup target add` alone could
|
||||
never have produced it: `tree-sitter` and `tree-sitter-typescript` compile C through the
|
||||
`cc` crate, and Ubuntu ships no aarch64 musl cross compiler. Both Linux targets now build
|
||||
through zig, which is one, so the arch that was missing and the arch that worked share a
|
||||
toolchain instead of having two.
|
||||
|
||||
Each release job also runs the binary it just built, wherever the runner can execute it —
|
||||
a binary that links and will not start is the failure a release pipeline must not leave
|
||||
for a user's terminal to find. Both macOS binaries run on the arm64 macOS runner, the
|
||||
Intel one through Rosetta, which is probed rather than assumed since a runner without it
|
||||
would otherwise fail a release over its own configuration; and each Linux binary runs wherever
|
||||
`ubuntu-latest` resolves to its architecture. Because that last part depends on the
|
||||
runner pool rather than on the pipeline, a separate job pins an arm64 Linux runner and
|
||||
installs the published binary there through `install.sh` — so the arm64 artifact is
|
||||
started before it reaches anyone, on every release, and the installer's arm64 branch and
|
||||
checksum verification are exercised against the real assets on the way.
|
||||
|
||||
- **`install.sh` resolves `latest` without the release API.** The API is rate-limited to
|
||||
60 requests an hour per IP unauthenticated — an office behind one NAT or a CI runner
|
||||
burns through it — and a throttled response carries no `tag_name`, so the installer
|
||||
failed with "could not resolve latest release tag" and no hint of the cause. It now
|
||||
follows the `/releases/latest` redirect, which has no such limit and which Gitea
|
||||
implements the same way, keeping the API as the fallback for the wget path. The error
|
||||
that remains names the rate limit and points at `MATCHA_VERSION`.
|
||||
|
||||
- **A beta release is flagged as a prerelease.** Nothing set the flag, so every beta
|
||||
answered `/releases/latest` — which is what `install.sh` resolves when no
|
||||
`MATCHA_VERSION` is given. Harmless while every release is a beta, and wrong the moment
|
||||
a stable one exists: the next beta published after it would displace it for everyone
|
||||
installing with the default.
|
||||
|
||||
- **CI runs `test_install.sh`.** It has existed since the installer landed and no workflow
|
||||
ever ran it. It now runs on Linux and macOS, with `shellcheck` alongside, and covers a
|
||||
third case: an unresolvable `latest` must explain itself and install nothing.
|
||||
|
||||
- **`MIT` is a file, not just a manifest field.** `Cargo.toml` declared `license = "MIT"` and
|
||||
the published crate carried no license text. Added along with the `DCO` the README has been
|
||||
requiring sign-off against, and a `CONTRIBUTING.md` saying how.
|
||||
|
||||
## [26.8.0-beta.0] - 2026-08-07
|
||||
|
||||
### Added
|
||||
|
||||
- Publishing to crates.io via OIDC Trusted Publishing — no token in CI.
|
||||
|
||||
### Changed
|
||||
|
||||
- The crate is `matcha-cli` on crates.io (the name `matcha` was taken); the installed binary
|
||||
stays `matcha`, so `cargo install matcha-cli` still gives you `matcha`. Two-forge CI/CD:
|
||||
Gitea is origin, GitHub is the public mirror that release tags are promoted to.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The README's install paths point at hosts that actually resolve.
|
||||
|
||||
## [26.7.0] - 2026-07-13
|
||||
|
||||
First tagged release. A single native binary, no JS runtime needed to install it.
|
||||
|
||||
### Added
|
||||
|
||||
- **`matcha new`** — scaffolds from an embedded starter that is alive on first boot: it serves
|
||||
an `index.html` and streams a rotating zen message over `@Sse('/zen')`. `--runtime` picks
|
||||
node (the default), deno or bun through a shared template plus a per-runtime overlay;
|
||||
`--template-url` scaffolds from any git template, with a `gh:owner/repo` shorthand.
|
||||
- **`matcha run`** — detects the runtime and spawns it in watch mode. Precedence, first match
|
||||
wins: `matcha.toml`, then `deno.json`, then a bun lockfile, then `package.json`.
|
||||
- **`matcha create <controller|step|provider|module>`** — generates the piece and wires it in
|
||||
with tree-sitter: imports merge into an existing brace rather than adding a second binding
|
||||
for the same module, and an edit that would break the file's syntax reverts itself instead
|
||||
of being written. `--check` type-checks afterwards with the project's own runtime.
|
||||
- **`matcha add <sse|stream|buffer>`** — appends a capability handler to the controller,
|
||||
idempotent per capability.
|
||||
- **A `curl | sh` installer** with sha256 verification, and cross-platform binaries attached
|
||||
to each release.
|
||||
|
||||
[Unreleased]: https://github.com/Expressive-Tea/matcha/compare/v26.8.0-beta.0...HEAD
|
||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/matcha/compare/v26.7.0...v26.8.0-beta.0
|
||||
[26.7.0]: https://github.com/Expressive-Tea/matcha/releases/tag/v26.7.0
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# Contributing to matcha
|
||||
|
||||
matcha is the [green-tea](https://github.com/Expressive-Tea/green-tea) CLI. It is open
|
||||
source, but nobody pushes directly — changes land through reviewed pull requests with a
|
||||
**DCO sign-off**.
|
||||
|
||||
## Where to send your changes
|
||||
|
||||
Development happens on a private Gitea instance. **GitHub is a downstream mirror**: the
|
||||
promote workflow pushes `main` and version tags to it and nothing else, so there is no
|
||||
`develop` there and no long-lived branch for contributions.
|
||||
|
||||
**From GitHub:** open your pull request against `main` and say in the description that it
|
||||
is a contribution rather than a release. A maintainer carries the commits upstream into
|
||||
Gitea's `develop` with your authorship and your sign-off intact, and the change reaches
|
||||
GitHub again through the normal promotion. Nothing is merged into the GitHub `main`
|
||||
directly — that would put the two forges out of sync and break the next release push.
|
||||
|
||||
**From Gitea, if you have access:** follow the branch model below.
|
||||
|
||||
## Developer Certificate of Origin (DCO)
|
||||
|
||||
We use the [Developer Certificate of Origin](./DCO) instead of a CLA — a per-commit
|
||||
affirmation that you have the right to submit your work under this project's license. No
|
||||
copyright assignment, no paperwork.
|
||||
|
||||
**Every commit must be signed off:**
|
||||
|
||||
```bash
|
||||
git commit -s -m "fix(wire): keep a type import out of the value brace"
|
||||
```
|
||||
|
||||
That appends `Signed-off-by: Your Name <your@email>`, which has to match your commit
|
||||
author. Forgot it on the last commit:
|
||||
|
||||
```bash
|
||||
git commit --amend -s
|
||||
git push --force-with-lease
|
||||
```
|
||||
|
||||
## Working with AI assistance
|
||||
|
||||
Use one if it helps. There is no permission to ask for and nothing to declare.
|
||||
|
||||
What we do ask is that you read what it hands you before it becomes a pull request. Every
|
||||
line here is reviewed by a person, by hand, and usually that person is one person. A diff
|
||||
its own author has not read moves that work onto them and turns review into proofreading,
|
||||
which is the thing review is worst at.
|
||||
|
||||
**What assistants tend to get wrong in this repository in particular:**
|
||||
|
||||
- **They test the CLI instead of its output.** `cargo test` proves matcha writes the files
|
||||
it means to write. It cannot prove those files describe a project that runs. That gap is
|
||||
why the templates sat two core releases behind for two months with a green build.
|
||||
`scripts/starter-smoke.sh` is the check that closes it; run it for the runtime you touched.
|
||||
- **They write for Node and assume the rest follows.** matcha scaffolds for node, deno, bun
|
||||
and the edge, and the four differ in ways that bite. A generated handler that compiles
|
||||
under `tsc` can still be TS1272 under Deno's `isolatedModules` + `emitDecoratorMetadata`.
|
||||
- **They reach for a crate.** matcha has four dependencies and reads TOML and JSON with
|
||||
line scans on purpose. A new dependency for a value that is always written one per line
|
||||
is not a trade worth making.
|
||||
- **They pin `@green-tea/core` with a caret.** Core is prerelease-only, and npm excludes a
|
||||
prerelease from any range whose comparators carry a different `major.minor.patch`. A
|
||||
caret there is a pin to the oldest matching prerelease that nothing can move off. There
|
||||
is a test for this.
|
||||
- **They delete comments they read as redundant.** A comment here usually carries reasoning
|
||||
the code cannot show on its own — why a marker is a route literal rather than a decorator
|
||||
name, why the edge scaffold installs from JSR.
|
||||
|
||||
**Where you are unsure, say so** — not as a disclosure, as a pointer. "I did not run the
|
||||
bun leg" tells a reviewer where to spend their attention.
|
||||
|
||||
None of this changes the sign-off. `Signed-off-by` says you have the right to submit the
|
||||
work under this project's license, and that stays true however the text was produced.
|
||||
|
||||
## Branch model (GitFlow)
|
||||
|
||||
- `main` — production-ready, protected. No direct pushes. Tags are cut here.
|
||||
- `develop` — active development, protected. Feature branches merge here.
|
||||
- `feature/<name>` — branch from `develop`.
|
||||
- `hotfix/<name>` — branch from `main`.
|
||||
- `release/<version>` — release stabilization.
|
||||
|
||||
## Commits
|
||||
|
||||
Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `fix:`,
|
||||
`chore:`, `docs:`, `test:`, `refactor:`, `ci:`. Focus the message on the *why*. Do not add
|
||||
AI co-authoring attribution.
|
||||
|
||||
Anything user-visible gets a `CHANGELOG.md` entry under `## [Unreleased]`, in the same
|
||||
voice as the entries around it: what changed, and what it was before.
|
||||
|
||||
## Local setup
|
||||
|
||||
A stable Rust toolchain is all that is required to build and test the CLI:
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
cargo test
|
||||
```
|
||||
|
||||
The starter smoke needs the runtime it exercises — node, deno, bun or wrangler (which
|
||||
`npm install` brings in for the edge scaffold). You are not expected to install all four to
|
||||
fix a typo; you are expected to run the one your change touches, and to say which in the
|
||||
pull request.
|
||||
|
||||
```bash
|
||||
cargo build
|
||||
scripts/starter-smoke.sh node # also: deno, bun, edge
|
||||
```
|
||||
|
||||
It scaffolds into a temp directory, installs, type-checks, boots, curls `/` and the `/zen`
|
||||
stream, runs `matcha graph`/`explain`, then adds every `matcha add` capability and
|
||||
type-checks them together. It picks a random high port, so it does not collide with a
|
||||
server you already have running; `PORT=4567 scripts/starter-smoke.sh node` overrides.
|
||||
|
||||
## Before you open a pull request
|
||||
|
||||
Run what CI runs:
|
||||
|
||||
```bash
|
||||
cargo fmt --check
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test --locked
|
||||
scripts/starter-smoke.sh <the runtime you touched>
|
||||
```
|
||||
|
||||
CI runs the smoke for all four runtimes on a matrix, plus a weekly `core-freshness` job
|
||||
that fails when `CORE_VERSION` in `src/template.rs` falls behind core's `beta` dist-tag.
|
||||
|
||||
**Non-trivial logic leaves a check behind.** Not a suite — the smallest thing that fails if
|
||||
the logic breaks. A generator gets a test that the generated code carries what it must; a
|
||||
parser gets a test for the case that motivated it.
|
||||
|
||||
## Reporting issues
|
||||
|
||||
Bugs and feature requests go to
|
||||
[GitHub issues](https://github.com/Expressive-Tea/matcha/issues). A report that says what
|
||||
you ran, what you expected, and what happened — with the runtime and the matcha version
|
||||
from `matcha --version` — is worth several that do not.
|
||||
|
||||
Defects in the framework itself belong in the
|
||||
[green-tea repository](https://github.com/Expressive-Tea/green-tea/issues), not here.
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Be decent. Assume good faith, keep criticism about the code, and take the hint when someone
|
||||
asks you to drop it.
|
||||
Generated
+2
-2
@@ -253,8 +253,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "matcha"
|
||||
version = "26.7.0"
|
||||
name = "matcha-cli"
|
||||
version = "26.8.0-beta.0"
|
||||
dependencies = [
|
||||
"assert_cmd",
|
||||
"clap",
|
||||
|
||||
+7
-2
@@ -1,8 +1,13 @@
|
||||
[package]
|
||||
name = "matcha"
|
||||
version = "26.7.0"
|
||||
name = "matcha-cli"
|
||||
version = "26.8.0-beta.0"
|
||||
edition = "2021"
|
||||
description = "The green-tea CLI: scaffold a project, generate controllers, steps and providers already wired into their module, and run with your runtime detected. One native binary, no JS runtime needed to install it."
|
||||
license = "MIT"
|
||||
repository = "https://github.com/Expressive-Tea/matcha"
|
||||
|
||||
# The crate is `matcha-cli` on crates.io (the name `matcha` is taken), but the
|
||||
# installed binary stays `matcha` — `cargo install matcha-cli` gives you `matcha`.
|
||||
[[bin]]
|
||||
name = "matcha"
|
||||
path = "src/main.rs"
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
Developer Certificate of Origin
|
||||
Version 1.1
|
||||
|
||||
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
|
||||
1 Letterman Drive
|
||||
Suite D4700
|
||||
San Francisco, CA, 94129
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Developer's Certificate of Origin 1.1
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
(a) The contribution was created in whole or in part by me and I
|
||||
have the right to submit it under the open source license
|
||||
indicated in the file; or
|
||||
|
||||
(b) The contribution is based upon previous work that, to the best
|
||||
of my knowledge, is covered under an appropriate open source
|
||||
license and I have the right under that license to submit that
|
||||
work with modifications, whether created in whole or in part
|
||||
by me, under the same open source license (unless I am
|
||||
permitted to submit under a different license), as indicated
|
||||
in the file; or
|
||||
|
||||
(c) The contribution was provided directly to me by some other
|
||||
person who certified (a), (b) or (c) and I have not modified
|
||||
it.
|
||||
|
||||
(d) I understand and agree that this project and the contribution
|
||||
are public and that a record of the contribution (including all
|
||||
personal information I submit with it, including my sign-off) is
|
||||
maintained indefinitely and may be redistributed consistent with
|
||||
this project or the open source license(s) involved.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 green-tea contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,24 +1,34 @@
|
||||
# matcha
|
||||
|
||||
The [green-tea](https://git.svc.zoit.services/Green-Tea/core) CLI — scaffold, run, and generate green-tea apps from a single native binary. No JS runtime required to install or operate.
|
||||
The [green-tea](https://github.com/Expressive-Tea/green-tea) CLI — scaffold, run, and generate green-tea apps from a single native binary. No JS runtime required to install or operate.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.svc.zoit.services/Green-Tea/matcha/raw/branch/main/install.sh | sh
|
||||
cargo install matcha-cli
|
||||
```
|
||||
|
||||
Installs a prebuilt binary to `~/.local/bin` — no Rust required. Env vars go on
|
||||
the `sh` side of the pipe:
|
||||
Builds from [crates.io](https://crates.io/crates/matcha-cli) and installs the `matcha`
|
||||
binary. Needs a Rust toolchain; takes a few seconds.
|
||||
|
||||
**Prebuilt binary** (no Rust), from the latest GitHub release:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Expressive-Tea/matcha/main/install.sh | sh
|
||||
```
|
||||
|
||||
Drops the binary in `~/.local/bin`. Prebuilt for macOS (arm64, x86_64) and Linux
|
||||
(arm64, x86_64), statically linked against musl so any distro works, Alpine
|
||||
included. Env vars go on the `sh` side of the pipe:
|
||||
|
||||
```bash
|
||||
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
|
||||
```
|
||||
|
||||
**From source** (requires Rust — compiles and installs):
|
||||
**From git** (compiles the default branch):
|
||||
|
||||
```bash
|
||||
cargo install --git https://git.svc.zoit.services/Green-Tea/matcha
|
||||
cargo install --git https://github.com/Expressive-Tea/matcha
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -28,7 +38,11 @@ matcha new my-api # scaffold from the official starter
|
||||
matcha new my-api --template-url gh:owner/repo # scaffold from any git template
|
||||
matcha run # detect node/deno/bun and run in watch
|
||||
matcha create controller Users # generate + auto-wire into @Module
|
||||
matcha add sse # add a capability (sse|stream|buffer) to your controller
|
||||
matcha add sse # add a capability to your controller
|
||||
matcha graph # draw the dependency graph
|
||||
matcha explain /users/:id # one route's chain, in execution order
|
||||
matcha openapi # structural OpenAPI 3.1 for the route table
|
||||
matcha doctor # check the project for confusing misconfigurations
|
||||
```
|
||||
|
||||
### The starter
|
||||
@@ -37,6 +51,59 @@ matcha add sse # add a capability (sse|stream|buffer
|
||||
with the green-tea logo and streams a rotating zen message over `@Sse('/zen')`.
|
||||
Open the browser and it's already alive — `matcha run` boots it.
|
||||
|
||||
The graph is composed in `src/app.ts`, which exports the app; `src/main.ts`
|
||||
imports it and binds a port. The split is what lets `matcha graph` and
|
||||
`matcha explain` read your application without starting a server.
|
||||
|
||||
The `@green-tea/core` version is pinned exactly, not with a caret. Core is
|
||||
prerelease-only, and npm's semver excludes a prerelease from any range whose
|
||||
comparators carry a different `major.minor.patch` — so `^26.7.0-beta.0` never
|
||||
resolves past `26.7.0-beta.0` however many betas ship after it. CI scaffolds,
|
||||
installs, boots and introspects a real starter on every runtime, and a weekly
|
||||
job fails when the pin falls behind the `beta` dist-tag.
|
||||
|
||||
### Introspection
|
||||
|
||||
green-tea derives execution order from what each node declares it `needs` and
|
||||
`provides`, so the graph is a real artifact rather than a diagram someone drew.
|
||||
`matcha graph` prints it and `matcha explain` prints one route's slice of it.
|
||||
|
||||
```bash
|
||||
matcha graph # Mermaid (default)
|
||||
matcha graph --format dot # Graphviz
|
||||
matcha graph --format json # the raw GraphView
|
||||
matcha graph --out docs/graph.mmd # to a file instead of stdout
|
||||
matcha explain /users/:id # providers → steps → handler, with needs/provides
|
||||
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
|
||||
```
|
||||
|
||||
`openapi` is *structural*: green-tea derives paths, methods and parameters from
|
||||
the decorators, which is everything the graph knows. It does not invent response
|
||||
schemas, so the document describes the surface rather than the payloads.
|
||||
|
||||
Both import `src/app.ts` (override with `--entry`) and call `app.ready()`, which
|
||||
resolves the graph and deliberately does **not** run provider factories — asking
|
||||
for a diagram will not open your database connections. Your dependencies have to
|
||||
be installed, since this runs your code under your runtime.
|
||||
|
||||
`explain` takes the route **pattern** as declared, not a concrete URL:
|
||||
`/users/:id`, not `/users/42`. A miss lists the patterns that are registered.
|
||||
|
||||
### `add` capabilities
|
||||
|
||||
| | generates |
|
||||
|---|---|
|
||||
| `sse` | `@Sse` stream tagged with `sse(data, { id })`, reading `@header('last-event-id')` to resume |
|
||||
| `ws` | `@Ws` duplex handler: consume `@inbound()`, return a `channel()` — needs `ws` on Node |
|
||||
| `stream` | `@Stream` chunked response |
|
||||
| `upload` | `@Post` with `@body(): MultipartBody` — needs `busboy` |
|
||||
| `buffer` | `@Get` with a custom `@Transformer` shaping the whole response |
|
||||
|
||||
`matcha add <cap>` edits the only controller under `src/controllers`; with more
|
||||
than one it refuses and lists them, and `--controller <path>` picks. Repeats are
|
||||
no-ops. Both peer dependencies are lazy-loaded by core, so neither is needed to
|
||||
compile — only to serve the route.
|
||||
|
||||
### `create` / `add` auto-wiring
|
||||
|
||||
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
||||
@@ -44,16 +111,58 @@ 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
|
||||
`--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
|
||||
|
||||
`matcha run` picks the runtime by precedence, first match wins:
|
||||
|
||||
1. `matcha.toml` — `runtime = "node" | "deno" | "bun"`
|
||||
2. `deno.json` / `deno.jsonc` → **deno**
|
||||
3. `bun.lockb` / `bun.lock` → **bun**
|
||||
4. `package.json` → **node**
|
||||
1. `matcha.toml` — `runtime = "node" | "deno" | "bun" | "edge"`
|
||||
2. `wrangler.toml` / `wrangler.jsonc` → **edge**
|
||||
3. `deno.json` / `deno.jsonc` → **deno**
|
||||
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
|
||||
|
||||
```bash
|
||||
cargo test # unit + CLI integration
|
||||
scripts/starter-smoke.sh node # scaffold, install, type-check, boot, introspect
|
||||
scripts/starter-smoke.sh deno # (also bun, edge) — needs that runtime installed
|
||||
./test_install.sh # install.sh against a file:// fixture, no network
|
||||
```
|
||||
|
||||
`starter-smoke.sh` is the check that `cargo test` cannot be: `cargo test` proves
|
||||
the CLI writes the files it means to write, not that those files describe a
|
||||
project the current core will run.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+32
-10
@@ -1,14 +1,17 @@
|
||||
#!/bin/sh
|
||||
# matcha installer — downloads a prebuilt binary from Gitea Releases.
|
||||
# matcha installer — downloads a prebuilt binary from GitHub Releases.
|
||||
# curl -fsSL <raw>/install.sh | sh
|
||||
# Env: MATCHA_VERSION (tag, default latest), MATCHA_INSTALL_DIR (default ~/.local/bin),
|
||||
# MATCHA_REPO_BASE (default the Gitea repo URL).
|
||||
# MATCHA_REPO_BASE / MATCHA_API_BASE (override to install from the internal Gitea,
|
||||
# whose release API is GitHub-compatible for everything this script touches).
|
||||
set -eu
|
||||
|
||||
REPO_BASE="${MATCHA_REPO_BASE:-https://git.svc.zoit.services/Green-Tea/matcha}"
|
||||
# The API lives at the host root (/api/v1/...), NOT under the repo path. Keep it
|
||||
# separate from REPO_BASE (which is used for release DOWNLOAD urls under the repo).
|
||||
API_BASE="${MATCHA_API_BASE:-https://git.svc.zoit.services/api/v1/repos/Green-Tea/matcha}"
|
||||
# Public by default: the Gitea host is unreachable outside the network, and this script
|
||||
# is what crates.io and the README point people at.
|
||||
REPO_BASE="${MATCHA_REPO_BASE:-https://github.com/Expressive-Tea/matcha}"
|
||||
# The API lives on its own host, NOT under the repo path. Keep it separate from
|
||||
# REPO_BASE (which is used for release DOWNLOAD urls under the repo).
|
||||
API_BASE="${MATCHA_API_BASE:-https://api.github.com/repos/Expressive-Tea/matcha}"
|
||||
INSTALL_DIR="${MATCHA_INSTALL_DIR:-$HOME/.local/bin}"
|
||||
|
||||
err() { echo "matcha-install: $*" >&2; exit 1; }
|
||||
@@ -42,17 +45,36 @@ case "$os" in
|
||||
Linux)
|
||||
case "$arch" in
|
||||
x86_64|amd64) triple="x86_64-unknown-linux-musl" ;;
|
||||
arm64|aarch64) err "linux arm64 has no prebuilt binary yet — use: cargo install --git $REPO_BASE" ;;
|
||||
arm64|aarch64) triple="aarch64-unknown-linux-musl" ;;
|
||||
*) err "unsupported Linux arch: $arch" ;;
|
||||
esac ;;
|
||||
*) err "unsupported OS: $os — try: cargo install --git $REPO_BASE" ;;
|
||||
esac
|
||||
|
||||
# Resolving "latest" prefers the /releases/latest redirect over the release API.
|
||||
# The API is rate-limited to 60 requests an hour per IP unauthenticated, which an
|
||||
# office behind one NAT or a CI runner burns through — and when it trips, the
|
||||
# response carries no tag_name, so the old code failed with "could not resolve
|
||||
# latest release tag" and no hint of why. The redirect has no such limit and
|
||||
# Gitea implements it the same way. The API stays as the fallback, since that is
|
||||
# the path wget can follow without parsing headers.
|
||||
resolve_latest() {
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
effective=$(curl -fsSLI -o /dev/null -w '%{url_effective}' "$REPO_BASE/releases/latest" 2>/dev/null || true)
|
||||
case "$effective" in
|
||||
*/releases/tag/*) echo "${effective##*/}"; return 0 ;;
|
||||
esac
|
||||
fi
|
||||
fetch "$API_BASE/releases/latest" 2>/dev/null \
|
||||
| grep -o '"tag_name":[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4
|
||||
}
|
||||
|
||||
version="${MATCHA_VERSION:-latest}"
|
||||
if [ "$version" = "latest" ]; then
|
||||
tag=$(fetch "$API_BASE/releases/latest" \
|
||||
| grep -o '"tag_name":[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4)
|
||||
[ -n "$tag" ] || err "could not resolve latest release tag"
|
||||
tag=$(resolve_latest)
|
||||
[ -n "$tag" ] || err "could not resolve the latest release tag.
|
||||
The release API may be rate-limited (60/hour per IP without a token).
|
||||
Pin a version instead: curl -fsSL <raw>/install.sh | MATCHA_VERSION=v26.8.0-beta.0 sh"
|
||||
else
|
||||
tag="$version"
|
||||
fi
|
||||
|
||||
Executable
+105
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Scaffolds a starter with the matcha binary, installs it, type-checks it, boots
|
||||
# it, and asks it for its graph.
|
||||
#
|
||||
# This is the check the repository did not have. `cargo test` proves the CLI
|
||||
# writes the files it means to write; it cannot prove those files describe a
|
||||
# project the current `@green-tea/core` will run — which is exactly how the
|
||||
# templates sat two core releases behind for two months without a red build.
|
||||
#
|
||||
# Usage: scripts/starter-smoke.sh <node|deno|bun>
|
||||
set -euo pipefail
|
||||
|
||||
RUNTIME="${1:?usage: starter-smoke.sh <node|deno|bun|edge>}"
|
||||
MATCHA="${MATCHA:-$PWD/target/debug/matcha}"
|
||||
[ -x "$MATCHA" ] || { echo "no matcha binary at $MATCHA (cargo build first)" >&2; exit 2; }
|
||||
|
||||
case "$RUNTIME" in
|
||||
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) ;;
|
||||
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 ;;
|
||||
esac
|
||||
|
||||
# The starter hardcodes its port, so the script rewrites it to a free one rather
|
||||
# than colliding with whatever the person running this already has on 3000. A
|
||||
# check that only survives on a clean CI runner is a check nobody runs locally.
|
||||
PORT="${PORT:-$((20000 + RANDOM % 20000))}"
|
||||
|
||||
WORK="$(mktemp -d)"
|
||||
SERVER=""
|
||||
cleanup() {
|
||||
[ -n "$SERVER" ] && { pkill -P "$SERVER" 2>/dev/null || true; kill "$SERVER" 2>/dev/null || true; }
|
||||
rm -rf "$WORK"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
cd "$WORK"
|
||||
echo "▸ matcha new demo --runtime $RUNTIME"
|
||||
"$MATCHA" new demo --runtime "$RUNTIME"
|
||||
cd demo
|
||||
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[*]}"
|
||||
"${INSTALL[@]}"
|
||||
|
||||
echo "▸ ${CHECK[*]}"
|
||||
"${CHECK[@]}"
|
||||
|
||||
echo "▸ matcha run (boot on :$PORT)"
|
||||
"$MATCHA" run >"$WORK/server.log" 2>&1 &
|
||||
SERVER=$!
|
||||
for _ in $(seq 1 60); do
|
||||
curl -fsS -o /dev/null "http://localhost:$PORT/" 2>/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# 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.
|
||||
# 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" = 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,
|
||||
# which under `pipefail` fails the pipeline for a stream that arrived exactly as
|
||||
# intended — hence the capture-then-compare instead of a piped `grep -q`.
|
||||
zen="$(curl -fsS -N --max-time 5 "http://localhost:$PORT/zen" 2>/dev/null | head -1 || true)"
|
||||
case "$zen" in
|
||||
'data: {"zen":'*) ;;
|
||||
*) echo "GET /zen did not stream an SSE frame (got: ${zen:-<nothing>})"; cat "$WORK/server.log"; exit 1 ;;
|
||||
esac
|
||||
echo "✓ serves / and streams /zen"
|
||||
|
||||
pkill -P "$SERVER" 2>/dev/null || true; kill "$SERVER" 2>/dev/null || true; SERVER=""
|
||||
|
||||
# Introspection runs against the same project, so it also proves the entry file
|
||||
# the templates scaffold still exports the `app` that graph/explain import.
|
||||
echo "▸ matcha graph"
|
||||
"$MATCHA" graph | grep -q '^flowchart LR' || { echo "graph produced no mermaid"; exit 1; }
|
||||
"$MATCHA" graph --format dot | grep -q '^digraph green_tea' || { echo "graph produced no DOT"; exit 1; }
|
||||
"$MATCHA" explain /zen | grep -q '\[sse\]' || { echo "explain did not report the sse route"; exit 1; }
|
||||
"$MATCHA" openapi | grep -q '"openapi": "3.1.0"' || { echo "openapi produced no document"; exit 1; }
|
||||
echo "✓ graph, explain and openapi resolve"
|
||||
|
||||
# Every `matcha add` capability, spliced into one controller and type-checked
|
||||
# together. The stubs name core's real surface — `sse()` with an id, `@Ws` with
|
||||
# `@inbound()`, `MultipartBody`, `@Transformer` — so this is the thing that
|
||||
# notices when that surface moves. No peer dependency is installed on purpose:
|
||||
# core lazy-requires `ws` and `busboy`, so neither is needed to compile, and a
|
||||
# check that needed them would be hiding that fact.
|
||||
echo "▸ matcha add (every capability)"
|
||||
for cap in sse ws upload stream buffer; do
|
||||
"$MATCHA" add "$cap" >/dev/null || { echo "matcha add $cap failed"; exit 1; }
|
||||
done
|
||||
"${CHECK[@]}" || { echo "the generated handlers do not type-check"; exit 1; }
|
||||
echo "✓ every add capability type-checks"
|
||||
|
||||
echo "✓ $RUNTIME starter is good"
|
||||
+1
-1
@@ -5,7 +5,7 @@ fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
||||
match rt {
|
||||
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
||||
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
||||
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
||||
Runtime::Node | Runtime::Edge => ("npx", vec!["tsc", "--noEmit"]),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-3
@@ -1,5 +1,8 @@
|
||||
use clap::builder::PossibleValuesParser;
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::{cmd_add, cmd_create};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "matcha", version, about = "green-tea CLI")]
|
||||
pub struct Cli {
|
||||
@@ -14,22 +17,60 @@ pub enum Command {
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
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,
|
||||
},
|
||||
/// Detect the runtime and run the project in watch mode
|
||||
Run,
|
||||
/// Generate a piece and auto-wire it into the module
|
||||
Create {
|
||||
#[arg(value_parser = ["module", "controller", "step", "provider"])]
|
||||
#[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))]
|
||||
kind: String,
|
||||
name: String,
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
},
|
||||
/// Check the project for the misconfigurations that fail confusingly
|
||||
Doctor,
|
||||
/// Print the dependency graph (Mermaid, DOT, or JSON)
|
||||
Graph {
|
||||
#[arg(long, default_value = "mermaid", value_parser = ["mermaid", "dot", "json"])]
|
||||
format: String,
|
||||
/// Entry file exporting `app` (default: src/app.ts, then src/main.ts)
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
/// Write to this file instead of stdout
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Print the structural OpenAPI 3.1 document for the route table
|
||||
Openapi {
|
||||
/// API title (default: core's own)
|
||||
#[arg(long)]
|
||||
title: Option<String>,
|
||||
/// API version (default: core's own)
|
||||
#[arg(long)]
|
||||
api_version: Option<String>,
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Explain one route's chain, in execution order
|
||||
Explain {
|
||||
/// The route pattern as declared, e.g. /users/:id
|
||||
route: String,
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Add a capability to a controller
|
||||
Add {
|
||||
#[arg(value_parser = ["sse", "stream", "buffer"])]
|
||||
#[arg(value_parser = PossibleValuesParser::new(cmd_add::names()))]
|
||||
capability: String,
|
||||
/// Which controller to edit (default: the only one in src/controllers)
|
||||
#[arg(long)]
|
||||
controller: Option<String>,
|
||||
},
|
||||
}
|
||||
+259
-55
@@ -1,66 +1,198 @@
|
||||
//! `matcha add <sse|stream|buffer>` — appends a capability handler method to
|
||||
//! the single controller found under `src/controllers`, wiring in the
|
||||
//! decorator import via `wire::add_import` and splicing the method body via
|
||||
//! `wire::insert_method`.
|
||||
//! `matcha add <capability>` — append a ready handler to a controller, with the
|
||||
//! decorator imports it needs merged into the existing `@green-tea/core` import.
|
||||
//!
|
||||
//! Each capability is one row in [`CAPABILITIES`]: what to import, the method to
|
||||
//! splice, the literal that makes the insert idempotent, and the optional peer
|
||||
//! dependency the handler needs at runtime. Adding a capability is adding a row.
|
||||
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::wire;
|
||||
|
||||
/// Returns `(decorator symbol, method source, dedup marker)` for a known
|
||||
/// capability, or `None` for an unrecognized one.
|
||||
///
|
||||
/// The dedup marker is the route-path string literal baked into that
|
||||
/// capability's `handler()` template (e.g. `'/events'`, `'/stream'`,
|
||||
/// `'/data'`). It is unique per capability, unlike the decorator name — both
|
||||
/// `buffer` and any pre-existing handler can legitimately use `@Get` — so
|
||||
/// it's what `run` checks for before inserting, to keep `matcha add <cap>`
|
||||
/// idempotent per capability rather than per decorator.
|
||||
fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> {
|
||||
match cap {
|
||||
"sse" => Some((
|
||||
"Sse",
|
||||
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
||||
"'/events'",
|
||||
)),
|
||||
"stream" => Some((
|
||||
"Stream",
|
||||
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
||||
"'/stream'",
|
||||
)),
|
||||
"buffer" => Some((
|
||||
"Get",
|
||||
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
||||
"'/data'",
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
/// A handler `matcha add` can splice into a controller.
|
||||
struct Capability {
|
||||
/// Name as typed on the command line.
|
||||
name: &'static str,
|
||||
/// Symbols merged into the controller's `@green-tea/core` value import.
|
||||
imports: &'static [&'static str],
|
||||
/// Symbols that must arrive as `import type`, because they appear in a
|
||||
/// decorated signature. See [`wire::add_type_import`].
|
||||
type_imports: &'static [&'static str],
|
||||
/// The method source, spliced before the class's closing brace.
|
||||
method: &'static str,
|
||||
/// The route-path literal baked into `method`, used to keep the insert
|
||||
/// idempotent. It is the marker rather than the decorator name because a
|
||||
/// decorator is not unique — `buffer` uses `@Get`, and so does any handler
|
||||
/// the user already wrote.
|
||||
marker: &'static str,
|
||||
/// An optional peer dependency the handler needs at runtime, and the
|
||||
/// runtimes that need it. green-tea lazy-loads both, so a missing one is a
|
||||
/// clear error at the first request rather than a crash at boot — but it is
|
||||
/// still an error, and the person who just generated the handler is the one
|
||||
/// who can avoid it.
|
||||
peer: Option<(&'static str, &'static str)>,
|
||||
}
|
||||
|
||||
/// Finds the single `*.controller.ts` file in `src/controllers`. Errors if
|
||||
/// there are zero or more than one — this v1 has no way to disambiguate.
|
||||
fn only_controller() -> std::io::Result<PathBuf> {
|
||||
const CAPABILITIES: &[Capability] = &[
|
||||
Capability {
|
||||
name: "sse",
|
||||
// `sse()` and `@header` are what make the stream resumable. Without them
|
||||
// an `EventSource` reconnect silently restarts the iterable from its
|
||||
// beginning and loses whatever happened in the gap.
|
||||
imports: &["Sse", "sse", "header"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Sse('/events')
|
||||
events(@header('last-event-id') lastEventId?: string) {
|
||||
// The browser echoes the last id it saw back on reconnect. green-tea stores
|
||||
// nothing — no buffer, no replay — so what the gap means is this handler's
|
||||
// to decide: a paged log re-reads from an offset, a live sensor has no past
|
||||
// worth delivering.
|
||||
let next = lastEventId ? Number(lastEventId) + 1 : 0;
|
||||
return (async function* () {
|
||||
for (;;) {
|
||||
yield sse({ n: next }, { id: String(next) });
|
||||
next++;
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
})();
|
||||
}
|
||||
"#,
|
||||
marker: "'/events'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "stream",
|
||||
imports: &["Stream"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Stream('/stream')
|
||||
stream() {
|
||||
return (async function* () {
|
||||
yield 'chunk';
|
||||
})();
|
||||
}
|
||||
"#,
|
||||
marker: "'/stream'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "buffer",
|
||||
// "buffer" is the *transport* — the whole response at once, as opposed
|
||||
// to the incremental sse/stream/ws ones — and `@Transformer` is what
|
||||
// shapes it. The stub used to return `Buffer.from('hello')`, which is
|
||||
// not what the name means and never worked: `TransformerFn` returns
|
||||
// `body: string`, the default `JsonTransformer` is `JSON.stringify`,
|
||||
// and a Node Buffer stringifies to `{"type":"Buffer","data":[...]}`.
|
||||
imports: &["Get", "Transformer"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Get('/data')
|
||||
@Transformer((rows) => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/csv' },
|
||||
body: (rows as string[]).join('\n'),
|
||||
}))
|
||||
data() {
|
||||
return ['id,name', '1,matcha'];
|
||||
}
|
||||
"#,
|
||||
marker: "'/data'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "ws",
|
||||
imports: &["Ws", "inbound", "channel"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
// Two iterables: `@inbound()` is what the client sends, and the one returned
|
||||
// is what it receives. The pump is deliberately not awaited — the handler
|
||||
// returns the outbound channel now and fills it as messages arrive.
|
||||
const outbound = channel<string>();
|
||||
(async () => {
|
||||
for await (const message of incoming) outbound.push(`echo: ${message}`);
|
||||
outbound.close();
|
||||
})();
|
||||
return outbound;
|
||||
}
|
||||
"#,
|
||||
marker: "'/echo'",
|
||||
peer: Some(("ws", "Node")),
|
||||
},
|
||||
Capability {
|
||||
name: "upload",
|
||||
imports: &["Post", "body"],
|
||||
type_imports: &["MultipartBody"],
|
||||
method: r#"
|
||||
@Post('/upload')
|
||||
upload(@body() form: MultipartBody) {
|
||||
return Object.entries(form.files).map(([field, uploaded]) => {
|
||||
// A repeated part name arrives as an array, so a field holds either shape.
|
||||
const file = Array.isArray(uploaded) ? uploaded[0] : uploaded;
|
||||
return { field, filename: file.filename, size: file.size };
|
||||
});
|
||||
}
|
||||
"#,
|
||||
marker: "'/upload'",
|
||||
peer: Some(("busboy", "every runtime")),
|
||||
},
|
||||
];
|
||||
|
||||
/// The capability names, for clap's `value_parser` and for error messages.
|
||||
pub fn names() -> Vec<&'static str> {
|
||||
CAPABILITIES.iter().map(|c| c.name).collect()
|
||||
}
|
||||
|
||||
fn find(name: &str) -> Option<&'static Capability> {
|
||||
CAPABILITIES.iter().find(|c| c.name == name)
|
||||
}
|
||||
|
||||
/// Resolves which controller to edit. With `--controller` the path is taken as
|
||||
/// given; without it there must be exactly one `*.controller.ts` under
|
||||
/// `src/controllers`, since guessing between several would edit the wrong file
|
||||
/// as often as the right one.
|
||||
fn resolve_controller(explicit: Option<&str>) -> std::io::Result<PathBuf> {
|
||||
if let Some(path) = explicit {
|
||||
let p = PathBuf::from(path);
|
||||
return if p.exists() {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!("no such controller: {path}"),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
let dir = std::path::Path::new("src/controllers");
|
||||
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
|
||||
.collect();
|
||||
hits.sort();
|
||||
match hits.len() {
|
||||
1 => Ok(hits.pop().unwrap()),
|
||||
0 => Err(Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"no *.controller.ts in src/controllers",
|
||||
)),
|
||||
_ => Err(Error::other(
|
||||
"multiple controllers; specify which (not yet supported)",
|
||||
)),
|
||||
_ => {
|
||||
let list: Vec<String> = hits.iter().map(|p| format!(" {}", p.display())).collect();
|
||||
Err(Error::other(format!(
|
||||
"{} controllers found — pass --controller <path>:\n{}",
|
||||
hits.len(),
|
||||
list.join("\n")
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the class name following `export class `. This is a plain text
|
||||
/// scan rather than a tree-sitter query — `insert_method` does the real
|
||||
/// grammar-aware work once the name is known.
|
||||
/// Extracts the class name following `export class `. A plain text scan rather
|
||||
/// than a tree-sitter query — `insert_method` does the grammar-aware work once
|
||||
/// the name is known.
|
||||
fn class_name(src: &str) -> Option<String> {
|
||||
let idx = src.find("export class ")? + "export class ".len();
|
||||
let rest = &src[idx..];
|
||||
@@ -68,31 +200,103 @@ fn class_name(src: &str) -> Option<String> {
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
pub fn run(cap: &str) -> std::io::Result<()> {
|
||||
let (decorator, method, marker) = handler(cap)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
||||
let path = only_controller()?;
|
||||
pub fn run(cap: &str, controller: Option<&str>) -> std::io::Result<()> {
|
||||
let capability = find(cap).ok_or_else(|| {
|
||||
Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown capability {cap} (try: {})", names().join(", ")),
|
||||
)
|
||||
})?;
|
||||
|
||||
let path = resolve_controller(controller)?;
|
||||
let src = std::fs::read_to_string(&path)?;
|
||||
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
|
||||
if src.contains(marker) {
|
||||
if src.contains(capability.marker) {
|
||||
println!("→ {cap} already present in {class}");
|
||||
return Ok(());
|
||||
}
|
||||
// wire::add_import merges `decorator` into an existing
|
||||
// `import { ... } from '@green-tea/core';` brace when one is already
|
||||
// present, rather than appending a second import line for the same
|
||||
// module (which would be a duplicate ESM binding — a hard SyntaxError,
|
||||
// not a harmless dupe).
|
||||
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
|
||||
match wire::insert_method(&with_import, &class, &method) {
|
||||
|
||||
// add_import merges each symbol into an existing
|
||||
// `import { ... } from '@green-tea/core';` brace rather than appending a
|
||||
// second import line for the same module — which would be a duplicate ESM
|
||||
// binding, a hard SyntaxError rather than a harmless dupe.
|
||||
let mut edited = src;
|
||||
for symbol in capability.imports {
|
||||
edited = wire::add_import(&edited, symbol, "@green-tea/core");
|
||||
}
|
||||
for symbol in capability.type_imports {
|
||||
edited = wire::add_type_import(&edited, symbol, "@green-tea/core");
|
||||
}
|
||||
|
||||
match wire::insert_method(&edited, &class, capability.method) {
|
||||
Some(out) => {
|
||||
std::fs::write(&path, out)?;
|
||||
println!("✓ added @{decorator} to {class}");
|
||||
println!("✓ added {cap} handler to {class} ({})", path.display());
|
||||
if let Some((package, runtimes)) = capability.peer {
|
||||
println!(
|
||||
"→ needs the optional peer dependency '{package}' on {runtimes}: npm i {package}"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => println!(
|
||||
"→ could not edit {}; add @{decorator} handler manually",
|
||||
"→ could not edit {}; add the {cap} handler manually",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_capability_marker_appears_in_its_own_method() {
|
||||
for cap in CAPABILITIES {
|
||||
assert!(
|
||||
cap.method.contains(cap.marker),
|
||||
"{}: marker {} is not in the method it guards",
|
||||
cap.name,
|
||||
cap.marker
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker is what makes a second `matcha add <cap>` a no-op, so two
|
||||
/// capabilities sharing one would make each look already-present after the
|
||||
/// other had been added.
|
||||
#[test]
|
||||
fn markers_are_unique_across_capabilities() {
|
||||
for (i, a) in CAPABILITIES.iter().enumerate() {
|
||||
for b in &CAPABILITIES[i + 1..] {
|
||||
assert_ne!(
|
||||
a.marker, b.marker,
|
||||
"{} and {} share a marker",
|
||||
a.name, b.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generated handler that references a symbol it did not import does not
|
||||
/// compile, and `matcha add` would have written it anyway.
|
||||
#[test]
|
||||
fn every_capability_imports_the_symbols_it_uses() {
|
||||
for cap in CAPABILITIES {
|
||||
for symbol in cap.imports.iter().chain(cap.type_imports) {
|
||||
assert!(
|
||||
cap.method.contains(*symbol),
|
||||
"{} imports {symbol} without using it",
|
||||
cap.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_capability_lists_the_known_ones() {
|
||||
let err = run("telepathy", None).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert!(err.to_string().contains("sse"));
|
||||
}
|
||||
}
|
||||
+80
-52
@@ -5,63 +5,88 @@
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::wire;
|
||||
use crate::{entry, wire};
|
||||
|
||||
/// A piece that lives inside a module: a file under `src/<subdir>/` plus an
|
||||
/// entry in one of `@Module`'s arrays.
|
||||
///
|
||||
/// `module` is not one of these — it is registered in the `createApp` call
|
||||
/// rather than in a module array — so it stays a case of its own below.
|
||||
struct Piece {
|
||||
/// Name as typed on the command line.
|
||||
kind: &'static str,
|
||||
/// Directory under `src/`, and the `@Module` key, which are the same word
|
||||
/// for all three.
|
||||
subdir: &'static str,
|
||||
/// Filename infix: `users.controller.ts`.
|
||||
ext: &'static str,
|
||||
/// Appended to the given name to form the exported symbol.
|
||||
suffix: &'static str,
|
||||
stub: fn(&str) -> String,
|
||||
}
|
||||
|
||||
const PIECES: &[Piece] = &[
|
||||
Piece {
|
||||
kind: "controller",
|
||||
subdir: "controllers",
|
||||
ext: "controller",
|
||||
suffix: "Controller",
|
||||
stub: controller_stub,
|
||||
},
|
||||
Piece {
|
||||
kind: "step",
|
||||
subdir: "steps",
|
||||
ext: "step",
|
||||
suffix: "Step",
|
||||
stub: step_stub,
|
||||
},
|
||||
Piece {
|
||||
kind: "provider",
|
||||
subdir: "providers",
|
||||
ext: "provider",
|
||||
suffix: "Provider",
|
||||
stub: provider_stub,
|
||||
},
|
||||
];
|
||||
|
||||
/// Every `create` kind, for clap's `value_parser` and for error messages. One
|
||||
/// list, so a new kind cannot be accepted by the parser and rejected by `run`
|
||||
/// (or the reverse).
|
||||
pub fn kinds() -> Vec<&'static str> {
|
||||
std::iter::once("module")
|
||||
.chain(PIECES.iter().map(|p| p.kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
||||
match kind {
|
||||
"controller" => create_piece(
|
||||
name,
|
||||
check,
|
||||
"controllers",
|
||||
"controller",
|
||||
"Controller",
|
||||
"controllers",
|
||||
controller_stub(name),
|
||||
),
|
||||
"step" => create_piece(
|
||||
name,
|
||||
check,
|
||||
"steps",
|
||||
"step",
|
||||
"Step",
|
||||
"steps",
|
||||
step_stub(name),
|
||||
),
|
||||
"provider" => create_piece(
|
||||
name,
|
||||
check,
|
||||
"providers",
|
||||
"provider",
|
||||
"Provider",
|
||||
"providers",
|
||||
provider_stub(name),
|
||||
),
|
||||
"module" => create_module(name, check),
|
||||
other => Err(Error::new(
|
||||
if kind == "module" {
|
||||
return create_module(name, check);
|
||||
}
|
||||
match PIECES.iter().find(|p| p.kind == kind) {
|
||||
Some(piece) => create_piece(name, check, piece),
|
||||
None => Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown kind {other}"),
|
||||
format!("unknown kind {kind} (try: {})", kinds().join(", ")),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a piece file under `src/<subdir>/` and wires it into the `@Module`
|
||||
/// in `src/app.module.ts` (`module_key` array). Emit-only + hint on failure.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn create_piece(
|
||||
name: &str,
|
||||
check: bool,
|
||||
subdir: &str,
|
||||
ext: &str,
|
||||
suffix: &str,
|
||||
module_key: &str,
|
||||
stub: String,
|
||||
) -> std::io::Result<()> {
|
||||
/// in `src/app.module.ts`. Emit-only + hint on failure.
|
||||
fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
|
||||
let Piece {
|
||||
subdir,
|
||||
ext,
|
||||
suffix,
|
||||
..
|
||||
} = *piece;
|
||||
let module_key = subdir;
|
||||
let lower = name.to_lowercase();
|
||||
let file = Path::new("src")
|
||||
.join(subdir)
|
||||
.join(format!("{lower}.{ext}.ts"));
|
||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||
std::fs::write(&file, stub)?;
|
||||
std::fs::write(&file, (piece.stub)(name))?;
|
||||
println!("✓ {}", file.display());
|
||||
|
||||
let symbol = format!("{name}{suffix}");
|
||||
@@ -86,7 +111,7 @@ fn create_piece(
|
||||
}
|
||||
|
||||
/// Writes `src/<name>.module.ts` and registers it in the `createApp({ modules })`
|
||||
/// call in `src/main.ts`. Emit-only + hint on failure.
|
||||
/// call in the project's entry file. Emit-only + hint on failure.
|
||||
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"));
|
||||
@@ -96,20 +121,23 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> {
|
||||
|
||||
let symbol = format!("{name}Module");
|
||||
let from = format!("./{lower}.module");
|
||||
let main_path = Path::new("src/main.ts");
|
||||
if !main_path.exists() {
|
||||
println!("→ register {symbol} in createApp({{ modules }}) manually (no src/main.ts found)");
|
||||
let Some(entry_path) = entry::find(Path::new(".")) else {
|
||||
println!(
|
||||
"→ register {symbol} in createApp({{ modules }}) manually (no {} found)",
|
||||
entry::candidates()
|
||||
);
|
||||
return maybe_check(check);
|
||||
}
|
||||
let src = std::fs::read_to_string(main_path)?;
|
||||
};
|
||||
let src = std::fs::read_to_string(&entry_path)?;
|
||||
let imported = wire::add_import(&src, &symbol, &from);
|
||||
match wire::add_to_createapp_modules(&imported, &symbol) {
|
||||
Some(wired) => {
|
||||
std::fs::write(main_path, wired)?;
|
||||
std::fs::write(&entry_path, wired)?;
|
||||
println!("✓ registered {symbol} in createApp");
|
||||
}
|
||||
None => println!(
|
||||
"→ could not auto-register; add {symbol} to createApp modules[] in src/main.ts"
|
||||
"→ could not auto-register; add {symbol} to createApp modules[] in {}",
|
||||
entry_path.display()
|
||||
),
|
||||
}
|
||||
maybe_check(check)
|
||||
|
||||
@@ -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]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
//! `matcha graph` and `matcha explain <pattern>` — introspection of the
|
||||
//! dependency graph the framework builds from `needs`/`provides`.
|
||||
//!
|
||||
//! Both work the same way: write a short script next to the project, import its
|
||||
//! entry file, `await app.ready()`, print, delete the script. `ready()` is the
|
||||
//! reason this is cheap and safe to run — it resolves the graph and is
|
||||
//! documented as deliberately *not* running provider factories, so drawing a
|
||||
//! 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::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
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";
|
||||
|
||||
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
|
||||
pub fn graph(
|
||||
dir: &Path,
|
||||
format: &str,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
) -> std::io::Result<()> {
|
||||
let print = match format {
|
||||
"mermaid" => "console.log(app.toMermaid());",
|
||||
"dot" => "console.log(app.toDOT());",
|
||||
"json" => "console.log(JSON.stringify(app.graph(), null, 2));",
|
||||
other => {
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown format '{other}' (mermaid, dot, json)"),
|
||||
))
|
||||
}
|
||||
};
|
||||
emit(dir, entry_override, out, print)
|
||||
}
|
||||
|
||||
/// `matcha explain <pattern>` — one route's chain, in execution order, with
|
||||
/// each node's needs and provides.
|
||||
///
|
||||
/// The argument is the route *pattern* as declared (`/users/:id`), not a
|
||||
/// concrete URL: `explainRoute` matches the pattern string exactly. A miss
|
||||
/// therefore lists what is actually registered, which is the only useful thing
|
||||
/// to say to someone who just guessed wrong.
|
||||
pub fn explain(
|
||||
dir: &Path,
|
||||
route: &str,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
) -> std::io::Result<()> {
|
||||
let route = js_string(route);
|
||||
let body = format!(
|
||||
r#"let explained;
|
||||
try {{
|
||||
explained = app.explain({route});
|
||||
}} catch {{
|
||||
const patterns = app.graph().routes.map((r) => ` ${{r.method.padEnd(6)}} ${{r.pattern}}`);
|
||||
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.
|
||||
///
|
||||
/// Structural is the honest word for it: green-tea derives paths, methods and
|
||||
/// parameters from the decorators, which is everything the graph knows. It does
|
||||
/// not invent response schemas, so what comes out describes the surface rather
|
||||
/// than the payloads.
|
||||
pub fn openapi(
|
||||
dir: &Path,
|
||||
title: Option<&str>,
|
||||
version: Option<&str>,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
) -> std::io::Result<()> {
|
||||
// `app.openapi()` takes an optional info object; passing nothing lets core
|
||||
// apply its own defaults rather than having the CLI invent a title.
|
||||
let info = match (title, version) {
|
||||
(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(
|
||||
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
|
||||
/// detected runtime, and routes its stdout to a file or to ours.
|
||||
fn emit(
|
||||
dir: &Path,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
body: &str,
|
||||
) -> std::io::Result<()> {
|
||||
let entry_path = match entry_override {
|
||||
Some(explicit) => {
|
||||
let p = dir.join(explicit);
|
||||
if !p.exists() {
|
||||
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
|
||||
}
|
||||
PathBuf::from(explicit)
|
||||
}
|
||||
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(|| {
|
||||
Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
||||
)
|
||||
})?;
|
||||
|
||||
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 {
|
||||
Some(file) => {
|
||||
std::fs::write(dir.join(file), &stdout)?;
|
||||
println!("✓ {file}");
|
||||
}
|
||||
None => print!("{stdout}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The generated script: import the app, resolve the graph, run `body`.
|
||||
fn script(entry_path: &Path, body: &str) -> String {
|
||||
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",
|
||||
js_string(&specifier(entry_path)),
|
||||
entry_path.display(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs `script` under `rt` in `dir`. The child's stderr is inherited rather
|
||||
/// than captured: a type error or a boot failure is the reason someone runs
|
||||
/// this, and it should reach them as it happens.
|
||||
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.
|
||||
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_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]
|
||||
fn unknown_format_is_rejected() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let err = graph(d.path(), "svg", None, None).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
||||
Runtime::Deno => ("deno", vec!["task", "dev"]),
|
||||
Runtime::Bun => ("bun", 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"]));
|
||||
}
|
||||
#[test]
|
||||
fn edge_runs_wrangler_through_the_dev_script() {
|
||||
assert_eq!(command_for(Runtime::Edge), ("npm", vec!["run", "dev"]));
|
||||
}
|
||||
#[test]
|
||||
fn node_watch() {
|
||||
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Where the application graph is composed: the file holding the `createApp`
|
||||
//! call and exporting the `app` it returns.
|
||||
//!
|
||||
//! `src/app.ts` is what `matcha new` scaffolds, and it exists as its own file
|
||||
//! precisely so the graph can be imported without binding a port. Projects
|
||||
//! scaffolded before that split — and hand-written ones that never took it —
|
||||
//! keep the whole thing in `src/main.ts`, so that stays a candidate.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Candidate entry files, most specific first.
|
||||
const CANDIDATES: [&str; 2] = ["src/app.ts", "src/main.ts"];
|
||||
|
||||
/// The first candidate that exists under `dir`, or `None` when neither does.
|
||||
pub fn find(dir: &Path) -> Option<PathBuf> {
|
||||
CANDIDATES.iter().map(|c| dir.join(c)).find(|p| p.exists())
|
||||
}
|
||||
|
||||
/// The candidate list as prose, for the error a caller prints when `find`
|
||||
/// returns `None`.
|
||||
pub fn candidates() -> String {
|
||||
CANDIDATES.join(" or ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn touch(dir: &Path, rel: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_app_over_main() {
|
||||
let d = tempdir().unwrap();
|
||||
touch(d.path(), "src/main.ts");
|
||||
touch(d.path(), "src/app.ts");
|
||||
assert_eq!(find(d.path()), Some(d.path().join("src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_main() {
|
||||
let d = tempdir().unwrap();
|
||||
touch(d.path(), "src/main.ts");
|
||||
assert_eq!(find(d.path()), Some(d.path().join("src/main.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_when_neither_exists() {
|
||||
let d = tempdir().unwrap();
|
||||
assert_eq!(find(d.path()), None);
|
||||
}
|
||||
}
|
||||
+53
-2
@@ -2,8 +2,11 @@ mod check;
|
||||
mod cli;
|
||||
mod cmd_add;
|
||||
mod cmd_create;
|
||||
mod cmd_doctor;
|
||||
mod cmd_graph;
|
||||
mod cmd_new;
|
||||
mod cmd_run;
|
||||
mod entry;
|
||||
mod runtime;
|
||||
mod template;
|
||||
mod wire;
|
||||
@@ -36,8 +39,56 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Add { capability } => {
|
||||
if let Err(e) = cmd_add::run(&capability) {
|
||||
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 } => {
|
||||
if let Err(e) = cmd_graph::graph(
|
||||
std::path::Path::new("."),
|
||||
&format,
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Openapi {
|
||||
title,
|
||||
api_version,
|
||||
entry,
|
||||
out,
|
||||
} => {
|
||||
if let Err(e) = cmd_graph::openapi(
|
||||
std::path::Path::new("."),
|
||||
title.as_deref(),
|
||||
api_version.as_deref(),
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Explain { route, entry, out } => {
|
||||
if let Err(e) = cmd_graph::explain(
|
||||
std::path::Path::new("."),
|
||||
&route,
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Add {
|
||||
capability,
|
||||
controller,
|
||||
} => {
|
||||
if let Err(e) = cmd_add::run(&capability, controller.as_deref()) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,11 @@ pub enum Runtime {
|
||||
Node,
|
||||
Deno,
|
||||
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 {
|
||||
@@ -13,6 +18,7 @@ impl Runtime {
|
||||
"node" => Some(Runtime::Node),
|
||||
"deno" => Some(Runtime::Deno),
|
||||
"bun" => Some(Runtime::Bun),
|
||||
"edge" => Some(Runtime::Edge),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -39,6 +45,10 @@ pub fn detect(dir: &Path) -> Option<Runtime> {
|
||||
if let Some(r) = override_from_toml(dir) {
|
||||
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") {
|
||||
return Some(Runtime::Deno);
|
||||
}
|
||||
@@ -92,6 +102,14 @@ mod tests {
|
||||
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]
|
||||
fn nothing_detected() {
|
||||
let d = tempdir().unwrap();
|
||||
|
||||
+81
-1
@@ -3,16 +3,31 @@ use std::path::Path;
|
||||
|
||||
use crate::runtime::Runtime;
|
||||
|
||||
/// The `@green-tea/core` version `matcha new` writes into a scaffolded project,
|
||||
/// substituted for `{{core_version}}` in the runtime overlays.
|
||||
///
|
||||
/// **Pinned exactly, on purpose.** Core is prerelease-only, and npm's semver
|
||||
/// excludes a prerelease from any range whose comparators carry a different
|
||||
/// `major.minor.patch` — so `^26.7.0-beta.0` never resolves past `26.7.0-beta.0`,
|
||||
/// however many betas ship after it. A caret here is not a looser pin, it is a
|
||||
/// pin to the oldest matching prerelease that nothing can move off. When core
|
||||
/// reaches a stable major this becomes a range (`^27`) and the exactness stops
|
||||
/// mattering; until then the `core-freshness` CI job fails when this falls
|
||||
/// behind the `beta` dist-tag, which is what keeps it current.
|
||||
pub const CORE_VERSION: &str = "26.9.0-beta.1";
|
||||
|
||||
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_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_EDGE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/edge");
|
||||
|
||||
fn overlay_for(runtime: Runtime) -> &'static Dir<'static> {
|
||||
match runtime {
|
||||
Runtime::Deno => &RUNTIME_DENO,
|
||||
Runtime::Node => &RUNTIME_NODE,
|
||||
Runtime::Bun => &RUNTIME_BUN,
|
||||
Runtime::Edge => &RUNTIME_EDGE,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +50,11 @@ fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let contents = std::str::from_utf8(f.contents())
|
||||
.map(|s| s.replace("{{project_name}}", name).into_bytes())
|
||||
.map(|s| {
|
||||
s.replace("{{project_name}}", name)
|
||||
.replace("{{core_version}}", CORE_VERSION)
|
||||
.into_bytes()
|
||||
})
|
||||
.unwrap_or_else(|_| f.contents().to_vec());
|
||||
std::fs::write(out, contents)?;
|
||||
}
|
||||
@@ -49,6 +68,60 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// The graph has to be importable without binding a port, which is why the
|
||||
/// scaffold composes it in `src/app.ts` and leaves `src/main.ts` holding
|
||||
/// only the runtime's serve call. `matcha graph` and `matcha explain`
|
||||
/// import the former; breaking the split breaks both.
|
||||
#[test]
|
||||
fn every_runtime_exports_the_app_from_its_own_module() {
|
||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
|
||||
let d = tempdir().unwrap();
|
||||
write_starter(d.path(), "my-api", rt).unwrap();
|
||||
|
||||
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||
assert!(
|
||||
app.contains("export const app = createApp("),
|
||||
"{rt:?} app.ts"
|
||||
);
|
||||
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(
|
||||
main.contains("import { app } from './app';"),
|
||||
"{rt:?} main.ts"
|
||||
);
|
||||
assert!(
|
||||
!main.contains("createApp("),
|
||||
"{rt:?} main.ts still composes the graph"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Core is prerelease-only, and a caret over a prerelease never resolves
|
||||
/// past its own `major.minor.patch` — `^26.7.0-beta.0` pinned every
|
||||
/// scaffold to 26.7.0-beta.0 while three later betas shipped. Nothing here
|
||||
/// may carry a range.
|
||||
#[test]
|
||||
fn no_runtime_scaffolds_a_caret_range_for_core() {
|
||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
|
||||
let d = tempdir().unwrap();
|
||||
write_starter(d.path(), "my-api", rt).unwrap();
|
||||
|
||||
let manifest = ["package.json", "deno.json"]
|
||||
.iter()
|
||||
.map(|f| d.path().join(f))
|
||||
.find(|p| p.exists())
|
||||
.map(|p| std::fs::read_to_string(p).unwrap())
|
||||
.unwrap();
|
||||
let pin = manifest
|
||||
.lines()
|
||||
.find(|l| l.contains("@green-tea/core\":"))
|
||||
.unwrap_or_else(|| panic!("{rt:?} declares no core dependency"));
|
||||
assert!(pin.contains(CORE_VERSION), "{rt:?}: {pin}");
|
||||
assert!(!pin.contains('^'), "{rt:?} pins core with a caret: {pin}");
|
||||
assert!(!pin.contains('~'), "{rt:?} pins core with a tilde: {pin}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deno_writes_shared_and_deno_overlay() {
|
||||
let d = tempdir().unwrap();
|
||||
@@ -66,6 +139,10 @@ mod tests {
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(main.contains("Deno.serve"));
|
||||
assert!(!d.path().join("package.json").exists());
|
||||
|
||||
let deno_json = std::fs::read_to_string(d.path().join("deno.json")).unwrap();
|
||||
assert!(deno_json.contains(&format!("jsr:@green-tea/core@{CORE_VERSION}")));
|
||||
assert!(!deno_json.contains("{{core_version}}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -83,6 +160,9 @@ mod tests {
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(main.contains("app.listen"));
|
||||
assert!(!d.path().join("deno.json").exists());
|
||||
|
||||
assert!(pkg.contains(&format!("\"@green-tea/core\": \"{CORE_VERSION}\"")));
|
||||
assert!(!pkg.contains("{{core_version}}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+98
-7
@@ -64,10 +64,27 @@ fn has_error(node: Node) -> bool {
|
||||
/// accepted; if merging somehow produces broken text, this falls back to
|
||||
/// appending a fresh import line rather than returning broken source.
|
||||
pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
insert_import(src, symbol, from, false)
|
||||
}
|
||||
|
||||
/// Same as [`add_import`], but for `import type { ... } from '<from>';`.
|
||||
///
|
||||
/// A type used in a decorated method signature has to arrive this way. Under
|
||||
/// `isolatedModules` with `emitDecoratorMetadata` — Deno's defaults — a type
|
||||
/// reached through a value import is TS1272, because the emitted
|
||||
/// `design:paramtypes` would reference a binding the compiler erased. Node and
|
||||
/// bun's `tsc` accept it, so the same generated handler compiles on two
|
||||
/// runtimes and fails on the third.
|
||||
pub fn add_type_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
insert_import(src, symbol, from, true)
|
||||
}
|
||||
|
||||
fn insert_import(src: &str, symbol: &str, from: &str, type_only: bool) -> String {
|
||||
let tree = parser().parse(src, None).unwrap();
|
||||
let root = tree.root_node();
|
||||
let keyword = if type_only { "import type" } else { "import" };
|
||||
|
||||
if let Some(named_imports) = find_named_imports(&root, src, from) {
|
||||
if let Some(named_imports) = find_named_imports(&root, src, from, type_only) {
|
||||
let mut c = named_imports.walk();
|
||||
let already_present = named_imports.named_children(&mut c).any(|spec| {
|
||||
spec.kind() == "import_specifier"
|
||||
@@ -98,7 +115,7 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
// through to the append-a-new-line path below rather than return it.
|
||||
}
|
||||
|
||||
let line = format!("import {{ {symbol} }} from '{from}';");
|
||||
let line = format!("{keyword} {{ {symbol} }} from '{from}';");
|
||||
if src.contains(&line) {
|
||||
return src.to_string();
|
||||
}
|
||||
@@ -120,18 +137,41 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether an `import_statement` is the `import type { ... }` form.
|
||||
///
|
||||
/// Read off the statement's own text rather than its grammar node: the `type`
|
||||
/// modifier's shape differs between tree-sitter-typescript versions, and the
|
||||
/// node here is always a well-formed import statement, so the prefix is exact.
|
||||
fn is_type_only(stmt: &Node, src: &str) -> bool {
|
||||
stmt.utf8_text(src.as_bytes())
|
||||
.map(|text| text.trim_start().starts_with("import type"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import
|
||||
/// { ... } from '<from>';` statement whose module specifier string literal
|
||||
/// equals `from` exactly. Returns `None` when no import statement has that
|
||||
/// source, or when the matching statement has no named-imports clause at all
|
||||
/// (e.g. a bare default import) — callers treat that as "can't merge, fall
|
||||
/// back to appending a new line".
|
||||
fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option<Node<'a>> {
|
||||
/// equals `from` exactly and whose type-only-ness matches `type_only`. Returns
|
||||
/// `None` when no import statement has that source, or when the matching
|
||||
/// statement has no named-imports clause at all (e.g. a bare default import) —
|
||||
/// callers treat that as "can't merge, fall back to appending a new line".
|
||||
///
|
||||
/// The `type_only` split matters in both directions: merging a value symbol
|
||||
/// into an `import type` line erases it at runtime, and merging a type into a
|
||||
/// value line is the TS1272 that [`add_type_import`] exists to avoid.
|
||||
fn find_named_imports<'a>(
|
||||
root: &Node<'a>,
|
||||
src: &str,
|
||||
from: &str,
|
||||
type_only: bool,
|
||||
) -> Option<Node<'a>> {
|
||||
let mut c = root.walk();
|
||||
for stmt in root.children(&mut c) {
|
||||
if stmt.kind() != "import_statement" {
|
||||
continue;
|
||||
}
|
||||
if is_type_only(&stmt, src) != type_only {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = stmt.child_by_field_name("source") else {
|
||||
continue;
|
||||
};
|
||||
@@ -568,4 +608,55 @@ export class AppModule {}
|
||||
let src = "const app = createApp({ modules: MODULES });\n";
|
||||
assert!(add_to_createapp_modules(src, "UsersModule").is_none());
|
||||
}
|
||||
|
||||
/// A type in a decorated signature must not ride the value import: under
|
||||
/// `isolatedModules` + `emitDecoratorMetadata` that is TS1272, which node's
|
||||
/// and bun's tsc accept and Deno rejects.
|
||||
#[test]
|
||||
fn type_import_gets_its_own_statement() {
|
||||
let src = "import { Route } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "MultipartBody", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import type { MultipartBody } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
out.contains("import { Route } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The dangerous direction: a value symbol merged into an `import type`
|
||||
/// line is erased at compile time, so the decorator it names is simply
|
||||
/// undefined at runtime.
|
||||
#[test]
|
||||
fn value_import_never_merges_into_a_type_import() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_import(src, "Post", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import { Post } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
!out.contains("import type { MultipartBody, Post }"),
|
||||
"Post was merged into the type-only import:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_import_merges_into_an_existing_type_import() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "UploadedFile", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import type { MultipartBody, UploadedFile }"),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_import_is_idempotent() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "MultipartBody", "@green-tea/core");
|
||||
assert_eq!(out, src);
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,6 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": { "dev": "bun --watch run src/main.ts" },
|
||||
"dependencies": { "@green-tea/core": "^26.7.0-beta.0" }
|
||||
"dependencies": { "@green-tea/core": "{{core_version}}" },
|
||||
"devDependencies": { "@types/bun": "^1" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
Bun.serve({ port: 8000, fetch: app.fetch });
|
||||
console.log('🍵 green-tea running on http://localhost:8000');
|
||||
@@ -3,7 +3,9 @@
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["bun"],
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": { "experimentalDecorators": true },
|
||||
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true },
|
||||
"unstable": ["sloppy-imports"],
|
||||
"imports": { "@green-tea/core": "npm:@green-tea/core@^26.7.0-beta.0" },
|
||||
"imports": { "@green-tea/core": "jsr:@green-tea/core@{{core_version}}" },
|
||||
"tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
Deno.serve({ port: 8000 }, app.fetch);
|
||||
console.log('🍵 green-tea running on http://localhost:8000');
|
||||
@@ -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"
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": { "dev": "tsx watch src/main.ts" },
|
||||
"dependencies": { "@green-tea/core": "^26.7.0-beta.0" },
|
||||
"dependencies": { "@green-tea/core": "{{core_version}}" },
|
||||
"devDependencies": { "tsx": "^4", "typescript": "^5" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
app.listen(3000);
|
||||
console.log('🍵 green-tea running on http://localhost:3000');
|
||||
@@ -4,6 +4,7 @@
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
/**
|
||||
* The application graph, exported rather than kept local so it can be reached
|
||||
* without serving: `matcha graph` and `matcha explain` import this file and
|
||||
* call `app.ready()`, which resolves the graph and does not boot providers.
|
||||
* `src/main.ts` is the half that binds a port.
|
||||
*/
|
||||
export const app = createApp({ modules: [AppModule] });
|
||||
+19
-1
@@ -8,7 +8,10 @@ fail() { echo "FAIL: $*" >&2; exit 1; }
|
||||
os=$(uname -s); arch=$(uname -m)
|
||||
case "$os" in
|
||||
Darwin) case "$arch" in arm64|aarch64) triple=aarch64-apple-darwin;; x86_64) triple=x86_64-apple-darwin;; esac;;
|
||||
Linux) case "$arch" in x86_64|amd64) triple=x86_64-unknown-linux-musl;; esac;;
|
||||
Linux) case "$arch" in
|
||||
x86_64|amd64) triple=x86_64-unknown-linux-musl;;
|
||||
arm64|aarch64) triple=aarch64-unknown-linux-musl;;
|
||||
esac;;
|
||||
esac
|
||||
[ -n "${triple:-}" ] || { echo "SKIP: unsupported test host"; exit 0; }
|
||||
|
||||
@@ -43,4 +46,19 @@ if MATCHA_REPO_BASE="file://$work/fixture" MATCHA_VERSION="$tag" MATCHA_INSTALL_
|
||||
fi
|
||||
[ -e "$bin2/matcha" ] && fail "matcha must NOT be installed on checksum mismatch"
|
||||
|
||||
# --- case 3: an unresolvable "latest" explains itself and installs nothing ---
|
||||
# Both bases point at a path that does not exist, so the redirect and the API
|
||||
# fallback each come back empty. The branch is worth a test because its failure
|
||||
# mode is a message: the old one said only "could not resolve latest release
|
||||
# tag", which is also what a rate-limited API produces.
|
||||
bin3="$work/bin3"
|
||||
out=$(MATCHA_REPO_BASE="file://$work/nowhere" MATCHA_API_BASE="file://$work/nowhere" \
|
||||
MATCHA_INSTALL_DIR="$bin3" sh "$here/install.sh" 2>&1) && \
|
||||
fail "install.sh should have failed with no resolvable latest"
|
||||
case "$out" in
|
||||
*MATCHA_VERSION*) ;;
|
||||
*) fail "the unresolvable-latest error must point at MATCHA_VERSION; got: $out" ;;
|
||||
esac
|
||||
[ -e "$bin3/matcha" ] && fail "matcha must NOT be installed when latest cannot resolve"
|
||||
|
||||
echo "PASS: test_install.sh"
|
||||
+117
-1
@@ -21,7 +21,17 @@ fn add_sse_appends_handler() {
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Sse("));
|
||||
assert!(out.contains("import { Route, Get, Sse }") || out.contains("Sse }"));
|
||||
// The generated stream is resumable, which takes three symbols, not one:
|
||||
// `@Sse` to declare the route, `sse()` to tag each event with an id, and
|
||||
// `@header` to read the id the browser echoes back on reconnect.
|
||||
for symbol in ["Sse", "sse", "header"] {
|
||||
assert!(
|
||||
out.contains(&format!("{symbol},")) || out.contains(&format!("{symbol} }}")),
|
||||
"{symbol} not imported:\n{out}"
|
||||
);
|
||||
}
|
||||
assert!(out.contains("last-event-id"));
|
||||
assert!(out.contains("id: String(next)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -83,3 +93,109 @@ fn add_errors_when_multiple_controllers_and_writes_nothing() {
|
||||
original
|
||||
);
|
||||
}
|
||||
|
||||
fn seed(dir: &std::path::Path, name: &str) {
|
||||
std::fs::create_dir_all(dir.join("src/controllers")).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(format!("src/controllers/{name}.controller.ts")),
|
||||
format!(
|
||||
"import {{ Route, Get }} from '@green-tea/core';\n\n@Route('/')\nexport class {}Controller {{\n @Get('/')\n home() {{}}\n}}\n",
|
||||
name.to_uppercase()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_ws_wires_the_duplex_handler_and_names_its_peer_dependency() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "ws"])
|
||||
.assert()
|
||||
.success()
|
||||
// `ws` is lazy-required, so its absence is a runtime error rather than a
|
||||
// boot failure — the moment to mention it is when the handler is written.
|
||||
.stdout(predicates::str::contains("npm i ws"));
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Ws('/echo')"));
|
||||
assert!(out.contains("@inbound()"));
|
||||
assert!(out.contains("channel<string>()"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_upload_wires_multipart_and_names_busboy() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "upload"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicates::str::contains("npm i busboy"));
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Post('/upload')"));
|
||||
assert!(out.contains("MultipartBody"));
|
||||
}
|
||||
|
||||
/// With more than one controller the CLI used to refuse and stop. It still
|
||||
/// refuses to guess, but `--controller` is now the way through.
|
||||
#[test]
|
||||
fn add_targets_the_named_controller_when_several_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
seed(d.path(), "users");
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "sse"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains("--controller"));
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args([
|
||||
"add",
|
||||
"sse",
|
||||
"--controller",
|
||||
"src/controllers/users.controller.ts",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let users =
|
||||
std::fs::read_to_string(d.path().join("src/controllers/users.controller.ts")).unwrap();
|
||||
assert!(users.contains("@Sse("));
|
||||
let home =
|
||||
std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(
|
||||
!home.contains("@Sse("),
|
||||
"the other controller was edited too"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_rejects_a_controller_path_that_does_not_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args([
|
||||
"add",
|
||||
"sse",
|
||||
"--controller",
|
||||
"src/controllers/nope.controller.ts",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains("no such controller"));
|
||||
}
|
||||
+26
-1
@@ -11,7 +11,32 @@ fn help_lists_all_subcommands() {
|
||||
.stdout(contains("new"))
|
||||
.stdout(contains("run"))
|
||||
.stdout(contains("create"))
|
||||
.stdout(contains("add"));
|
||||
.stdout(contains("add"))
|
||||
.stdout(contains("graph"))
|
||||
.stdout(contains("explain"))
|
||||
.stdout(contains("openapi"))
|
||||
.stdout(contains("doctor"));
|
||||
}
|
||||
|
||||
/// clap's accepted values and the values `run` dispatches on come from one list
|
||||
/// per command now. This is what proves the wiring reached clap — a regression
|
||||
/// would take the parser and the dispatcher out of step, which shows up as a
|
||||
/// value the CLI accepts and then refuses.
|
||||
#[test]
|
||||
fn create_and_add_advertise_every_value_they_accept() {
|
||||
for (command, values) in [
|
||||
("create", vec!["module", "controller", "step", "provider"]),
|
||||
("add", vec!["sse", "stream", "buffer", "ws", "upload"]),
|
||||
] {
|
||||
let mut assertion = Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.args([command, "--help"])
|
||||
.assert()
|
||||
.success();
|
||||
for value in values {
|
||||
assertion = assertion.stdout(contains(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -84,3 +84,38 @@ fn create_module_writes_and_registers_in_createapp() {
|
||||
assert!(main.contains("AppModule, UsersModule"));
|
||||
assert!(main.contains("import { UsersModule }"));
|
||||
}
|
||||
|
||||
/// A project scaffolded today composes its graph in `src/app.ts`, so that is
|
||||
/// where a new module has to be registered. `src/main.ts` only serves, and
|
||||
/// wiring a module into it would put the module in a file that never calls
|
||||
/// `createApp` — silently, since `add_to_createapp_modules` would simply find
|
||||
/// nothing to edit and the CLI would print its "add it manually" hint.
|
||||
#[test]
|
||||
fn create_module_prefers_app_ts_over_main_ts() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::create_dir_all(d.path().join("src")).unwrap();
|
||||
std::fs::write(
|
||||
d.path().join("src/app.ts"),
|
||||
"import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nexport const app = createApp({ modules: [AppModule] });\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
d.path().join("src/main.ts"),
|
||||
"import { app } from './app';\n\napp.listen(3000);\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["create", "module", "Users"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let app_ts = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||
assert!(app_ts.contains("AppModule, UsersModule"));
|
||||
assert!(app_ts.contains("import { UsersModule }"));
|
||||
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(!main.contains("UsersModule"), "main.ts was edited: {main}");
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use assert_cmd::Command;
|
||||
use predicates::str::contains;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// Both introspection commands need a file that exports the app. Without one
|
||||
/// there is nothing to import, and the failure has to name the fix — a stack
|
||||
/// trace from a runtime that could not resolve a module does not.
|
||||
#[test]
|
||||
fn graph_without_an_entry_says_what_is_missing() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("graph")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--entry"))
|
||||
.stderr(contains("export const app = createApp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explain_rejects_an_entry_that_does_not_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["explain", "/users", "--entry", "src/nope.ts"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("no such entry"));
|
||||
}
|
||||
|
||||
/// Runtime detection comes after the entry is found, so a project with an entry
|
||||
/// and no manifest is a distinct failure with its own message.
|
||||
#[test]
|
||||
fn graph_without_a_runtime_says_so() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::create_dir_all(d.path().join("src")).unwrap();
|
||||
std::fs::write(d.path().join("src/app.ts"), "export const app = {};\n").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("graph")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("no runtime detected"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_rejects_an_unknown_format() {
|
||||
let d = tempdir().unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["graph", "--format", "svg"])
|
||||
.assert()
|
||||
.failure();
|
||||
}
|
||||
|
||||
/// openapi shares graph's entry resolution, so it shares its failure modes —
|
||||
/// including the one that has to name the fix.
|
||||
#[test]
|
||||
fn openapi_without_an_entry_says_what_is_missing() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("openapi")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--entry"));
|
||||
}
|
||||
Reference in new issue
Block a user