All files / cli/src/generators project-scaffold.js

78.86% Statements 97/123
85.71% Branches 66/77
100% Functions 7/7
78.86% Lines 97/123

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565                                5x                                   46x   46x 46x     46x                   46x 14x   46x 20x   46x 9x 2x     7x     46x       46x 359x     46x     46x 46x   46x     46x 2x 2x   44x 44x     46x     46x           46x   46x     46x   46x     46x 20x 20x 20x 20x     20x                                         20x 20x       20x 20x         20x       46x 9x     9x 9x     9x     9x 9x 9x     9x 9x 9x 9x             9x       46x 5x   5x 5x 5x 5x         46x     46x                                         46x                             46x   46x 46x   46x                                                     46x 2x 2x 2x     2x           46x   46x         46x 46x     46x 20x 20x       46x 9x 9x       46x 5x 5x     46x             46x                                                                                                                                                                     46x     46x                                                                       46x               46x                                                                                     46x     46x                                                                                                                 46x     46x                               46x    
/**
 * Project scaffolding generator
 */
 
import { writeFileSync, mkdirSync, copyFileSync, constants, readFileSync, appendFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import { getCLIVersion } from '../utils/version.js';
import { generateServerFile, getRuntimeDependencies } from './runtime-scaffold.js';
import { generateDatabaseScaffolding } from './database-scaffold.js';
import { generateAuthScaffolding } from './auth-scaffold.js';
import { generateDockerScaffolding, generateHealthCheck } from './docker-scaffold.js';
import { generatePackageScaffolding } from './package-scaffold.js';
import { generateTsConfig, generateJsConfig, getTypeScriptDependencies } from './typescript-config.js';
 
// Get current CLI version automatically
const cliVersion = getCLIVersion();
 
/**
 * Scaffold a new Coherent.js project
 */
export async function scaffoldProject(projectPath, options) {
  const {
    name,
    template,
    skipInstall,
    skipGit,
    runtime = 'built-in',
    database = null,
    auth = null,
    packages = [],
    language = 'javascript',
    packageManager = 'npm',
    onProgress = () => {}
  } = options;
 
  const isTypeScript = language === 'typescript';
  const fileExtension = isTypeScript ? '.ts' : '.js';
 
  // Create directory structure
  const dirs = [
    'src',
    'src/components',
    'src/pages',
    'src/utils',
    'public',
    'tests'
  ];
 
  // Add directories based on selections
  if (packages.includes('api') || auth) {
    dirs.push('src/api');
  }
  if (database) {
    dirs.push('src/db', 'src/db/models', 'data');
  }
  if (auth) {
    if (runtime === 'fastify') {
      dirs.push('src/plugins');
    } else {
      // For built-in, express, and koa
      dirs.push('src/middleware');
    }
  }
  Iif (packages.includes('i18n')) {
    dirs.push('src/i18n', 'src/i18n/locales');
  }
 
  dirs.forEach(dir => {
    mkdirSync(join(projectPath, dir), { recursive: true });
  });
 
  onProgress('Created project structure');
 
  // Generate package.json
  const packageJson = generatePackageJson(name, { template, runtime, database, auth, packages, language, packageManager });
  writeFileSync(join(projectPath, 'package.json'), JSON.stringify(packageJson, null, 2));
 
  onProgress('Generated package.json');
 
  // Generate TypeScript or JavaScript config
  if (isTypeScript) {
    const tsConfig = generateTsConfig();
    writeFileSync(join(projectPath, 'tsconfig.json'), JSON.stringify(tsConfig, null, 2));
  } else {
    const jsConfig = generateJsConfig();
    writeFileSync(join(projectPath, 'jsconfig.json'), JSON.stringify(jsConfig, null, 2));
  }
 
  onProgress('Created configuration files');
 
  // Generate main server file
  const serverContent = generateServerFile(runtime, {
    port: 3000,
    hasApi: packages.includes('api') || auth,
    hasDatabase: !!database,
    hasAuth: !!auth
  });
  writeFileSync(join(projectPath, `src/index${fileExtension}`), serverContent);
 
  onProgress('Set up server');
 
  // Generate HomePage component
  await generateHomePageComponent(projectPath, name, isTypeScript, fileExtension);
 
  onProgress('Created components');
 
  // Generate database scaffolding
  if (database) {
    const dbScaffolding = generateDatabaseScaffolding(database, language);
    writeFileSync(join(projectPath, `src/db/config${fileExtension}`), dbScaffolding.config);
    writeFileSync(join(projectPath, `src/db/index${fileExtension}`), dbScaffolding.init);
    writeFileSync(join(projectPath, `src/db/models/User${fileExtension}`), dbScaffolding.model);
 
    // Generate Docker configuration if requested
    Iif (options.dockerConfig && database !== 'sqlite') {
      const dockerScaffolding = generateDockerScaffolding(database, options.dockerConfig);
 
      // Write Docker files
      writeFileSync(join(projectPath, 'docker-compose.yml'), dockerScaffolding['docker-compose.yml']);
      writeFileSync(join(projectPath, 'Dockerfile'), dockerScaffolding['Dockerfile']);
      writeFileSync(join(projectPath, '.dockerignore'), dockerScaffolding['.dockerignore']);
 
      // Generate health check script
      writeFileSync(join(projectPath, `healthcheck${fileExtension}`), generateHealthCheck());
 
      // Update .env.example with Docker configuration
      let envContent = '';
      for (const [key, value] of Object.entries(dockerScaffolding.envConfig)) {
        envContent += `${key}=${value}\n`;
      }
      writeFileSync(join(projectPath, '.env.example'), envContent);
 
      onProgress('Created Docker configuration');
    } else {
      // Generate or update .env.example without Docker
      const existingEnv = '';
      writeFileSync(join(projectPath, '.env.example'), existingEnv + dbScaffolding.env);
    }
 
    // Create .env from .env.example if it doesn't exist
    try {
      copyFileSync(join(projectPath, '.env.example'), join(projectPath, '.env'), constants.COPYFILE_EXCL);
    } catch {
      // Ignore if .env already exists
    }
 
    onProgress('Configured database');
  }
 
  // Generate auth scaffolding
  if (auth) {
    const authScaffolding = generateAuthScaffolding(auth, runtime);
 
    // Write auth middleware/plugin
    const authDir = runtime === 'fastify' ? 'plugins' : 'middleware';
    writeFileSync(join(projectPath, `src/${authDir}/auth${fileExtension}`), authScaffolding.middleware);
 
    // Write auth routes
    writeFileSync(join(projectPath, `src/api/auth${fileExtension}`), authScaffolding.routes);
 
    // Append to .env.example
    const envPath = join(projectPath, '.env.example');
    const existingEnv = '';
    writeFileSync(envPath, existingEnv + authScaffolding.env);
 
    // Update .env if it exists
    try {
      const envContent = readFileSync(join(projectPath, '.env'), 'utf8');
      Eif (!envContent.includes('JWT_SECRET') && !envContent.includes('SESSION_SECRET')) {
        appendFileSync(join(projectPath, '.env'), authScaffolding.env);
      }
    } catch {
      // .env might not exist if database wasn't selected first, create it
      writeFileSync(join(projectPath, '.env'), authScaffolding.env);
    }
 
    onProgress('Set up authentication');
  }
 
  // Generate optional package scaffolding
  if (packages.length > 0) {
    const { files } = generatePackageScaffolding(packages);
 
    Object.entries(files).forEach(([filePath, content]) => {
      const fullPath = join(projectPath, filePath);
      mkdirSync(dirname(fullPath), { recursive: true });
      writeFileSync(fullPath, content);
    });
  }
 
  // Generate common files
  generateCommonFiles(projectPath, name);
 
  // Install dependencies
  Iif (!skipInstall) {
    console.log(`📦 Installing dependencies with ${packageManager}...`);
    try {
      const installCommands = {
        npm: 'npm install',
        yarn: 'yarn install',
        pnpm: 'pnpm install'
      };
 
      const installCmd = installCommands[packageManager] || 'npm install';
 
      execSync(installCmd, {
        cwd: projectPath,
        stdio: 'inherit'
      });
    } catch {
      console.warn(`⚠️  Failed to install dependencies with ${packageManager}`);
    }
  }
 
  // Initialize git
  Iif (!skipGit) {
    try {
      execSync('git init', { cwd: projectPath, stdio: 'pipe' });
      execSync('git add .', { cwd: projectPath, stdio: 'pipe' });
      execSync('git commit -m "Initial commit"', { cwd: projectPath, stdio: 'pipe' });
    } catch {
      console.warn('⚠️  Failed to initialize git repository');
    }
  }
}
 
/**
 * Generate package.json based on options
 */
function generatePackageJson(name, options) {
  const { runtime = 'built-in', database = null, auth = null, packages = [], language = 'javascript', packageManager = 'npm' } = options;
 
  const isTypeScript = language === 'typescript';
  const fileExt = isTypeScript ? '.ts' : '.js';
 
  const base = {
    name,
    version: '1.0.0',
    description: 'A Coherent.js application',
    type: 'module',
    main: isTypeScript ? 'dist/index.js' : `src/index${fileExt}`,
    scripts: isTypeScript ? {
      dev: 'tsx watch src/index.ts',
      build: 'tsc',
      start: 'node dist/index.js',
      typecheck: 'tsc --noEmit',
      test: 'tsx tests/*.test.ts'
    } : {
      dev: 'node src/index.js',
      build: 'coherent build',
      start: 'node src/index.js',
      test: 'node --test tests/*.test.js'
    },
    dependencies: {
      '@coherent.js/core': `^${cliVersion}`
    },
    devDependencies: {
      '@coherent.js/cli': `^${cliVersion}`
    }
  };
 
  // Add TypeScript dependencies
  if (isTypeScript) {
    const tsDeps = getTypeScriptDependencies();
    Object.assign(base.devDependencies, tsDeps);
    base.devDependencies.tsx = '^4.19.2'; // For running TypeScript files directly
 
    // Add @types for auth packages if auth is enabled
    Iif (auth) {
      base.devDependencies['@types/jsonwebtoken'] = '^9.0.7';
    }
  }
 
  // Add packageManager field (Corepack standard)
  Iif (packageManager === 'pnpm') {
    base.packageManager = 'pnpm@9.0.0';
  } else Iif (packageManager === 'yarn') {
    base.packageManager = 'yarn@4.0.0';
  }
 
  // Runtime dependencies
  const runtimeDeps = getRuntimeDependencies(runtime);
  Object.assign(base.dependencies, runtimeDeps);
 
  // Database dependencies
  if (database) {
    const { dependencies: dbDeps } = generateDatabaseScaffolding(database, language);
    Object.assign(base.dependencies, dbDeps);
  }
 
  // Auth dependencies
  if (auth) {
    const { dependencies: authDeps } = generateAuthScaffolding(auth, runtime);
    Object.assign(base.dependencies, authDeps);
  }
 
  // Optional package dependencies
  if (packages.length > 0) {
    const { dependencies: pkgDeps } = generatePackageScaffolding(packages);
    Object.assign(base.dependencies, pkgDeps);
  }
 
  return base;
}
 
/**
 * Generate HomePage component
 */
async function generateHomePageComponent(projectPath, name, isTypeScript, fileExtension) {
  const homePage = isTypeScript ? `/**
 * HomePage Component
 */
interface HomePageProps {
  title?: string;
}
 
export function HomePage(props: HomePageProps = {}): object {
  const { title = 'Welcome to ${name}!' } = props;
 
  return {
    div: {
      className: 'container',
      children: [
        { h1: { text: title } },
        {
          p: {
            text: 'This is a Coherent.js application built with pure JavaScript objects.'
          }
        },
        {
          div: {
            className: 'features',
            children: [
              { h2: { text: 'Features:' } },
              {
                ul: {
                  children: [
                    { li: { text: '⚡ Lightning fast SSR' } },
                    { li: { text: '🎯 Pure JavaScript objects' } },
                    { li: { text: '🔒 Built-in XSS protection' } },
                    { li: { text: '📦 Minimal bundle size' } },
                    { li: { text: '📘 TypeScript support' } }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  };
}
` : `/**
 * HomePage Component
 */
export function HomePage(props = {}) {
  const { title = 'Welcome to ${name}!' } = props;
 
  return {
    div: {
      className: 'container',
      children: [
        { h1: { text: title } },
        {
          p: {
            text: 'This is a Coherent.js application built with pure JavaScript objects.'
          }
        },
        {
          div: {
            className: 'features',
            children: [
              { h2: { text: 'Features:' } },
              {
                ul: {
                  children: [
                    { li: { text: '⚡ Lightning fast SSR' } },
                    { li: { text: '🎯 Pure JavaScript objects' } },
                    { li: { text: '🔒 Built-in XSS protection' } },
                    { li: { text: '📦 Minimal bundle size' } }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  };
}
`;
 
  writeFileSync(join(projectPath, `src/components/HomePage${fileExtension}`), homePage);
 
  // Simple Button component example
  const buttonComponent = isTypeScript ? `/**
 * Button Component
 */
interface ButtonProps {
  text?: string;
  onClick?: () => void;
  className?: string;
}
 
export function Button(props: ButtonProps = {}): object {
  const { text = 'Click me', onClick, className = '' } = props;
 
  return {
    button: {
      className: \`btn \${className}\`,
      onclick: onClick,
      text
    }
  };
}
` : `/**
 * Button Component
 */
export function Button(props = {}) {
  const { text = 'Click me', onClick, className = '' } = props;
 
  return {
    button: {
      className: \`btn \${className}\`,
      onclick: onClick,
      text
    }
  };
}
`;
 
  writeFileSync(join(projectPath, `src/components/Button${fileExtension}`), buttonComponent);
}
 
/**
 * Generate common files (README, gitignore, etc.)
 */
function generateCommonFiles(projectPath, name) {
  // README.md
  const readme = `# ${name}
 
A Coherent.js application built with pure JavaScript objects.
 
## Getting Started
 
\`\`\`bash
# Install dependencies
pnpm install
 
# Start development server
pnpm run dev
 
# Build for production
pnpm run build
 
# Run tests
pnpm test
\`\`\`
 
## Project Structure
 
\`\`\`
src/
  components/     # Reusable components
  pages/         # Page components
  api/           # API routes
  utils/         # Utility functions
  index.js       # Main entry point
public/          # Static assets
tests/           # Test files
\`\`\`
 
## Learn More
 
- [Coherent.js Documentation](https://github.com/Tomdrouv1/coherent.js)
- [API Reference](https://github.com/Tomdrouv1/coherent.js/tree/main/docs/api-reference.md)
 
## License
 
MIT
`;
 
  writeFileSync(join(projectPath, 'README.md'), readme);
 
  // .gitignore
  const gitignore = `# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-_error.log*
 
# Production builds
dist/
build/
 
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
 
# Runtime data
pids
*.pid
*.seed
*.pid.lock
 
# Coverage directory used by tools like istanbul
coverage/
*.lcov
 
# nyc test coverage
.nyc_output
 
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
 
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
 
# Logs
logs
*.log
 
# Optional npm cache directory
.npm
 
# Optional REPL history
.node_repl_history
`;
 
  writeFileSync(join(projectPath, '.gitignore'), gitignore);
 
  // Basic test file
  const testFile = `import { describe, it, expect } from 'vitest';
import { render } from '@coherent.js/core';
 
describe('Basic Component Rendering', () => {
  it('renders basic component', () => {
    const component = {
      div: {
        text: 'Hello, World!'
      }
    };
 
    const html = render(component);
    expect(html).toContain('Hello, World!');
  });
});`;
 
  writeFileSync(join(projectPath, 'tests/basic.test.js'), testFile);
}