or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

blueprint-system.mdcli-commands.mdindex.mdmodels-utilities.mdprogrammatic-api.md
tile.json

programmatic-api.mddocs/

Programmatic API

Ember CLI provides a JavaScript API that allows you to integrate its functionality into Node.js applications, build tools, and custom scripts. This programmatic interface gives you access to all CLI capabilities without shell execution.

Capabilities

Main Entry Point

The primary function for executing Ember CLI operations programmatically.

/**
 * Main Ember CLI programmatic entry point
 * @param options - Configuration options for CLI execution
 * @returns Promise resolving to exit code (0 = success, >0 = error)
 */
function emberCli(options: CliOptions): Promise<number>;

interface CliOptions {
  /** CLI arguments array (e.g., ['build', '--environment', 'production']) */
  cliArgs: string[];
  /** Input stream for interactive commands (default: process.stdin) */
  inputStream?: NodeJS.ReadableStream;
  /** Output stream for command output (default: process.stdout) */
  outputStream?: NodeJS.WritableStream;
  /** Error stream for error output (default: process.stderr) */
  errorStream?: NodeJS.WritableStream;
  /** Custom UI class for handling user interaction */
  UI?: any;
  /** Enable testing mode (disables certain features) */
  testing?: boolean;
  /** CLI configuration object */
  cli?: CliConfig;
  /** Disable dependency checker */
  disableDependencyChecker?: boolean;
  /** Custom Yam configuration loader */
  Yam?: any;
  /** Process object for handling signals (default: process) */
  process?: NodeJS.Process;
  /** Error log array for collecting errors */
  errorLog?: Error[];
}

interface CliConfig {
  /** CLI name (default: 'ember') */
  name?: string;
  /** CLI root directory */
  root?: string;
  /** NPM package name (default: 'ember-cli') */
  npmPackage?: string;
}

Usage Examples:

const emberCli = require('ember-cli');

// Build project for production
emberCli({
  cliArgs: ['build', '--environment', 'production'],
  outputStream: process.stdout,
  errorStream: process.stderr
}).then(exitCode => {
  if (exitCode === 0) {
    console.log('Build successful');
  } else {
    console.error('Build failed');
    process.exit(exitCode);
  }
});

// Generate component
emberCli({
  cliArgs: ['generate', 'component', 'user-profile']
}).then(exitCode => {
  console.log('Generation completed with exit code:', exitCode);
});

// Start development server programmatically  
emberCli({
  cliArgs: ['serve', '--port', '3000'],
  inputStream: process.stdin,
  outputStream: process.stdout
});

CLI Class

The core CLI coordinator class that manages command execution and environment setup.

class CLI {
  /**
   * Create a new CLI instance
   * @param options - CLI configuration options
   */
  constructor(options: CLIConstructorOptions);
  
  /**
   * Run CLI with the provided environment
   * @param environment - Environment configuration
   * @returns Promise resolving to exit code
   */
  run(environment: Environment): Promise<number>;
  
  /**
   * Create a command instance
   * @param commandName - Name of the command to create
   * @param commandArgs - Arguments for the command
   * @returns Command instance
   */
  maybeMakeCommand(commandName: string, commandArgs: string[]): Command;
  
  /** CLI name */
  name: string;
  /** UI instance for user interaction */
  ui: UI;
  /** Testing mode flag */
  testing: boolean;
  /** Dependency checker disabled flag */
  disableDependencyChecker: boolean;
  /** CLI root directory */
  root: string;
  /** NPM package name */
  npmPackage: string;
  /** Instrumentation instance */
  instrumentation: Instrumentation;
  /** Package info cache */
  packageInfoCache: any;
}

interface CLIConstructorOptions {
  /** UI instance for user interaction */
  ui: UI;
  /** Testing mode flag */
  testing?: boolean;
  /** CLI name */
  name?: string;
  /** Disable dependency checker */
  disableDependencyChecker?: boolean;
  /** CLI root directory */
  root?: string;
  /** NPM package name */
  npmPackage?: string;
  /** Instrumentation instance */
  instrumentation?: Instrumentation;
  /** Initial instrumentation data */
  initInstrumentation?: any;
}

interface Environment {
  /** Available CLI tasks */
  tasks: { [key: string]: Task };
  /** CLI arguments */
  cliArgs: string[];
  /** Available CLI commands */
  commands: { [key: string]: Command };
  /** Project instance */
  project: Project;
  /** CLI settings */
  settings: any;
}

Project API

Access and manipulate Ember.js project information and configuration.

class Project {
  /**
   * Find the closest project from a given path
   * @param pathName - Starting path to search from
   * @returns Project instance or null if not found
   */
  static closestSync(pathName: string): Project | null;
  
  /**
   * Get project instance or create null project
   * @param ui - UI instance
   * @param cli - CLI instance  
   * @returns Project instance
   */
  static projectOrnullProject(ui: UI, cli: CLI): Project;
  
  /**
   * Require a module relative to the project
   * @param module - Module path to require
   * @returns Required module
   */
  require(module: string): any;
  
  /**
   * Discover and instantiate project addons
   * @returns Promise resolving when addon discovery is complete
   */
  addonDiscovery(): Promise<void>;
  
  /**
   * Resolve a module path relative to the project root
   * @param module - Module path to resolve
   * @returns Resolved module path
   */
  resolveSync(module: string): string;
  
  /**
   * Get project dependencies (combines dependencies and devDependencies)
   * @returns Object with all project dependencies
   */
  dependencies(): { [key: string]: string };
  
  /**
   * Check if project has dependencies installed
   * @returns True if dependencies are available
   */
  hasDependencies(): boolean;
}

interface ProjectOptions {
  /** Project root directory */
  root: string;
  /** Package.json contents */
  pkg: any;
  /** UI instance */
  ui: UI;
  /** CLI instance */
  cli: CLI;
}

Command API

Base class for creating custom CLI commands and accessing command functionality.

class Command {
  /**
   * Extend the base Command class
   * @param options - Command configuration options
   * @returns Extended Command class
   */
  static extend(options: CommandOptions): typeof Command;
  
  /**
   * Run the command with given options
   * @param options - Command options
   * @param rawArgs - Raw command arguments
   * @returns Promise resolving to exit code or result
   */
  run(options: any, rawArgs: string[]): Promise<any>;
  
  /**
   * Validate and run the command
   * @param rawArgs - Raw command arguments
   * @returns Promise resolving to exit code or result
   */
  validateAndRun(rawArgs: string[]): Promise<any>;
  
  /**
   * Hook called before command execution
   * @param rawArgs - Raw command arguments
   * @returns Promise resolving when setup is complete
   */
  beforeRun(rawArgs: string[]): Promise<void>;
  
  /**
   * Hook called when command is interrupted
   * @returns Promise resolving when cleanup is complete
   */
  onInterrupt(): Promise<void>;
}

interface CommandOptions {
  /** Command name */
  name: string;
  /** Command description */
  description: string;
  /** Command aliases */
  aliases?: string[];
  /** Available options */
  availableOptions?: CommandOption[];
  /** Anonymous options */
  anonymousOptions?: string[];
  /** Where command works: 'insideProject', 'outsideProject', 'everywhere' */
  works?: string;
}

interface CommandOption {
  /** Option name */
  name: string;
  /** Option type */
  type: any;
  /** Default value */
  default?: any;
  /** Option aliases */
  aliases?: string[];
  /** Option description */
  description?: string;
}

Task API

Access to build tasks and custom task creation.

class Task {
  /**
   * Extend the base Task class
   * @param options - Task configuration options
   * @returns Extended Task class
   */
  static extend(options: TaskOptions): typeof Task;
  
  /**
   * Run the task
   * @param options - Task options
   * @returns Promise resolving when task is complete
   */
  run(options: any): Promise<any>;
}

interface TaskOptions {
  /** Task name */
  name: string;
  /** Task description */
  description?: string;
  /** Task function */
  run: (options: any) => Promise<any>;
}

Builder API

Programmatic access to Ember CLI's build system.

class Builder {
  /**
   * Create a new builder instance
   * @param options - Builder configuration options
   */
  constructor(options: BuilderOptions);
  
  /**
   * Build the project
   * @returns Promise resolving to build results
   */
  build(): Promise<BuildResult>;
  
  /**
   * Clean up builder resources
   * @returns Promise resolving when cleanup is complete
   */
  cleanup(): Promise<void>;
}

interface BuilderOptions {
  /** UI instance */
  ui: UI;
  /** Output directory */
  outputPath: string;
  /** Build environment */
  environment: string;
  /** Project instance */
  project: Project;
}

interface BuildResult {
  /** Build directory */
  directory: string;
  /** Build graph */
  graph: any;
  /** Total files processed */
  totalTime: number;
}

UI API

Interface for custom user interaction handling.

interface UI {
  /** Input stream */
  inputStream: NodeJS.ReadableStream;
  /** Output stream */
  outputStream: NodeJS.WritableStream;
  /** Error stream */
  errorStream: NodeJS.WritableStream;
  /** Error log array */
  errorLog: Error[];
  
  /**
   * Write output message
   * @param message - Message to write
   */
  write(message: string): void;
  
  /**
   * Write error message
   * @param error - Error to write
   */
  writeError(error: Error | string): void;
  
  /**
   * Prompt user for input
   * @param options - Prompt options
   * @returns Promise resolving to user input
   */
  prompt(options: PromptOptions): Promise<any>;
}

interface PromptOptions {
  /** Input type */
  type: string;
  /** Prompt message */
  message: string;
  /** Default value */
  default?: any;
  /** Available choices */
  choices?: any[];
}

Integration Examples

Custom Build Script

const emberCli = require('ember-cli');
const path = require('path');

async function customBuild() {
  console.log('Starting custom Ember build...');
  
  // Change to project directory
  process.chdir(path.join(__dirname, 'my-ember-app'));
  
  // Run production build
  const exitCode = await emberCli({
    cliArgs: ['build', '--environment', 'production', '--output-path', 'dist-custom'],
    outputStream: process.stdout,
    errorStream: process.stderr
  });
  
  if (exitCode === 0) {
    console.log('✅ Build completed successfully');
    
    // Run tests after build
    const testExitCode = await emberCli({
      cliArgs: ['test', '--environment', 'production']
    });
    
    console.log('Test exit code:', testExitCode);
  } else {
    console.error('❌ Build failed with exit code:', exitCode);
    process.exit(exitCode);
  }
}

customBuild().catch(console.error);

Development Server Integration

const emberCli = require('ember-cli');

async function startDevServer(port = 4200) {
  console.log(`Starting Ember development server on port ${port}...`);
  
  try {
    await emberCli({
      cliArgs: ['serve', '--port', port.toString(), '--live-reload-port', '35729'],
      inputStream: process.stdin,
      outputStream: process.stdout,
      errorStream: process.stderr
    });
  } catch (error) {
    console.error('Failed to start development server:', error);
    process.exit(1);
  }
}

// Start server
startDevServer(3000);

Code Generation Automation

const emberCli = require('ember-cli');

async function generateComponents(components) {
  for (const component of components) {
    console.log(`Generating component: ${component}`);
    
    const exitCode = await emberCli({
      cliArgs: ['generate', 'component', component],
      outputStream: process.stdout,
      errorStream: process.stderr
    });
    
    if (exitCode !== 0) {
      console.error(`Failed to generate component: ${component}`);
      return false;
    }
  }
  
  console.log('All components generated successfully');
  return true;
}

// Generate multiple components
generateComponents(['user-profile', 'nav-bar', 'footer'])
  .catch(console.error);

Error Handling

The programmatic API returns exit codes and can throw errors:

const emberCli = require('ember-cli');

try {
  const exitCode = await emberCli({
    cliArgs: ['build', '--environment', 'production']
  });
  
  // Handle exit codes
  switch (exitCode) {
    case 0:
      console.log('Success');
      break;
    case 1:
      console.error('General error');
      break;
    default:
      console.error('Unknown error:', exitCode);
  }
} catch (error) {
  // Handle exceptions
  console.error('Exception occurred:', error.message);
  process.exit(1);
}

Environment Variables

The programmatic API respects the same environment variables as the CLI:

  • EMBER_ENV: Build environment override
  • PORT: Default development server port
  • EMBER_CLI_TEST_COMMAND: Command for testing
  • DEBUG: Enable debug logging
  • Various EMBER_VERBOSE_* flags for detailed output

Testing Integration

When using the programmatic API in tests:

const emberCli = require('ember-cli');

// Enable testing mode
const exitCode = await emberCli({
  cliArgs: ['test'],
  testing: true,
  outputStream: mockOutputStream,
  errorStream: mockErrorStream
});

// Testing mode disables certain features like update checks
// and provides more predictable behavior