# Utility Functions

Additional utilities for message formatting, metafile analysis, service management, and version information. These functions provide supporting functionality for build analysis, error handling, and environment management.

## Capabilities

### Message Formatting

Format error and warning messages for display with customizable styling and detail levels.

```typescript { .api }
/**
 * Format error and warning messages for display
 * @param messages - Array of messages to format
 * @param options - Formatting configuration
 * @returns Promise resolving to formatted message strings
 */
function formatMessages(
  messages: PartialMessage[],
  options: FormatMessagesOptions
): Promise<string[]>;

/**
 * Synchronously format error and warning messages (Node.js only)
 * @param messages - Array of messages to format
 * @param options - Formatting configuration
 * @returns Formatted message strings
 * @throws Error in browser environments
 */
function formatMessagesSync(
  messages: PartialMessage[],
  options: FormatMessagesOptions
): string[];
```

**Usage Examples:**

```typescript
import * as esbuild from "esbuild";

try {
  await esbuild.build({
    entryPoints: ["src/broken.js"],
    bundle: true,
    outfile: "dist/app.js",
  });
} catch (error) {
  if (error.errors) {
    // Format errors for display
    const formatted = await esbuild.formatMessages(error.errors, {
      kind: "error",
      color: true,
      terminalWidth: 80,
    });
    
    formatted.forEach(msg => console.error(msg));
  }
  
  if (error.warnings) {
    // Format warnings
    const formatted = await esbuild.formatMessages(error.warnings, {
      kind: "warning", 
      color: true,
      terminalWidth: 80,
    });
    
    formatted.forEach(msg => console.warn(msg));
  }
}
```

### Metafile Analysis

Analyze bundle metadata to understand bundle composition, dependencies, and optimization opportunities.

```typescript { .api }
/**
 * Analyze bundle metadata for insights and optimization
 * @param metafile - Metafile object or JSON string
 * @param options - Analysis configuration
 * @returns Promise resolving to human-readable analysis
 */
function analyzeMetafile(
  metafile: Metafile | string,
  options?: AnalyzeMetafileOptions
): Promise<string>;

/**
 * Synchronously analyze bundle metadata (Node.js only)
 * @param metafile - Metafile object or JSON string
 * @param options - Analysis configuration
 * @returns Human-readable analysis
 * @throws Error in browser environments
 */
function analyzeMetafileSync(
  metafile: Metafile | string,
  options?: AnalyzeMetafileOptions
): string;
```

**Usage Examples:**

```typescript
import * as esbuild from "esbuild";

// Build with metafile generation
const result = await esbuild.build({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  metafile: true,
  splitting: true,
  format: "esm",
});

if (result.metafile) {
  // Basic analysis
  const analysis = await esbuild.analyzeMetafile(result.metafile);
  console.log(analysis);
  
  // Detailed analysis with options
  const detailedAnalysis = await esbuild.analyzeMetafile(result.metafile, {
    verbose: true,
    color: true,
  });
  console.log(detailedAnalysis);
}
```

### Service Management

Functions for initializing and managing the ESBuild service, particularly important for browser environments.

```typescript { .api }
/**
 * Initialize ESBuild service (required for browser usage)
 * @param options - Initialization configuration
 * @returns Promise that resolves when service is ready
 */
function initialize(options: InitializeOptions): Promise<void>;

/**
 * Stop the ESBuild service and clean up resources
 * @returns Promise that resolves when service is stopped
 */
function stop(): Promise<void>;
```

**Usage Examples:**

```typescript
// Browser usage
if (typeof window !== "undefined") {
  // Initialize before using ESBuild in browser
  await esbuild.initialize({
    wasmURL: "/node_modules/esbuild-wasm/esbuild.wasm",
  });
  
  // Now safe to use build/transform
  const result = await esbuild.transform("console.log('hello')", {
    loader: "js",
    format: "esm",
  });
  
  console.log(result.code);
}

// Clean up when done
process.on("exit", async () => {
  await esbuild.stop();
});
```

### Version Information

Access to the current ESBuild version.

```typescript { .api }
/**
 * ESBuild package version string
 */
const version: string;
```

**Usage Example:**

```typescript
import * as esbuild from "esbuild";

console.log(`Using ESBuild version: ${esbuild.version}`);

// Version comparison
const [major, minor, patch] = esbuild.version.split('.').map(Number);
if (major >= 0 && minor >= 20) {
  console.log("Using modern ESBuild version with latest features");
}
```

## Types

### FormatMessagesOptions Interface

Configuration for message formatting.

```typescript { .api }
interface FormatMessagesOptions {
  /**
   * Type of messages being formatted
   */
  kind: "error" | "warning";
  
  /**
   * Enable colored output
   * @default false
   */
  color?: boolean;
  
  /**
   * Terminal width for text wrapping
   * @default 80
   */
  terminalWidth?: number;
}
```

### AnalyzeMetafileOptions Interface

Configuration for metafile analysis.

```typescript { .api }
interface AnalyzeMetafileOptions {
  /**
   * Enable verbose analysis output
   * @default false
   */
  verbose?: boolean;
  
  /**
   * Enable colored output
   * @default false
   */
  color?: boolean;
}
```

### PartialMessage Interface

Partial message structure for formatting.

```typescript { .api }
interface PartialMessage {
  id?: string;
  pluginName?: string;
  text?: string;
  location?: PartialLocation;
  notes?: PartialNote[];
  detail?: any;
}

interface PartialLocation {
  file?: string;
  namespace?: string;
  line?: number;
  column?: number;
  length?: number;
  lineText?: string;
  suggestion?: string;
}

interface PartialNote {
  text?: string;
  location?: PartialLocation;
}
```

### InitializeOptions Interface

Configuration for service initialization.

```typescript { .api }
interface InitializeOptions {
  /**
   * URL or path to the WebAssembly binary
   */
  wasmURL?: string | URL;
  
  /**
   * WebAssembly module instance
   */
  wasmModule?: WebAssembly.Module;
  
  /**
   * Custom worker implementation
   */
  worker?: boolean;
}
```

### Metafile Interface

Structure of bundle metadata for analysis.

```typescript { .api }
interface Metafile {
  inputs: Record<string, {
    bytes: number;
    imports: Array<{
      path: string;
      kind: ImportKind;
      external?: boolean;
      original?: string;
      with?: Record<string, string>;
    }>;
    format?: "cjs" | "esm";
    with?: Record<string, string>;
  }>;
  
  outputs: Record<string, {
    bytes: number;
    inputs: Record<string, {
      bytesInOutput: number;
    }>;
    imports: Array<{
      path: string;
      kind: ImportKind | "file-loader";
      external?: boolean;
    }>;
    exports: string[];
    entryPoint?: string;
    cssBundle?: string;
  }>;
}
```

## Error Handling Patterns

### Comprehensive Error Processing

```typescript
async function buildWithErrorHandling() {
  try {
    const result = await esbuild.build({
      entryPoints: ["src/app.js"],
      bundle: true,
      outfile: "dist/app.js",
      logLevel: "silent", // Handle errors manually
    });
    
    // Process warnings
    if (result.warnings.length > 0) {
      const formatted = await esbuild.formatMessages(result.warnings, {
        kind: "warning",
        color: true,
      });
      formatted.forEach(msg => console.warn(msg));
    }
    
    return result;
    
  } catch (error) {
    // Process build errors
    if (error.errors?.length > 0) {
      const formatted = await esbuild.formatMessages(error.errors, {
        kind: "error",
        color: true,
        terminalWidth: process.stdout.columns || 80,
      });
      formatted.forEach(msg => console.error(msg));
    }
    
    throw error;
  }
}
```

### Metafile Analysis Workflow

```typescript
async function analyzeBundle(buildOptions: esbuild.BuildOptions) {
  const result = await esbuild.build({
    ...buildOptions,
    metafile: true,
    write: false, // Keep outputs in memory for analysis
  });
  
  if (!result.metafile) {
    throw new Error("Metafile generation failed");
  }
  
  // Basic analysis
  console.log("=== Bundle Analysis ===");
  const analysis = await esbuild.analyzeMetafile(result.metafile, {
    verbose: true,
    color: true,
  });
  console.log(analysis);
  
  // Custom analysis
  console.log("=== Custom Metrics ===");
  const totalSize = Object.values(result.metafile.outputs)
    .reduce((sum, output) => sum + output.bytes, 0);
  
  console.log(`Total bundle size: ${(totalSize / 1024).toFixed(2)} KB`);
  
  const entryPoints = Object.entries(result.metafile.outputs)
    .filter(([_, output]) => output.entryPoint)
    .length;
    
  console.log(`Entry points: ${entryPoints}`);
  
  return result;
}
```