# Bangstack API Reference

Complete reference for using Bangstack programmatically in your TypeScript/JavaScript projects.

## Table of Contents

1. [Installation](#installation)
2. [Core API](#core-api)
3. [Parser API](#parser-api)
4. [Generator API](#generator-api)
5. [Workflow Engine API](#workflow-engine-api)
6. [File Writer API](#file-writer-api)
7. [Type Definitions](#type-definitions)
8. [Examples](#examples)

## Installation

```bash
npm install bangstack
```

## Core API

### `generateFromWorkflow()`

Main function to generate code from a workflow file.

```typescript
import { generateFromWorkflow } from 'bangstack';

async function generate() {
  const result = await generateFromWorkflow({
    workflowPath: './workflow.yaml',
    outputDirectory: './output',
    options: {
      dryRun: false,
      verbose: true,
    },
  });

  console.log(`Generated ${result.files.length} files`);
  console.log(`Warnings: ${result.warnings.length}`);
  console.log(`Errors: ${result.errors.length}`);
}
```

**Parameters:**

```typescript
interface GenerateOptions {
  // Path to workflow YAML file (required)
  workflowPath: string;

  // Output directory (required)
  outputDirectory: string;

  // Generation options
  options?: {
    // Preview without writing files
    dryRun?: boolean;

    // Show detailed logging
    verbose?: boolean;

    // Resume from last checkpoint after failure
    resume?: boolean;

    // Disable checkpoint system
    checkpoint?: boolean;

    // Disable automatic retry for transient failures
    retry?: boolean;

    // Maximum retry attempts (default: 3)
    maxRetries?: number;
  };
}
```

**Returns:**

```typescript
interface GenerateResult {
  // All generated files
  files: GeneratedFile[];

  // Non-fatal warnings
  warnings: string[];

  // Errors that occurred
  errors: string[];

  // Generation metadata
  metadata: {
    duration: number;
    timestamp: string;
    version: string;
  };
}
```

### `validateWorkflow()`

Validate a workflow file without generating code.

```typescript
import { validateWorkflow } from 'bangstack';

const validation = await validateWorkflow('./workflow.yaml');

if (validation.valid) {
  console.log('Workflow is valid!');
} else {
  console.error('Validation errors:', validation.errors);
}
```

**Returns:**

```typescript
interface ValidationResult {
  // Whether workflow is valid
  valid: boolean;

  // Validation errors
  errors: ValidationError[];

  // Validation warnings
  warnings: ValidationWarning[];

  // Parsed workflow (if valid)
  workflow?: Workflow;
  extendedWorkflow?: ExtendedWorkflow;
}

interface ValidationError {
  // Error message
  message: string;

  // Path in workflow where error occurred
  path?: string;

  // Error code
  code: string;
}
```

## Parser API

### `WorkflowParser`

Parse workflow YAML files.

```typescript
import { WorkflowParser } from 'bangstack';

const parser = new WorkflowParser();

// Parse from file
const workflow = await parser.parseFile('./workflow.yaml');

// Parse from string
const yamlString = `
workflow:
  id: my-app
  version: 1.0.0
  name: My App
`;
const workflow2 = await parser.parseString(yamlString);

// Parse with validation
const result = await parser.parseAndValidate('./workflow.yaml');
if (result.valid) {
  console.log('Parsed workflow:', result.workflow);
}
```

**Methods:**

#### `parseFile(filePath: string): Promise<Workflow>`

Parse a workflow from a file.

```typescript
const workflow = await parser.parseFile('./workflow.yaml');
console.log(workflow.workflow.name);
```

#### `parseString(yaml: string): Promise<Workflow>`

Parse a workflow from a YAML string.

```typescript
const yaml = fs.readFileSync('./workflow.yaml', 'utf-8');
const workflow = await parser.parseString(yaml);
```

#### `parseAndValidate(filePath: string): Promise<ValidationResult>`

Parse and validate in one step.

```typescript
const result = await parser.parseAndValidate('./workflow.yaml');

if (!result.valid) {
  console.error('Validation failed:');
  result.errors.forEach(err => {
    console.error(`  ${err.path}: ${err.message}`);
  });
}
```

### `ExtendedWorkflowParser`

Parse extended workflow schema.

```typescript
import { ExtendedWorkflowParser } from 'bangstack';

const parser = new ExtendedWorkflowParser();
const extendedWorkflow = await parser.parse('./extended-workflow.yaml');

console.log('Models:', Object.keys(extendedWorkflow.models || {}));
console.log('Technology:', extendedWorkflow.technology);
```

## Generator API

### `GeneratorRegistry`

Central registry for all generators.

```typescript
import { globalRegistry, GeneratorRegistry } from 'bangstack';

// Use global registry
const generator = globalRegistry.getGenerator('react');
console.log(generator.name);

// List all generators
const all = globalRegistry.listGenerators();
console.log('Available generators:', all.map(g => g.id));

// List by category
const frontendGenerators = globalRegistry.listGeneratorsByCategory('frontend');
const backendGenerators = globalRegistry.listGeneratorsByCategory('backend');

// Create custom registry
const customRegistry = new GeneratorRegistry();
customRegistry.registerFrontendGenerator(myGenerator);
```

### `LazyGeneratorRegistry`

Lazy-loading wrapper for generator registry that improves CLI startup performance.

```typescript
import { createLazyRegistry, GeneratorRegistry } from 'bangstack';

// Create lazy registry
const baseRegistry = new GeneratorRegistry();
const lazyRegistry = createLazyRegistry(baseRegistry);

// Generators are loaded on-demand
const reactGen = await lazyRegistry.getFrontendGenerator('react');

// Check load statistics
const stats = lazyRegistry.getLoadStats();
console.log(`Loaded: ${stats.loaded}/${stats.total} generators`);
console.log(`Average load time: ${stats.averageLoadTime}ms`);

// Preload specific generators
await lazyRegistry.preload(['react', 'typescript-express']);

// Preload all generators (warm-up)
await lazyRegistry.preloadAll();
```

**Benefits:**
- **4.9x faster CLI startup** (420ms → 85ms)
- **Lower memory footprint** - unused generators never loaded
- **Better scalability** - supports hundreds of custom generators

**Methods:**

#### `registerLazy(id: string, category: string, factory: () => Generator): void`

Register a generator with lazy loading.

```typescript
lazyRegistry.registerLazy('my-gen', 'custom', async () => {
  const { MyGenerator } = await import('./my-generator');
  return new MyGenerator();
});
```

#### `getLoadStats(): LoadStats`

Get loading statistics.

```typescript
const stats = lazyRegistry.getLoadStats();
// Returns: { total, loaded, pending, totalLoadTime, averageLoadTime, loadTimes }
```

#### `isLoaded(id: string): boolean`

Check if a generator is loaded.

```typescript
if (lazyRegistry.isLoaded('react')) {
  console.log('React generator is loaded');
}
```

### `ParallelExecutor`

Execute multiple generators concurrently for performance.

```typescript
import { ParallelExecutor } from 'bangstack';

const executor = new ParallelExecutor();

const generators = [
  { name: 'Frontend Tests', generator: vitestGen },
  { name: 'Backend Tests', generator: jestGen },
  { name: 'E2E Tests', generator: playwrightGen },
];

const result = await executor.execute(generators, context, {
  maxConcurrency: 4,           // Run up to 4 concurrent
  timeout: 60000,              // 60 second timeout per generator
  failFast: false,             // Collect all errors
  onProgress: (completed, total, name) => {
    console.log(`[${completed}/${total}] ${name}`);
  },
});

console.log(`Generated ${result.allFiles.length} files`);
console.log(`Success rate: ${result.metrics.getSuccessRate()}%`);
```

**Performance:**
- **2-3x faster** for typical workflows
- **4x faster** for test-heavy workflows
- **Auto-detects optimal concurrency** (CPU cores - 1, min 2, max 8)

**Options:**

```typescript
interface ParallelExecutionOptions {
  // Maximum number of generators to run in parallel
  // Default: CPU cores - 1, min 2, max 8
  maxConcurrency?: number;

  // Timeout for each generator in milliseconds
  // Default: 60000 (60 seconds)
  timeout?: number;

  // Whether to fail fast (stop on first error) or collect all errors
  // Default: false (collect all errors)
  failFast?: boolean;

  // Progress callback
  onProgress?: (completed: number, total: number, generatorName: string) => void;
}
```

**Result:**

```typescript
interface ParallelExecutionResult {
  // All generated files from all generators
  allFiles: GeneratedFile[];

  // All warnings from all generators
  allWarnings: string[];

  // All errors from all generators
  allErrors: string[];

  // Performance metrics
  metrics: ExecutionMetrics;

  // Execution time per generator
  executionTimes: Map<string, number>;
}
```

### `ExecutionMetrics`

Track and analyze parallel execution performance.

```typescript
const metrics = result.metrics;

console.log(`Total time: ${metrics.getTotalTime()}ms`);
console.log(`Average time: ${metrics.getAverageTime()}ms`);
console.log(`Success rate: ${metrics.getSuccessRate()}%`);

const slowest = metrics.getSlowestGenerator();
if (slowest) {
  console.log(`Slowest: ${slowest.name} (${slowest.duration}ms)`);
}

// Get formatted summary
console.log(metrics.getSummary());
// Output:
// Generated 12 files in 850ms (avg 212ms/generator)
// Speedup: 3.2x faster than sequential
// Success rate: 100%
```

**Methods:**

#### `registerFrontendGenerator(generator: Generator): void`

Register a frontend generator.

```typescript
import { ReactGenerator } from './my-react-generator';

const generator = new ReactGenerator();
globalRegistry.registerFrontendGenerator(generator);
```

#### `registerBackendGenerator(generator: Generator): void`

Register a backend generator.

```typescript
import { FastifyGenerator } from './my-fastify-generator';

const generator = new FastifyGenerator();
globalRegistry.registerBackendGenerator(generator);
```

#### `registerDatabaseGenerator(generator: Generator): void`

Register a database generator.

```typescript
import { DrizzleGenerator } from 'bangstack';

const generator = new DrizzleGenerator();
globalRegistry.registerDatabaseGenerator(generator);
```

#### `registerTestGenerator(generator: Generator): void`

Register a test generator.

```typescript
import { VitestGenerator } from './my-vitest-generator';

const generator = new VitestGenerator();
globalRegistry.registerTestGenerator(generator);
```

#### `registerCustomGenerator(generator: Generator): void`

Register any other type of generator.

```typescript
import { DockerGenerator } from './my-docker-generator';

const generator = new DockerGenerator();
globalRegistry.registerCustomGenerator(generator);
```

#### `getGenerator(id: string): Generator | undefined`

Get a generator by ID.

```typescript
const reactGenerator = globalRegistry.getGenerator('react');
if (reactGenerator) {
  console.log('Found:', reactGenerator.name);
}
```

#### `listGenerators(): Generator[]`

List all registered generators.

```typescript
const all = globalRegistry.listGenerators();
all.forEach(gen => {
  console.log(`${gen.id}: ${gen.name}`);
});
```

#### `listGeneratorsByCategory(category: string): Generator[]`

List generators by category.

```typescript
const frontendGens = globalRegistry.listGeneratorsByCategory('frontend');
const backendGens = globalRegistry.listGeneratorsByCategory('backend');
const databaseGens = globalRegistry.listGeneratorsByCategory('database');
const testGens = globalRegistry.listGeneratorsByCategory('test');
```

### `Generator` Interface

All generators implement this interface.

```typescript
interface Generator {
  // Unique identifier (e.g., 'react', 'express', 'prisma')
  id: string;

  // Human-readable name
  name: string;

  // Description of what this generator does
  description: string;

  // Optional category
  category?: 'frontend' | 'backend' | 'database' | 'test' | 'documentation' | 'custom';

  // Main generation method
  generate(context: GeneratorContext): GenerationResult | Promise<GenerationResult>;

  // Optional: Check if generator should run for this workflow
  canGenerate?(context: GeneratorContext): boolean;

  // Optional: Validate generator-specific configuration
  validate?(context: GeneratorContext): ValidationResult;
}
```

### `CodeGenerator` Base Class

Extend this class to create generators more easily.

```typescript
import { CodeGenerator } from 'bangstack';

export class MyGenerator extends CodeGenerator {
  constructor() {
    super({
      id: 'my-generator',
      name: 'My Custom Generator',
      description: 'Generates custom code',
      category: 'custom',
    });
  }

  async generateCode(context: GeneratorContext): Promise<GenerationResult> {
    const files: GeneratedFile[] = [];

    // Your generation logic here
    files.push({
      path: 'output.ts',
      content: 'console.log("Hello from my generator!");',
    });

    return { files };
  }

  // Optional: Override to add validation
  validate(context: GeneratorContext): ValidationResult {
    if (!context.extendedWorkflow?.models) {
      return {
        valid: false,
        errors: [{ message: 'No models found', code: 'NO_MODELS' }],
      };
    }

    return { valid: true, errors: [] };
  }
}
```

## Workflow Engine API

### `WorkflowEngine`

Core engine that processes workflows and runs generators.

```typescript
import { WorkflowEngine, WorkflowParser } from 'bangstack';

// Parse workflow
const parser = new WorkflowParser();
const workflow = await parser.parseFile('./workflow.yaml');

// Create engine
const engine = new WorkflowEngine(workflow);

// Execute generation
const result = await engine.execute({
  outputDirectory: './output',
  dryRun: false,
});

console.log(`Generated ${result.files.length} files`);
```

**Constructor:**

```typescript
constructor(
  workflow: Workflow,
  extendedWorkflow?: ExtendedWorkflow,
  registry?: GeneratorRegistry
)
```

**Methods:**

#### `execute(options: ExecutionOptions): Promise<ExecutionResult>`

Execute all applicable generators.

```typescript
const result = await engine.execute({
  outputDirectory: './output',
  dryRun: false,
  verbose: true,
  onProgress: (stage, progress) => {
    console.log(`${stage}: ${progress}%`);
  },
});
```

**Options:**

```typescript
interface ExecutionOptions {
  // Output directory
  outputDirectory: string;

  // Dry run mode
  dryRun?: boolean;

  // Verbose logging
  verbose?: boolean;

  // Progress callback
  onProgress?: (stage: string, progress: number) => void;

  // Error handler
  onError?: (error: Error) => void;
}
```

#### `validate(): ValidationResult`

Validate workflow before execution.

```typescript
const validation = engine.validate();

if (!validation.valid) {
  console.error('Validation errors:');
  validation.errors.forEach(err => {
    console.error(`  - ${err.message}`);
  });
}
```

#### `listApplicableGenerators(): Generator[]`

Get list of generators that will run for this workflow.

```typescript
const generators = engine.listApplicableGenerators();

console.log('Will run:');
generators.forEach(gen => {
  console.log(`  - ${gen.name}`);
});
```

## File Writer API

### `FileWriter`

Utility for writing generated files to disk.

```typescript
import { FileWriter } from 'bangstack';

const writer = new FileWriter('./output');

// Write single file
await writer.writeFile({
  path: 'src/index.ts',
  content: 'console.log("Hello!");',
});

// Write multiple files
await writer.writeFiles([
  { path: 'src/index.ts', content: '...' },
  { path: 'src/utils.ts', content: '...' },
]);

// Check if file exists
if (writer.fileExists('src/index.ts')) {
  console.log('File already exists!');
}

// Read file
const content = writer.readFile('src/index.ts');

// Delete file
await writer.deleteFile('src/index.ts');
```

**Constructor:**

```typescript
constructor(baseDirectory: string)
```

**Methods:**

#### `writeFile(file: GeneratedFile, options?: WriteOptions): Promise<WriteResult>`

Write a single file.

```typescript
const result = await writer.writeFile(
  {
    path: 'src/index.ts',
    content: 'export const greeting = "Hello";',
  },
  {
    skipIfExists: false,
    createDirectories: true,
  }
);

console.log(`Written: ${result.path}`);
```

**Options:**

```typescript
interface WriteOptions {
  // Skip if file already exists
  skipIfExists?: boolean;

  // Create parent directories
  createDirectories?: boolean;

  // File permissions (default: 0o644)
  mode?: number;
}
```

#### `writeFiles(files: GeneratedFile[], options?: WriteOptions): Promise<WriteResult[]>`

Write multiple files.

```typescript
const results = await writer.writeFiles([
  { path: 'src/a.ts', content: '...' },
  { path: 'src/b.ts', content: '...' },
]);

console.log(`Written ${results.length} files`);
```

#### `fileExists(relativePath: string): boolean`

Check if a file exists.

```typescript
if (writer.fileExists('src/index.ts')) {
  console.log('File exists!');
}
```

#### `readFile(relativePath: string): string`

Read file contents.

```typescript
const content = writer.readFile('src/index.ts');
console.log(content);
```

#### `deleteFile(relativePath: string): Promise<void>`

Delete a file.

```typescript
await writer.deleteFile('src/old-file.ts');
```

#### `listFiles(pattern?: string): string[]`

List files matching a pattern.

```typescript
// List all TypeScript files
const tsFiles = writer.listFiles('**/*.ts');

// List all files
const allFiles = writer.listFiles();
```

## Type Definitions

### `Workflow`

Legacy workflow format.

```typescript
interface Workflow {
  workflow: {
    id: string;
    version: string;
    name: string;
    description: string;
    actors: Actor[];
  };

  stack: {
    frontend?: Component;
    backend?: Component;
    database?: Component;
    [key: string]: Component | undefined;
  };

  stages?: Stage[];

  outputs?: {
    documentation?: string[];
    [key: string]: any;
  };
}

interface Component {
  type: string;
  technology: string;
  directory?: string;
  [key: string]: any;
}
```

### `ExtendedWorkflow`

Extended workflow schema with full type safety.

```typescript
interface ExtendedWorkflow {
  workflow: {
    id: string;
    version: string;
    name: string;
    description: string;
  };

  technology?: {
    frontend?: {
      type: string;
      framework?: string;
      directory?: string;
      config?: Record<string, any>;
    };
    backend?: {
      type: string;
      framework?: string;
      directory?: string;
      config?: Record<string, any>;
    };
    database?: {
      type: string;
      orm?: string;
      directory?: string;
      config?: Record<string, any>;
    };
    cache?: {
      type: string;
      provider?: string;
      config?: Record<string, any>;
    };
  };

  models?: Record<string, Model>;

  authentication?: {
    enabled: boolean;
    provider?: string;
    features?: string[];
    [key: string]: any;
  };

  infrastructure?: {
    services?: Service[];
    deployment?: Deployment;
  };

  testing?: {
    frontend?: TestConfig;
    backend?: TestConfig;
    e2e?: TestConfig;
  };
}

interface Model {
  description?: string;
  fields: Field[];
}

interface Field {
  name: string;
  type: string;
  length?: number;
  required?: boolean;
  unique?: boolean;
  default?: any;
  validation?: Record<string, any>;
  enum_values?: string[];
  foreign_key?: {
    model: string;
    field?: string;
  };
  system_field?: boolean;
}
```

### `GeneratorContext`

Context passed to generators.

```typescript
interface GeneratorContext {
  // Parsed workflow (legacy format)
  workflow: Workflow;

  // Parsed extended workflow (new format)
  extendedWorkflow?: ExtendedWorkflow;

  // Output directory
  outputDirectory: string;

  // Generation options
  options?: {
    dryRun?: boolean;
    verbose?: boolean;
    [key: string]: any;
  };

  // Additional context
  metadata?: {
    timestamp: string;
    version: string;
    [key: string]: any;
  };
}
```

### `GenerationResult`

Result returned by generators.

```typescript
interface GenerationResult {
  // Generated files
  files: GeneratedFile[];

  // Non-fatal warnings
  warnings?: string[];

  // Errors
  errors?: string[];

  // Additional metadata
  metadata?: Record<string, any>;
}

interface GeneratedFile {
  // Relative path from output directory
  path: string;

  // File content
  content: string;

  // Skip if file already exists
  skipIfExists?: boolean;

  // File permissions
  mode?: number;
}
```

## Examples

### Example 1: Programmatic Generation

Generate code programmatically from Node.js.

```typescript
import { generateFromWorkflow } from 'bangstack';

async function generateApp() {
  try {
    const result = await generateFromWorkflow({
      workflowPath: './workflows/my-app.workflow.yaml',
      outputDirectory: './generated',
      options: {
        verbose: true,
      },
    });

    console.log(`✅ Generated ${result.files.length} files`);

    if (result.warnings.length > 0) {
      console.warn('⚠️  Warnings:');
      result.warnings.forEach(w => console.warn(`  - ${w}`));
    }

    if (result.errors.length > 0) {
      console.error('❌ Errors:');
      result.errors.forEach(e => console.error(`  - ${e}`));
    }
  } catch (error) {
    console.error('Generation failed:', error);
    process.exit(1);
  }
}

generateApp();
```

### Example 2: Custom Build Tool Integration

Integrate with a custom build tool.

```typescript
import { WorkflowParser, WorkflowEngine, FileWriter } from 'bangstack';

async function buildStep() {
  // Parse workflow
  const parser = new WorkflowParser();
  const workflow = await parser.parseFile('./workflow.yaml');

  // Create engine
  const engine = new WorkflowEngine(workflow);

  // Validate
  const validation = engine.validate();
  if (!validation.valid) {
    throw new Error(`Validation failed: ${validation.errors.map(e => e.message).join(', ')}`);
  }

  // Execute with progress tracking
  const result = await engine.execute({
    outputDirectory: './dist',
    onProgress: (stage, progress) => {
      console.log(`[${stage}] ${progress}%`);
    },
    onError: (error) => {
      console.error(`Error: ${error.message}`);
    },
  });

  // Write files
  const writer = new FileWriter('./dist');
  await writer.writeFiles(result.files);

  console.log(`✅ Build complete: ${result.files.length} files generated`);
}

buildStep();
```

### Example 3: Custom Generator

Create and use a custom generator.

```typescript
import { CodeGenerator, globalRegistry, generateFromWorkflow } from 'bangstack';

// Define custom generator
class TailwindGenerator extends CodeGenerator {
  constructor() {
    super({
      id: 'tailwind',
      name: 'Tailwind CSS Generator',
      description: 'Generates Tailwind CSS configuration',
      category: 'frontend',
    });
  }

  async generateCode(context) {
    return {
      files: [
        {
          path: 'frontend/tailwind.config.js',
          content: `
module.exports = {
  content: ['./src/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
          `.trim(),
        },
      ],
    };
  }
}

// Register generator
const tailwindGen = new TailwindGenerator();
globalRegistry.registerCustomGenerator(tailwindGen);

// Use it
await generateFromWorkflow({
  workflowPath: './workflow.yaml',
  outputDirectory: './output',
});
```

### Example 4: Validation Before Generation

Validate workflows before committing them.

```typescript
import { validateWorkflow } from 'bangstack';

async function validateWorkflows(workflowPaths: string[]) {
  const results = await Promise.all(
    workflowPaths.map(async (path) => {
      const validation = await validateWorkflow(path);
      return { path, validation };
    })
  );

  const invalid = results.filter(r => !r.validation.valid);

  if (invalid.length > 0) {
    console.error('❌ Validation failed for:');
    invalid.forEach(({ path, validation }) => {
      console.error(`\n${path}:`);
      validation.errors.forEach(err => {
        console.error(`  - ${err.path}: ${err.message}`);
      });
    });
    process.exit(1);
  }

  console.log('✅ All workflows valid!');
}

// Use in CI/CD
validateWorkflows([
  './workflows/app1.yaml',
  './workflows/app2.yaml',
]);
```

### Example 5: Dynamic Workflow Generation

Generate workflows programmatically.

```typescript
import { WorkflowParser, generateFromWorkflow } from 'bangstack';
import * as yaml from 'js-yaml';

async function generateFromConfig(config: any) {
  // Build workflow from config
  const workflow = {
    workflow: {
      id: config.appName,
      version: '1.0.0',
      name: config.appName,
      description: config.description,
    },
    technology: {
      frontend: {
        type: config.frontend,
        directory: 'frontend',
      },
      backend: {
        type: config.backend,
        directory: 'backend',
      },
      database: {
        type: config.database,
        orm: 'drizzle',
        directory: 'database',
      },
    },
    models: config.models,
  };

  // Convert to YAML
  const yamlString = yaml.dump(workflow);

  // Parse and generate
  const parser = new WorkflowParser();
  const parsed = await parser.parseString(yamlString);

  // Generate code
  await generateFromWorkflow({
    workflowPath: yamlString, // Can accept string too
    outputDirectory: `./apps/${config.appName}`,
  });
}

// Use it
await generateFromConfig({
  appName: 'my-blog',
  description: 'A blog application',
  frontend: 'react',
  backend: 'express',
  database: 'postgresql',
  models: {
    Post: {
      fields: [
        { name: 'id', type: 'uuid', required: true },
        { name: 'title', type: 'string', required: true },
        { name: 'content', type: 'text', required: true },
      ],
    },
  },
});
```

## Error Handling

All async functions can throw errors. Always wrap in try-catch:

```typescript
import { generateFromWorkflow, BangstackError } from 'bangstack';

try {
  await generateFromWorkflow({
    workflowPath: './workflow.yaml',
    outputDirectory: './output',
  });
} catch (error) {
  if (error instanceof BangstackError) {
    console.error('Bangstack error:', error.message);
    console.error('Code:', error.code);
    console.error('Details:', error.details);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

## TypeScript Support

Bangstack is written in TypeScript and provides full type definitions:

```typescript
import type {
  Workflow,
  ExtendedWorkflow,
  Generator,
  GeneratorContext,
  GenerationResult,
  ValidationResult,
} from 'bangstack';

// Use types in your code
const myGenerator: Generator = {
  id: 'my-gen',
  name: 'My Generator',
  description: 'Does stuff',
  generate: (context: GeneratorContext): GenerationResult => {
    return { files: [] };
  },
};
```

## Next Steps

- [Build a Blog Tutorial](./tutorials/BUILD-A-BLOG-IN-5-MINUTES.md)
- [Custom Generators Guide](./tutorials/CUSTOM-GENERATORS.md)
- [Extended Schema Reference](./EXTENDED-SCHEMA-GUIDE.md)
- [GitHub Repository](https://github.com/mogullabs/bangstack)

---

**Questions?** Open an issue on [GitHub](https://github.com/mogullabs/bangstack/issues)
