# @serve.zone/interfaces 📋

**TypeScript interfaces for the Cloudly ecosystem.** Type-safe contracts for multi-cloud infrastructure management.

## 🎯 What is @serve.zone/interfaces?

This package provides the complete set of TypeScript interfaces that power the Cloudly platform. It ensures type safety and consistency across all components - from API requests to data models, from service definitions to infrastructure configurations.

## ✨ Features

- **🔒 Type Safety** - Comprehensive TypeScript interfaces for all Cloudly operations
- **📦 Modular Structure** - Organized by domain for easy navigation
- **🔄 Version Compatibility** - Interfaces versioned with the platform
- **📚 Well Documented** - Each interface includes JSDoc comments
- **🎭 Multi-Purpose** - Used by API clients, CLI tools, and web interfaces
- **✅ Validation Ready** - Compatible with runtime type checking libraries

## 🚀 Installation

```bash
pnpm add @serve.zone/interfaces
```

## 🏗️ Interface Categories

### 📡 Request/Response Interfaces

Typed contracts for API communication:

```typescript
import { 
  IRequest_GetAllImages,
  IRequest_CreateCluster,
  IRequest_DeployService 
} from '@serve.zone/interfaces';

// Type-safe request
const request: IRequest_GetAllImages['request'] = {
  identity: userIdentity,
  filters: {
    tag: 'production'
  }
};

// Type-safe response
const response: IRequest_GetAllImages['response'] = {
  images: [...]
};
```

### 📦 Data Models

Core data structures for Cloudly entities:

```typescript
import { 
  ICluster, 
  IService, 
  IImage, 
  ISecret,
  IServer 
} from '@serve.zone/interfaces';

// Define a service
const service: IService = {
  id: 'service-123',
  data: {
    name: 'api-service',
    imageId: 'image-456',
    imageVersion: '2.0.0',
    environment: {
      NODE_ENV: 'production'
    },
    scaleFactor: 3,
    balancingStrategy: 'round-robin',
    ports: {
      web: 80,
      metrics: 9090
    },
    domains: [
      { name: 'api.example.com' }
    ],
    deploymentIds: [],
    deploymentDirectiveIds: []
  }
};
```

### 🔐 Authentication & Identity

Identity management interfaces:

```typescript
import { 
  IIdentity, 
  IServiceToken,
  IPermission 
} from '@serve.zone/interfaces';

const identity: IIdentity = {
  id: 'user-789',
  name: 'service-account',
  type: 'service',
  permissions: ['cluster:read', 'service:write'],
  tokenHash: 'hashed-token',
  metadata: {
    createdAt: new Date(),
    lastAccess: new Date()
  }
};
```

### 🌐 Network Configuration

Networking and routing interfaces:

```typescript
import { 
  IReverseProxyConfig,
  IDomainConfig,
  ILoadBalancerConfig 
} from '@serve.zone/interfaces';

const proxyConfig: IReverseProxyConfig = {
  domain: 'app.example.com',
  path: '/api',
  serviceAddress: 'http://api-service:3000',
  ssl: true,
  headers: {
    'X-Real-IP': '$remote_addr'
  }
};
```

### 📊 Monitoring & Metrics

Observability interfaces:

```typescript
import { 
  IServerMetrics,
  IServiceMetrics,
  IClusterHealth 
} from '@serve.zone/interfaces';

const metrics: IServerMetrics = {
  serverId: 'server-001',
  cpuUsageInPercent: 65,
  memoryUsageinMB: 3072,
  memoryAvailableInMB: 8192,
  diskUsageInPercent: 40,
  networkInMbps: 100,
  networkOutMbps: 150,
  containerCount: 12,
  containerMetrics: [...]
};
```

### 🔒 Secret Management

Security and credential interfaces:

```typescript
import { 
  ISecretGroup,
  ISecretBundle,
  IEncryptedData 
} from '@serve.zone/interfaces';

const secretGroup: ISecretGroup = {
  id: 'secrets-123',
  name: 'database-credentials',
  secrets: [
    {
      key: 'DB_HOST',
      value: 'encrypted-value',
      encrypted: true
    },
    {
      key: 'DB_PASSWORD',
      value: 'encrypted-value',
      encrypted: true
    }
  ],
  metadata: {
    environment: 'production',
    service: 'api'
  }
};
```

## 📚 Common Usage Patterns

### Creating Type-Safe API Clients

```typescript
import { 
  IRequest_CreateService,
  IService 
} from '@serve.zone/interfaces';

class ServiceClient {
  async createService(
    serviceData: IService['data']
  ): Promise<IService> {
    const request: IRequest_CreateService['request'] = {
      identity: this.identity,
      serviceData
    };
    
    const response = await this.client.send<IRequest_CreateService>(
      'createService',
      request
    );
    
    return response.service;
  }
}
```

### Validating Incoming Data

```typescript
import { ICluster } from '@serve.zone/interfaces';
import { validateType } from 'your-validation-library';

function validateClusterData(data: unknown): ICluster {
  if (!validateType<ICluster>(data)) {
    throw new Error('Invalid cluster data');
  }
  return data;
}
```

### Building Configuration Objects

```typescript
import { 
  ICloudlyConfig,
  IMongoDescriptor 
} from '@serve.zone/interfaces';

const config: ICloudlyConfig = {
  cfToken: process.env.CF_TOKEN!,
  hetznerToken: process.env.HETZNER_TOKEN!,
  environment: 'production',
  letsEncryptEmail: 'certs@example.com',
  publicUrl: 'cloudly.example.com',
  publicPort: 443,
  mongoDescriptor: {
    mongoDbUrl: process.env.MONGO_URL!,
    mongoDbName: 'cloudly',
    mongoDbUser: process.env.MONGO_USER!,
    mongoDbPass: process.env.MONGO_PASS!
  }
};
```

## 🎯 Advanced Features

### Generic Request Handler

```typescript
import { ITypedRequest } from '@serve.zone/interfaces';

class RequestHandler {
  async handle<T extends ITypedRequest>(
    request: T['request']
  ): Promise<T['response']> {
    // Type-safe request handling
    return this.processRequest(request);
  }
}
```

### Discriminated Unions

```typescript
import { IDeploymentStatus } from '@serve.zone/interfaces';

function handleStatus(status: IDeploymentStatus) {
  switch (status.type) {
    case 'pending':
      console.log('Deployment pending...');
      break;
    case 'running':
      console.log(`Running on ${status.serverId}`);
      break;
    case 'failed':
      console.log(`Failed: ${status.error}`);
      break;
  }
}
```

### Extending Interfaces

```typescript
import { IService } from '@serve.zone/interfaces';

interface IExtendedService extends IService {
  customMetadata: {
    team: string;
    costCenter: string;
    sla: 'standard' | 'premium';
  };
}
```

## 🔄 Version Compatibility

| @serve.zone/interfaces | @serve.zone/cloudly | @serve.zone/api | @serve.zone/cli |
|------------------------|---------------------|-----------------|-----------------|
| 5.x                    | 5.x                 | 5.x             | 5.x             |
| 4.x                    | 4.x                 | 4.x             | 4.x             |
| 3.x                    | 3.x                 | 3.x             | 3.x             |

## 📖 Interface Documentation

All interfaces include comprehensive JSDoc comments:

```typescript
/**
 * Represents a cluster configuration
 * @interface ICluster
 */
export interface ICluster {
  /**
   * Unique identifier for the cluster
   * @type {string}
   */
  id: string;
  
  /**
   * Cluster configuration data
   * @type {IClusterData}
   */
  data: IClusterData;
}
```

## 🛠️ Development Tips

### Import Organization

```typescript
// Group imports by category
import { 
  // Data models
  ICluster,
  IService,
  IImage,
  
  // Requests
  IRequest_CreateCluster,
  IRequest_DeployService,
  
  // Configuration
  ICloudlyConfig,
  IReverseProxyConfig
} from '@serve.zone/interfaces';
```

### Type Guards

```typescript
import { IService, ICluster } from '@serve.zone/interfaces';

function isService(entity: IService | ICluster): entity is IService {
  return 'imageId' in entity.data;
}
```

## License and Legal Information

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. 

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

### Company Information

Task Venture Capital GmbH  
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.