> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cadcamfun.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Creating extensions

# Creating Extensions

This guide walks you through the process of creating a custom extension for the API Extensions system. Extensions allow you to enhance the application's functionality or add new features without modifying the core code.

## Extension Structure

Each extension consists of two main components:

1. **Manifest File**: A JSON file containing metadata about the extension
2. **Implementation Files**: TypeScript/JavaScript files that implement the extension's functionality

### Extension Manifest

The manifest file (`manifest.json`) defines the extension's metadata:

```json theme={null}
{
  "id": "my-custom-extension",
  "name": "My Custom Extension",
  "description": "Adds custom functionality to the CAD generator",
  "version": "1.0.0",
  "author": "Your Name",
  "type": "cad-generator",
  "main": "index.js",
  "accessLevel": "public",
  "capabilities": ["generate"],
  "dependencies": {
    "other-extension": "^1.0.0"
  }
}
```

#### Manifest Properties

| Property     | Type      | Description                                                 |
| ------------ | --------- | ----------------------------------------------------------- |
| id           | string    | Unique identifier for the extension                         |
| name         | string    | Display name for the extension                              |
| description  | string    | Brief description of what the extension does                |
| version      | string    | Semantic version (major.minor.patch)                        |
| author       | string    | Name of the extension creator                               |
| type         | string    | Type of extension (cad-generator, model-modifier, exporter) |
| main         | string    | Path to the main JavaScript file                            |
| accessLevel  | string    | Access level (public, private, restricted)                  |
| capabilities | string\[] | List of capabilities the extension provides                 |
| dependencies | object    | Map of other extensions this extension depends on           |

### Extension Implementation

The main implementation file exports a function that will be called when the extension is executed:

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from 'api-extensions/types/extension-types';

/**
 * Main extension execution function
 */
export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  // Extension implementation here
  
  return {
    // Return result
  };
}
```

## Extension Types

### CAD Generator Extensions

CAD Generator extensions create 3D models from input data:

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from 'api-extensions/types/extension-types';

export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  // Extract data from context
  const { text, options } = context;
  
  // Generate geometry
  const geometry = {
    type: 'composite',
    primitives: [
      {
        type: 'box',
        width: 10,
        height: 5,
        depth: 3,
        center: [0, 0, 0]
      }
    ]
  };
  
  // Return the generated geometry
  return {
    geometry
  };
}
```

### Model Modifier Extensions

Model Modifier extensions transform existing geometry:

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from 'api-extensions/types/extension-types';

export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  // Extract geometry from context
  const { geometry, options } = context;
  
  // Apply modifications to the geometry
  // For example, add rounded corners to a box
  
  // Return the modified geometry
  return {
    geometry: modifiedGeometry
  };
}
```

### Exporter Extensions

Exporter extensions convert models to specific file formats:

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from 'api-extensions/types/extension-types';

export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  // Extract model from context
  const { model, options } = context;
  
  // Convert model to the desired format
  const exportedData = convertToFormat(model, options.format);
  
  // Return the exported data
  return {
    fileName: `${model.name}.${options.format}`,
    format: options.format,
    data: exportedData,
    size: exportedData.length
  };
}
```

## Text-to-CAD Extensions

Creating an extension for the Text-to-CAD system typically involves:

1. Analyzing the text input
2. Extracting relevant parameters
3. Generating or modifying geometry based on those parameters

### Example: Custom Shape Generator

Here's an example of a CAD generator extension that creates a custom shape:

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from 'api-extensions/types/extension-types';

export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  const { text, options } = context;
  
  // Check if our extension should handle this request
  if (!text.normalized.includes('hexagonal prism')) {
    // Not for us, return without changes
    return context.geometry ? { geometry: context.geometry } : {};
  }
  
  // Extract parameters
  let radius = 5; // Default
  let height = 10; // Default
  
  // Look for radius in text
  const radiusMatch = text.normalized.match(/radius\s*[:=]?\s*(\d+(\.\d+)?)/i);
  if (radiusMatch) {
    radius = parseFloat(radiusMatch[1]);
  }
  
  // Look for height in text
  const heightMatch = text.normalized.match(/height\s*[:=]?\s*(\d+(\.\d+)?)/i);
  if (heightMatch) {
    height = parseFloat(heightMatch[1]);
  }
  
  // Create hexagonal prism geometry
  const geometry = {
    type: 'prism',
    sides: 6,
    radius,
    height,
    center: [0, 0, 0]
  };
  
  return {
    geometry
  };
}
```

## Testing Extensions

To test your extension:

1. Create a directory for your extension in the `api-extensions/extensions/built-in` directory
2. Add your manifest and implementation files
3. Restart the application to load your extension
4. Make requests that should trigger your extension

## Example: Complete Extension

Here's a complete example of a Text-to-CAD extension that adds support for creating gears:

### Directory Structure

```
api-extensions/extensions/built-in/gear-generator/
├── manifest.json
└── index.js
```

### manifest.json

```json theme={null}
{
  "id": "gear-generator",
  "name": "Gear Generator",
  "description": "Generates parametric gears from text descriptions",
  "version": "1.0.0",
  "author": "Your Name",
  "type": "cad-generator",
  "main": "index.js",
  "accessLevel": "public",
  "capabilities": ["generate"]
}
```

### index.js

```typescript theme={null}
import { ExtensionContext, ExtensionResult } from '../../../types/extension-types';

/**
 * Gear Generator Extension
 */
export default async function execute(context: ExtensionContext): Promise<ExtensionResult> {
  const { text, options } = context;
  
  // Check if this text is asking for a gear
  if (!text.normalized.includes('gear')) {
    return context.geometry ? { geometry: context.geometry } : {};
  }
  
  // Extract gear parameters
  let toothCount = 20; // Default
  let module = 1;     // Default
  let thickness = 5;  // Default
  
  // Match tooth count
  const toothMatch = text.normalized.match(/(\d+)\s*(?:tooth|teeth)/i);
  if (toothMatch) {
    toothCount = parseInt(toothMatch[1], 10);
  }
  
  // Match module (tooth size)
  const moduleMatch = text.normalized.match(/module\s*[:=]?\s*(\d+(\.\d+)?)/i);
  if (moduleMatch) {
    module = parseFloat(moduleMatch[1]);
  }
  
  // Match thickness
  const thicknessMatch = text.normalized.match(/thickness\s*[:=]?\s*(\d+(\.\d+)?)/i);
  if (thicknessMatch) {
    thickness = parseFloat(thicknessMatch[1]);
  }
  
  // Calculate gear properties
  const pitchDiameter = toothCount * module;
  const rootDiameter = pitchDiameter - 2.5 * module;
  const outerDiameter = pitchDiameter + 2 * module;
  
  // Create a simplified gear geometry
  // In a real implementation, this would create actual gear teeth
  const geometry = {
    type: 'gear',
    toothCount,
    module,
    thickness,
    pitchDiameter,
    rootDiameter,
    outerDiameter,
    center: [0, 0, 0]
  };
  
  return {
    geometry
  };
}
```

## Publishing Your Extension

To share your extension with others:

1. Package your extension (manifest and code)
2. Document its functionality and usage
3. Distribute it through your preferred channels
4. Users can install it using the Extension Manager

For more information about the installation process, see [Installing Extensions](./installing-extensions.md).

## Best Practices

* **Keep extensions focused**: Each extension should do one thing well
* **Validate inputs**: Check that inputs are valid before processing
* **Provide fallbacks**: Handle cases where parameters are missing
* **Include documentation**: Document how to use your extension
* **Version appropriately**: Use semantic versioning for your extensions
* **Handle errors gracefully**: Return meaningful error messages
* **Respect timeouts**: Extensions should complete quickly or provide progress updates
