diff --git a/.changeset/first-release-cli.md b/.changeset/first-release-cli.md new file mode 100644 index 0000000..04fd6fa --- /dev/null +++ b/.changeset/first-release-cli.md @@ -0,0 +1,9 @@ +--- +'@druxt/cli': minor +--- + +First release of the Druxt command-line tool, with the binary `drx`. + +- `drx init` creates a site from a starter in a registry, records its layout and parts in `drx.config.json` and prints what the site needs next. +- `drx info` prints the versions of the CLI, Node and the packages of each part of a project. +- The registry holds one starter, `quickstart`, and the `monorepo` layout is the one available. diff --git a/.changeset/first-release-create-druxt.md b/.changeset/first-release-create-druxt.md new file mode 100644 index 0000000..86f7f31 --- /dev/null +++ b/.changeset/first-release-create-druxt.md @@ -0,0 +1,5 @@ +--- +'create-druxt': minor +--- + +First release. `npm create druxt my-site` runs `drx init my-site` from `@druxt/cli`. diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..ff40edd --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,30 @@ +{ + "name": "Druxt CLI", + "image": "mcr.microsoft.com/devcontainers/base:trixie", + "features": { + // The version in .nvmrc, which the pipelines build on. Node 16 is for running a site made from the 0.x + // starter: `nvm use 16.18.1` in the site's directory. + "ghcr.io/devcontainers/features/node:1": { + "version": "24.18.0", + "additionalVersions": "16.18.1" + }, + // For the Drupal part of a site `drx init` creates. The feature builds PHP from source, against trixie's + // SQLite, which meets Drupal 11's minimum. + "ghcr.io/devcontainers/features/php:1": { + "version": "8.4", + "installComposer": true + }, + "ghcr.io/devcontainers/features/github-cli:1": {} + }, + // Installs the dependencies and builds both packages, so `drx` runs as soon as the container is up. + "postCreateCommand": "npm ci && npm run build && npm link --workspace @druxt/cli --workspace create-druxt", + "customizations": { + "vscode": { + "extensions": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "vitest.explorer" + ] + } + } +} diff --git a/.github/banner.svg b/.github/banner.svg new file mode 100644 index 0000000..80a5230 --- /dev/null +++ b/.github/banner.svg @@ -0,0 +1 @@ + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb8c696..ec20d3b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,8 +4,7 @@ name: CI # The same lint and test set as .gitlab-ci.yml. Nothing on this side lints this # file: the GitLab pipeline runs actionlint over it. # -# There is no publish job. A release is cut by hand from the changesets until -# a workflow with its own token is added on purpose. +# There is no publish job here. release.yml cuts the releases. on: push: @@ -107,6 +106,7 @@ jobs: - run: npm ci + # The coverage floor in vitest.config.ts is what fails here. - run: npm test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -114,3 +114,40 @@ jobs: with: name: test-results path: reports/junit/ + + # A published install reads each package's files allowlist and links its + # binaries, which the unit tests do not. + pack: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - run: npm run build + + - name: Pack, install and run the packages + run: | + mkdir -p "$RUNNER_TEMP/pack-check" + npm pack --workspaces --pack-destination "$RUNNER_TEMP/pack-check" + version="$(node -p "require('./packages/cli/package.json').version")" + cd "$RUNNER_TEMP/pack-check" + npm init -y > /dev/null + npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + test "$(./node_modules/.bin/drx --version)" = "$version" + test -f node_modules/@druxt/cli/starters/index.json + ./node_modules/.bin/drx info + ./node_modules/.bin/create-druxt --help + + # The one step that needs the network: a site from the real quickstart + # tarball the registry entry points at. + - run: npm run test:e2e diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..d3ae502 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,492 @@ +--- +name: Release + +# Publishes the packages to npm, through two channels that stay off until the +# setup in RELEASING.md is complete. +# +# dev: a push to a release branch that changes a changeset publishes a +# snapshot of each package it releases under the `dev` dist-tag, such as +# 0.1.0-dev.20261030024907. Nothing is committed and no git tag is made. +# Install one with `@dev`. +# +# release: while changesets are pending, a "version packages" pull request +# stays open against the release branch. Merging it is the release decision. +# The push that follows finds each version that is not released yet, +# publishes it, and creates a `@` tag and a GitHub Release. +# +# A release branch is named for its major, such as `0.x` or `1.x`, matched by +# pattern so a branch cut on demand is not invisible here. +# +# Building and publishing are separate jobs. A build job runs repository code, +# install scripts included, so it holds no publishing rights. It ends by +# packing the tarballs. A publish job holds the OIDC permission and runs +# nothing from the repository. It downloads the tarballs and hands them to npm. +# +# Publishing uses npm trusted publishing (OIDC), so there is no token. It stays +# off until the repository variable NPM_PUBLISH is `true`. Until then the +# packed tarballs are the dry run. + +on: + push: + branches: ['*.x'] + paths: + - '.changeset/*.md' + # Entering or leaving pre mode changes this file and no changeset. + - '.changeset/pre.json' + # The changelog generator and its settings write the version pull + # request, so a change to either rebuilds it. + - '.changeset/changelog.cjs' + - '.changeset/config.json' + - '!.changeset/README.md' + # No branch filter, so a stacked pull request that changes these paths runs + # the rehearsal too. + pull_request: + paths: + - .github/workflows/release.yml + - .changeset/changelog.cjs + - .changeset/config.json + - scripts/release-check.mjs + - package.json + - package-lock.json + # The manifests that are published. + - packages/*/package.json + workflow_dispatch: + +permissions: + contents: read + +# Never cancel a publish half way through. +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + # Whether this run follows a changeset, which decides whether it cuts a dev + # snapshot. A push that changes only the changelog generator or its settings + # cuts none. Every push still reaches `pack`, so a release that an earlier + # run left unfinished, or whose queued run a later push replaced, still goes + # out. + changes: + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + changeset: ${{ steps.diff.outputs.changeset }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + + - id: diff + env: + EVENT: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} + AFTER: ${{ github.sha }} + run: | + changeset=true + # Only a push can be generator-only. + if [ "$EVENT" = push ]; then + changeset=false + # A push that creates a branch, or whose previous commit is gone, + # has nothing to compare against, so it cuts no snapshot. A manual + # run cuts it instead. + # NUL-separated, so git does not quote a name with non-ASCII bytes. + if git cat-file -e "$BEFORE^{commit}" 2>/dev/null \ + && git diff --name-only -z "$BEFORE" "$AFTER" \ + | tr '\0' '\n' \ + | grep -v '^\.changeset/README\.md$' \ + | grep -Eq '^\.changeset/([^/]+\.md|pre\.json)$'; then + changeset=true + fi + fi + echo "changeset=$changeset" >> "$GITHUB_OUTPUT" + + # Runs on pull requests too, as a rehearsal. No id-token here: a lifecycle + # script in a pull request must not be able to reach npm. A fork's own + # pushes have no business releasing, so they skip. + snapshot: + needs: changes + if: ${{ !github.event.repository.fork && needs.changes.outputs.changeset == 'true' }} + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + version: ${{ steps.snapshot.outputs.version }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + # corepack reads the packageManager field, as in ci.yml. + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - name: Count pending changesets + id: pending + run: | + count=$(find .changeset -maxdepth 1 -name '*.md' ! -name 'README.md' | wc -l) + echo "count=$count" >> "$GITHUB_OUTPUT" + echo "Pending changesets: $count" >> "$GITHUB_STEP_SUMMARY" + + # A snapshot cannot be cut in pre mode. The checkout is thrown away, so + # dropping the marker here changes nothing on the branch. An empty + # changeset releases nothing and leaves the versions as they were, so + # only a package whose version changed goes on to be packed. + - name: Version the snapshot + id: snapshot + if: steps.pending.outputs.count != '0' + run: | + rm -f .changeset/pre.json + versions() { + for dir in packages/*; do + node -p "const p = require('./$dir/package.json'); p.name + '@' + p.version + ' $dir'" + done + } + versions > "$RUNNER_TEMP/before" + npx changeset version --snapshot dev + versions | grep -vxFf "$RUNNER_TEMP/before" > "$RUNNER_TEMP/snapshot" || true + if [ -s "$RUNNER_TEMP/snapshot" ]; then + echo "version=$(cut -d ' ' -f 1 "$RUNNER_TEMP/snapshot" | paste -s -d ' ')" >> "$GITHUB_OUTPUT" + else + echo "No changeset releases a package, so there is no snapshot." >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.snapshot.outputs.version != '' + run: npm run build + + - name: Check the release + if: steps.snapshot.outputs.version != '' + run: npm run release:check + + - name: Pack the tarballs + if: steps.snapshot.outputs.version != '' + run: | + # A directory per package, named after the package's own, so the + # publishing job takes them in the order of packages/: @druxt/cli + # before create-druxt, which depends on that snapshot of it. + while read -r release dir; do + mkdir -p "dev-package/${dir##*/}" + npm pack --workspace "$dir" --pack-destination "dev-package/${dir##*/}" + echo "Packed $release" >> "$GITHUB_STEP_SUMMARY" + done < "$RUNNER_TEMP/snapshot" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: steps.snapshot.outputs.version != '' + with: + name: dev-package + path: dev-package + retention-days: 7 + if-no-files-found: error + + # No checkout and no install: nothing from the repository runs with the OIDC + # permission. Trusted publishing needs npm 11.5.1 or later, so npm is set to + # an exact version here and not left to the one the runner's Node has. + dev: + needs: snapshot + # workflow_dispatch takes no branch filter and can target a tag, so a tag + # named like a release branch would otherwise pass the name test. + if: >- + github.event_name != 'pull_request' && + startsWith(github.ref, 'refs/heads/') && + endsWith(github.ref, '.x') && + vars.NPM_PUBLISH == 'true' && + needs.snapshot.outputs.version != '' + runs-on: ubuntu-latest + permissions: + id-token: write + steps: + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + # An exact version, and no install scripts: this job can publish. + - name: Update npm + run: npm install --global --ignore-scripts npm@11.19.1 + + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: dev-package + path: dev-package + + # The leading ./ matters: npm reads a bare "dir/file.tgz" as the GitHub + # shorthand "user/repo" and tries to clone it. A snapshot npm already + # has is skipped, so a rerun after one package published and the next + # failed goes on to the one that is missing. + - name: Publish under the dev tag + shell: bash + run: | + # Prints what npm has for a field of a package or version, and nothing + # when npm has none. Any other failure stops the job here: a registry + # error must never read as "not published". + npm_field() { + local out + if out="$(npm view "$1" "$2" 2> npm-view.err)"; then + printf '%s' "$out" + elif ! grep -q 'E404' npm-view.err; then + cat npm-view.err >&2 + return 1 + fi + } + for file in dev-package/*/*.tgz; do + release="$(tar -xzOf "$file" package/package.json | node -p "const p = JSON.parse(require('fs').readFileSync(0, 'utf8')); p.name + '@' + p.version")" + have="$(npm_field "$release" version)" + if [ -n "$have" ]; then + echo "- $release (already on npm)" >> "$GITHUB_STEP_SUMMARY" + continue + fi + npm publish "./$file" --tag dev --access public + echo "- $release (published, \`dev\`)" >> "$GITHUB_STEP_SUMMARY" + done + + # Opens or updates the version pull request. It holds a token that can write + # to the repository, and the changesets action leaves that token on disk, so + # this job installs without scripts and builds and packs nothing. The pack + # job does that, read-only. What it does run from the repository is what + # versioning needs: the `release:version` script and the changelog generator + # that changesets loads, both as the release branch has them. + version: + if: ${{ !github.event.repository.fork && github.event_name == 'push' }} + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + outputs: + pending: ${{ steps.changesets.outputs.has-changesets }} + steps: + # GitHub runs no checks on a pull request opened with the workflow's own + # token, and a protected branch requires them. An app token gets them + # run. Without the app the pull request still opens, and its checks need + # a manual run. + - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + id: app + if: vars.RELEASE_APP_ID != '' + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + - run: corepack enable && corepack prepare --activate + + - run: npm ci --ignore-scripts + + # Only opens or updates the pull request. The title is the squash commit's + # subject, so it has to be a conventional commit. v2, because the v1 + # action is the one for @changesets/cli 2. + - uses: changesets/action@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2.1.2 + id: changesets + with: + github-token: ${{ steps.app.outputs.token || github.token }} + version-script: npm run release:version + pr-title: 'chore(release): version packages' + commit-message: 'chore(release): version packages' + + # A pending changeset means its work is not finished, so nothing + # publishes. Say so, rather than leave a quiet run that reads as a + # failure. + - name: Say why nothing will publish + if: steps.changesets.outputs.has-changesets == 'true' + run: | + { + echo "### No publish this run" + echo + echo "Changesets are still pending, so the version pull request has been" + echo "opened or updated instead. Merging that pull request is what releases." + } >> "$GITHUB_STEP_SUMMARY" + + # Finds each version that is not fully released, and packs it with its + # release notes. A version counts as released once npm has it and its GitHub + # Release exists, so a rerun after a failed Release creation still finishes + # the job. It runs repository code, so it holds no write or publishing rights. + pack: + needs: version + if: needs.version.outputs.pending == 'false' + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + tags: ${{ steps.unreleased.outputs.tags }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + # corepack reads the packageManager field, as in ci.yml. + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + # One directory per package to release, named after the package's own, + # holding its tag here and its dist-tag, tarball and notes below. + - name: Find the versions that are not released yet + id: unreleased + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + tags= + for dir in packages/*; do + tag="$(node -p "const p = require('./$dir/package.json'); p.name + '@' + p.version")" + if [ -n "$(node scripts/release-check.mjs "$dir" --unpublished)" ]; then + echo "$tag is not on npm yet." + elif ! gh release view "$tag" > /dev/null 2>&1; then + echo "$tag is on npm, but has no GitHub Release yet." + else + echo "$tag is already released." + continue + fi + mkdir -p "release-package/${dir##*/}" + echo "$tag" > "release-package/${dir##*/}/tag" + tags="$tags $tag" + done + echo "tags=${tags# }" >> "$GITHUB_OUTPUT" + + # npm moves `latest` to whatever it publishes untagged, so a release from + # an older major's branch, or a prerelease, takes a tag of its own. + - name: Choose the npm dist-tags + if: steps.unreleased.outputs.tags != '' + run: | + for out in release-package/*; do + node scripts/release-check.mjs "packages/${out##*/}" --dist-tag > "$out/dist-tag" + done + + - name: Build + if: steps.unreleased.outputs.tags != '' + run: npm run build + + - name: Check the release + if: steps.unreleased.outputs.tags != '' + run: npm run release:check + + # The tarball and the release notes travel together, so the publishing + # job needs nothing from the repository. + - name: Pack the tarballs and the release notes + if: steps.unreleased.outputs.tags != '' + run: | + for out in release-package/*; do + dir="packages/${out##*/}" + npm pack --workspace "$dir" --pack-destination "$out" + # The entry runs from the version's heading to the next version, or + # to the first line changesets would not write. + DIR="$dir" node -e " + const dir = './' + process.env.DIR + const lines = require('fs').readFileSync(dir + '/CHANGELOG.md', 'utf8').split('\n') + const start = lines.indexOf('## ' + require(dir + '/package.json').version) + const entry = [] + for (const line of start < 0 ? [] : lines.slice(start + 1)) { + if (/^(## |[^\s#-])/.test(line)) break + entry.push(line) + } + process.stdout.write(entry.join('\n').trim() + '\n') + " > "$out/notes.md" + done + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: steps.unreleased.outputs.tags != '' + with: + name: release-package + path: release-package + retention-days: 30 + if-no-files-found: error + + # No checkout and no install: nothing from the repository runs with the OIDC + # permission. A rerun skips a version an earlier attempt published, and + # still creates a missing GitHub Release. + release: + needs: pack + if: needs.pack.outputs.tags != '' && vars.NPM_PUBLISH == 'true' + runs-on: ubuntu-latest + # Pauses for a required reviewer before anything reaches npm. + environment: release + permissions: + id-token: write + contents: write + steps: + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + # An exact version, and no install scripts: this job can publish. + - name: Update npm + run: npm install --global --ignore-scripts npm@11.19.1 + + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: release-package + path: release-package + + - name: Publish, tag and create the GitHub Releases + shell: bash + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + # Prints what npm has for a field of a package or version, and nothing + # when npm has none. Any other failure stops the job here: a registry + # error must never read as "not published". + npm_field() { + local out + if out="$(npm view "$1" "$2" 2> npm-view.err)"; then + printf '%s' "$out" + elif ! grep -q 'E404' npm-view.err; then + cat npm-view.err >&2 + return 1 + fi + } + for out in release-package/*; do + tag="$(cat "$out/tag")" + dist_tag="$(cat "$out/dist-tag")" + # The dist-tag was chosen when the tarball was packed, and the + # approval can come much later. Another release line may have + # published a higher version since, and an explicit `latest` + # would move the tag back to this one. Ask npm again. + if [ "$dist_tag" = latest ]; then + latest="$(npm_field "${tag%@*}" dist-tags.latest)" + dist_tag="$(node -e ' + const core = (version) => version.split("-")[0].split(".").map(Number) + const [version, latest] = process.argv.slice(1).map((v) => v && core(v)) + const below = latest && (version[0] - latest[0] || version[1] - latest[1] || version[2] - latest[2]) < 0 + console.log(below ? "latest-" + version[0] : "latest") + ' "${tag##*@}" "$latest")" + fi + have="$(npm_field "$tag" version)" + if [ -n "$have" ]; then + state="already on npm" + else + npm publish "./$out"/*.tgz --access public --tag "$dist_tag" + state="published" + fi + if ! gh release view "$tag" > /dev/null 2>&1; then + # Only a release npm calls latest is GitHub's latest too. + flags=(--latest=false) + [ "$dist_tag" = latest ] && flags=(--latest) + [ "$dist_tag" = next ] && flags+=(--prerelease) + gh release create "$tag" --target "$GITHUB_SHA" --title "$tag" --notes-file "$out/notes.md" "${flags[@]}" + fi + echo "- $tag ($state, \`$dist_tag\`)" >> "$GITHUB_STEP_SUMMARY" + done diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f8ae19d..979a200 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -192,6 +192,9 @@ lint:prose: # --- Test --- # +# No network: the tests serve their own registry and tarball from a loopback +# port. The coverage floor in vitest.config.ts is what fails this job when +# coverage drops. test:unit: extends: .node stage: test @@ -210,6 +213,39 @@ test:unit: # Puts the coverage percentage in the merge request widget. coverage: '/All files\s*\|\s*([\d.]+)/' +# A published install reads each package's files allowlist and links its +# binaries. The unit tests read the sources and do neither, so this is the job +# that proves the packages a user downloads can be installed and run. +test:pack: + extends: .node + stage: test + needs: [] + script: + - section_start "build" "Building both packages" + - npm run build + - section_end "build" + - section_start "pack" "Packing and installing the tarballs" + - mkdir -p "$CI_PROJECT_DIR/pack-check" + - npm pack --workspaces --pack-destination "$CI_PROJECT_DIR/pack-check" + - cd "$CI_PROJECT_DIR/pack-check" && npm init -y > /dev/null + - npm install ./druxt-cli-*.tgz ./create-druxt-*.tgz --no-audit --no-fund + - test "$(./node_modules/.bin/drx --version)" = "$(node -p "require('$CI_PROJECT_DIR/packages/cli/package.json').version")" + - test -f node_modules/@druxt/cli/starters/index.json + - ./node_modules/.bin/drx info + - ./node_modules/.bin/create-druxt --help + - section_end "pack" + +# The one job that needs the network: it creates a site from the real +# quickstart tarball the registry entry points at, and reads it back. +test:e2e: + extends: .node + stage: test + needs: [] + script: + - section_start "e2e" "Creating a site from the real starter" + - npm run test:e2e + - section_end "e2e" + # # --- Secret detection --- # diff --git a/.gitlab/scripts/check-attribution.sh b/.gitlab/scripts/check-attribution.sh index a322e89..3beef94 100755 --- a/.gitlab/scripts/check-attribution.sh +++ b/.gitlab/scripts/check-attribution.sh @@ -46,8 +46,12 @@ tools='claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|w # Each alternative in pieces: the trailer keys, the footer, the session link # and the noreply address are the shapes seen in practice. -trailer='(co-authored|assisted)'"-by:.*\\b(${tools})\\b" -footer="generated (with|by).*\\b(${tools}|ai)\\b" +# +# The word edges are spelled out. "\b" is a GNU extension: the regex library +# git is built with on macOS reads it as a plain "b", and matches nothing. +edge='[^[:alnum:]_]' +trailer='(co-authored|assisted)'"-by:(.*${edge})?(${tools})(${edge}|\$)" +footer="generated (with|by)${edge}(.*${edge})?(${tools}|ai)(${edge}|\$)" session='claude-'"session:|claude\\.ai/code/session" address='noreply'"@anthropic\\.com" pattern="(${trailer})|(${footer})|(${session})|(${address})" diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc index 9d5f5eb..c20b044 100644 --- a/.markdownlint-cli2.jsonc +++ b/.markdownlint-cli2.jsonc @@ -2,11 +2,13 @@ // MD013 (line length) is off: prose reflows, and a hard wrap in Markdown // shows up as a diff on every edit to the paragraph, not the sentence. // MD024 is scoped to siblings so a changelog can repeat "Fixed" per release. + // MD033 allows the two elements of the README banner, a linked image. // MD041 is off: a changeset starts with front matter, not a heading. "config": { "default": true, "MD013": false, "MD024": { "siblings_only": true }, + "MD033": { "allowed_elements": ["a", "img"] }, "MD041": false }, "ignores": [ diff --git a/AGENTS.md b/AGENTS.md index c4a1b71..d29256a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,11 +10,23 @@ The Druxt command-line tool: `@druxt/cli`, with the binary `drx`, and `create-dr registry. `npm run lint:private` enforces the URL-shaped half of this and runs in the pipeline. It cannot catch an internal name written as prose, so that part is on you. +- **A private registry or source is never named in the code.** It belongs in + the user configuration file, on the user's machine. +- **The names of kinds stay in `packages/cli/src/adapters/`.** A part has a + role and a kind, and the kind is a value. No key, type or command outside + that directory may be named after a kind. `packages/cli/test/seams.test.ts` + fails when one is. +- **Every prompt has a flag,** and a command never waits for input when there + is no terminal. +- **stdout is the result, stderr is everything else.** A command with `--json` + prints one JSON document on stdout and nothing else there. - **Check a library's API in its own package before using it.** The unjs libraries change between minors. - **Conventional Commits**, and the same for pull request and merge request titles. This repository squash-merges, so the title becomes the commit subject, and a prose title breaks the next push to the target branch. +- **The coverage floor in `vitest.config.ts` goes up, never down.** If a change + drops coverage, the change needs a test. - **No AI tool is credited.** No co-author trailer naming an assistant, no generated-with footer, no session link, in commits, merge request descriptions or tracked files. The commit-msg hook rejects it locally, and @@ -25,35 +37,43 @@ The Druxt command-line tool: `@druxt/cli`, with the binary `drx`, and `create-dr - **A change a user of a package would notice carries a changeset** (`npm run changeset`). Do not write a package's `CHANGELOG.md` by hand: the release writes it from `.changeset/`, through `.changeset/changelog.cjs`. -- **Nothing here publishes to npm.** There is no publish job in either - pipeline. Do not add one that would run without a token. +- **Only `.github/workflows/release.yml` publishes to npm,** and only once the + setup in `RELEASING.md` is done. Its publish jobs check out nothing and hold + no npm token: npm accepts the workflow's own identity. The `release` job holds the + run's own GitHub token, to create the tag and the Release. Do not add a publish step anywhere else, or one that runs + repository code. ## Layout -| Path | Purpose | -| ------------------------ | ------------------------------------------------------------------ | -| `packages/cli/` | `@druxt/cli`. The manifest only: there are no sources yet | -| `packages/create-druxt/` | `create-druxt`. The manifest only: there are no sources yet | -| `.changeset/` | Pending release notes, and the generator that writes the changelog | -| `scripts/` | Repository tooling, excluded from the packages | -| `test/` | Tests of the repository tooling | -| `.githooks/` | Committed hooks, enabled by `npm install` | -| `.gitlab/scripts/` | Content checks, copied from the Druxt repository standard | +| Path | Purpose | +| ---------------------------- | ------------------------------------------------------------------ | +| `packages/cli/` | `@druxt/cli`. `src/commands/` holds a file per command | +| `packages/cli/src/adapters/` | A file per kind of part, behind the interface in `adapter.ts` | +| `packages/cli/src/registry/` | Reading and checking the starter registry | +| `packages/create-druxt/` | `create-druxt`, which runs `drx init` | +| `starters/` | The public starter registry. The build copies it into `@druxt/cli` | +| `.changeset/` | Pending release notes, and the generator that writes the changelog | +| `scripts/` | Repository tooling, excluded from the packages | +| `test/` | Tests of the repository tooling | +| `.githooks/` | Committed hooks, enabled by `npm install` | +| `.gitlab/scripts/` | Content checks, copied from the Druxt repository standard | ## Commands ```bash npm install # dependencies, and enables the git hooks -npm run typecheck # tests and configuration -npm test # vitest, coverage reported, no network +npm run build # tsc for both packages, and the registry copy +npm run typecheck # sources, tests and configuration +npm test # vitest, coverage floor enforced, no network +npm run test:e2e # creates a site from the real starter, needs the network npm run lint # every linter except prose npm run lint:prose # Vale, after `npm run lint:prose:install` ``` ## Toolchain -Pinned in `.mise.toml`. The packages will be TypeScript, built with `tsc` and -no bundler, as ES modules. `c12` stays on 3 while 4 is a release candidate, and +Pinned in `.mise.toml`. The packages are TypeScript, built with `tsc` and no +bundler, as ES modules. `c12` stays on 3 while 4 is a release candidate, and `typescript` stays on 6 until `typescript-eslint` supports 7. Renovate is configured not to offer either. `markdown-it`, which the changelog generator reads a changeset with, stays on 14: from 15 it no longer takes diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..cf45821 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +Each package keeps its own changelog, written by [changesets](https://github.com/changesets/changesets) +when a release is cut: + +- `@druxt/cli`: `packages/cli/CHANGELOG.md` +- `create-druxt`: `packages/create-druxt/CHANGELOG.md` + +Changes that are merged and not yet released are the files in `.changeset/`. + +Changes to the repository that are in no package, such as its pipelines, are recorded here. + +## [Unreleased] + +### Added + +- The workspace, with `@druxt/cli` and `create-druxt`, on the Druxt repository standard: committed + git hooks, linting, a GitLab pipeline and a GitHub Actions workflow, secret scanning with a + detection canary, a private-host check, an attribution check and prose linting. +- The starter registry under `starters/`, with one entry, `quickstart`. +- A release workflow, which keeps a pull request open that versions the packages, and publishes + them when it is merged. `RELEASING.md` describes it. +- A changelog generator, a check that runs before a publish, and CodeQL analysis. + +[Unreleased]: https://github.com/druxt/cli/commits/0.x diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index adaab14..a895afa 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,22 +15,45 @@ nothing. The toolchain is pinned in `.mise.toml`. With [mise](https://mise.jdx.dev) installed, `mise install` gives you the same Node the pipeline uses. +To run the CLI from your checkout: + +```bash +npm run build +node packages/cli/dist/bin.js --help +``` + ## Before you push ```bash npm run lint # every check except prose, which needs Vale installed npm run typecheck -npm test # vitest, with coverage reported +npm test # vitest, with the coverage floor enforced ``` -The pre-commit hook runs all three. The tests run offline. +The pre-commit hook runs all three. Because the unit tests serve their own +fixture registry and tarball from a loopback port, they run offline. `npm run test:e2e` is the +one test that downloads the real starter, and it is not in the hook. ## Tests -Write the test before the code it covers, and see it fail. The tests of the -repository's own tooling are in `test/`. +Write the test before the code it covers, and see it fail. A change to a +command needs a test that runs the command through `runCli`, as +`packages/cli/test/helpers/run.ts` does. + +`vitest.config.ts` carries a coverage floor measured from the current tests. +Raise it when coverage improves. Do not lower it to make a change pass. -`npm test` reports coverage and does not enforce a floor yet. +## Adding a starter + +Add `starters/.json` and the name to `starters/index.json`. The format is +in the README. Set `maintained` to the date you last saw the starter work, and +run `npm run test:e2e` if the default starter changed. + +## Adding a kind + +Add a file to `packages/cli/src/adapters/` that exports a `KindAdapter`, and +add it to the list in `packages/cli/src/adapters/index.ts`. Nothing outside +that directory should need to change. ## Changesets @@ -51,6 +74,12 @@ edit those files by hand. The first line of a changeset becomes the entry: The rest of the changeset follows as a paragraph of its own. +## Releases + +Releases are cut from `0.x` by `.github/workflows/release.yml`. Merging the +pull request it keeps open, titled `chore(release): version packages`, is the +release. `RELEASING.md` has the whole process and its one-time setup. + ## Commit messages [Conventional Commits](https://www.conventionalcommits.org). The commit-msg diff --git a/README.md b/README.md new file mode 100644 index 0000000..17c1f4c --- /dev/null +++ b/README.md @@ -0,0 +1,212 @@ + + + + @druxt/cli: Command-line tool for Druxt + + + +# Druxt CLI + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +This repository holds two packages: + +| Package | What it is | +| -------------- | ------------------------------------------------------------- | +| `@druxt/cli` | The CLI. Its binary is `drx`. | +| `create-druxt` | `npm create druxt`. It runs `drx init` and does nothing else. | + +## Quickstart + +```bash +npm create druxt@latest my-site +cd my-site +npx @druxt/cli info +``` + +You will need Node 22.12 or newer to run the CLI. The site it creates has its own requirements, which `drx init` prints. + +## Running it + +| You want to | Run | +| ------------------- | -------------------------------------------------------------------------------------------- | +| Create a site | `npm create druxt@latest [dir]` | +| Run any command | `npx @druxt/cli ` | +| Use it in a project | `npm install -D @druxt/cli`, then `drx ` in a package script or `npx drx ` | + +`npx drx` does not work outside a project that has `@druxt/cli` installed. Another package holds the name `drx` on npm, so `npx drx` downloads that package and not this one. Use `npx @druxt/cli`. + +## Node + +`drx` runs on Node 22.12 or later. A site may pin an older Node for itself, as the 0.x starter pins Node 16, and a version manager then switches to it in the site's directory. `drx` still works there: started on an older Node, it runs the same command again on a newer Node from the machine. It looks beside its own binary first, which is the Node it was installed with, then along `PATH`, then where mise, nvm, fnm, Volta and asdf keep their installs. + +The tools a command starts, such as the site's package manager, come from your own `PATH`, so the site is installed with the Node it runs on. When the Node you are on is too old, `DRX_NODE` chooses the newer one: set it to the path of a `node` binary. A Node that is new enough is used as it is, whatever `DRX_NODE` says. + +## Commands + +### `drx init [dir]` + +Creates a site from a starter in a registry, writes `drx.config.json` at its root, and prints what the site needs and what to run next. + +| Option | What it does | Default | +| --------------------------- | ----------------------------------------------------------------- | ------------------------------------------------ | +| `[dir]` | The directory to create the site in | Asked for, or the starter's default with `--yes` | +| `--starter ` | The starter to create the site from | The registry's default | +| `--layout ` | `monorepo`, `split` or `workspace`. Only `monorepo` is available. | The starter's layout | +| `--registry ` | A starter registry: a URL, or a name from the user configuration | The public registry | +| `--source ` | Where the Druxt packages come from. Only `npm` is available. | `npm` | +| `--install`, `--no-install` | Install the site's dependencies after creating it, or do not | Asked for, or no | +| `--force` | Write into a directory that exists and is not empty | Refuse | +| `--yes`, `-y` | Accept the default for everything not given, and ask nothing | | +| `--json` | Print the result as JSON on stdout | | + +At a terminal, `init` asks for the directory, the starter when the registry has more than one, the layout, and whether to install. A flag answers each question, so the command runs unattended: + +```bash +npx @druxt/cli init my-site --yes --json +``` + +With no terminal, `init` uses the defaults and never waits for input. It needs the directory or `--yes`, and fails with a message saying so when it has neither. + +`--install` runs the install of the package manager the starter declares. For the `quickstart` starter that is `npm install`, which also sets up the Drupal backend when PHP and Composer are present. The steps printed under "Next" then leave out what the install ran, so nothing is set up twice. + +### `drx info` + +Prints the versions of the CLI and Node. Inside a project it adds the layout and, for each part, the packages that matter: `nuxt` and every `druxt`, `druxt-*` or `@druxt/*` package for a Nuxt part, and Drupal core and the Druxt module for a Drupal part. Run it from any directory in the project. + +| Option | What it does | +| -------- | ---------------------------------- | +| `--json` | Print the report as JSON on stdout | + +Outside a project it says so and prints the two versions. + +### `drx --help`, `drx --help`, `drx --version` + +Usage for the CLI or one command, and the version. + +### Output and exit codes + +- The result of a command goes to stdout: text, or one JSON document with `--json`. +- Progress, warnings, errors and prompts go to stderr. +- A command that fails exits with 1. With `--json` it also prints `{ "ok": false, "error": { "code", "message" } }` on stdout. + +## The project configuration + +`drx init` writes `drx.config.json` at the root of the site. Later commands find the project by it. + +```json +{ + "layout": "monorepo", + "line": "0.x", + "starter": "quickstart", + "source": "npm", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ] +} +``` + +| Key | What it holds | +| --------- | ---------------------------------------------------------------------------------------------------- | +| `layout` | The arrangement of the parts: `monorepo`, `split` or `workspace` | +| `line` | The Druxt release line | +| `starter` | The name of the starter the site was created from | +| `source` | The name of the source its Druxt packages come from | +| `parts` | Each part of the site: its `role` (`frontend` or `backend`), its `kind` and its `path` from the root | + +A kind is `nuxt` or `drupal` in this version. + +## The starter registry + +A registry is a URL that answers `/.json` for each starter, in the format [giget](https://github.com/unjs/giget) defines, and `/index.json` with the names. The public registry is the [`starters/`](starters/) directory of this repository. + +```json +{ + "name": "quickstart", + "tar": "https://codeload.github.com/druxt/quickstart/tar.gz/refs/heads/develop", + "defaultDir": "my-druxt-site", + "url": "https://github.com/druxt/quickstart", + "druxt": { + "line": "0.x", + "layout": "monorepo", + "parts": [ + { "role": "frontend", "kind": "nuxt", "path": "nuxt" }, + { "role": "backend", "kind": "drupal", "path": "drupal" } + ], + "requires": { + "node": "16.18.1", + "tools": ["PHP 8.3 or newer with Composer, or DDEV"] + }, + "maintained": "2026-11-15", + "default": true, + "steps": ["npm run setup", "npm run dev"], + "install": { + "runs": ["npm run setup"], + "notes": ["npm run dev starts the backend again when it is not running."] + } + } +} +``` + +`name`, `tar`, `defaultDir`, `url`, `subdir` and `headers` are giget's fields. giget ignores the `druxt` object, so the same file works with `GIGET_REGISTRY= npx giget quickstart`. + +| Key in `druxt` | What it holds | +| ---------------- | -------------------------------------------------------------------------- | +| `line` | The Druxt release line | +| `layout` | The layout the starter has | +| `parts` | The parts of the starter, as in the project configuration | +| `requires.node` | The Node version the site runs on: a full version, or a major such as `22` | +| `requires.tools` | What else the site needs, each as a phrase to show the user | +| `maintained` | The date the starter was last checked to work, as `YYYY-MM-DD` | +| `default` | `true` for the starter `init` uses when none is named | +| `steps` | Optional. The commands to run in the new site, in order | +| `install.runs` | Optional. The steps the install runs itself, left out of "Next" after one | +| `install.notes` | Optional. Lines printed under "Note" after an install | + +`index.json` is `{ "starters": ["quickstart"] }`. + +`init` checks an entry before it downloads anything, and fails with a message naming the field that is wrong. It warns when the starter was last maintained more than a year ago, and when the running Node is not the one the starter needs. + +The package includes a copy of the public registry. When the public registry cannot be read, `init` uses the copy and says so. A registry you name with `--registry` is never replaced by the copy. + +## The user configuration + +`~/.config/drx/config.json` names registries and sources of your own. `DRX_CONFIG` points at another file, and `XDG_CONFIG_HOME` is used when it is set. + +```json +{ + "registries": { + "team": "https://example.com/starters" + }, + "sources": { + "next": { "type": "npm", "tag": "next" }, + "branch": { "type": "git", "url": "https://example.com/druxt.git", "ref": "main" } + } +} +``` + +- `--registry team` reads starters from that URL. `GIGET_AUTH` is giget's own variable, and giget sends it as a bearer token with every tarball it downloads. The CLI also sends it to a registry you name, and never to the public registry. +- `--source` takes `npm`, `git:#`, or a name defined here. Only `npm` creates a site in this version. The others are read and answer that they are not available yet. + +## Not there yet + +- The `split` and `workspace` layouts. `--layout` accepts them and fails with a message. +- Sources other than `npm`. +- Adding a module, making a wrapper component and upgrading a site. +- Kinds other than `nuxt` and `drupal`. +- A published public registry. Until this repository is public, `init` reads the copy in the package. + +## Development + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +```bash +npm install +npm run build +npm test +``` + +## Licence + +[MIT](LICENSE) diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..89549d6 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,67 @@ +# Releasing + +`@druxt/cli` and `create-druxt` publish to npm from `.github/workflows/release.yml`. Nobody runs `npm publish` by hand after the first version. The workflow stays off until the [one-time setup](#one-time-setup) is done. + +| Channel | npm dist-tag | When it publishes | What it is for | +| ----------- | ------------ | ---------------------------------------------------------- | ------------------------------------- | +| Development | `dev` | A push to a release branch that changes a changeset | Trying unreleased work on a real site | +| Stable | `latest` | When you merge the pull request that versions the packages | Everyone else | + +A release branch is named for its major, such as `0.x` or `1.x`. The workflow matches them by pattern, so a branch cut on demand releases too. Set `baseBranch` in `.changeset/config.json` to the branch your releases come from. + +Each package has a version of its own. A changeset names the packages it releases, and a package no changeset names is not published. `create-druxt` depends on `@druxt/cli`, so a release of the CLI brings a patch release of `create-druxt` with it. + +## Development releases + +A push to a release branch that adds or changes a changeset cuts a snapshot of each package the pending changesets release, and publishes it under the `dev` tag: + +```bash +npx @druxt/cli@dev init my-site +``` + +A snapshot version reads `0.1.0-dev.20261030024907`: the version the pending changesets add up to, then the tag and a timestamp. Nothing is committed, no git tag is made, and `latest` does not move. A changeset that releases nothing, such as an empty one, cuts no snapshot. + +## Stable releases + +1. Merge pull requests that carry a changeset. Add one with `npm run changeset`. +2. The workflow opens a pull request titled `chore(release): version packages`, and keeps it up to date. It holds the version bumps, each package's changelog entry and the lock file that matches them. +3. Merge that pull request when the release is ready. This is the release decision. +4. The push that follows waits for a reviewer to approve the `release` environment, then publishes each new version to `latest`. It also creates a tag such as `@druxt/cli@0.1.0` for each, with a GitHub Release whose notes are that version's entry in the package's `CHANGELOG.md`. + +A release from an older major's branch publishes under its own tag: `1.9.1`, cut on `1.x` after `2.0.0`, goes to `latest-1`. GitHub does not mark its Release as the latest one. A prerelease publishes under `next`. The tag is chosen when the version is packed, and `latest` is checked against npm again after the approval, in case another release line published a higher version while the run waited. + +A few seconds pass between that check and the publish. If two release lines publish inside them, `latest` can end on the older major. Nothing is lost. Run `npm dist-tag add @druxt/cli@2.0.0 latest` for each package to point the tag back at the newer version. Release branches are not put in one queue to close this, because a release that waits in a shared queue can be cancelled by the next one. + +A version counts as released once npm has it and its GitHub Release exists. If a run fails between the two, or after one package and before the other, rerun it: it skips what is published and creates what is missing. + +## Build and publish jobs + +| Job | Runs repository code | Can write to the repository | Can publish to npm | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | ------------------ | +| `snapshot`, `pack` | Yes, install scripts included | No | No | +| `version` | The `release:version` script and the changelog generator, as the release branch has them. Dependencies are installed without scripts | Yes, to open the version pull request | No | +| `dev`, `release` | No, they check out nothing | `release` creates the tags and Releases | Yes | + +The build jobs end by packing the tarballs, and the publish jobs hand those tarballs to npm. A pull request rehearses the `snapshot` job only, so code in a pull request never runs with publishing rights. A fork's own pushes skip the workflow. + +## The pre-publish gate + +`npm run release:check` runs before every publish, on both channels and over both packages. It refuses a release when: + +- a dependency uses a specifier that only resolves on the author's machine, such as `link:` or `workspace:` +- the version is at or below the highest one npm already has for its major +- an entry in `files` was not built + +## The changelogs + +The pull request that versions the packages is written by `npm run release:version`. It applies the pending changesets and writes `packages/cli/CHANGELOG.md` and `packages/create-druxt/CHANGELOG.md` through `.changeset/changelog.cjs`. It then brings `package-lock.json` up to date with the new versions. `CONTRIBUTING.md` says how a changeset reads as an entry. + +## One-time setup + +Publishing uses npm trusted publishing, so there is no npm token to store or rotate. Until the setup is complete the workflow stops after packing: the tarballs it would have published are attached to the run as an artifact, and nothing reaches npm. + +1. Publish the first version of each package by hand, from a clean build of the merged version pull request: `npm publish --workspaces --access public`. A package that does not exist on npm yet cannot name a trusted publisher. +2. On the npm website, open each package, then **Settings**, then **Trusted publisher**. Choose GitHub Actions, and enter the organization, the repository and the workflow filename `release.yml`. Leave the environment empty, because the `dev` job publishes without one. Under **Allowed actions**, tick **Allow npm publish**: the workflow publishes directly, and a publisher limited to staged publishing refuses it. +3. Under the repository's **Settings**, then **Environments**, create the `release` environment and add yourself, or the people who cut releases, as required reviewers. Without a rule the environment still works, but nothing pauses before a stable publish. +4. Create a GitHub App with read and write access to **Contents** and **Pull requests**, and install it on the repository. Store its ID as the repository variable `RELEASE_APP_ID` and its private key as the secret `RELEASE_APP_PRIVATE_KEY`. GitHub doesn't run checks on a pull request opened with the workflow's own token, so a protected branch would never see them pass. Without the app, tick **Allow GitHub Actions to create and approve pull requests** under **Settings**, **Actions**, **General**, or the workflow cannot open its pull request at all. +5. Set the repository variable `NPM_PUBLISH` to `true`. diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..537b190 --- /dev/null +++ b/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/package-lock.json b/package-lock.json index 40e5409..bf3aa7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -62,7 +62,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -72,7 +72,7 @@ "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, + "devOptional": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -82,7 +82,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/types": "^7.29.14" @@ -98,7 +98,7 @@ "version": "7.29.14", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/helper-string-parser": "^7.29.14", @@ -389,7 +389,6 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.6.0.tgz", "integrity": "sha512-4GZynIB2IIe431odxesswvWTCP6orvqd6e2b07b3VFWBQRqUqIHc/EPIZwFoKS692QBp+ooPuXKaJV8g4kXuYA==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-width": "^3.0.2", @@ -404,7 +403,6 @@ "version": "1.9.0", "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.9.0.tgz", "integrity": "sha512-tEj8X2No2A1c9NDnZECxiiJ8TP3vmFlN9tLlLeSaMqVW4tUmVG2R4qpv/eP4zymWxnymYLkLcIYVV0VcWj3RCQ==", - "dev": true, "license": "MIT", "dependencies": { "@clack/core": "1.6.0", @@ -3397,6 +3395,34 @@ "node": ">=8" } }, + "node_modules/c12": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.4.tgz", + "integrity": "sha512-cM0ApFQSBXuourJejzwv/AuPRvAxordTyParRVcHjjtXirtkzM0uK2L9TTn9s0cXZbG7E55jCivRQzoxYmRAlA==", + "license": "MIT", + "dependencies": { + "chokidar": "^5.0.0", + "confbox": "^0.2.4", + "defu": "^6.1.6", + "dotenv": "^17.3.1", + "exsolve": "^1.0.8", + "giget": "^3.2.0", + "jiti": "^2.6.1", + "ohash": "^2.0.11", + "pathe": "^2.0.3", + "perfect-debounce": "^2.1.0", + "pkg-types": "^2.3.0", + "rc9": "^3.0.1" + }, + "peerDependencies": { + "magicast": "*" + }, + "peerDependenciesMeta": { + "magicast": { + "optional": true + } + } + }, "node_modules/cac": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/cac/-/cac-7.1.0.tgz", @@ -3516,6 +3542,27 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "license": "MIT" + }, "node_modules/cliui": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", @@ -3573,6 +3620,12 @@ "node": ">= 6" } }, + "node_modules/confbox": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.2.4.tgz", + "integrity": "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ==", + "license": "MIT" + }, "node_modules/conventional-changelog-angular": { "version": "9.4.0", "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-9.4.0.tgz", @@ -3914,6 +3967,12 @@ "dev": true, "license": "MIT" }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -3924,6 +3983,12 @@ "node": ">=6" } }, + "node_modules/destr": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/destr/-/destr-2.0.5.tgz", + "integrity": "sha512-ugFTXCtDZunbzasqBxrK93Ik/DRYsO6S/fedkWEMKqt04xZ4csmnmwGDBAb07QWNaGMAmnTIemsYZCksjATwsA==", + "license": "MIT" + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -3949,6 +4014,18 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/emoji-regex": { "version": "10.6.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", @@ -4261,6 +4338,12 @@ "node": ">=12.0.0" } }, + "node_modules/exsolve": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "integrity": "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==", + "license": "MIT" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -4326,14 +4409,12 @@ "version": "3.0.3", "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", - "dev": true, "license": "MIT" }, "node_modules/fast-string-width": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-truncated-width": "^3.0.2" @@ -4360,7 +4441,6 @@ "version": "0.2.2", "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", - "dev": true, "license": "MIT", "dependencies": { "fast-string-width": "^3.0.2" @@ -4542,6 +4622,15 @@ "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" } }, + "node_modules/giget": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/giget/-/giget-3.3.1.tgz", + "integrity": "sha512-r+mvuDjrjMpsdw46Kmeydb8bdHm7wOKw8wNBtTndkjbPjgAp5oUJUxRE76wZFknxIPokfWvep2qSXK37aXE6zg==", + "license": "MIT", + "bin": { + "giget": "dist/cli.mjs" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -4852,7 +4941,6 @@ "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", - "dev": true, "license": "MIT", "bin": { "jiti": "lib/jiti-cli.mjs" @@ -5374,7 +5462,7 @@ "version": "0.5.5", "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", - "dev": true, + "devOptional": true, "license": "MIT", "dependencies": { "@babel/parser": "^7.29.7", @@ -6250,6 +6338,12 @@ "node": ">=12.20.0" } }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "license": "MIT" + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -6447,6 +6541,18 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -6467,6 +6573,23 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pkg-types": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "integrity": "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==", + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.3", + "pathe": "^2.0.3" + } + }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "integrity": "sha512-ZUAKhKlkCOrIGKc8cj7zek9s9z1mveHif/25nUshI2BzCRzF7KH7KHa+Lnh2ubq+e1tIlaFuP763mzW4qVoehg==", + "license": "MIT" + }, "node_modules/postcss": { "version": "8.5.33", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", @@ -6584,6 +6707,16 @@ ], "license": "MIT" }, + "node_modules/rc9": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rc9/-/rc9-3.1.0.tgz", + "integrity": "sha512-ufjkNVzbRHKcCOmTahZkmVsyc3W+MSk3jY03m+a7tGHkIsdVMG9l10/3HvFbWkkKzY5VFp3pkRsIo/UYgmFL7Q==", + "license": "MIT", + "dependencies": { + "defu": "^6.1.7", + "destr": "^2.0.5" + } + }, "node_modules/re2js": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/re2js/-/re2js-2.9.1.tgz", @@ -6594,6 +6727,19 @@ "node": ">=20.0.0" } }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -6748,7 +6894,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-2.0.0.tgz", "integrity": "sha512-2WCqLdt12eN6ehLI50S2/ZxoowXU3DD1KVPRyVP0WEsFahrGZZmCdq1K59qjJljMRIDTwx1D9YaRK+hDneBUMg==", - "dev": true, "license": "MIT", "engines": { "node": ">=20" @@ -6784,7 +6929,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, + "devOptional": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -7380,6 +7525,12 @@ "name": "@druxt/cli", "version": "0.0.0", "license": "MIT", + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" + }, "bin": { "drx": "dist/bin.js" }, @@ -7390,6 +7541,9 @@ "packages/create-druxt": { "version": "0.0.0", "license": "MIT", + "dependencies": { + "@druxt/cli": "^0.0.0" + }, "bin": { "create-druxt": "dist/bin.js" }, diff --git a/packages/cli/LICENSE b/packages/cli/LICENSE new file mode 100644 index 0000000..51b53d2 --- /dev/null +++ b/packages/cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DruxtJS + +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. diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..335895d --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,21 @@ +# @druxt/cli + +> The command-line tool for [Druxt](https://druxtjs.org), the fully decoupled Drupal and Nuxt framework. + +```bash +npx @druxt/cli init my-site +npx @druxt/cli info +``` + +The binary is `drx`. Install the package in a project to use that name: `npm install -D @druxt/cli`, then `drx ` in a package script. `npx drx` without the package installed downloads another package that holds the name on npm. + +| Command | What it does | +| ---------------- | ------------------------------------------------------------------------- | +| `drx init [dir]` | Creates a site from a starter and records its layout in `drx.config.json` | +| `drx info` | Prints the versions of the CLI, Node and the packages of each part | + +The options, the registry format and the configuration files are in the [repository README](https://github.com/druxt/cli#readme). + +## Licence + +[MIT](LICENSE) diff --git a/packages/cli/package.json b/packages/cli/package.json index 4749cba..cc6661e 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -18,6 +18,10 @@ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" + }, + "./launch": { + "types": "./dist/launch.d.ts", + "import": "./dist/launch.js" } }, "types": "./dist/index.d.ts", @@ -36,5 +40,11 @@ }, "publishConfig": { "access": "public" + }, + "dependencies": { + "@clack/prompts": "^1.9.0", + "c12": "^3.3.4", + "citty": "^0.2.2", + "giget": "^3.3.1" } } diff --git a/packages/cli/src/adapters/adapter.ts b/packages/cli/src/adapters/adapter.ts new file mode 100644 index 0000000..623b547 --- /dev/null +++ b/packages/cli/src/adapters/adapter.ts @@ -0,0 +1,33 @@ +import { DrxError } from '../errors.js' +import type { Role } from '../parts.js' + +/** One package a part depends on. */ +export interface PackageVersion { + name: string + /** The range the part asks for, or null when it does not declare one. */ + range: string | null + /** The version that is installed, or null when none is. */ + installed: string | null +} + +/** + * Everything the CLI knows about one kind of part. The commands call this + * interface and never a kind by name, so a new kind is a new file in this + * directory and one line in index.ts. + */ +export interface KindAdapter { + /** The value a part's `kind` holds. */ + readonly kind: string + readonly role: Role + /** True when the directory holds a part of this kind. */ + detect(dir: string): Promise + /** The packages `info` reports for a part of this kind. */ + packages(dir: string): Promise + /** Installs a module into the part and registers it. Not available yet. */ + addModule(dir: string, name: string): Promise +} + +/** The `addModule` of every adapter until the `add` command exists. */ +export async function addModuleNotAvailable(): Promise { + throw new DrxError('not-available', 'Adding a module is not available yet.') +} diff --git a/packages/cli/src/adapters/drupal.ts b/packages/cli/src/adapters/drupal.ts new file mode 100644 index 0000000..e043157 --- /dev/null +++ b/packages/cli/src/adapters/drupal.ts @@ -0,0 +1,60 @@ +import { join } from 'node:path' +import { isRecord } from '../validate.js' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +/** Any of these in `require` makes a Composer project a Drupal site. */ +const CORE = ['drupal/core-recommended', 'drupal/core'] +const REPORTED = [...CORE, 'drupal/druxt'] + +async function required(dir: string): Promise> { + return stringMap(await readJsonObject(join(dir, 'composer.json')), 'require') +} + +/** The version of each package Composer has installed, which is none until `composer install` has run. */ +async function installed(dir: string): Promise> { + const manifest = await readJsonObject( + join(dir, 'vendor', 'composer', 'installed.json') + ) + const versions = new Map() + const packages = manifest?.packages + if (!Array.isArray(packages)) return versions + for (const entry of packages) { + if ( + isRecord(entry) && + typeof entry.name === 'string' && + typeof entry.version === 'string' + ) { + versions.set(entry.name, entry.version) + } + } + return versions +} + +export const drupalAdapter: KindAdapter = { + kind: 'drupal', + role: 'backend', + + async detect(dir) { + const requires = await required(dir) + return CORE.some((name) => name in requires) + }, + + async packages(dir) { + const requires = await required(dir) + const versions = await installed(dir) + return REPORTED.filter((name) => name in requires).map( + (name): PackageVersion => ({ + name, + range: requires[name] ?? null, + installed: versions.get(name) ?? null, + }) + ) + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/index.ts b/packages/cli/src/adapters/index.ts new file mode 100644 index 0000000..e8dfaef --- /dev/null +++ b/packages/cli/src/adapters/index.ts @@ -0,0 +1,16 @@ +import type { KindAdapter } from './adapter.js' +import { drupalAdapter } from './drupal.js' +import { nuxtAdapter } from './nuxt.js' + +export type { KindAdapter, PackageVersion } from './adapter.js' + +/** Every kind this version knows. A new kind is a new file and a line here. */ +const ADAPTERS: readonly KindAdapter[] = [nuxtAdapter, drupalAdapter] + +export function adapterFor(kind: string): KindAdapter | undefined { + return ADAPTERS.find((adapter) => adapter.kind === kind) +} + +export function knownKinds(): string[] { + return ADAPTERS.map((adapter) => adapter.kind) +} diff --git a/packages/cli/src/adapters/nuxt.ts b/packages/cli/src/adapters/nuxt.ts new file mode 100644 index 0000000..7cfe1e6 --- /dev/null +++ b/packages/cli/src/adapters/nuxt.ts @@ -0,0 +1,71 @@ +import { existsSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { + addModuleNotAvailable, + type KindAdapter, + type PackageVersion, +} from './adapter.js' +import { readJsonObject, stringMap } from './read-json.js' + +const CONFIG_FILES = ['js', 'ts', 'mjs', 'cjs', 'mts'].map( + (extension) => `nuxt.config.${extension}` +) + +/** The framework itself, then the Druxt packages of either naming scheme. */ +const FRAMEWORK = 'nuxt' +const DRUXT_PACKAGE = /^(druxt|druxt-.+|@druxt\/.+)$/ + +async function declared(dir: string): Promise> { + const manifest = await readJsonObject(join(dir, 'package.json')) + return { + ...stringMap(manifest, 'devDependencies'), + ...stringMap(manifest, 'dependencies'), + } +} + +/** + * The package.json of an installed package, as Node finds it from `dir`: in + * the nearest node_modules on the way up, which is the project's root when + * its workspaces are hoisted. + */ +async function installedManifest(dir: string, name: string) { + for (let from = resolve(dir); ; from = dirname(from)) { + const manifest = await readJsonObject( + join(from, 'node_modules', name, 'package.json') + ) + if (manifest || dirname(from) === from) return manifest + } +} + +export const nuxtAdapter: KindAdapter = { + kind: 'nuxt', + role: 'frontend', + + async detect(dir) { + if (CONFIG_FILES.some((file) => existsSync(join(dir, file)))) return true + return FRAMEWORK in (await declared(dir)) + }, + + async packages(dir) { + const ranges = await declared(dir) + const names = Object.keys(ranges) + .filter((name) => name === FRAMEWORK || DRUXT_PACKAGE.test(name)) + .sort((a, b) => + a === FRAMEWORK ? -1 : b === FRAMEWORK ? 1 : a.localeCompare(b) + ) + + const versions: PackageVersion[] = [] + for (const name of names) { + const installed = await installedManifest(dir, name) + versions.push({ + name, + range: ranges[name] ?? null, + installed: + typeof installed?.version === 'string' ? installed.version : null, + }) + } + return versions + }, + + addModule: addModuleNotAvailable, +} diff --git a/packages/cli/src/adapters/read-json.ts b/packages/cli/src/adapters/read-json.ts new file mode 100644 index 0000000..11b6f00 --- /dev/null +++ b/packages/cli/src/adapters/read-json.ts @@ -0,0 +1,28 @@ +import { readFile } from 'node:fs/promises' +import { isRecord } from '../validate.js' + +/** A JSON file's object, or undefined when it is missing or not an object. */ +export async function readJsonObject( + file: string +): Promise | undefined> { + try { + const parsed: unknown = JSON.parse(await readFile(file, 'utf8')) + return isRecord(parsed) ? parsed : undefined + } catch { + return undefined + } +} + +/** The string values of one key of an object, such as `dependencies`. */ +export function stringMap( + object: Record | undefined, + key: string +): Record { + const value = object?.[key] + if (!isRecord(value)) return {} + return Object.fromEntries( + Object.entries(value).filter( + (entry): entry is [string, string] => typeof entry[1] === 'string' + ) + ) +} diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts new file mode 100644 index 0000000..f4e9ecc --- /dev/null +++ b/packages/cli/src/args.ts @@ -0,0 +1,33 @@ +import type { ArgsDef } from 'citty' +import { DrxError } from './errors.js' + +/** + * Fails on an option the command does not define. citty accepts any flag + * and hands it to the command, so a mistyped one would otherwise be ignored. + */ +export function assertKnownOptions( + rawArgs: string[], + definitions: ArgsDef, + command: string +): void { + const known = new Set() + for (const [name, definition] of Object.entries(definitions)) { + if (definition.type === 'positional') continue + known.add(name) + if (definition.type === 'boolean') known.add(`no-${name}`) + const alias = 'alias' in definition ? definition.alias : undefined + for (const short of [alias ?? []].flat()) known.add(short) + } + + for (const argument of rawArgs) { + if (argument === '--') return + if (!argument.startsWith('-') || argument === '-') continue + const name = argument.replace(/^--?/, '').split('=')[0] ?? '' + if (!known.has(name)) { + throw new DrxError( + 'usage', + `Unknown option ${argument.split('=')[0]}. Run "drx ${command} --help" for the options.` + ) + } + } +} diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts new file mode 100644 index 0000000..dc663a2 --- /dev/null +++ b/packages/cli/src/bin.ts @@ -0,0 +1,11 @@ +#!/usr/bin/env node +import { homedir } from 'node:os' +import { launchProcess } from './launch.js' + +// The commands are named, not imported: their libraries do not load on an old Node. +process.exitCode = await launchProcess( + process, + homedir(), + new URL('./cli.js', import.meta.url).href, + 'runCli' +) diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts new file mode 100644 index 0000000..b9b42b7 --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,110 @@ +import { stripVTControlCharacters } from 'node:util' +import { defineCommand, renderUsage, runCommand, type CommandDef } from 'citty' +import { infoCommand } from './commands/info.js' +import { initCommand } from './commands/init.js' +import { defaultContext, type CliContext, type TextStream } from './context.js' +import { DrxError } from './errors.js' +import { cliVersion } from './package-root.js' + +function mainCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'drx', + version: cliVersion(), + description: 'The Druxt command-line tool', + }, + subCommands: { + init: initCommand(context), + info: infoCommand(context), + }, + }) +} + +/** citty colours its output whatever it writes to. A pipe gets plain text. */ +function plain(stream: TextStream, text: string): string { + return stream.isTTY ? text : stripVTControlCharacters(text) +} + +/** The meta of a command, which citty lets be a value, a promise or a function. */ +async function resolveMeta(command: CommandDef) { + const { meta } = command + return typeof meta === 'function' ? await meta() : await meta +} + +/** The usage of the command the arguments name, or of `drx` itself. */ +async function usage( + main: CommandDef, + subCommands: Record, + argv: string[], + startedAs: CliContext['startedAs'] +): Promise { + const name = argv.find((argument) => !argument.startsWith('-')) + const command = name ? subCommands[name] : undefined + if (command && startedAs && startedAs.command === name) { + const meta = { ...(await resolveMeta(command)), name: startedAs.name } + return renderUsage({ ...command, meta }) + } + return command ? renderUsage(command, main) : renderUsage(main) +} + +/** The code and message to report for anything a command throws. */ +function describe(error: unknown): { code: string; message: string } { + if (error instanceof DrxError) { + return { code: error.code, message: error.message } + } + // citty's own error for a bad argument or command. The class is not + // exported, so it is recognised by name. + if (error instanceof Error && error.name === 'CLIError') { + return { + code: 'usage', + message: `${stripVTControlCharacters(error.message)}. Run "drx --help" for the commands and "drx --help" for their options.`, + } + } + return { + code: 'unexpected', + message: + error instanceof Error ? (error.stack ?? error.message) : String(error), + } +} + +/** + * Runs the CLI with the given arguments and returns the exit code. It never + * exits the process or throws, so a caller decides what to do with the code. + */ +export async function runCli( + argv: string[], + overrides: Partial = {} +): Promise { + const context = { ...defaultContext(), ...overrides } + const main = mainCommand(context) + const subCommands = main.subCommands as Record + const { stdout, stderr } = context + + try { + if (argv.includes('--help') || argv.includes('-h')) { + stdout.write( + `${plain(stdout, await usage(main, subCommands, argv, context.startedAs))}\n` + ) + return 0 + } + if (argv.length === 1 && ['--version', '-v'].includes(argv[0] ?? '')) { + stdout.write(`${cliVersion()}\n`) + return 0 + } + if (argv.length === 0) { + stderr.write(`${plain(stderr, await renderUsage(main))}\n`) + return 1 + } + await runCommand(main, { rawArgs: argv }) + return 0 + } catch (error) { + const failure = describe(error) + if (argv.includes('--json')) { + stdout.write( + `${JSON.stringify({ ok: false, error: failure }, null, 2)}\n` + ) + } + stderr.write(`Error: ${failure.message}\n`) + return 1 + } +} diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts new file mode 100644 index 0000000..8cf8775 --- /dev/null +++ b/packages/cli/src/commands/info.ts @@ -0,0 +1,133 @@ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { adapterFor, type PackageVersion } from '../adapters/index.js' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { columns, createOutput } from '../output.js' +import { cliVersion } from '../package-root.js' +import type { Part } from '../parts.js' +import { + CONFIG_FILE, + findProjectRoot, + loadProjectConfig, + type ProjectConfig, +} from '../project.js' + +interface PartReport extends Part { + /** False when the part's directory is not there. */ + exists: boolean + /** True when the adapter for its kind recognises the directory. */ + detected: boolean + packages: PackageVersion[] +} + +interface InfoReport { + cli: { name: string; version: string } + node: string + project: + | (Omit & { + root: string + parts: PartReport[] + }) + | null +} + +async function reportPart(root: string, part: Part): Promise { + const dir = join(root, part.path) + const adapter = adapterFor(part.kind) + const exists = existsSync(dir) + const detected = exists && adapter ? await adapter.detect(dir) : false + return { + ...part, + exists, + detected, + packages: detected && adapter ? await adapter.packages(dir) : [], + } +} + +function partLines(part: PartReport): string[] { + const heading = `${part.role} ${part.kind} ${part.path}/` + if (!adapterFor(part.kind)) { + return [heading, ` This version has no adapter for the ${part.kind} kind.`] + } + if (!part.exists) return [heading, ' The directory does not exist.'] + if (!part.detected) { + return [heading, ` The directory does not look like a ${part.kind} part.`] + } + if (part.packages.length === 0) { + return [heading, ' No packages to report.'] + } + const rows = part.packages.map((entry) => [ + entry.name, + entry.range ?? '', + entry.installed ? `installed ${entry.installed}` : 'not installed', + ]) + return [heading, ...columns(rows, ' ')] +} + +function text(report: InfoReport, cwd: string): string { + const lines = columns([ + ['drx', report.cli.version], + ['Node', report.node], + ]) + lines.push('') + const project = report.project + if (!project) { + lines.push( + `Not inside a Druxt project: no ${CONFIG_FILE} in ${cwd} or above it.` + ) + return lines.join('\n') + } + lines.push( + ...columns([ + ['Project', project.root], + ['Layout', project.layout], + ['Line', project.line], + ['Starter', project.starter], + ['Source', project.source], + ]) + ) + for (const part of project.parts) { + lines.push('', ...partLines(part)) + } + return lines.join('\n') +} + +const args = { + json: { + type: 'boolean', + description: 'Print the report as JSON on stdout', + }, +} satisfies ArgsDef + +export function infoCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'info', + description: + 'Print the versions of the CLI, Node and the packages of each part of the project', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'info') + const output = createOutput(context, parsed.json === true) + + const report: InfoReport = { + cli: { name: '@druxt/cli', version: cliVersion() }, + node: context.nodeVersion, + project: null, + } + const root = findProjectRoot(context.cwd) + if (root) { + const config = await loadProjectConfig(root) + const parts: PartReport[] = [] + for (const part of config.parts) { + parts.push(await reportPart(root, part)) + } + report.project = { root, ...config, parts } + } + output.result(report, text(report, context.cwd)) + }, + }) +} diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts new file mode 100644 index 0000000..5fe932e --- /dev/null +++ b/packages/cli/src/commands/init.ts @@ -0,0 +1,399 @@ +import { createHash } from 'node:crypto' +import { existsSync, readdirSync, statSync } from 'node:fs' +import { isAbsolute, join, relative, resolve } from 'node:path' +import { defineCommand, type ArgsDef } from 'citty' +import { assertKnownOptions } from '../args.js' +import type { CliContext } from '../context.js' +import { DrxError } from '../errors.js' +import { + assertLayoutAvailable, + AVAILABLE_LAYOUTS, + isLayout, + LAYOUTS, + type Layout, +} from '../layouts.js' +import { createOutput, type Output } from '../output.js' +import { writeProjectConfig, type ProjectConfig } from '../project.js' +import { shellQuote } from '../repeat.js' +import type { StarterEntry } from '../registry/entry.js' +import { + defaultStarter, + openRegistry, + type Registry, +} from '../registry/registry.js' +import { + assertSourceAvailable, + DEFAULT_SOURCE, + resolveSource, +} from '../sources.js' +import { loadUserConfig, resolveRegistryUrl } from '../user-config.js' + +/** A starter not maintained for this long gets a warning. */ +const STALE_AFTER_DAYS = 365 + +const args = { + dir: { + type: 'positional', + required: false, + description: 'The directory to create the site in', + }, + starter: { + type: 'string', + valueHint: 'name', + description: + 'The starter to create the site from (default: the default of the registry)', + }, + layout: { + type: 'enum', + options: [...LAYOUTS], + description: `How the parts of the site are put together (available: ${AVAILABLE_LAYOUTS.join(', ')})`, + }, + registry: { + type: 'string', + valueHint: 'url', + description: + 'A starter registry: a URL, or a name from the user configuration', + }, + source: { + type: 'string', + valueHint: 'name', + description: `Where the Druxt packages come from (default: ${DEFAULT_SOURCE})`, + }, + install: { + type: 'boolean', + description: 'Install the dependencies of the site after creating it', + negativeDescription: 'Do not install the dependencies of the site', + }, + force: { + type: 'boolean', + description: 'Write into a directory that exists and is not empty', + }, + yes: { + type: 'boolean', + alias: 'y', + description: 'Accept the default for everything not given, and ask nothing', + }, + json: { + type: 'boolean', + description: 'Print the result as JSON on stdout', + }, +} satisfies ArgsDef + +interface InitOptions { + dir?: string + starter?: string + layout?: Layout + registry?: string + source?: string + install?: boolean + force: boolean + yes: boolean +} + +/** A string option's value, or an error when it was given with none. */ +function valueOf(name: string, value: unknown): string | undefined { + if (value === undefined) return undefined + if (typeof value !== 'string' || value.trim() === '') { + throw new DrxError('usage', `--${name} needs a value.`) + } + return value +} + +async function chooseStarter( + registry: Registry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + if (options.starter) return registry.entry(options.starter) + + const names = await registry.names() + if (canAsk && names.length > 1) { + const chosen = await context.prompter.select({ + message: 'Which starter?', + choices: names.map((name) => ({ value: name, label: name })), + }) + return registry.entry(chosen) + } + + const entry = await defaultStarter(registry) + if (!entry) { + throw new DrxError( + 'unknown-starter', + `The registry marks no starter as the default. Pass --starter with one of: ${names.join(', ')}.` + ) + } + return entry +} + +async function chooseLayout( + entry: StarterEntry, + options: InitOptions, + context: CliContext, + canAsk: boolean +): Promise { + const own = entry.druxt.layout + let layout = options.layout + if (!layout && canAsk) { + layout = await context.prompter.select({ + message: 'Which layout?', + choices: LAYOUTS.map((value) => ({ + value, + label: value, + ...(AVAILABLE_LAYOUTS.includes(value) + ? {} + : { hint: 'not available yet' }), + })), + initial: own, + }) + } + layout ??= own + assertLayoutAvailable(layout) + if (layout !== own) { + throw new DrxError( + 'not-available', + `The ${entry.name} starter has the ${own} layout and cannot be created as ${layout}.` + ) + } + return layout +} + +/** The directory to create, checked against what is already there. */ +function targetDirectory(cwd: string, dir: string, force: boolean): string { + const target = resolve(cwd, dir) + if (!existsSync(target)) return target + if (!statSync(target).isDirectory()) { + throw new DrxError( + 'directory-not-empty', + `${target} is a file, not a directory.` + ) + } + if (!force && readdirSync(target).length > 0) { + throw new DrxError( + 'directory-not-empty', + `${target} exists and is not empty. Choose another directory, or pass --force to write into it.` + ) + } + return target +} + +/** True when `running` is the version `needed` names, or one inside it. */ +function nodeSatisfies(running: string, needed: string): boolean { + const version = needed.replace(/^v/, '') + return running === version || running.startsWith(`${version}.`) +} + +function warnAboutStarter( + entry: StarterEntry, + target: string, + context: CliContext, + output: Output +): void { + const { requires, maintained, parts } = entry.druxt + if (!nodeSatisfies(context.nodeVersion, requires.node)) { + output.warn( + `The ${entry.name} starter needs Node ${requires.node} and this is Node ${context.nodeVersion}. Switch before you install or run the site.` + ) + } + const age = context.now().getTime() - new Date(maintained).getTime() + if (age > STALE_AFTER_DAYS * 24 * 60 * 60 * 1000) { + output.warn( + `The ${entry.name} starter was last maintained on ${maintained} and may no longer work.` + ) + } + for (const part of parts) { + if (!existsSync(join(target, part.path))) { + output.warn( + `The starter has no ${part.path}/ directory, which its registry entry names as the ${part.role} part.` + ) + } + } +} + +async function runInit( + options: InitOptions, + context: CliContext, + output: Output +): Promise { + const canAsk = context.interactive && !options.yes + if (!options.dir && !canAsk && !options.yes) { + throw new DrxError( + 'usage', + 'No directory was given and there is no terminal to ask on. Pass a directory, as in "drx init my-site", or --yes to use the default of the starter.' + ) + } + + // Everything that can fail without the network is checked before it is used. + const userConfig = await loadUserConfig(context.env) + const source = resolveSource(options.source ?? DEFAULT_SOURCE, userConfig) + assertSourceAvailable(source) + if (options.layout) assertLayoutAvailable(options.layout) + const registryUrl = options.registry + ? resolveRegistryUrl(options.registry, userConfig) + : undefined + + const registry = await openRegistry({ + ...(registryUrl ? { url: registryUrl } : {}), + defaultUrl: context.defaultRegistry, + bundledDir: context.bundledRegistryDir, + fetch: context.fetch, + ...(context.env.GIGET_AUTH ? { auth: context.env.GIGET_AUTH } : {}), + }) + if (registry.origin === 'bundled') { + output.note(`${registry.fallbackReason}`) + output.note('Reading starters from the copy bundled with this version.') + } else { + output.note(`Reading starters from ${registry.location}.`) + } + + const entry = await chooseStarter(registry, options, context, canAsk) + const layout = await chooseLayout(entry, options, context, canAsk) + + const defaultDir = entry.defaultDir ?? entry.name + const dir = + options.dir ?? + (canAsk + ? await context.prompter.text({ + message: 'Where should the site be created?', + initial: defaultDir, + }) + : defaultDir) + const target = targetDirectory(context.cwd, dir, options.force) + + const install = + options.install ?? + (canAsk + ? await context.prompter.confirm({ + message: 'Install its dependencies now?', + initial: false, + }) + : false) + + output.note(`Fetching the ${entry.name} starter from ${entry.tar}.`) + try { + await context.download(`starter:${entry.name}`, { + // The entry is already read and checked, so giget is handed it as it + // is and looks nothing up. + providers: { + starter: () => ({ + name: entry.name, + // giget keeps the archive under the name and the version, and + // unpacks the kept one when a fetch fails. The version is the + // address, so the kept archive is only ever this entry's own. + version: createHash('sha256').update(entry.tar).digest('hex'), + tar: entry.tar, + ...(entry.subdir ? { subdir: entry.subdir } : {}), + ...(entry.headers ? { headers: entry.headers } : {}), + }), + }, + registry: false, + dir: target, + // The directory was checked above, with --force taken into account. + force: true, + silent: true, + }) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'download', + `Could not fetch the ${entry.name} starter: ${detail}` + ) + } + + const config: ProjectConfig = { + layout, + line: entry.druxt.line, + starter: entry.name, + source: source.name, + parts: entry.druxt.parts, + } + await writeProjectConfig(target, config) + warnAboutStarter(entry, target, context, output) + + if (install) { + output.note('Installing dependencies.') + try { + await context.install(target) + } catch (error) { + const detail = error instanceof Error ? error.message : String(error) + throw new DrxError( + 'install', + `The site was created in ${target}, but installing its dependencies failed: ${detail}` + ) + } + } + + const fromCwd = relative(context.cwd, target) + const inside = fromCwd !== '' && !fromCwd.startsWith('..') + // A step the install ran is not left to run: running a setup twice can + // undo the first. + const ran = install ? entry.druxt.install : undefined + const shown = inside && !isAbsolute(fromCwd) ? fromCwd : target + const next = [ + // A name that starts with a hyphen is written as a path: a shell reads + // "cd -" as the previous directory, and "cd -x" as an option. + `cd ${shellQuote(shown.startsWith('-') ? `./${shown}` : shown)}`, + ...(entry.druxt.steps ?? []).filter((step) => !ran?.runs?.includes(step)), + ] + const notes = ran?.notes ?? [] + const { requires } = entry.druxt + + output.result( + { + ok: true, + directory: target, + registry: { origin: registry.origin, location: registry.location }, + ...config, + installed: install, + requires, + next, + notes, + }, + [ + `Created a Druxt site in ${target} from the ${entry.name} starter.`, + '', + 'It needs:', + ` Node ${requires.node}`, + ...requires.tools.map((tool) => ` ${tool}`), + '', + 'Next:', + ...next.map((step) => ` ${step}`), + ...(notes.length > 0 + ? ['', 'Note:', ...notes.map((note) => ` ${note}`)] + : []), + ].join('\n') + ) +} + +export function initCommand(context: CliContext) { + return defineCommand({ + meta: { + name: 'init', + description: 'Create a Druxt site from a starter', + }, + args, + async run({ args: parsed, rawArgs }) { + assertKnownOptions(rawArgs, args, 'init') + const options: InitOptions = { + force: parsed.force === true, + yes: parsed.yes === true, + } + const dir = valueOf('dir', parsed.dir) + const starter = valueOf('starter', parsed.starter) + const registry = valueOf('registry', parsed.registry) + const source = valueOf('source', parsed.source) + if (dir) options.dir = dir + if (starter) options.starter = starter + if (registry) options.registry = registry + if (source) options.source = source + if (isLayout(parsed.layout)) options.layout = parsed.layout + if (typeof parsed.install === 'boolean') options.install = parsed.install + + await runInit( + options, + context, + createOutput(context, parsed.json === true) + ) + }, + }) +} diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts new file mode 100644 index 0000000..1d4c344 --- /dev/null +++ b/packages/cli/src/context.ts @@ -0,0 +1,86 @@ +import { downloadTemplate } from 'giget' +import { installDependencies } from './install.js' +import { bundledRegistryDir } from './package-root.js' +import { terminalPrompter } from './prompts.js' +import { DEFAULT_REGISTRY } from './registry/registry.js' + +/** The part of a stream the CLI writes to. */ +export interface TextStream { + write(chunk: string): unknown + isTTY?: boolean +} + +export interface Choice { + value: T + label: string + hint?: string +} + +/** The questions a command may ask a person at the terminal. */ +export interface Prompter { + text(question: { message: string; initial?: string }): Promise + select(question: { + message: string + choices: Choice[] + initial?: T + }): Promise + confirm(question: { message: string; initial: boolean }): Promise +} + +/** The version in DRX_RELAUNCHED, when it holds one. */ +export function shellNode(value: string | undefined): string | undefined { + return value && /^\d+\.\d+\.\d+$/.test(value) ? value : undefined +} + +/** + * Everything a command takes from the process it runs in. The tests pass + * their own, so no command reads `process` directly. + */ +export interface CliContext { + cwd: string + env: Record + /** The result of a command: its text, or its JSON with `--json`. */ + stdout: TextStream + /** Progress, warnings, errors and prompts. */ + stderr: TextStream + /** True when a person is at the terminal to answer a prompt. */ + interactive: boolean + /** The running Node version, without the leading `v`. */ + nodeVersion: string + now: () => Date + fetch: typeof fetch + prompter: Prompter + /** The registry used when `--registry` is not given. */ + defaultRegistry: string + /** The copy of the registry used when the default cannot be read. */ + bundledRegistryDir: string + /** Fetches and unpacks a template. giget's `downloadTemplate`. */ + download: typeof downloadTemplate + /** Installs the dependencies of the site in a directory. */ + install: (dir: string) => Promise + /** + * Set by a binary that runs one command under a name of its own, so the + * usage of that command is headed by the name the user typed. + */ + startedAs?: { command: string; name: string } +} + +export function defaultContext(): CliContext { + return { + cwd: process.cwd(), + env: process.env, + stdout: process.stdout, + stderr: process.stderr, + interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY), + // After a relaunch on a newer Node, the Node the user's shell is on: it is + // the one a site is installed and run with. + nodeVersion: shellNode(process.env.DRX_RELAUNCHED) ?? process.versions.node, + now: () => new Date(), + fetch: globalThis.fetch, + prompter: terminalPrompter(), + defaultRegistry: DEFAULT_REGISTRY, + bundledRegistryDir: bundledRegistryDir(), + download: downloadTemplate, + install: (dir) => installDependencies(dir), + } +} diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..b6c7c57 --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,28 @@ +/** What went wrong, for a caller reading `--json` output. */ +export type DrxErrorCode = + | 'usage' + | 'not-available' + | 'registry' + | 'invalid-entry' + | 'unknown-starter' + | 'unknown-source' + | 'directory-not-empty' + | 'config' + | 'download' + | 'install' + | 'cancelled' + | 'node' + +/** + * A failure the user can act on. Its message is printed as it is, with no + * stack trace, and the process exits non-zero. + */ +export class DrxError extends Error { + readonly code: DrxErrorCode + + constructor(code: DrxErrorCode, message: string) { + super(message) + this.name = 'DrxError' + this.code = code + } +} diff --git a/packages/cli/src/find-node.ts b/packages/cli/src/find-node.ts new file mode 100644 index 0000000..9c644f0 --- /dev/null +++ b/packages/cli/src/find-node.ts @@ -0,0 +1,126 @@ +// Read by the binary on any Node, so it uses only what an old Node has. +import { spawnSync } from 'node:child_process' +import { existsSync, readdirSync, realpathSync } from 'node:fs' +import { delimiter, dirname, join } from 'node:path' +import { nodeTooOld } from './node-version.js' + +export interface NodeSearch { + env: Record + /** The path this binary was started as. */ + script: string + /** The user's home directory, where version managers keep their installs. */ + home: string + /** The path of the Node that is running, which is not worth trying again. */ + current: string + /** Directories of binaries that a system install puts Node in. */ + system?: string[] +} + +/** Where a system install, or Homebrew, puts Node. */ +const SYSTEM = ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin'] + +const NAME = process.platform === 'win32' ? 'node.exe' : 'node' + +/** The version a Node at this path reports, or undefined when it is not one. */ +function versionOf(path: string): string | undefined { + if (!existsSync(path)) return undefined + const result = spawnSync(path, ['--version'], { + encoding: 'utf8', + timeout: 5000, + stdio: ['ignore', 'pipe', 'ignore'], + }) + if (result.status !== 0 || typeof result.stdout !== 'string') return undefined + const match = /^v(\d+\.\d+\.\d+)/.exec(result.stdout.trim()) + return match ? match[1] : undefined +} + +/** The directories of a version manager's installs, the newest version first. */ +function installs(root: string, bin: string): string[] { + let names: string[] + try { + names = readdirSync(root) + } catch { + return [] + } + const numbers = (name: string) => + name + .replace(/^v/, '') + .split('.') + .map((part) => Number.parseInt(part, 10) || 0) + return names + .slice() + .sort((a, b) => { + const x = numbers(a) + const y = numbers(b) + for (let index = 0; index < 3; index++) { + const difference = (y[index] || 0) - (x[index] || 0) + if (difference !== 0) return difference + } + return 0 + }) + .map((name) => join(root, name, bin, NAME)) +} + +/** Where a newer Node may be, in the order they are tried. */ +function candidates(search: NodeSearch): string[] { + const { env, script, home } = search + const list: string[] = [] + if (env.DRX_NODE) list.push(env.DRX_NODE) + + // The Node this binary was installed with sits beside it, in the same + // directory of binaries. A version manager that switched to an older Node + // for the site has left this one in place. + list.push(join(dirname(script), NAME)) + try { + list.push(join(dirname(realpathSync(script)), NAME)) + } catch { + // The script path is not a file, as when the module is run directly. + } + + for (const dir of (env.PATH || env.Path || '').split(delimiter)) { + if (dir) list.push(join(dir, NAME)) + } + + const data = env.XDG_DATA_HOME || join(home, '.local', 'share') + list.push( + ...installs(join(data, 'mise', 'installs', 'node'), 'bin'), + ...installs( + join(env.NVM_DIR || join(home, '.nvm'), 'versions', 'node'), + 'bin' + ), + ...(env.FNM_DIR + ? installs( + join(env.FNM_DIR, 'node-versions'), + join('installation', 'bin') + ) + : []), + ...installs( + join(data, 'fnm', 'node-versions'), + join('installation', 'bin') + ), + ...installs( + join(home, '.fnm', 'node-versions'), + join('installation', 'bin') + ), + ...installs(join(home, '.volta', 'tools', 'image', 'node'), 'bin'), + ...installs(join(home, '.asdf', 'installs', 'nodejs'), 'bin'), + ...(search.system ?? SYSTEM).map((dir) => join(dir, NAME)) + ) + if (env.ProgramFiles) list.push(join(env.ProgramFiles, 'nodejs', NAME)) + return list +} + +/** + * The path of a Node on this machine that is new enough for drx, or undefined + * when there is none. + */ +export function findNewerNode(search: NodeSearch): string | undefined { + const tried = new Set([search.current]) + for (const path of candidates(search)) { + if (tried.has(path)) continue + tried.add(path) + const version = versionOf(path) + if (version && !nodeTooOld(version)) return path + } + return undefined +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 0000000..90930bb --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,11 @@ +export { runCli } from './cli.js' +export type { CliContext, Prompter } from './context.js' +export { DrxError, type DrxErrorCode } from './errors.js' +export type { KindAdapter, PackageVersion } from './adapters/index.js' +export type { Layout } from './layouts.js' +export type { Part, Role } from './parts.js' +export type { ProjectConfig } from './project.js' +export type { StarterDetails, StarterEntry } from './registry/entry.js' +export { DEFAULT_REGISTRY } from './registry/registry.js' +export type { Source, SourceDefinition } from './sources.js' +export type { UserConfig } from './user-config.js' diff --git a/packages/cli/src/install.ts b/packages/cli/src/install.ts new file mode 100644 index 0000000..221ab27 --- /dev/null +++ b/packages/cli/src/install.ts @@ -0,0 +1,54 @@ +import { spawn } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' + +const MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'] as const +type Manager = (typeof MANAGERS)[number] + +/** + * The package manager a directory declares in the `packageManager` field of + * its package.json, or npm when it declares none. Undefined when there is no + * package.json to install from. + */ +export async function packageManagerOf( + dir: string +): Promise { + let manifest: { packageManager?: unknown } + try { + manifest = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) + } catch { + return undefined + } + const declared = String(manifest.packageManager ?? '').split('@')[0] + return MANAGERS.find((manager) => manager === declared) ?? 'npm' +} + +/** + * Runs the install of the directory's package manager. Its output goes to + * stderr, so the stdout of the CLI stays the result of the command. + */ +export async function installDependencies( + dir: string, + env: NodeJS.ProcessEnv = process.env +): Promise { + const manager = await packageManagerOf(dir) + if (!manager) { + throw new Error(`${dir} has no package.json to install from`) + } + await new Promise((resolve, reject) => { + const child = spawn(manager, ['install'], { + cwd: dir, + env, + stdio: ['ignore', process.stderr, process.stderr], + shell: process.platform === 'win32', + }) + child.on('error', (error) => + reject(new Error(`${manager} install could not start: ${error.message}`)) + ) + child.on('close', (code) => + code === 0 + ? resolve() + : reject(new Error(`${manager} install exited with code ${code}`)) + ) + }) +} diff --git a/packages/cli/src/launch.ts b/packages/cli/src/launch.ts new file mode 100644 index 0000000..1cce640 --- /dev/null +++ b/packages/cli/src/launch.ts @@ -0,0 +1,122 @@ +// Read by the binary on any Node, so it uses only what an old Node has. +import { spawn, type StdioOptions } from 'node:child_process' +import { findNewerNode } from './find-node.js' +import { nodeTooOld } from './node-version.js' + +export interface Launch { + /** The version of the Node that is running. */ + node: string + argv: string[] + /** The path this binary was started as. */ + script: string + env: Record + home: string + /** The path of the Node that is running. */ + current: string + stderr: { write(text: string): unknown } + stdout: { write(text: string): unknown } + /** Runs the command on this Node. Loaded only when this Node is new enough. */ + run: (argv: string[]) => Promise + stdio?: StdioOptions + /** Directories of binaries that a system install puts Node in. */ + system?: string[] +} + +/** + * Reports a failure of the launcher itself. No command ran, so with `--json` + * the one JSON document on stdout is this error. + */ +function fail(options: Launch, message: string): number { + if (options.argv.includes('--json')) { + options.stdout.write( + `${JSON.stringify({ ok: false, error: { code: 'node', message } }, null, 2)}\n` + ) + } + options.stderr.write(`Error: ${message}\n`) + return 1 +} + +/** + * Runs a command and returns its exit code. + * + * A site can pin an older Node than drx runs on, and a version manager + * switches to it in the site's directory. On such a Node the command is run + * again on a newer Node from this machine. The tools the command starts, such + * as the site's package manager, still come from the user's own PATH. + */ +export async function launch(options: Launch): Promise { + const problem = nodeTooOld(options.node) + if (!problem) return options.run(options.argv) + + const newer = options.env.DRX_RELAUNCHED + ? undefined + : findNewerNode({ + env: options.env, + script: options.script, + home: options.home, + current: options.current, + ...(options.system ? { system: options.system } : {}), + }) + if (!newer) { + return fail( + options, + `${problem}\nNo newer Node was found on this machine. Install one, or set DRX_NODE to the path of its node binary.` + ) + } + + return new Promise((resolve) => { + const child = spawn(newer, [options.script, ...options.argv], { + stdio: options.stdio ?? 'inherit', + // The Node the user's shell is on, which is the one their site runs on. + env: { ...options.env, DRX_RELAUNCHED: options.node }, + }) + child.on('error', (error) => { + resolve( + fail( + options, + `${problem}\n${newer} could not be started: ${error.message}` + ) + ) + }) + child.on('close', (code) => resolve(code === null ? 1 : code)) + }) +} + +/** What `launchProcess` reads from the running process. */ +export interface RunningProcess { + versions: { node: string } + argv: string[] + env: Record + execPath: string + stderr: { write(text: string): unknown } + stdout: { write(text: string): unknown } +} + +/** + * Launches a binary from the process it was started in. The command is the + * named export of a module, which is loaded only on a Node that is new enough. + */ +export function launchProcess( + running: RunningProcess, + home: string, + module: string, + name: string +): Promise { + return launch({ + node: running.versions.node, + argv: running.argv.slice(2), + script: running.argv[1] ?? '', + env: running.env, + home, + current: running.execPath, + stderr: running.stderr, + stdout: running.stdout, + run: async (argv) => { + const loaded = (await import(module)) as Record< + string, + (argv: string[]) => Promise + > + return loaded[name]!(argv) + }, + }) +} diff --git a/packages/cli/src/layouts.ts b/packages/cli/src/layouts.ts new file mode 100644 index 0000000..ce61241 --- /dev/null +++ b/packages/cli/src/layouts.ts @@ -0,0 +1,24 @@ +import { DrxError } from './errors.js' + +/** + * How the parts of a site are put together: one repository, a repository per + * part, or a parent repository with each part as a submodule. + */ +export const LAYOUTS = ['monorepo', 'split', 'workspace'] as const +export type Layout = (typeof LAYOUTS)[number] + +/** The layouts `init` can create. */ +export const AVAILABLE_LAYOUTS: readonly Layout[] = ['monorepo'] + +export function isLayout(value: unknown): value is Layout { + return LAYOUTS.includes(value as Layout) +} + +export function assertLayoutAvailable(layout: Layout): void { + if (!AVAILABLE_LAYOUTS.includes(layout)) { + throw new DrxError( + 'not-available', + `The ${layout} layout is not available yet. Use --layout ${AVAILABLE_LAYOUTS.join(' or ')}.` + ) + } +} diff --git a/packages/cli/src/node-version.ts b/packages/cli/src/node-version.ts new file mode 100644 index 0000000..b8303c1 --- /dev/null +++ b/packages/cli/src/node-version.ts @@ -0,0 +1,33 @@ +// Read by the binary before anything else is loaded, so it has no imports and +// only syntax an old Node can parse. + +/** The oldest Node drx runs on. The same as `engines.node` in package.json. */ +export const MINIMUM_NODE = '22.12.0' + +function parts(version: string): number[] { + return version.split('.').map((part) => Number.parseInt(part, 10) || 0) +} + +/** + * What to tell the user when this Node is older than drx needs, or undefined + * when it is new enough. + */ +export function nodeTooOld(current: string): string | undefined { + const have = parts(current) + const need = parts(MINIMUM_NODE) + for (let index = 0; index < need.length; index++) { + const a = have[index] || 0 + const b = need[index] || 0 + if (a > b) return undefined + if (a < b) { + return ( + 'drx needs Node ' + + MINIMUM_NODE + + ' or later, and this is Node ' + + current + + '.' + ) + } + } + return undefined +} diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.ts new file mode 100644 index 0000000..0fb5a58 --- /dev/null +++ b/packages/cli/src/output.ts @@ -0,0 +1,46 @@ +import type { CliContext } from './context.js' + +/** + * Where a command writes. The result goes to stdout: text, or JSON with + * `--json`. Everything said along the way goes to stderr, so stdout can be + * piped or parsed whichever form it takes. + */ +export interface Output { + readonly json: boolean + /** Progress, on stderr. */ + note(message: string): void + /** Something the user should know that does not stop the command. */ + warn(message: string): void + /** The result, on stdout. `text` is used unless `--json` was given. */ + result(data: unknown, text: string): void +} + +export function createOutput(context: CliContext, json: boolean): Output { + return { + json, + note: (message) => context.stderr.write(`${message}\n`), + warn: (message) => context.stderr.write(`Warning: ${message}\n`), + result: (data, text) => + context.stdout.write( + json ? `${JSON.stringify(data, null, 2)}\n` : `${text}\n` + ), + } +} + +/** Lines of cells, with every column padded to its widest cell. */ +export function columns(rows: string[][], indent = ''): string[] { + const widths: number[] = [] + for (const row of rows) { + for (const [index, cell] of row.entries()) { + widths[index] = Math.max(widths[index] ?? 0, cell.length) + } + } + return rows.map( + (row) => + indent + + row + .map((cell, index) => cell.padEnd(widths[index] ?? 0)) + .join(' ') + .trimEnd() + ) +} diff --git a/packages/cli/src/package-root.ts b/packages/cli/src/package-root.ts new file mode 100644 index 0000000..d845098 --- /dev/null +++ b/packages/cli/src/package-root.ts @@ -0,0 +1,39 @@ +import { existsSync, readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * The directory of this package, found from this file. The sources sit in + * src/ and the build in dist/, at different depths, so the nearest + * package.json is the fixed point. + */ +export function packageRoot(): string { + let dir = dirname(fileURLToPath(import.meta.url)) + while (!existsSync(join(dir, 'package.json'))) { + const parent = dirname(dir) + if (parent === dir) { + throw new Error('No package.json found above the CLI sources.') + } + dir = parent + } + return dir +} + +export function cliVersion(): string { + const manifest = JSON.parse( + readFileSync(join(packageRoot(), 'package.json'), 'utf8') + ) as { version: string } + return manifest.version +} + +/** + * The registry files that ship with the package. The build copies them into + * the package. In a checkout that has not been built they are read from the + * repository root. + */ +export function bundledRegistryDir(): string { + const root = packageRoot() + const packaged = join(root, 'starters') + if (existsSync(join(packaged, 'index.json'))) return packaged + return join(root, '..', '..', 'starters') +} diff --git a/packages/cli/src/parts.ts b/packages/cli/src/parts.ts new file mode 100644 index 0000000..881c2bf --- /dev/null +++ b/packages/cli/src/parts.ts @@ -0,0 +1,50 @@ +import { isNonEmptyString, isRecord } from './validate.js' + +export const ROLES = ['frontend', 'backend'] as const +export type Role = (typeof ROLES)[number] + +/** + * One side of a site. The role says what it is for and the kind says what it + * is built with. The kind is a plain string, so a new one needs an adapter + * and no change to this type. + */ +export interface Part { + role: Role + kind: string + /** Relative to the project root, with forward slashes. */ + path: string +} + +/** True for a path that stays inside the directory it is resolved against. */ +function isInsidePath(value: unknown): value is string { + if (!isNonEmptyString(value)) return false + if (value.startsWith('/') || /^[a-z]:/i.test(value)) return false + return !value.split(/[\\/]/).includes('..') +} + +/** + * The first problem with a list of parts, as "