diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fff7c31..2d1d1ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,7 +45,7 @@ jobs: run: npm run build generated-project: - name: Generated project - ${{ matrix.package-manager }}, Node ${{ matrix.node-version }} + name: Generated project - ${{ matrix.package-manager }}, Node ${{ matrix.node-version }} ${{ matrix.features }} runs-on: ubuntu-latest needs: cli strategy: @@ -53,6 +53,15 @@ jobs: matrix: node-version: [22, 24, 26] package-manager: [npm, pnpm] + features: ['--gatekeeper'] + # The project without extras must keep working as features are added. + include: + - node-version: 24 + package-manager: npm + features: '--no-gatekeeper' + - node-version: 24 + package-manager: pnpm + features: '--no-gatekeeper' steps: - name: Checkout @@ -79,7 +88,7 @@ jobs: git config --global user.email "ci@example.com" - name: Scaffold a project - run: node dist/index.js test-api --yes --package-manager ${{ matrix.package-manager }} + run: node dist/index.js test-api --yes --package-manager ${{ matrix.package-manager }} ${{ matrix.features }} - name: Everything is committed, including the lockfile working-directory: test-api @@ -113,6 +122,13 @@ jobs: echo "Malformed JSON status: $status" test "$status" = "400" + # Rate limit headers only when Gatekeeper was chosen. + if [ "${{ matrix.features }}" = "--gatekeeper" ]; then + curl -sI http://localhost:3000/api/health | grep -qi '^x-ratelimit-limit: 100' + else + ! curl -sI http://localhost:3000/api/health | grep -qi '^x-ratelimit-limit' + fi + docker: name: Docker image - ${{ matrix.package-manager }} runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index af897b6..510346b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [1.1.0] - 2026-11-09 + +### Added + +- Interactive setup: project name, Gatekeeper rate limiting and package manager. `--yes` takes the defaults, any option passed on the command line isn't asked, and it never asks in CI. +- Optional rate limiting with [Gatekeeper](https://github.com/SibilSoren/gatekeeper) 2: 100 requests a minute per IP, added by default. `--gatekeeper` / `--no-gatekeeper` choose without asking. ### Fixed @@ -35,7 +40,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `typecheck` script, `.dockerignore`, `.nvmrc` and tests for validation, error handling and Swagger in generated projects. -- CI scaffolds a project with npm and pnpm on Node 22, 24 and 26, then builds, tests, lints, boots the production build and builds the Docker image. It also runs weekly to catch dependency changes. +- CI scaffolds a project with npm and pnpm on Node 22, 24 and 26, with and without Gatekeeper, then builds, tests, lints, boots the production build and builds the Docker image. It also runs weekly to catch dependency changes. +- CLI tests that scaffold every combination of options and check the generated files, so a new option can't change what the others produce. ## [1.0.0] - 2026-06-09 diff --git a/README.md b/README.md index b3ca598..051912e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Scaffold a production-ready **Node.js + TypeScript + Express** API with a single npx create-api-starterkit my-api ``` -**Zero prompts. Zero config. Just works.** +Answer two questions, or add `--yes` to take the defaults. Requires Node.js 22.12 or later. ## What You Get @@ -26,6 +26,7 @@ A fully configured API project with: - 🐳 **Docker** — multi-stage Dockerfile + docker-compose - 🎨 **ESLint + Prettier** — consistent code style - 🪝 **Husky + lint-staged** — git hooks for quality +- 🚦 **Rate limiting** (optional) — [Gatekeeper](https://github.com/SibilSoren/gatekeeper), 100 requests a minute per IP by default ## Quick Start @@ -51,9 +52,13 @@ npx create-api-starterkit [options] | Option | Description | Default | |---|---|---| +| `-y, --yes` | Skip the questions and use the defaults | asks | +| `--gatekeeper` / `--no-gatekeeper` | Add or skip Gatekeeper rate limiting | add | +| `--package-manager ` | Use `npm` or `pnpm` | `npm` | | `--skip-install` | Skip dependency installation | `false` | | `--no-git` | Skip git initialization | `false` | -| `--package-manager ` | Use `npm` or `pnpm` | `npm` | + +Any option you pass on the command line isn't asked again. In CI (when `CI` is set), it never asks. ## Generated Project Structure diff --git a/docs/index.html b/docs/index.html index 0f09011..1b88228 100644 --- a/docs/index.html +++ b/docs/index.html @@ -4,7 +4,7 @@ create-api-starterkit — Scaffold Production-Ready APIs in Seconds - + @@ -54,7 +54,7 @@

in seconds.

- One command. Zero prompts. Zero config.
+ One command. Two questions, or --yes for the defaults.
A fully configured Node.js + TypeScript + Express API — ready to build on.

@@ -195,6 +195,14 @@

You're live!

CLI Options

+
+ -y, --yes + Skip the questions and use the defaults +
+
+ --no-gatekeeper + Skip Gatekeeper rate limiting (added by default) +
--skip-install Skip dependency installation diff --git a/package-lock.json b/package-lock.json index 938faee..2b90a53 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "create-api-starterkit", - "version": "1.0.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "create-api-starterkit", - "version": "1.0.0", + "version": "1.1.0", "license": "MIT", "dependencies": { "@clack/prompts": "^1.5.1", diff --git a/package.json b/package.json index ff19f8c..f51406c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "create-api-starterkit", - "version": "1.0.0", + "version": "1.1.0", "description": "Scaffold a production-ready Node.js + TypeScript + Express API with a single command", "type": "module", "bin": { diff --git a/src/create.ts b/src/create.ts index 1a329ed..426b3db 100644 --- a/src/create.ts +++ b/src/create.ts @@ -14,6 +14,11 @@ import { installCommand, runCommand, } from './utils/package-manager.js'; +import { + GATEKEEPER_PACKAGE, + GATEKEEPER_VERSION, + injectGatekeeper, +} from './utils/gatekeeper.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -35,7 +40,7 @@ export async function createProject(options: CreateOptions): Promise { } // ─── Check target directory ───────────────────────────── - const targetDir = path.resolve(process.cwd(), projectName); + const targetDir = path.resolve(options.cwd ?? process.cwd(), projectName); if (!isDirEmpty(targetDir)) { log.error(`Directory "${projectName}" already exists and is not empty.`); @@ -77,38 +82,21 @@ export async function createProject(options: CreateOptions): Promise { const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); if (options.includeGatekeeper) { - pkg.dependencies = pkg.dependencies || {}; - pkg.dependencies['@sibilsoren/gatekeeper'] = '^1.0.0'; - } - - if (options.includePrisma) { - pkg.dependencies = pkg.dependencies || {}; - pkg.devDependencies = pkg.devDependencies || {}; - pkg.dependencies['@prisma/client'] = '^5.10.0'; - pkg.devDependencies['prisma'] = '^5.10.0'; - pkg.scripts = pkg.scripts || {}; - pkg.scripts['db:push'] = 'npx prisma db push'; - pkg.scripts['db:studio'] = 'npx prisma studio'; + pkg.dependencies = sortKeys({ + ...pkg.dependencies, + [GATEKEEPER_PACKAGE]: GATEKEEPER_VERSION, + }); } - - fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2)); + + fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n'); } - // Inject Gatekeeper into app.ts if (options.includeGatekeeper) { const appTsPath = path.join(targetDir, 'src', 'app.ts'); - if (fs.existsSync(appTsPath)) { - let appTs = fs.readFileSync(appTsPath, 'utf-8'); - appTs = appTs.replace( - "import { healthRoutes } from './modules/health/health.routes.js';", - "import { healthRoutes } from './modules/health/health.routes.js';\nimport gatekeeper from '@sibilsoren/gatekeeper';" - ); - appTs = appTs.replace( - "// ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);", - "// ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);\n\n // ─── Rate Limiting ────────────────────────────────────────\n app.use(gatekeeper({ limit: 100, window: 60 }));" - ); - fs.writeFileSync(appTsPath, appTs); - } + fs.writeFileSync( + appTsPath, + injectGatekeeper(fs.readFileSync(appTsPath, 'utf-8')), + ); } if (packageManager === 'pnpm') { @@ -167,17 +155,6 @@ export async function createProject(options: CreateOptions): Promise { printCommandOutput(error); log.warning(`Fix the error above, then run "${installCmd}" in the project directory.`); } - - if (options.includePrisma) { - log.step(++currentStep, totalSteps + 1, 'Initializing Prisma...'); - try { - const prismaCmd = packageManager === 'pnpm' ? 'pnpm dlx prisma init' : 'npx prisma init'; - execSync(prismaCmd, { cwd: targetDir, stdio: 'ignore' }); - log.success('Prisma initialized'); - } catch { - log.warning('Failed to initialize Prisma. Run "npx prisma init" manually.'); - } - } } // ─── Initial commit ───────────────────────────────────── @@ -223,6 +200,15 @@ export async function createProject(options: CreateOptions): Promise { log.blank(); } +/** + * Sort an object's keys, the way npm keeps dependency lists. + */ +function sortKeys(object: Record): Record { + return Object.fromEntries( + Object.entries(object).sort(([a], [b]) => a.localeCompare(b)), + ); +} + /** * Print the tail of a failed command's output, so the user sees why it failed. */ diff --git a/src/index.ts b/src/index.ts index ffd86ba..e722b9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ import * as p from '@clack/prompts'; import { createProject } from './create.js'; import type { CreateOptions } from './types.js'; import { log } from './utils/logger.js'; +import { validateProjectName } from './utils/validate.js'; import { PACKAGE_MANAGERS, isPackageManager } from './utils/package-manager.js'; // package.json sits one level up from both src/ and dist/. @@ -22,6 +23,8 @@ program .option('--skip-install', 'Skip installing dependencies', false) .option('--no-git', 'Skip git initialization') .option('--package-manager ', `Package manager to use (${PACKAGE_MANAGERS.join(', ')})`) + .option('--gatekeeper', 'Add Gatekeeper rate limiting (default)') + .option('--no-gatekeeper', 'Skip Gatekeeper rate limiting') .option('-y, --yes', 'Skip prompts and use defaults') .action(async (projectNameArg: string | undefined, opts: Record) => { console.log(); @@ -41,8 +44,7 @@ program skipInstall: opts.skipInstall as boolean, noGit: !opts.git, packageManager: isPackageManager(opts.packageManager) ? opts.packageManager : 'npm', - includeGatekeeper: false, - includePrisma: false, + includeGatekeeper: (opts.gatekeeper as boolean | undefined) ?? true, }; await createProject(options); return; @@ -58,21 +60,17 @@ program message: 'What is the name of your project?', placeholder: 'my-awesome-api', defaultValue: 'my-api', - validate: (val) => { - if (!val) return 'Project name is required'; - }, + // Empty means the default name; anything else must be a valid package name. + validate: (val) => (val ? validateProjectName(val).message : undefined), }); }, - includeGatekeeper: () => - p.confirm({ - message: 'Would you like to include Gatekeeper (Distributed Rate Limiter)?', + includeGatekeeper: () => { + if (opts.gatekeeper !== undefined) return Promise.resolve(opts.gatekeeper as boolean); + return p.confirm({ + message: 'Add rate limiting with Gatekeeper? (100 requests a minute per IP, easy to change)', initialValue: true, - }), - includePrisma: () => - p.confirm({ - message: 'Would you like to scaffold Prisma ORM?', - initialValue: true, - }), + }); + }, packageManager: () => { if (opts.packageManager) return Promise.resolve(opts.packageManager as string); return p.select({ @@ -96,7 +94,6 @@ program noGit: !opts.git, packageManager: isPackageManager(project.packageManager) ? project.packageManager : 'npm', includeGatekeeper: project.includeGatekeeper as boolean, - includePrisma: project.includePrisma as boolean, }; await createProject(options); diff --git a/src/types.ts b/src/types.ts index 8c674f3..5ee1766 100644 --- a/src/types.ts +++ b/src/types.ts @@ -11,6 +11,6 @@ export interface CreateOptions { packageManager: PackageManager; /** Include Gatekeeper rate limiter */ includeGatekeeper: boolean; - /** Include Prisma ORM */ - includePrisma: boolean; + /** Directory to create the project in (default: the current directory) */ + cwd?: string; } diff --git a/src/utils/gatekeeper.ts b/src/utils/gatekeeper.ts new file mode 100644 index 0000000..38462aa --- /dev/null +++ b/src/utils/gatekeeper.ts @@ -0,0 +1,36 @@ +export const GATEKEEPER_PACKAGE = '@sibilsoren/gatekeeper'; +export const GATEKEEPER_VERSION = '^2.0.0'; + +// Each anchor must match the template's src/app.ts exactly. +const IMPORT_ANCHOR = + "import { healthRoutes } from './modules/health/health.routes.js';"; +const MIDDLEWARE_ANCHOR = + ' // ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);\n'; + +const MIDDLEWARE = ` + // ─── Rate Limiting ──────────────────────────────────────── + // 100 requests per minute per client IP, counted in memory. Running more + // than one server? Share the count with a RedisStore: + // https://github.com/SibilSoren/gatekeeper#redis-store-distributed + app.use(gatekeeper({ limit: 100, window: '1m' })); +`; + +/** + * Add Gatekeeper rate limiting to the template's app.ts, right after request + * logging so rate-limited requests are still logged. Throws if the template + * no longer matches, so a template change can't silently skip it. + */ +export function injectGatekeeper(appTs: string): string { + for (const anchor of [IMPORT_ANCHOR, MIDDLEWARE_ANCHOR]) { + if (!appTs.includes(anchor)) { + throw new Error(`app.ts template changed; can't find: ${anchor}`); + } + } + + return appTs + .replace( + IMPORT_ANCHOR, + `${IMPORT_ANCHOR}\nimport { gatekeeper } from '${GATEKEEPER_PACKAGE}';`, + ) + .replace(MIDDLEWARE_ANCHOR, `${MIDDLEWARE_ANCHOR}${MIDDLEWARE}`); +} diff --git a/tests/create.test.ts b/tests/create.test.ts new file mode 100644 index 0000000..0cbb0d4 --- /dev/null +++ b/tests/create.test.ts @@ -0,0 +1,159 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { createProject } from '../src/create.js'; +import type { CreateOptions } from '../src/types.js'; + +/** + * Scaffolds real projects (without installing or git) for each combination + * of options, so a new option can't quietly change what the others generate. + */ + +const templateDir = new URL('../template/', import.meta.url); +const templateFile = (name: string) => + fs.readFileSync(new URL(name, templateDir), 'utf-8'); + +let workDir: string; + +beforeEach(() => { + workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cas-test-')); + vi.spyOn(console, 'log').mockImplementation(() => {}); +}); + +afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(workDir, { recursive: true, force: true }); +}); + +async function scaffold(overrides: Partial = {}) { + const options: CreateOptions = { + projectName: 'my-api', + skipInstall: true, + noGit: true, + packageManager: 'npm', + includeGatekeeper: false, + cwd: workDir, + ...overrides, + }; + await createProject(options); + + const dir = path.join(workDir, options.projectName); + const read = (name: string) => fs.readFileSync(path.join(dir, name), 'utf-8'); + const exists = (name: string) => fs.existsSync(path.join(dir, name)); + return { dir, read, exists, pkg: JSON.parse(read('package.json')) }; +} + +function allFiles(dir: string): string[] { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + return entry.isDirectory() ? allFiles(full) : [full]; + }); +} + +describe('createProject: no extras', () => { + it('copies the template unchanged apart from the project name', async () => { + const project = await scaffold(); + + expect(project.pkg.name).toBe('my-api'); + expect(project.read('src/app.ts')).toBe(templateFile('src/app.ts')); + expect(project.read('Dockerfile')).toBe(templateFile('Dockerfile')); + expect(project.pkg.dependencies).toEqual( + JSON.parse(templateFile('package.json')).dependencies, + ); + }); + + it('replaces every placeholder', async () => { + const project = await scaffold(); + + for (const file of allFiles(project.dir)) { + expect(fs.readFileSync(file, 'utf-8'), file).not.toContain( + '{{PROJECT_NAME}}', + ); + } + }); + + it('creates .gitignore, .env and the pre-commit hook', async () => { + const project = await scaffold(); + + expect(project.exists('.gitignore')).toBe(true); + expect(project.exists('_gitignore')).toBe(false); + expect(project.read('.env')).toBe(templateFile('.env.example')); + expect(project.read('.husky/pre-commit')).toContain('lint-staged'); + }); + + it('adds no pnpm files', async () => { + const project = await scaffold(); + + expect(project.exists('pnpm-workspace.yaml')).toBe(false); + expect(project.pkg.packageManager).toBeUndefined(); + }); +}); + +describe('createProject: --gatekeeper', () => { + it('adds the dependency and the middleware', async () => { + const project = await scaffold({ includeGatekeeper: true }); + + expect(project.pkg.dependencies['@sibilsoren/gatekeeper']).toBe('^2.0.0'); + expect(Object.keys(project.pkg.dependencies)).toEqual( + Object.keys(project.pkg.dependencies).sort(), + ); + expect(project.read('src/app.ts')).toContain( + "app.use(gatekeeper({ limit: 100, window: '1m' }));", + ); + }); + + it('changes nothing else', async () => { + const project = await scaffold({ includeGatekeeper: true }); + + expect(project.read('Dockerfile')).toBe(templateFile('Dockerfile')); + expect(project.read('README.md')).toBe( + templateFile('README.md').replaceAll('{{PROJECT_NAME}}', 'my-api'), + ); + }); +}); + +describe('createProject: --package-manager pnpm', () => { + it('adds pnpm settings and switches the Dockerfile and README', async () => { + const project = await scaffold({ packageManager: 'pnpm' }); + + expect(project.read('pnpm-workspace.yaml')).toContain('esbuild: true'); + expect(project.read('Dockerfile')).toContain('pnpm install --frozen-lockfile'); + expect(project.read('Dockerfile')).not.toContain('npm ci'); + expect(project.read('README.md')).toContain('pnpm dev'); + }); + + it('works together with --gatekeeper', async () => { + const project = await scaffold({ + packageManager: 'pnpm', + includeGatekeeper: true, + }); + + expect(project.pkg.dependencies['@sibilsoren/gatekeeper']).toBe('^2.0.0'); + expect(project.exists('pnpm-workspace.yaml')).toBe(true); + }); +}); + +describe('createProject: refuses bad input', () => { + beforeEach(() => { + vi.spyOn(process, 'exit').mockImplementation((code) => { + throw new Error(`process.exit(${code})`); + }); + }); + + it('rejects an invalid project name', async () => { + await expect(scaffold({ projectName: 'My API' })).rejects.toThrow( + 'process.exit(1)', + ); + }); + + it("doesn't overwrite a folder that isn't empty", async () => { + fs.mkdirSync(path.join(workDir, 'my-api')); + fs.writeFileSync(path.join(workDir, 'my-api', 'keep.txt'), 'mine'); + + await expect(scaffold()).rejects.toThrow('process.exit(1)'); + expect(fs.readFileSync(path.join(workDir, 'my-api', 'keep.txt'), 'utf-8')).toBe( + 'mine', + ); + }); +}); diff --git a/tests/gatekeeper.test.ts b/tests/gatekeeper.test.ts new file mode 100644 index 0000000..b300fff --- /dev/null +++ b/tests/gatekeeper.test.ts @@ -0,0 +1,31 @@ +import fs from 'node:fs'; +import { describe, it, expect } from 'vitest'; +import { injectGatekeeper } from '../src/utils/gatekeeper.js'; + +const templateAppTs = fs.readFileSync( + new URL('../template/src/app.ts', import.meta.url), + 'utf-8', +); + +describe('injectGatekeeper', () => { + it('imports gatekeeper by name and adds it after request logging', () => { + const appTs = injectGatekeeper(templateAppTs); + + expect(appTs).toContain( + "import { gatekeeper } from '@sibilsoren/gatekeeper';", + ); + expect(appTs).toContain("app.use(gatekeeper({ limit: 100, window: '1m' }));"); + expect(appTs.indexOf('app.use(requestLogger)')).toBeLessThan( + appTs.indexOf('app.use(gatekeeper('), + ); + expect(appTs.indexOf('app.use(gatekeeper(')).toBeLessThan( + appTs.indexOf("app.use('/api/health'"), + ); + }); + + it('fails loudly if the template no longer matches', () => { + expect(() => injectGatekeeper('export const app = 1;\n')).toThrow( + /app.ts template changed/, + ); + }); +});