# NPM Commands Reference Complete reference for all npm scripts in Changemaker Lite V2. ## Overview Changemaker Lite V2 uses npm scripts for development, building, testing, and database management. Scripts are defined in `package.json` files in two main directories: - **api/package.json** - Backend API scripts (Express + Fastify) - **admin/package.json** - Frontend GUI scripts (React + Vite) This guide documents all available scripts, their usage, and common combinations. ## API Scripts Location: `api/package.json` ### Development Scripts #### `npm run dev` Starts the Express API server in development mode with hot reload. ```bash cd api npm run dev ``` **What it does:** - Runs `tsx watch src/server.ts` - Auto-restarts on file changes (`.ts` files) - Loads environment from `.env` - Runs on port `API_PORT` (default: 4000) **Output:** ``` Server running on port 4000 Database connected Redis connected BullMQ worker started ``` **Use when:** - Developing API endpoints - Testing backend changes - Debugging server code #### `npm run dev:media` Starts the Fastify Media API server in development mode. ```bash cd api npm run dev:media ``` **What it does:** - Runs `tsx watch src/media-server.ts` - Auto-restarts on file changes - Runs on port `MEDIA_API_PORT` (default: 4100) **Output:** ``` Media API server running on port 4100 Database connected ``` **Use when:** - Developing media features (video upload, reactions) - Testing Media API endpoints - Working on FFprobe integration ### Build Scripts #### `npm run build` Compiles TypeScript to JavaScript for production. ```bash cd api npm run build ``` **What it does:** - Runs `tsc --build` - Outputs to `dist/` directory - Type-checks all code - Fails on type errors **Output:** ``` dist/ ├── server.js ├── media-server.js └── modules/ ├── auth/ ├── users/ └── ... ``` **Use when:** - Preparing for production deployment - Verifying build succeeds - Creating Docker images #### `npm run clean` Removes compiled JavaScript and build artifacts. ```bash cd api npm run clean ``` **What it does:** - Deletes `dist/` directory - Removes `*.tsbuildinfo` files **Use when:** - Starting fresh build - Fixing build cache issues - Cleaning up after development ### Production Scripts #### `npm start` Runs the compiled API server (production mode). ```bash cd api npm start ``` **What it does:** - Runs `node dist/server.js` - Requires `npm run build` first - Uses production environment (`NODE_ENV=production`) **Output:** ``` Server running on port 4000 Database connected Redis connected ``` **Use when:** - Running in production (Docker) - Testing production build locally #### `npm run start:media` Runs the compiled Media API server (production mode). ```bash cd api npm run start:media ``` **What it does:** - Runs `node dist/media-server.js` - Requires `npm run build` first **Use when:** - Running Media API in production - Testing production Media API ### Code Quality Scripts #### `npm run type-check` Type-checks TypeScript without emitting files. ```bash cd api npm run type-check ``` **What it does:** - Runs `tsc --noEmit` - Reports type errors - Does NOT generate files **Output:** ``` # Success (no output) # Errors src/modules/auth/auth.service.ts:45:12 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. ``` **Use when:** - Before committing code - In CI/CD pipeline - Debugging type errors #### `npm run lint` Runs ESLint to check code style. ```bash cd api npm run lint ``` **What it does:** - Runs `eslint src/ --ext .ts` - Reports style violations - Checks for common errors **Output:** ``` # Success ✔ 150 files linted, 0 errors, 0 warnings # Errors src/modules/auth/auth.service.ts 45:12 error 'foo' is assigned a value but never used @typescript-eslint/no-unused-vars ``` **Use when:** - Before committing code - Enforcing code style - Finding potential bugs #### `npm run lint:fix` Automatically fixes ESLint errors where possible. ```bash cd api npm run lint:fix ``` **What it does:** - Runs `eslint src/ --ext .ts --fix` - Auto-fixes style issues (formatting, imports, etc.) - Reports unfixable errors **Use when:** - After writing new code - Cleaning up formatting - Before commit #### `npm run format` Formats code with Prettier. ```bash cd api npm run format ``` **What it does:** - Runs `prettier --write "src/**/*.{ts,js,json}"` - Formats all TypeScript, JavaScript, and JSON files - Overwrites files in place **Use when:** - Standardizing code format - After merge conflicts - Team-wide formatting #### `npm run format:check` Checks if code is formatted correctly (CI). ```bash cd api npm run format:check ``` **What it does:** - Runs `prettier --check "src/**/*.{ts,js,json}"` - Reports unformatted files - Does NOT modify files **Use when:** - In CI/CD pipeline - Verifying format before commit ### Database Scripts #### `npm run prisma:migrate` Creates and applies a new Prisma migration. ```bash cd api npm run prisma:migrate # Or with name: npx prisma migrate dev --name add_user_field ``` **What it does:** - Prompts for migration name - Generates SQL migration in `prisma/migrations/` - Applies migration to development database - Regenerates Prisma Client **Output:** ``` ✔ Enter a name for the new migration: … add_user_field Applying migration `20260213000000_add_user_field` ✔ Generated Prisma Client to ./node_modules/@prisma/client ``` **Use when:** - Changing database schema - Adding new models - Modifying fields #### `npm run prisma:deploy` Applies pending migrations (production). ```bash cd api npm run prisma:deploy ``` **What it does:** - Runs `prisma migrate deploy` - Applies unapplied migrations only - Does NOT create new migrations - Safe for production **Output:** ``` Environment variables loaded from .env Datasource "db": PostgreSQL database "changemaker_v2_db" 2 migrations found in prisma/migrations Applying migration `20260213000000_add_user_field` All migrations have been successfully applied. ``` **Use when:** - Deploying to production - Applying migrations in Docker - CI/CD deployment #### `npm run prisma:seed` Seeds database with initial data. ```bash cd api npm run prisma:seed ``` **What it does:** - Runs `tsx prisma/seed.ts` - Creates admin user - Creates default settings - Creates sample blocks **Output:** ``` Running seed command `tsx prisma/seed.ts` ... Seeding database... Created default settings Created admin user: admin@example.com Created 10 sample blocks Seed completed successfully ``` **Use when:** - First-time setup - After reset - Populating test data #### `npm run prisma:studio` Opens Prisma Studio (database GUI). ```bash cd api npm run prisma:studio ``` **What it does:** - Runs `prisma studio` - Opens browser at http://localhost:5555 - Shows all tables and data - Allows CRUD operations **Use when:** - Inspecting database - Manual data editing - Debugging data issues #### `npm run prisma:reset` Resets database (DESTRUCTIVE). ```bash cd api npm run prisma:reset ``` **What it does:** - Drops all tables - Re-applies all migrations - Runs seed script - **DELETES ALL DATA** **Output:** ``` ⚠️ You are about to drop the database 'changemaker_v2_db' All data will be lost. Do you want to continue? [y/N]: y Database reset successful Migrations applied Seed completed ``` **Use when:** - Starting fresh in development - Fixing migration conflicts - **NEVER in production** #### `npm run prisma:validate` Validates Prisma schema. ```bash cd api npm run prisma:validate ``` **What it does:** - Runs `prisma validate` - Checks schema syntax - Verifies relations - Does NOT touch database **Output:** ``` # Success The schema is valid ✔ # Errors Error validating model "User": Field "foo" references unknown model "Bar" ``` **Use when:** - After editing schema - Before creating migration - In CI/CD pipeline #### `npm run drizzle:push` Pushes Drizzle schema changes to database (Media API). ```bash cd api npm run drizzle:push ``` **What it does:** - Runs `drizzle-kit push` - Syncs `src/modules/media/db/schema.ts` to database - Does NOT create migration files - Direct schema sync **Output:** ``` Reading config from drizzle.config.ts Pushing schema to database... ✔ Schema pushed successfully ``` **Use when:** - Changing Media API tables (videos, jobs, reactions) - Rapid prototyping (no migrations) - Development only #### `npm run drizzle:studio` Opens Drizzle Studio (database GUI for Media API). ```bash cd api npm run drizzle:studio ``` **What it does:** - Runs `drizzle-kit studio` - Opens browser at http://localhost:4983 - Shows Media API tables only **Use when:** - Inspecting media tables - Debugging video data - Manual media data editing ### Testing Scripts #### `npm test` Runs all tests (when configured). ```bash cd api npm test ``` **What it does:** - Runs Jest test suite - Executes `*.test.ts` files - Reports pass/fail **Note:** Tests are part of Phase 15 (in progress). #### `npm run test:watch` Runs tests in watch mode. ```bash cd api npm run test:watch ``` **What it does:** - Runs `jest --watch` - Re-runs tests on file changes #### `npm run test:coverage` Runs tests with coverage report. ```bash cd api npm run test:coverage ``` **What it does:** - Runs `jest --coverage` - Generates coverage report in `coverage/` ### Utility Scripts #### `npm run env:validate` Validates required environment variables. ```bash cd api npm run env:validate ``` **What it does:** - Checks `.env` has required vars - Uses Zod validation (from `config/env.ts`) - Fails if vars missing/invalid **Output:** ``` # Success ✔ Environment variables valid # Errors Error: Missing required environment variables: - JWT_ACCESS_SECRET - REDIS_PASSWORD ``` **Use when:** - After editing .env - Before deployment - Debugging config issues ## Admin Scripts Location: `admin/package.json` ### Development Scripts #### `npm run dev` Starts Vite development server with HMR. ```bash cd admin npm run dev ``` **What it does:** - Runs `vite` - Starts dev server on port `ADMIN_PORT` (default: 3000) - Enables Hot Module Replacement (HMR) - Proxies API requests to `VITE_API_URL` **Output:** ``` VITE v5.x.x ready in 500 ms ➜ Local: http://localhost:3000/ ➜ Network: use --host to expose ``` **Use when:** - Developing frontend components - Testing UI changes - Working on React code ### Build Scripts #### `npm run build` Builds production-optimized bundle. ```bash cd admin npm run build ``` **What it does:** - Runs `tsc --noEmit && vite build` - Type-checks TypeScript - Bundles JavaScript/CSS - Optimizes assets (minify, tree-shake) - Outputs to `dist/` **Output:** ``` vite v5.x.x building for production... ✓ 1245 modules transformed. dist/index.html 0.45 kB dist/assets/index-a1b2c3d4.js 245.67 kB │ gzip: 78.23 kB dist/assets/index-e5f6g7h8.css 12.34 kB │ gzip: 3.45 kB ✓ built in 15.23s ``` **Use when:** - Preparing for production deployment - Creating Docker image - Verifying build size #### `npm run preview` Previews production build locally. ```bash cd admin npm run preview ``` **What it does:** - Runs `vite preview` - Serves `dist/` directory - Runs on port 4173 (Vite default) **Output:** ``` ➜ Local: http://localhost:4173/ ➜ Network: use --host to expose ``` **Use when:** - Testing production build - Verifying optimizations - Before deployment ### Code Quality Scripts #### `npm run type-check` Type-checks TypeScript without emitting files. ```bash cd admin npm run type-check ``` **What it does:** - Runs `tsc --noEmit` - Reports type errors - Checks all `.ts` and `.tsx` files **Output:** ``` # Success (no output) # Errors src/pages/UsersPage.tsx:123:45 - error TS2339: Property 'foo' does not exist on type 'User'. ``` **Use when:** - Before committing code - In CI/CD pipeline - Debugging type errors #### `npm run lint` Runs ESLint to check code style. ```bash cd admin npm run lint ``` **What it does:** - Runs `eslint src/ --ext .ts,.tsx` - Reports style violations - Checks React best practices **Output:** ``` # Success ✔ 85 files linted, 0 errors, 0 warnings # Errors src/pages/UsersPage.tsx 123:45 error 'foo' is assigned a value but never used @typescript-eslint/no-unused-vars 200:10 warning Missing dependency in useEffect react-hooks/exhaustive-deps ``` **Use when:** - Before committing code - Enforcing code style - Finding potential bugs #### `npm run lint:fix` Automatically fixes ESLint errors where possible. ```bash cd admin npm run lint:fix ``` **What it does:** - Runs `eslint src/ --ext .ts,.tsx --fix` - Auto-fixes style issues - Reports unfixable errors **Use when:** - After writing new code - Cleaning up formatting - Before commit #### `npm run format` Formats code with Prettier. ```bash cd admin npm run format ``` **What it does:** - Runs `prettier --write "src/**/*.{ts,tsx,css,json}"` - Formats all source files - Overwrites files in place **Use when:** - Standardizing code format - After merge conflicts - Team-wide formatting #### `npm run format:check` Checks if code is formatted correctly (CI). ```bash cd admin npm run format:check ``` **What it does:** - Runs `prettier --check "src/**/*.{ts,tsx,css,json}"` - Reports unformatted files - Does NOT modify files **Use when:** - In CI/CD pipeline - Verifying format before commit ### Testing Scripts #### `npm test` Runs all tests (when configured). ```bash cd admin npm test ``` **What it does:** - Runs Vitest test suite - Executes `*.test.tsx` and `*.spec.tsx` files - Reports pass/fail **Note:** Tests are part of Phase 15 (in progress). #### `npm run test:watch` Runs tests in watch mode. ```bash cd admin npm run test:watch ``` **What it does:** - Runs `vitest` - Re-runs tests on file changes #### `npm run test:ui` Runs tests with UI (Vitest UI). ```bash cd admin npm run test:ui ``` **What it does:** - Runs `vitest --ui` - Opens browser with test UI - Shows test results visually #### `npm run test:coverage` Runs tests with coverage report. ```bash cd admin npm run test:coverage ``` **What it does:** - Runs `vitest --coverage` - Generates coverage report in `coverage/` ### Utility Scripts #### `npm run clean` Removes build artifacts and cache. ```bash cd admin npm run clean ``` **What it does:** - Deletes `dist/` directory - Removes `node_modules/.vite/` cache - Removes `tsconfig.tsbuildinfo` **Use when:** - Starting fresh build - Fixing build cache issues - Cleaning up after development ## Docker Commands When running services in Docker, use `docker compose exec` to run npm scripts: ### API in Docker ```bash # Development server (already running via docker compose up) docker compose logs -f api # Type-check docker compose exec api npm run type-check # Prisma migrate docker compose exec api npx prisma migrate dev --name add_field # Prisma Studio docker compose exec api npx prisma studio # Prisma seed docker compose exec api npx prisma db seed # Drizzle push (Media API) docker compose exec api npx drizzle-kit push # Lint docker compose exec api npm run lint # Format docker compose exec api npm run format ``` ### Admin in Docker ```bash # Development server (already running via docker compose up) docker compose logs -f admin # Type-check docker compose exec admin npm run type-check # Lint docker compose exec admin npm run lint # Build docker compose exec admin npm run build ``` ### Rebuild Containers ```bash # Rebuild after package.json changes docker compose build --no-cache api admin # Restart services docker compose restart api admin ``` ## Script Chaining ### Sequential Execution (&&) Run scripts in sequence, stop on first failure: ```bash # Type-check, then build cd api npm run type-check && npm run build # Lint, format, type-check cd admin npm run lint && npm run format && npm run type-check # Full quality check before commit cd api npm run lint:fix && npm run format && npm run type-check && npm test ``` ### Parallel Execution (npm-run-all) Install `npm-run-all` for parallel script execution: ```bash # Install (project root) npm install --save-dev npm-run-all # Add to package.json { "scripts": { "check": "npm-run-all --parallel type-check lint test" } } # Run all checks in parallel npm run check ``` ### Pre/Post Hooks npm automatically runs `pre*` and `post*` scripts: ```bash # package.json { "scripts": { "prebuild": "npm run clean", "build": "tsc --build", "postbuild": "npm run copy-assets" } } # Running npm run build executes: # 1. npm run prebuild (clean) # 2. npm run build (tsc) # 3. npm run postbuild (copy-assets) ``` ## Common Script Combinations ### Full Development Setup ```bash # 1. Install dependencies cd api && npm install && cd .. cd admin && npm install && cd .. # 2. Setup database cd api npx prisma migrate deploy npx prisma db seed cd .. # 3. Start development servers # Option A: Docker docker compose up -d api admin # Option B: Local cd api && npm run dev # Terminal 1 cd admin && npm run dev # Terminal 2 ``` ### Pre-Commit Quality Check ```bash # API quality check cd api npm run lint:fix npm run format npm run type-check # npm test # When tests available cd .. # Admin quality check cd admin npm run lint:fix npm run format npm run type-check # npm test # When tests available cd .. # Commit if all pass git add . git commit -m "feat: add new feature" ``` ### Production Build ```bash # Build API cd api npm run clean npm run build cd .. # Build Admin cd admin npm run clean npm run build cd .. # Build Docker images docker compose build api admin # Start production services docker compose -f docker-compose.yml up -d api admin ``` ### Database Migration Workflow ```bash # 1. Edit schema cd api vi prisma/schema.prisma # 2. Validate schema npx prisma validate # 3. Create migration npx prisma migrate dev --name add_user_field # 4. Verify migration SQL cat prisma/migrations/20260213000000_add_user_field/migration.sql # 5. Test on clean database npx prisma migrate reset # WARNING: Deletes data npx prisma migrate deploy npx prisma db seed # 6. Commit migration git add prisma/migrations/ prisma/schema.prisma git commit -m "feat(db): add field to User model" ``` ### Database Inspection ```bash # Prisma Studio (main API) cd api npx prisma studio # Open http://localhost:5555 # Drizzle Studio (Media API) cd api npx drizzle-kit studio # Open http://localhost:4983 # Direct PostgreSQL query docker compose exec v2-postgres psql -U changemaker_v2 -d changemaker_v2_db # Run SQL queries ``` ### Full Type Check ```bash # Type-check both projects cd api && npx tsc --noEmit && cd .. cd admin && npx tsc --noEmit && cd .. # Or create root script (package.json in project root) { "scripts": { "type-check": "cd api && npm run type-check && cd ../admin && npm run type-check" } } # Run from root npm run type-check ``` ## CI/CD Integration ### GitHub Actions Example ```yaml name: CI on: [push, pull_request] jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '20' - name: Install dependencies working-directory: ./api run: npm ci - name: Type check working-directory: ./api run: npm run type-check - name: Lint working-directory: ./api run: npm run lint - name: Format check working-directory: ./api run: npm run format:check - name: Test working-directory: ./api run: npm test - name: Build working-directory: ./api run: npm run build admin: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '20' - name: Install dependencies working-directory: ./admin run: npm ci - name: Type check working-directory: ./admin run: npm run type-check - name: Lint working-directory: ./admin run: npm run lint - name: Format check working-directory: ./admin run: npm run format:check - name: Test working-directory: ./admin run: npm test - name: Build working-directory: ./admin run: npm run build ``` ## Troubleshooting ### Script Not Found **Problem:** ``` npm ERR! missing script: dev ``` **Solution:** - Check `package.json` has the script defined - Verify you're in correct directory (`api/` or `admin/`) - Run `npm install` to ensure dependencies installed ### Permission Errors **Problem:** ``` Error: EACCES: permission denied ``` **Solution:** - Don't use `sudo npm` (creates permission issues) - Fix npm permissions: `sudo chown -R $(whoami) ~/.npm` - Or use nvm for user-level Node.js installation ### Port Already in Use **Problem:** ``` Error: listen EADDRINUSE: address already in use :::4000 ``` **Solution:** - Find and kill process using port: `lsof -ti:4000 | xargs kill -9` - Or change port in `.env`: `API_PORT=4002` - Or use Docker (isolated ports) ### TypeScript Errors on Build **Problem:** ``` src/modules/auth/auth.service.ts:45:12 - error TS2339 ``` **Solution:** - Fix type errors in code - Or check `tsconfig.json` is correct - Or update type definitions: `npm install --save-dev @types/node@latest` ### Prisma Migration Conflicts **Problem:** ``` Error: P3005 The database schema is not in sync with the migration history ``` **Solution:** - Development: `npx prisma migrate reset` (DELETES DATA) - Production: `npx prisma migrate resolve --applied ` - Or create new migration to fix state ### npm install Failures **Problem:** ``` npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree ``` **Solution:** - Clear cache: `npm cache clean --force` - Delete and reinstall: `rm -rf node_modules package-lock.json && npm install` - Use `--legacy-peer-deps` flag: `npm install --legacy-peer-deps` ### Vite Build Errors **Problem:** ``` Error: Could not resolve entry module (index.html) ``` **Solution:** - Ensure `index.html` exists in `admin/` - Check `vite.config.ts` has correct root - Clear cache: `rm -rf node_modules/.vite && npm run dev` ## Best Practices ### Script Naming Conventions - **dev** - Development mode with hot reload - **build** - Production build - **start** - Run production build - **test** - Run tests - **lint** - Check code style - **lint:fix** - Auto-fix code style - **format** - Format code - **type-check** - TypeScript validation - **clean** - Remove build artifacts ### Script Organization Group related scripts: ```json { "scripts": { // Development "dev": "tsx watch src/server.ts", "dev:media": "tsx watch src/media-server.ts", // Build "build": "tsc --build", "clean": "rm -rf dist", // Quality "type-check": "tsc --noEmit", "lint": "eslint src/ --ext .ts", "lint:fix": "eslint src/ --ext .ts --fix", "format": "prettier --write \"src/**/*.ts\"", // Database "prisma:migrate": "prisma migrate dev", "prisma:deploy": "prisma migrate deploy", "prisma:seed": "tsx prisma/seed.ts" } } ``` ### Environment-Specific Scripts Use cross-env for environment variables: ```bash npm install --save-dev cross-env ``` ```json { "scripts": { "dev": "cross-env NODE_ENV=development tsx watch src/server.ts", "build": "cross-env NODE_ENV=production tsc --build", "test": "cross-env NODE_ENV=test jest" } } ``` ### Script Documentation Add comments in package.json: ```json { "scripts": { "// Development": "", "dev": "tsx watch src/server.ts", "// Build": "", "build": "tsc --build", "// Quality": "", "type-check": "tsc --noEmit" } } ``` ## Quick Reference ### API Scripts ```bash npm run dev # Dev server (port 4000) npm run dev:media # Media API dev (port 4100) npm run build # Build for production npm start # Run production server npm run type-check # TypeScript validation npm run lint # ESLint check npm run lint:fix # ESLint auto-fix npm run format # Prettier format npx prisma migrate dev # Create migration npx prisma migrate deploy # Apply migrations npx prisma db seed # Seed database npx prisma studio # Database GUI npx drizzle-kit push # Push Media schema ``` ### Admin Scripts ```bash npm run dev # Dev server (port 3000) npm run build # Build for production npm run preview # Preview production build npm run type-check # TypeScript validation npm run lint # ESLint check npm run lint:fix # ESLint auto-fix npm run format # Prettier format npm test # Run tests npm run test:ui # Test UI ``` ### Docker Scripts ```bash docker compose exec api npm run type-check docker compose exec api npx prisma migrate dev docker compose exec admin npm run lint docker compose build --no-cache api admin ``` ## Related Documentation - **Setup:** [Local Development Setup](local-setup.md) - **Workflow:** [Docker Workflow](docker-workflow.md) - **Database:** [Migrations Guide](migrations.md) - **Testing:** [Testing Guide](testing.md) - **Code Style:** [Code Style Guide](code-style.md) - **Debugging:** [Debugging Guide](debugging.md) ## Summary You now know: - ✅ All available npm scripts in API and Admin - ✅ What each script does and when to use it - ✅ How to run scripts in Docker containers - ✅ How to chain scripts together - ✅ Common script combinations for workflows - ✅ How to troubleshoot script errors - ✅ Best practices for script organization **Quick Start:** ```bash # Development cd api && npm run dev cd admin && npm run dev # Pre-commit cd api && npm run lint:fix && npm run type-check cd admin && npm run lint:fix && npm run type-check # Production build cd api && npm run build cd admin && npm run build ```