npm package: @kahkeshan/addon-cli
Description: CLI tool for developing and publishing Kahkeshan addons
Author: Hamid Rayati
Latest version: 1.0.1

# Kahkeshan Addon CLI

CLI tool for developing, packaging, and publishing Kahkeshan addons.

## Installation

### Local Development

```bash
cd tools/addon-cli
npm install
npm run build
npm link  # Makes kahkeshan-addon available globally
```

### Via NPM (when published)

```bash
npm install -g @kahkeshan/addon-cli
```

## Commands

### `init` - Initialize New Addon

Create a new addon project with boilerplate code.

```bash
kahkeshan-addon init <addon-name> [options]
```

**Options:**
- `-t, --template <type>` - Template type (content, service, ui) [default: content]
- `-d, --dir <directory>` - Output directory [default: .]

**Example:**
```bash
kahkeshan-addon init my-awesome-addon
cd my-awesome-addon
npm install
```

**Generated Structure:**
```
my-awesome-addon/
├── manifest.ts                 # Addon metadata
├── my-awesome-addon.module.ts  # NestJS module
├── my-awesome-addon.service.ts # Service logic
├── my-awesome-addon.resolver.ts # GraphQL resolver
├── package.json
├── tsconfig.json
├── README.md
├── .gitignore
├── src/
│   ├── dto/
│   └── models/
├── assets/
│   └── icon.png (placeholder)
└── test/
```

### `build` - Build Addon

Compile TypeScript to JavaScript.

```bash
kahkeshan-addon build [options]
```

**Options:**
- `-w, --watch` - Watch mode for development

**Examples:**
```bash
# Single build
kahkeshan-addon build

# Watch mode
kahkeshan-addon build --watch
```

### `validate` - Validate Addon

Check addon structure and manifest for errors.

```bash
kahkeshan-addon validate [options]
```

**Options:**
- `-p, --path <path>` - Addon directory path [default: .]

**Example:**
```bash
kahkeshan-addon validate
```

**Validation Checks:**
- ✅ manifest.ts exists
- ✅ Required manifest fields (addonId, name, version)
- ✅ Semantic versioning format
- ✅ Module file exists (*.module.ts)
- ⚠️ Service file exists (*.service.ts)
- ⚠️ package.json exists
- ⚠️ tsconfig.json exists
- ⚠️ README.md exists

### `package` - Package Addon

Create a `.tar.gz` package for deployment.

```bash
kahkeshan-addon package [options]
```

**Options:**
- `-o, --output <path>` - Output directory [default: ./dist]

**Example:**
```bash
kahkeshan-addon package
# Creates: dist/addon-name@1.0.0.tar.gz
```

**Package Contents:**
- manifest.ts
- *.module.ts
- *.service.ts
- *.resolver.ts
- src/ directory
- package.json
- tsconfig.json
- README.md
- assets/ directory

### `upload` - Upload to Platform

Upload addon package to Kahkeshan platform.

```bash
kahkeshan-addon upload <package-file> [options]
```

**Options:**
- `-u, --url <url>` - Platform URL [default: http://localhost:4001]
- `-t, --token <token>` - Authentication token

**Environment Variables:**
- `KAHKESHAN_URL` - Platform URL
- `KAHKESHAN_TOKEN` - Authentication token

**Examples:**
```bash
# With explicit token
kahkeshan-addon upload dist/my-addon@1.0.0.tar.gz \
  --url http://localhost:4001 \
  --token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

# Using environment variables
export KAHKESHAN_URL=http://localhost:4001
export KAHKESHAN_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
kahkeshan-addon upload dist/my-addon@1.0.0.tar.gz

# Upload to production
kahkeshan-addon upload dist/my-addon@1.0.0.tar.gz \
  --url https://api.kahkeshan.com \
  --token $PROD_TOKEN
```

**Response:**
```
✔ Addon uploaded successfully!

Addon ID: addon:my-addon
Addon has been installed and is ready for activation.
```

## Complete Workflow

### 1. Create New Addon

```bash
# Initialize
kahkeshan-addon init my-forum-addon
cd my-forum-addon

# Install dependencies
npm install
```

### 2. Develop

Edit your files:

**manifest.ts:**
```typescript
export const manifest: AddonManifest = {
  addonId: 'addon:forum',
  name: 'Forum',
  version: '1.0.0',
  description: 'Discussion forum addon',
  // ... more config
};
```

**my-forum-addon.service.ts:**
```typescript
@Injectable()
export class ForumService {
  async createTopic(input: CreateTopicInput) {
    // Your logic
  }
}
```

**my-forum-addon.resolver.ts:**
```typescript
@Resolver()
export class ForumResolver {
  @Mutation(() => Topic)
  async createTopic(@Args('input') input: CreateTopicInput) {
    return await this.forumService.createTopic(input);
  }
}
```

### 3. Build

```bash
# Build once
kahkeshan-addon build

# Or watch mode during development
kahkeshan-addon build --watch
```

### 4. Validate

```bash
kahkeshan-addon validate
```

Output:
```
✔ Validation passed

Your addon structure looks good!
```

### 5. Package

```bash
kahkeshan-addon package
```

Output:
```
✔ Addon packaged successfully!
  dist/forum@1.0.0.tar.gz (42.5 KB)

Next step:
  kahkeshan-addon upload dist/forum@1.0.0.tar.gz
```

### 6. Upload

```bash
kahkeshan-addon upload dist/forum@1.0.0.tar.gz --token YOUR_TOKEN
```

Output:
```
✔ Addon uploaded successfully!

Addon ID: addon:forum
Addon has been installed and is ready for activation.
```

### 7. Activate

Go to Kahkeshan admin panel:
1. Navigate to your planet settings
2. Go to "Addons" section
3. Find "Forum" in the list
4. Click "Enable"
5. Configure addon settings if needed

## Development Tips

### Watch Mode

Use watch mode for rapid development:

```bash
# Terminal 1: Build in watch mode
kahkeshan-addon build --watch

# Terminal 2: Run validation periodically
watch -n 5 kahkeshan-addon validate
```

### Hot Reload

For local testing without upload:

```bash
# Link addon locally (in addon directory)
npm link

# In main project
npm link @kahkeshan/addon-my-addon
```

### Environment Setup

Create `.env` file in your addon directory:

```bash
KAHKESHAN_URL=http://localhost:4001
KAHKESHAN_TOKEN=your-dev-token-here
```

Then upload becomes:

```bash
kahkeshan-addon upload dist/my-addon@1.0.0.tar.gz
```

### Version Management

Update version in `manifest.ts`:

```typescript
export const manifest: AddonManifest = {
  addonId: 'addon:my-addon',
  name: 'My Addon',
  version: '1.1.0',  // Updated version
  // ...
};
```

Then rebuild and package:

```bash
kahkeshan-addon build
kahkeshan-addon package
# Creates: dist/my-addon@1.1.0.tar.gz
```

## Troubleshooting

### Command Not Found

```bash
# Re-link the CLI
cd tools/addon-cli
npm link

# Or use full path
node tools/addon-cli/dist/index.js init my-addon
```

### Validation Errors

```bash
✖ Validation failed

Errors:
  - manifest.ts not found
  - Missing required field: addonId

Warnings:
  - package.json not found
```

**Solution**: Ensure you're in the addon directory and all required files exist.

### Upload Fails

```bash
✖ Upload failed
Server error: 401
{"error": "Unauthorized"}
```

**Solutions:**
- Verify authentication token is valid
- Check if token has expired
- Ensure platform URL is correct

### Package Too Large

```bash
⚠ Warning: Package size is 15.3 MB
```

**Solution**: Exclude unnecessary files:

```bash
# Add to .gitignore
node_modules/
dist/
test/
*.log
.env
```

## CI/CD Integration

### GitHub Actions

```yaml
name: Build and Upload Addon

on:
  push:
    tags:
      - 'v*'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install CLI
        run: |
          cd tools/addon-cli
          npm install
          npm run build
          npm link
      
      - name: Build Addon
        run: |
          cd my-addon
          npm install
          kahkeshan-addon build
      
      - name: Validate
        run: |
          cd my-addon
          kahkeshan-addon validate
      
      - name: Package
        run: |
          cd my-addon
          kahkeshan-addon package
      
      - name: Upload to Platform
        env:
          KAHKESHAN_TOKEN: ${{ secrets.KAHKESHAN_TOKEN }}
        run: |
          cd my-addon
          kahkeshan-addon upload dist/*.tar.gz \
            --url https://api.kahkeshan.com
```

## API Reference

### AddonManifest Interface

```typescript
export interface AddonManifest {
  addonId: string;              // 'addon:my-addon'
  name: string;                 // 'My Addon'
  version: string;              // '1.0.0' (semver)
  description?: string;
  author?: string;
  license?: string;
  
  dependencies?: {
    core?: string;              // '^1.0.0'
    addons?: Record<string, string>;
    npm?: string[];
  };
  
  permissions?: {
    database?: Array<{
      collection: string;
      operations: string[];
    }>;
    storage?: boolean;
    messaging?: boolean;
    graphql?: boolean;
    webhooks?: boolean;
  };
  
  hooks?: {
    onInstall?: string;
    onEnable?: string;
    onDisable?: string;
    onUninstall?: string;
    onUpdate?: string;
  };
  
  config?: {
    schema?: Record<string, any>;
    defaults?: Record<string, any>;
  };
  
  assets?: {
    icon?: string;
    screenshots?: string[];
    static?: string;
  };
  
  endpoints?: {
    graphql?: boolean;
    rest?: boolean;
    websocket?: boolean;
  };
}
```

## Support

- **Issues**: [github.com/hamid-rayati/galaxy-backend-nestjs/issues](https://github.com/hamid-rayati/galaxy-backend-nestjs/issues)
- **Documentation**: [docs/addons/](../../docs/addons/)
- **Examples**: [apps/addons/wall/](../../apps/addons/wall/)

## License

MIT