All files / bin cli.js

88.41% Statements 290/328
89.76% Branches 114/127
75% Functions 3/4
88.41% Lines 290/328

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 329250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 6x 6x 6x 6x 3x 3x 6x 6x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 246x 246x 246x 246x 246x 246x 246x 246x 250x 250x 250x 250x 250x 250x 250x 250x     250x 250x 250x 250x 250x 250x 250x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 7x 252x   245x 7x 7x 252x 252x 252x 252x 2x 252x 250x 250x 1x 1x 250x 252x 252x 252x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 252x 252x 252x 252x 252x 252x 252x 51x 51x 51x             51x 51x 51x 51x 252x 252x 35x 30x 30x             30x 35x 5x 35x 3x 30x 9x 27x 14x 18x 4x 4x 4x 35x 252x 252x 7x 7x 7x             7x 7x 1x 7x 1x 6x 1x 5x 4x 4x       7x 252x 252x 83x 66x 66x 1x 1x 1x 1x 1x 1x 66x 82x 82x 252x 2x 2x 252x 252x 10x 10x 252x     252x     252x 252x 2x 2x 252x 252x 3x 3x 252x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x 7x 7x 7x 7x 7x 7x 14x 4x 4x 14x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 252x 252x                 252x 20x 20x 252x 10x 10x 252x 7x 7x 252x 4x 4x 252x 2x 2x 2x 2x 2x 252x 2x 2x 252x 7x 7x 7x 7x 7x 7x 1x 1x 1x 6x 6x 6x 252x 252x 250x  
import path from 'path';
import { fileURLToPath } from 'url';
import loadConfig, { getClosestKey } from '../lib/config.js';
import { loadEnv } from '../lib/env.js';
import { checkGitStatus } from './utils.js';
import { createSeverityFormatter, cyan, gray, red } from './colors.js';
import { initProject } from './commands/init.js';
import { generateComponent, generatePage, generateBridge, generateGuard } from './commands/generate.js';
import { destroyComponent, destroyPage, destroyBridge, destroyGuard } from './commands/destroy.js';
import { buildProject, cleanProject, checkProject } from './commands/build.js';
import { serveProject, watchProject } from './commands/serve.js';
import { printHelp } from './commands/help.js';
import { runDoctor } from './commands/doctor.js';
import { runInspect } from './commands/inspect.js';
import { runStats } from './commands/stats.js';
import { runEnv } from './commands/env.js';
import { explainDiagnostic } from './commands/explain.js';
import { runTrace } from './commands/trace.js';
import { runAtlas, runQuery } from './commands/atlas.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const findProjectRoot = loadConfig.findProjectRoot;
 
/**
 * Every command name and alias the CLI dispatches on.
 *
 * Used only to suggest a correction for a mistyped command, so an entry missing
 * here costs a suggestion rather than a command.
 * @type {string[]}
 */
export const KNOWN_COMMANDS = [
  'init', 'generate', 'g', 'destroy', 'd', 'build', 'b', 'clean', 'check', 'lint',
  'doctor', 'env', 'explain', 'inspect', 'i', 'stats', 's', 'atlas', 'impact', 'why',
  'trace', 'serve', 'watch', 'w', 'help',
];
 
/**
 * Reports a command the CLI does not recognise, with a correction when one is near.
 * @param {string} command - The command as typed.
 * @returns {void}
 */
function reportUnknownCommand(command) {
  const closest = getClosestKey(command, KNOWN_COMMANDS);
  console.error(red(`Unknown command: "${command}"`));
  if (closest) {
    console.error(gray(`Did you mean "avenx ${closest}"?`));
  }
  console.error('');
}
 
/**
 * Avenx CLI - Command Line Interface router for Avenx-JS.
 */
export class AvenxCLI {
  /**
   * Creates an instance of AvenxCLI.
   * Initializes the base directory and framework directory paths.
   * @param {object} [options]
   */
  constructor(options = {}) {
    this.baseDir = options.baseDir || findProjectRoot(process.cwd());
    loadEnv(this.baseDir);
    this.frameworkDir = path.join(__dirname, '..');
    this.config = { ...loadConfig(this.baseDir), ...options };
    // Tint compiler warnings yellow and errors red for every command that compiles
    // (build, check, watch, serve). Stays inert when colors are unsupported.
    this.config.logging = { ...this.config.logging, formatter: createSeverityFormatter() };
  }
 
  /**
   * Serves the project on specified port and host.
   * @param {number} port
   * @param {string} host
   * @param {boolean} [open] - Whether to open the browser automatically.
   */
  serveProject(port, host, open) {
    return serveProject(this, port, host, open);
  }
 
  /**
   * Executes a given CLI command with provided arguments.
   * @param {string} command - The command to run (e.g., 'init', 'generate', 'build', 'serve', 'help').
   * @param {string[]} args - Additional arguments for the command.
   */
  async run(command, args = []) {
    const dryRun = args.includes('--dry-run') || args.includes('-d');
    const force = args.includes('--force') || args.includes('-f');
    const withTest = args.includes('--with-test');
    const noTest = args.includes('--no-test');
 
    // `avenx build` is production by default; `--dev` opts out. `--prod` is
    // accepted so a script can state the intent it relies on. `serve` and
    // `watch` are development unless the flag says otherwise.
    const explicitDev = args.includes('--dev') || args.includes('--development');
    const explicitProd = args.includes('--prod') || args.includes('--production');
    if (explicitDev) {
      this.config.mode = 'development';
    } else if (explicitProd) {
      this.config.mode = 'production';
    } else if (command === 'serve' || command === 'watch' || command === 'w') {
      this.config.mode = 'development';
    }
 
    let templateName = null;
    const templateIndex = args.findIndex((arg) => arg === '--template' || arg === '-t');
    if (templateIndex !== -1 && templateIndex + 1 < args.length) {
      templateName = args[templateIndex + 1];
    } else {
      const templateInline = args.find((arg) => arg.startsWith('--template=') || arg.startsWith('-t='));
      if (templateInline) {
        templateName = templateInline.split('=').slice(1).join('=');
      }
    }
 
    const filteredArgs = args.filter(
      (arg, idx) =>
        arg !== '--dry-run' &&
        arg !== '-d' &&
        arg !== '--force' &&
        arg !== '-f' &&
        arg !== '--no-color' &&
        arg !== '--no-colors' &&
        arg !== '--dev' &&
        arg !== '--development' &&
        arg !== '--prod' &&
        arg !== '--production' &&
        arg !== '--template' &&
        arg !== '-t' &&
        !(templateIndex !== -1 && idx === templateIndex + 1) &&
        !arg.startsWith('--template=') &&
        !arg.startsWith('-t=') &&
        arg !== '--with-test' &&
        arg !== '--no-test',
    );
    const type = filteredArgs[0];
    const name = filteredArgs[1];
 
    switch (command) {
      case 'init':
        if (!force) {
          const proceed = await checkGitStatus(this.baseDir);
          if (!proceed) {
            // Declining is a refusal to run, not a successful no-op. Exiting 0
            // here made `avenx build && deploy` deploy whatever was already in
            // dist/, which contradicts the documented contract that build exits
            // 0 only on a successful build.
            process.exit(1);
          }
        }
        await initProject(this, args);
        process.exit(0);
        break;
      case 'generate':
      case 'g':
        if (!force) {
          const proceed = await checkGitStatus(this.baseDir);
          if (!proceed) {
            // Declining is a refusal to run, not a successful no-op. Exiting 0
            // here made `avenx build && deploy` deploy whatever was already in
            // dist/, which contradicts the documented contract that build exits
            // 0 only on a successful build.
            process.exit(1);
          }
        }
        if (type === 'bridge') {
          generateBridge(this, name, dryRun, force, templateName);
        } else if (type === 'guard') {
          generateGuard(this, name, dryRun, force, templateName);
        } else if (type === 'page' || type === 'p') {
          generatePage(this, name, dryRun, force, templateName);
        } else if (type === 'component' || type === 'c') {
          generateComponent(this, name, dryRun, force, templateName, withTest, noTest);
        } else {
          // Default to component if type is not specified (e.g., `avenx g MyButton`)
          generateComponent(this, type, dryRun, force, templateName, withTest, noTest);
        }
        break;
      case 'destroy':
      case 'd':
        if (!force) {
          const proceed = await checkGitStatus(this.baseDir);
          if (!proceed) {
            // Declining is a refusal to run, not a successful no-op. Exiting 0
            // here made `avenx build && deploy` deploy whatever was already in
            // dist/, which contradicts the documented contract that build exits
            // 0 only on a successful build.
            process.exit(1);
          }
        }
        if (type === 'bridge') {
          destroyBridge(this, name, dryRun);
        } else if (type === 'guard') {
          destroyGuard(this, name, dryRun);
        } else if (type === 'page' || type === 'p') {
          destroyPage(this, name, dryRun);
        } else if (type === 'component' || type === 'c') {
          destroyComponent(this, name, dryRun);
        } else {
          // Default to component if only one arg or type is 'component'
          destroyComponent(this, name || type, dryRun);
        }
        break;
      case 'build':
      case 'b':
        if (!force) {
          const proceed = await checkGitStatus(this.baseDir);
          if (!proceed) {
            // Declining is a refusal to run, not a successful no-op. Exiting 0
            // here made `avenx build && deploy` deploy whatever was already in
            // dist/, which contradicts the documented contract that build exits
            // 0 only on a successful build.
            process.exit(1);
          }
        }
        buildProject(this);
        break;
      case 'clean':
        cleanProject(this);
        break;
      case 'check':
      case 'lint':
        checkProject(this, args);
        break;
      case 'doctor':
        runDoctor(this);
        break;
      case 'env':
        runEnv(this);
        break;
      case 'inspect':
      case 'i':
        runInspect(this);
        break;
      case 'stats':
      case 's':
        runStats(this, args);
        break;
      case 'serve': {
        // Recording is opt-in and development-only. It is read here rather
        // than from config alone so that turning it on is always a visible,
        // deliberate act at the command line.
        this.traceEnabled = args.includes('--trace');
        const portIdx = args.findIndex((a) => a === '--port' || a === '-p' || a.startsWith('--port=') || a.startsWith('-p='));
        const hostIdx = args.findIndex((a) => a === '--host' || a === '-h' || a.startsWith('--host=') || a.startsWith('-h='));
        const open = args.includes('--open') || args.includes('-o');
 
        if (args.includes('--no-live-reload') || args.includes('--live-reload=false')) {
          this.config.server.liveReload = false;
        }
 
        // The positional port is the first bare argument that is not itself the
        // value of a flag. Only args[0] used to be considered, so any leading
        // flag — `serve --trace 8080`, `serve --open 8080` — silently fell back
        // to the default port.
        const flagValueIndexes = new Set();
        for (const idx of [portIdx, hostIdx]) {
          if (idx !== -1 && !args[idx].includes('=')) {
            flagValueIndexes.add(idx + 1);
          }
        }
        const positionalPort = args.find(
          (arg, idx) => !arg.startsWith('-') && !flagValueIndexes.has(idx) && /^\d+$/.test(arg.trim()),
        );
 
        const rawPortVal = portIdx !== -1
          ? (args[portIdx].includes('=') ? args[portIdx].split('=').slice(1).join('=') : args[portIdx + 1])
          : (positionalPort ?? null);
        const rawPort = rawPortVal?.replace(/[^0-9]/g, '');
        const port = rawPort
          ? parseInt(rawPort, 10)
          : (process.env.PORT ? parseInt(String(process.env.PORT).replace(/[^0-9]/g, ''), 10) : null) || this.config.server?.port || 3000;
 
        const rawHostVal = hostIdx !== -1
          ? (args[hostIdx].includes('=') ? args[hostIdx].split('=').slice(1).join('=') : args[hostIdx + 1])
          : null;
        const host = rawHostVal ? rawHostVal.trim().replace(/\/+$/g, '') : 'localhost';
 
        this.serveProject(port, host, open);
        break;
      }
      case 'watch':
      case 'w':
        console.log(cyan(`👀 Watching for changes in ${this.config.srcDir}/...\n`));
        buildProject(this);
        watchProject(this);
        process.on('SIGINT', () => {
          console.log(`\n${gray('Stopping watch...')}`);
          process.exit(0);
        });
        break;
      case 'trace':
        runTrace(this, args);
        break;
      case 'atlas':
        runAtlas(this, args);
        break;
      case 'impact':
        runQuery(this, args, 'in');
        break;
      case 'why':
        runQuery(this, args, 'out');
        break;
      case 'explain': {
        const asJson = args.includes('--json');
        const codeArg = args.find((a) => !a.startsWith('-'));
        explainDiagnostic(this, codeArg, asJson);
        break;
      }
      case 'help':
        printHelp();
        break;
      default:
        // No command at all is a request for help, and exits 0. An
        // *unrecognised* command is a mistake, and used to do the same thing --
        // so `avenx buidl` printed the help text and exited 0, which meant
        // `avenx buidl && deploy` deployed whatever was already in dist/. A
        // mistyped command now says so and exits non-zero.
        if (!command || command.startsWith('-')) {
          printHelp();
          break;
        }
        reportUnknownCommand(command);
        printHelp();
        process.exit(1);
    }
  }
}