# Appmixer AI Connector & Component Generator

An AI-powered CLI tool that automatically generates complete Appmixer connectors and components. This tool leverages AI to analyze API documentation and create production-ready connector code with proper authentication, components, and test plans.

## Table of Contents

- [Quick Start](#quick-start)
- [Installation](#installation)
- [Commands](#commands)
    - [Generate Connector](#generate-connector)
    - [Generate Component](#generate-component)
- [How It Works](#how-it-works)
- [Troubleshooting](#troubleshooting)
- [Development Guidelines](#development-guidelines)

---

## Quick Start

```bash
# 1. Clone and setup
git clone https://github.com/appmixer-ai/appmixer-connectors.git
cd appmixer-connectors
npm install appmixer

# 2. Configure environment (create .env in appmixer-connectors root)
copy .env.example .env   # Windows
# Edit .env and add your API keys (OpenAI, Anthropic, etc.)

# 3. Generate a connector
appmixer ai connector stripe --context ./stripe-context.md --icon ./stripe.svg

# 4. Generate a component
appmixer ai component stripe CreateCharge

```

---

## Installation

### Prerequisites
- Node.js v16 or higher
- API keys for AI services (OpenAI, Anthropic, etc.)

### Setup Steps

1. Clone the connectors repository:
```bash
git clone https://github.com/appmixer-ai/appmixer-connectors.git
cd appmixer-connectors
```

2. Install the Appmixer CLI:
```bash
npm install appmixer
```

3. Create `.env` file in the appmixer-connectors root:
```bash
copy .env.example .env   # Windows
# cp .env.example .env   # macOS/Linux
```

Edit `.env` and add your API keys:
```env
OPENAI_API_KEY=your_key_here
ANTHROPIC_API_KEY=your_key_here
```

---

## Commands

### Generate Connector

Creates a complete connector with authentication, components, and test plans.

```bash
appmixer ai connector <connector-name> [options]
```

**Options:**
- `-i, --icon <file>` - **Required for the first run.** Path to icon file (embedded in service.json as data URI).
- `-c, --context <file>` - Optional. Path to Markdown/text API docs
- `-m, --module <name>` - Module name (default: "core")
- `-e, --vendor <name>` - Vendor namespace (default: "appmixer")


**Context Resolution (if --context not provided):**
1. Uses OpenAPI spec at `src/appmixer/<connector>/artifacts/openapi.json` (if exists)
2. Attempts automatic discovery via web search

### Using OpenAPI Specifications

The AI connector generator can automatically parse OpenAPI/Swagger specifications to generate connectors. This is the recommended approach when an OpenAPI spec is available, as it provides more accurate schema information.

**Setup:**
```bash
# Create the artifacts directory and place your OpenAPI spec
mkdir -p src/appmixer/<connector>/artifacts
cp your-openapi-spec.json src/appmixer/<connector>/artifacts/openapi.json

# Generate the connector
appmixer ai connector <connector> --icon ./icon.svg
```

**Supported formats:**
- `openapi.json` - OpenAPI 3.0 JSON
- `openapi.yaml` or `openapi.yml` - OpenAPI 3.0 YAML
- Swagger 2.0 specs are automatically converted to OpenAPI 3.0

**What gets extracted:**
- API title, description, and version
- Base URL from servers
- Authentication schemes (OAuth2, API Key, Bearer, Basic)
- Endpoints with parameters, request bodies, and response schemas
- Component names generated from `operationId` or path

**Handling large specifications:**

For APIs with hundreds or thousands of endpoints (e.g., ConnectWise with 2800+ operations), the generator automatically:
- Limits output to the 30 most relevant endpoints (configurable)
- Prioritizes endpoints by method: POST (create) > GET (read/list) > PUT/PATCH (update) > DELETE
- Boosts list endpoints and tagged operations
- Displays a message when limiting is applied

Additional components can be added individually after initial generation:
```bash
appmixer ai component <connector> <ComponentName>
```

**Example output:**
When an OpenAPI spec is detected, you'll see:
```
OpenAPI spec found at src/appmixer/stripe/artifacts/openapi.json
Parsing OpenAPI spec...
Note: This API has 350 endpoints. Limiting to 30 most relevant for initial connector generation.
✓ Context generated from OpenAPI spec
```

**Context file example**
Context file includes basic information about the API and expected components to be generated.

sample context file for Harvest API:
```
# Harvest Connector for Appmixer

## Overview
Harvest connector provides integration with Harvest's API v2 for time tracking, project management, invoicing, and expense management. Harvest is a time tracking and invoicing software used by businesses and freelancers.

## Authentication
- **Type**: OAuth 2.0
- **Authorization URL**: `https://id.getharvest.com/oauth2/authorize`
- **Token URL**: `https://id.getharvest.com/api/v2/oauth2/token`
- **Required Headers**: 
  - `Authorization: Bearer ACCESS_TOKEN`
  - `Harvest-Account-ID: ACCOUNT_ID`
  - `User-Agent: APPLICATION_NAME (contact@email.com)`
- **Setup**: [Harvest Developers Portal](https://id.getharvest.com/developers)

## Components

### Client Management
- **ListClients** - Retrieve all clients with active/inactive filtering
- **GetClient** - Retrieve specific client by ID
- **CreateClient** - Create new client
- **UpdateClient** - Update client details
- **DeleteClient** - Archive client (soft delete)
- **ListContacts** - List client contacts
- **CreateContact** - Create client contact
- **UpdateContact** - Update contact information
- **DeleteContact** - Remove client contact

```

**Examples:**
```bash
# With context file
appmixer ai connector stripe \
  --context "./stripe-api-docs.md" \
  --icon "./stripe.svg"

# Without context (uses OpenAPI or auto-discovery)
appmixer ai connector stripe --icon "./stripe.svg"

# Generate specific component first, then continue with connector flow
appmixer ai connector elevenlabs EditProjectContent --icon ./icon.svg
```

**Generate specific component:**
If you provide a component name as a second argument, the CLI will:
1. Check if the component exists
2. If not, generate it automatically (with recipe, skeleton, refactor, and tests)
3. Continue with the regular connector workflow (auth validation, test plan, etc.)

This is useful when you want to add a new component to an existing connector and ensure it's included in the test plan.

**What Gets Generated:**
- `auth.js` - Authentication module.
- `service.json` - Service metadata, base URLs, icon
- `bundle.json` - Component registration
- `components/` - One directory per component with `component.json` and `<Name>.js`
- `<connector>/artifacts/ai-artifacts` - generator artifacts and logs. This folder contains intermediate files used by the AI generator for reproducibility and debugging. Context file (if provided) and icon file is copied here.

---
#### How It Works

#####  Generation Workflow

1. ✅ **Detect or generate auth.js**
2. ✅ **Detect or generate components**
3. ✅ **Apply Appmixer standards (refactor)** - Applied for all components. Static analysis of the generated code. Apply fixes to follow Appmixer conventions.
4. ✅ **Validate authentication** - Test the authentication using the appmixer cli command `appmixer test auth login <path to auth.js>`. If it fails, prompt user to fix or continue. Authentication is required for further steps.
5. ✅ **Detect or create test plan** - Test plan is logical sequence for component tests. For example "Create" component must be tested before "Get" or "Update".
6. ✅ **Generate tests and test components** - For each component in the test plan, generate test cases and run tests (using the `appmixer test component` command). Connector is marker as complete when at least one test case per component passes. There is also a limit of 5 attempts to fix failed tests. After 5 attempts, the process stops and component is marked as failed.
7. ✅ **Report results** - Summary of test results - `test-plan-report.md` is generated in the connector artifacts folder.

**Important Note**: You can interrupt the process at any time (Ctrl+C). The generated code up to that point will be saved, along with logs and artifacts for debugging. When you re-run the command, it will resume from the last successful step. This allows you to fix any issues (e.g., authentication) and continue without starting over.

### Generate Component

Creates individual components for an existing connector.

```bash
appmixer ai component <connector> <component>
```

**Arguments:**
- `<connector>` - Required. Connector name
- `<component>` - Required. Component name

**Options:**
- `-m, --module <name>` - Module name (default: "core")
- `-e, --vendor <name>` - Vendor namespace (default: "appmixer")

**Examples:**
```bash
# Single component
appmixer ai component stripe CreateCharge
```

**Note:** Component commands must be run from the `appmixer-connectors` root directory.

---

## Artifacts System

AI generates intermediate artifact files (JSON) stored in `<connector>/artifacts/ai-artifacts/`:

- **`<component>/componentRecipe.json`** - Component metadata, schemas, sample data (generated when `appmixer ai component` is run)
- **`SERVICE_INFO_ACTIONS_AND_TRIGGERS`** - Connector metadata, schemas, sample data for all components (generated when `appmixer ai connector` is run)
- **`context.md`** - Copy of your context file for reproducibility
- **`commands-log`** - Text file containing all CLI commands run during generation
- **`testplan.json`** - Component test cases and progress
- **`progress.json`** - JSON file tracking progress of the refactoring steps (Apply Appmixer standards step).

---

**Force regeneration:**
```bash
rm -rf ai-artifacts/<connector>  # Delete artifacts
appmixer ai connector <connector> --context ./context.md --icon ./icon.svg
```
