open-index/open-npm huggingface dataset:
npm package: @korajs/cli
Description: Kora.js CLI tooling and project scaffolding
Latest version: 0.1.15

# @korajs/cli

CLI tooling for Kora.js. Scaffold new apps, run the development server, manage schema migrations, and generate TypeScript types.

## Install

```bash
pnpm add -g @korajs/cli
```

Or use directly with `npx`:

```bash
npx create-kora-app my-app
```

## Commands

### create-kora-app

Scaffold a new Kora.js project:

```bash
npx create-kora-app my-app

# Interactive prompts:
#   Select a template: React (basic) | React (with sync)
#   Package manager: pnpm | npm | yarn | bun
```

### kora dev

Start the development environment:

```bash
kora dev
```

This runs:
- Vite dev server for your application
- Kora sync server (if configured)
- Schema file watcher with auto type generation
- Embedded DevTools (toggle with `Ctrl+Shift+K`)

### kora migrate

Detect schema changes and generate migrations:

```bash
kora migrate
# Detects changes, generates migration file, prompts to apply
```

### kora generate types

Generate TypeScript types from your schema:

```bash
kora generate types
# Output: kora/generated/types.ts
```

## Quick Start

```bash
npx create-kora-app my-app
cd my-app
pnpm dev
```

You'll have a working offline-first app in under 2 minutes.

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/core
Description: Kora.js core package
Latest version: 0.1.3

# @korajs/core

Schema definitions, operations, Hybrid Logical Clock, version vectors, and type inference for Kora.js. This is the foundation package -- all other packages depend on it.

> Most developers don't install this directly. Use [`korajs`](https://www.npmjs.com/package/korajs) instead.

## Install

```bash
pnpm add @korajs/core
```

## Usage

### Define a Schema

```typescript
import { defineSchema, t } from '@korajs/core'

const schema = defineSchema({
  version: 1,
  collections: {
    todos: {
      fields: {
        title: t.string(),
        completed: t.boolean().default(false),
        tags: t.array(t.string()).default([]),
        notes: t.richtext(),
        priority: t.enum(['low', 'medium', 'high']).default('medium'),
        createdAt: t.timestamp().auto(),
      },
      indexes: ['completed'],
    },
  },
})
```

### Hybrid Logical Clock

```typescript
import { HybridLogicalClock } from '@korajs/core'

const clock = new HybridLogicalClock('node-1')

const ts1 = clock.now()
const ts2 = clock.now()

// Timestamps are always monotonically increasing
HybridLogicalClock.compare(ts1, ts2) // negative (ts1 < ts2)

// Merge with a remote timestamp
const ts3 = clock.receive(remoteTimestamp)
```

### Version Vectors

```typescript
import { mergeVectors, deltaOperations } from '@korajs/core'

const merged = mergeVectors(localVector, remoteVector)
const missing = deltaOperations(localVector, remoteVector, operationLog)
```

## What's Inside

- **Schema system** -- `defineSchema`, `t` field builders, full TypeScript type inference
- **Operation type** -- immutable, content-addressed mutation records
- **Hybrid Logical Clock** -- causal ordering without synchronized clocks
- **Version vectors** -- efficient delta sync computation
- **Error types** -- structured `KoraError` base class

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/devtools
Description: Kora.js devtools package
Latest version: 0.1.3

# @korajs/devtools

Browser DevTools extension for Kora.js. Inspect operations, trace conflict resolution decisions, monitor sync status, and debug your offline-first app in real time.

## Install

```bash
pnpm add -D @korajs/devtools
```

## Enable

Add `devtools: true` to your app config:

```typescript
import { createApp } from 'korajs'

const app = createApp({
  schema,
  devtools: process.env.NODE_ENV === 'development',
})
```

When enabled, the Kora DevTools panel appears in your browser's developer tools.

## Panels

### Sync Timeline
Horizontal timeline of operations and sync events, color-coded by type. Click any event to inspect it. Causal arrows show dependencies between operations.

### Conflict Inspector
Table of all merge events, filterable by collection, tier, and strategy. Expand any row to see the full `MergeTrace` -- input values, base value, resolved output, and which tier handled it.

### Operation Log
Searchable list of all operations. Click an operation to view its full payload, causal dependencies, and the database state at that point in time.

### Network Status
Real-time connection quality indicator, pending operation count, bandwidth graph, and last sync timestamp.

## Instrumentation Events

The DevTools extension listens for events emitted by the Kora runtime:

- `operation:created` / `operation:applied`
- `merge:started` / `merge:completed` / `merge:conflict`
- `sync:connected` / `sync:disconnected` / `sync:sent` / `sync:received`
- `query:subscribed` / `query:invalidated` / `query:executed`
- `connection:quality`

## Keyboard Shortcut

In development mode, press `Ctrl+Shift+K` (or `Cmd+Shift+K` on macOS) to toggle the embedded DevTools overlay.

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/merge
Description: Kora.js merge package
Latest version: 0.1.2

# @korajs/merge

Three-tier conflict resolution engine for Kora.js. Handles concurrent modifications across offline devices and produces deterministic, commutative merge results.

> Most developers don't install this directly. Use [`korajs`](https://www.npmjs.com/package/korajs) instead.

## Install

```bash
pnpm add @korajs/merge
```

## How It Works

The merge engine resolves conflicts in three tiers:

**Tier 1 -- Auto-Merge (default for all fields):**
- `string`, `number`, `boolean`, `enum`, `timestamp` -- Last-Write-Wins via HLC
- `array` -- Add-wins set (union of elements)
- `richtext` -- Yjs CRDT (character-level merge)

**Tier 2 -- Constraint Validation:**
After auto-merge, constraints (unique, capacity, referential) are checked. Violations trigger the configured `onConflict` strategy.

**Tier 3 -- Custom Resolvers:**
For domain-specific logic that neither auto-merge nor constraints can handle.

## Usage

```typescript
import { MergeEngine } from '@korajs/merge'

const engine = new MergeEngine({ schema })

// Merge two concurrent operations
const result = engine.merge(localOperation, remoteOperation)

// result.value   -- the resolved value
// result.trace   -- full MergeTrace for debugging/DevTools
// result.tier    -- which tier resolved it (1, 2, or 3)
```

### Custom Resolver

```typescript
const schema = defineSchema({
  collections: {
    inventory: {
      fields: {
        productId: t.string(),
        quantity: t.number(),
      },
      resolve: {
        quantity: (local, remote, base) => {
          // Additive merge: apply both deltas
          const localDelta = local - base
          const remoteDelta = remote - base
          return Math.max(0, base + localDelta + remoteDelta)
        },
      },
    },
  },
})
```

## Guarantees

- **Deterministic** -- same operations always produce the same result
- **Commutative** -- `merge(A, B)` equals `merge(B, A)`
- **Idempotent** -- applying the same operation twice has no additional effect
- **Traceable** -- every decision produces a `MergeTrace` for inspection

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/react
Description: Kora.js React hooks and bindings for offline-first applications
Latest version: 0.1.6

# @korajs/react

React hooks and bindings for Kora.js. Reactive queries that update automatically, optimistic mutations, sync status tracking, and rich text editing support.

## Install

```bash
pnpm add korajs @korajs/react
```

## Usage

### Provider

```tsx
import { KoraProvider } from '@korajs/react'

function App() {
  return (
    <KoraProvider app={app}>
      <TodoList />
    </KoraProvider>
  )
}
```

### Reactive Queries

```tsx
import { useQuery } from '@korajs/react'

function TodoList() {
  const todos = useQuery(app.todos.where({ completed: false }).orderBy('createdAt'))
  // Always up to date. No loading state needed for local data.

  return todos.map((todo) => <TodoItem key={todo.id} todo={todo} />)
}
```

### Mutations

```tsx
import { useMutation } from '@korajs/react'

function AddTodo() {
  const addTodo = useMutation(app.todos.insert)

  return <button onClick={() => addTodo({ title: 'New todo' })}>Add</button>
}
```

### Sync Status

```tsx
import { useSyncStatus } from '@korajs/react'

function SyncIndicator() {
  const status = useSyncStatus()
  // 'connected' | 'syncing' | 'synced' | 'offline' | 'error'
  return <span>{status}</span>
}
```

All hooks use `useSyncExternalStore` for React 18+ concurrent mode safety.

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/server
Description: Kora.js self-hosted sync server
Latest version: 0.1.7

# @korajs/server

Self-hosted sync server for Kora.js applications. Accepts WebSocket and HTTP connections from Kora clients, stores operations, and relays changes between devices. Supports multiple storage backends via Drizzle ORM.

## Install

```bash
pnpm add @korajs/server
```

## Quick Start

```typescript
import { createKoraServer, MemoryServerStore } from '@korajs/server'

const server = createKoraServer({
  store: new MemoryServerStore(),
  port: 4567,
})

await server.start()
// Kora sync server listening on ws://localhost:4567
```

## Production Setup with PostgreSQL

```typescript
import { createKoraServer, PostgresServerStore, TokenAuthProvider } from '@korajs/server'

const server = createKoraServer({
  store: new PostgresServerStore({
    connectionString: process.env.DATABASE_URL,
  }),
  port: 4567,
  auth: new TokenAuthProvider({
    validate: async (token) => {
      // Validate JWT or session token
      const user = await verifyToken(token)
      return { userId: user.id, scopes: { todos: { userId: user.id } } }
    },
  }),
})

await server.start()
```

## Storage Backends

| Backend | Package | Use Case |
|---------|---------|----------|
| `MemoryServerStore` | Built-in | Development and testing |
| `SqliteServerStore` | Built-in | Small deployments, prototyping |
| `PostgresServerStore` | Built-in | Production |

## Configuration

```typescript
createKoraServer({
  store: serverStore,         // Required: storage backend
  port: 4567,                 // Default: 4567
  auth: authProvider,         // Optional: authentication provider
  batchSize: 1000,            // Optional: max operations per sync batch
  maxConnections: 0,          // Optional: 0 = unlimited
})
```

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/store
Description: Kora.js store package
Latest version: 0.1.2

# @korajs/store

Local storage engine for Kora.js. Supports SQLite WASM with OPFS persistence, IndexedDB fallback, and native SQLite for server-side use. Provides CRUD operations, reactive queries, and subscriptions.

> Most developers don't install this directly. Use [`korajs`](https://www.npmjs.com/package/korajs) instead.

## Install

```bash
pnpm add @korajs/store
```

## Usage

### Create a Store

```typescript
import { createStore } from '@korajs/store'
import { defineSchema, t } from '@korajs/core'

const schema = defineSchema({
  version: 1,
  collections: {
    todos: {
      fields: {
        title: t.string(),
        completed: t.boolean().default(false),
        createdAt: t.timestamp().auto(),
      },
    },
  },
})

const store = await createStore({ schema, adapter: 'sqlite-wasm' })
```

### Insert and Query

```typescript
await store.insert('todos', { title: 'Ship Kora v1' })

const active = await store.query('todos', {
  where: { completed: false },
  orderBy: { createdAt: 'desc' },
  limit: 10,
})
```

### Reactive Subscriptions

```typescript
const unsubscribe = store.subscribe(
  { collection: 'todos', where: { completed: false }, orderBy: { createdAt: 'asc' } },
  (todos) => {
    // Called immediately with current data, then on every change
    console.log(todos)
  }
)
```

## Storage Adapters

| Adapter | Environment | Persistence |
|---------|-------------|-------------|
| `sqlite-wasm` | Browser (default) | OPFS |
| `indexeddb` | Browser (fallback) | IndexedDB |
| `sqlite-native` | Node.js / Electron | Filesystem |

The adapter is selected automatically based on environment. SQLite WASM runs in a Web Worker to avoid blocking the main thread.

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korajs/sync
Description: Kora.js sync package
Latest version: 0.1.5

# @korajs/sync

Sync protocol and transports for Kora.js. Handles version vector delta sync, causal ordering, Protobuf wire format, and automatic reconnection with operation queuing.

> Most developers don't install this directly. Use [`korajs`](https://www.npmjs.com/package/korajs) instead.

## Install

```bash
pnpm add @korajs/sync
```

## Usage

### WebSocket Transport

```typescript
import { SyncEngine, WebSocketTransport } from '@korajs/sync'

const transport = new WebSocketTransport({
  url: 'wss://my-server.com/kora',
  auth: async () => ({ token: await getAuthToken() }),
})

const sync = new SyncEngine({
  transport,
  mergeEngine,
  operationLog,
})

sync.start()
```

### HTTP Transport

```typescript
import { HttpTransport } from '@korajs/sync'

const transport = new HttpTransport({
  url: 'https://my-server.com/kora/sync',
  pollInterval: 5000,
})
```

### Sync Events

```typescript
sync.on('connected', () => console.log('Connected'))
sync.on('disconnected', (reason) => console.log('Disconnected:', reason))
sync.on('sent', (ops) => console.log('Sent', ops.length, 'operations'))
sync.on('received', (ops) => console.log('Received', ops.length, 'operations'))
```

## Protocol

1. **Handshake** -- exchange version vectors to determine what each side is missing
2. **Delta sync** -- send only the operations the other side doesn't have
3. **Real-time streaming** -- bidirectional operation flow after initial sync
4. **Resumable** -- reconnects pick up from the last acknowledged sequence number

Operations are always sent in causal order. The protocol is idempotent -- duplicate operations are detected via content-addressing and safely ignored.

## License

MIT

See the [full documentation](https://github.com/ehoneahobed/kora) for guides, API reference, and examples.
npm package: @korala/api-client
Description: TypeScript API client for Korala document signing API
Latest version: 1.2.0

# @korala/api-client

TypeScript API client for the [Korala](https://korala.ai) document signing platform.

## Installation

```bash
npm install @korala/api-client
```

## Authentication

Korala uses HMAC signature authentication. You'll need an API key ID and secret from your [Korala dashboard](https://korala.ai).

```typescript
import { KoralaClient } from '@korala/api-client';

const client = new KoralaClient({
  apiKeyId: 'your-api-key-id',
  apiSecret: 'your-api-secret',
  baseUrl: 'https://api.korala.ai/api/v1', // optional, defaults to production
});
```

## Usage

### Create and send a document

```typescript
// Upload a PDF
const { documentId, uploadUrl } = await client.documents.createUploadUrl({
  fileName: 'contract.pdf',
  contentType: 'application/pdf',
});

// Upload the file to the presigned URL
await fetch(uploadUrl, { method: 'PUT', body: pdfBuffer });

// Confirm the upload
await client.documents.confirmUpload(documentId);

// Add a signer
const signer = await client.signers.create(documentId, {
  name: 'John Doe',
  email: 'john@example.com',
});

// Add a signature field
await client.fields.create(documentId, {
  signerId: signer.id,
  fieldType: 'signature',
  pageNumber: 1,
  xPosition: 100,
  yPosition: 500,
  width: 200,
  height: 50,
});

// Send for signing
await client.documents.send(documentId);
```

### Create a document from a template

```typescript
const document = await client.templates.createDocument(templateId, {
  name: 'Sales Agreement - Acme Corp',
  signers: {
    buyer: { name: 'Jane Smith', email: 'jane@acme.com' },
  },
  variables: {
    company_name: 'Acme Corporation',
    contract_date: '2026-03-16',
  },
});
```

### Bulk sign (countersign)

Sign multiple documents at once using a saved signature:

```typescript
// Create a saved signature for the signer
await client.signatures.create({
  email: 'ceo@company.com',
  name: 'Jane Smith',
  signatureImageUrl: 'https://example.com/signature.png',
  isDefault: true,
});

// Bulk sign all pending documents
const result = await client.documents.bulkSign({
  documentIds: ['doc-1', 'doc-2', 'doc-3'],
  signerEmail: 'ceo@company.com',
});

console.log(`${result.signed} signed, ${result.failed} failed`);
```

### Webhooks

```typescript
const webhook = await client.webhooks.create({
  url: 'https://your-app.com/webhooks/korala',
  events: ['document.completed', 'document.signed'],
});
```

## API Reference

| Resource | Methods |
|----------|---------|
| `client.documents` | `createUploadUrl`, `confirmUpload`, `list`, `get`, `send`, `void`, `getAuditTrail`, `bulkSign` |
| `client.signers` | `list`, `create` |
| `client.fields` | `list`, `create`, `update`, `delete` |
| `client.signatures` | `list`, `get`, `create`, `delete` |
| `client.templates` | `list`, `get`, `createDocument`, `generate` |
| `client.webhooks` | `list`, `get`, `create`, `update`, `delete` |

## License

MIT
npm package: @korala/auth
Description: HMAC authentication utilities for the Korala document signing API
Latest version: 1.1.0

# @korala/auth

HMAC authentication utilities for the [Korala](https://korala.ai) document signing API.

## Installation

```bash
npm install @korala/auth
```

## Usage

### Sign API requests

```typescript
import { signRequest } from '@korala/auth';

const { signature, timestamp } = signRequest({
  method: 'POST',
  path: '/api/v1/documents',
  body: JSON.stringify({ name: 'Contract' }),
  secret: 'your-api-secret',
});

// Use in request headers
fetch('https://api.korala.ai/api/v1/documents', {
  method: 'POST',
  headers: {
    'X-API-Key': 'your-api-key-id',
    'X-Timestamp': String(timestamp),
    'X-Signature': signature,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Contract' }),
});
```

### Verify webhook signatures

```typescript
import { verifyWebhookSignature } from '@korala/auth';

const isValid = verifyWebhookSignature({
  payload: rawBody,
  signature: headers['x-signature'],
  timestamp: headers['x-timestamp'],
  secret: webhookSecret,
});
```

> **Note:** Most users should use `@korala/api-client` which handles authentication automatically. This package is for advanced use cases or custom HTTP clients.

## API

| Function | Description |
|----------|-------------|
| `signRequest(opts)` | Generate HMAC signature + timestamp for an API request |
| `verifySignature(opts)` | Verify an incoming API request signature |
| `signWebhookPayload(payload, secret)` | Sign a webhook payload |
| `verifyWebhookSignature(opts)` | Verify a webhook delivery signature |
| `computeSignature(message, secret)` | Low-level HMAC-SHA256 computation |
| `getTimestamp()` | Get current Unix timestamp in seconds |
| `isTimestampValid(timestamp, maxAge?)` | Check if a timestamp is within the allowed window |

## Documentation

Full documentation at [docs.korala.ai](https://docs.korala.ai).

## License

MIT
npm package: @korala/public-dtos
Description: Public TypeScript types for the Korala document signing API
Latest version: 1.2.0

# @korala/public-dtos

TypeScript type definitions for the [Korala](https://korala.ai) document signing API.

## Installation

```bash
npm install @korala/public-dtos
```

## Usage

```typescript
import {
  DocumentStatus,
  FieldType,
  type DocumentDto,
  type SignerDto,
} from '@korala/public-dtos';

function isComplete(doc: DocumentDto): boolean {
  return doc.status === DocumentStatus.Completed;
}
```

> **Note:** Most users should use `@korala/api-client` which re-exports all types from this package. Install this package directly only if you need the types without the API client.

## Exported Types

### Enums

| Enum | Values |
|------|--------|
| `DocumentStatus` | `Draft`, `Pending`, `Completed`, `Voided`, `Declined` |
| `FieldType` | `Signature`, `Initials`, `Date`, `Text`, `Checkbox` |
| `AuthMethod` | `Bearer`, `Hmac` |
| `SignerStatus` | `Pending`, `Viewed`, `Signed`, `Declined` |

### DTOs

Documents, signers, fields, templates, webhooks, signatures, and all request/response types used by the Korala API.

## Documentation

Full API documentation at [docs.korala.ai](https://docs.korala.ai).

## License

MIT