# TypeScript SDK Reference

The `@aja/motion-pipeline-sdk` package provides a type-safe TypeScript client
for interacting with the Aja Motion Pipeline API.

## Installation

```bash
pnpm add @aja/motion-pipeline-sdk
# or
npm install @aja/motion-pipeline-sdk
# or
yarn add @aja/motion-pipeline-sdk
```

## Quick Start

```typescript
import { createClient } from '@aja/motion-pipeline-sdk';

// Create a client instance
const client = createClient({
  baseUrl: 'https://api.aja.oshun.io',
  auth: {
    type: 'api-key',
    apiKey: 'your-api-key',
  },
});

// Submit a video for processing
const result = await client.submitJob({
  input: {
    type: 'url',
    url: 'https://example.com/dance-video.mp4',
    filename: 'dance-video.mp4',
  },
  pipelineConfig: {
    name: 'my-dance-config',
    domain: 'dance',
    qualityPreset: 'high',
  },
});

if (result.success) {
  console.log('Job submitted:', result.data.jobId);
}
```

## Client Configuration

### `createClient(config: ClientConfig): MotionPipelineClient`

Creates a new SDK client instance.

#### Parameters

| Parameter   | Type          | Required | Description                                      |
| ----------- | ------------- | -------- | ------------------------------------------------ |
| `baseUrl`   | `string`      | Yes      | Base URL of the Motion Pipeline API              |
| `auth`      | `AuthConfig`  | Yes      | Authentication configuration                     |
| `retry`     | `RetryConfig` | No       | Retry behavior configuration                     |
| `timeoutMs` | `number`      | No       | Request timeout in milliseconds (default: 30000) |

#### Auth Configuration

```typescript
// API Key Authentication
const client = createClient({
  baseUrl: 'https://api.aja.oshun.io',
  auth: {
    type: 'api-key',
    apiKey: 'your-api-key',
  },
});

// Bearer Token Authentication
const client = createClient({
  baseUrl: 'https://api.aja.oshun.io',
  auth: {
    type: 'bearer',
    token: 'your-jwt-token',
  },
});

// No Authentication (for local development)
const client = createClient({
  baseUrl: 'http://localhost:3000',
  auth: { type: 'none' },
});
```

#### Retry Configuration

```typescript
const client = createClient({
  baseUrl: 'https://api.aja.oshun.io',
  auth: { type: 'api-key', apiKey: 'your-key' },
  retry: {
    maxAttempts: 3, // Maximum retry attempts
    initialDelayMs: 1000, // Initial delay between retries
    maxDelayMs: 10000, // Maximum delay between retries
    multiplier: 2, // Exponential backoff multiplier
  },
});
```

---

## Job Management

### `submitJob(request: CreateJobRequest): Promise<Result<JobSubmitResponse>>`

Submits a new video for processing.

#### Input Types

```typescript
// URL Input
const result = await client.submitJob({
  input: {
    type: 'url',
    url: 'https://example.com/video.mp4',
    filename: 'video.mp4',
  },
  pipelineConfig: configId('config-123'),
});

// Storage Path Input
const result = await client.submitJob({
  input: {
    type: 'storage',
    storagePath: '/videos/my-video.mp4',
    filename: 'my-video.mp4',
  },
  pipelineConfig: {
    name: 'inline-config',
    domain: 'general',
    qualityPreset: 'standard',
  },
});
```

#### Job Options

```typescript
const result = await client.submitJob({
  input: { type: 'url', url: videoUrl, filename: 'video.mp4' },
  pipelineConfig: configId('config-123'),
  options: {
    priority: 'high', // 'critical' | 'high' | 'normal' | 'low' | 'background'
    tags: ['production', 'dance'], // Organization tags
    timeoutMs: 3600000, // Processing timeout (1 hour)
    webhook: {
      // Webhook notification
      url: 'https://your-app.com/webhooks/aja',
      events: ['completed', 'failed'],
    },
  },
});
```

### `getJob(id: JobId): Promise<Result<Job>>`

Gets details of a specific job.

```typescript
import { jobId } from '@aja/motion-pipeline-sdk';

const result = await client.getJob(jobId('job-abc-123'));

if (result.success) {
  const job = result.data;
  console.log('Status:', job.status);
  console.log('Progress:', job.progress);
  console.log('Created:', job.createdAt);
}
```

### `listJobs(query?: JobListQuery): Promise<Result<JobListResponse>>`

Lists jobs with optional filtering.

```typescript
// List all jobs
const result = await client.listJobs();

// Filter by status
const pending = await client.listJobs({ status: 'pending' });

// Filter by tags
const production = await client.listJobs({ tags: ['production'] });

// Paginated results
const page2 = await client.listJobs({
  limit: 20,
  offset: 20,
  status: 'completed',
});

if (result.success) {
  console.log(`Found ${result.data.total} jobs`);
  for (const job of result.data.jobs) {
    console.log(`${job.id}: ${job.status}`);
  }
}
```

### `cancelJob(id: JobId): Promise<Result<void>>`

Cancels a running or queued job.

```typescript
const result = await client.cancelJob(jobId('job-abc-123'));

if (result.success) {
  console.log('Job cancelled successfully');
}
```

### `retryJob(id: JobId): Promise<Result<JobSubmitResponse>>`

Retries a failed job.

```typescript
const result = await client.retryJob(jobId('job-abc-123'));

if (result.success) {
  console.log('New job ID:', result.data.jobId);
}
```

---

## Streaming Progress

### `streamJobProgress(id: JobId, handlers: StreamHandlers): () => void`

Streams real-time progress updates for a job using Server-Sent Events.

```typescript
import { jobId } from '@aja/motion-pipeline-sdk';

const unsubscribe = client.streamJobProgress(jobId('job-abc-123'), {
  onProgress: (event) => {
    console.log(`Stage: ${event.data.stage}`);
    console.log(`Progress: ${(event.data.progress * 100).toFixed(1)}%`);
  },
  onStageChange: (event) => {
    console.log(`Now processing: ${event.data.stage}`);
  },
  onComplete: (event) => {
    console.log('Job completed!');
    console.log('Outputs:', event.data.outputs);
  },
  onError: (event) => {
    console.error('Job failed:', event.data.error);
  },
});

// Stop streaming when done
unsubscribe();
```

#### Stream Event Types

```typescript
interface StreamEvent {
  type: 'progress' | 'stage_change' | 'complete' | 'error' | 'heartbeat';
  timestamp: string;
  data: {
    jobId: string;
    stage?: string;
    progress?: number;
    message?: string;
    outputs?: JobOutput[];
    error?: string;
  };
}
```

---

## Output Management

### `listOutputs(id: JobId): Promise<Result<OutputListResponse>>`

Lists all output files for a completed job.

```typescript
const result = await client.listOutputs(jobId('job-abc-123'));

if (result.success) {
  for (const output of result.data.outputs) {
    console.log(`${output.name}: ${output.format} (${output.sizeBytes} bytes)`);
  }
}
```

### `generateDownloadUrl(id: JobId, options: DownloadOptions): Promise<Result<DownloadUrlResponse>>`

Generates a signed download URL for job outputs.

```typescript
const result = await client.generateDownloadUrl(jobId('job-abc-123'), {
  format: 'fbx',
  expiresIn: 3600, // URL expires in 1 hour
});

if (result.success) {
  console.log('Download URL:', result.data.url);
  console.log('Expires:', result.data.expiresAt);
}
```

---

## Configuration Management

### `createConfig(config: CreateConfigRequest): Promise<Result<ConfigCreateResponse>>`

Creates a new pipeline configuration.

```typescript
const result = await client.createConfig({
  name: 'dance-production',
  description: 'High-quality dance motion capture',
  domain: 'dance',
  qualityPreset: 'high',
});

if (result.success) {
  console.log('Config created:', result.data.id);
}
```

### `getConfig(id: ConfigId): Promise<Result<PipelineConfiguration>>`

Gets a specific configuration by ID.

```typescript
import { configId } from '@aja/motion-pipeline-sdk';

const result = await client.getConfig(configId('config-123'));

if (result.success) {
  console.log('Config:', result.data.name);
  console.log('Domain:', result.data.domain);
  console.log('Preset:', result.data.qualityPreset);
}
```

### `getConfigByName(name: string): Promise<Result<PipelineConfiguration>>`

Gets a configuration by its name.

```typescript
const result = await client.getConfigByName('dance-production');

if (result.success) {
  console.log('Found config:', result.data.id);
}
```

### `listConfigs(query?: ConfigListQuery): Promise<Result<ConfigListResponse>>`

Lists all configurations.

```typescript
const result = await client.listConfigs();

if (result.success) {
  for (const config of result.data.configs) {
    console.log(`${config.name}: ${config.domain} (${config.qualityPreset})`);
  }
}
```

### `updateConfig(id: ConfigId, updates: UpdateConfigRequest): Promise<Result<PipelineConfiguration>>`

Updates an existing configuration.

```typescript
const result = await client.updateConfig(configId('config-123'), {
  description: 'Updated description',
  qualityPreset: 'ultra',
});

if (result.success) {
  console.log('Config updated');
}
```

### `deleteConfig(id: ConfigId): Promise<Result<void>>`

Deletes a configuration.

```typescript
const result = await client.deleteConfig(configId('config-123'));

if (result.success) {
  console.log('Config deleted');
}
```

---

## Health & Monitoring

### `health(): Promise<Result<ServiceHealth>>`

Gets the health status of the service.

```typescript
const result = await client.health();

if (result.success) {
  console.log('Status:', result.data.status);
  console.log('Uptime:', result.data.uptimeSeconds, 'seconds');

  for (const [name, component] of Object.entries(
    result.data.components ?? {}
  )) {
    console.log(`${name}: ${component.status}`);
  }
}
```

### `queueStats(): Promise<Result<QueueStats>>`

Gets queue statistics.

```typescript
const result = await client.queueStats();

if (result.success) {
  const stats = result.data;
  console.log('Waiting:', stats.waiting);
  console.log('Active:', stats.active);
  console.log('Completed:', stats.completed);
  console.log('Failed:', stats.failed);
}
```

---

## Type Definitions

### Branded Types

The SDK uses branded types for IDs to ensure type safety:

```typescript
import {
  jobId,
  configId,
  type JobId,
  type ConfigId,
} from '@aja/motion-pipeline-sdk';

// Create branded IDs from strings
const jid: JobId = jobId('job-abc-123');
const cid: ConfigId = configId('config-xyz-456');

// Type-safe function calls
client.getJob(jid); // ✓ Valid
client.getJob('string'); // ✗ Type error
```

### Result Type

All SDK methods return a `Result` type for explicit error handling:

```typescript
type Result<T> =
  | { success: true; data: T }
  | { success: false; error: ApiError };

interface ApiError {
  code: string;
  message: string;
  details?: Record<string, unknown>;
}
```

### Job Status

```typescript
type JobStatus =
  | 'pending' // Job created, not yet queued
  | 'queued' // Job in queue, waiting for worker
  | 'processing' // Job actively being processed
  | 'completed' // Job finished successfully
  | 'failed' // Job failed with error
  | 'cancelled'; // Job was cancelled
```

### Pipeline Domains

```typescript
type PipelineDomain =
  | 'general' // All-purpose motion capture
  | 'yoga' // Yoga poses and slow movements
  | 'fitness' // Exercise and workout tracking
  | 'dance' // Dance and choreography
  | 'martial-arts' // Combat sports
  | 'sports'; // Athletic motion
```

### Quality Presets

```typescript
type QualityPreset =
  | 'draft' // Fast, lower quality
  | 'standard' // Balanced
  | 'high' // High quality
  | 'ultra'; // Best quality
```

### Job Priority

```typescript
type JobPriority =
  | 'critical' // Process immediately
  | 'high' // High priority
  | 'normal' // Default priority
  | 'low' // Low priority
  | 'background'; // Process when idle
```

---

## Error Handling

```typescript
const result = await client.submitJob(request);

if (!result.success) {
  const error = result.error;

  switch (error.code) {
    case 'INVALID_INPUT':
      console.error('Invalid video format:', error.message);
      break;
    case 'QUOTA_EXCEEDED':
      console.error('Processing quota exceeded');
      break;
    case 'UNAUTHORIZED':
      console.error('Invalid API key');
      break;
    default:
      console.error('Unexpected error:', error.message);
  }
  return;
}

// Success path
const job = result.data;
```

---

## Best Practices

### 1. Reuse Client Instances

Create a single client instance and reuse it across your application:

```typescript
// client.ts
import { createClient } from '@aja/motion-pipeline-sdk';

export const ajaClient = createClient({
  baseUrl: process.env.AJA_API_URL!,
  auth: {
    type: 'api-key',
    apiKey: process.env.AJA_API_KEY!,
  },
});
```

### 2. Handle All Error Cases

Always check `result.success` before accessing data:

```typescript
const result = await client.getJob(id);
if (!result.success) {
  // Handle error appropriately
  throw new Error(result.error.message);
}
// Now TypeScript knows result.data exists
const job = result.data;
```

### 3. Use Webhooks for Production

For production workloads, use webhooks instead of polling:

```typescript
await client.submitJob({
  input: { type: 'url', url: videoUrl, filename: 'video.mp4' },
  pipelineConfig: configId,
  options: {
    webhook: {
      url: 'https://your-app.com/webhooks/aja',
      events: ['completed', 'failed'],
    },
  },
});
```

### 4. Stream Progress for Long Jobs

For long-running jobs, use streaming instead of polling:

```typescript
const unsubscribe = client.streamJobProgress(jobId, {
  onProgress: (event) => updateUI(event.data.progress),
  onComplete: (event) => handleComplete(event.data),
  onError: (event) => handleError(event.data),
});
```
