Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
def572a876 | ||
|
|
2acd4561ff | ||
|
|
af2a853855 | ||
|
|
958d69dfd9 | ||
|
|
e58d230596 | ||
|
|
8573cdfb4b | ||
|
|
bcd5f79990 | ||
|
|
56b5d7581f | ||
|
|
0865d9a479 | ||
|
|
ecbd441eb4 | ||
|
|
53d54cf250 | ||
|
|
64ec413c25 | ||
|
|
647aef5a1b | ||
|
|
42b5cc2616 | ||
|
|
04d7a25402 | ||
|
|
8e45c1170f | ||
|
|
8bd558991d | ||
|
|
d9f2b07802 | ||
|
|
a8f1658e4d | ||
|
|
865d87487b | ||
|
|
9641bd51a7 | ||
|
|
ea510c5112 | ||
|
|
9acb0b34c9 | ||
|
|
a4827f2e13 | ||
|
|
47d1d6e037 | ||
|
|
99c8578120 | ||
|
|
202c4b2711 | ||
|
|
9e719b159d | ||
|
|
ecdc46cac3 | ||
|
|
4358091d07 | ||
|
|
e4a350fcbf | ||
|
|
70b51e5de4 | ||
|
|
52241cc9a6 | ||
|
|
efe7ad6027 | ||
|
|
42c1148903 | ||
|
|
3c3b7aaf8e | ||
|
|
f2a3c16023 | ||
|
|
c5b4a56ccd | ||
|
|
56340f6b21 | ||
|
|
6304ad7e24 | ||
|
|
483cc23dea | ||
|
|
db27c35953 | ||
|
|
82d6b809da | ||
|
|
0d96a085f9 | ||
|
|
04a45a7765 | ||
|
|
87cf3eac82 | ||
|
|
88090f34a2 | ||
|
|
5c8f72b409 | ||
|
|
a3250da225 | ||
|
|
0a2713d377 | ||
|
|
827e6863ad | ||
|
|
3e76868811 | ||
|
|
8910fe22ee | ||
|
|
95b7b92fdf | ||
|
|
3e6fa7797b | ||
|
|
f88c11ac0b | ||
|
|
1764aa764b | ||
|
|
bee7580ab4 | ||
|
|
b8aac3bb6a | ||
|
|
e5a1b7583a | ||
|
|
88dd2035c4 | ||
|
|
dfba02a7ce | ||
|
|
371c5f708f | ||
|
|
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,104 @@
|
|||||||
|
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@v5
|
||||||
|
- 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@v5
|
||||||
|
- 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@v5
|
||||||
|
- name: Compare the scaffold pin against the latest dist-tag
|
||||||
|
run: |
|
||||||
|
pinned=$(grep -oP 'CORE_VERSION: &str = "\K[^"]+' src/template.rs)
|
||||||
|
latest=$(npm view @green-tea/core dist-tags.latest)
|
||||||
|
echo "pinned=$pinned latest=$latest"
|
||||||
|
if [ "$pinned" != "$latest" ]; then
|
||||||
|
echo "::error::matcha scaffolds @green-tea/core@$pinned but the latest 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:
|
||||||
|
# macos-14 is retired on GitHub but is the self-hosted runner's label on Gitea; see release.yml.
|
||||||
|
runs-on: ${{ matrix.os == 'macos-14' && github.server_url == 'https://github.com' && 'macos-15' || matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest, macos-14]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
- 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,36 @@
|
|||||||
|
name: Promote → GitHub
|
||||||
|
|
||||||
|
# Runs on GITEA ONLY. Mirrors `main` to the public GitHub repo.
|
||||||
|
#
|
||||||
|
# Tags are NOT promoted here. They are promoted by release.yml's `promote-tag`
|
||||||
|
# job, which waits for this forge's builds to pass first — pushing a tag is what
|
||||||
|
# starts GitHub's release and its crates.io publish, and crates.io cannot be
|
||||||
|
# unpublished, only yanked. Both workflows used to fire on the same tag push, so
|
||||||
|
# Gitea built and GitHub published at the same time and this forge was never the
|
||||||
|
# check it was meant to be.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
push-github:
|
||||||
|
if: ${{ github.server_url != 'https://github.com' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Push main 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"
|
||||||
|
# Deliberately not `--tags`. v26.7.0 points at a different commit on
|
||||||
|
# each forge and v26.8.0-beta.0 is annotated here and lightweight
|
||||||
|
# there, so pushing every tag is a non-fast-forward that fails — which
|
||||||
|
# it has been doing on every push to main, reddening a job whose real
|
||||||
|
# work (the line above) had already succeeded. Reconciling that
|
||||||
|
# divergence means rewriting what a published tag points at, which is
|
||||||
|
# a decision rather than a fix; new tags are unaffected and go through
|
||||||
|
# release.yml.
|
||||||
|
git push github "HEAD:refs/heads/main"
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
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
|
||||||
|
# GitHub retired the macos-14 image (jobs are cancelled with "configuration not supported");
|
||||||
|
# on Gitea, macos-14 is the label of the self-hosted macOS runner, so only GitHub moves.
|
||||||
|
runs-on: ${{ matrix.os == 'macos-14' && github.server_url == 'https://github.com' && 'macos-15' || matrix.os }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- 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@v3
|
||||||
|
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@v5
|
||||||
|
- 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
|
||||||
|
|
||||||
|
# Gitea only: hand the tag to GitHub, but only once this forge has built all
|
||||||
|
# four targets and run every artifact it can.
|
||||||
|
#
|
||||||
|
# This is the gate. Pushing the tag is what starts GitHub's release and, with
|
||||||
|
# it, the crates.io publish — and crates.io has no unpublish, only yank. So the
|
||||||
|
# local build is not a parallel opinion, it is the thing that has to pass
|
||||||
|
# first. `needs: build` is what makes the two sequential; when both workflows
|
||||||
|
# fired on the same tag push they were not.
|
||||||
|
promote-tag:
|
||||||
|
needs: build
|
||||||
|
if: ${{ github.server_url != 'https://github.com' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Push the tag 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"
|
||||||
|
# `${{ github.ref_name }}` rather than $GITHUB_REF_NAME: the expression
|
||||||
|
# is what promote.yml used to hand v26.8.0-beta.0 to GitHub, so it is
|
||||||
|
# proven on this act_runner. Whether the env var is exported here is
|
||||||
|
# not, and getting it wrong would push an empty ref and leave the tag
|
||||||
|
# on this forge alone.
|
||||||
|
git push github "refs/tags/${{ github.ref_name }}"
|
||||||
|
|
||||||
|
# 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@v5
|
||||||
|
- 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
|
||||||
+284
@@ -0,0 +1,284 @@
|
|||||||
|
# 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. **From 26.11.0-rc.1 matcha releases with core**: `matcha` X scaffolds
|
||||||
|
`@green-tea/core` X. Before that the CLI ran on its own version line. The core version a scaffold
|
||||||
|
is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [26.11.0-rc.2] - 2026-11-23
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **New projects scaffold `@green-tea/core` 26.11.0-rc.2** (`CORE_VERSION`). That core release fixes
|
||||||
|
nine security advisories reported against 26.11.0-rc.1. Projects already scaffolded should run
|
||||||
|
`npm install @green-tea/core@26.11.0-rc.2` or the equivalent for their runtime.
|
||||||
|
- The scaffolded `AGENTS.md` lists every generator: `matcha add cookie`, `matcha create transformer`
|
||||||
|
and `matcha create plugin` were missing. It also points agents at the official plugins' READMEs.
|
||||||
|
- The README documents installing with Homebrew: `brew install expressive-tea/tap/matcha`.
|
||||||
|
|
||||||
|
## [26.11.0-rc.1] - 2026-11-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`matcha add cookie`** adds `GET /prefs`, which reads a cookie with `@cookie('theme')`, and
|
||||||
|
`POST /prefs`, which sets it through a `@Transformer` and `setCookie()`. Core has no response-cookie
|
||||||
|
API, so the transformer is where a `Set-Cookie` header is sent. Needs `@green-tea/core` RC.1.
|
||||||
|
- **`matcha create transformer <Name>`** writes `src/transformers/<name>.transformer.ts`, a typed
|
||||||
|
`TransformerFn`, and prints the `@Transformer(...)` line that attaches it. A transformer belongs to
|
||||||
|
a route, not a module, so there is nothing to wire.
|
||||||
|
- **Every starter ships an `AGENTS.md` and a `CLAUDE.md` that imports it.** green-tea is new, so a
|
||||||
|
coding agent falls back on Express habits. The file states the rules that differ: it is a graph, not a
|
||||||
|
chain, a handler declares its needs in its signature, and the graph is checked at boot. It also points
|
||||||
|
the agent at `matcha routes|tokens|explain --json`, so it reads the app instead of guessing, and at the
|
||||||
|
`llms.txt` shipped inside the installed `@green-tea/core`.
|
||||||
|
- **`matcha agents`** writes the same two files into a project that predates them. The files name the
|
||||||
|
core version the project actually depends on. An existing file is left alone unless `--force` is passed.
|
||||||
|
- **`matcha routes` and `matcha tokens`.** `routes` lists every route with its transport and chain.
|
||||||
|
`tokens` lists every token, with who provides it and who needs it, handlers included. It is
|
||||||
|
the check to run before writing `@needs('x')`.
|
||||||
|
- **`--json` on `explain`, `routes` and `tokens`** (`graph --format json` already had it). It
|
||||||
|
prints one JSON document on stdout, so an agent inspecting an app reads the graph instead of
|
||||||
|
guessing it. A refused query (an unknown pattern) prints a structured error on stderr and
|
||||||
|
exits 1.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Scaffolds pin `@green-tea/core` 26.11.0-rc.1**, the API-freeze release candidate, and matcha's own
|
||||||
|
version now matches it.
|
||||||
|
- **The edge starter installs core from npm.** core#93 is fixed in RC.1, so the `.npmrc` and the
|
||||||
|
`npm:@jsr/green-tea__core` alias are gone. `matcha doctor` still reads the alias, so edge projects
|
||||||
|
scaffolded before this keep working.
|
||||||
|
- The weekly `core-freshness` CI job compares `CORE_VERSION` against core's `latest` dist-tag, where
|
||||||
|
release candidates and the stable release publish. `beta` stays on 26.9.0-beta.2.
|
||||||
|
- Introspection runs through one query layer (`src/introspect.rs`): every command asks one
|
||||||
|
question and gets one JSON document back, then renders it as text unless `--json` is passed.
|
||||||
|
Text output is unchanged. The layer is also the seam a future `matcha mcp` would serve over
|
||||||
|
MCP. It adds `serde_json` as a dependency.
|
||||||
|
- **The node starter awaits `app.listen(3000)`.** A port already in use, or a provider that fails at
|
||||||
|
boot, now stops the process with its own error rather than an unhandled rejection.
|
||||||
|
- **The node and edge starters declare `engines: { node: ">=22" }`**, matching `@green-tea/core`,
|
||||||
|
which no longer supports Node 18 or 20.
|
||||||
|
- **`matcha create step|provider` derives the token from the class name in camelCase.**
|
||||||
|
`create step current-user` writes `CurrentUserStep` providing `currentUser`. It used to write
|
||||||
|
`current-userStep` and `return { current-user: null }`, which does not parse. A single word is
|
||||||
|
unchanged (`Users` still provides `users`).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **`matcha create` no longer overwrites a file that already exists.** Running it twice with the same
|
||||||
|
name silently replaced the first file, edits included. Now it refuses and names the file.
|
||||||
|
- **`matcha create` rejects names that cannot become a class** (`2fast`, `us.ers`) instead of
|
||||||
|
writing a file that does not compile. For a step or provider, it also rejects names whose token
|
||||||
|
core already provides (`logger`, `rooms`, `events`, `bus`, and the request tokens `req`,
|
||||||
|
`params`, `query`, `body`, `headers`, `cookies`, `inbound`, `abort`). `createApp` would refuse the
|
||||||
|
first group, and the second would shadow what every route reads.
|
||||||
|
|
||||||
|
## [26.9.0-beta.1] - 2026-09-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **`matcha create plugin`.** By default it scaffolds an in-app plugin in a folder of its own,
|
||||||
|
`plugins/<name>/`, and registers it in `createApp({ plugins })`. With `--package` (or `--package=DIR`) it writes
|
||||||
|
a package instead. JSR is the default, and `--registry both` adds an ESM-only npm build. The
|
||||||
|
package passes `deno test`, `node --test`, `bun test` and `deno publish --dry-run` as generated.
|
||||||
|
At a terminal it asks for what the flags leave out. Without one it takes the defaults, and fails
|
||||||
|
with the flag to pass instead of waiting for an answer.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Scaffolds `@green-tea/core` 26.9.0-beta.2** (`CORE_VERSION` moved from beta.1). That is the
|
||||||
|
release where a plugin became `{ name, mount }` and `app.boot()` became public, so a project
|
||||||
|
made with the previous version could not use plugins in their current form.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **The Deno and Bun starters bound the port before booting.** They passed `app.fetch` straight to
|
||||||
|
`Deno.serve` and `Bun.serve`, so a provider that failed left the port open and answering 500 to
|
||||||
|
every request. They now `await serveDeno(app)` and `await serveBun(app)`, which boot first.
|
||||||
|
|
||||||
|
## [26.9.0-beta.0] - 2026-09-05
|
||||||
|
|
||||||
|
### 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.11.0-rc.2...HEAD
|
||||||
|
[26.11.0-rc.2]: https://github.com/Expressive-Tea/matcha/compare/v26.11.0-rc.1...v26.11.0-rc.2
|
||||||
|
[26.11.0-rc.1]: https://github.com/Expressive-Tea/matcha/compare/v26.9.0-beta.1...v26.11.0-rc.1
|
||||||
|
[26.9.0-beta.1]: https://github.com/Expressive-Tea/matcha/compare/v26.9.0-beta.0...v26.9.0-beta.1
|
||||||
|
[26.9.0-beta.0]: https://github.com/Expressive-Tea/matcha/compare/v26.8.0-beta.0...v26.9.0-beta.0
|
||||||
|
[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 `latest` 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
+37
-2
@@ -240,6 +240,12 @@ version = "1.70.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.186"
|
version = "0.2.186"
|
||||||
@@ -253,13 +259,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "matcha"
|
name = "matcha-cli"
|
||||||
version = "26.7.0"
|
version = "26.11.0-rc.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"assert_cmd",
|
"assert_cmd",
|
||||||
"clap",
|
"clap",
|
||||||
"include_dir",
|
"include_dir",
|
||||||
"predicates",
|
"predicates",
|
||||||
|
"serde_json",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tree-sitter",
|
"tree-sitter",
|
||||||
"tree-sitter-typescript",
|
"tree-sitter-typescript",
|
||||||
@@ -394,6 +401,15 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.228"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_core"
|
name = "serde_core"
|
||||||
version = "1.0.228"
|
version = "1.0.228"
|
||||||
@@ -414,6 +430,19 @@ dependencies = [
|
|||||||
"syn",
|
"syn",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_json"
|
||||||
|
version = "1.0.154"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||||
|
dependencies = [
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"zmij",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
@@ -511,3 +540,9 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zmij"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
+8
-2
@@ -1,8 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "matcha"
|
name = "matcha-cli"
|
||||||
version = "26.7.0"
|
version = "26.11.0-rc.2"
|
||||||
edition = "2021"
|
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]]
|
[[bin]]
|
||||||
name = "matcha"
|
name = "matcha"
|
||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
@@ -10,6 +15,7 @@ path = "src/main.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
include_dir = "0.7"
|
include_dir = "0.7"
|
||||||
|
serde_json = "1"
|
||||||
tree-sitter = "0.22"
|
tree-sitter = "0.22"
|
||||||
tree-sitter-typescript = "0.21"
|
tree-sitter-typescript = "0.21"
|
||||||
|
|
||||||
|
|||||||
@@ -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,40 @@
|
|||||||
# matcha
|
# 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
|
## Install
|
||||||
|
|
||||||
```bash
|
```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
|
Builds from [crates.io](https://crates.io/crates/matcha-cli) and installs the `matcha`
|
||||||
the `sh` side of the pipe:
|
binary. Needs a Rust toolchain; takes a few seconds.
|
||||||
|
|
||||||
|
**Homebrew** (macOS, Linux):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
brew install expressive-tea/tap/matcha
|
||||||
|
```
|
||||||
|
|
||||||
|
**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
|
```bash
|
||||||
curl -fsSL …/install.sh | MATCHA_VERSION=v26.7.0 MATCHA_INSTALL_DIR=/usr/local/bin sh
|
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
|
```bash
|
||||||
cargo install --git https://git.svc.zoit.services/Green-Tea/matcha
|
cargo install --git https://github.com/Expressive-Tea/matcha
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
@@ -28,7 +44,15 @@ matcha new my-api # scaffold from the official starter
|
|||||||
matcha new my-api --template-url gh:owner/repo # scaffold from any git template
|
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 run # detect node/deno/bun and run in watch
|
||||||
matcha create controller Users # generate + auto-wire into @Module
|
matcha create controller Users # generate + auto-wire into @Module
|
||||||
matcha add sse # add a capability (sse|stream|buffer) to your controller
|
matcha create plugin "Plugin Algo" # an in-app plugin, or --package for its own package
|
||||||
|
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 routes # every route and the chain it runs
|
||||||
|
matcha tokens # every token: who provides it, who needs it
|
||||||
|
matcha openapi # structural OpenAPI 3.1 for the route table
|
||||||
|
matcha doctor # check the project for confusing misconfigurations
|
||||||
|
matcha agents # write AGENTS.md/CLAUDE.md for coding agents (new projects get them)
|
||||||
```
|
```
|
||||||
|
|
||||||
### The starter
|
### The starter
|
||||||
@@ -37,6 +61,79 @@ matcha add sse # add a capability (sse|stream|buffer
|
|||||||
with the green-tea logo and streams a rotating zen message over `@Sse('/zen')`.
|
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.
|
Open the browser and it's already alive — `matcha run` boots it.
|
||||||
|
|
||||||
|
It also writes an `AGENTS.md` (and a `CLAUDE.md` that imports it) for coding
|
||||||
|
agents. green-tea is new enough that an agent's training data says Express, so
|
||||||
|
the file states the rules that differ, points at `matcha routes|tokens|explain
|
||||||
|
--json` for reading the app, and at the `llms.txt` inside the installed core.
|
||||||
|
`matcha agents` adds the same files to an older project.
|
||||||
|
|
||||||
|
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 `latest` 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 routes # every route: method, pattern, transport, chain
|
||||||
|
matcha tokens # every token, who provides it, who needs it
|
||||||
|
matcha explain /users/:id --json # any of explain/routes/tokens as JSON, for a program or an agent
|
||||||
|
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
|
||||||
|
```
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
`tokens` answers the question to ask before writing `@needs('x')`: does anything
|
||||||
|
provide `x`, and who else depends on it? A token nothing provides is listed with
|
||||||
|
`— (nothing provides it)`, which is the boot error you are about to get.
|
||||||
|
|
||||||
|
**For agents.** `--json` prints the same data the text is rendered from: exactly
|
||||||
|
one JSON document on stdout, so a program parses stdout and nothing else. When a
|
||||||
|
query is refused (an unknown route pattern), stderr carries
|
||||||
|
`{"error": {"code", "message", …}}` and the exit code is 1. Every query is one
|
||||||
|
self-contained document, so the same set can later be served over MCP without a
|
||||||
|
second implementation.
|
||||||
|
|
||||||
|
### `add` capabilities
|
||||||
|
|
||||||
|
| | 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` / `add` auto-wiring
|
||||||
|
|
||||||
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
||||||
@@ -44,16 +141,79 @@ and wire pieces into the right `@Module` array or controller. Edits are
|
|||||||
idempotent and revert themselves if they would break the file's syntax. Pass
|
idempotent and revert themselves if they would break the file's syntax. Pass
|
||||||
`--check` to `create` to type-check with your project's runtime afterward.
|
`--check` to `create` to type-check with your project's runtime afterward.
|
||||||
|
|
||||||
|
### `matcha create plugin`
|
||||||
|
|
||||||
|
An in-app plugin by default, or a package of its own.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
matcha create plugin "Plugin Algo" # plugins/plugin-algo/, registered in createApp
|
||||||
|
matcha create plugin algo --folder lib/plugins
|
||||||
|
matcha create plugin algo --package=./algo --scope acme # a JSR package
|
||||||
|
matcha create plugin algo --package=./algo --scope acme --registry both # JSR + npm, ESM only
|
||||||
|
```
|
||||||
|
|
||||||
|
In-app, each plugin gets a folder of its own under `plugins/` (or `--folder`, relative to the
|
||||||
|
project root) and is registered in `createApp({ plugins })`. It lives in a folder so it can become
|
||||||
|
a package later without being pulled out of the app.
|
||||||
|
|
||||||
|
`--package` writes a package into the current directory, or `--package=DIR` into `DIR`, and either
|
||||||
|
one has to be empty. The `=` is required, so a word after a bare `--package` is the plugin's
|
||||||
|
name. JSR is the default, because it records which runtimes a package supports. `--registry both`
|
||||||
|
adds npm with a `tsc` build to ESM only, and suggests the `@scope/green-tea-<name>` name without
|
||||||
|
requiring it. The package passes `deno test`, `node --test`,
|
||||||
|
`bun test` and `deno publish --dry-run` as generated.
|
||||||
|
|
||||||
|
At a terminal it asks for whatever the flags leave out. Without a terminal (CI, a pipe) it takes the
|
||||||
|
defaults, and for anything that has no default it stops and names the flag to pass.
|
||||||
|
|
||||||
|
### `matcha doctor`
|
||||||
|
|
||||||
|
The checks whose failures are confusing rather than loud: `experimentalDecorators`
|
||||||
|
missing (every `@Route` becomes a syntax error, and the message blames the
|
||||||
|
decorator), a core pin that cannot resolve, an installed version that does not
|
||||||
|
match the manifest, an entry that does not export `app`, and `@Ws`/multipart
|
||||||
|
routes whose optional peer dependency is not installed — core lazy-loads `ws`
|
||||||
|
and `busboy`, so those compile and fail at the first request instead.
|
||||||
|
|
||||||
|
Every check is a file read: no runtime is spawned and nothing is fetched, so it
|
||||||
|
works before the project installs. Exits non-zero on a `✗`.
|
||||||
|
|
||||||
## Runtime detection
|
## Runtime detection
|
||||||
|
|
||||||
`matcha run` picks the runtime by precedence, first match wins:
|
`matcha run` picks the runtime by precedence, first match wins:
|
||||||
|
|
||||||
1. `matcha.toml` — `runtime = "node" | "deno" | "bun"`
|
1. `matcha.toml` — `runtime = "node" | "deno" | "bun" | "edge"`
|
||||||
2. `deno.json` / `deno.jsonc` → **deno**
|
2. `wrangler.toml` / `wrangler.jsonc` → **edge**
|
||||||
3. `bun.lockb` / `bun.lock` → **bun**
|
3. `deno.json` / `deno.jsonc` → **deno**
|
||||||
4. `package.json` → **node**
|
4. `bun.lockb` / `bun.lock` → **bun**
|
||||||
|
5. `package.json` → **node**
|
||||||
|
|
||||||
Edge is a deploy target, not a `matcha run` target.
|
`wrangler.toml` is checked before `package.json` because an edge project has both.
|
||||||
|
|
||||||
|
### Edge
|
||||||
|
|
||||||
|
`matcha new my-api --runtime edge` scaffolds a Cloudflare Worker: `wrangler.toml`
|
||||||
|
with `nodejs_compat`, `edgeHandler(app)` as the default export, and wrangler's
|
||||||
|
`[assets]` serving `./public` — so `/` is the same page as on the other runtimes
|
||||||
|
and `/zen` is the same stream, from the worker. `matcha run` is `wrangler dev`,
|
||||||
|
which boots real workerd locally.
|
||||||
|
|
||||||
|
Two differences the edge cannot hide. `@Html('file')`, `static` and multipart
|
||||||
|
uploads need a filesystem workerd does not have, and shutdown teardown never
|
||||||
|
runs — an isolate is discarded, not closed.
|
||||||
|
|
||||||
|
## 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
|
## License
|
||||||
|
|
||||||
|
|||||||
+32
-10
@@ -1,14 +1,17 @@
|
|||||||
#!/bin/sh
|
#!/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
|
# curl -fsSL <raw>/install.sh | sh
|
||||||
# Env: MATCHA_VERSION (tag, default latest), MATCHA_INSTALL_DIR (default ~/.local/bin),
|
# 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
|
set -eu
|
||||||
|
|
||||||
REPO_BASE="${MATCHA_REPO_BASE:-https://git.svc.zoit.services/Green-Tea/matcha}"
|
# Public by default: the Gitea host is unreachable outside the network, and this script
|
||||||
# The API lives at the host root (/api/v1/...), NOT under the repo path. Keep it
|
# is what crates.io and the README point people at.
|
||||||
# separate from REPO_BASE (which is used for release DOWNLOAD urls under the repo).
|
REPO_BASE="${MATCHA_REPO_BASE:-https://github.com/Expressive-Tea/matcha}"
|
||||||
API_BASE="${MATCHA_API_BASE:-https://git.svc.zoit.services/api/v1/repos/Green-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}"
|
INSTALL_DIR="${MATCHA_INSTALL_DIR:-$HOME/.local/bin}"
|
||||||
|
|
||||||
err() { echo "matcha-install: $*" >&2; exit 1; }
|
err() { echo "matcha-install: $*" >&2; exit 1; }
|
||||||
@@ -42,17 +45,36 @@ case "$os" in
|
|||||||
Linux)
|
Linux)
|
||||||
case "$arch" in
|
case "$arch" in
|
||||||
x86_64|amd64) triple="x86_64-unknown-linux-musl" ;;
|
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" ;;
|
*) err "unsupported Linux arch: $arch" ;;
|
||||||
esac ;;
|
esac ;;
|
||||||
*) err "unsupported OS: $os — try: cargo install --git $REPO_BASE" ;;
|
*) err "unsupported OS: $os — try: cargo install --git $REPO_BASE" ;;
|
||||||
esac
|
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}"
|
version="${MATCHA_VERSION:-latest}"
|
||||||
if [ "$version" = "latest" ]; then
|
if [ "$version" = "latest" ]; then
|
||||||
tag=$(fetch "$API_BASE/releases/latest" \
|
tag=$(resolve_latest)
|
||||||
| grep -o '"tag_name":[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4)
|
[ -n "$tag" ] || err "could not resolve the latest release tag.
|
||||||
[ -n "$tag" ] || err "could not resolve 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
|
else
|
||||||
tag="$version"
|
tag="$version"
|
||||||
fi
|
fi
|
||||||
|
|||||||
Executable
+117
@@ -0,0 +1,117 @@
|
|||||||
|
#!/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|edge>
|
||||||
|
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=""
|
||||||
|
# `matcha run` is started in its own process group (set -m below) so the whole tree dies
|
||||||
|
# together. `pkill -P` reached only direct children: on edge, wrangler's workerd is a
|
||||||
|
# grandchild, kept writing demo/.wrangler, and `rm -rf` failed with "Directory not empty".
|
||||||
|
stop_server() {
|
||||||
|
[ -n "$SERVER" ] || return 0
|
||||||
|
kill -- -"$SERVER" 2>/dev/null || true
|
||||||
|
wait "$SERVER" 2>/dev/null || true
|
||||||
|
SERVER=""
|
||||||
|
}
|
||||||
|
cleanup() {
|
||||||
|
stop_server
|
||||||
|
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)"
|
||||||
|
set -m
|
||||||
|
"$MATCHA" run >"$WORK/server.log" 2>&1 &
|
||||||
|
SERVER=$!
|
||||||
|
set +m
|
||||||
|
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"
|
||||||
|
|
||||||
|
stop_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 cookie; do
|
||||||
|
"$MATCHA" add "$cap" >/dev/null || { echo "matcha add $cap failed"; exit 1; }
|
||||||
|
done
|
||||||
|
"$MATCHA" create transformer Csv >/dev/null || { echo "matcha create transformer failed"; exit 1; }
|
||||||
|
"${CHECK[@]}" || { echo "the generated handlers do not type-check"; exit 1; }
|
||||||
|
echo "✓ every add capability type-checks"
|
||||||
|
|
||||||
|
echo "✓ $RUNTIME starter is good"
|
||||||
+226
@@ -0,0 +1,226 @@
|
|||||||
|
//! Questions for a person at a terminal, and defaults for everyone else.
|
||||||
|
//!
|
||||||
|
//! Off a TTY (CI, a pipe, a script) nothing is asked: each question takes its
|
||||||
|
//! default, and one without a default is an error naming the flag to pass.
|
||||||
|
//! Blocking on a read that nobody will ever answer is the one thing this must
|
||||||
|
//! never do.
|
||||||
|
|
||||||
|
use std::io::{self, BufRead, IsTerminal, Write};
|
||||||
|
|
||||||
|
pub struct Ask<R, W> {
|
||||||
|
interactive: bool,
|
||||||
|
input: R,
|
||||||
|
output: W,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ask<io::StdinLock<'static>, io::Stderr> {
|
||||||
|
/// Prompts go to stderr, so stdout stays the report of what was written.
|
||||||
|
pub fn stdio() -> Self {
|
||||||
|
Ask::new(io::stdin().is_terminal(), io::stdin().lock(), io::stderr())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: BufRead, W: Write> Ask<R, W> {
|
||||||
|
pub fn new(interactive: bool, input: R, output: W) -> Self {
|
||||||
|
Ask {
|
||||||
|
interactive,
|
||||||
|
input,
|
||||||
|
output,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A line for the person answering; silent off a TTY.
|
||||||
|
pub fn say(&mut self, text: &str) -> io::Result<()> {
|
||||||
|
if self.interactive {
|
||||||
|
writeln!(self.output, "{text}")?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line(&mut self, prompt: &str) -> io::Result<String> {
|
||||||
|
write!(self.output, "{prompt} ")?;
|
||||||
|
self.output.flush()?;
|
||||||
|
let mut answer = String::new();
|
||||||
|
if self.input.read_line(&mut answer)? == 0 {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::UnexpectedEof,
|
||||||
|
"no answer (end of input)",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(answer.trim().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn yes_no(&mut self, question: &str, default: bool) -> io::Result<bool> {
|
||||||
|
if !self.interactive {
|
||||||
|
return Ok(default);
|
||||||
|
}
|
||||||
|
let hint = if default { "(Y/n)" } else { "(y/N)" };
|
||||||
|
let answer = self.line(&format!("{question} {hint}"))?.to_lowercase();
|
||||||
|
Ok(match answer.as_str() {
|
||||||
|
"" => default,
|
||||||
|
"y" | "yes" => true,
|
||||||
|
_ => false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One of `choices`, each `(key, value)`: the answer may be the key or the
|
||||||
|
/// value, and Enter takes `default`. Anything else is asked again. Quietly
|
||||||
|
/// taking the default would turn a typed `npm` into a JSR-only package.
|
||||||
|
pub fn choice(
|
||||||
|
&mut self,
|
||||||
|
question: &str,
|
||||||
|
choices: &[(&str, &'static str)],
|
||||||
|
default: &'static str,
|
||||||
|
flag: &str,
|
||||||
|
) -> io::Result<&'static str> {
|
||||||
|
if !self.interactive {
|
||||||
|
return Ok(default);
|
||||||
|
}
|
||||||
|
let keys: Vec<&str> = choices.iter().map(|(k, _)| *k).collect();
|
||||||
|
loop {
|
||||||
|
let answer = self.line(question)?.to_lowercase();
|
||||||
|
if answer.is_empty() {
|
||||||
|
return Ok(default);
|
||||||
|
}
|
||||||
|
if let Some((_, v)) = choices.iter().find(|(k, v)| answer == *k || answer == *v) {
|
||||||
|
return Ok(v);
|
||||||
|
}
|
||||||
|
writeln!(self.output, "answer {} (or pass {flag})", keys.join(" or "))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `flag` names what to pass instead, for the error off a TTY.
|
||||||
|
pub fn text(
|
||||||
|
&mut self,
|
||||||
|
question: &str,
|
||||||
|
default: Option<&str>,
|
||||||
|
flag: &str,
|
||||||
|
) -> io::Result<String> {
|
||||||
|
if !self.interactive {
|
||||||
|
return default.map(str::to_string).ok_or_else(|| {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("no terminal to ask on; pass {flag}"),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let prompt = match default {
|
||||||
|
Some(d) => format!("{question} ({d})"),
|
||||||
|
None => question.to_string(),
|
||||||
|
};
|
||||||
|
loop {
|
||||||
|
let answer = self.line(&prompt)?;
|
||||||
|
if !answer.is_empty() {
|
||||||
|
return Ok(answer);
|
||||||
|
}
|
||||||
|
if let Some(d) = default {
|
||||||
|
return Ok(d.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
|
fn scripted(answers: &str) -> Ask<Cursor<Vec<u8>>, Vec<u8>> {
|
||||||
|
Ask::new(true, Cursor::new(answers.as_bytes().to_vec()), Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn piped() -> Ask<Cursor<Vec<u8>>, Vec<u8>> {
|
||||||
|
Ask::new(false, Cursor::new(Vec::new()), Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn yes_no_takes_the_default_on_enter_and_reads_y() {
|
||||||
|
assert!(!scripted("\n").yes_no("Package?", false).unwrap());
|
||||||
|
assert!(scripted("y\n").yes_no("Package?", false).unwrap());
|
||||||
|
assert!(scripted("YES\n").yes_no("Package?", false).unwrap());
|
||||||
|
assert!(!scripted("nope\n").yes_no("Package?", false).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_takes_the_default_on_enter() {
|
||||||
|
assert_eq!(
|
||||||
|
scripted("\n")
|
||||||
|
.text("Folder?", Some("plugins"), "--folder")
|
||||||
|
.unwrap(),
|
||||||
|
"plugins"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
scripted("lib\n")
|
||||||
|
.text("Folder?", Some("plugins"), "--folder")
|
||||||
|
.unwrap(),
|
||||||
|
"lib"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_without_a_default_asks_again_until_answered() {
|
||||||
|
assert_eq!(
|
||||||
|
scripted("\n\nalgo\n").text("Name?", None, "NAME").unwrap(),
|
||||||
|
"algo"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn text_errors_on_eof() {
|
||||||
|
let err = scripted("").text("Name?", None, "NAME").unwrap_err();
|
||||||
|
assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn choice_asks_again_on_an_answer_that_is_not_offered() {
|
||||||
|
let mut ask = scripted("npm\n3\n2\n");
|
||||||
|
let picked = ask
|
||||||
|
.choice(
|
||||||
|
"Publish to:",
|
||||||
|
&[("1", "jsr"), ("2", "both")],
|
||||||
|
"jsr",
|
||||||
|
"--registry",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(picked, "both");
|
||||||
|
let shown = String::from_utf8(ask.output.clone()).unwrap();
|
||||||
|
assert!(shown.contains("answer 1 or 2"), "{shown}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn choice_takes_the_default_on_enter_and_off_a_tty() {
|
||||||
|
let choices = [("1", "jsr"), ("2", "both")];
|
||||||
|
assert_eq!(
|
||||||
|
scripted("\n")
|
||||||
|
.choice("P?", &choices, "jsr", "--registry")
|
||||||
|
.unwrap(),
|
||||||
|
"jsr"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
scripted("both\n")
|
||||||
|
.choice("P?", &choices, "jsr", "--registry")
|
||||||
|
.unwrap(),
|
||||||
|
"both"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
piped().choice("P?", &choices, "jsr", "--registry").unwrap(),
|
||||||
|
"jsr"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn off_a_tty_nothing_is_asked() {
|
||||||
|
let mut ask = piped();
|
||||||
|
assert!(!ask.yes_no("Package?", false).unwrap());
|
||||||
|
assert_eq!(
|
||||||
|
ask.text("Folder?", Some("plugins"), "--folder").unwrap(),
|
||||||
|
"plugins"
|
||||||
|
);
|
||||||
|
let err = ask.text("Name?", None, "the NAME argument").unwrap_err();
|
||||||
|
assert!(err.to_string().contains("the NAME argument"), "{err}");
|
||||||
|
assert!(
|
||||||
|
ask.output.is_empty(),
|
||||||
|
"nothing is printed when nobody is there to answer"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -5,7 +5,7 @@ fn check_command(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
|||||||
match rt {
|
match rt {
|
||||||
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
Runtime::Deno => ("deno", vec!["check", "src/app.module.ts"]),
|
||||||
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
Runtime::Bun => ("bunx", vec!["tsc", "--noEmit"]),
|
||||||
Runtime::Node => ("npx", vec!["tsc", "--noEmit"]),
|
Runtime::Node | Runtime::Edge => ("npx", vec!["tsc", "--noEmit"]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+90
-4
@@ -1,5 +1,8 @@
|
|||||||
|
use clap::builder::PossibleValuesParser;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
|
|
||||||
|
use crate::{cmd_add, cmd_create};
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(name = "matcha", version, about = "green-tea CLI")]
|
#[command(name = "matcha", version, about = "green-tea CLI")]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
@@ -14,22 +17,105 @@ pub enum Command {
|
|||||||
name: String,
|
name: String,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
template_url: Option<String>,
|
template_url: Option<String>,
|
||||||
#[arg(long, default_value = "node", value_parser = ["node", "deno", "bun"])]
|
#[arg(long, default_value = "node", value_parser = ["node", "deno", "bun", "edge"])]
|
||||||
runtime: String,
|
runtime: String,
|
||||||
},
|
},
|
||||||
/// Detect the runtime and run the project in watch mode
|
/// Detect the runtime and run the project in watch mode
|
||||||
Run,
|
Run,
|
||||||
/// Generate a piece and auto-wire it into the module
|
/// Generate a piece and auto-wire it into the module
|
||||||
Create {
|
Create {
|
||||||
#[arg(value_parser = ["module", "controller", "step", "provider"])]
|
#[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))]
|
||||||
kind: String,
|
kind: String,
|
||||||
name: String,
|
/// Required for every kind but `plugin`, which asks for it
|
||||||
|
name: Option<String>,
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
check: bool,
|
check: bool,
|
||||||
|
/// plugin: a package of its own, in --package=DIR (default: the current directory, which must be empty)
|
||||||
|
#[arg(long, num_args = 0..=1, require_equals = true, value_name = "DIR")]
|
||||||
|
package: Option<Option<String>>,
|
||||||
|
/// plugin, in-app: folder relative to the project root (default: plugins)
|
||||||
|
#[arg(long)]
|
||||||
|
folder: Option<String>,
|
||||||
|
/// plugin, package: the JSR scope
|
||||||
|
#[arg(long)]
|
||||||
|
scope: Option<String>,
|
||||||
|
/// plugin, package: where it publishes (default: jsr)
|
||||||
|
#[arg(long, value_parser = ["jsr", "both"])]
|
||||||
|
registry: Option<String>,
|
||||||
|
/// plugin, package, both: the npm name (default: @<scope>/green-tea-<slug>)
|
||||||
|
#[arg(long)]
|
||||||
|
npm_name: Option<String>,
|
||||||
|
},
|
||||||
|
/// Check the project for the misconfigurations that fail confusingly
|
||||||
|
Doctor,
|
||||||
|
/// Write AGENTS.md and CLAUDE.md: green-tea's rules for coding agents
|
||||||
|
Agents {
|
||||||
|
/// Overwrite the files if they exist
|
||||||
|
#[arg(long)]
|
||||||
|
force: bool,
|
||||||
|
},
|
||||||
|
/// 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>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
|
},
|
||||||
|
/// List every route, its transport, and the chain it runs
|
||||||
|
Routes {
|
||||||
|
#[arg(long)]
|
||||||
|
entry: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
out: Option<String>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
|
},
|
||||||
|
/// List every token: who provides it and who needs it
|
||||||
|
Tokens {
|
||||||
|
#[arg(long)]
|
||||||
|
entry: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
out: Option<String>,
|
||||||
|
/// Print the answer as JSON, for a program or an agent
|
||||||
|
#[arg(long)]
|
||||||
|
json: bool,
|
||||||
},
|
},
|
||||||
/// Add a capability to a controller
|
/// Add a capability to a controller
|
||||||
Add {
|
Add {
|
||||||
#[arg(value_parser = ["sse", "stream", "buffer"])]
|
#[arg(value_parser = PossibleValuesParser::new(cmd_add::names()))]
|
||||||
capability: String,
|
capability: String,
|
||||||
|
/// Which controller to edit (default: the only one in src/controllers)
|
||||||
|
#[arg(long)]
|
||||||
|
controller: Option<String>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
+291
-54
@@ -1,66 +1,231 @@
|
|||||||
//! `matcha add <sse|stream|buffer>` — appends a capability handler method to
|
//! `matcha add <capability>` — append a ready handler to a controller, with the
|
||||||
//! the single controller found under `src/controllers`, wiring in the
|
//! decorator imports it needs merged into the existing `@green-tea/core` import.
|
||||||
//! decorator import via `wire::add_import` and splicing the method body via
|
//!
|
||||||
//! `wire::insert_method`.
|
//! 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::io::{Error, ErrorKind};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use crate::wire;
|
use crate::wire;
|
||||||
|
|
||||||
/// Returns `(decorator symbol, method source, dedup marker)` for a known
|
/// A handler `matcha add` can splice into a controller.
|
||||||
/// capability, or `None` for an unrecognized one.
|
struct Capability {
|
||||||
///
|
/// Name as typed on the command line.
|
||||||
/// The dedup marker is the route-path string literal baked into that
|
name: &'static str,
|
||||||
/// capability's `handler()` template (e.g. `'/events'`, `'/stream'`,
|
/// Symbols merged into the controller's `@green-tea/core` value import.
|
||||||
/// `'/data'`). It is unique per capability, unlike the decorator name — both
|
imports: &'static [&'static str],
|
||||||
/// `buffer` and any pre-existing handler can legitimately use `@Get` — so
|
/// Symbols that must arrive as `import type`, because they appear in a
|
||||||
/// it's what `run` checks for before inserting, to keep `matcha add <cap>`
|
/// decorated signature. See [`wire::add_type_import`].
|
||||||
/// idempotent per capability rather than per decorator.
|
type_imports: &'static [&'static str],
|
||||||
fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> {
|
/// The method source, spliced before the class's closing brace.
|
||||||
match cap {
|
method: &'static str,
|
||||||
"sse" => Some((
|
/// The route-path literal baked into `method`, used to keep the insert
|
||||||
"Sse",
|
/// idempotent. It is the marker rather than the decorator name because a
|
||||||
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
/// decorator is not unique — `buffer` uses `@Get`, and so does any handler
|
||||||
"'/events'",
|
/// the user already wrote.
|
||||||
)),
|
marker: &'static str,
|
||||||
"stream" => Some((
|
/// An optional peer dependency the handler needs at runtime, and the
|
||||||
"Stream",
|
/// runtimes that need it. green-tea lazy-loads both, so a missing one is a
|
||||||
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
/// clear error at the first request rather than a crash at boot — but it is
|
||||||
"'/stream'",
|
/// still an error, and the person who just generated the handler is the one
|
||||||
)),
|
/// who can avoid it.
|
||||||
"buffer" => Some((
|
peer: Option<(&'static str, &'static str)>,
|
||||||
"Get",
|
|
||||||
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
|
||||||
"'/data'",
|
|
||||||
)),
|
|
||||||
_ => None,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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")),
|
||||||
|
},
|
||||||
|
Capability {
|
||||||
|
name: "cookie",
|
||||||
|
// Reading is a decorator. Writing is a `Set-Cookie` header, which core only builds
|
||||||
|
// (`setCookie`) and a transformer sends: core has no response-cookie API of its own.
|
||||||
|
imports: &["Get", "Post", "Transformer", "body", "cookie", "setCookie"],
|
||||||
|
type_imports: &[],
|
||||||
|
method: r#"
|
||||||
|
@Get('/prefs')
|
||||||
|
prefs(@cookie('theme') theme?: string) {
|
||||||
|
return { theme: theme ?? 'light' };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/prefs')
|
||||||
|
@Transformer((value) => {
|
||||||
|
const { theme } = value as { theme: string };
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
'content-type': 'application/json',
|
||||||
|
// Secure and HttpOnly are on by default. Safari, a LAN IP or a plain-HTTP host other
|
||||||
|
// than localhost drops a Secure cookie: pass `secure: false` there in development.
|
||||||
|
'set-cookie': setCookie('theme', encodeURIComponent(theme), { maxAge: 60 * 60 * 24 * 365 }),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ theme }),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
savePrefs(@body('theme') theme: string) {
|
||||||
|
return { theme };
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
marker: "'/prefs'",
|
||||||
|
peer: None,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/// 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}"),
|
||||||
|
))
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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> {
|
|
||||||
let dir = std::path::Path::new("src/controllers");
|
let dir = std::path::Path::new("src/controllers");
|
||||||
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
|
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
|
||||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||||
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
|
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
|
||||||
.collect();
|
.collect();
|
||||||
|
hits.sort();
|
||||||
match hits.len() {
|
match hits.len() {
|
||||||
1 => Ok(hits.pop().unwrap()),
|
1 => Ok(hits.pop().unwrap()),
|
||||||
0 => Err(Error::new(
|
0 => Err(Error::new(
|
||||||
ErrorKind::NotFound,
|
ErrorKind::NotFound,
|
||||||
"no *.controller.ts in src/controllers",
|
"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
|
/// Extracts the class name following `export class `. A plain text scan rather
|
||||||
/// scan rather than a tree-sitter query — `insert_method` does the real
|
/// than a tree-sitter query — `insert_method` does the grammar-aware work once
|
||||||
/// grammar-aware work once the name is known.
|
/// the name is known.
|
||||||
fn class_name(src: &str) -> Option<String> {
|
fn class_name(src: &str) -> Option<String> {
|
||||||
let idx = src.find("export class ")? + "export class ".len();
|
let idx = src.find("export class ")? + "export class ".len();
|
||||||
let rest = &src[idx..];
|
let rest = &src[idx..];
|
||||||
@@ -68,31 +233,103 @@ fn class_name(src: &str) -> Option<String> {
|
|||||||
Some(rest[..end].to_string())
|
Some(rest[..end].to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run(cap: &str) -> std::io::Result<()> {
|
pub fn run(cap: &str, controller: Option<&str>) -> std::io::Result<()> {
|
||||||
let (decorator, method, marker) = handler(cap)
|
let capability = find(cap).ok_or_else(|| {
|
||||||
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
Error::new(
|
||||||
let path = only_controller()?;
|
ErrorKind::InvalidInput,
|
||||||
|
format!("unknown capability {cap} (try: {})", names().join(", ")),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let path = resolve_controller(controller)?;
|
||||||
let src = std::fs::read_to_string(&path)?;
|
let src = std::fs::read_to_string(&path)?;
|
||||||
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
|
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}");
|
println!("→ {cap} already present in {class}");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
// wire::add_import merges `decorator` into an existing
|
|
||||||
// `import { ... } from '@green-tea/core';` brace when one is already
|
// add_import merges each symbol into an existing
|
||||||
// present, rather than appending a second import line for the same
|
// `import { ... } from '@green-tea/core';` brace rather than appending a
|
||||||
// module (which would be a duplicate ESM binding — a hard SyntaxError,
|
// second import line for the same module — which would be a duplicate ESM
|
||||||
// not a harmless dupe).
|
// binding, a hard SyntaxError rather than a harmless dupe.
|
||||||
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
|
let mut edited = src;
|
||||||
match wire::insert_method(&with_import, &class, &method) {
|
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) => {
|
Some(out) => {
|
||||||
std::fs::write(&path, 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!(
|
None => println!(
|
||||||
"→ could not edit {}; add @{decorator} handler manually",
|
"→ could not edit {}; add the {cap} handler manually",
|
||||||
path.display()
|
path.display()
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
Ok(())
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! `matcha agents` — write `AGENTS.md` and `CLAUDE.md` into a project that was
|
||||||
|
//! scaffolded before matcha wrote them, so a coding agent opening it finds
|
||||||
|
//! green-tea's rules instead of applying Express habits.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::template::{self, AGENT_FILES, CORE_VERSION};
|
||||||
|
|
||||||
|
pub fn run(dir: &Path, force: bool) -> std::io::Result<()> {
|
||||||
|
let name = project_name(dir);
|
||||||
|
let version = core_version(dir).unwrap_or_else(|| CORE_VERSION.to_string());
|
||||||
|
|
||||||
|
for file in AGENT_FILES {
|
||||||
|
let path = dir.join(file);
|
||||||
|
if path.exists() && !force {
|
||||||
|
println!("· {file} exists, left as is (--force to overwrite)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let contents = template::agent_file(file, &name, &version)
|
||||||
|
.expect("agent files are embedded in the binary");
|
||||||
|
std::fs::write(&path, contents)?;
|
||||||
|
println!("✓ {file}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `package.json`'s `name`, else the directory's.
|
||||||
|
fn project_name(dir: &Path) -> String {
|
||||||
|
std::fs::read_to_string(dir.join("package.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|pkg| field(&pkg, "\"name\""))
|
||||||
|
.or_else(|| {
|
||||||
|
std::fs::canonicalize(dir)
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| "this project".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The core version the project actually depends on, so the file names the
|
||||||
|
/// version whose rules apply: `package.json` (npm, Bun, edge) or `deno.json`'s
|
||||||
|
/// `jsr:@green-tea/core@…` import.
|
||||||
|
fn core_version(dir: &Path) -> Option<String> {
|
||||||
|
if let Ok(pkg) = std::fs::read_to_string(dir.join("package.json")) {
|
||||||
|
if let Some(v) = field(&pkg, "\"@green-tea/core\"") {
|
||||||
|
return Some(v.trim_start_matches(['^', '~', '=']).to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let deno = std::fs::read_to_string(dir.join("deno.json")).ok()?;
|
||||||
|
let at = deno.find("@green-tea/core@")? + "@green-tea/core@".len();
|
||||||
|
Some(
|
||||||
|
deno[at..]
|
||||||
|
.chars()
|
||||||
|
.take_while(|c| !matches!(c, '"' | '/'))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The string value after `key:` in a JSON text. Enough for the two flat
|
||||||
|
/// fields read here, without a JSON parse of a file that may not be valid.
|
||||||
|
fn field(json: &str, key: &str) -> Option<String> {
|
||||||
|
let rest = &json[json.find(key)? + key.len()..];
|
||||||
|
let rest = rest
|
||||||
|
.trim_start()
|
||||||
|
.strip_prefix(':')?
|
||||||
|
.trim_start()
|
||||||
|
.strip_prefix('"')?;
|
||||||
|
Some(rest[..rest.find('"')?].to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn writes_both_files_with_the_projects_own_core_version() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
d.path().join("package.json"),
|
||||||
|
r#"{ "name": "shop", "dependencies": { "@green-tea/core": "26.9.0-beta.1" } }"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
run(d.path(), false).unwrap();
|
||||||
|
let agents = std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap();
|
||||||
|
assert!(agents.contains("# AGENTS.md — shop"));
|
||||||
|
assert!(agents.contains("26.9.0-beta.1"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("CLAUDE.md"))
|
||||||
|
.unwrap()
|
||||||
|
.trim(),
|
||||||
|
"@AGENTS.md"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn leaves_an_existing_file_alone_unless_forced() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::write(d.path().join("AGENTS.md"), "mine").unwrap();
|
||||||
|
run(d.path(), false).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap(),
|
||||||
|
"mine"
|
||||||
|
);
|
||||||
|
run(d.path(), true).unwrap();
|
||||||
|
assert_ne!(
|
||||||
|
std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap(),
|
||||||
|
"mine"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_the_version_from_a_deno_import() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
d.path().join("deno.json"),
|
||||||
|
r#"{ "imports": { "@green-tea/core": "jsr:@green-tea/core@26.9.0-beta.2" } }"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(core_version(d.path()).as_deref(), Some("26.9.0-beta.2"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+174
-58
@@ -5,63 +5,149 @@
|
|||||||
use std::io::{Error, ErrorKind};
|
use std::io::{Error, ErrorKind};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::wire;
|
use crate::{entry, naming, 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> {
|
||||||
|
["module"]
|
||||||
|
.into_iter()
|
||||||
|
.chain(PIECES.iter().map(|p| p.kind))
|
||||||
|
.chain(["transformer", "plugin"])
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens core already owns. A step or provider that provides one fails `createApp` (the framework
|
||||||
|
/// tokens) or shadows what every route reads from the request (the request tokens).
|
||||||
|
const TAKEN_TOKENS: &[&str] = &[
|
||||||
|
"logger", "rooms", "events", "bus", "req", "params", "query", "body", "headers", "cookies",
|
||||||
|
"inbound", "abort",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// `Users` stays `Users`; `current-user`, `current_user` and `current user` become `CurrentUser`.
|
||||||
|
/// `None` for anything that cannot become a TypeScript class name.
|
||||||
|
fn class_name(name: &str) -> Option<String> {
|
||||||
|
let name = name.trim();
|
||||||
|
if name.starts_with(|c: char| c.is_ascii_alphabetic())
|
||||||
|
&& name.chars().all(|c| c.is_ascii_alphanumeric())
|
||||||
|
{
|
||||||
|
let (first, rest) = name.split_at(1);
|
||||||
|
return Some(first.to_ascii_uppercase() + rest);
|
||||||
|
}
|
||||||
|
naming::slug(name).map(|s| naming::pascal(&s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The token a step or provider named `CurrentUser` provides: `currentUser`.
|
||||||
|
fn token(class: &str) -> String {
|
||||||
|
let (first, rest) = class.split_at(1);
|
||||||
|
first.to_ascii_lowercase() + rest
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refuses to replace a file the person may already have edited.
|
||||||
|
fn write_new(file: &Path, contents: String) -> std::io::Result<()> {
|
||||||
|
if file.exists() {
|
||||||
|
return Err(Error::new(
|
||||||
|
ErrorKind::AlreadyExists,
|
||||||
|
format!(
|
||||||
|
"{} already exists; matcha create does not overwrite it",
|
||||||
|
file.display()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(file.parent().unwrap())?;
|
||||||
|
std::fs::write(file, contents)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
||||||
match kind {
|
let Some(class) = class_name(name) else {
|
||||||
"controller" => create_piece(
|
return Err(Error::new(
|
||||||
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(
|
|
||||||
ErrorKind::InvalidInput,
|
ErrorKind::InvalidInput,
|
||||||
format!("unknown kind {other}"),
|
format!("'{name}' cannot name a class: use letters and digits, starting with a letter (Users, CurrentUser, current-user)"),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let name = class.as_str();
|
||||||
|
if (kind == "step" || kind == "provider") && TAKEN_TOKENS.contains(&token(name).as_str()) {
|
||||||
|
return Err(Error::new(
|
||||||
|
ErrorKind::InvalidInput,
|
||||||
|
format!(
|
||||||
|
"a {kind} named {name} would provide '{}', which core already provides; pick another name",
|
||||||
|
token(name)
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if kind == "module" {
|
||||||
|
return create_module(name, check);
|
||||||
|
}
|
||||||
|
if kind == "transformer" {
|
||||||
|
return create_transformer(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 {kind} (try: {})", kinds().join(", ")),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes a piece file under `src/<subdir>/` and wires it into the `@Module`
|
/// 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.
|
/// in `src/app.module.ts`. Emit-only + hint on failure.
|
||||||
#[allow(clippy::too_many_arguments)]
|
fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
|
||||||
fn create_piece(
|
let Piece {
|
||||||
name: &str,
|
subdir,
|
||||||
check: bool,
|
ext,
|
||||||
subdir: &str,
|
suffix,
|
||||||
ext: &str,
|
..
|
||||||
suffix: &str,
|
} = *piece;
|
||||||
module_key: &str,
|
let module_key = subdir;
|
||||||
stub: String,
|
|
||||||
) -> std::io::Result<()> {
|
|
||||||
let lower = name.to_lowercase();
|
let lower = name.to_lowercase();
|
||||||
let file = Path::new("src")
|
let file = Path::new("src")
|
||||||
.join(subdir)
|
.join(subdir)
|
||||||
.join(format!("{lower}.{ext}.ts"));
|
.join(format!("{lower}.{ext}.ts"));
|
||||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
write_new(&file, (piece.stub)(name))?;
|
||||||
std::fs::write(&file, stub)?;
|
|
||||||
println!("✓ {}", file.display());
|
println!("✓ {}", file.display());
|
||||||
|
|
||||||
let symbol = format!("{name}{suffix}");
|
let symbol = format!("{name}{suffix}");
|
||||||
@@ -86,36 +172,66 @@ fn create_piece(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Writes `src/<name>.module.ts` and registers it in the `createApp({ modules })`
|
/// 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<()> {
|
fn create_module(name: &str, check: bool) -> std::io::Result<()> {
|
||||||
let lower = name.to_lowercase();
|
let lower = name.to_lowercase();
|
||||||
let file = Path::new("src").join(format!("{lower}.module.ts"));
|
let file = Path::new("src").join(format!("{lower}.module.ts"));
|
||||||
std::fs::create_dir_all(file.parent().unwrap())?;
|
write_new(&file, module_stub(name))?;
|
||||||
std::fs::write(&file, module_stub(name))?;
|
|
||||||
println!("✓ {}", file.display());
|
println!("✓ {}", file.display());
|
||||||
|
|
||||||
let symbol = format!("{name}Module");
|
let symbol = format!("{name}Module");
|
||||||
let from = format!("./{lower}.module");
|
let from = format!("./{lower}.module");
|
||||||
let main_path = Path::new("src/main.ts");
|
let Some(entry_path) = entry::find(Path::new(".")) else {
|
||||||
if !main_path.exists() {
|
println!(
|
||||||
println!("→ register {symbol} in createApp({{ modules }}) manually (no src/main.ts found)");
|
"→ register {symbol} in createApp({{ modules }}) manually (no {} found)",
|
||||||
|
entry::candidates()
|
||||||
|
);
|
||||||
return maybe_check(check);
|
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);
|
let imported = wire::add_import(&src, &symbol, &from);
|
||||||
match wire::add_to_createapp_modules(&imported, &symbol) {
|
match wire::add_to_createapp_modules(&imported, &symbol) {
|
||||||
Some(wired) => {
|
Some(wired) => {
|
||||||
std::fs::write(main_path, wired)?;
|
std::fs::write(&entry_path, wired)?;
|
||||||
println!("✓ registered {symbol} in createApp");
|
println!("✓ registered {symbol} in createApp");
|
||||||
}
|
}
|
||||||
None => println!(
|
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)
|
maybe_check(check)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn maybe_check(check: bool) -> std::io::Result<()> {
|
/// Writes `src/transformers/<name>.transformer.ts`. Nothing to wire: a transformer is attached
|
||||||
|
/// per route with `@Transformer`, so the hint says where it goes instead.
|
||||||
|
fn create_transformer(name: &str, check: bool) -> std::io::Result<()> {
|
||||||
|
let lower = name.to_lowercase();
|
||||||
|
let file = Path::new("src/transformers").join(format!("{lower}.transformer.ts"));
|
||||||
|
let symbol = format!("{}Transformer", token(name));
|
||||||
|
write_new(&file, transformer_stub(&symbol))?;
|
||||||
|
println!("✓ {}", file.display());
|
||||||
|
println!(
|
||||||
|
"→ attach it to a route: @Transformer({symbol}), imported from './transformers/{lower}.transformer'"
|
||||||
|
);
|
||||||
|
maybe_check(check)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transformer_stub(symbol: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"import type {{ TransformerFn }} from '@green-tea/core';\n\n\
|
||||||
|
/**\n * Turns what a handler returns into the response. Attach it to a route with\n\
|
||||||
|
* `@Transformer({symbol})`; routes without one use the default JSON transformer.\n\
|
||||||
|
* Set the status and headers here (`set-cookie` takes an array, one header per cookie).\n */\n\
|
||||||
|
export const {symbol}: TransformerFn = (value) => ({{\n\
|
||||||
|
status: 200,\n\
|
||||||
|
headers: {{ 'content-type': 'application/json' }},\n\
|
||||||
|
body: JSON.stringify(value),\n\
|
||||||
|
}});\n"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> {
|
||||||
if check {
|
if check {
|
||||||
match crate::check::run(Path::new(".")) {
|
match crate::check::run(Path::new(".")) {
|
||||||
Ok(true) => println!("✓ type-check passed"),
|
Ok(true) => println!("✓ type-check passed"),
|
||||||
@@ -134,14 +250,14 @@ fn controller_stub(name: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn step_stub(name: &str) -> String {
|
fn step_stub(name: &str) -> String {
|
||||||
let lower = name.to_lowercase();
|
let lower = token(name);
|
||||||
format!(
|
format!(
|
||||||
"import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record<string, unknown>) {{\n return {{ {lower}: null }};\n }}\n}}\n"
|
"import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record<string, unknown>) {{\n return {{ {lower}: null }};\n }}\n}}\n"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn provider_stub(name: &str) -> String {
|
fn provider_stub(name: &str) -> String {
|
||||||
let lower = name.to_lowercase();
|
let lower = token(name);
|
||||||
format!(
|
format!(
|
||||||
"import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n"
|
"import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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,311 @@
|
|||||||
|
//! `matcha graph`, `routes`, `tokens`, `explain` and `openapi`: the CLI over
|
||||||
|
//! [`crate::introspect`].
|
||||||
|
//!
|
||||||
|
//! Each command asks one [`Query`] and renders the JSON that comes back, as
|
||||||
|
//! text for a person or, with `--json`, unchanged for a program. An agent
|
||||||
|
//! inspecting an app uses the second form; the future `matcha mcp` serves the
|
||||||
|
//! same documents without going through this file at all.
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::introspect::{self, Diagram, Query, Refusal, Target};
|
||||||
|
|
||||||
|
/// How a command prints its answer.
|
||||||
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
pub enum Render {
|
||||||
|
Text,
|
||||||
|
Json,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
|
||||||
|
pub fn graph(
|
||||||
|
dir: &Path,
|
||||||
|
format: &str,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let (query, render) = match format {
|
||||||
|
"mermaid" => (Query::Diagram(Diagram::Mermaid), Render::Text),
|
||||||
|
"dot" => (Query::Diagram(Diagram::Dot), Render::Text),
|
||||||
|
"json" => (Query::Graph, Render::Json),
|
||||||
|
other => {
|
||||||
|
return Err(Error::new(
|
||||||
|
ErrorKind::InvalidInput,
|
||||||
|
format!("unknown format '{other}' (mermaid, dot, json)"),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
answer(dir, entry, out, &query, render, |data| {
|
||||||
|
data.as_str().unwrap_or_default().to_string()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha routes` — every route, its transport, and the chain it runs.
|
||||||
|
pub fn routes(
|
||||||
|
dir: &Path,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
answer(dir, entry, out, &Query::Routes, render, routes_text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha tokens` — every token, who provides it and who needs it. The
|
||||||
|
/// question to ask before writing `@needs('x')`: does anything provide `x`?
|
||||||
|
pub fn tokens(
|
||||||
|
dir: &Path,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
answer(dir, entry, out, &Query::Tokens, render, tokens_text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `matcha explain <pattern>` — one route's chain, in execution order, with
|
||||||
|
/// each node's needs and provides.
|
||||||
|
///
|
||||||
|
/// The argument is the route *pattern* as declared (`/users/:id`), not a
|
||||||
|
/// concrete URL: `explain` matches the pattern string exactly. A miss 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: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
render: Render,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
answer(
|
||||||
|
dir,
|
||||||
|
entry,
|
||||||
|
out,
|
||||||
|
&Query::Explain(route.to_string()),
|
||||||
|
render,
|
||||||
|
explain_text,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `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: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let query = Query::OpenApi {
|
||||||
|
title: title.map(str::to_string),
|
||||||
|
version: version.map(str::to_string),
|
||||||
|
};
|
||||||
|
answer(dir, entry, out, &query, Render::Json, |_| String::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks, renders, and writes to `out` or stdout. A refusal goes to stderr — as
|
||||||
|
/// JSON under `--json`, so a program reads the same shape either way — and
|
||||||
|
/// exits 1. A failed run has already printed its own diagnosis (the child's
|
||||||
|
/// stderr is inherited), so it exits with no second message on top.
|
||||||
|
fn answer(
|
||||||
|
dir: &Path,
|
||||||
|
entry: Option<&str>,
|
||||||
|
out: Option<&str>,
|
||||||
|
query: &Query,
|
||||||
|
render: Render,
|
||||||
|
text: impl Fn(&Value) -> String,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let target = Target { dir, entry };
|
||||||
|
let data = match introspect::query(&target, query) {
|
||||||
|
Ok(Ok(data)) => data,
|
||||||
|
Ok(Err(refusal)) => {
|
||||||
|
report_refusal(&refusal, render);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == ErrorKind::Other => std::process::exit(1),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut printed = match render {
|
||||||
|
Render::Json => serde_json::to_string_pretty(&data).map_err(Error::other)?,
|
||||||
|
Render::Text => text(&data),
|
||||||
|
};
|
||||||
|
if !printed.ends_with('\n') {
|
||||||
|
printed.push('\n');
|
||||||
|
}
|
||||||
|
match out {
|
||||||
|
Some(file) => {
|
||||||
|
std::fs::write(dir.join(file), &printed)?;
|
||||||
|
println!("✓ {file}");
|
||||||
|
}
|
||||||
|
None => print!("{printed}"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report_refusal(refusal: &Refusal, render: Render) {
|
||||||
|
if render == Render::Json {
|
||||||
|
eprintln!("{}", serde_json::json!({ "error": refusal.0 }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eprintln!("{}", refusal.message());
|
||||||
|
if let Some(registered) = refusal.0["registered"].as_array() {
|
||||||
|
eprintln!("\nregistered patterns:");
|
||||||
|
for r in registered {
|
||||||
|
eprintln!(" {:<6} {}", str_of(&r["method"]), str_of(&r["pattern"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn str_of(v: &Value) -> &str {
|
||||||
|
v.as_str().unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_of(v: &Value) -> Vec<&str> {
|
||||||
|
v.as_array()
|
||||||
|
.map(|a| a.iter().map(str_of).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn routes_text(data: &Value) -> String {
|
||||||
|
let routes = data.as_array().cloned().unwrap_or_default();
|
||||||
|
let width = routes
|
||||||
|
.iter()
|
||||||
|
.map(|r| str_of(&r["method"]).len())
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
routes
|
||||||
|
.iter()
|
||||||
|
.map(|r| {
|
||||||
|
let chain = list_of(&r["chain"]).join(" → ");
|
||||||
|
format!(
|
||||||
|
"{:<width$} {} [{}] {}",
|
||||||
|
str_of(&r["method"]),
|
||||||
|
str_of(&r["pattern"]),
|
||||||
|
str_of(&r["transport"]),
|
||||||
|
chain
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tokens_text(data: &Value) -> String {
|
||||||
|
let names = |v: &Value| {
|
||||||
|
v.as_array()
|
||||||
|
.map(|a| {
|
||||||
|
a.iter()
|
||||||
|
.map(|n| match n["route"].as_str() {
|
||||||
|
Some(route) => format!("{} ({route})", str_of(&n["name"])),
|
||||||
|
None => str_of(&n["name"]).to_string(),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
data.as_array()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
let provided = names(&t["providedBy"]);
|
||||||
|
let needed = names(&t["neededBy"]);
|
||||||
|
format!(
|
||||||
|
"{}\n provided by: {}\n needed by: {}",
|
||||||
|
str_of(&t["token"]),
|
||||||
|
if provided.is_empty() {
|
||||||
|
if t["source"] == "request" {
|
||||||
|
"the request (built in)"
|
||||||
|
} else {
|
||||||
|
"— (nothing provides it)"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
&provided
|
||||||
|
},
|
||||||
|
if needed.is_empty() { "—" } else { &needed },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn explain_text(data: &Value) -> String {
|
||||||
|
let chain = data["chain"].as_array().cloned().unwrap_or_default();
|
||||||
|
let width = chain
|
||||||
|
.iter()
|
||||||
|
.map(|n| str_of(&n["kind"]).len())
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0);
|
||||||
|
let mut lines = vec![format!(
|
||||||
|
"{} {} [{}]",
|
||||||
|
str_of(&data["method"]),
|
||||||
|
str_of(&data["pattern"]),
|
||||||
|
str_of(&data["transport"])
|
||||||
|
)];
|
||||||
|
for n in &chain {
|
||||||
|
let needs = list_of(&n["needs"]);
|
||||||
|
let provides = list_of(&n["provides"]);
|
||||||
|
let mut line = format!(" {:<width$} {}", str_of(&n["kind"]), str_of(&n["name"]));
|
||||||
|
if !needs.is_empty() {
|
||||||
|
line.push_str(&format!(" needs: {}", needs.join(", ")));
|
||||||
|
}
|
||||||
|
if !provides.is_empty() {
|
||||||
|
line.push_str(&format!(" provides: {}", provides.join(", ")));
|
||||||
|
}
|
||||||
|
line.push_str(&format!(" ({})", str_of(&n["origin"])));
|
||||||
|
lines.push(line);
|
||||||
|
}
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explain_text_keeps_the_layout_it_had() {
|
||||||
|
let data = json!({
|
||||||
|
"method": "GET", "pattern": "/users/:id", "transport": "http",
|
||||||
|
"chain": [
|
||||||
|
{ "kind": "provider", "name": "db", "needs": [], "provides": ["db"], "origin": "src/db.ts" },
|
||||||
|
{ "kind": "handler", "name": "Users.get", "needs": ["db"], "provides": [], "origin": "src/users.ts" }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
explain_text(&data),
|
||||||
|
"GET /users/:id [http]\n provider db provides: db (src/db.ts)\n handler Users.get needs: db (src/users.ts)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_text_names_the_request_for_its_built_in_tokens() {
|
||||||
|
let data = json!([{ "token": "req", "source": "request", "providedBy": [], "neededBy": [{ "kind": "step", "name": "user" }] }]);
|
||||||
|
assert_eq!(
|
||||||
|
tokens_text(&data),
|
||||||
|
"req\n provided by: the request (built in)\n needed by: user"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_text_says_when_nothing_provides_a_token() {
|
||||||
|
let data = json!([{ "token": "user", "providedBy": [], "neededBy": [{ "kind": "handler", "name": "Me.get", "route": "/me" }] }]);
|
||||||
|
assert_eq!(
|
||||||
|
tokens_text(&data),
|
||||||
|
"user\n provided by: — (nothing provides it)\n needed by: Me.get (/me)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
//! `matcha create plugin`: an in-app plugin folder by default, or, with
|
||||||
|
//! `--package` or a yes, a package of its own.
|
||||||
|
|
||||||
|
use std::io::{self, BufRead, Error, ErrorKind, Write};
|
||||||
|
use std::path::{Component, Path};
|
||||||
|
|
||||||
|
use crate::ask::Ask;
|
||||||
|
use crate::{entry, naming, plugin_files, wire};
|
||||||
|
|
||||||
|
pub struct Opts {
|
||||||
|
pub name: Option<String>,
|
||||||
|
/// `None`: not asked for. `Some(None)`: `--package` with no directory.
|
||||||
|
pub package: Option<Option<String>>,
|
||||||
|
pub folder: Option<String>,
|
||||||
|
pub scope: Option<String>,
|
||||||
|
pub registry: Option<String>,
|
||||||
|
pub npm_name: Option<String>,
|
||||||
|
pub check: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(opts: Opts) -> io::Result<()> {
|
||||||
|
run_with(opts, &mut Ask::stdio(), Path::new("."))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run_with<R: BufRead, W: Write>(
|
||||||
|
opts: Opts,
|
||||||
|
ask: &mut Ask<R, W>,
|
||||||
|
root: &Path,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
// A NAME given on the command line is checked before any question.
|
||||||
|
if let Some(name) = &opts.name {
|
||||||
|
check_name(name)?;
|
||||||
|
}
|
||||||
|
let package = match opts.package {
|
||||||
|
Some(_) => true,
|
||||||
|
None => ask.yes_no("Separate it as a package?", false)?,
|
||||||
|
};
|
||||||
|
if package {
|
||||||
|
for (flag, given) in [("--folder", opts.folder.is_some()), ("--check", opts.check)] {
|
||||||
|
if given {
|
||||||
|
println!("note: {flag} only applies to an in-app plugin; ignored");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
package_mode(opts, ask, root)
|
||||||
|
} else {
|
||||||
|
for (flag, given) in [
|
||||||
|
("--scope", opts.scope.is_some()),
|
||||||
|
("--registry", opts.registry.is_some()),
|
||||||
|
("--npm-name", opts.npm_name.is_some()),
|
||||||
|
] {
|
||||||
|
if given {
|
||||||
|
println!("note: {flag} only applies to --package; ignored");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
in_app(opts, ask, root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid(msg: String) -> Error {
|
||||||
|
Error::new(ErrorKind::InvalidInput, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The slug for `raw`, or why it cannot be one: not a name, or a factory that
|
||||||
|
/// would be a reserved word.
|
||||||
|
fn check_name(raw: &str) -> io::Result<String> {
|
||||||
|
let slug = naming::slug(raw).ok_or_else(|| {
|
||||||
|
invalid(format!(
|
||||||
|
"'{raw}' does not make a plugin name: start with a letter, and use letters, digits, spaces or hyphens"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let fun = naming::camel(&slug);
|
||||||
|
if naming::is_reserved(&fun) {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"'{raw}' would make the factory `{fun}`, which is a reserved word in TypeScript; pick another name"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(slug)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_slug<R: BufRead, W: Write>(
|
||||||
|
name: Option<String>,
|
||||||
|
ask: &mut Ask<R, W>,
|
||||||
|
) -> io::Result<String> {
|
||||||
|
let raw = match name {
|
||||||
|
Some(n) => n,
|
||||||
|
None => ask.text("Plugin name?", None, "the NAME argument")?,
|
||||||
|
};
|
||||||
|
check_name(&raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Relative, and never climbing out: `..` or an absolute path would put the
|
||||||
|
/// plugin outside the project it is being wired into.
|
||||||
|
fn inside_project(folder: &str) -> bool {
|
||||||
|
!folder.is_empty()
|
||||||
|
&& Path::new(folder)
|
||||||
|
.components()
|
||||||
|
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn in_app<R: BufRead, W: Write>(opts: Opts, ask: &mut Ask<R, W>, root: &Path) -> io::Result<()> {
|
||||||
|
let Some(entry_path) = entry::find(root) else {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"an in-app plugin is wired into createApp, and there is no {} here; run this in a project, or pass --package for a package of its own",
|
||||||
|
entry::candidates()
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let folder = match opts.folder {
|
||||||
|
Some(f) => f,
|
||||||
|
None => ask.text("Folder?", Some("plugins"), "--folder")?,
|
||||||
|
};
|
||||||
|
if !inside_project(&folder) {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"the plugin folder has to be inside the project, got '{folder}'"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
// `.`, `./plugins` and `plugins/` all mean what they say without leaving a
|
||||||
|
// `./` or a trailing slash in the import path.
|
||||||
|
let folder: Vec<String> = Path::new(&folder)
|
||||||
|
.components()
|
||||||
|
.filter_map(|c| match c {
|
||||||
|
Component::Normal(p) => Some(p.to_string_lossy().into_owned()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let folder = folder.join("/");
|
||||||
|
let slug = resolve_slug(opts.name, ask)?;
|
||||||
|
|
||||||
|
let fun = naming::camel(&slug);
|
||||||
|
let src = std::fs::read_to_string(&entry_path)?;
|
||||||
|
let entry_shown = entry_path
|
||||||
|
.strip_prefix(root)
|
||||||
|
.unwrap_or(&entry_path)
|
||||||
|
.display()
|
||||||
|
.to_string();
|
||||||
|
// A second binding of a name the entry already has is a SyntaxError, and it
|
||||||
|
// would break the app rather than only the new plugin.
|
||||||
|
if wire::binds(&src, &fun) {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"{entry_shown} already uses `{fun}`, so the plugin's factory would collide with it; pick another name"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let shown = Path::new(&folder).join(&slug);
|
||||||
|
let dir = root.join(&shown);
|
||||||
|
if dir.exists() {
|
||||||
|
return Err(Error::new(
|
||||||
|
ErrorKind::AlreadyExists,
|
||||||
|
format!("{} already exists", shown.display()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let call = format!("{fun}()");
|
||||||
|
// Both entry candidates live in src/, so the plugin folder is one level up.
|
||||||
|
let from = if folder.is_empty() {
|
||||||
|
format!("../{slug}/index")
|
||||||
|
} else {
|
||||||
|
format!("../{folder}/{slug}/index")
|
||||||
|
};
|
||||||
|
let wired = wire::add_to_createapp(&wire::add_import(&src, &fun, &from), "plugins", &call);
|
||||||
|
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?;
|
||||||
|
println!("✓ {}", shown.join("index.ts").display());
|
||||||
|
|
||||||
|
match wired {
|
||||||
|
Some(wired) => {
|
||||||
|
// The plugin folder and its registration land together or not at
|
||||||
|
// all: a folder left behind would make the rerun say "already exists".
|
||||||
|
if let Err(e) = std::fs::write(&entry_path, wired) {
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
return Err(Error::new(
|
||||||
|
e.kind(),
|
||||||
|
format!(
|
||||||
|
"could not write {entry_shown} ({e}); removed {} again",
|
||||||
|
shown.display()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
println!("✓ registered {call} in createApp");
|
||||||
|
}
|
||||||
|
None => println!(
|
||||||
|
"→ could not auto-register; add {call} to createApp plugins[] in {entry_shown}, and import {{ {fun} }} from '{from}'"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
crate::cmd_create::maybe_check(opts.check)
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_DIR: &str = "a plugin package needs an empty directory, so the package stays self-contained — pass --package=<dir> or run it in an empty folder";
|
||||||
|
const NPM_CONVENTION: &str =
|
||||||
|
"green-tea-<x> is the naming convention; the plugin listing uses it to find green-tea plugins.";
|
||||||
|
|
||||||
|
/// JSR's scope rule: 2 to 20 characters, lowercase letters, digits and
|
||||||
|
/// hyphens, and not starting with a hyphen.
|
||||||
|
fn valid_scope(s: &str) -> bool {
|
||||||
|
(2..=20).contains(&s.len())
|
||||||
|
&& !s.starts_with('-')
|
||||||
|
&& s.chars()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes every file, reporting each; on a failure, the error names the files
|
||||||
|
/// already written, so a half-filled directory is not a mystery on the rerun.
|
||||||
|
fn write_all(dir: &Path, root: &Path, files: &[(String, String)]) -> io::Result<()> {
|
||||||
|
let mut written: Vec<&str> = Vec::new();
|
||||||
|
for (rel, content) in files {
|
||||||
|
let path = dir.join(rel);
|
||||||
|
let result = std::fs::create_dir_all(path.parent().unwrap())
|
||||||
|
.and_then(|()| std::fs::write(&path, content));
|
||||||
|
if let Err(e) = result {
|
||||||
|
let so_far = if written.is_empty() {
|
||||||
|
"none".to_string()
|
||||||
|
} else {
|
||||||
|
written.join(", ")
|
||||||
|
};
|
||||||
|
return Err(Error::new(
|
||||||
|
e.kind(),
|
||||||
|
format!("could not write {rel} ({e}); already written: {so_far}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
println!("✓ {}", path.strip_prefix(root).unwrap_or(&path).display());
|
||||||
|
written.push(rel);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// npm's package name rule, closely enough to catch a typo: optional `@scope/`, lowercase.
|
||||||
|
fn valid_npm_name(s: &str) -> bool {
|
||||||
|
let part = |p: &str| {
|
||||||
|
!p.is_empty()
|
||||||
|
&& !p.starts_with(['.', '_'])
|
||||||
|
&& p.chars()
|
||||||
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "-._~".contains(c))
|
||||||
|
};
|
||||||
|
match s.strip_prefix('@').and_then(|rest| rest.split_once('/')) {
|
||||||
|
Some((scope, name)) => part(scope) && part(name),
|
||||||
|
None => !s.starts_with('@') && part(s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn package_mode<R: BufRead, W: Write>(
|
||||||
|
opts: Opts,
|
||||||
|
ask: &mut Ask<R, W>,
|
||||||
|
root: &Path,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
// The directory is checked before any question: a person should not answer
|
||||||
|
// four questions to be told the folder was never going to work.
|
||||||
|
let dir = match &opts.package {
|
||||||
|
Some(Some(d)) => root.join(d),
|
||||||
|
_ => root.to_path_buf(),
|
||||||
|
};
|
||||||
|
let dir_shown = dir.strip_prefix(root).unwrap_or(&dir).display().to_string();
|
||||||
|
let dir_shown = if dir_shown.is_empty() {
|
||||||
|
".".to_string()
|
||||||
|
} else {
|
||||||
|
dir_shown
|
||||||
|
};
|
||||||
|
if dir.is_file() {
|
||||||
|
return Err(invalid(format!("{dir_shown} is a file; {EMPTY_DIR}")));
|
||||||
|
}
|
||||||
|
if dir.exists() && std::fs::read_dir(&dir)?.next().is_some() {
|
||||||
|
return Err(invalid(format!("{dir_shown}: {EMPTY_DIR}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let slug = resolve_slug(opts.name, ask)?;
|
||||||
|
let scope = match opts.scope {
|
||||||
|
Some(s) => s,
|
||||||
|
None => ask.text("JSR scope?", None, "--scope")?,
|
||||||
|
};
|
||||||
|
let scope = scope.trim_start_matches('@').to_string();
|
||||||
|
if !valid_scope(&scope) {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"'{scope}' is not a JSR scope: 2 to 20 lowercase letters, digits or hyphens, not starting with a hyphen"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let registry = match opts.registry {
|
||||||
|
Some(r) => r,
|
||||||
|
None => {
|
||||||
|
ask.say(&format!("\n{}\n", plugin_files::JSR_BANNER))?;
|
||||||
|
ask.choice(
|
||||||
|
"Publish to: (1) JSR only [default] (2) JSR + npm",
|
||||||
|
&[("1", "jsr"), ("2", "both")],
|
||||||
|
"jsr",
|
||||||
|
"--registry",
|
||||||
|
)?
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let npm = if registry == "both" {
|
||||||
|
let suggested = format!("@{scope}/green-tea-{slug}");
|
||||||
|
let name = match opts.npm_name {
|
||||||
|
Some(n) => n,
|
||||||
|
// The default in parentheses is the suggestion; Enter takes it.
|
||||||
|
None => ask.text("npm package name?", Some(&suggested), "--npm-name")?,
|
||||||
|
};
|
||||||
|
if !valid_npm_name(&name) {
|
||||||
|
return Err(invalid(format!("'{name}' is not a valid npm name")));
|
||||||
|
}
|
||||||
|
let unscoped = name.rsplit('/').next().unwrap_or(&name);
|
||||||
|
if !unscoped.starts_with("green-tea-") {
|
||||||
|
println!("note: {NPM_CONVENTION}");
|
||||||
|
}
|
||||||
|
Some(name)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let package = plugin_files::Package { slug, scope, npm };
|
||||||
|
write_all(&dir, root, &plugin_files::package(&package))?;
|
||||||
|
println!(
|
||||||
|
"→ next: fill in the Runtimes table in README.md, then `deno test` and `deno publish`"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
|
fn opts(name: Option<&str>) -> Opts {
|
||||||
|
Opts {
|
||||||
|
name: name.map(str::to_string),
|
||||||
|
package: None,
|
||||||
|
folder: None,
|
||||||
|
scope: None,
|
||||||
|
registry: None,
|
||||||
|
npm_name: None,
|
||||||
|
check: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A NAME passed on the command line is checked before any question: nobody should answer
|
||||||
|
/// "package?" and "folder?" to learn the name was never going to work. With no answers
|
||||||
|
/// scripted, asking anything would end in an end-of-input error instead.
|
||||||
|
#[test]
|
||||||
|
fn a_bad_name_fails_before_any_question() {
|
||||||
|
let mut ask = Ask::new(true, Cursor::new(Vec::new()), Vec::new());
|
||||||
|
let err = run_with(opts(Some("🍵")), &mut ask, Path::new("/nonexistent")).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("does not make a plugin name"),
|
||||||
|
"{err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn write_all_reports_what_it_wrote_before_failing() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let files = vec![
|
||||||
|
("a".to_string(), "x".to_string()),
|
||||||
|
("a/b".to_string(), "y".to_string()),
|
||||||
|
];
|
||||||
|
let err = write_all(d.path(), d.path(), &files).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("already written: a"), "{err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,9 @@ fn command_for(rt: Runtime) -> (&'static str, Vec<&'static str>) {
|
|||||||
Runtime::Deno => ("deno", vec!["task", "dev"]),
|
Runtime::Deno => ("deno", vec!["task", "dev"]),
|
||||||
Runtime::Bun => ("bun", vec!["run", "dev"]),
|
Runtime::Bun => ("bun", vec!["run", "dev"]),
|
||||||
Runtime::Node => ("npm", vec!["run", "dev"]),
|
Runtime::Node => ("npm", vec!["run", "dev"]),
|
||||||
|
// The scaffold's `dev` script is `wrangler dev`, which boots real
|
||||||
|
// workerd locally — so edge is a `matcha run` target after all.
|
||||||
|
Runtime::Edge => ("npm", vec!["run", "dev"]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,6 +44,10 @@ mod tests {
|
|||||||
assert_eq!(command_for(Runtime::Bun), ("bun", vec!["run", "dev"]));
|
assert_eq!(command_for(Runtime::Bun), ("bun", vec!["run", "dev"]));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
|
fn edge_runs_wrangler_through_the_dev_script() {
|
||||||
|
assert_eq!(command_for(Runtime::Edge), ("npm", vec!["run", "dev"]));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
fn node_watch() {
|
fn node_watch() {
|
||||||
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
assert_eq!(command_for(Runtime::Node), ("npm", vec!["run", "dev"]));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
//! Introspection queries against a project's app: one query in, one JSON
|
||||||
|
//! document out.
|
||||||
|
//!
|
||||||
|
//! This is the data layer under `matcha graph`, `routes`, `tokens`, `explain`
|
||||||
|
//! and `openapi`. The CLI renders what comes back, as text or with `--json` as
|
||||||
|
//! it is; a future `matcha mcp` serves the same documents as tools. Keeping the
|
||||||
|
//! JSON as the contract is what lets that server be a thin layer over
|
||||||
|
//! [`query`] rather than a second implementation, and it is why the human
|
||||||
|
//! formatting lives in Rust (`cmd_graph`) instead of in the generated script.
|
||||||
|
//!
|
||||||
|
//! How a query runs: write a short script next to the project, import its entry
|
||||||
|
//! file, `await app.ready()`, print one JSON envelope, delete the script.
|
||||||
|
//! `ready()` resolves the graph and is documented as *not* running provider
|
||||||
|
//! factories, so asking about the graph does not open database connections. It
|
||||||
|
//! is also required: on a mesh app the graph is not knowable until its teapots
|
||||||
|
//! have been asked, and `graph()`/`explain()` throw until then.
|
||||||
|
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::entry;
|
||||||
|
use crate::runtime::{self, Runtime};
|
||||||
|
|
||||||
|
/// Written into the project root so the runtime resolves `@green-tea/core` from
|
||||||
|
/// the project's own `node_modules`/import map, then removed. Dotted so it is
|
||||||
|
/// invisible to a `src/**` glob if a run dies before cleanup.
|
||||||
|
const SCRIPT_NAME: &str = ".matcha-introspect.ts";
|
||||||
|
|
||||||
|
/// What to ask the app. Each variant is one future MCP tool.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum Query {
|
||||||
|
/// The whole graph as data: nodes and routes (`app.graph()`).
|
||||||
|
Graph,
|
||||||
|
/// The graph as a diagram string; `mermaid` or `dot`.
|
||||||
|
Diagram(Diagram),
|
||||||
|
/// Every route with its transport and the chain it runs.
|
||||||
|
Routes,
|
||||||
|
/// Every token: who provides it and who needs it.
|
||||||
|
Tokens,
|
||||||
|
/// One route's chain in execution order, by declared pattern.
|
||||||
|
Explain(String),
|
||||||
|
/// The structural OpenAPI 3.1 document.
|
||||||
|
OpenApi {
|
||||||
|
title: Option<String>,
|
||||||
|
version: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
|
pub enum Diagram {
|
||||||
|
Mermaid,
|
||||||
|
Dot,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A query the app answered with a refusal rather than data — a route pattern
|
||||||
|
/// that is not registered, say. Carried as JSON so a caller (a person, an agent,
|
||||||
|
/// an MCP client) gets the same machine-readable reason.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct Refusal(pub Value);
|
||||||
|
|
||||||
|
impl Refusal {
|
||||||
|
pub fn message(&self) -> &str {
|
||||||
|
self.0["message"].as_str().unwrap_or("query refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the app lives: the project directory and, optionally, an entry file
|
||||||
|
/// other than the default `src/app.ts` / `src/main.ts`.
|
||||||
|
pub struct Target<'a> {
|
||||||
|
pub dir: &'a Path,
|
||||||
|
pub entry: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `query` against the app in `target`. `Ok(Ok(data))` is the answer,
|
||||||
|
/// `Ok(Err(refusal))` is the app saying no in a structured way, and `Err` is
|
||||||
|
/// everything that stopped the question being asked — no entry, no runtime, a
|
||||||
|
/// type error or a failed boot. The child's stderr is inherited, so those reach
|
||||||
|
/// the terminal as they happen.
|
||||||
|
pub fn query(target: &Target, query: &Query) -> std::io::Result<Result<Value, Refusal>> {
|
||||||
|
let entry_path = resolve_entry(target)?;
|
||||||
|
let rt = runtime::detect(target.dir).ok_or_else(|| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
"no runtime detected (need deno.json, bun.lock, or package.json)",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let script_path = target.dir.join(SCRIPT_NAME);
|
||||||
|
std::fs::write(&script_path, script(&entry_path, &body(query)))?;
|
||||||
|
let result = run(rt, target.dir, SCRIPT_NAME);
|
||||||
|
std::fs::remove_file(&script_path).ok();
|
||||||
|
|
||||||
|
let output = result?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(Error::other(format!(
|
||||||
|
"the app could not be inspected (exit {})",
|
||||||
|
output.status.code().unwrap_or(1)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
parse_envelope(&String::from_utf8_lossy(&output.stdout))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The envelope is the script's last stdout line, so anything the app logs
|
||||||
|
/// while booting cannot be mistaken for the answer.
|
||||||
|
fn parse_envelope(stdout: &str) -> std::io::Result<Result<Value, Refusal>> {
|
||||||
|
let line = stdout
|
||||||
|
.lines()
|
||||||
|
.rev()
|
||||||
|
.find(|l| !l.trim().is_empty())
|
||||||
|
.unwrap_or("");
|
||||||
|
let envelope: Value = serde_json::from_str(line).map_err(|e| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
format!("the introspection script printed no answer ({e})"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
match envelope["ok"].as_bool() {
|
||||||
|
Some(true) => Ok(Ok(envelope["data"].clone())),
|
||||||
|
Some(false) => Ok(Err(Refusal(envelope["error"].clone()))),
|
||||||
|
None => Err(Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
"malformed introspection answer",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The JavaScript expression (or statements ending in `data = …`) that computes
|
||||||
|
/// the answer. Everything is plain data built from public `App` methods.
|
||||||
|
fn body(query: &Query) -> String {
|
||||||
|
match query {
|
||||||
|
Query::Graph => "data = app.graph();".into(),
|
||||||
|
Query::Diagram(Diagram::Mermaid) => "data = app.toMermaid();".into(),
|
||||||
|
Query::Diagram(Diagram::Dot) => "data = app.toDOT();".into(),
|
||||||
|
Query::Routes => "data = app.graph().routes;".into(),
|
||||||
|
Query::Tokens => TOKENS.into(),
|
||||||
|
Query::Explain(pattern) => format!(
|
||||||
|
r#"try {{
|
||||||
|
data = app.explain({pattern});
|
||||||
|
}} catch {{
|
||||||
|
refuse({{
|
||||||
|
code: 'route_not_found',
|
||||||
|
message: `no route matching pattern ${{{pattern}}}`,
|
||||||
|
registered: app.graph().routes.map((r) => ({{ method: r.method, pattern: r.pattern }})),
|
||||||
|
}});
|
||||||
|
}}"#,
|
||||||
|
pattern = js_string(pattern)
|
||||||
|
),
|
||||||
|
Query::OpenApi { title, version } => {
|
||||||
|
let mut fields = Vec::new();
|
||||||
|
if let Some(t) = title {
|
||||||
|
fields.push(format!("title: {}", js_string(t)));
|
||||||
|
}
|
||||||
|
if let Some(v) = version {
|
||||||
|
fields.push(format!("version: {}", js_string(v)));
|
||||||
|
}
|
||||||
|
// No info object at all lets core apply its own defaults rather than
|
||||||
|
// having the CLI invent a title.
|
||||||
|
let info = if fields.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("{{ {} }}", fields.join(", "))
|
||||||
|
};
|
||||||
|
format!("data = app.openapi({info});")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens, from the graph's nodes plus each route's handler (only `explain`
|
||||||
|
/// knows what a handler needs). Sorted, so the answer is stable across runs.
|
||||||
|
///
|
||||||
|
/// A token that something needs and no node provides is one the request itself
|
||||||
|
/// carries (`req`, `params`, `body`, …). That is an inference, and a sound one:
|
||||||
|
/// `app.ready()` has validated the graph, so a needed token with no producer
|
||||||
|
/// would already have failed it. Marking those `"source": "request"` keeps an
|
||||||
|
/// agent from reading "nothing provides it" and writing a provider for `req`.
|
||||||
|
const TOKENS: &str = r#"const tokens = new Map();
|
||||||
|
const entry = (t) => tokens.get(t) ?? tokens.set(t, { token: t, providedBy: [], neededBy: [] }).get(t);
|
||||||
|
const graph = app.graph();
|
||||||
|
for (const n of graph.nodes) {
|
||||||
|
for (const t of n.provides) entry(t).providedBy.push({ kind: n.kind, name: n.name, origin: n.origin });
|
||||||
|
for (const t of n.needs) entry(t).neededBy.push({ kind: n.kind, name: n.name, origin: n.origin });
|
||||||
|
}
|
||||||
|
for (const pattern of new Set(graph.routes.map((r) => r.pattern))) {
|
||||||
|
for (const n of app.explain(pattern).chain) {
|
||||||
|
if (n.kind !== 'handler') continue;
|
||||||
|
for (const t of n.needs) entry(t).neededBy.push({ kind: 'handler', name: n.name, origin: n.origin, route: pattern });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const t of tokens.values()) t.source = t.providedBy.length ? 'graph' : 'request';
|
||||||
|
data = [...tokens.values()].sort((a, b) => a.token.localeCompare(b.token));"#;
|
||||||
|
|
||||||
|
fn resolve_entry(target: &Target) -> std::io::Result<PathBuf> {
|
||||||
|
match target.entry {
|
||||||
|
Some(explicit) => {
|
||||||
|
if !target.dir.join(explicit).exists() {
|
||||||
|
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
|
||||||
|
}
|
||||||
|
Ok(PathBuf::from(explicit))
|
||||||
|
}
|
||||||
|
None => entry::find(target.dir)
|
||||||
|
.map(|p| p.strip_prefix(target.dir).unwrap_or(&p).to_path_buf())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
Error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
format!(
|
||||||
|
"no {} found — pass --entry <file>. It must export the app: `export const app = createApp(...)`",
|
||||||
|
entry::candidates()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The generated script: import the app, resolve the graph, run `body`, print
|
||||||
|
/// one envelope. `refuse` ends the script with a structured error instead of
|
||||||
|
/// data.
|
||||||
|
fn script(entry_path: &Path, body: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"// generated by matcha; safe to delete\n\
|
||||||
|
import {{ app }} from {};\n\n\
|
||||||
|
if (!app) {{\n console.error('{} does not export `app` — matcha needs `export const app = createApp(...)`');\n process.exit(1);\n}}\n\
|
||||||
|
const refuse = (error) => {{\n console.log(JSON.stringify({{ ok: false, error }}));\n process.exit(0);\n}};\n\
|
||||||
|
await app.ready();\n\
|
||||||
|
let data;\n\
|
||||||
|
{body}\n\
|
||||||
|
console.log(JSON.stringify({{ ok: true, data }}));\n",
|
||||||
|
js_string(&specifier(entry_path)),
|
||||||
|
entry_path.display(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `script` under `rt` in `dir`, stdout captured, stderr inherited.
|
||||||
|
fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::Output> {
|
||||||
|
let (prog, args) = runner(rt, script);
|
||||||
|
let child = Command::new(prog)
|
||||||
|
.args(&args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::inherit())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| Error::new(e.kind(), format!("could not run {prog}: {e}")))?;
|
||||||
|
child.wait_with_output()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
|
||||||
|
let s = script.to_string();
|
||||||
|
match rt {
|
||||||
|
// Edge resolves its graph under node: `src/app.ts` imports core, never
|
||||||
|
// `edgeHandler`, so nothing here needs workerd — and workerd could not
|
||||||
|
// print to a terminal anyway.
|
||||||
|
Runtime::Node | Runtime::Edge => ("npx", vec!["tsx".into(), s]),
|
||||||
|
// `ready()` opens no provider connections, but a mesh app does reach its
|
||||||
|
// teapots there, so net is part of resolving the graph rather than extra.
|
||||||
|
Runtime::Deno => (
|
||||||
|
"deno",
|
||||||
|
vec![
|
||||||
|
"run".into(),
|
||||||
|
"--allow-read".into(),
|
||||||
|
"--allow-env".into(),
|
||||||
|
"--allow-net".into(),
|
||||||
|
s,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
Runtime::Bun => ("bun", vec!["run".into(), s]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A project-root-relative path as an ES module specifier: forward slashes,
|
||||||
|
/// always `./`-prefixed, extension kept so Deno resolves it without leaning on
|
||||||
|
/// `sloppy-imports`.
|
||||||
|
fn specifier(path: &Path) -> String {
|
||||||
|
let raw = path.to_string_lossy().replace('\\', "/");
|
||||||
|
format!("./{}", raw.strip_prefix("./").unwrap_or(&raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-quoted JS string literal. Route patterns reach this from argv, so the
|
||||||
|
/// quote and the backslash have to be escaped rather than assumed absent.
|
||||||
|
pub(crate) fn js_string(value: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(value.len() + 2);
|
||||||
|
out.push('\'');
|
||||||
|
for ch in value.chars() {
|
||||||
|
match ch {
|
||||||
|
'\\' => out.push_str("\\\\"),
|
||||||
|
'\'' => out.push_str("\\'"),
|
||||||
|
'\n' => out.push_str("\\n"),
|
||||||
|
'\r' => out.push_str("\\r"),
|
||||||
|
_ => out.push(ch),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push('\'');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn specifier_is_dot_slash_prefixed_with_extension() {
|
||||||
|
assert_eq!(specifier(Path::new("src/app.ts")), "./src/app.ts");
|
||||||
|
assert_eq!(specifier(Path::new("./src/app.ts")), "./src/app.ts");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn js_string_escapes_quote_and_backslash() {
|
||||||
|
assert_eq!(js_string("a'b"), r"'a\'b'");
|
||||||
|
assert_eq!(js_string(r"a\b"), r"'a\\b'");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn script_imports_the_entry_awaits_ready_and_prints_one_envelope() {
|
||||||
|
let out = script(Path::new("src/app.ts"), "data = 1;");
|
||||||
|
assert!(out.contains("import { app } from './src/app.ts';"));
|
||||||
|
assert!(out.contains("await app.ready();"));
|
||||||
|
assert!(out.contains("data = 1;"));
|
||||||
|
assert!(out.contains("JSON.stringify({ ok: true, data })"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn node_runs_through_tsx() {
|
||||||
|
assert_eq!(
|
||||||
|
runner(Runtime::Node, ".matcha-introspect.ts"),
|
||||||
|
(
|
||||||
|
"npx",
|
||||||
|
vec!["tsx".to_string(), ".matcha-introspect.ts".to_string()]
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_envelope_is_the_last_line_so_boot_logs_cannot_pose_as_the_answer() {
|
||||||
|
let out = "{\"level\":\"info\",\"msg\":\"booted\"}\n{\"ok\":true,\"data\":[1]}\n";
|
||||||
|
assert_eq!(parse_envelope(out).unwrap(), Ok(serde_json::json!([1])));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_refusal_comes_back_structured() {
|
||||||
|
let out =
|
||||||
|
"{\"ok\":false,\"error\":{\"code\":\"route_not_found\",\"message\":\"no route\"}}";
|
||||||
|
let refusal = parse_envelope(out).unwrap().unwrap_err();
|
||||||
|
assert_eq!(refusal.0["code"], "route_not_found");
|
||||||
|
assert_eq!(refusal.message(), "no route");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explain_escapes_the_pattern() {
|
||||||
|
assert!(body(&Query::Explain("/a'b".into())).contains(r"app.explain('/a\'b')"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+147
-4
@@ -1,9 +1,18 @@
|
|||||||
|
mod ask;
|
||||||
mod check;
|
mod check;
|
||||||
mod cli;
|
mod cli;
|
||||||
mod cmd_add;
|
mod cmd_add;
|
||||||
|
mod cmd_agents;
|
||||||
mod cmd_create;
|
mod cmd_create;
|
||||||
|
mod cmd_doctor;
|
||||||
|
mod cmd_graph;
|
||||||
mod cmd_new;
|
mod cmd_new;
|
||||||
|
mod cmd_plugin;
|
||||||
mod cmd_run;
|
mod cmd_run;
|
||||||
|
mod entry;
|
||||||
|
mod introspect;
|
||||||
|
mod naming;
|
||||||
|
mod plugin_files;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
mod template;
|
mod template;
|
||||||
mod wire;
|
mod wire;
|
||||||
@@ -30,17 +39,151 @@ fn main() {
|
|||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Command::Create { kind, name, check } => {
|
Command::Create {
|
||||||
if let Err(e) = cmd_create::run(&kind, &name, check) {
|
kind,
|
||||||
|
name,
|
||||||
|
check,
|
||||||
|
package,
|
||||||
|
folder,
|
||||||
|
scope,
|
||||||
|
registry,
|
||||||
|
npm_name,
|
||||||
|
} => {
|
||||||
|
let stray: Vec<&str> = [
|
||||||
|
("--package", package.is_some()),
|
||||||
|
("--folder", folder.is_some()),
|
||||||
|
("--scope", scope.is_some()),
|
||||||
|
("--registry", registry.is_some()),
|
||||||
|
("--npm-name", npm_name.is_some()),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(_, on)| *on)
|
||||||
|
.map(|(flag, _)| flag)
|
||||||
|
.collect();
|
||||||
|
let result = if kind != "plugin" && !stray.is_empty() {
|
||||||
|
Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!("{} only apply to create plugin", stray.join(", ")),
|
||||||
|
))
|
||||||
|
} else if kind == "plugin" {
|
||||||
|
cmd_plugin::run(cmd_plugin::Opts {
|
||||||
|
name,
|
||||||
|
package,
|
||||||
|
folder,
|
||||||
|
scope,
|
||||||
|
registry,
|
||||||
|
npm_name,
|
||||||
|
check,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
match name {
|
||||||
|
Some(name) => cmd_create::run(&kind, &name, check),
|
||||||
|
None => Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!("create {kind} needs a name"),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = result {
|
||||||
eprintln!("error: {e}");
|
eprintln!("error: {e}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Command::Add { capability } => {
|
Command::Agents { force } => {
|
||||||
if let Err(e) = cmd_add::run(&capability) {
|
if let Err(e) = cmd_agents::run(std::path::Path::new("."), force) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Doctor => {
|
||||||
|
if let Err(e) = cmd_doctor::run(std::path::Path::new(".")) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Graph { format, entry, out } => {
|
||||||
|
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,
|
||||||
|
json,
|
||||||
|
} => {
|
||||||
|
if let Err(e) = cmd_graph::explain(
|
||||||
|
std::path::Path::new("."),
|
||||||
|
&route,
|
||||||
|
entry.as_deref(),
|
||||||
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
|
) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Routes { entry, out, json } => {
|
||||||
|
if let Err(e) = cmd_graph::routes(
|
||||||
|
std::path::Path::new("."),
|
||||||
|
entry.as_deref(),
|
||||||
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
|
) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Tokens { entry, out, json } => {
|
||||||
|
if let Err(e) = cmd_graph::tokens(
|
||||||
|
std::path::Path::new("."),
|
||||||
|
entry.as_deref(),
|
||||||
|
out.as_deref(),
|
||||||
|
render(json),
|
||||||
|
) {
|
||||||
|
eprintln!("error: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Command::Add {
|
||||||
|
capability,
|
||||||
|
controller,
|
||||||
|
} => {
|
||||||
|
if let Err(e) = cmd_add::run(&capability, controller.as_deref()) {
|
||||||
eprintln!("error: {e}");
|
eprintln!("error: {e}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render(json: bool) -> cmd_graph::Render {
|
||||||
|
if json {
|
||||||
|
cmd_graph::Render::Json
|
||||||
|
} else {
|
||||||
|
cmd_graph::Render::Text
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
//! Names for a plugin: the slug a person types their way into, and the
|
||||||
|
//! TypeScript identifiers derived from it.
|
||||||
|
//!
|
||||||
|
//! The slug is one string on purpose. It is the folder, the plugin's `name`,
|
||||||
|
//! its node name and the token it provides — the same rule the official
|
||||||
|
//! plugins follow — so a plugin never has two names to keep in step.
|
||||||
|
|
||||||
|
/// `Plugin Algo` → `plugin-algo`. Letters and digits are kept (lowercased);
|
||||||
|
/// spaces, `-` and `_` separate words; anything else rejects the name, because
|
||||||
|
/// quietly dropping a `.` or an emoji would hand back a name nobody typed.
|
||||||
|
/// `None` when nothing usable is left or the result does not start with a letter.
|
||||||
|
pub fn slug(name: &str) -> Option<String> {
|
||||||
|
let mut out = String::new();
|
||||||
|
for ch in name.trim().chars() {
|
||||||
|
if ch.is_ascii_alphanumeric() {
|
||||||
|
out.push(ch.to_ascii_lowercase());
|
||||||
|
} else if ch.is_whitespace() || ch == '-' || ch == '_' {
|
||||||
|
if !out.is_empty() && !out.ends_with('-') {
|
||||||
|
out.push('-');
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out = out.trim_end_matches('-').to_string();
|
||||||
|
out.starts_with(|c: char| c.is_ascii_lowercase())
|
||||||
|
.then_some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn words(slug: &str) -> impl Iterator<Item = &str> {
|
||||||
|
slug.split('-').filter(|w| !w.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capitalised(word: &str) -> String {
|
||||||
|
let mut chars = word.chars();
|
||||||
|
match chars.next() {
|
||||||
|
Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(),
|
||||||
|
None => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `plugin-algo` → `PluginAlgo`, for the options interface.
|
||||||
|
pub fn pascal(slug: &str) -> String {
|
||||||
|
words(slug).map(capitalised).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `plugin-algo` → `pluginAlgo`, for the factory.
|
||||||
|
pub fn camel(slug: &str) -> String {
|
||||||
|
let mut words = words(slug);
|
||||||
|
let first = words.next().unwrap_or_default().to_string();
|
||||||
|
first + &words.map(capitalised).collect::<String>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Words that cannot name a function in a TypeScript module: JS keywords, the
|
||||||
|
/// strict-mode reserved words (modules are always strict) and the literals.
|
||||||
|
/// `camel` of a slug is lowercase-first, so only lowercase spellings matter.
|
||||||
|
const RESERVED: &[&str] = &[
|
||||||
|
"arguments",
|
||||||
|
"await",
|
||||||
|
"break",
|
||||||
|
"case",
|
||||||
|
"catch",
|
||||||
|
"class",
|
||||||
|
"const",
|
||||||
|
"continue",
|
||||||
|
"debugger",
|
||||||
|
"default",
|
||||||
|
"delete",
|
||||||
|
"do",
|
||||||
|
"else",
|
||||||
|
"enum",
|
||||||
|
"eval",
|
||||||
|
"export",
|
||||||
|
"extends",
|
||||||
|
"false",
|
||||||
|
"finally",
|
||||||
|
"for",
|
||||||
|
"function",
|
||||||
|
"if",
|
||||||
|
"implements",
|
||||||
|
"import",
|
||||||
|
"in",
|
||||||
|
"instanceof",
|
||||||
|
"interface",
|
||||||
|
"let",
|
||||||
|
"new",
|
||||||
|
"null",
|
||||||
|
"package",
|
||||||
|
"private",
|
||||||
|
"protected",
|
||||||
|
"public",
|
||||||
|
"return",
|
||||||
|
"static",
|
||||||
|
"super",
|
||||||
|
"switch",
|
||||||
|
"this",
|
||||||
|
"throw",
|
||||||
|
"true",
|
||||||
|
"try",
|
||||||
|
"typeof",
|
||||||
|
"var",
|
||||||
|
"void",
|
||||||
|
"while",
|
||||||
|
"with",
|
||||||
|
"yield",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// True when `ident` cannot be used as the factory's name.
|
||||||
|
pub fn is_reserved(ident: &str) -> bool {
|
||||||
|
RESERVED.contains(&ident)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn slug_kebab_cases_what_was_typed() {
|
||||||
|
assert_eq!(slug("Plugin Algo").as_deref(), Some("plugin-algo"));
|
||||||
|
assert_eq!(slug("algo").as_deref(), Some("algo"));
|
||||||
|
assert_eq!(slug(" Rate Limit ").as_deref(), Some("rate-limit"));
|
||||||
|
assert_eq!(slug("rate_limit").as_deref(), Some("rate-limit"));
|
||||||
|
assert_eq!(slug("already-kebab").as_deref(), Some("already-kebab"));
|
||||||
|
assert_eq!(slug("v2 cache").as_deref(), Some("v2-cache"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn slug_rejects_what_cannot_be_a_name() {
|
||||||
|
assert_eq!(slug(""), None);
|
||||||
|
assert_eq!(slug(" "), None);
|
||||||
|
assert_eq!(slug("--"), None);
|
||||||
|
assert_eq!(slug("🍵"), None);
|
||||||
|
assert_eq!(slug("2fa"), None);
|
||||||
|
assert_eq!(slug("rate.limit"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reserved_words_and_uses_are_found() {
|
||||||
|
assert!(is_reserved("delete"));
|
||||||
|
assert!(is_reserved("class"));
|
||||||
|
assert!(!is_reserved("pluginAlgo"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identifiers_follow_the_slug() {
|
||||||
|
assert_eq!(camel("plugin-algo"), "pluginAlgo");
|
||||||
|
assert_eq!(pascal("plugin-algo"), "PluginAlgo");
|
||||||
|
assert_eq!(camel("algo"), "algo");
|
||||||
|
assert_eq!(pascal("v2-cache"), "V2Cache");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
//! The text of every file `matcha create plugin` writes. Pure: slug and
|
||||||
|
//! options in, file content out, so the shapes are tested without a disk.
|
||||||
|
|
||||||
|
use crate::naming::{camel, pascal};
|
||||||
|
use crate::template::CORE_VERSION;
|
||||||
|
|
||||||
|
/// The plugin itself, the same in both modes. It follows the official
|
||||||
|
/// plugins' convention: one string is the plugin name, the node name and the
|
||||||
|
/// token, and `provides` renames it, so two instances can sit side by side.
|
||||||
|
pub fn factory(slug: &str) -> String {
|
||||||
|
let fun = camel(slug);
|
||||||
|
let opts = format!("{}Options", pascal(slug));
|
||||||
|
format!(
|
||||||
|
"import type {{ Plugin }} from '@green-tea/core';
|
||||||
|
|
||||||
|
export interface {opts} {{
|
||||||
|
/** The token this plugin provides. Change it to mount two instances side by side. */
|
||||||
|
provides?: string;
|
||||||
|
}}
|
||||||
|
|
||||||
|
export function {fun}(options: {opts} = {{}}): Plugin {{
|
||||||
|
const provides = options.provides ?? '{slug}';
|
||||||
|
|
||||||
|
return {{
|
||||||
|
name: provides,
|
||||||
|
mount({{ scope }}) {{
|
||||||
|
scope.add({{
|
||||||
|
kind: 'provider',
|
||||||
|
name: provides,
|
||||||
|
needs: [],
|
||||||
|
provides: [provides],
|
||||||
|
run: () => ({{ [provides]: null }}),
|
||||||
|
}});
|
||||||
|
}},
|
||||||
|
}};
|
||||||
|
}}
|
||||||
|
"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const JSR_BANNER: &str = "JSR is recommended. It records which runtimes a package supports (Node, Deno, Bun, workerd), and the green-tea plugin listing shows that for every plugin.";
|
||||||
|
|
||||||
|
pub struct Package {
|
||||||
|
pub slug: String,
|
||||||
|
pub scope: String,
|
||||||
|
/// `Some(name)` when it also publishes to npm.
|
||||||
|
pub npm: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Package {
|
||||||
|
fn jsr_name(&self) -> String {
|
||||||
|
format!("@{}/{}", self.scope, self.slug)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every file of a package, as (path relative to the package root, content).
|
||||||
|
pub fn package(p: &Package) -> Vec<(String, String)> {
|
||||||
|
let mut files = vec![
|
||||||
|
("deno.json".to_string(), deno_json(p)),
|
||||||
|
("package.json".to_string(), package_json(p)),
|
||||||
|
("src/index.ts".to_string(), factory(&p.slug)),
|
||||||
|
(format!("test/{}.test.ts", p.slug), test_ts(p)),
|
||||||
|
("README.md".to_string(), readme(p)),
|
||||||
|
(
|
||||||
|
"CHANGELOG.md".to_string(),
|
||||||
|
"# Changelog\n\n## [Unreleased]\n\n- First version.\n".to_string(),
|
||||||
|
),
|
||||||
|
("LICENSE".to_string(), license(p)),
|
||||||
|
(
|
||||||
|
".gitignore".to_string(),
|
||||||
|
"node_modules\ndist\n.DS_Store\n".to_string(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if p.npm.is_some() {
|
||||||
|
files.push(("tsconfig.json".to_string(), TSCONFIG.to_string()));
|
||||||
|
}
|
||||||
|
files
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deno_json(p: &Package) -> String {
|
||||||
|
format!(
|
||||||
|
r#"{{
|
||||||
|
"name": "{name}",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"license": "MIT",
|
||||||
|
"exports": "./src/index.ts",
|
||||||
|
"nodeModulesDir": "auto",
|
||||||
|
"imports": {{
|
||||||
|
"@green-tea/core": "npm:@green-tea/core@{CORE_VERSION}"
|
||||||
|
}},
|
||||||
|
"tasks": {{
|
||||||
|
"test": "deno test --allow-env --allow-read"
|
||||||
|
}},
|
||||||
|
"publish": {{
|
||||||
|
"include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"]
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"#,
|
||||||
|
name = p.jsr_name()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ENGINES: &str = r#" "engines": {
|
||||||
|
"node": ">=22.18",
|
||||||
|
"deno": ">=2",
|
||||||
|
"bun": ">=1.3"
|
||||||
|
},"#;
|
||||||
|
|
||||||
|
fn package_json(p: &Package) -> String {
|
||||||
|
match &p.npm {
|
||||||
|
None => format!(
|
||||||
|
r#"{{
|
||||||
|
"name": "{name}",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
{ENGINES}
|
||||||
|
"scripts": {{
|
||||||
|
"test": "node --test test/*.test.ts"
|
||||||
|
}},
|
||||||
|
"devDependencies": {{
|
||||||
|
"@green-tea/core": "{CORE_VERSION}",
|
||||||
|
"@types/node": "^22"
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"#,
|
||||||
|
name = p.jsr_name()
|
||||||
|
),
|
||||||
|
Some(npm) => format!(
|
||||||
|
r#"{{
|
||||||
|
"name": "{npm}",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
"exports": {{
|
||||||
|
".": {{
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"import": "./dist/index.js"
|
||||||
|
}}
|
||||||
|
}},
|
||||||
|
"files": ["dist"],
|
||||||
|
{ENGINES}
|
||||||
|
"scripts": {{
|
||||||
|
"build": "tsc",
|
||||||
|
"prepublishOnly": "npm run build",
|
||||||
|
"test": "node --test test/*.test.ts"
|
||||||
|
}},
|
||||||
|
"devDependencies": {{
|
||||||
|
"@green-tea/core": "{CORE_VERSION}",
|
||||||
|
"@types/node": "^22",
|
||||||
|
"typescript": "^5"
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
"#
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TSCONFIG: &str = r#"{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2022",
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"declaration": true,
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
fn test_ts(p: &Package) -> String {
|
||||||
|
let fun = camel(&p.slug);
|
||||||
|
let slug = &p.slug;
|
||||||
|
format!(
|
||||||
|
"import {{ strict as assert }} from 'node:assert';
|
||||||
|
import {{ test }} from 'node:test';
|
||||||
|
|
||||||
|
import {{ createApp }} from '@green-tea/core';
|
||||||
|
|
||||||
|
import {{ {fun} }} from '../src/index.ts';
|
||||||
|
|
||||||
|
test('mounts, boots, and puts its token in the graph', async () => {{
|
||||||
|
const app = createApp({{ modules: [], plugins: [{fun}()] }});
|
||||||
|
await app.boot();
|
||||||
|
assert.ok(app.graph().nodes.some((node) => node.provides.includes('{slug}')));
|
||||||
|
}});
|
||||||
|
|
||||||
|
test('two instances mount side by side under different tokens', async () => {{
|
||||||
|
const app = createApp({{ modules: [], plugins: [{fun}(), {fun}({{ provides: '{slug}-2' }})] }});
|
||||||
|
await app.boot();
|
||||||
|
}});
|
||||||
|
|
||||||
|
test('two instances under one name are refused', () => {{
|
||||||
|
assert.throws(() => createApp({{ modules: [], plugins: [{fun}(), {fun}()] }}), /two plugins are named/);
|
||||||
|
}});
|
||||||
|
"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// MIT as a starting point, which the README tells the author to change. The
|
||||||
|
/// holder is the scope, the closest thing to an author matcha knows.
|
||||||
|
fn license(p: &Package) -> String {
|
||||||
|
// Whole years since the epoch, averaged over leap years: a copyright line
|
||||||
|
// needs the year, not the date, and this needs no dependency.
|
||||||
|
let year = 1970
|
||||||
|
+ std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs() / 31_556_952)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let scope = &p.scope;
|
||||||
|
format!(
|
||||||
|
"MIT License
|
||||||
|
|
||||||
|
Copyright (c) {year} {scope}
|
||||||
|
|
||||||
|
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.
|
||||||
|
"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn readme(p: &Package) -> String {
|
||||||
|
let jsr = p.jsr_name();
|
||||||
|
let fun = camel(&p.slug);
|
||||||
|
let npm_install = match &p.npm {
|
||||||
|
Some(npm) => format!("\nOr from npm:\n\n```bash\nnpm i {npm}\n```\n"),
|
||||||
|
None => String::new(),
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
"# {jsr}
|
||||||
|
|
||||||
|
> {JSR_BANNER}
|
||||||
|
|
||||||
|
What this plugin adds to a green-tea app, in one or two sentences.
|
||||||
|
|
||||||
|
## Runtimes
|
||||||
|
|
||||||
|
| Runtime | Supported | Why not |
|
||||||
|
|---|---|---|
|
||||||
|
| Node | | |
|
||||||
|
| Deno | | |
|
||||||
|
| Bun | | |
|
||||||
|
| workerd (edge) | | |
|
||||||
|
|
||||||
|
Fill in every row. The green-tea plugin listing asks for a reason beside each runtime this does not support.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx jsr add {jsr}
|
||||||
|
```
|
||||||
|
{npm_install}
|
||||||
|
Needs `@green-tea/core@{CORE_VERSION}` or newer.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import {{ createApp }} from '@green-tea/core';
|
||||||
|
import {{ {fun} }} from '{jsr}';
|
||||||
|
|
||||||
|
const app = createApp({{ modules: [AppModule], plugins: [{fun}()] }});
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT, as generated. Change `LICENSE` and the `license` fields in `deno.json` and `package.json`
|
||||||
|
if you publish under another.
|
||||||
|
|
||||||
|
## List it
|
||||||
|
|
||||||
|
Once it is published, add it to the green-tea plugin listing: https://green-tea.expressive-tea.io/plugins/#contribute
|
||||||
|
"
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -5,6 +5,11 @@ pub enum Runtime {
|
|||||||
Node,
|
Node,
|
||||||
Deno,
|
Deno,
|
||||||
Bun,
|
Bun,
|
||||||
|
/// Cloudflare Workers. Unlike the other three this is a deploy target as
|
||||||
|
/// much as a local one — `wrangler dev` runs it in real workerd, but the
|
||||||
|
/// graph is resolved under node, since introspection never touches the
|
||||||
|
/// edge handler.
|
||||||
|
Edge,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
@@ -13,6 +18,7 @@ impl Runtime {
|
|||||||
"node" => Some(Runtime::Node),
|
"node" => Some(Runtime::Node),
|
||||||
"deno" => Some(Runtime::Deno),
|
"deno" => Some(Runtime::Deno),
|
||||||
"bun" => Some(Runtime::Bun),
|
"bun" => Some(Runtime::Bun),
|
||||||
|
"edge" => Some(Runtime::Edge),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,6 +45,10 @@ pub fn detect(dir: &Path) -> Option<Runtime> {
|
|||||||
if let Some(r) = override_from_toml(dir) {
|
if let Some(r) = override_from_toml(dir) {
|
||||||
return Some(r);
|
return Some(r);
|
||||||
}
|
}
|
||||||
|
// Before package.json, which an edge project also has.
|
||||||
|
if exists(dir, "wrangler.toml") || exists(dir, "wrangler.jsonc") {
|
||||||
|
return Some(Runtime::Edge);
|
||||||
|
}
|
||||||
if exists(dir, "deno.json") || exists(dir, "deno.jsonc") {
|
if exists(dir, "deno.json") || exists(dir, "deno.jsonc") {
|
||||||
return Some(Runtime::Deno);
|
return Some(Runtime::Deno);
|
||||||
}
|
}
|
||||||
@@ -92,6 +102,14 @@ mod tests {
|
|||||||
assert_eq!(detect(d.path()), Some(Runtime::Bun));
|
assert_eq!(detect(d.path()), Some(Runtime::Bun));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrangler_toml_wins_over_package_json() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
touch(d.path(), "package.json");
|
||||||
|
fs::write(d.path().join("wrangler.toml"), "name = \"x\"\n").unwrap();
|
||||||
|
assert_eq!(detect(d.path()), Some(Runtime::Edge));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn nothing_detected() {
|
fn nothing_detected() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
|
|||||||
+128
-3
@@ -3,16 +3,31 @@ use std::path::Path;
|
|||||||
|
|
||||||
use crate::runtime::Runtime;
|
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 `latest` dist-tag, which is what keeps it current.
|
||||||
|
pub const CORE_VERSION: &str = "26.11.0-rc.2";
|
||||||
|
|
||||||
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
|
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
|
||||||
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
|
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
|
||||||
pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node");
|
pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node");
|
||||||
pub static RUNTIME_BUN: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/bun");
|
pub static RUNTIME_BUN: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/bun");
|
||||||
|
pub static RUNTIME_EDGE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/edge");
|
||||||
|
|
||||||
fn overlay_for(runtime: Runtime) -> &'static Dir<'static> {
|
fn overlay_for(runtime: Runtime) -> &'static Dir<'static> {
|
||||||
match runtime {
|
match runtime {
|
||||||
Runtime::Deno => &RUNTIME_DENO,
|
Runtime::Deno => &RUNTIME_DENO,
|
||||||
Runtime::Node => &RUNTIME_NODE,
|
Runtime::Node => &RUNTIME_NODE,
|
||||||
Runtime::Bun => &RUNTIME_BUN,
|
Runtime::Bun => &RUNTIME_BUN,
|
||||||
|
Runtime::Edge => &RUNTIME_EDGE,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,7 +50,7 @@ fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
|
|||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
let contents = std::str::from_utf8(f.contents())
|
let contents = std::str::from_utf8(f.contents())
|
||||||
.map(|s| s.replace("{{project_name}}", name).into_bytes())
|
.map(|s| render(s, name, CORE_VERSION).into_bytes())
|
||||||
.unwrap_or_else(|_| f.contents().to_vec());
|
.unwrap_or_else(|_| f.contents().to_vec());
|
||||||
std::fs::write(out, contents)?;
|
std::fs::write(out, contents)?;
|
||||||
}
|
}
|
||||||
@@ -44,11 +59,109 @@ fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render(template: &str, project_name: &str, core_version: &str) -> String {
|
||||||
|
template
|
||||||
|
.replace("{{project_name}}", project_name)
|
||||||
|
.replace("{{core_version}}", core_version)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The files that tell a coding agent how this project and green-tea work:
|
||||||
|
/// `AGENTS.md` (read by Codex, OpenCode and others) and a `CLAUDE.md` that
|
||||||
|
/// imports it. `matcha new` writes them with the starter; `matcha agents`
|
||||||
|
/// writes them into a project that predates them.
|
||||||
|
pub const AGENT_FILES: [&str; 2] = ["AGENTS.md", "CLAUDE.md"];
|
||||||
|
|
||||||
|
/// Renders one of [`AGENT_FILES`] for a project already on `core_version`.
|
||||||
|
pub fn agent_file(file: &str, project_name: &str, core_version: &str) -> Option<String> {
|
||||||
|
let f = SHARED.get_file(file)?;
|
||||||
|
Some(render(
|
||||||
|
std::str::from_utf8(f.contents()).ok()?,
|
||||||
|
project_name,
|
||||||
|
core_version,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use tempfile::tempdir;
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every starter tells a coding agent where green-tea's rules are, with the
|
||||||
|
/// version it was scaffolded on, and points it at the introspection
|
||||||
|
/// commands rather than at guessing.
|
||||||
|
#[test]
|
||||||
|
fn every_runtime_scaffolds_the_agent_files() {
|
||||||
|
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
write_starter(d.path(), "my-api", rt).unwrap();
|
||||||
|
let agents = std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap();
|
||||||
|
assert!(agents.contains("# AGENTS.md — my-api"), "{rt:?}");
|
||||||
|
assert!(agents.contains(CORE_VERSION), "{rt:?}");
|
||||||
|
assert!(!agents.contains("{{"), "{rt:?} left a placeholder");
|
||||||
|
assert!(agents.contains("matcha tokens --json"), "{rt:?}");
|
||||||
|
assert!(
|
||||||
|
agents.contains("node_modules/@green-tea/core/llms.txt"),
|
||||||
|
"{rt:?}"
|
||||||
|
);
|
||||||
|
let claude = std::fs::read_to_string(d.path().join("CLAUDE.md")).unwrap();
|
||||||
|
assert_eq!(claude.trim(), "@AGENTS.md", "{rt:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deno_writes_shared_and_deno_overlay() {
|
fn deno_writes_shared_and_deno_overlay() {
|
||||||
let d = tempdir().unwrap();
|
let d = tempdir().unwrap();
|
||||||
@@ -64,8 +177,15 @@ mod tests {
|
|||||||
assert!(d.path().join("deno.json").exists());
|
assert!(d.path().join("deno.json").exists());
|
||||||
assert!(d.path().join("matcha.toml").exists());
|
assert!(d.path().join("matcha.toml").exists());
|
||||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||||
assert!(main.contains("Deno.serve"));
|
// serveDeno boots before it binds; Deno.serve(app.fetch) bound first and
|
||||||
|
// left a port answering 500 when a provider failed.
|
||||||
|
assert!(main.contains("await serveDeno(app"));
|
||||||
|
assert!(!main.contains("Deno.serve("));
|
||||||
assert!(!d.path().join("package.json").exists());
|
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]
|
#[test]
|
||||||
@@ -83,6 +203,9 @@ mod tests {
|
|||||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||||
assert!(main.contains("app.listen"));
|
assert!(main.contains("app.listen"));
|
||||||
assert!(!d.path().join("deno.json").exists());
|
assert!(!d.path().join("deno.json").exists());
|
||||||
|
|
||||||
|
assert!(pkg.contains(&format!("\"@green-tea/core\": \"{CORE_VERSION}\"")));
|
||||||
|
assert!(!pkg.contains("{{core_version}}"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -97,7 +220,9 @@ mod tests {
|
|||||||
assert!(pkg.contains("\"name\": \"my-api\""));
|
assert!(pkg.contains("\"name\": \"my-api\""));
|
||||||
assert!(!pkg.contains("{{project_name}}"));
|
assert!(!pkg.contains("{{project_name}}"));
|
||||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||||
assert!(main.contains("Bun.serve"));
|
// Same reason as Deno: serveBun boots first.
|
||||||
|
assert!(main.contains("await serveBun(app"));
|
||||||
|
assert!(!main.contains("Bun.serve("));
|
||||||
assert!(!d.path().join("deno.json").exists());
|
assert!(!d.path().join("deno.json").exists());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+178
-14
@@ -64,10 +64,27 @@ fn has_error(node: Node) -> bool {
|
|||||||
/// accepted; if merging somehow produces broken text, this falls back to
|
/// accepted; if merging somehow produces broken text, this falls back to
|
||||||
/// appending a fresh import line rather than returning broken source.
|
/// appending a fresh import line rather than returning broken source.
|
||||||
pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
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 tree = parser().parse(src, None).unwrap();
|
||||||
let root = tree.root_node();
|
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 mut c = named_imports.walk();
|
||||||
let already_present = named_imports.named_children(&mut c).any(|spec| {
|
let already_present = named_imports.named_children(&mut c).any(|spec| {
|
||||||
spec.kind() == "import_specifier"
|
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.
|
// 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) {
|
if src.contains(&line) {
|
||||||
return src.to_string();
|
return src.to_string();
|
||||||
}
|
}
|
||||||
@@ -120,18 +137,41 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
|||||||
out
|
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
|
/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import
|
||||||
/// { ... } from '<from>';` statement whose module specifier string literal
|
/// { ... } from '<from>';` statement whose module specifier string literal
|
||||||
/// equals `from` exactly. Returns `None` when no import statement has that
|
/// equals `from` exactly and whose type-only-ness matches `type_only`. Returns
|
||||||
/// source, or when the matching statement has no named-imports clause at all
|
/// `None` when no import statement has that source, or when the matching
|
||||||
/// (e.g. a bare default import) — callers treat that as "can't merge, fall
|
/// statement has no named-imports clause at all (e.g. a bare default import) —
|
||||||
/// back to appending a new line".
|
/// 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>> {
|
///
|
||||||
|
/// 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();
|
let mut c = root.walk();
|
||||||
for stmt in root.children(&mut c) {
|
for stmt in root.children(&mut c) {
|
||||||
if stmt.kind() != "import_statement" {
|
if stmt.kind() != "import_statement" {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if is_type_only(&stmt, src) != type_only {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(source) = stmt.child_by_field_name("source") else {
|
let Some(source) = stmt.child_by_field_name("source") else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -175,15 +215,43 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String>
|
|||||||
insert_into_object_array(src, object, key, symbol)
|
insert_into_object_array(src, object, key, symbol)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts `symbol` into the `modules` array of the first `createApp(...)`
|
/// True when `ident` is an identifier anywhere in `src`: an import, a
|
||||||
/// call's argument object (creating the `modules` key if absent). Idempotent;
|
/// declaration or a use. Read from the parse tree, so a word inside a string
|
||||||
/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call
|
/// (`'@green-tea/core'`) or a comment does not count; those are not bindings
|
||||||
/// with an object argument is found.
|
/// and cannot collide.
|
||||||
pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
|
pub fn binds(src: &str, ident: &str) -> bool {
|
||||||
|
fn visit(node: Node, src: &str, ident: &str) -> bool {
|
||||||
|
if matches!(
|
||||||
|
node.kind(),
|
||||||
|
"identifier" | "type_identifier" | "shorthand_property_identifier_pattern"
|
||||||
|
) && node.utf8_text(src.as_bytes()).ok() == Some(ident)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let mut c = node.walk();
|
||||||
|
let found = node.children(&mut c).any(|child| visit(child, src, ident));
|
||||||
|
found
|
||||||
|
}
|
||||||
|
let tree = parser().parse(src, None).unwrap();
|
||||||
|
visit(tree.root_node(), src, ident)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inserts `item` into the `key: [...]` array of the first `createApp(...)`
|
||||||
|
/// call's argument object, creating the key if absent. `item` is any array
|
||||||
|
/// element: a symbol for `modules`, a call like `algo()` for `plugins`.
|
||||||
|
/// Idempotent; returns `None` on parse breakage, when there is no
|
||||||
|
/// `createApp({...})`, or when `key` holds something other than an array
|
||||||
|
/// literal.
|
||||||
|
pub fn add_to_createapp(src: &str, key: &str, item: &str) -> Option<String> {
|
||||||
let tree = parser().parse(src, None).unwrap();
|
let tree = parser().parse(src, None).unwrap();
|
||||||
let root = tree.root_node();
|
let root = tree.root_node();
|
||||||
let object = find_createapp_object(&root, src)?;
|
let object = find_createapp_object(&root, src)?;
|
||||||
insert_into_object_array(src, object, "modules", symbol)
|
insert_into_object_array(src, object, key, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `add_to_createapp` for `modules`, kept as the name `create module` reads.
|
||||||
|
pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
|
||||||
|
add_to_createapp(src, "modules", symbol)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
|
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
|
||||||
@@ -193,7 +261,7 @@ pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
|
|||||||
fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option<String> {
|
fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option<String> {
|
||||||
if let Some((open, close)) = find_key_array_span(object, src, key) {
|
if let Some((open, close)) = find_key_array_span(object, src, key) {
|
||||||
let inner = &src[open + 1..close];
|
let inner = &src[open + 1..close];
|
||||||
if inner.split(',').map(str::trim).any(|s| s == symbol) {
|
if array_elements(object, src, key).iter().any(|e| e == symbol) {
|
||||||
return Some(src.to_string()); // idempotent
|
return Some(src.to_string()); // idempotent
|
||||||
}
|
}
|
||||||
let joined = if inner.trim().is_empty() {
|
let joined = if inner.trim().is_empty() {
|
||||||
@@ -237,6 +305,32 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) ->
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The text of each element of `object`'s `key: [...]` array, read from the
|
||||||
|
/// parse tree: `algo({ a: 1, b: 2 })` is one element, which a split on `,` is not.
|
||||||
|
fn array_elements(object: Node, src: &str, key: &str) -> Vec<String> {
|
||||||
|
let mut c = object.walk();
|
||||||
|
for pair in object.named_children(&mut c) {
|
||||||
|
let is_key = pair.kind() == "pair"
|
||||||
|
&& pair
|
||||||
|
.child_by_field_name("key")
|
||||||
|
.and_then(|k| k.utf8_text(src.as_bytes()).ok())
|
||||||
|
== Some(key);
|
||||||
|
let Some(array) = pair
|
||||||
|
.child_by_field_name("value")
|
||||||
|
.filter(|v| is_key && v.kind() == "array")
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mut ac = array.walk();
|
||||||
|
return array
|
||||||
|
.named_children(&mut ac)
|
||||||
|
.filter_map(|e| e.utf8_text(src.as_bytes()).ok())
|
||||||
|
.map(|t| t.split_whitespace().collect::<Vec<_>>().join(" "))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
/// True when `object` has any direct `pair` child whose key text equals `key`,
|
/// True when `object` has any direct `pair` child whose key text equals `key`,
|
||||||
/// regardless of the value's kind. Used to avoid creating a duplicate key when
|
/// regardless of the value's kind. Used to avoid creating a duplicate key when
|
||||||
/// an existing pair's value isn't an array literal.
|
/// an existing pair's value isn't an array literal.
|
||||||
@@ -405,6 +499,25 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#[test]
|
||||||
|
fn an_element_with_commas_inside_is_still_one_element() {
|
||||||
|
let src = "const app = createApp({ plugins: [algo({ a: 1, b: 2 })] });\n";
|
||||||
|
assert_eq!(
|
||||||
|
add_to_createapp(src, "plugins", "algo({ a: 1, b: 2 })").as_deref(),
|
||||||
|
Some(src)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn binds_sees_identifiers_not_strings_or_comments() {
|
||||||
|
let src = "import { createApp } from '@green-tea/core';\n// green tea\nexport const app = createApp({});\n";
|
||||||
|
assert!(binds(src, "createApp"));
|
||||||
|
assert!(binds(src, "app"));
|
||||||
|
assert!(!binds(src, "core"));
|
||||||
|
assert!(!binds(src, "green"));
|
||||||
|
assert!(!binds(src, "appModule"));
|
||||||
|
}
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
const MOD: &str = r#"import { Module } from '@green-tea/core';
|
const MOD: &str = r#"import { Module } from '@green-tea/core';
|
||||||
@@ -568,4 +681,55 @@ export class AppModule {}
|
|||||||
let src = "const app = createApp({ modules: MODULES });\n";
|
let src = "const app = createApp({ modules: MODULES });\n";
|
||||||
assert!(add_to_createapp_modules(src, "UsersModule").is_none());
|
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",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": { "dev": "bun --watch run src/main.ts" },
|
"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,8 @@
|
|||||||
import { createApp } from '@green-tea/core';
|
import { serveBun } from '@green-tea/core/bun';
|
||||||
import { AppModule } from './app.module';
|
|
||||||
|
|
||||||
const app = createApp({ modules: [AppModule] });
|
import { app } from './app';
|
||||||
|
|
||||||
Bun.serve({ port: 8000, fetch: app.fetch });
|
// Boots before it binds: a provider that fails stops the process here, instead
|
||||||
|
// of leaving an open port that answers 500 to everything.
|
||||||
|
await serveBun(app, { port: 8000 });
|
||||||
console.log('🍵 green-tea running on http://localhost:8000');
|
console.log('🍵 green-tea running on http://localhost:8000');
|
||||||
@@ -3,7 +3,9 @@
|
|||||||
"target": "esnext",
|
"target": "esnext",
|
||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
|
"types": ["bun"],
|
||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": { "experimentalDecorators": true },
|
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true },
|
||||||
"unstable": ["sloppy-imports"],
|
"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" }
|
"tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" }
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import { createApp } from '@green-tea/core';
|
import { serveDeno } from '@green-tea/core/deno';
|
||||||
import { AppModule } from './app.module';
|
|
||||||
|
|
||||||
const app = createApp({ modules: [AppModule] });
|
import { app } from './app';
|
||||||
|
|
||||||
Deno.serve({ port: 8000 }, app.fetch);
|
// Boots before it binds: a provider that fails stops the process here, instead
|
||||||
|
// of leaving an open port that answers 500 to everything.
|
||||||
|
await serveDeno(app, { port: 8000 });
|
||||||
console.log('🍵 green-tea running on http://localhost:8000');
|
console.log('🍵 green-tea running on http://localhost:8000');
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
runtime = "edge"
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"name": "{{project_name}}",
|
||||||
|
"type": "module",
|
||||||
|
"private": true,
|
||||||
|
"engines": { "node": ">=22" },
|
||||||
|
"scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy" },
|
||||||
|
"dependencies": { "@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"
|
||||||
@@ -2,7 +2,8 @@
|
|||||||
"name": "{{project_name}}",
|
"name": "{{project_name}}",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"engines": { "node": ">=22" },
|
||||||
"scripts": { "dev": "tsx watch src/main.ts" },
|
"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" }
|
"devDependencies": { "tsx": "^4", "typescript": "^5" }
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { createApp } from '@green-tea/core';
|
import { app } from './app';
|
||||||
import { AppModule } from './app.module';
|
|
||||||
|
|
||||||
const app = createApp({ modules: [AppModule] });
|
// Awaited, so a boot or bind failure stops the process with its own error instead of surfacing
|
||||||
|
// later as an unhandled rejection.
|
||||||
app.listen(3000);
|
await app.listen(3000);
|
||||||
console.log('🍵 green-tea running on http://localhost:3000');
|
console.log('🍵 green-tea running on http://localhost:3000');
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
"experimentalDecorators": true,
|
"experimentalDecorators": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true
|
"skipLibCheck": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# AGENTS.md — {{project_name}}
|
||||||
|
|
||||||
|
A [green-tea](https://green-tea.expressive-tea.io/docs/) app (`@green-tea/core` {{core_version}}), scaffolded by
|
||||||
|
matcha. Read this before editing.
|
||||||
|
|
||||||
|
## green-tea is not Express
|
||||||
|
|
||||||
|
green-tea is new, so code that looks right from Express, Fastify or NestJS habits is usually wrong here.
|
||||||
|
|
||||||
|
- The request pipeline is a **dependency graph**, not a middleware chain. There is no `app.use`, no
|
||||||
|
`next()`, and nothing mutates `req` or `res`.
|
||||||
|
- A `@Provider` builds a value once at boot. A `@Step` computes a value per request. Each declares
|
||||||
|
`provides` and `needs`, and green-tea derives the order from those declarations.
|
||||||
|
- A handler declares what it needs **in its signature**: `@needs('user')`, `@param('id')`, `@body()`,
|
||||||
|
`@query()`, `@cookie('name')`. Return a value to answer: an object becomes JSON 200, `undefined` becomes 204.
|
||||||
|
Throw `Unauthorized`, `NotFound` or another `HttpError` to fail the request.
|
||||||
|
- `createApp` validates the graph at boot. A token nothing provides, a token with two producers, or a node
|
||||||
|
that needs what it provides all fail before the app serves anything.
|
||||||
|
- **Reuse what the graph already has.** Before writing a new step, check whether a token you need, such as
|
||||||
|
`user`, already exists. Before writing `@needs('x')`, check that something provides `x`.
|
||||||
|
|
||||||
|
## Look before you edit
|
||||||
|
|
||||||
|
Ask the app what it contains instead of guessing. These commands read `src/app.ts` without starting a
|
||||||
|
server or opening connections:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
matcha routes --json # every route, its transport, and the chain it runs
|
||||||
|
matcha tokens --json # every token: who provides it, who needs it
|
||||||
|
matcha explain /some/:pattern --json # one route's chain, in execution order
|
||||||
|
matcha graph --format json # the whole graph
|
||||||
|
```
|
||||||
|
|
||||||
|
`explain` takes the route **pattern** as declared (`/users/:id`), not a URL.
|
||||||
|
|
||||||
|
## Where things are
|
||||||
|
|
||||||
|
- `src/app.ts` builds and exports `app` (`createApp({ modules: [...] })`). Introspection and tests import it.
|
||||||
|
- `src/main.ts` serves `app`. It is the only file that differs per runtime.
|
||||||
|
- `src/app.module.ts` lists the providers, steps and controllers with `@Module`.
|
||||||
|
- `matcha create controller|step|provider|module|transformer <Name>` generates a piece and wires it into the module.
|
||||||
|
- `matcha create plugin` scaffolds a plugin, in-app or (`--package`) as its own package.
|
||||||
|
- `matcha add sse|stream|buffer|ws|upload|cookie` adds a capability to a controller.
|
||||||
|
|
||||||
|
## Check your work
|
||||||
|
|
||||||
|
- Type-check: `npx tsc --noEmit` (Node, edge), `deno check src/main.ts` (Deno), `bunx tsc --noEmit` (Bun).
|
||||||
|
- Test without a port: `await app.fetch(new Request('http://x/api/thing'))` returns a `Response`.
|
||||||
|
- `matcha doctor` finds the misconfigurations that fail confusingly.
|
||||||
|
|
||||||
|
## The full guide
|
||||||
|
|
||||||
|
The rules, decorators, built-in tokens and common mistakes for the installed version are in the package
|
||||||
|
itself:
|
||||||
|
|
||||||
|
- npm / Bun: `node_modules/@green-tea/core/llms.txt`
|
||||||
|
- Deno (JSR): `https://jsr.io/@green-tea/core/{{core_version}}/llms.txt`
|
||||||
|
|
||||||
|
Official plugins (`@green-tea/jwt`, `@green-tea/metrics`, `@green-tea/rate-limit`, ...) ship no llms.txt;
|
||||||
|
read the installed one's `node_modules/@green-tea/<name>/README.md`.
|
||||||
|
|
||||||
|
The complete docs as one file: https://green-tea.expressive-tea.io/docs/llms-full.txt
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -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)
|
os=$(uname -s); arch=$(uname -m)
|
||||||
case "$os" in
|
case "$os" in
|
||||||
Darwin) case "$arch" in arm64|aarch64) triple=aarch64-apple-darwin;; x86_64) triple=x86_64-apple-darwin;; esac;;
|
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
|
esac
|
||||||
[ -n "${triple:-}" ] || { echo "SKIP: unsupported test host"; exit 0; }
|
[ -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
|
fi
|
||||||
[ -e "$bin2/matcha" ] && fail "matcha must NOT be installed on checksum mismatch"
|
[ -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"
|
echo "PASS: test_install.sh"
|
||||||
+151
-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();
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
assert!(out.contains("@Sse("));
|
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]
|
#[test]
|
||||||
@@ -83,3 +93,143 @@ fn add_errors_when_multiple_controllers_and_writes_nothing() {
|
|||||||
original
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_cookie_reads_with_the_decorator_and_writes_through_a_transformer() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
d.path().join("src/controllers/home.controller.ts"),
|
||||||
|
"import { Route, Get } from '@green-tea/core';\n\n\
|
||||||
|
@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
for _ in 0..2 {
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(d.path())
|
||||||
|
.args(["add", "cookie"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
}
|
||||||
|
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||||
|
assert!(out.contains("@cookie('theme')"), "{out}");
|
||||||
|
assert!(out.contains("'set-cookie': setCookie("), "{out}");
|
||||||
|
for symbol in ["Post", "Transformer", "body", "cookie", "setCookie"] {
|
||||||
|
assert!(
|
||||||
|
out.contains(&format!("{symbol},")) || out.contains(&format!("{symbol} }}")),
|
||||||
|
"{symbol} not imported:\n{out}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
out.matches("@Post('/prefs')").count(),
|
||||||
|
1,
|
||||||
|
"not idempotent:\n{out}"
|
||||||
|
);
|
||||||
|
}
|
||||||
+29
-1
@@ -11,7 +11,35 @@ fn help_lists_all_subcommands() {
|
|||||||
.stdout(contains("new"))
|
.stdout(contains("new"))
|
||||||
.stdout(contains("run"))
|
.stdout(contains("run"))
|
||||||
.stdout(contains("create"))
|
.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", "plugin"],
|
||||||
|
),
|
||||||
|
("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]
|
#[test]
|
||||||
|
|||||||
+112
@@ -84,3 +84,115 @@ fn create_module_writes_and_registers_in_createapp() {
|
|||||||
assert!(main.contains("AppModule, UsersModule"));
|
assert!(main.contains("AppModule, UsersModule"));
|
||||||
assert!(main.contains("import { 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}");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(dir: &std::path::Path, kind: &str, name: &str) -> assert_cmd::assert::Assert {
|
||||||
|
Command::cargo_bin("matcha")
|
||||||
|
.unwrap()
|
||||||
|
.current_dir(dir)
|
||||||
|
.args(["create", kind, name])
|
||||||
|
.assert()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_step_keeps_camel_case_in_the_token_and_reads_kebab_input() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
seed_module(d.path());
|
||||||
|
create(d.path(), "step", "current-user").success();
|
||||||
|
let step = std::fs::read_to_string(d.path().join("src/steps/currentuser.step.ts")).unwrap();
|
||||||
|
assert!(step.contains("class CurrentUserStep"), "{step}");
|
||||||
|
assert!(step.contains("provides: 'currentUser'"), "{step}");
|
||||||
|
assert!(step.contains("return { currentUser: null }"), "{step}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_refuses_a_token_core_already_provides() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
seed_module(d.path());
|
||||||
|
create(d.path(), "provider", "Logger")
|
||||||
|
.failure()
|
||||||
|
.stderr(predicates::str::contains("core already provides"));
|
||||||
|
create(d.path(), "step", "req").failure();
|
||||||
|
assert!(!d.path().join("src/providers/logger.provider.ts").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_refuses_a_name_that_cannot_be_a_class() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
seed_module(d.path());
|
||||||
|
create(d.path(), "controller", "2fast").failure();
|
||||||
|
create(d.path(), "controller", "us.ers").failure();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_does_not_overwrite_an_existing_file() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
seed_module(d.path());
|
||||||
|
create(d.path(), "controller", "Users").success();
|
||||||
|
let file = d.path().join("src/controllers/users.controller.ts");
|
||||||
|
std::fs::write(&file, "// edited\n").unwrap();
|
||||||
|
create(d.path(), "controller", "Users")
|
||||||
|
.failure()
|
||||||
|
.stderr(predicates::str::contains("already exists"));
|
||||||
|
assert_eq!(std::fs::read_to_string(&file).unwrap(), "// edited\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_transformer_writes_a_typed_function_and_says_where_it_goes() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
seed_module(d.path());
|
||||||
|
create(d.path(), "transformer", "csv-export")
|
||||||
|
.success()
|
||||||
|
.stdout(predicates::str::contains(
|
||||||
|
"@Transformer(csvExportTransformer)",
|
||||||
|
));
|
||||||
|
let file = std::fs::read_to_string(d.path().join("src/transformers/csvexport.transformer.ts"))
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
file.contains("import type { TransformerFn } from '@green-tea/core'"),
|
||||||
|
"{file}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
file.contains("export const csvExportTransformer: TransformerFn"),
|
||||||
|
"{file}"
|
||||||
|
);
|
||||||
|
let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
|
||||||
|
assert!(
|
||||||
|
!module.contains("Transformer"),
|
||||||
|
"a transformer is not a module member:\n{module}"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
+630
@@ -0,0 +1,630 @@
|
|||||||
|
use assert_cmd::Command;
|
||||||
|
use predicates::str::contains;
|
||||||
|
use tempfile::tempdir;
|
||||||
|
|
||||||
|
const APP: &str = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nexport const app = createApp({ modules: [AppModule] });\n";
|
||||||
|
|
||||||
|
fn project(app_ts: &str) -> tempfile::TempDir {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("src")).unwrap();
|
||||||
|
std::fs::write(d.path().join("src/app.ts"), app_ts).unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matcha(dir: &std::path::Path) -> Command {
|
||||||
|
let mut c = Command::cargo_bin("matcha").unwrap();
|
||||||
|
c.current_dir(dir);
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_is_the_default_and_wires_into_create_app() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "Plugin Algo"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
|
||||||
|
let index = std::fs::read_to_string(d.path().join("plugins/plugin-algo/index.ts")).unwrap();
|
||||||
|
assert!(index.contains("export function pluginAlgo("));
|
||||||
|
assert!(index.contains("options.provides ?? 'plugin-algo'"));
|
||||||
|
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||||
|
assert!(
|
||||||
|
app.contains("import { pluginAlgo } from '../plugins/plugin-algo/index';"),
|
||||||
|
"{app}"
|
||||||
|
);
|
||||||
|
assert!(app.contains("plugins: [pluginAlgo()]"), "{app}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_appends_to_an_existing_plugins_array() {
|
||||||
|
let d = project("import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: [other()] });\n");
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||||
|
assert!(app.contains("plugins: [other(), algo()]"), "{app}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_honours_folder() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--folder", "lib/plugins"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
assert!(d.path().join("lib/plugins/algo/index.ts").exists());
|
||||||
|
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||||
|
assert!(app.contains("'../lib/plugins/algo/index'"), "{app}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_leaves_a_non_array_plugins_alone_and_says_what_to_add() {
|
||||||
|
let original = "import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: PLUGINS });\n";
|
||||||
|
let d = project(original);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo"])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains("add algo() to createApp plugins[]"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(),
|
||||||
|
original
|
||||||
|
);
|
||||||
|
assert!(d.path().join("plugins/algo/index.ts").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_refuses_an_existing_folder() {
|
||||||
|
let d = project(APP);
|
||||||
|
std::fs::create_dir_all(d.path().join("plugins/algo")).unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("already exists"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(),
|
||||||
|
APP
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_refuses_a_folder_outside_the_project() {
|
||||||
|
let d = project(APP);
|
||||||
|
for folder in ["../outside", "/tmp/elsewhere"] {
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--folder", folder])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("inside the project"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn in_app_needs_a_project() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("src/app.ts"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_name_writes_nothing() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "🍵"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("does not make a plugin name"));
|
||||||
|
assert!(!d.path().join("plugins").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn off_a_tty_a_missing_name_is_an_error_not_a_hang() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin"])
|
||||||
|
.timeout(std::time::Duration::from_secs(10))
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("NAME"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn other_kinds_still_require_a_name() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "controller"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("needs a name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn files_under(dir: &std::path::Path) -> Vec<String> {
|
||||||
|
fn walk(base: &std::path::Path, dir: &std::path::Path, out: &mut Vec<String>) {
|
||||||
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out)
|
||||||
|
} else {
|
||||||
|
out.push(p.strip_prefix(base).unwrap().display().to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
walk(dir, dir, &mut out);
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_jsr_writes_the_tree_into_dir() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"Plugin Algo",
|
||||||
|
"--package=algo-pkg",
|
||||||
|
"--scope",
|
||||||
|
"@acme",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let pkg = d.path().join("algo-pkg");
|
||||||
|
assert_eq!(
|
||||||
|
files_under(&pkg),
|
||||||
|
[
|
||||||
|
".gitignore",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"LICENSE",
|
||||||
|
"README.md",
|
||||||
|
"deno.json",
|
||||||
|
"package.json",
|
||||||
|
"src/index.ts",
|
||||||
|
"test/plugin-algo.test.ts"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
let deno = std::fs::read_to_string(pkg.join("deno.json")).unwrap();
|
||||||
|
assert!(deno.contains("\"name\": \"@acme/plugin-algo\""), "{deno}");
|
||||||
|
assert!(deno.contains("npm:@green-tea/core@26.11.0-rc.2"), "{deno}");
|
||||||
|
// Without it `deno test` needs a `deno install` first, and then fails to
|
||||||
|
// type-check `node:assert` for want of @types/node.
|
||||||
|
assert!(deno.contains("\"nodeModulesDir\": \"auto\""), "{deno}");
|
||||||
|
let pj = std::fs::read_to_string(pkg.join("package.json")).unwrap();
|
||||||
|
assert!(pj.contains("\"private\": true"), "{pj}");
|
||||||
|
assert!(pj.contains("\"devDependencies\""), "{pj}");
|
||||||
|
assert!(
|
||||||
|
!pj.contains("\"dependencies\""),
|
||||||
|
"core is a type-only dependency: {pj}"
|
||||||
|
);
|
||||||
|
let readme = std::fs::read_to_string(pkg.join("README.md")).unwrap();
|
||||||
|
assert!(readme.contains("JSR is recommended"), "banner");
|
||||||
|
for runtime in ["| Node |", "| Deno |", "| Bun |", "| workerd (edge) |"] {
|
||||||
|
assert!(readme.contains(runtime), "{runtime} row");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_both_adds_the_npm_build() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=p",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--registry",
|
||||||
|
"both",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let pkg = d.path().join("p");
|
||||||
|
assert!(pkg.join("tsconfig.json").exists());
|
||||||
|
let pj = std::fs::read_to_string(pkg.join("package.json")).unwrap();
|
||||||
|
assert!(
|
||||||
|
pj.contains("\"name\": \"@acme/green-tea-algo\""),
|
||||||
|
"suggested name is the default: {pj}"
|
||||||
|
);
|
||||||
|
assert!(!pj.contains("\"private\""), "{pj}");
|
||||||
|
assert!(pj.contains("\"prepublishOnly\": \"npm run build\""), "{pj}");
|
||||||
|
let readme = std::fs::read_to_string(pkg.join("README.md")).unwrap();
|
||||||
|
assert!(readme.contains("npm i @acme/green-tea-algo"), "{readme}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn both_package_json_is_esm_only() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=p",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--registry",
|
||||||
|
"both",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap();
|
||||||
|
assert!(pj.contains("\"type\": \"module\""), "{pj}");
|
||||||
|
assert!(!pj.contains("require"), "{pj}");
|
||||||
|
assert!(!pj.contains(".cjs"), "{pj}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_accepts_any_npm_name_and_notes_the_convention() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=p",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--registry",
|
||||||
|
"both",
|
||||||
|
"--npm-name",
|
||||||
|
"algo-plugin",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains("green-tea-<x> is the naming convention"));
|
||||||
|
let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap();
|
||||||
|
assert!(pj.contains("\"name\": \"algo-plugin\""), "{pj}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_refuses_a_non_empty_directory_and_writes_nothing() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::write(d.path().join("keep.txt"), "x").unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--package", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("a plugin package needs an empty directory"));
|
||||||
|
assert_eq!(files_under(d.path()), ["keep.txt"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_in_an_empty_current_directory() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--package", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
assert!(d.path().join("deno.json").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_off_a_tty_needs_a_scope() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--package=p"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("--scope"));
|
||||||
|
assert!(!d.path().join("p").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_rejects_a_bad_scope_or_npm_name() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=p",
|
||||||
|
"--scope",
|
||||||
|
"Ac Me",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("scope"));
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=q",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--registry",
|
||||||
|
"both",
|
||||||
|
"--npm-name",
|
||||||
|
"Not Valid",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("npm name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_name_whose_factory_would_be_a_reserved_word_writes_nothing() {
|
||||||
|
for name in ["delete", "class", "default", "new", "import"] {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", name])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("reserved word"));
|
||||||
|
assert!(!d.path().join("plugins").exists(), "{name}");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(),
|
||||||
|
APP
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_package_whose_factory_would_be_a_reserved_word_writes_nothing() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"delete",
|
||||||
|
"--package=p",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("reserved word"));
|
||||||
|
assert!(!d.path().join("p").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `create app` → `createApp`, and `app` → `app`: both already exist in the entry, and a second
|
||||||
|
/// binding of the same name is a SyntaxError that would break the app, not just the plugin.
|
||||||
|
#[test]
|
||||||
|
fn in_app_refuses_a_factory_name_the_entry_already_uses() {
|
||||||
|
for name in ["create app", "app"] {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", name])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("already"));
|
||||||
|
assert!(!d.path().join("plugins").exists(), "{name}");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(),
|
||||||
|
APP,
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The scaffolded app.ts imports from '@green-tea/core' and './app.module'. Words inside those
|
||||||
|
/// strings are not bindings, so `core`, `tea` and `module` are free names for a plugin.
|
||||||
|
#[test]
|
||||||
|
fn words_inside_strings_and_comments_are_not_collisions() {
|
||||||
|
let app = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\n// the green tea app\nexport const app = createApp({ modules: [AppModule] });\n";
|
||||||
|
for name in ["core", "tea", "module", "green"] {
|
||||||
|
let d = project(app);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", name])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
assert!(
|
||||||
|
d.path().join(format!("plugins/{name}/index.ts")).exists(),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_engines_need_the_node_that_strips_types() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--package=p", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap();
|
||||||
|
// `node --test test/*.test.ts` needs unflagged type stripping, which is 22.18+.
|
||||||
|
assert!(pj.contains("\"node\": \">=22.18\""), "{pj}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_generated_test_asserts_the_token_is_in_the_graph() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--package=p", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let t = std::fs::read_to_string(d.path().join("p/test/algo.test.ts")).unwrap();
|
||||||
|
assert!(t.contains("app.graph()"), "{t}");
|
||||||
|
assert!(t.contains("provides.includes('algo')"), "{t}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn package_into_a_path_that_is_a_file_names_it() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::write(d.path().join("taken"), "x").unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=taken",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("taken is a file"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_empty_directory_error_names_the_directory() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("busy")).unwrap();
|
||||||
|
std::fs::write(d.path().join("busy/keep.txt"), "x").unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package=busy",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("busy: a plugin package needs an empty directory"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn in_app_leaves_nothing_behind_when_the_entry_cannot_be_written() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let d = project(APP);
|
||||||
|
let entry = d.path().join("src/app.ts");
|
||||||
|
std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o444)).unwrap();
|
||||||
|
// Root ignores the mode (CI containers run as root), so there is no failed
|
||||||
|
// write to roll back from. Say so rather than pass on a write that worked.
|
||||||
|
if std::fs::OpenOptions::new().write(true).open(&entry).is_ok() {
|
||||||
|
eprintln!("skipped: this user can write a 0444 file, so the failure cannot be staged");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo"])
|
||||||
|
.assert()
|
||||||
|
.failure();
|
||||||
|
std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||||
|
assert!(
|
||||||
|
!d.path().join("plugins/algo").exists(),
|
||||||
|
"the plugin folder is rolled back"
|
||||||
|
);
|
||||||
|
assert_eq!(std::fs::read_to_string(&entry).unwrap(), APP);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folder_dot_and_leading_dot_slash_give_clean_imports() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--folder", "."])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
assert!(d.path().join("algo/index.ts").exists());
|
||||||
|
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||||
|
assert!(app.contains("from '../algo/index'"), "{app}");
|
||||||
|
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--folder", "./plugins/"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||||
|
assert!(app.contains("from '../plugins/algo/index'"), "{app}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plugin_flags_on_another_kind_are_an_error() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "controller", "Users", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("only apply to create plugin"));
|
||||||
|
assert!(!d.path().join("src/controllers").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flags_for_the_other_mode_are_named_as_ignored() {
|
||||||
|
let d = project(APP);
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "algo", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains("--scope only applies to --package; ignored"));
|
||||||
|
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--folder",
|
||||||
|
"x",
|
||||||
|
"--check",
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(contains(
|
||||||
|
"--folder only applies to an in-app plugin; ignored",
|
||||||
|
))
|
||||||
|
.stdout(contains(
|
||||||
|
"--check only applies to an in-app plugin; ignored",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `--package algo` used to take `algo` as the directory. It now needs `--package=DIR`, so a
|
||||||
|
/// bare word after `--package` is the plugin's name.
|
||||||
|
#[test]
|
||||||
|
fn a_word_after_package_is_the_name_not_the_directory() {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args(["create", "plugin", "--package", "algo", "--scope", "acme"])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let deno = std::fs::read_to_string(d.path().join("deno.json")).unwrap();
|
||||||
|
assert!(deno.contains("\"name\": \"@acme/algo\""), "{deno}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scopes_jsr_would_refuse_are_refused() {
|
||||||
|
for scope in ["-", "-acme", "a", "abcdefghijklmnopqrstu"] {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
// `=` so a leading hyphen is a value, not another flag.
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package",
|
||||||
|
&format!("--scope={scope}"),
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.failure()
|
||||||
|
.stderr(contains("is not a JSR scope"));
|
||||||
|
assert!(!d.path().join("deno.json").exists(), "{scope}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn packages_ship_a_license_and_node_types() {
|
||||||
|
for registry in ["jsr", "both"] {
|
||||||
|
let d = tempdir().unwrap();
|
||||||
|
matcha(d.path())
|
||||||
|
.args([
|
||||||
|
"create",
|
||||||
|
"plugin",
|
||||||
|
"algo",
|
||||||
|
"--package",
|
||||||
|
"--scope",
|
||||||
|
"acme",
|
||||||
|
"--registry",
|
||||||
|
registry,
|
||||||
|
])
|
||||||
|
.assert()
|
||||||
|
.success();
|
||||||
|
let license = std::fs::read_to_string(d.path().join("LICENSE")).unwrap();
|
||||||
|
assert!(license.starts_with("MIT License"), "{registry}");
|
||||||
|
let pj = std::fs::read_to_string(d.path().join("package.json")).unwrap();
|
||||||
|
assert!(pj.contains("\"license\": \"MIT\""), "{registry}: {pj}");
|
||||||
|
assert!(pj.contains("\"@types/node\""), "{registry}: {pj}");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user