All files / bin/commands init.js

95.07% Statements 328/345
72.41% Branches 21/29
100% Functions 2/2
95.07% Lines 328/345

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 346418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 418x 80x 80x 80x 80x 80x 10x 10x 10x 10x 1x 1x 10x     10x 80x 80x             80x 418x 418x 418x 418x 418x 418x 418x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 1x 1x 1x     1x 80x 80x 80x 80x 80x 80x 80x 80x   80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 480x 480x 480x 474x 474x 80x 80x 80x 80x 80x 79x 79x 79x 79x 80x 80x 80x 80x 80x 80x 79x 79x 79x 79x 80x 80x 80x 79x 79x 79x 79x 80x 80x 80x 80x 79x 79x 79x 80x 80x 80x 80x 79x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 79x 75x 75x 75x 75x 75x 79x 79x 80x 80x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 80x 80x 80x 80x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 80x 1x 1x 1x         1x     1x 80x 80x 80x 80x 80x 78x 78x 78x 80x 80x 80x 80x 79x 79x 79x 79x 79x 79x 80x 80x 80x 80x 80x 80x 4x 4x 80x  
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { readTemplate } from '../utils.js';
import { runWizard } from '../wizard.js';
import { getInitialHtml } from './serve.js';
import { bold, cyan, green, red, gray } from '../colors.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json'), 'utf8'));
 
/**
 * Stops `avenx init` from silently ignoring an argument it does not use.
 *
 * `init` scaffolds into the current working directory, as the CLI reference
 * states. It also accepted and discarded any other word on the command line, so
 * `avenx init my-app` -- which the routing tutorial documented, and which is
 * what every other scaffolder in the ecosystem means -- scattered a project
 * across whatever directory the user happened to be in and exited 0. The next
 * documented step, `cd my-app`, then failed with no explanation of why.
 *
 * Refusing is the honest answer: creating the directory instead would be a new
 * behaviour, and guessing which the user meant after the files are already
 * written is worse than not starting.
 * @param {string[]} args - The arguments passed after `init`.
 * @returns {void}
 * @throws {never} Exits the process with code 1 when an argument is unexpected.
 */
function rejectUnexpectedArguments(args) {
  const flagsWithValues = ['--layout', '--style'];
  const unexpected = [];
 
  for (let i = 0; i < (args || []).length; i++) {
    const arg = args[i];
    if (arg.startsWith('-')) {
      // If it is a flag that takes a value in the next argument, skip the next argument.
      if (flagsWithValues.includes(arg)) {
        i++;
      }
    } else {
      unexpected.push(arg);
    }
  }
 
  if (unexpected.length === 0) return;

  const name = unexpected[0];
  console.error(red(`avenx init does not take a project name (got "${name}").`));
  console.error(gray('It scaffolds into the current directory. To create a new one:'));
  console.error(gray(`  mkdir ${name} && cd ${name} && npx avenx init`));
  process.exit(1);
}
 
/**
 * Initializes a new Avenx project structure.
 * @param {object} cli - AvenxCLI instance.
 * @param {string[]} [args] - CLI arguments.
 */
export async function initProject(cli, args = []) {
  rejectUnexpectedArguments(args);
 
  const { stylePreprocessor, layoutTemplate, isInteractive } = await runWizard(args);
 
  console.log(
    bold(cyan(`🚀 Initializing new Avenx-JS project (Style: ${stylePreprocessor}, Layout: ${layoutTemplate})...`)),
  );
 
  // Write avenx.config.json if preprocessor option is configured
  const configPath = path.join(cli.baseDir, 'avenx.config.json');
  let userConfig = {};
 
  if (fs.existsSync(configPath)) {
    try {
      userConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    } catch {
      userConfig = {};
    }
  }
 
  userConfig.style = {
    ...userConfig.style,
    preprocessor: stylePreprocessor,
  };
 
  fs.writeFileSync(configPath, JSON.stringify(userConfig, null, 2) + '\n');
  if (!fs.existsSync(configPath)) {
    console.log('  Created: avenx.config.json');
  } else {
    console.log('  Updated: avenx.config.json');
  }
  cli.config = { ...cli.config, ...userConfig };
 
  const dirs = [
    `${cli.config.srcDir}/components`,
    `${cli.config.srcDir}/pages`,
    `${cli.config.srcDir}/global`,
    `${cli.config.srcDir}/guards`,
    cli.config.distDir,
    '.vscode',
  ];
 
  dirs.forEach((dir) => {
    const fullPath = path.join(cli.baseDir, dir);
    const created = fs.mkdirSync(fullPath, { recursive: true });
    if (created) {
      console.log(`  Created: ${dir}`);
    }
  });
 
  // Create initial .vscode files
  const jsConfigPath = path.join(cli.baseDir, '.vscode/jsconfig.json');
  if (!fs.existsSync(jsConfigPath)) {
    const template = readTemplate(cli.baseDir, cli.config, cli.frameworkDir, 'vscode', 'jsconfig.json.template');
    fs.writeFileSync(jsConfigPath, template);
    console.log('  Created: .vscode/jsconfig.json');
  }
 
  // Teaches the editor's HTML mode about Avenx's own tags, which is what turns
  // component files from "markup the editor does not understand" into files
  // with completion and hover documentation. Referenced by settings.json.
  const htmlDataPath = path.join(cli.baseDir, '.vscode/avenx.html-data.json');
  if (!fs.existsSync(htmlDataPath)) {
    const template = readTemplate(cli.baseDir, cli.config, cli.frameworkDir, 'vscode', 'avenx.html-data.json.template');
    fs.writeFileSync(htmlDataPath, template);
    console.log('  Created: .vscode/avenx.html-data.json');
  }
 
  const settingsPath = path.join(cli.baseDir, '.vscode/settings.json');
  if (!fs.existsSync(settingsPath)) {
    const template = readTemplate(cli.baseDir, cli.config, cli.frameworkDir, 'vscode', 'settings.json.template');
    fs.writeFileSync(settingsPath, template);
    console.log('  Created: .vscode/settings.json');
  }
 
  // Create initial index.html
  const indexHtmlPath = path.join(cli.baseDir, 'index.html');
  if (!fs.existsSync(indexHtmlPath)) {
    fs.writeFileSync(indexHtmlPath, getInitialHtml(cli));
    console.log('  Created: index.html');
  }
 
  // Create initial main.app.js
  const mainAppPath = path.join(cli.baseDir, cli.config.srcDir, 'main.app.js');
  if (!fs.existsSync(mainAppPath)) {
    if (layoutTemplate === 'routing') {
      fs.writeFileSync(
        mainAppPath,
        "import { AvenxApp } from 'avenx-core/runtime';\n" +
          "import Navbar from './components/navbar/navbar.component.js';\n\n" +
          "const app = new AvenxApp({ target: '#app' });\n\n" +
          "app.register('Navbar', Navbar);\n\n" +
          'app.initRouter({\n' +
          "  '': 'Home',\n" +
          "  '#/about': 'About',\n" +
          '});\n',
      );
    } else {
      fs.writeFileSync(
        mainAppPath,
        "import { AvenxApp } from 'avenx-core/runtime';\n\nconst app = new AvenxApp({ target: '#app' });\n",
      );
    }
    console.log(`  Created: ${cli.config.srcDir}/main.app.js`);
  }
 
  if (layoutTemplate === 'routing') {
    const homePageJsPath = path.join(cli.baseDir, cli.config.srcDir, 'pages', 'home.page.js');
    const homePageCssPath = path.join(cli.baseDir, cli.config.srcDir, 'pages', 'home.page.css');
    const aboutPageJsPath = path.join(cli.baseDir, cli.config.srcDir, 'pages', 'about.page.js');
    const aboutPageCssPath = path.join(cli.baseDir, cli.config.srcDir, 'pages', 'about.page.css');
 
    const navbarDir = path.join(cli.baseDir, cli.config.srcDir, 'components', 'navbar');
    if (!fs.existsSync(navbarDir)) {
      fs.mkdirSync(navbarDir, { recursive: true });
    }
    const navbarJsPath = path.join(navbarDir, 'navbar.component.js');
    const navbarCssPath = path.join(navbarDir, 'navbar.component.css');
 
    // Write Home page
    if (!fs.existsSync(homePageJsPath)) {
      fs.writeFileSync(
        homePageJsPath,
        '<state title="Home" />\n\n' +
          '<Navbar />\n\n' +
          '<div @css pageContainer>\n' +
          '    <h1>{{ title }} Page</h1>\n' +
          '    <p>Welcome to the home page of your new Avenx application!</p>\n' +
          '    <p>This layout template demonstrates hash-based routing using AvenxRouter.</p>\n' +
          '</div>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/pages/home.page.js`);
    }
    if (!fs.existsSync(homePageCssPath)) {
      fs.writeFileSync(
        homePageCssPath,
        '<@css>\n' +
          'pageContainer {\n' +
          '    padding: 20px;\n' +
          '    font-family: sans-serif;\n' +
          '    max-width: 800px;\n' +
          '    margin: 0 auto;\n' +
          '}\n' +
          '</@css>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/pages/home.page.css`);
    }
 
    // Write About page
    if (!fs.existsSync(aboutPageJsPath)) {
      fs.writeFileSync(
        aboutPageJsPath,
        '<state title="About" />\n\n' +
          '<Navbar />\n\n' +
          '<div @css pageContainer>\n' +
          '    <h1>{{ title }} Page</h1>\n' +
          '    <p>Welcome to the about page.</p>\n' +
          '</div>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/pages/about.page.js`);
    }
    if (!fs.existsSync(aboutPageCssPath)) {
      fs.writeFileSync(
        aboutPageCssPath,
        '<@css>\n' +
          'pageContainer {\n' +
          '    padding: 20px;\n' +
          '    font-family: sans-serif;\n' +
          '    max-width: 800px;\n' +
          '    margin: 0 auto;\n' +
          '}\n' +
          '</@css>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/pages/about.page.css`);
    }
 
    // Write Navbar component
    if (!fs.existsSync(navbarJsPath)) {
      fs.writeFileSync(
        navbarJsPath,
        '<state activeRoute="" />\n\n' +
          '<action name="onMount">\n' +
          "    this.state.activeRoute = window.location.hash || '#/';\n" +
          '</action>\n\n' +
          '<nav>\n' +
          '    <@css container />\n' +
          "    <a @css link href=\"#/\" aria-current=\"{{ activeRoute === '#/' ? 'page' : '' }}\">Home</a>\n" +
          "    <a @css link href=\"#/about\" aria-current=\"{{ activeRoute === '#/about' ? 'page' : '' }}\">About</a>\n" +
          '</nav>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/components/navbar/navbar.component.js`);
    }
    if (!fs.existsSync(navbarCssPath)) {
      fs.writeFileSync(
        navbarCssPath,
        '<@global>\n' +
          '    @def primary #6366f1;\n' +
          '    @def dark #1e1b4b;\n' +
          '    @def gray #e2e8f0;\n' +
          '</@global>\n\n' +
          '<@css>\n' +
          '    container {\n' +
          '        display: flex;\n' +
          '        gap: 1.5rem;\n' +
          '        padding: 1rem 2rem;\n' +
          '        background: @dark;\n' +
          '        border-bottom: 2px solid @primary;\n' +
          '    }\n\n' +
          '    link {\n' +
          '        color: white;\n' +
          '        text-decoration: none;\n' +
          '        font-weight: 500;\n' +
          '        font-family: sans-serif;\n' +
          '        &:hover {\n' +
          '            color: @primary;\n' +
          '        }\n' +
          '    }\n' +
          '</@css>\n',
      );
      console.log(`  Created: ${cli.config.srcDir}/components/navbar/navbar.component.css`);
    }
  }
 
  // Create or update package.json
  const packageJsonPath = path.join(cli.baseDir, 'package.json');
  if (!fs.existsSync(packageJsonPath)) {
    const projectName =
      path
        .basename(cli.baseDir)
        .toLowerCase()
        .replace(/[^a-z0-9-_]/g, '') || 'avenx-app';
    const packageContent = {
      name: projectName,
      version: '1.0.0',
      type: 'module',
      scripts: {
        dev: 'avenx serve',
        build: 'avenx build',
        serve: 'avenx serve',
      },
      dependencies: {
        'avenx-core': `^${packageJson.version}`,
      },
    };
    fs.writeFileSync(packageJsonPath, JSON.stringify(packageContent, null, 2) + '\n');
    console.log('   Created: package.json');
  } else {
    try {
      const existingPkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
      if (existingPkg.type !== 'module') {
        existingPkg.type = 'module';
        fs.writeFileSync(packageJsonPath, JSON.stringify(existingPkg, null, 2) + '\n');
        console.log('   Updated: package.json (set type: module)');
      }
    } catch {
      // If parsing fails, leave the file as is
    }
  }
 
  // Create initial .gitignore
  const gitignorePath = path.join(cli.baseDir, '.gitignore');
 
  if (!fs.existsSync(gitignorePath)) {
    fs.writeFileSync(gitignorePath, `node_modules/\n${cli.config.distDir}/\n.DS_Store\n.env\n.env.*\n!.env.example\n`);
    console.log('  Created: .gitignore');
  }
  // Create initial .prettierrc
  const prettierPath = path.join(cli.baseDir, '.prettierrc');
 
  if (!fs.existsSync(prettierPath)) {
    const template = readTemplate(cli.baseDir, cli.config, cli.frameworkDir, 'init', '.prettierrc');
 
    fs.writeFileSync(prettierPath, template);
 
    console.log('  Created: .prettierrc');
  }
 
  // Last, so the success line is the last thing printed. It used to be
  // followed by another "Created:" line, which reads as work continuing after
  // the command claimed to be finished.
  console.log(green('✅ Project initialized successfully!'));
  if (isInteractive) {
    process.stdin.pause();
  }
}