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

# Installation

> Install kSync v0.2 and set up your development environment

## Prerequisites

Before installing kSync v0.2, make sure you have:

<CardGroup cols={2}>
  <Card title="Node.js 18+" icon="node-js">
    kSync v0.2 requires Node.js 18 or higher for modern JavaScript features
  </Card>

  <Card title="TypeScript (Recommended)" icon="typescript">
    TypeScript provides excellent IntelliSense with 50+ configuration options
  </Card>
</CardGroup>

## Package Installation

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @klastra/ksync
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @klastra/ksync
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @klastra/ksync
    ```
  </Tab>

  <Tab title="bun">
    ```bash theme={null}
    bun add @klastra/ksync
    ```
  </Tab>
</Tabs>

<Note>
  **No dependencies required!** kSync v0.2 works out of the box with smart defaults. Zod is optional for advanced schema validation.
</Note>

## Quick Start (30 seconds)

Get running instantly with factory functions:

```typescript theme={null}
import { createKSync } from '@klastra/ksync';

// Works immediately with smart defaults
const ksync = createKSync();

// Send events
await ksync.send('message', { text: 'Hello world!' });

// Listen for events
ksync.on('message', (data) => console.log(data.text));
```

## TypeScript Configuration

For the best experience with TypeScript, add these settings to your `tsconfig.json`:

```json tsconfig.json theme={null}
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react-jsx"  // For React integration
  }
}
```

## Environment Setup

### Browser Environment

For browser applications, kSync v0.2 automatically configures optimal settings:

* **IndexedDB** for local storage with memory fallback
* **Web Locks API** for tab coordination
* **WebSocket** for real-time sync
* **Smart batching** for performance

```typescript theme={null}
import { createKSync } from '@klastra/ksync';

// Browser-optimized configuration
const ksync = createKSync({
  serverUrl: 'ws://localhost:8080', // Your WebSocket server
  // Storage automatically uses IndexedDB
});
```

### Node.js Environment

For server-side or Node.js applications:

```typescript theme={null}
import { createKSync } from '@klastra/ksync';

// Server-optimized configuration
const ksync = createKSync({
  storage: { type: 'memory' }, // Memory storage for servers
  sync: { enabled: false },    // Disable sync on server
});
```

### Bun Environment

kSync v0.2 is optimized for Bun and works perfectly:

```typescript theme={null}
import { createKSync } from '@klastra/ksync';

const ksync = createKSync({
  serverUrl: 'ws://localhost:8080',
  performance: { 
    batchSize: 200,  // Leverage Bun's performance
    batchDelay: 5    // Ultra-low latency
  }
});
```

## Factory Functions

kSync v0.2 provides optimized presets for common use cases:

<CodeGroup>
  ```typescript Chat Application theme={null}
  import { createChat } from '@klastra/ksync';

  // Optimized for chat with presence
  const chat = createChat('room-name', {
    serverUrl: 'ws://localhost:8080'
  });

  await chat.setPresence({ 
    status: 'online', 
    metadata: { name: 'Alice' } 
  });
  ```

  ```typescript Multiplayer Game theme={null}
  import { createGame } from '@klastra/ksync';

  // Optimized for low-latency gaming
  const game = createGame('game-id', {
    performance: { batchDelay: 5 }
  });

  await game.send('player-move', { x: 100, y: 200 });
  ```

  ```typescript AI Application theme={null}
  import { createAI } from '@klastra/ksync';

  // Optimized for AI streaming
  const ai = createAI('assistant', {
    features: { streaming: true }
  });

  ai.on('stream-chunk', (data) => {
    process.stdout.write(data.data);
  });
  ```

  ```typescript Todo Application theme={null}
  import { createTodos } from '@klastra/ksync';

  // Optimized for task management
  const todos = createTodos({
    offline: { persistence: true }
  });

  await todos.send('todo-created', {
    id: 'todo-1',
    title: 'Learn kSync v0.2'
  });
  ```
</CodeGroup>

## Development Server Setup

### Option 1: Use Built-in Server

kSync v0.2 includes a production-ready WebSocket server:

```bash theme={null}
# Clone for development
git clone https://github.com/0ni-x4/ksync.git
cd ksync

# Install dependencies
npm install

# Start the development server
npm run server
```

### Option 2: Custom Server

Create your own high-performance WebSocket server:

<CodeGroup>
  ```typescript Simple Server theme={null}
  import { WebSocketServer } from 'ws';

  const wss = new WebSocketServer({ port: 8080 });
  console.log('🚀 kSync server running on ws://localhost:8080');

  wss.on('connection', (ws) => {
    console.log('📱 Client connected');

    ws.on('message', (data) => {
      // Broadcast to all other clients
      wss.clients.forEach((client) => {
        if (client !== ws && client.readyState === 1) {
          client.send(data);
        }
      });
    });
  });
  ```

  ```typescript Bun Server theme={null}
  // Ultra-fast Bun WebSocket server
  const server = Bun.serve({
    port: 8080,
    fetch(req, server) {
      if (server.upgrade(req)) return;
      return new Response("Upgrade failed", { status: 500 });
    },
    websocket: {
      message(ws, message) {
        ws.publish("global", message); // Broadcast
      },
      open(ws) {
        ws.subscribe("global");
        console.log("📱 Client connected");
      },
    },
  });

  console.log(`🚀 kSync server on ws://localhost:${server.port}`);
  ```

  ```typescript Production Server theme={null}
  import { WebSocketServer } from 'ws';
  import { createServer } from 'http';

  const server = createServer();
  const wss = new WebSocketServer({ server });

  // Room-based routing
  const rooms = new Map();

  wss.on('connection', (ws, request) => {
    let currentRoom = null;
    
    ws.on('message', (data) => {
      try {
        const message = JSON.parse(data.toString());
        
        // Handle room joining
        if (message.type === 'join-room') {
          currentRoom = message.room;
          if (!rooms.has(currentRoom)) {
            rooms.set(currentRoom, new Set());
          }
          rooms.get(currentRoom).add(ws);
          return;
        }
        
        // Broadcast to room
        if (currentRoom && rooms.has(currentRoom)) {
          rooms.get(currentRoom).forEach(client => {
            if (client !== ws && client.readyState === 1) {
              client.send(data);
            }
          });
        }
      } catch (error) {
        console.error('Message error:', error);
      }
    });
    
    ws.on('close', () => {
      if (currentRoom && rooms.has(currentRoom)) {
        rooms.get(currentRoom).delete(ws);
      }
    });
  });

  server.listen(8080, () => {
    console.log('🚀 Production kSync server on port 8080');
  });
  ```
</CodeGroup>

## Performance Optimization

kSync v0.2 is production-ready with enterprise performance:

<Callout type="info">
  **Benchmark Results:**

  * 🎯 **600k+ ops/sec** with 500 concurrent clients
  * 🧠 **2MB memory** for 1000 clients + 10k events
  * 🌐 **Network resilient** - handles 10-200ms latency
  * ⚡ **Sub-5ms** event processing with optimized batching
</Callout>

### Production Configuration

```typescript theme={null}
import { createKSync } from '@klastra/ksync';

const ksync = createKSync({
  // High-performance settings
  performance: {
    batchSize: 200,              // Higher throughput
    batchDelay: 5,               // Low latency
    materializationCaching: true, // Cache computed state
    compressionThreshold: 1024   // Compress large payloads
  },
  
  // Production features
  auth: {
    token: process.env.JWT_TOKEN,
    type: 'bearer'
  },
  
  // Monitoring
  debug: {
    events: false,         // Disable in production
    performance: true,     // Monitor metrics
    sync: false,
    storage: false
  },
  
  // Scaling
  offline: {
    queueSize: 10000,      // Large offline queue
    persistence: true      // Persist across restarts
  }
});
```

## What's Next?

<CardGroup cols={2}>
  <Card title="Quick Start Guide" icon="play" href="/quickstart">
    Build your first real-time app in 2 minutes
  </Card>

  <Card title="Factory Functions" icon="magic-wand" href="/guides/factory-functions">
    Learn about optimized presets for different use cases
  </Card>

  <Card title="Performance Benchmarks" icon="chart-line" href="/benchmarks">
    See detailed performance metrics and optimization tips
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/core">
    Explore all 50+ configuration options and methods
  </Card>
</CardGroup>

***

**kSync v0.2: Enterprise performance with developer-friendly APIs.**
