diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 0000000..e5b6d8d --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,8 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works +with multi-package repos, or single-package repos to help you version and publish your code. You can +find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in +[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/changelog.cjs b/.changeset/changelog.cjs new file mode 100644 index 0000000..2b4a78f --- /dev/null +++ b/.changeset/changelog.cjs @@ -0,0 +1,263 @@ +/** + * Changelog generator for @changesets/cli. + * + * Turns changeset summaries written as conventional commit subjects + * ("feat(#87): add attrs passthrough") into changelog sentences with the + * issue and commit linked ("Added attrs passthrough ([#87](…), [abc1234](…))"). + * Pure string transforms: no network, no GitHub API, works offline. + * + * Repo-agnostic: the link base comes from the root package.json repository + * field, so the same file serves every Druxt repository. + */ +const path = require('path') + +const MarkdownIt = require('markdown-it') + +const REPO = (() => { + try { + // Changesets runs from the repository root. + const pkg = require(path.join(process.cwd(), 'package.json')) + const url = + typeof pkg.repository === 'string' + ? pkg.repository + : (pkg.repository || {}).url || '' + const match = + url.match(/github\.com[/:]([\w.-]+\/[\w.-]+?)(?:\.git)?$/) || + url.match(/^github:([\w.-]+\/[\w.-]+)$/) || + // npm's bare shorthand ("owner/repo") also means GitHub. + url.match(/^([\w.-]+\/[\w.-]+)$/) + if (match) return `https://github.com/${match[1]}` + } catch { + // Fall through to the default. + } + return 'https://github.com/druxt/druxt.js' +})() + +// Leading verbs normalized to Keep a Changelog past tense. +const VERBS = { + add: 'Added', + added: 'Added', + adds: 'Added', + create: 'Added', + created: 'Added', + fix: 'Fixed', + fixed: 'Fixed', + fixes: 'Fixed', + remove: 'Removed', + removed: 'Removed', + deprecate: 'Deprecated', + deprecated: 'Deprecated', + update: 'Updated', + updated: 'Updated', + change: 'Changed', + changed: 'Changed', + refactor: 'Refactored', + refactored: 'Refactored', + improve: 'Improved', + improved: 'Improved', + simplify: 'Simplified', + simplified: 'Simplified', + prevent: 'Prevented', + prevented: 'Prevented', + allow: 'Allowed', + allowed: 'Allowed', + ensure: 'Ensured', + ensured: 'Ensured', + normalize: 'Normalized', + normalized: 'Normalized', + rename: 'Renamed', + renamed: 'Renamed', + move: 'Moved', + moved: 'Moved', + replace: 'Replaced', + replaced: 'Replaced', + disable: 'Disabled', + disabled: 'Disabled', + enable: 'Enabled', + enabled: 'Enabled', + restore: 'Restored', + restored: 'Restored', +} + +// CommonMark, so a summary is read the way it renders. +const md = new MarkdownIt('commonmark') + +// Records each `#123` the inline parser reaches as plain text, with its +// offset. It runs after every built-in rule, so autolinks, code spans, HTML, +// entities and escapes consume their own text first, and a ref inside one of +// them never gets here. A ref in the text of a Markdown link or an HTML `` +// is reached, but with `linkLevel` raised, so it is skipped. +md.inline.ruler.push('issue_ref', (state, silent) => { + const ref = /^#(\d+)\b/.exec(state.src.slice(state.pos, state.posMax)) + if (!ref) return false + if (!silent && !state.linkLevel) { + const token = state.push('issue_ref', '', 0) + token.content = ref[1] + token.meta = { start: state.pos, end: state.pos + ref[0].length } + } + state.pos += ref[0].length + return true +}) + +/** + * Where a URL linkify-it found really ends. linkify-it stops at nested + * parentheses, as in `https://example.org/a(b(c))#123`, so the URL runs on + * past them, but never past a space, a `<` or `>`, or a `)` it did not open: + * the `)` that closes a Markdown link, or the `>` that closes an autolink. + * + * @param {string} text - The text the URL was found in. + * @param {{ index: number, lastIndex: number }} url - linkify-it's match. + * @returns {number} The index after the URL's last character. + */ +const urlEnd = (text, url) => { + let depth = 0 + for (const char of text.slice(url.index, url.lastIndex)) { + if (char === '(') depth++ + else if (char === ')') depth-- + } + let end = url.lastIndex + for (; end < text.length && !/[\s<>]/.test(text[end]); end++) { + if (text[end] === '(') depth++ + else if (text[end] === ')') { + if (depth <= 0) break + depth-- + } + } + return end +} + +const linkIssues = (text, env) => { + // A bare URL, such as `https://example.org/guide#123`, is text to CommonMark, + // so its refs are found with linkify-it, which markdown-it bundles. + const urls = (md.linkify.match(text) || []).map((url) => [ + url.index, + urlEnd(text, url), + ]) + const inUrl = (start) => + urls.some(([from, to]) => from <= start && start < to) + // `[#123]` reads as a label someone meant to write. + const refs = md + .parseInline(text, env)[0] + .children.filter( + (token) => + token.type === 'issue_ref' && + text[token.meta.start - 1] !== '[' && + !inUrl(token.meta.start) + ) + let out = '' + let last = 0 + for (const ref of refs) { + out += + text.slice(last, ref.meta.start) + + `[#${ref.content}](${REPO}/issues/${ref.content})` + last = ref.meta.end + } + return out + text.slice(last) +} + +// The Conventional Commits types. Any other word before a colon, such as +// "Windows: ", is part of the sentence. +const TYPES = 'build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test' +const PREFIX = new RegExp(`^(${TYPES})(?:\\(([^)]*)\\))?(!)?:\\s*`) + +/** + * One changeset summary line to one changelog sentence. + * + * @param {string} summary - The changeset's first line. + * @param {object} [env] - The markdown-it environment the rest of the summary + * was parsed in, so a reference link defined there resolves. + * @returns {{ text: string, issues: string[], breaking: boolean }} The + * rewritten sentence plus any issue refs found in the prefix. + */ +const rewrite = (summary, env = {}) => { + let text = summary.trim() + const issues = [] + let breaking = false + + const prefix = text.match(PREFIX) + if (prefix) { + breaking = Boolean(prefix[3]) + for (const ref of (prefix[2] || '').match(/#\d+/g) || []) + issues.push(ref.slice(1)) + text = text.slice(prefix[0].length).trim() + } + + const verb = text.match(/^([A-Za-z]+)\b/) + if (verb && VERBS[verb[1].toLowerCase()]) { + text = VERBS[verb[1].toLowerCase()] + text.slice(verb[1].length) + } else { + text = text.charAt(0).toUpperCase() + text.slice(1) + } + + text = linkIssues(text, env).replace(/\.+$/, '') + '.' + return { text, issues, breaking } +} + +// A `Commit: ` line names the change when the changeset file was added later. +const COMMIT = /^ {0,3}Commit:\s*([0-9a-f]{7,40})\s*$/i +// Conventional commits also declare breakage in a footer. +const BREAKING = /^ {0,3}BREAKING[ -]CHANGE:/ + +/** + * Which lines are prose rather than code, so an example of a `Commit:` line + * or a breaking-change footer stays an example. + * + * @param {string[]} lines - The summary's lines after the first. + * @param {object} env - Collects the link reference definitions found. + * @returns {boolean[]} True for each line outside a fenced or indented code + * block or an HTML block. + */ +const proseLines = (lines, env) => { + const prose = lines.map(() => true) + for (const token of md.parse(lines.join('\n'), env)) { + if ( + ['fence', 'code_block', 'html_block'].includes(token.type) && + token.map + ) { + for (let i = token.map[0]; i < token.map[1]; i++) prose[i] = false + } + } + return prose +} + +const getReleaseLine = async (changeset) => { + const [first, ...lines] = changeset.summary.split('\n') + const env = {} + const prose = proseLines(lines, env) + const override = lines + .map((line, i) => prose[i] && COMMIT.exec(line)) + .find(Boolean) + const rest = lines.filter((line, i) => !(prose[i] && COMMIT.test(line))) + const commit = override ? override[1] : changeset.commit + const result = rewrite(first, env) + const { text, issues } = result + const breaking = + result.breaking || lines.some((line, i) => prose[i] && BREAKING.test(line)) + + const refs = issues.map((n) => `[#${n}](${REPO}/issues/${n})`) + if (commit) { + refs.push(`[\`${commit.slice(0, 7)}\`](${REPO}/commit/${commit})`) + } + + let line = `- ${breaking ? '**Breaking change.** ' : ''}${text}${refs.length ? ` (${refs.join(', ')})` : ''}` + // A paragraph of its own under the bullet. Joined straight beneath it, the + // body ran into the first paragraph and left the links in its middle. + // Only the blank lines before the body go, so an indented code block that + // opens it keeps its indent. + const body = rest + .join('\n') + .replace(/^(?:[ \t]*\n)+/, '') + .trimEnd() + if (body) line += '\n\n' + body.replace(/^(?=.)/gm, ' ') + return line +} + +const getDependencyReleaseLine = async (changesets, dependenciesUpdated) => { + if (!dependenciesUpdated.length) return '' + const list = dependenciesUpdated + .map((dep) => `${dep.name}@${dep.newVersion}`) + .join(', ') + return `- Updated dependencies: ${list}.` +} + +module.exports = { getReleaseLine, getDependencyReleaseLine, rewrite } diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000..17b8cca --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@4.0.1/schema.json", + "changelog": "./changelog.cjs", + "commit": false, + "fixed": [], + "linked": [], + "access": "public", + "baseBranch": "0.x", + "updateInternalDependencies": "patch", + "ignore": [], + "snapshot": { + "useCalculatedVersion": true, + "prereleaseTemplate": "{tag}.{datetime}" + } +} diff --git a/.cspell-project-words.txt b/.cspell-project-words.txt new file mode 100644 index 0000000..152e2e1 --- /dev/null +++ b/.cspell-project-words.txt @@ -0,0 +1,46 @@ +# Add a term here rather than switching the check off for a file. +# Words this project uses that the standard dictionaries do not carry. +actionlint +automerge +citty +clack +commitlint +consola +corepack +cspell +dbaeumer +DDEV +druxt +druxtjs +esbenp +giget +gitleaks +interruptible +knip +Ksection +Lando +lndo +markdownlint +mise +Nuxt +nvmrc +opencode +unjs +unstub +vitest +yamllint +drush +PATHEXT +alacritty +COLORTERM +truecolor +wordmark +magicast +cweagans +docroot +relock +repatch +autobuild +linkify +SARIF +gpgsign diff --git a/.cspell.json b/.cspell.json new file mode 100644 index 0000000..942f080 --- /dev/null +++ b/.cspell.json @@ -0,0 +1,24 @@ +{ + "files": ["**/*.{js,mjs,ts,json,jsonc,md,yml,yaml}"], + "language": "en,en-GB", + "dictionaryDefinitions": [ + { + "name": "project-words", + "path": "./.cspell-project-words.txt" + } + ], + "dictionaries": ["project-words", "bash", "misc", "node", "softwareTerms"], + "ignorePaths": [ + ".git/", + "node_modules/", + "**/node_modules/", + "**/dist/", + "coverage/", + "reports/", + "**/CHANGELOG.md", + "package-lock.json", + ".vale/", + "packages/cli/starters/" + ], + "useGitignore": true +} diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..6735462 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,7 @@ +#!/usr/bin/env sh +# Conventional Commits, checked before the commit exists. +# +# This repository squash-merges, so the merge request or pull request title +# becomes the commit subject too. A prose title breaks the next push to the +# target branch for everyone, not only its author. +exec npx --no -- commitlint --edit "$1" diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 0000000..032a201 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,11 @@ +#!/usr/bin/env sh +# The fast half of CI: every linter, the type check, then the unit tests. +# +# The end-to-end test is not here. It downloads a real starter over the +# network, and a hook that needs the network gets bypassed with --no-verify. +set -e +npm run --silent lint +npm run --silent typecheck +# Git sets GIT_DIR and GIT_INDEX_FILE for a hook. The tests make repositories of +# their own, and with those set their commits would land in this one. +env -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_PREFIX npm test --silent diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..e406596 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,31 @@ +--- +name: Bug report +about: Something does not work as documented +title: '' +labels: bug +assignees: '' +--- + +## What happened + +## What you expected + +## How to reproduce + +The command you ran, with its options: + +```bash + +``` + +## Versions + +Paste the output of `npx @druxt/cli info`, run inside the project if there is one. + +```text + +``` + +## Anything else + +The full output of the command, or a link to a reproduction. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..d2c86a0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest something the CLI should do +title: '' +labels: enhancement +assignees: '' +--- + +## The problem + +What are you trying to do that the CLI makes hard or impossible? + +## What you would like + +## Alternatives you have considered + +## Anything else diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..6f74451 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ + + +## What changed + +## Why + +## How it was checked + +- [ ] `npm run lint` and `npm run typecheck` pass +- [ ] `npm test` passes, and coverage did not drop +- [ ] A changeset is included, if a published package changed +- [ ] Nothing that resolves only on a private network reached a tracked file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..bb8c696 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,116 @@ +--- +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. + +on: + push: + # A release line is .x, or ..x when an old minor needs + # a patch. The pattern matches both, as * matches dots. + branches: ["*.x"] + # No branch filter on purpose. The filter matches the pull request's base, so + # a pull request stacked on another branch would run no jobs, and show no + # checks rather than failing ones. + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + runs-on: ubuntu-latest + steps: + # Actions are pinned to commit SHAs, not tags. A tag is a mutable + # reference to code that runs with this repository's credentials. + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + # The attribution and prose checks read the pull request's own + # commits, so its base has to be present. + fetch-depth: 0 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + # corepack reads the packageManager field, so the manager the lockfile was + # written by is the one that installs it, and this file never names one. + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + - run: npm run lint:js + + - run: npm run lint:format + + - run: npm run typecheck + + - run: npm run lint:md + + - run: npm run lint:cspell + + - run: npm run lint:knip + + # This repository is public. A host only the author can reach must never + # reach a tracked file. + - run: npm run lint:private + + - name: Lint commit messages + if: github.event_name == 'pull_request' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: npm run lint:commit -- --from "$BASE_SHA" --to HEAD --verbose + + # The work is the author's. No commit, pull request description or + # tracked file may credit an AI tool as author, co-author or generator. + - name: Check for AI attribution + env: + ATTRIBUTION_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + run: bash .gitlab/scripts/check-attribution.sh + + # Project voice over the markdown a change touches, its commit messages + # and the pull request description. + - name: Lint prose + env: + PROSE_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + PROSE_LINT_GLOB: "!.changeset/README.md" + run: | + bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles + bash .gitlab/scripts/lint-prose.sh + + - run: npm run lint:audit + + test: + 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 test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() + with: + name: test-results + path: reports/junit/ diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000..e3c0dc5 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,84 @@ +--- +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: 'CodeQL' + +on: + push: + # The release lines. A pattern, so a branch cut on demand is scanned too. + branches: ['*.x'] + pull_request: + schedule: + - cron: '15 5 * * 2' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: ['javascript'] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@4187e74d05793876e9989daffde9c3e66b4acd07 # v3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@4187e74d05793876e9989daffde9c3e66b4acd07 # v3 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + # - run: | + # make bootstrap + # make release + + # Code scanning refuses an upload from a private repository without + # Advanced Security, which fails this step after the analysis has run. + # There the results are kept as SARIF instead, and the next step fails + # on them. + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@4187e74d05793876e9989daffde9c3e66b4acd07 # v3 + with: + upload: ${{ github.event.repository.private && 'never' || 'always' }} + output: sarif-results + + - name: List the findings of a private repository + if: ${{ github.event.repository.private }} + run: | + jq -r '.runs[].results[] | "\(.locations[0].physicalLocation.artifactLocation.uri):\(.locations[0].physicalLocation.region.startLine) \(.ruleId): \(.message.text)"' sarif-results/*.sarif + test "$(jq -s '[.[].runs[].results[]] | length' sarif-results/*.sarif)" -eq 0 diff --git a/.github/workflows/metadata.yml b/.github/workflows/metadata.yml new file mode 100644 index 0000000..92fb5b9 --- /dev/null +++ b/.github/workflows/metadata.yml @@ -0,0 +1,73 @@ +--- +name: Metadata + +# What a check has to read from the pull request itself, not from its commits +# or its files: the title a squash merge keeps as the commit subject, and the +# description, which must credit no AI tool and is prose like any other. +# +# It is separate from ci.yml because it needs the edited activity type, and +# ci.yml must not have it. ci.yml cancels in progress, so an edit that arrived +# while its jobs ran would cancel them, and every bot that touches a +# description would start the whole set again on a commit that had passed. +# +# synchronize is in the list although a push changes neither field: a required +# check has to exist on the head commit. + +on: + # No branch filter, as in ci.yml. + pull_request: + types: [opened, reopened, synchronize, edited] + +permissions: + contents: read + +# One run per pull request. An edit that arrives while a run is going replaces +# it, because the fields that run read are no longer the ones on the pull +# request. +concurrency: + group: metadata-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + metadata: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + # The attribution and prose checks read the pull request's own + # commits, so its base has to be present. + fetch-depth: 0 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version-file: .nvmrc + cache: npm + + - run: corepack enable && corepack prepare --activate + + - run: npm ci + + # Through the environment, never written into the script: a title is + # whatever its author typed. + - name: Lint the title a squash merge would keep + env: + PR_TITLE: ${{ github.event.pull_request.title }} + run: printf '%s\n' "$PR_TITLE" | npm run --silent lint:commit + + # Here as well as in ci.yml, because only this workflow sees the + # description change. + - name: Check for AI attribution + env: + ATTRIBUTION_BASE_SHA: ${{ github.event.pull_request.base.sha }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + run: bash .gitlab/scripts/check-attribution.sh + + - name: Lint prose + env: + PROSE_BASE_SHA: ${{ github.event.pull_request.base.sha }} + MERGE_REQUEST_DESCRIPTION: ${{ github.event.pull_request.body }} + PROSE_LINT_GLOB: "!.changeset/README.md" + run: | + bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles + bash .gitlab/scripts/lint-prose.sh diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..f8ae19d --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,270 @@ +--- +# CI for the Druxt CLI. See the Druxt repository standard for what each job is +# for. +# +# GitHub Actions (.github/workflows/ci.yml) runs the same lint and test set. +# Keep the two in step: nothing on the GitHub side lints that workflow, so +# lint:yaml here runs actionlint over it in return. +# +# Secret scanning is gitleaks, not GitLab's Security/Secret-Detection template. +# That template is an Ultimate-tier feature: on a non-Ultimate instance the +# include produces no job at all, so the configuration reads as coverage while +# scanning nothing. + +stages: + - lint + - test + +workflow: + rules: + - if: $CI_PIPELINE_SOURCE == 'merge_request_event' + - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS + when: never + - if: $CI_COMMIT_BRANCH + +default: + tags: [docker] + timeout: 15m + before_script: + - 'section_start() { local n="$1" t="${2:-$1}"; printf "\e[0Ksection_start:%s:%s\r\e[0K%s\n" "$(date +%s)" "$n" "$t"; }' + - 'section_end() { printf "\e[0Ksection_end:%s:%s\r\e[0K\n" "$(date +%s)" "$1"; }' + +# Shared Node setup. `corepack prepare --activate` reads the packageManager +# field, so this block names no manager version. The cache is keyed by the +# lockfile hash: a dependency bump misses once and hits after that. +.node: + image: node:24.18.0 + interruptible: true + cache: + key: + files: + - package-lock.json + prefix: node-24.18.0 + paths: + - .npm/ + before_script: + - !reference [default, before_script] + - corepack enable + - corepack prepare --activate + - npm ci --cache .npm --prefer-offline + +# +# --- Lint --- +# + +lint:js: + extends: .node + stage: lint + script: + - section_start "eslint" "Linting sources, tests and scripts" + - npm run lint:js + - section_end "eslint" + - section_start "prettier" "Checking formatting" + - npm run lint:format + - section_end "prettier" + - section_start "typecheck" "Type checking" + - npm run typecheck + - section_end "typecheck" + +lint:md: + extends: .node + stage: lint + script: + - section_start "markdownlint" "Linting Markdown" + - npm run lint:md + - section_end "markdownlint" + +lint:cspell: + extends: .node + stage: lint + script: + - section_start "cspell" "Spell checking" + - npm run lint:cspell + - section_end "cspell" + +# This repository is public, and the registry it carries is read by every copy +# of the CLI. A host only the author can reach must never reach a tracked file. +lint:private: + extends: .node + stage: lint + script: + - section_start "private-refs" "Checking for private host references" + - npm run lint:private + - section_end "private-refs" + +lint:knip: + extends: .node + stage: lint + script: + - section_start "knip" "Checking for unused and undeclared dependencies" + - npm run lint:knip + - section_end "knip" + +# Production only. A shipped runtime dependency is what reaches a user. A +# devDependency advisory is worth knowing about and not worth blocking on. +lint:audit: + extends: .node + stage: lint + script: + - section_start "audit" "Auditing shipped dependencies" + - npm run lint:audit + - section_end "audit" + +# yamllint covers this file. actionlint covers the GitHub workflow, which +# nothing on the GitHub side lints before a push. +lint:yaml: + stage: lint + image: python:3.12-slim + interruptible: true + variables: + ACTIONLINT_VERSION: '1.7.12' + ACTIONLINT_SHA256: '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8' + script: + - section_start "yamllint" "Linting YAML" + - pip install --quiet yamllint + - yamllint .gitlab-ci.yml .github/workflows/ + - section_end "yamllint" + - section_start "actionlint" "Linting GitHub workflows" + - apt-get update -qq && apt-get install -y -qq curl > /dev/null + - curl -sSLo actionlint.tar.gz "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + - echo "${ACTIONLINT_SHA256} actionlint.tar.gz" | sha256sum -c - + - tar -xzf actionlint.tar.gz actionlint + - ./actionlint -color + - section_end "actionlint" + +# The merge request's own commits, not the whole history. This repository +# squash-merges, so a prose title becomes the commit subject and breaks the +# next push to the target branch. +lint:commit: + extends: .node + stage: lint + # Full history, so the merge base is present and no commit is cut off. + variables: + GIT_DEPTH: 0 + rules: + - if: $CI_PIPELINE_SOURCE == 'merge_request_event' + script: + - section_start "commitlint" "Validating commit messages" + # The base and the head GitLab gives the merge request, not the target + # branch fetched by name: a merge request from a fork runs in the fork, + # which may have no branch of that name. The base is an ancestor of the + # head, so the full clone holds it. A merged results pipeline checks out a + # merge commit, with the target's newer commits behind it, and names the + # source branch's own head in a variable that is empty otherwise. + - git cat-file -e "${CI_MERGE_REQUEST_DIFF_BASE_SHA}^{commit}" + - npm run lint:commit -- --from "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --to "${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:-HEAD}" --verbose + - section_end "commitlint" + +# The work is the author's. No commit, merge request description or tracked +# file may credit an AI tool as author, co-author or generator. Full history, +# because the range is the merge request's own and its base has to be present. +lint:attribution: + image: node:24.18.0 + stage: lint + interruptible: true + variables: + GIT_DEPTH: 0 + script: + - section_start "attribution" "Checking for AI attribution" + - bash .gitlab/scripts/check-attribution.sh + - section_end "attribution" + +# Project voice over the markdown a change touches, its commit messages and the +# merge request description. The changesets README is third-party text. +lint:prose: + image: node:24.18.0 + stage: lint + interruptible: true + variables: + GIT_DEPTH: 0 + PROSE_LINT_GLOB: "!.changeset/README.md" + cache: + key: vale-3.17.1 + paths: + - .vale/ + script: + - section_start "prose" "Linting prose with Vale" + - bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles + - bash .gitlab/scripts/lint-prose.sh + - section_end "prose" + +# +# --- Test --- +# + +test:unit: + extends: .node + stage: test + needs: [] + script: + - section_start "vitest" "Running unit tests" + - npm test -- --reporter=default --reporter=junit --outputFile.junit=reports/junit/junit.xml + - section_end "vitest" + artifacts: + when: always + reports: + junit: reports/junit/junit.xml + paths: + - coverage/ + expire_in: 1 week + # Puts the coverage percentage in the merge request widget. + coverage: '/All files\s*\|\s*([\d.]+)/' + +# +# --- Secret detection --- +# + +secret-detection: + stage: lint + image: alpine:3.21 + interruptible: true + dependencies: [] + variables: + # Full history. gitleaks reads the commits the clone holds, and the default + # clone holds the last 20, so a credential added and removed earlier in a + # longer push would never be read. + GIT_DEPTH: 0 + GITLEAKS_VERSION: '8.30.1' + GITLEAKS_SHA256: '551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb' + script: + - section_start "gitleaks" "Scanning for committed secrets" + - apk add --no-cache curl tar git > /dev/null + - curl -sSLo gitleaks.tar.gz "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" + - echo "${GITLEAKS_SHA256} gitleaks.tar.gz" | sha256sum -c - + - tar -xzf gitleaks.tar.gz gitleaks + - ./gitleaks detect --source . --no-banner --redact --verbose + - section_end "gitleaks" + # A scan that finds nothing looks identical to a scan that cannot find + # anything. Plant three credentials outside the repository and assert all + # three are reported, so a bad download, a config change or a widened + # allowlist fails the job. + # + # Each value is split across its own prefix so no fragment in this file + # triggers the rule it is meant to exercise: the repository scan above runs + # over this file too, and a canary that flags itself would need an ignore + # entry, which is the thing being guarded against. + # + # Fixed values, not generated ones. Detection is keyword-driven, not + # entropy-driven, so a generated credential fires only sometimes. A value + # verified once keeps firing. + # + # Invented, not copied from any vendor's documentation: gitleaks allowlists + # documentation keys, and a canary built from one would never fire. + - section_start "canary" "Checking that the scanner still detects" + - | + canary="$(mktemp -d)" + pat="gh""p_8fK2mQ7xR4tV9nB3jH6yW1sZ5cD8gL0aE4uY" + stripe="sk""_live_51aBcD2eFgH3iJkL4mNoP5qR6sTuV7wXyZ8a" + slack="xo""xb-263594753641-2529420432-J1n4h6a9pQrStUvWxYz1AbCd" + printf 'a = "%s"\nb = "%s"\nc = "%s"\n' "$pat" "$stripe" "$slack" > "$canary/canary.txt" + ./gitleaks detect --no-git --source "$canary" --no-banner --redact \ + --report-format json --report-path "$canary/report.json" || true + found=$(grep -c '"RuleID"' "$canary/report.json" || true) + rm -rf "$canary" + if [ "$found" != "3" ]; then + echo "The canary planted 3 credentials and gitleaks reported $found." + echo "The scan above proves nothing while this is true." + exit 1 + fi + echo "Canary detected 3 of 3 planted credentials." + - section_end "canary" diff --git a/.gitlab/issue_templates/Default.md b/.gitlab/issue_templates/Default.md new file mode 100644 index 0000000..c93e419 --- /dev/null +++ b/.gitlab/issue_templates/Default.md @@ -0,0 +1,19 @@ +## What happened + +## What you expected + +## How to reproduce + +The command you ran, with its options: + +```bash + +``` + +## Versions + +Paste the output of `npx @druxt/cli info`, run inside the project if there is one. + +```text + +``` diff --git a/.gitlab/merge_request_templates/Default.md b/.gitlab/merge_request_templates/Default.md new file mode 100644 index 0000000..9419241 --- /dev/null +++ b/.gitlab/merge_request_templates/Default.md @@ -0,0 +1,19 @@ + + +## What changed + +## Why + +## How it was checked + +- [ ] `npm run lint` and `npm run typecheck` pass +- [ ] `npm test` passes, and coverage did not drop +- [ ] A changeset is included, if a published package changed +- [ ] Nothing that resolves only on a private network reached a tracked file diff --git a/.gitlab/scripts/check-attribution.sh b/.gitlab/scripts/check-attribution.sh new file mode 100755 index 0000000..a322e89 --- /dev/null +++ b/.gitlab/scripts/check-attribution.sh @@ -0,0 +1,185 @@ +#!/usr/bin/env bash +# Rejects AI authorship claims in commits, the merge request description and +# tracked files. The work is the author's; a tool takes no credit for it. +# +# Usage: check-attribution.sh [--files-only] [] +# +# Commits: the range ..HEAD. Without an argument the base is read from +# ATTRIBUTION_BASE_SHA, then CI_MERGE_REQUEST_DIFF_BASE_SHA, then +# CI_COMMIT_BEFORE_SHA. With none of those only HEAD is read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# When GITLAB_API_TOKEN, CI_API_V4_URL, CI_PROJECT_ID and CI_MERGE_REQUEST_IID +# are all set the description is fetched instead, because the variable is cut +# at 2700 characters and a footer sits at the end. On a merge request pipeline +# with no description from either source the check refuses: passing over a +# description it never read is not a pass. +# +# Files: every tracked text file, whatever the range. +# +# Exit codes: 0 clean, 1 attribution found, 2 cannot run. +# +# The rejected strings are assembled from fragments below, so this file passes +# its own scan. Keep them that way. + +set -uo pipefail + +files_only=0 +base="" +for arg in "$@"; do + case "$arg" in + --files-only) files_only=1 ;; + -h|--help) sed -n '2,22p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +if ! git rev-parse --show-toplevel >/dev/null 2>&1; then + echo "[ERROR] not inside a git repository; nothing to check." >&2 + exit 2 +fi + +# Tool names that must not appear as an author, co-author or generator. +# Each is matched as a whole word, so a name inside another word, such as the +# one in "precursor", credits no tool. +tools='claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm|amp' + +# 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" +session='claude-'"session:|claude\\.ai/code/session" +address='noreply'"@anthropic\\.com" +pattern="(${trailer})|(${footer})|(${session})|(${address})" + +# grep exits 1 when nothing matches and above 1 when it could not run. Only +# the first is a clean result: a scan that failed has read nothing. +scan_failed() { + echo "[ERROR] the scan of $1 could not run (exit $2); nothing was checked." >&2 + exit 2 +} + +failures=0 +report() { + echo "[FAIL] $1" + failures=$((failures + 1)) +} + +# --- commits ----------------------------------------------------------------- + +commits_checked=0 +if [ "$files_only" -eq 0 ]; then + if [ -z "$base" ]; then + base="${ATTRIBUTION_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" + fi + if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" + fi + + # An all-zero sha is what GitHub passes as the previous commit of a first + # push, and what GitLab passes as CI_COMMIT_BEFORE_SHA for a new branch. + case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac + + if [ -n "$base" ]; then + if ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 + fi + shas="$(git rev-list "${base}..HEAD")" + else + shas="$(git rev-parse HEAD)" + fi + + for sha in $shas; do + commits_checked=$((commits_checked + 1)) + short="$(git rev-parse --short "$sha")" + # Read first, then search. In one pipeline, grep's "no match" would be the + # status of a git log that could not read the message. + message="$(git log -1 --format=%B "$sha")" + rc=$? + [ "$rc" -ne 0 ] && scan_failed "commit ${short}" "$rc" + hits="$(printf '%s\n' "$message" | grep -iE "$pattern")" + rc=$? + [ "$rc" -gt 1 ] && scan_failed "commit ${short}" "$rc" + while IFS= read -r line; do + [ -n "$line" ] && report "commit ${short}: ${line}" + done <<< "$hits" + done +fi + +# --- merge request description ----------------------------------------------- + +description_checked=0 +if [ "$files_only" -eq 0 ]; then + description="" + have_description=0 + + if [ -n "${GITLAB_API_TOKEN:-}" ] && [ -n "${CI_API_V4_URL:-}" ] \ + && [ -n "${CI_PROJECT_ID:-}" ] && [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + url="${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${CI_MERGE_REQUEST_IID}" + payload="$(curl -sSf --header "PRIVATE-TOKEN: ${GITLAB_API_TOKEN}" "$url" 2>/dev/null || true)" + if [ -n "$payload" ]; then + if command -v python3 >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | python3 -c 'import json,sys; print(json.load(sys.stdin).get("description") or "")')" && have_description=1 + elif command -v node >/dev/null 2>&1; then + description="$(printf '%s' "$payload" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>process.stdout.write(JSON.parse(d).description||""))')" && have_description=1 + fi + fi + fi + + if [ "$have_description" -eq 0 ]; then + if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$MERGE_REQUEST_DESCRIPTION" + have_description=1 + elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + description="$CI_MERGE_REQUEST_DESCRIPTION" + have_description=1 + if [ "${#description}" -ge 2700 ]; then + echo "[WARN] CI_MERGE_REQUEST_DESCRIPTION is cut at 2700 characters; set GITLAB_API_TOKEN so the full description is read." >&2 + fi + elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 + fi + fi + + if [ "$have_description" -eq 1 ]; then + description_checked=1 + hits="$(printf '%s\n' "$description" | grep -iE "$pattern")" + rc=$? + [ "$rc" -gt 1 ] && scan_failed "the merge request description" "$rc" + while IFS= read -r line; do + [ -n "$line" ] && report "merge request description: ${line}" + done <<< "$hits" + fi +fi + +# --- tracked files ----------------------------------------------------------- + +files_checked="$(git ls-files | wc -l | tr -d ' ')" +hits="$(git grep -nIiE "$pattern" -- .)" +rc=$? +[ "$rc" -gt 1 ] && scan_failed "the tracked files" "$rc" +# The index too. Before a commit, a staged line that the working copy no longer +# has is still what the commit records. In a pipeline the two are the same. +staged="$(git grep --cached -nIiE "$pattern" -- .)" +rc=$? +[ "$rc" -gt 1 ] && scan_failed "the staged files" "$rc" +while IFS= read -r line; do + [ -n "$line" ] && report "$line" +done <<< "$(printf '%s\n%s\n' "$hits" "$staged" | sort -u)" + +# --- verdict ----------------------------------------------------------------- + +scope="${files_checked} tracked files" +if [ "$files_only" -eq 0 ]; then + scope="${commits_checked} commits, $([ "$description_checked" -eq 1 ] && echo 'the merge request description' || echo 'no description'), ${scope}" +fi + +if [ "$failures" -gt 0 ]; then + echo "[FAIL] ${failures} attribution line(s) across ${scope}. The work is the author's; remove the credit." + exit 1 +fi +echo "[PASS] no AI attribution in ${scope}." diff --git a/.gitlab/scripts/install-vale.sh b/.gitlab/scripts/install-vale.sh new file mode 100755 index 0000000..10dd246 --- /dev/null +++ b/.gitlab/scripts/install-vale.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Installs a pinned Vale and the ai-tells style package, both checksum-verified. +# +# Usage: install-vale.sh [] +# +# Why not `vale sync`: it fetches whatever the package URL serves and verifies +# nothing. Here the version and its checksum move together, so a bump is a +# reviewed change rather than something that happens inside a job. +# +# Environment: +# VALE_VERSION pinned below. Overriding it requires VALE_SHA256 too, +# because the pinned checksums are for the pinned version. +# VALE_SHA256 expected checksum of the Vale archive for this platform. +# AI_TELLS_VERSION pinned below. Same rule: override both or neither. +# AI_TELLS_SHA256 expected checksum of the style package archive. +# +# Exit codes: 0 installed or already present, 1 checksum mismatch, 2 cannot run. + +set -euo pipefail + +bin_dir="${1:?usage: install-vale.sh []}" +styles_dir="${2:-}" + +pinned_vale="3.17.1" +pinned_ai_tells="1.31.0" +pinned_ai_tells_sha256="bc1267248f13e65928475c439ad7ae1bf806a20d09254c08d7d8c4a9c8b811f0" + +vale_version="${VALE_VERSION:-$pinned_vale}" +ai_tells_version="${AI_TELLS_VERSION:-$pinned_ai_tells}" + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) + asset="Linux_64-bit" + pinned_vale_sha256="db947f89f2292e6a0381a61de155f6a5f5cb4cb460ca178ea412ef605559cefd" ;; + Linux-aarch64|Linux-arm64) + asset="Linux_arm64" + pinned_vale_sha256="92d91ebf9ee69ec077379be95cd09e6710ab33d3d5bab66bb482e66ebc80dc23" ;; + Darwin-x86_64) + asset="macOS_64-bit" + pinned_vale_sha256="b37ab999dfd1414d041bd2e94ced103292d634da76f954c385bf789dc7f5f939" ;; + Darwin-arm64) + asset="macOS_arm64" + pinned_vale_sha256="80cacf85ef23f53cfdd77355ec41a6ef99aec136f15dfb3517723482f35593f9" ;; + *) + echo "Unsupported platform: $(uname -s) $(uname -m)" >&2 + exit 2 ;; +esac + +if [ "$vale_version" != "$pinned_vale" ] && [ -z "${VALE_SHA256:-}" ]; then + echo "VALE_VERSION=${vale_version} is not the pinned ${pinned_vale}; set VALE_SHA256 for it." >&2 + exit 2 +fi +if [ "$ai_tells_version" != "$pinned_ai_tells" ] && [ -z "${AI_TELLS_SHA256:-}" ]; then + echo "AI_TELLS_VERSION=${ai_tells_version} is not the pinned ${pinned_ai_tells}; set AI_TELLS_SHA256 for it." >&2 + exit 2 +fi +vale_sha256="${VALE_SHA256:-$pinned_vale_sha256}" +ai_tells_sha256="${AI_TELLS_SHA256:-$pinned_ai_tells_sha256}" + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# `sha256sum` on Linux, `shasum` on macOS. Either way the comparison is +# exact, and a mismatch removes the download so nothing later can run it. +verify() { + local file="$1" expected="$2" actual + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$file" | cut -d' ' -f1)" + else + actual="$(shasum -a 256 "$file" | cut -d' ' -f1)" + fi + if [ "$actual" != "$expected" ]; then + echo "checksum mismatch for $(basename "$file"): expected ${expected}, got ${actual}; refusing to install it." >&2 + rm -f "$file" + return 1 + fi +} + +fetch() { + curl -sSfL --retry 3 -o "$2" "$1" +} + +# --- Vale -------------------------------------------------------------------- + +if [ -x "$bin_dir/vale" ] && "$bin_dir/vale" --version 2>/dev/null | grep -q "$vale_version"; then + echo "vale ${vale_version} already installed in ${bin_dir}" +else + archive="$work/vale.tar.gz" + fetch "https://github.com/errata-ai/vale/releases/download/v${vale_version}/vale_${vale_version}_${asset}.tar.gz" "$archive" + verify "$archive" "$vale_sha256" || exit 1 + tar -xzf "$archive" -C "$work" vale + mkdir -p "$bin_dir" + install -m 0755 "$work/vale" "$bin_dir/vale" + echo "vale ${vale_version} installed in ${bin_dir}" +fi + +# --- ai-tells ---------------------------------------------------------------- + +if [ -z "$styles_dir" ]; then + exit 0 +fi + +marker="$styles_dir/ai-tells/.installed-version" +if [ -f "$marker" ] && [ "$(cat "$marker")" = "$ai_tells_version" ]; then + echo "ai-tells ${ai_tells_version} already installed in ${styles_dir}" + exit 0 +fi + +zip="$work/ai-tells.zip" +fetch "https://github.com/tbhb/vale-ai-tells/releases/download/v${ai_tells_version}/ai-tells.zip" "$zip" +verify "$zip" "$ai_tells_sha256" || exit 1 + +# The package is a zip. Not every image has unzip, and every image that runs +# this has one of the others. +if command -v unzip >/dev/null 2>&1; then + unzip -q -o "$zip" -d "$work/unpacked" +elif command -v python3 >/dev/null 2>&1; then + python3 -m zipfile -e "$zip" "$work/unpacked" +elif command -v bsdtar >/dev/null 2>&1; then + mkdir -p "$work/unpacked" && bsdtar -xf "$zip" -C "$work/unpacked" +else + echo "No unzip, python3 or bsdtar available to unpack the style package." >&2 + exit 2 +fi + +if [ ! -d "$work/unpacked/ai-tells/styles/ai-tells" ]; then + echo "The style package did not contain styles/ai-tells; its layout has changed." >&2 + exit 2 +fi +mkdir -p "$styles_dir" +rm -rf "$styles_dir/ai-tells" +cp -R "$work/unpacked/ai-tells/styles/ai-tells" "$styles_dir/ai-tells" +printf '%s\n' "$ai_tells_version" > "$marker" +echo "ai-tells ${ai_tells_version} installed in ${styles_dir}" diff --git a/.gitlab/scripts/lint-prose.sh b/.gitlab/scripts/lint-prose.sh new file mode 100755 index 0000000..de6a724 --- /dev/null +++ b/.gitlab/scripts/lint-prose.sh @@ -0,0 +1,202 @@ +#!/usr/bin/env bash +# Lints prose with Vale: the markdown a change touches, the commit messages in +# its range, and the merge request description. All three are content someone +# wrote for this repository, and the project voice applies to all of it. +# +# Usage: lint-prose.sh [--all] [] +# +# Markdown: files added or modified in ..HEAD; with --all, every tracked +# markdown file. Without an argument the base is read from PROSE_BASE_SHA, +# then CI_MERGE_REQUEST_DIFF_BASE_SHA, then CI_COMMIT_BEFORE_SHA. With none of +# those the files and message of HEAD alone are read. +# +# Description: MERGE_REQUEST_DESCRIPTION, then CI_MERGE_REQUEST_DESCRIPTION. +# A merge request pipeline with neither is refused, as check-attribution.sh +# does and for the same reason. +# +# Environment: +# VALE_BIN path to vale; PATH otherwise. See install-vale.sh. +# PROSE_LINT_GLOB passed to `vale --glob` for the repository's markdown, +# to keep fixtures and vendored prose out. Never applied +# to commit messages or the description: those are never +# fixtures. +# +# Before any input is read, an em-dash is written to a file outside the tree +# and linted. If that does not fire, the .vale.ini has no section covering the +# generated inputs and the run would pass by linting nothing, so it refuses. +# +# Exit codes: 0 clean, 1 findings, 2 cannot run. + +set -uo pipefail + +all=0 +base="" +for arg in "$@"; do + case "$arg" in + --all) all=1 ;; + -h|--help) sed -n '2,28p' "$0"; exit 0 ;; + *) base="$arg" ;; + esac +done + +root="$(git rev-parse --show-toplevel 2>/dev/null)" || { + echo "[ERROR] not inside a git repository; nothing to lint." >&2 + exit 2 +} + +# VALE_BIN, then PATH, then the repository's own .vale/bin, which is where +# install-vale.sh puts it when a repository installs it for itself. +vale="${VALE_BIN:-$(command -v vale 2>/dev/null || true)}" +if [ -z "$vale" ] && [ -x "$root/.vale/bin/vale" ]; then + vale="$root/.vale/bin/vale" +fi +if [ -z "$vale" ] || [ ! -x "$vale" ]; then + echo "[ERROR] vale is not installed. Run install-vale.sh .vale/bin .vale/styles in the repository root, or put vale on PATH." >&2 + exit 2 +fi + +ini="$root/.vale.ini" +if [ ! -f "$ini" ]; then + echo "[ERROR] no .vale.ini at ${root}; there is no project voice to apply." >&2 + exit 2 +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# --- canary ------------------------------------------------------------------ + +mkdir -p "$work/canary" +printf 'Canary text %s with a dash.\n' "$(printf '\xe2\x80\x94')" > "$work/canary/canary.md" +canary_out="$(cd "$work/canary" && "$vale" --config "$ini" --output=line canary.md 2>&1)" +canary_rc=$? +if [ "$canary_rc" -eq 0 ] || ! printf '%s' "$canary_out" | grep -q 'canary.md:'; then + echo "[ERROR] canary did not fire: .vale.ini applies no em-dash rule to files outside the tree, so commit messages and the description would be linted by nothing." >&2 + echo " Add a section such as [*.md] with BasedOnStyles = ai-tells. Vale said:" >&2 + printf '%s\n' "$canary_out" | sed 's/^/ /' >&2 + exit 2 +fi + +# --- range ------------------------------------------------------------------- + +if [ -z "$base" ]; then + base="${PROSE_BASE_SHA:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-}}" +fi +if [ -z "$base" ] && [ -n "${CI_COMMIT_BEFORE_SHA:-}" ] \ + && [ "$CI_COMMIT_BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + base="$CI_COMMIT_BEFORE_SHA" +fi +case "$base" in 0000000000000000000000000000000000000000) base="" ;; esac +if [ -n "$base" ] && ! git cat-file -e "${base}^{commit}" 2>/dev/null; then + echo "[ERROR] base ${base} is not a commit in this repository." >&2 + exit 2 +fi + +findings=0 + +# --- commit messages and the description ------------------------------------- + +inputs="$work/inputs" +mkdir -p "$inputs/commits" + +if [ -n "$base" ]; then + shas="$(git rev-list "${base}..HEAD")" +else + shas="$(git rev-parse HEAD)" +fi +commits=0 +for sha in $shas; do + commits=$((commits + 1)) + git log -1 --format=%B "$sha" > "$inputs/commits/$(git rev-parse --short "$sha").md" +done + +description_state="no description" +if [ -n "${MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_DESCRIPTION+x}" ]; then + printf '%s\n' "$CI_MERGE_REQUEST_DESCRIPTION" > "$inputs/merge-request.md" + description_state="the merge request description" +elif [ -n "${CI_MERGE_REQUEST_IID:-}" ]; then + echo "[ERROR] merge request pipeline, but the description is not available." >&2 + echo " GitLab exposes it as CI_MERGE_REQUEST_DESCRIPTION (16.0 and later); other platforms pass MERGE_REQUEST_DESCRIPTION." >&2 + exit 2 +fi + +# CodeRabbit writes its summary into the description and rewrites it on every +# review. Nobody here wrote it, and an edit to it is lost on the next review. +# Only a block closed by a marker of its own kind is dropped: after an opening +# marker with no such closing one, the rest is still linted. The block's lines +# are blanked, not removed, so Vale's line numbers match the description. A +# description edited on GitHub can end its lines in CRLF, which the markers +# would miss. +if [ -f "$inputs/merge-request.md" ]; then + awk ' + { sub(/\r$/, "") } + /^$/ && !held { + held = 1; block = $0; lines = 1 + kind = $0; sub(/^$/, "", kind) + next + } + held { block = block "\n" $0; lines++ } + held && $0 == "" { held = 0; for (i = 0; i < lines; i++) print ""; next } + !held { print } + END { if (held) print block } + ' "$inputs/merge-request.md" > "$inputs/merge-request.tmp" && mv "$inputs/merge-request.tmp" "$inputs/merge-request.md" +fi + +generated=() +for f in "$inputs"/commits/*.md "$inputs/merge-request.md"; do + [ -f "$f" ] && generated+=("${f#"$inputs"/}") +done +if [ "${#generated[@]}" -gt 0 ]; then + out="$(cd "$inputs" && "$vale" --config "$ini" --output=line "${generated[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- the repository's markdown ----------------------------------------------- + +# A read loop, and each array that can be empty expanded behind a guard: +# macOS has bash 3.2 as /bin/bash, which has no builtin that reads into an +# array and will not expand an empty one under `set -u`. +if [ "$all" -eq 1 ]; then + list=(ls-files -z -- '*.md') +elif [ -n "$base" ]; then + list=(diff -z --name-only --diff-filter=AMR "$base" HEAD -- '*.md') +else + list=(diff-tree -z --no-commit-id -r --name-only --diff-filter=AMR HEAD -- '*.md') +fi +existing=() +while IFS= read -r -d '' f; do + [ -f "$root/$f" ] && existing+=("$f") +done < <(git -C "$root" "${list[@]}") + +if [ "${#existing[@]}" -gt 0 ]; then + glob=() + if [ -n "${PROSE_LINT_GLOB:-}" ]; then + glob=(--glob="$PROSE_LINT_GLOB") + fi + out="$(cd "$root" && "$vale" --config "$ini" --output=line ${glob[@]+"${glob[@]}"} "${existing[@]}" 2>&1)" + rc=$? + if [ -n "$out" ]; then + printf '%s\n' "$out" + fi + if [ "$rc" -ne 0 ]; then + findings=$((findings + 1)) + fi +fi + +# --- verdict ----------------------------------------------------------------- + +scope="${commits} commit message(s), ${description_state}, ${#existing[@]} markdown file(s)" +if [ "$findings" -gt 0 ]; then + echo "[FAIL] prose findings across ${scope}." + exit 1 +fi +echo "[PASS] prose clean across ${scope}." diff --git a/.markdownlint-cli2.jsonc b/.markdownlint-cli2.jsonc new file mode 100644 index 0000000..9d5f5eb --- /dev/null +++ b/.markdownlint-cli2.jsonc @@ -0,0 +1,21 @@ +{ + // 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. + // MD041 is off: a changeset starts with front matter, not a heading. + "config": { + "default": true, + "MD013": false, + "MD024": { "siblings_only": true }, + "MD041": false + }, + "ignores": [ + "node_modules/**", + "**/node_modules/**", + "**/dist/**", + "coverage/**", + ".vale/**", + "**/CHANGELOG.md", + ".changeset/**" + ] +} diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..58399a0 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,14 @@ +node_modules/ +dist/ +coverage/ +reports/ +package-lock.json +CHANGELOG.md +.vale/ +packages/cli/starters/ + +# Pipeline definitions are owned by yamllint, not prettier. The two disagree on +# comment spacing, and letting both format these files means each run of one +# undoes the other. +.gitlab-ci.yml +.github/workflows/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..0b5f863 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,23 @@ +{ + "printWidth": 80, + "semi": false, + "singleQuote": true, + "trailingComma": "es5", + "tabWidth": 2, + "overrides": [ + { + "files": ["*.jsonc", "tsconfig*.json"], + "options": { + "parser": "jsonc", + "trailingComma": "none" + } + }, + { + "files": ["*.md"], + "options": { + "printWidth": 100, + "proseWrap": "preserve" + } + } + ] +} diff --git a/.vale.ini b/.vale.ini new file mode 100644 index 0000000..b6c5662 --- /dev/null +++ b/.vale.ini @@ -0,0 +1,11 @@ +# Project voice for everything written here: markdown, commit messages and +# merge request descriptions. .gitlab/scripts/lint-prose.sh feeds all three +# through this configuration. +# +# StylesPath is populated by .gitlab/scripts/install-vale.sh, pinned and +# verified by checksum, not by `vale sync`. +StylesPath = .vale/styles +MinAlertLevel = error + +[*.md] +BasedOnStyles = ai-tells diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..cc245ab --- /dev/null +++ b/.yamllint @@ -0,0 +1,10 @@ +--- +extends: default +rules: + # 200, not 80: pipeline scripts carry long commands, and wrapping them makes + # them harder to read rather than easier. + line-length: + max: 200 + level: warning + truthy: + check-keys: false diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c4a1b71 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,60 @@ +# Agent instructions + +The Druxt command-line tool: `@druxt/cli`, with the binary `drx`, and `create-druxt`. + +## Rules + +- **This repository is public.** Nothing that resolves only on a private + network may reach a tracked file: no internal URLs, hostnames, repository + names or issue links, in any file including comments and the starter + 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. +- **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. +- **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 + `npm run lint:attribution` and the pipeline check the rest. +- **Prose is linted with Vale.** It covers the markdown a change touches, its + commit messages and the merge request description. + `npm run lint:prose:install` once, then `npm run lint:prose`. +- **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. + +## 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 | + +## 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 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 +`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 +`www.example.org` for a URL, and an issue number in one would be linked. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..3f07d74 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# Claude Code + +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..adaab14 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,69 @@ +# Contributing + +Thanks for helping. + +## Getting set up + +```bash +npm install +``` + +That installs dependencies and enables the git hooks. If you skipped install +scripts, run `npm run hooks:install` by hand, or the hooks stay on disk doing +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. + +## Before you push + +```bash +npm run lint # every check except prose, which needs Vale installed +npm run typecheck +npm test # vitest, with coverage reported +``` + +The pre-commit hook runs all three. The tests run offline. + +## Tests + +Write the test before the code it covers, and see it fail. The tests of the +repository's own tooling are in `test/`. + +`npm test` reports coverage and does not enforce a floor yet. + +## Changesets + +A change that a user of `@druxt/cli` or `create-druxt` would notice needs a +changeset. Run `npm run changeset`, pick the packages and the bump, and write +one or two plain sentences about the change. Commit the file it writes in +`.changeset/` with your change. + +The release turns the changesets into each package's `CHANGELOG.md`, so do not +edit those files by hand. The first line of a changeset becomes the entry: + +- A Conventional Commits prefix is dropped. An issue in its scope, as in + `fix(#12):`, is linked, and a `!` marks the entry as a breaking change. +- A leading verb is put in the past tense, so "add" reads "Added". +- `#12` in the sentence links the issue. +- The commit that added the changeset is linked. A line reading + `Commit: ` in the body names a different one. + +The rest of the changeset follows as a paragraph of its own. + +## Commit messages + +[Conventional Commits](https://www.conventionalcommits.org). The commit-msg +hook checks them, and the pipeline checks the whole merge-request range. + +This repository squash-merges, so the pull request or merge request **title** +becomes the commit subject. Title your pull request the same way you would +title a commit. + +## What not to put in a file + +This repository is public. Nothing that only resolves on a private network may +reach a tracked file, whether as a URL, in a comment or in the starter +registry. `npm run lint:private` checks this and runs in the pipeline. When you +need to cite something internal, describe it without the URL or point at a +public equivalent. diff --git a/commitlint.config.mjs b/commitlint.config.mjs new file mode 100644 index 0000000..cebf70f --- /dev/null +++ b/commitlint.config.mjs @@ -0,0 +1,47 @@ +// Conventional Commits, unmodified, plus one project rule. +// +// The type list is deliberately the stock one. A repository-specific vocabulary +// means a contributor who has worked on another Druxt repository guesses wrong, +// and the value of the convention is that it is the same everywhere. +// +// no-ai-attribution: the work is the author's. A co-author trailer naming a +// coding assistant, a generated-with footer or a session link hands ownership +// to a tool. .gitlab/scripts/check-attribution.sh runs the same check over the +// merge request range and every tracked file in CI; this is the local half, +// run by the commit-msg hook. The pattern is assembled from pieces so that this +// file passes its own scan. +const tools = + 'claude|anthropic|copilot|chatgpt|openai|gemini|codex|cursor|aider|devin|windsurf|opencode|glm|amp' +const attribution = new RegExp( + [ + // Whole words only: a name inside another word, such as the one in "precursor", credits no tool. + '(co-authored|assisted)' + `-by:.*\\b(${tools})\\b`, + `generated (with|by).*\\b(${tools}|ai)\\b`, + 'claude-' + 'session:', + 'claude\\.ai/code/session', + 'noreply' + '@anthropic\\.com', + ].join('|'), + 'i' +) + +export default { + extends: ['@commitlint/config-conventional'], + plugins: [ + { + rules: { + 'no-ai-attribution': ({ raw }) => { + const hit = raw.match(attribution) + return [ + !hit, + hit + ? `AI attribution is not allowed: "${hit[0].trim()}". The work is the author's.` + : '', + ] + }, + }, + }, + ], + rules: { + 'no-ai-attribution': [2, 'always'], + }, +} diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000..ef18462 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,33 @@ +import js from '@eslint/js' +import prettier from 'eslint-config-prettier' +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { + ignores: [ + '**/dist/**', + '**/node_modules/**', + 'coverage/**', + 'reports/**', + '.vale/**', + 'packages/cli/starters/**', + ], + }, + js.configs.recommended, + ...tseslint.configs.recommended, + prettier, + { + languageOptions: { + ecmaVersion: 2023, + sourceType: 'module', + globals: globals.node, + }, + }, + { + // The changelog generator: changesets loads it as CommonJS. + files: ['**/*.cjs'], + languageOptions: { sourceType: 'commonjs' }, + rules: { '@typescript-eslint/no-require-imports': 'off' }, + } +) diff --git a/knip.jsonc b/knip.jsonc new file mode 100644 index 0000000..2a2c97d --- /dev/null +++ b/knip.jsonc @@ -0,0 +1,13 @@ +{ + "$schema": "https://unpkg.com/knip@6/schema.json", + "workspaces": { + ".": { + "entry": ["scripts/*.mjs", "test/**/*.test.ts"], + "project": ["scripts/**/*.mjs", "test/**/*.ts"] + }, + "packages/*": { + "entry": ["src/index.ts", "src/bin.ts", "test/**/*.test.ts"], + "project": ["src/**/*.ts", "test/**/*.ts"] + } + } +} diff --git a/package-lock.json b/package-lock.json index 7f2edd2..40e5409 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "eslint-config-prettier": "10.1.8", "globals": "17.14.0", "knip": "6.45.1", + "markdown-it": "14.3.3", "markdownlint-cli2": "0.24.1", "prettier": "3.10.1", "typescript": "6.0.3", @@ -3956,13 +3957,13 @@ "license": "MIT" }, "node_modules/entities": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", - "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", "dev": true, "license": "BSD-2-Clause", "engines": { - "node": ">=20.19.0" + "node": ">=0.12" }, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" @@ -5324,9 +5325,9 @@ "license": "MIT" }, "node_modules/linkify-it": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", - "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.2.tgz", + "integrity": "sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==", "dev": true, "funding": [ { @@ -5340,7 +5341,7 @@ ], "license": "MIT", "dependencies": { - "uc.micro": "^3.0.0" + "uc.micro": "^2.0.0" } }, "node_modules/locate-path": { @@ -5382,9 +5383,9 @@ } }, "node_modules/markdown-it": { - "version": "15.0.3", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", - "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", + "version": "14.3.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.3.3.tgz", + "integrity": "sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==", "dev": true, "funding": [ { @@ -5398,34 +5399,17 @@ ], "license": "MIT", "dependencies": { - "argparse": "^3.0.3", - "entities": "^8.1.0", - "linkify-it": "^6.1.0", - "mdurl": "^2.1.0", + "argparse": "^2.0.1", + "entities": "^4.5.0", + "linkify-it": "^5.0.2", + "mdurl": "^2.0.0", "punycode.js": "^2.3.1", - "uc.micro": "^3.0.0" + "uc.micro": "^2.1.0" }, "bin": { "markdown-it": "bin/markdown-it.mjs" } }, - "node_modules/markdown-it/node_modules/argparse": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", - "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/puzrin" - }, - { - "type": "github", - "url": "https://github.com/sponsors/nodeca" - } - ], - "license": "PSF-2.0" - }, "node_modules/markdownlint": { "version": "0.42.1", "resolved": "https://registry.npmjs.org/markdownlint/-/markdownlint-0.42.1.tgz", @@ -5508,6 +5492,19 @@ ], "license": "PSF-2.0" }, + "node_modules/markdownlint-cli2/node_modules/entities": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", + "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/markdownlint-cli2/node_modules/js-yaml": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", @@ -5531,6 +5528,61 @@ "js-yaml": "bin/js-yaml.mjs" } }, + "node_modules/markdownlint-cli2/node_modules/linkify-it": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-6.1.0.tgz", + "integrity": "sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "uc.micro": "^3.0.0" + } + }, + "node_modules/markdownlint-cli2/node_modules/markdown-it": { + "version": "15.0.3", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz", + "integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/markdown-it" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^3.0.3", + "entities": "^8.1.0", + "linkify-it": "^6.1.0", + "mdurl": "^2.1.0", + "punycode.js": "^2.3.1", + "uc.micro": "^3.0.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdownlint-cli2/node_modules/uc.micro": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", + "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "dev": true, + "license": "MIT" + }, "node_modules/mdurl": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.1.0.tgz", @@ -6924,9 +6976,9 @@ } }, "node_modules/uc.micro": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-3.0.0.tgz", - "integrity": "sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", "dev": true, "license": "MIT" }, diff --git a/package.json b/package.json index acf5140..7df1050 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,10 @@ "private": true, "description": "Workspace for @druxt/cli, the Druxt command-line tool, and create-druxt.", "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/druxt/cli.git" + }, "type": "module", "workspaces": [ "packages/cli", @@ -27,6 +31,8 @@ "lint:prose": "PROSE_LINT_GLOB='!.changeset/README.md' bash .gitlab/scripts/lint-prose.sh --all", "lint:prose:install": "bash .gitlab/scripts/install-vale.sh .vale/bin .vale/styles", "postinstall": "node scripts/postinstall.mjs", + "release:check": "node scripts/release-check.mjs packages/cli packages/create-druxt", + "release:version": "changeset version && npm install --package-lock-only --ignore-scripts --no-audit --no-fund", "test": "vitest run --coverage", "test:e2e": "DRX_E2E=1 vitest run packages/cli/test/e2e", "typecheck": "tsc --noEmit" @@ -47,6 +53,7 @@ "eslint-config-prettier": "10.1.8", "globals": "17.14.0", "knip": "6.45.1", + "markdown-it": "14.3.3", "markdownlint-cli2": "0.24.1", "prettier": "3.10.1", "typescript": "6.0.3", diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..4be9e84 --- /dev/null +++ b/renovate.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:recommended"], + "baseBranches": ["0.x"], + "automerge": false, + "rangeStrategy": "bump", + "dependencyDashboard": true, + "branchPrefix": "deps/", + "labels": ["dependencies"], + "enabledManagers": ["github-actions", "npm"], + "packageRules": [ + { + "description": "Pin GitHub Actions to commit SHAs. A tag is a mutable reference to code that runs with repository credentials. npm packages already carry integrity hashes in the lockfile.", + "matchManagers": ["github-actions"], + "pinDigests": true + }, + { + "description": "Held on purpose. c12 4 is a release candidate, and typescript-eslint does not support TypeScript 7 yet. Bump each by hand when that changes.", + "matchManagers": ["npm"], + "matchPackageNames": ["c12", "typescript"], + "enabled": false + }, + { + "description": "Majors need a person. An automated major lands a breaking change on a branch nobody chose to upgrade.", + "matchManagers": ["npm", "github-actions"], + "matchUpdateTypes": ["major"], + "enabled": false + }, + { + "description": "One pull request for everything else. Ungrouped updates produce a pull request per dependency and the whole set gets ignored together.", + "matchPackageNames": ["*"], + "groupName": "all dependencies", + "groupSlug": "all" + } + ] +} diff --git a/scripts/lint-private-refs.mjs b/scripts/lint-private-refs.mjs new file mode 100644 index 0000000..6cd9c20 --- /dev/null +++ b/scripts/lint-private-refs.mjs @@ -0,0 +1,185 @@ +/** + * Fail if a tracked file points at a host only the author can reach. + * + * This repository is public, and the starter registry it carries is read by + * every copy of the CLI, so a private URL here reaches everyone who runs it. + * + * The rule is the shape of the host, not a list of known hostnames - + * anything resolvable only inside a LAN. localhost, loopback and the + * DDEV and Lando development domains are how a site runs locally, so + * they are the exceptions. + * + * Known gap: this matches host shape, so it catches `scheme://host/...` + * and scp-style git remotes. It cannot catch an internal project or + * repository name written as prose, which has no shape to match. A + * green run here is not a statement about that class. + */ + +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') + +/** Development hosts that are meant to be here. */ +const ALLOWED = [ + /^localhost$/i, + /^127\./, + /^::1$/, + /\.ddev\.site$/i, + /\.lndo\.site$/i, +] + +/** Hosts nobody outside the author's network can resolve. */ +const PRIVATE_HOST = [ + // With or without labels before it: `http://intranet/` is a private name too. + /^([a-z0-9-]+\.)*(local|internal|lan|home|corp|intranet)$/i, + /^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, + /^192\.168\.\d{1,3}\.\d{1,3}$/, + /^172\.(1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}$/, + // Link-local, as fe80::/10 is below. + /^169\.254\.\d{1,3}\.\d{1,3}$/, + /^f[cd][0-9a-f]{2}:/i, + /^fe[89ab][0-9a-f]:/i, +] + +/** + * Scheme, then the authority's host. + * + * Userinfo has to be stepped over rather than captured, because a git + * remote usually carries it - `https://oauth2:TOKEN@host/path` - and + * capturing `oauth2` instead of the host let the whole URL through. + */ +// The bracket class takes dots as well as hex: an IPv4-mapped literal such as +// [::ffff:10.0.0.8] is a bracketed host that carries an RFC1918 address. +// A scheme is read in any case, as a URL parser reads it. +const URL_HOST = + /(?:[a-z][a-z0-9+.-]*:\/\/(?:[^/@\s]*@)?|\bgit@)(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]+)/gi + +/** + * The IPv4 address inside an IPv4-mapped IPv6 literal, else the host as given. + * + * A mapped address has four spellings, compressed or expanded, with the last + * 32 bits written as dotted decimal or as two hex groups. Matching the dotted + * spelling alone let `[0:0:0:0:0:ffff:0a00:0008]` name a private endpoint that + * every pattern below then read as a public one. + */ +export function mappedToIpv4(host) { + if (!/^[0-9a-f:.]+$/i.test(host) || !host.includes(':')) return host + + // A trailing dotted quad occupies the last two groups. Rewriting it as hex + // first means the zero-fill below only ever counts groups. + const text = host.replace( + /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/, + (_, a, b, c, d) => + [((+a << 8) | +b).toString(16), ((+c << 8) | +d).toString(16)].join(':') + ) + + const [head, tail] = text.split('::') + const left = head ? head.split(':') : [] + const right = tail === undefined ? [] : tail ? tail.split(':') : [] + // `::` stands for at least one group, so more than seven beside it is not an + // address, and there is nothing to fill. + if (tail !== undefined && left.length + right.length > 7) return host + const groups = + tail === undefined + ? left + : left.concat(Array(8 - left.length - right.length).fill('0'), right) + + if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/i.test(g))) { + return host + } + const value = groups.map((g) => parseInt(g, 16)) + if (!value.slice(0, 5).every((g) => g === 0) || value[5] !== 0xffff) { + return host + } + return [value[6] >> 8, value[6] & 0xff, value[7] >> 8, value[7] & 0xff].join( + '.' + ) +} + +/** Every private host referenced by `text`, with the line it sits on. */ +export function findPrivateRefs(text) { + const found = [] + text.split('\n').forEach((line, index) => { + for (const match of line.matchAll(URL_HOST)) { + const host = mappedToIpv4( + match[1].replace(/^\[|\]$/g, '').replace(/[.:]+$/, '') + ) + if (ALLOWED.some((pattern) => pattern.test(host))) { + continue + } + if (PRIVATE_HOST.some((pattern) => pattern.test(host))) { + found.push({ line: index + 1, host }) + } + } + }) + return found +} + +/** Tracked files, which is the set that actually gets published. */ +export function trackedFiles(root = ROOT) { + return execFileSync('git', ['-C', root, 'ls-files', '-z'], { + encoding: 'utf8', + }) + .split('\0') + .filter(Boolean) +} + +/** + * The rule's own source and test state private hosts on purpose - the + * patterns here, the examples there. Nothing else gets an exemption: + * an opt-out marker anyone could paste would eventually be pasted over + * a real leak. + */ +const SELF = ['scripts/lint-private-refs.mjs', 'test/private-refs.test.ts'] + +export function lintPrivateRefs(root = ROOT) { + const problems = [] + for (const file of trackedFiles(root)) { + if (SELF.includes(file)) { + continue + } + const absolute = path.join(root, file) + let text + try { + text = fs.readFileSync(absolute, 'utf8') + } catch { + continue + } + if (text.includes('\0')) { + continue + } + for (const hit of findPrivateRefs(text)) { + problems.push(`${file}:${hit.line}: ${hit.host}`) + } + } + return problems +} + +export function main(root = ROOT) { + const problems = lintPrivateRefs(root) + if (problems.length > 0) { + console.error( + [ + '', + 'These tracked files reference a host that only resolves on a private network:', + '', + ...problems.map((problem) => ` ${problem}`), + '', + 'This repository is public. Replace the reference with a public one,', + 'or describe the thing without a URL.', + '', + ].join('\n') + ) + process.exit(1) + } + console.log('No private hosts referenced by tracked files.') +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + // An explicit root keeps the tests honest: they run the real command + // against a throwaway repository rather than this one. + main(process.argv[2] ? path.resolve(process.argv[2]) : ROOT) +} diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs new file mode 100644 index 0000000..4d184ba --- /dev/null +++ b/scripts/postinstall.mjs @@ -0,0 +1,49 @@ +/** + * Point git at the committed hooks directory. + * + * The hooks live in .githooks/ and are activated with + * `git config core.hooksPath`, which is a per-clone setting rather than + * something the repository carries. Without this step a fresh clone has the + * hooks on disk and none of them running, which is worse than having no hooks + * at all: the repository looks protected and is not. + * + * A committed directory, not husky: it is the same in every Druxt repository, + * including the ones with no package.json, and costs no dependency. + * + * Quiet on failure. A CI install runs this too, and there is nothing to gain + * from failing an install because a hook could not be configured in a + * container that will never make a commit. + */ + +import { execFileSync } from 'node:child_process' +import { realpathSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +const root = realpathSync(fileURLToPath(new URL('..', import.meta.url))) + +let top +try { + top = execFileSync('git', ['rev-parse', '--show-toplevel'], { + cwd: root, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + }).trim() +} catch { + // Not a git checkout: a published tarball, or a vendored copy. Nothing to do. + process.exit(0) +} + +// A vendored copy inside another checkout finds that checkout's repository. +// Its hooks are not this package's to change. +if (realpathSync(top) !== root) process.exit(0) + +try { + execFileSync('git', ['config', 'core.hooksPath', '.githooks'], { + cwd: root, + stdio: 'ignore', + }) + console.log('Git hooks enabled from .githooks/') +} catch (error) { + console.warn(`Could not enable git hooks: ${error.message}`) + console.warn('Run `npm run hooks:install` by hand if you intend to commit.') +} diff --git a/scripts/release-check.mjs b/scripts/release-check.mjs new file mode 100644 index 0000000..885cebc --- /dev/null +++ b/scripts/release-check.mjs @@ -0,0 +1,393 @@ +/** + * Pre-publish gate: refuse a release that would publish a broken package. + * The release workflow runs it after versioning and building, before any + * publish. + * + * node scripts/release-check.mjs [...] [--offline] + * [--skip-files] [--unpublished] [--dist-tag] + * [--registry=] + * + * Each directory holds one package. Without one, the repository root is the + * package. A workspace names its packages, as `npm run release:check` does. + * + * --offline skip the npm registry comparison. + * --skip-files skip the built-files check, for when no build has run. + * --registry= read the published versions from this registry, not npm's. + * --unpublished print `name@version` when npm does not have this version + * yet, and check nothing. + * --dist-tag print the npm dist-tag a stable publish of this version takes, + * and check nothing. + * + * It checks three things. A dependency specifier such as `link:`, + * `workspace:` or a path resolves on the author's machine and nowhere else. + * A version at or below the published one either fails to publish or, as a + * snapshot, sorts below the release it was cut after. And a build that emits + * nothing, or part of what it should, still exits zero, so a `files` entry + * has to exist and hold something, and every entry point the manifest + * declares has to be among the files npm would pack. + */ + +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import http from 'node:http' +import https from 'node:https' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const FIELDS = ['dependencies', 'peerDependencies', 'optionalDependencies'] +const UNPUBLISHABLE = + /^(workspace|link|file|portal|git|git\+ssh|git\+https|github|https?):/ +// What npm reads as a file or a directory with no `file:` in front: a spec +// that starts with a dot, `~/`, a slash of either kind or a drive letter, or +// that names a tarball. The Windows forms count wherever this runs, because +// the manifest may have been written there. +const LOCAL_PATH = /^(?:\.|~\/|[/\\]|[a-zA-Z]:)|\.(?:tgz|tar\.gz|tar)$/i +const REGISTRY = 'https://registry.npmjs.org' +const REGISTRY_TIMEOUT = 15000 +const VERSION = /^(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?$/ + +/** + * Splits a version into its numeric core and whether it is a prerelease. + * + * @param {string} version - The version to parse. + * @returns {object|null} `{ core, prerelease }`, or `null` when it is invalid. + */ +export function parseVersion(version) { + const match = VERSION.exec(version) + if (!match) return null + return { + core: match.slice(1, 4).map(Number), + prerelease: Boolean(match[4]), + } +} + +// Compares two numeric cores: negative, zero or positive, as a sort would. +const compareCores = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2] + +// The highest published stable release with the given major, or `null` when the +// major has none. Prereleases are left out on purpose. A dev snapshot has the +// core of the release it is cut towards, so it shares that core with every +// snapshot before it, and a prerelease bar would refuse all but the first. +const highestStableOfMajor = (versions, major) => + versions + .map((version) => ({ version, ...parseVersion(version) })) + .filter(({ core, prerelease }) => core && !prerelease && core[0] === major) + .reduce( + (top, next) => + !top || compareCores(next.core, top.core) > 0 ? next : top, + null + ) + +/** + * Picks the npm dist-tag for a stable publish. npm moves `latest` to whatever + * it publishes without a tag, and refuses to when the version is a prerelease + * or lower than `latest`, so those take a tag of their own. + * + * @param {string} version - The version to publish. + * @param {object|null} record - `{ latest, versions }` from npm, or `null` when unpublished. + * @returns {string} `next` for a prerelease, `latest-` below `latest`, else `latest`. + */ +export function distTag(version, record) { + const parsed = parseVersion(version) + if (parsed.prerelease) return 'next' + const latest = record && parseVersion(record.latest) + if (latest && compareCores(parsed.core, latest.core) < 0) { + return `latest-${parsed.core[0]}` + } + return 'latest' +} + +/** + * Every file the manifest names as a way into the package, with the key it + * is named under. A pattern such as `./dist/*` names no one file, so it is + * left out. + * + * @param {object} manifest - The parsed package.json. + * @returns {Array<{ key: string, file: string }>} The entry points. + */ +export function entryPoints(manifest) { + const found = [] + const walk = (key, value) => { + if (typeof value === 'string') { + if (!value.includes('*')) found.push({ key, file: value }) + } else if (Array.isArray(value)) { + value.forEach((item) => walk(key, item)) + } else if (value && typeof value === 'object') { + for (const [name, item] of Object.entries(value)) { + // A subpath or a path-like bin name reads better in brackets. + walk( + /^[\w$]+$/.test(name) ? `${key}.${name}` : `${key}["${name}"]`, + item + ) + } + } + } + for (const key of ['bin', 'main', 'module', 'types', 'typings', 'exports']) { + walk(key, manifest[key]) + } + return found +} + +/** + * The files npm would put in the tarball, as paths from the package root. + * `npm pack --dry-run` reads the package directory and writes nothing. + * + * @param {string} dir - The package directory. + * @returns {string[]} The packed paths. + */ +export function packedFiles(dir) { + const out = execFileSync( + 'npm', + ['pack', '--dry-run', '--json', '--ignore-scripts'], + { + cwd: dir, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + shell: process.platform === 'win32', + } + ) + return JSON.parse(out)[0].files.map((file) => file.path) +} + +/** + * Checks a manifest against the rules. + * + * @param {object} options - The check input. + * @param {object} options.manifest - The parsed package.json. + * @param {string} options.dir - The package directory. + * @param {object|null} [options.record] - `{ latest, versions }` from npm, or `null` when unpublished. Omit to skip the registry rule. + * @param {boolean} [options.files] - Whether to check the `files` entries. + * @returns {string[]} One message per problem. + */ +export function checkManifest({ manifest, dir, record, files = true }) { + const problems = [] + const parsed = parseVersion(manifest.version) + + if (!parsed) { + return [`"${manifest.version}" is not a valid version.`] + } + + for (const field of FIELDS) { + for (const [dep, range] of Object.entries(manifest[field] || {})) { + if (UNPUBLISHABLE.test(range) || LOCAL_PATH.test(range)) { + problems.push( + `${field}.${dep} is "${range}", which does not resolve from npm.` + ) + } + } + } + + if (record && !record.versions.includes(manifest.version)) { + const top = highestStableOfMajor(record.versions, parsed.core[0]) + if (top && compareCores(parsed.core, top.core) <= 0) { + problems.push( + `${manifest.version} does not rise above the published ${top.version}.` + ) + } + } + + if (files) { + // Without a list npm packs the whole directory, and nothing here could + // say whether the build output is in it. + if (!Array.isArray(manifest.files) || manifest.files.length === 0) { + problems.push('package.json has no "files" list to check the build by.') + } + for (const entry of manifest.files || []) { + const target = path.join(dir, entry) + if (!fs.existsSync(target)) { + problems.push(`files entry "${entry}" does not exist. Build first.`) + } else if ( + fs.statSync(target).isDirectory() && + fs.readdirSync(target).length === 0 + ) { + problems.push(`files entry "${entry}" is empty.`) + } + } + + // A directory that holds something can still lack the one file a `bin` + // or an `exports` condition points at. + const declared = entryPoints(manifest) + if (declared.length) { + let packed + try { + packed = new Set(packedFiles(dir)) + } catch (error) { + problems.push( + `npm could not list the files it would pack: ${error.message.trim()}` + ) + } + for (const { key, file } of packed ? declared : []) { + if (!packed.has(path.posix.normalize(file.replace(/\\/g, '/')))) { + problems.push( + `${key} is "${file}", which is not among the files npm would pack.` + ) + } + } + } + } + + return problems +} + +/** + * Fetches the published versions of a package. + * + * @param {string} name - The package name. + * @param {string} [registry] - The registry to ask, npm's own by default. + * @returns {Promise} `{ latest, versions }`, or `null` when npm has no such package. + */ +export function fetchRecord(name, registry = REGISTRY) { + const url = `${registry.replace(/\/$/, '')}/${name.replace(/\//g, '%2f')}` + const client = url.startsWith('http:') ? http : https + const headers = { accept: 'application/vnd.npm.install-v1+json' } + + return new Promise((resolve, reject) => { + const request = client.get( + url, + { headers, timeout: REGISTRY_TIMEOUT }, + (response) => { + if (response.statusCode === 404) { + response.resume() + return resolve(null) + } + if (response.statusCode !== 200) { + response.resume() + return reject( + new Error(`npm answered ${response.statusCode} for ${name}.`) + ) + } + + let body = '' + response.setEncoding('utf8') + response.on('data', (chunk) => { + body += chunk + }) + // A connection that closes part way through the body ends the + // response with no `end`, and with no error unless something listens + // for one. Left alone, the promise never settles and the process + // exits 0 having checked nothing. + const incomplete = () => + reject( + new Error( + `npm closed the connection before its answer for ${name} was complete.` + ) + ) + response.on('error', incomplete) + response.on('close', () => { + if (!response.complete) incomplete() + }) + response.on('end', () => { + const data = JSON.parse(body) + resolve({ + latest: data['dist-tags'].latest, + versions: Object.keys(data.versions), + }) + }) + } + ) + + // Without this a stalled connection holds the job until its own timeout. + request.on('timeout', () => + request.destroy( + new Error(`npm did not answer for ${name} within 15 seconds.`) + ) + ) + request.on('error', reject) + }) +} + +/** + * Runs one package through the options given. + * + * @param {string} dir - The package directory. + * @param {string[]} options - The flags from the command line. + * @returns {Promise} A `{ name, problem }` per problem. + */ +async function checkPackage(dir, options) { + const manifest = JSON.parse( + fs.readFileSync(path.join(dir, 'package.json'), 'utf8') + ) + if (manifest.private) { + console.log('release-check: the package is private, nothing to publish.') + return [] + } + + // A recorded registry answer, so the tests never depend on the network. + const recorded = options.find((arg) => arg.startsWith('--registry-file=')) + let record + if (recorded) { + record = JSON.parse(fs.readFileSync(recorded.split('=')[1], 'utf8')) + } else if (!options.includes('--offline')) { + const registry = options.find((arg) => arg.startsWith('--registry=')) + record = await fetchRecord( + manifest.name, + registry ? registry.slice('--registry='.length) : undefined + ) + } + + if (options.includes('--unpublished')) { + if (record === undefined) { + throw new Error('--unpublished needs the registry, so not --offline.') + } + if (!record || !record.versions.includes(manifest.version)) { + console.log(`${manifest.name}@${manifest.version}`) + } + return [] + } + + if (options.includes('--dist-tag')) { + if (record === undefined) { + throw new Error('--dist-tag needs the registry, so not --offline.') + } + console.log(distTag(manifest.version, record)) + return [] + } + + const problems = checkManifest({ + manifest, + dir, + record, + files: !options.includes('--skip-files'), + }) + if (!problems.length) { + console.log( + `release-check: ${manifest.name}@${manifest.version} can publish.` + ) + } + // With one package the message is enough. With several, it names its own. + return problems.map((problem) => ({ name: manifest.name, problem })) +} + +export async function main(argv = process.argv.slice(2)) { + const flags = ['--offline', '--skip-files', '--unpublished', '--dist-tag'] + const options = argv.filter((arg) => arg.startsWith('--')) + const unknown = options.filter( + (arg) => + !flags.includes(arg) && + !arg.startsWith('--registry-file=') && + !arg.startsWith('--registry=') + ) + if (unknown.length) throw new Error(`Unknown option: ${unknown.join(', ')}`) + + const named = argv.filter((arg) => !arg.startsWith('--')) + const dirs = (named.length ? named : [ROOT]).map((dir) => path.resolve(dir)) + + // Every package is checked before the verdict, so one run lists the + // problems of all of them. + const problems = [] + for (const dir of dirs) problems.push(...(await checkPackage(dir, options))) + for (const { name, problem } of problems) { + console.error( + `release-check: ${dirs.length > 1 ? `${name}: ` : ''}${problem}` + ) + } + if (problems.length) process.exit(1) +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + main().catch((error) => { + console.error(`release-check: ${error.message}`) + process.exit(1) + }) +} diff --git a/test/attribution.test.ts b/test/attribution.test.ts new file mode 100644 index 0000000..e7e9004 --- /dev/null +++ b/test/attribution.test.ts @@ -0,0 +1,174 @@ +// The two halves of the attribution rule: the commitlint rule the commit-msg +// hook runs, and the script the pipelines run. Each carries its own copy of +// the pattern, so every sample here goes through both and they have to agree. +import { execFileSync, spawnSync } from 'node:child_process' +import { + chmodSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { delimiter, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' +import config from '../commitlint.config.mjs' + +const SCRIPT = fileURLToPath( + new URL('../.gitlab/scripts/check-attribution.sh', import.meta.url) +) + +// In pieces, so that this file passes the scan it tests. +const CO = 'Co-authored' + '-by: ' +const ASSISTED = 'Assisted' + '-by: ' +const GENERATED = 'Generated ' + 'with ' + +const REJECTED = [ + `${CO}Claude `, + `${CO}Amp `, + `${ASSISTED}Claude`, + `${ASSISTED}GitHub Copilot`, + `${GENERATED}Copilot`, + `${GENERATED}Cursor`, +] +const ACCEPTED = [ + `${CO}Sam Champion `, + `${ASSISTED}Ana Ramp `, + 'Reviewed-by: Ana ', + // A tool's name inside another word credits no tool. + 'Generated ' + 'by the precursor script', +] + +const rule = config.plugins[0]!.rules['no-ai-attribution'] +const hookAccepts = (message: string) => rule({ raw: message })[0] + +// Only what the script needs. A pipeline variable from the run this test is +// part of would otherwise choose the range or the description for it. +const env = (path = process.env.PATH ?? '') => ({ + PATH: path, + HOME: process.env.HOME ?? '', +}) + +let dirs: string[] = [] + +afterEach(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }) + dirs = [] +}) + +const temp = () => { + const dir = mkdtempSync(join(tmpdir(), 'drx-attribution-')) + dirs.push(dir) + return dir +} + +const repoWithCommit = (message: string) => { + const repo = temp() + const git = (...args: string[]) => + execFileSync( + 'git', + [ + '-C', + repo, + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.org', + '-c', + 'commit.gpgsign=false', + '-c', + 'core.hooksPath=/dev/null', + ...args, + ], + { stdio: 'pipe' } + ) + git('init', '-q') + writeFileSync(join(repo, 'README.md'), 'A file.\n') + git('add', 'README.md') + git('commit', '-q', '-m', `docs: add a file\n\n${message}`) + return repo +} + +const check = (repo: string, path?: string) => + spawnSync('bash', [SCRIPT], { cwd: repo, env: env(path), encoding: 'utf8' }) + +/** The path of the real git, quoted for a shell script, so a directory with a space in its name stays whole. */ +const realGit = () => { + const path = execFileSync('which', ['git'], { encoding: 'utf8' }).trim() + return `'${path.replace(/'/g, `'\\''`)}'` +} + +// A command of the given name that fails as one that could not run does. +const broken = (name: string, script: string) => { + const bin = temp() + mkdirSync(bin, { recursive: true }) + writeFileSync(join(bin, name), `#!/bin/sh\n${script}\n`) + chmodSync(join(bin, name), 0o755) + return [bin, process.env.PATH ?? ''].join(delimiter) +} + +describe('the attribution rule', () => { + test.each(REJECTED)('the hook and the script both refuse "%s"', (line) => { + expect(hookAccepts(`docs: add a file\n\n${line}`)).toBe(false) + const result = check(repoWithCommit(line)) + expect(result.stdout).toContain('[FAIL]') + expect(result.status).toBe(1) + }) + + test.each(ACCEPTED)('the hook and the script both pass "%s"', (line) => { + expect(hookAccepts(`docs: add a file\n\n${line}`)).toBe(true) + const result = check(repoWithCommit(line)) + expect(result.stdout).toContain('[PASS]') + expect(result.status).toBe(0) + }) +}) + +describe('check-attribution.sh, when a scan cannot run', () => { + test('a grep that fails is not a clean commit message', () => { + const result = check( + repoWithCommit('Plain.'), + broken('grep', 'echo "grep: broken" >&2; exit 2') + ) + expect(result.stdout).not.toContain('[PASS]') + expect(result.status).toBe(2) + }) + + test('a git grep that fails is not a clean tree', () => { + const result = check( + repoWithCommit('Plain.'), + broken( + 'git', + `[ "$1" = grep ] && { echo "fatal: broken" >&2; exit 128; }\nexec ${realGit()} "$@"` + ) + ) + expect(result.stdout).not.toContain('[PASS]') + expect(result.stderr).toContain('fatal: broken') + expect(result.status).toBe(2) + }) + + // With pipefail a pipeline's status is its last failing command's, so grep's "no match" would hide + // a git log that could not read the message. + test('a git log that fails is not a clean commit message', () => { + const result = check( + repoWithCommit('Plain.'), + broken('git', `[ "$1" = log ] && exit 128\nexec ${realGit()} "$@"`) + ) + expect(result.stdout).not.toContain('[PASS]') + expect(result.status).toBe(2) + }) +}) + +describe('check-attribution.sh, run before a commit', () => { + test('reads what is staged, not only the working tree', () => { + const repo = repoWithCommit('Plain.') + writeFileSync(join(repo, 'NOTES.md'), `Notes.\n\n${GENERATED}Copilot\n`) + execFileSync('git', ['-C', repo, 'add', 'NOTES.md'], { stdio: 'pipe' }) + // The working copy is cleaned after staging: the commit would still record the staged line. + writeFileSync(join(repo, 'NOTES.md'), 'Notes.\n') + const result = check(repo) + expect(result.stdout).toContain('[FAIL]') + expect(result.stdout).toContain('NOTES.md') + expect(result.status).toBe(1) + }) +}) diff --git a/test/changelog.test.ts b/test/changelog.test.ts new file mode 100644 index 0000000..84bf538 --- /dev/null +++ b/test/changelog.test.ts @@ -0,0 +1,301 @@ +// The changelog generator, which writes each entry of a package's CHANGELOG.md +// at release time. It is in no package, so its coverage is not counted. +import { expect, test } from 'vitest' +import changelog from '../.changeset/changelog.cjs' + +const { getReleaseLine } = changelog + +const SHA = '75b37680976671879b03eaf2eb046d799456f5ef' +const LATER = '773a7b76a4115327c4cd5b6a937e8ecaa6f13c65' + +test('the links point at the repository the root package.json names', async () => { + const line = await getReleaseLine({ + summary: 'fix(#12): routes are kept.', + commit: LATER, + }) + expect(line).toBe( + '- Routes are kept. ([#12](https://github.com/druxt/cli/issues/12), ' + + `[\`773a7b7\`](https://github.com/druxt/cli/commit/${LATER}))` + ) +}) + +test('an entry links the commit that added its changeset', async () => { + const line = await getReleaseLine({ + summary: 'Routes are kept.', + commit: LATER, + }) + expect(line).toMatch(/\[`773a7b7`\]\(.*\/commit\/773a7b76/) +}) + +test('a Commit line links the change instead, and is left out of the entry', async () => { + const line = await getReleaseLine({ + summary: `Routes are kept.\n\nCommit: ${SHA}`, + commit: LATER, + }) + expect(line).toMatch(/\[`75b3768`\]\(.*\/commit\/75b37680/) + expect(line).not.toMatch(/773a7b7|Commit:/) +}) + +test('the rest of the body stays when a Commit line is removed', async () => { + const line = await getReleaseLine({ + summary: `Routes are kept.\n\nThe store too.\nCommit: ${SHA}`, + commit: LATER, + }) + expect(line).toMatch(/\n {2}The store too\.$/) +}) + +test('the body is a paragraph of its own, so the links close the first one', async () => { + const line = await getReleaseLine({ + summary: + 'fix(#962): a query reaches Drupal.\n\nIt was sent empty.\n\n```js\nget()\n```', + commit: LATER, + }) + // Joined straight under the bullet, the body ran into the first paragraph + // and left the links in the middle of it. + expect(line).toMatch( + /\/commit\/773a7b76[^)]*\)\)\n\n {2}It was sent empty\.\n\n {2}```js\n {2}get\(\)\n {2}```$/ + ) + expect(line).not.toMatch(/^ +$/m) +}) + +test('an issue ref in a link, a URL or code stays as written', async () => { + const line = await getReleaseLine({ + summary: + 'fix: see [the guide](https://example.org/#123), `#9` and for #45', + commit: LATER, + }) + expect(line).toMatch(/\(https:\/\/example\.org\/#123\)/) + expect(line).toMatch(/`#9`/) + expect(line).toMatch(//) + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) +}) + +test('only a Conventional Commits type is taken as a prefix', async () => { + const line = await getReleaseLine({ + summary: 'Windows: fix path resolution', + commit: LATER, + }) + expect(line).toMatch(/^- Windows: fix path resolution\. /) +}) + +test('an indented code block that opens the body keeps its indent', async () => { + const line = await getReleaseLine({ + summary: 'fix: keep the slot.\n\n const a = 1\n const b = 2', + commit: LATER, + }) + expect(line).toMatch(/\n\n {6}const a = 1\n {6}const b = 2$/) +}) + +test('a link whose destination holds parentheses stays as written', async () => { + for (const link of [ + '[the guide](https://example.org/guide(v2)#123)', + '[the guide](https://example.org/a(b(c))#123)', + '[the guide](https://example.org/guide\\(v2#123)', + '[issue #123][guide]', + ]) { + const line = await getReleaseLine({ + summary: `fix: see ${link} for #45\n\n[guide]: https://example.org/guide`, + commit: LATER, + }) + expect(line).toContain(link) + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) + } +}) + +test('a code span ends on a run of as many backticks as opened it', async () => { + const line = await getReleaseLine({ + summary: 'fix: show `foo ``` #9` for #45', + commit: LATER, + }) + expect(line).toContain('`foo ``` #9`') + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) +}) + +test('a Commit line in a code example stays in the example', async () => { + const fenced = await getReleaseLine({ + summary: `docs: show the metadata.\n\n\`\`\`\nCommit: ${SHA}\n\`\`\``, + commit: LATER, + }) + const indented = await getReleaseLine({ + summary: `docs: show the metadata.\n\n Commit: ${SHA}`, + commit: LATER, + }) + for (const line of [fenced, indented]) { + expect(line).toMatch(/\/commit\/773a7b76/) + expect(line).toMatch(new RegExp(`\\n {2}(?: {4})?Commit: ${SHA}`)) + } +}) + +test('a breaking-change footer in a code example does not mark the entry', async () => { + const fenced = await getReleaseLine({ + summary: + 'docs: show the footer.\n\n~~~\nBREAKING CHANGE: remove the old API\n~~~', + commit: LATER, + }) + const indented = await getReleaseLine({ + summary: + 'docs: show the footer.\n\n BREAKING CHANGE: remove the old API', + commit: LATER, + }) + const footer = await getReleaseLine({ + summary: 'fix: drop the old API.\n\nBREAKING CHANGE: use the new one.', + commit: LATER, + }) + expect(fenced).not.toMatch(/\*\*Breaking/) + expect(indented).not.toMatch(/\*\*Breaking/) + expect(footer).toMatch(/^- \*\*Breaking/) +}) + +test('a code span or a fence in a list item does not hide the footers after it', async () => { + for (const example of ['```example```', '- ~~~text\n example\n ~~~']) { + const line = await getReleaseLine({ + summary: `fix: drop the old API.\n\n${example}\n\nCommit: ${SHA}\nBREAKING CHANGE: use the new one.`, + commit: LATER, + }) + expect(line).toMatch(/^- \*\*Breaking/) + expect(line).toMatch(/\/commit\/75b37680/) + } +}) + +test('a link label with code, a quoted title or an angle-bracket destination stays as written', async () => { + for (const link of [ + '[guide `[`](guide#123)', + '[guide](guide#123 "release (")', + '[guide]()', + ]) { + const line = await getReleaseLine({ + summary: `fix: see ${link} for #45`, + commit: LATER, + }) + expect(line).toContain(link) + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) + } +}) + +test('an escaped or bracketed issue ref stays as written', async () => { + const line = await getReleaseLine({ + summary: 'fix: see \\#12 and [#7] for #45', + commit: LATER, + }) + expect(line).toContain('\\#12 and [#7]') + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) +}) + +test('an indented line that only looks like a list fence does not hide the footers after it', async () => { + const line = await getReleaseLine({ + summary: `fix: drop the old API.\n\n - ~~~\n\nCommit: ${SHA}\nBREAKING CHANGE: use the new one.`, + commit: LATER, + }) + expect(line).toMatch(/^- \*\*Breaking/) + expect(line).toMatch(/\/commit\/75b37680/) +}) + +test('a fence does not close on a line indented four spaces', async () => { + const line = await getReleaseLine({ + summary: `docs: show the footers.\n\n~~~text\n ~~~\nCommit: ${SHA}\nBREAKING CHANGE: migrate\n~~~`, + commit: LATER, + }) + expect(line).not.toMatch(/\*\*Breaking/) + expect(line).toMatch(/\/commit\/773a7b76/) + expect(line).toContain(`Commit: ${SHA}`) +}) + +test('an issue ref in an entity, an email autolink, a title or a reference link stays as written', async () => { + const definition = '\n\n[guide #123]: https://example.org/guide' + for (const [summary, kept] of [ + ['fix: show { for #45', '{'], + [ + 'fix: contact for #45', + '', + ], + [ + 'fix: see [the `]` guide #123](https://example.org) for #45', + '[the `]` guide #123](https://example.org)', + ], + [ + 'fix: see [guide](https://example.org "version) #123") for #45', + '[guide](https://example.org "version) #123")', + ], + [`fix: see [x][guide #123] for #45${definition}`, '[x][guide #123]'], + [`fix: see [guide #123][] for #45${definition}`, '[guide #123][]'], + [`fix: see [guide #123] for #45${definition}`, '[guide #123] for'], + ]) { + const line = await getReleaseLine({ summary, commit: LATER }) + expect(line).toContain(kept) + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) + } +}) + +test('a fence in a list item ends with the item, so the footers after it are read', async () => { + const line = await getReleaseLine({ + summary: `fix: drop the old API.\n\n- ~~~\n example\n\nCommit: ${SHA}\nBREAKING CHANGE: use the new one.`, + commit: LATER, + }) + expect(line).toMatch(/^- \*\*Breaking/) + expect(line).toMatch(/\/commit\/75b37680/) +}) + +test('a fence in a list item does not close on a line indented four spaces past the item', async () => { + const line = await getReleaseLine({ + summary: `docs: show the footers.\n\n- ~~~text\n ~~~\n Commit: ${SHA}\n BREAKING CHANGE: migrate\n ~~~`, + commit: LATER, + }) + expect(line).not.toMatch(/\*\*Breaking/) + expect(line).toMatch(/\/commit\/773a7b76/) +}) + +test('a Commit line or a breaking-change footer in an HTML block stays an example', async () => { + const line = await getReleaseLine({ + summary: `docs: show the footers.\n\n
\nCommit: ${SHA}\nBREAKING CHANGE: migrate\n
`, + commit: LATER, + }) + expect(line).not.toMatch(/\*\*Breaking/) + expect(line).toMatch(/\/commit\/773a7b76/) + expect(line).toContain(`Commit: ${SHA}`) +}) + +test('an issue ref inside an HTML link stays as written', async () => { + const line = await getReleaseLine({ + summary: 'fix: see
#123 for #45', + commit: LATER, + }) + expect(line).toContain('#123') + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) +}) + +test('an issue ref in a bare URL stays as written', async () => { + const line = await getReleaseLine({ + summary: + 'fix: see https://example.org/guide#123, www.example.org/a#7 and https://example.org/a(b(c))#8 for #45', + commit: LATER, + }) + expect(line).toContain( + 'https://example.org/guide#123, www.example.org/a#7 and https://example.org/a(b(c))#8 for' + ) + expect(line).toMatch(/\[#45\]\(.*\/issues\/45\)/) +}) + +test('a bare URL ends at the bracket or parenthesis that closes it', async () => { + for (const [summary, kept, linked] of [ + [ + 'fix: see (#45) for #46', + '', + ['45', '46'], + ], + [ + 'fix: see [x](https://example.org/b)#45 for #46', + '[x](https://example.org/b)', + ['45', '46'], + ], + [ + 'fix: (see https://example.org/c)#45 for #46', + 'https://example.org/c)', + ['45', '46'], + ], + ] as const) { + const line = await getReleaseLine({ summary, commit: LATER }) + expect(line).toContain(kept) + for (const n of linked) + expect(line).toMatch(new RegExp(`\\[#${n}\\]\\(.*\\/issues\\/${n}\\)`)) + } +}) diff --git a/test/git-env.test.ts b/test/git-env.test.ts new file mode 100644 index 0000000..f0cf050 --- /dev/null +++ b/test/git-env.test.ts @@ -0,0 +1,53 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { describe, expect, test } from 'vitest' +import { HOOK_GIT_VARIABLES, withoutHookGit } from './setup/git-env.js' + +describe('the variables a git hook hands to what it runs', () => { + test('are taken out of an environment, and nothing else is', () => { + const cleaned = withoutHookGit({ + GIT_DIR: '/repo/.git', + GIT_INDEX_FILE: '/repo/.git/index.lock', + GIT_WORK_TREE: '/repo', + GIT_PREFIX: 'packages/', + GIT_AUTHOR_NAME: 'A Person', + PATH: '/usr/bin', + }) + expect(cleaned).toEqual({ GIT_AUTHOR_NAME: 'A Person', PATH: '/usr/bin' }) + }) + + test('include the index, so a test never stages into the commit being made', () => { + expect(HOOK_GIT_VARIABLES).toContain('GIT_DIR') + expect(HOOK_GIT_VARIABLES).toContain('GIT_INDEX_FILE') + }) + + // The suite's own setup file has run by now. A hook's GIT_DIR in this process would send every `git init` + // and `git commit` a test makes into the repository being committed to. + test('are gone from the process the tests run in', () => { + for (const name of HOOK_GIT_VARIABLES) + expect(process.env[name]).toBe(undefined) + }) + + test('are removed by the setup file in a process that started with them', () => { + const setup = fileURLToPath(new URL('./setup/git-env.ts', import.meta.url)) + const out = execFileSync( + process.execPath, + [ + '--experimental-strip-types', + '--input-type=module', + '-e', + `await import(${JSON.stringify(setup)}); console.log(JSON.stringify([process.env.GIT_DIR ?? null, process.env.GIT_INDEX_FILE ?? null]))`, + ], + { + encoding: 'utf8', + env: { + ...process.env, + GIT_DIR: '/nowhere/.git', + GIT_INDEX_FILE: '/nowhere/index', + }, + stdio: ['ignore', 'pipe', 'ignore'], + } + ) + expect(JSON.parse(out)).toEqual([null, null]) + }) +}) diff --git a/test/lint-prose.test.ts b/test/lint-prose.test.ts new file mode 100644 index 0000000..cf4f08a --- /dev/null +++ b/test/lint-prose.test.ts @@ -0,0 +1,142 @@ +// lint-prose.sh, with a stand-in for Vale that records the files it is given. +// The stand-in fires on the script's canary, as a configured Vale does. +import { execFileSync, spawnSync } from 'node:child_process' +import { + chmodSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' + +const SCRIPT = fileURLToPath( + new URL('../.gitlab/scripts/lint-prose.sh', import.meta.url) +) + +let dirs: string[] = [] + +afterEach(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }) + dirs = [] +}) + +const temp = () => { + const dir = mkdtempSync(join(tmpdir(), 'drx-prose-')) + dirs.push(dir) + return dir +} + +const setup = (files: Record) => { + const repo = temp() + const bin = temp() + const log = join(bin, 'files.log') + const vale = join(bin, 'vale') + writeFileSync( + vale, + [ + '#!/bin/sh', + 'for arg in "$@"; do', + ' case "$arg" in', + ' canary.md) echo "canary.md:1:13:stand-in:fired"; exit 1 ;;', + ' --*) ;;', + ` *) printf '%s\\n' "$arg" >> "${log}" ;;`, + ' esac', + 'done', + '', + ].join('\n') + ) + chmodSync(vale, 0o755) + + const git = (...args: string[]) => + execFileSync( + 'git', + [ + '-C', + repo, + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.org', + '-c', + 'commit.gpgsign=false', + '-c', + 'core.hooksPath=/dev/null', + ...args, + ], + { stdio: 'pipe' } + ) + git('init', '-q') + writeFileSync(join(repo, '.vale.ini'), '[*.md]\n') + git('add', '.vale.ini') + git('commit', '-q', '-m', 'chore: add the configuration') + for (const [name, content] of Object.entries(files)) { + writeFileSync(join(repo, name), content) + } + git('add', '-A') + git('commit', '-q', '-m', 'docs: add the files') + + const run = (...args: string[]) => { + const result = spawnSync('bash', [SCRIPT, ...args], { + cwd: repo, + // Only what the script needs. A pipeline variable from the run this + // test is part of would otherwise choose the range for it. + env: { + PATH: process.env.PATH ?? '', + HOME: process.env.HOME ?? '', + VALE_BIN: vale, + }, + encoding: 'utf8', + }) + const seen = existsSync(log) + ? readFileSync(log, 'utf8').split('\n').filter(Boolean) + : [] + return { ...result, seen } + } + return { run } +} + +describe('lint-prose.sh', () => { + test('lints the markdown the last commit touched, whatever its name holds', () => { + const { run } = setup({ + 'notes.md': 'Notes.\n', + 'two words.md': 'More notes.\n', + 'code.ts': 'export {}\n', + }) + const result = run() + expect(result.stdout).toContain('2 markdown file(s)') + expect(result.status).toBe(0) + expect(result.seen).toContain('notes.md') + expect(result.seen).toContain('two words.md') + expect(result.seen).not.toContain('code.ts') + }) + + test('passes a commit that touches no markdown', () => { + const { run } = setup({ 'code.ts': 'export {}\n' }) + const result = run() + expect(result.stderr).toBe('') + expect(result.stdout).toContain('0 markdown file(s)') + expect(result.status).toBe(0) + }) + + test('--all lints every tracked markdown file', () => { + const { run } = setup({ 'notes.md': 'Notes.\n', 'more.md': 'More.\n' }) + const result = run('--all') + expect(result.stdout).toContain('2 markdown file(s)') + expect(result.seen).toEqual(expect.arrayContaining(['notes.md', 'more.md'])) + }) + + // macOS still has bash 3.2 as /bin/bash, where mapfile does not exist and + // an empty array is an unbound variable under `set -u`. + test('uses nothing a bash older than 4.4 lacks', () => { + const source = readFileSync(SCRIPT, 'utf8') + expect(source).not.toMatch(/\b(mapfile|readarray)\b/) + // Each array that can be empty is expanded behind a guard. + expect(source).not.toMatch(/ in "\$\{markdown\[@\]\}"/) + expect(source).not.toMatch(/ "\$\{glob\[@\]\}"/) + }) +}) diff --git a/test/postinstall.test.ts b/test/postinstall.test.ts new file mode 100644 index 0000000..2ddcfbb --- /dev/null +++ b/test/postinstall.test.ts @@ -0,0 +1,54 @@ +import { execFileSync } from 'node:child_process' +import { + copyFileSync, + mkdirSync, + mkdtempSync, + realpathSync, + rmSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' + +const SCRIPT = fileURLToPath( + new URL('../scripts/postinstall.mjs', import.meta.url) +) + +let repo: string | undefined + +afterEach(() => { + if (repo) rmSync(repo, { recursive: true, force: true }) +}) + +// A checkout with the script copied to `/scripts/`, then run from there. +const install = (under: string) => { + repo = realpathSync(mkdtempSync(join(tmpdir(), 'drx-postinstall-'))) + execFileSync('git', ['init', '-q', repo]) + const scripts = join(repo, under, 'scripts') + mkdirSync(scripts, { recursive: true }) + copyFileSync(SCRIPT, join(scripts, 'postinstall.mjs')) + execFileSync(process.execPath, [join(scripts, 'postinstall.mjs')], { + cwd: join(repo, under), + stdio: 'pipe', + }) + try { + return execFileSync( + 'git', + ['-C', repo, 'config', '--local', 'core.hooksPath'], + { encoding: 'utf8' } + ).trim() + } catch { + return undefined + } +} + +describe('the postinstall script', () => { + test('points its own checkout at the committed hooks', () => { + expect(install('.')).toBe('.githooks') + }) + + test('leaves the hooks of a checkout it is only vendored into', () => { + expect(install('vendor/druxt-cli')).toBeUndefined() + }) +}) diff --git a/test/private-refs.test.ts b/test/private-refs.test.ts new file mode 100644 index 0000000..742af91 --- /dev/null +++ b/test/private-refs.test.ts @@ -0,0 +1,118 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, describe, expect, test } from 'vitest' +import { findPrivateRefs, mappedToIpv4 } from '../scripts/lint-private-refs.mjs' + +const SCRIPT = fileURLToPath( + new URL('../scripts/lint-private-refs.mjs', import.meta.url) +) + +const hostsIn = (text: string) => findPrivateRefs(text).map((ref) => ref.host) + +// The hosts below are private on purpose. The rule exempts this file by path, +// which is why it can state them plainly. +describe('findPrivateRefs', () => { + test('finds a private host by name', () => { + expect(hostsIn('see http://gitlab.example.local/x')).toEqual([ + 'gitlab.example.local', + ]) + }) + + test('finds RFC1918 addresses', () => { + expect(hostsIn('http://10.0.0.8/ http://192.168.1.1/')).toEqual([ + '10.0.0.8', + '192.168.1.1', + ]) + expect(hostsIn('http://172.16.0.1/')).toEqual(['172.16.0.1']) + }) + + test('finds an RFC1918 address inside an IPv4-mapped IPv6 literal', () => { + expect(hostsIn('https://[::ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[::ffff:0a00:0008]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('https://[0:0:0:0:0:ffff:10.0.0.8]/x')).toEqual(['10.0.0.8']) + expect(hostsIn('http://[::ffff:c0a8:0101]/')).toEqual(['192.168.1.1']) + }) + + test('finds a link-local IPv6 address', () => { + expect(hostsIn('http://[fe80::1]/')).toEqual(['fe80::1']) + }) + + test('leaves public hosts alone', () => { + expect(hostsIn('https://druxtjs.org/docs')).toEqual([]) + expect(hostsIn('http://[2001:db8::1]/')).toEqual([]) + expect(hostsIn('http://[::ffff:8.8.8.8]/')).toEqual([]) + }) + + test('leaves the local development hosts alone', () => { + expect(hostsIn('http://localhost:3000/ http://127.0.0.1:8888/')).toEqual([]) + expect(hostsIn('http://[::1]/ https://example.ddev.site/')).toEqual([]) + }) + + test('finds a private name with nothing before it', () => { + expect(hostsIn('see http://intranet/project and http://corp/')).toEqual([ + 'intranet', + 'corp', + ]) + expect(hostsIn('http://localhost/ http://example/')).toEqual([]) + }) + + test('finds a link-local IPv4 address, mapped or not', () => { + expect(hostsIn('http://169.254.1.1/')).toEqual(['169.254.1.1']) + expect(hostsIn('http://[::ffff:169.254.1.1]/')).toEqual(['169.254.1.1']) + expect(hostsIn('http://169.253.1.1/ http://169.255.1.1/')).toEqual([]) + }) + + test('reads a scheme in any case', () => { + expect(hostsIn('HTTP://gitlab.example.local/x')).toEqual([ + 'gitlab.example.local', + ]) + expect(hostsIn('Https://10.0.0.8/')).toEqual(['10.0.0.8']) + }) + + test('ignores an IPv6 literal with too many groups', () => { + expect(mappedToIpv4('1:2:3:4:5:6:7::8:9')).toBe('1:2:3:4:5:6:7::8:9') + expect(hostsIn('http://[1:2:3:4:5:6:7::8:9]/')).toEqual([]) + }) + + test('reads the host, not the userinfo a git remote carries', () => { + expect(hostsIn('https://oauth2:token@gitlab.example.local/a')).toEqual([ + 'gitlab.example.local', + ]) + }) +}) + +describe('the lint:private command', () => { + let repo: string | undefined + + afterEach(() => { + if (repo) rmSync(repo, { recursive: true, force: true }) + }) + + const repoWith = (content: string) => { + repo = mkdtempSync(join(tmpdir(), 'drx-private-')) + execFileSync('git', ['init', '-q', repo]) + writeFileSync(join(repo, 'README.md'), content) + execFileSync('git', ['-C', repo, 'add', 'README.md']) + return repo + } + + const run = (root: string) => { + try { + execFileSync(process.execPath, [SCRIPT, root], { stdio: 'pipe' }) + return 0 + } catch (error) { + return (error as { status: number }).status + } + } + + test('passes a repository with public references only', () => { + expect(run(repoWith('See https://druxtjs.org.\n'))).toBe(0) + }) + + test('fails a repository whose tracked file names a private host', () => { + expect(run(repoWith('See http://gitlab.example.local/x.\n'))).toBe(1) + }) +}) diff --git a/test/release-check.test.ts b/test/release-check.test.ts new file mode 100644 index 0000000..e80e3d5 --- /dev/null +++ b/test/release-check.test.ts @@ -0,0 +1,412 @@ +import { execFile, spawnSync } from 'node:child_process' +import fs from 'node:fs' +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import os from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, test } from 'vitest' + +// The gate runs in a real node process here, which is how the release +// workflow runs it. +const SCRIPT = fileURLToPath( + new URL('../scripts/release-check.mjs', import.meta.url) +) + +let dir: string + +const write = (manifest: object, record?: object | null) => { + fs.writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) + if (record !== undefined) { + fs.writeFileSync(join(dir, 'registry.json'), JSON.stringify(record)) + } +} + +const run = (...flags: string[]) => { + const registry = fs.existsSync(join(dir, 'registry.json')) + ? [`--registry-file=${join(dir, 'registry.json')}`] + : ['--offline'] + const result = spawnSync( + process.execPath, + [SCRIPT, dir, ...registry, ...flags], + { encoding: 'utf8' } + ) + return { status: result.status, out: result.stdout + result.stderr } +} + +let server: Server | undefined + +beforeEach(() => { + dir = fs.mkdtempSync(join(os.tmpdir(), 'release-check-')) +}) + +afterEach(async () => { + fs.rmSync(dir, { recursive: true, force: true }) + const closing = server + server = undefined + if (closing) { + closing.closeAllConnections() + await new Promise((resolve) => closing.close(resolve)) + } +}) + +// A registry on a loopback port. The script runs without blocking this +// process, which has to answer it, and a script that hangs is killed. +const runAgainst = async ( + answer: Parameters[1], + ...flags: string[] +) => { + server = createServer(answer) + const listening = server + await new Promise((resolve) => + listening.listen(0, '127.0.0.1', resolve) + ) + const { port } = listening.address() as AddressInfo + return new Promise<{ status: number | string | null; out: string }>( + (resolve) => { + execFile( + process.execPath, + [SCRIPT, dir, `--registry=http://127.0.0.1:${port}`, ...flags], + { encoding: 'utf8', timeout: 10000 }, + (error, stdout, stderr) => + resolve({ + status: error ? (error.killed ? 'killed' : error.code!) : 0, + out: stdout + stderr, + }) + ) + } + ) +} + +describe('release-check', () => { + test('passes a publishable package', () => { + write({ name: 'x', version: '1.0.0', dependencies: { druxt: '^0.24.0' } }) + expect(run('--skip-files')).toEqual({ + status: 0, + out: 'release-check: x@1.0.0 can publish.\n', + }) + }) + + test.each(['workspace:*', 'link:../druxt', 'file:../druxt'])( + 'refuses the specifier %s', + (range) => { + write({ name: 'x', version: '1.0.0', peerDependencies: { druxt: range } }) + const result = run('--skip-files') + expect(result.status).toBe(1) + expect(result.out).toContain('does not resolve from npm') + } + ) + + test('refuses an invalid version', () => { + write({ name: 'x', version: '1.0' }) + expect(run('--skip-files').out).toContain('is not a valid version') + }) + + test('refuses a version below the published one', () => { + write( + { name: 'x', version: '1.1.9' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + const result = run('--skip-files') + expect(result.status).toBe(1) + expect(result.out).toContain('does not rise above the published 1.2.0') + }) + + test('refuses a snapshot of an already published version', () => { + write( + { name: 'x', version: '1.2.0-dev.20260920004838' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + expect(run('--skip-files').status).toBe(1) + }) + + test('passes a snapshot above the published version', () => { + write( + { name: 'x', version: '1.2.1-dev.20260920004838' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + expect(run('--skip-files').status).toBe(0) + }) + + test('passes a stable release over its own prerelease', () => { + write( + { name: 'x', version: '2.0.0' }, + { latest: '2.0.0-beta.1', versions: ['2.0.0-beta.1'] } + ) + expect(run('--skip-files').status).toBe(0) + }) + + test('passes a version branch release below a newer major', () => { + const record = { latest: '2.0.0', versions: ['1.9.0', '2.0.0'] } + write({ name: 'x', version: '1.9.1' }, record) + expect(run('--skip-files').status).toBe(0) + write({ name: 'x', version: '1.9.1-dev.20261031020000' }, record) + expect(run('--skip-files').status).toBe(0) + }) + + test('passes a dev snapshot cut after an earlier one of the same core', () => { + // `changeset version --snapshot` runs in CI and is never committed, so the + // pending changesets stay pending and every push computes the same core + // until the version pull request merges. Only the timestamp moves. + write( + { name: 'x', version: '0.2.0-dev.20261101000000' }, + { latest: '0.1.0', versions: ['0.1.0', '0.2.0-dev.20261031000000'] } + ) + expect(run('--skip-files').status).toBe(0) + }) + + test('refuses a version below the highest of its own major', () => { + write( + { name: 'x', version: '1.8.5' }, + { latest: '2.0.0', versions: ['1.9.0', '2.0.0'] } + ) + const result = run('--skip-files') + expect(result.status).toBe(1) + expect(result.out).toContain('does not rise above the published 1.9.0') + }) + + test('passes the first release of a new major', () => { + write( + { name: 'x', version: '3.0.0' }, + { latest: '2.0.0', versions: ['1.9.0', '2.0.0'] } + ) + expect(run('--skip-files').status).toBe(0) + }) + + test('passes an already published version, because publish skips it', () => { + write( + { name: 'x', version: '1.2.0' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + expect(run('--skip-files').status).toBe(0) + }) + + test('passes a package npm has never seen', () => { + write({ name: 'x', version: '0.0.1' }, null) + expect(run('--skip-files').status).toBe(0) + }) + + test('refuses a files entry that was not built, or is empty', () => { + write({ name: 'x', version: '1.0.0', files: ['dist', 'templates'] }) + fs.mkdirSync(join(dir, 'dist')) + const result = run() + expect(result.status).toBe(1) + expect(result.out).toContain('files entry "dist" is empty') + expect(result.out).toContain('files entry "templates" does not exist') + + fs.writeFileSync(join(dir, 'dist', 'index.js'), '') + fs.mkdirSync(join(dir, 'templates')) + fs.writeFileSync(join(dir, 'templates', 'plugin.js'), '') + expect(run().status).toBe(0) + }) + + test.each([undefined, []])('refuses a files list of %p', (list) => { + write({ name: 'x', version: '1.0.0', files: list }) + const result = run() + expect(result.status).toBe(1) + expect(result.out).toContain('has no "files" list') + expect(run('--skip-files').status).toBe(0) + }) + + test('skips a private package', () => { + write({ name: 'x', version: 'nope', private: true }) + expect(run()).toEqual({ + status: 0, + out: 'release-check: the package is private, nothing to publish.\n', + }) + }) + + test('--unpublished prints the version only when npm lacks it', () => { + write( + { name: 'x', version: '1.2.1' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + expect(run('--unpublished').out).toBe('x@1.2.1\n') + + write( + { name: 'x', version: '1.2.0' }, + { latest: '1.2.0', versions: ['1.2.0'] } + ) + expect(run('--unpublished').out).toBe('') + }) + + test.each([ + ['1.2.1', 'latest', { latest: '1.2.0', versions: ['1.2.0'] }], + ['2.0.0', 'latest', { latest: '2.0.0-beta.1', versions: ['2.0.0-beta.1'] }], + ['0.1.0', 'latest', null], + ['1.9.1', 'latest-1', { latest: '2.0.0', versions: ['1.9.0', '2.0.0'] }], + ['2.1.0-beta.0', 'next', { latest: '2.0.0', versions: ['2.0.0'] }], + ])('--dist-tag publishes %s as %s', (version, tag, record) => { + write({ name: 'x', version }, record) + expect(run('--dist-tag').out).toBe(`${tag}\n`) + }) + + test('refuses an unknown option', () => { + write({ name: 'x', version: '1.0.0' }) + const result = run('--nope') + expect(result.status).toBe(1) + expect(result.out).toContain('Unknown option: --nope') + }) + + test('checks every directory named, and says which package a problem is in', () => { + const second = join(dir, 'second') + fs.mkdirSync(second) + fs.writeFileSync( + join(dir, 'package.json'), + JSON.stringify({ name: 'x', version: '1.0.0' }) + ) + fs.writeFileSync( + join(second, 'package.json'), + JSON.stringify({ name: 'y', version: '1.0' }) + ) + const result = spawnSync( + process.execPath, + [SCRIPT, dir, second, '--offline', '--skip-files'], + { encoding: 'utf8' } + ) + expect(result.status).toBe(1) + expect(result.stdout).toBe('release-check: x@1.0.0 can publish.\n') + expect(result.stderr).toBe( + 'release-check: y: "1.0" is not a valid version.\n' + ) + }) + + test('--unpublished prints a line for each directory npm lacks', () => { + const second = join(dir, 'second') + fs.mkdirSync(second) + write({ name: 'x', version: '1.2.1' }, { latest: '1.2.0', versions: [] }) + fs.writeFileSync( + join(second, 'package.json'), + JSON.stringify({ name: 'y', version: '0.1.0' }) + ) + const result = spawnSync( + process.execPath, + [ + SCRIPT, + dir, + second, + `--registry-file=${join(dir, 'registry.json')}`, + '--unpublished', + ], + { encoding: 'utf8' } + ) + expect(result.stdout).toBe('x@1.2.1\ny@0.1.0\n') + }) + + test.each([ + '../druxt', + './vendor/druxt', + '/srv/druxt', + '~/druxt', + '..\\druxt', + 'C:\\code\\druxt', + 'druxt-0.25.0.tgz', + ])('refuses the local path %s', (range) => { + write({ name: 'x', version: '1.0.0', dependencies: { druxt: range } }) + const result = run('--skip-files') + expect(result.status).toBe(1) + expect(result.out).toContain('does not resolve from npm') + }) + + test.each([ + '^0.24.0', + '>=0.25.1 <1', + '1.x', + '*', + 'latest', + 'next', + 'npm:druxt-next@^1.0.0', + 'npm:@druxt/core@0.25.0', + ])('passes the range, tag or alias %s', (range) => { + write({ name: 'x', version: '1.0.0', dependencies: { druxt: range } }) + expect(run('--skip-files').status).toBe(0) + }) + + test('refuses a declared entry point that is not in the package', () => { + write({ + name: 'x', + version: '1.0.0', + files: ['dist'], + bin: { x: './dist/bin.js' }, + main: './dist/index.js', + types: './dist/index.d.ts', + exports: { + '.': { types: './dist/index.d.ts', import: './dist/index.js' }, + './tools': { import: { default: './dist/tools.js' } }, + './components/*': './dist/components/*', + './package.json': './package.json', + }, + }) + fs.mkdirSync(join(dir, 'dist')) + fs.writeFileSync(join(dir, 'dist', 'index.js'), '') + fs.writeFileSync(join(dir, 'dist', 'index.d.ts'), '') + + const result = run() + expect(result.status).toBe(1) + expect(result.out).toContain( + 'bin.x is "./dist/bin.js", which is not among the files npm would pack.' + ) + expect(result.out).toContain( + 'exports["./tools"].import.default is "./dist/tools.js", which is not among the files npm would pack.' + ) + expect(result.out).not.toContain('index') + expect(result.out).not.toContain('components') + + fs.writeFileSync(join(dir, 'dist', 'bin.js'), '') + fs.writeFileSync(join(dir, 'dist', 'tools.js'), '') + expect(run()).toEqual({ + status: 0, + out: 'release-check: x@1.0.0 can publish.\n', + }) + }) + + test('refuses an entry point that exists and is left out of the package', () => { + write({ + name: 'x', + version: '1.0.0', + files: ['dist'], + exports: { '.': './src/index.js' }, + }) + fs.mkdirSync(join(dir, 'dist')) + fs.writeFileSync(join(dir, 'dist', 'index.js'), '') + fs.mkdirSync(join(dir, 'src')) + fs.writeFileSync(join(dir, 'src', 'index.js'), '') + const result = run() + expect(result.status).toBe(1) + expect(result.out).toContain( + 'exports["."] is "./src/index.js", which is not among the files npm would pack.' + ) + }) + + test('reads the registry it is given', async () => { + write({ name: 'x', version: '1.1.9' }) + const result = await runAgainst((request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }).end( + JSON.stringify({ + 'dist-tags': { latest: '1.2.0' }, + versions: { '1.2.0': {} }, + }) + ) + }, '--skip-files') + expect(result.out).toContain('does not rise above the published 1.2.0') + expect(result.status).toBe(1) + }) + + test('fails when the registry closes before its answer is complete', async () => { + write({ name: 'x', version: '1.1.9' }) + const result = await runAgainst((request, response) => { + response.writeHead(200, { + 'content-type': 'application/json', + 'content-length': '4096', + }) + response.write('{"dist-tags": {"latest": "1.2.0"}, "versions": {', () => + response.socket?.destroy() + ) + }, '--skip-files') + expect(result.out).toContain( + 'release-check: npm closed the connection before its answer for x was complete.' + ) + expect(result.out).not.toContain('can publish') + expect(result.status).toBe(1) + }) +}) diff --git a/test/setup/git-env.ts b/test/setup/git-env.ts new file mode 100644 index 0000000..78a9d4e --- /dev/null +++ b/test/setup/git-env.ts @@ -0,0 +1,26 @@ +/** + * The variables git sets for a hook, which point every git command at the repository being committed to. + * + * A test that runs `git init` or `git commit` in a temporary directory would otherwise write to that + * repository's index and refs when the suite runs from the pre-commit hook. + */ +export const HOOK_GIT_VARIABLES = [ + 'GIT_DIR', + 'GIT_WORK_TREE', + 'GIT_INDEX_FILE', + 'GIT_PREFIX', + 'GIT_COMMON_DIR', + 'GIT_OBJECT_DIRECTORY', + 'GIT_ALTERNATE_OBJECT_DIRECTORIES', +] as const + +/** A copy of an environment without the variables a git hook sets. */ +export function withoutHookGit( + env: Record +): Record { + const cleaned = { ...env } + for (const name of HOOK_GIT_VARIABLES) delete cleaned[name] + return cleaned +} + +for (const name of HOOK_GIT_VARIABLES) delete process.env[name] diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..da3c933 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,24 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + resolve: { + // create-druxt imports the CLI by its package name. The tests read the + // CLI's sources, so they do not depend on a build having run. + alias: { + '@druxt/cli': fileURLToPath( + new URL('./packages/cli/src/index.ts', import.meta.url) + ), + }, + }, + test: { + include: ['packages/*/test/**/*.test.ts', 'test/**/*.test.ts'], + // A git hook's variables would send a test's own git commands to the repository being committed to. + setupFiles: ['./test/setup/git-env.ts'], + coverage: { + provider: 'v8', + include: ['packages/*/src/**/*.ts', 'scripts/lint-private-refs.mjs'], + reporter: ['text', 'lcov'], + }, + }, +})