# Veilborn Chronicles API Reference

> _Complete reference documentation for the Veilborn Chronicles game engine._

This document provides comprehensive API documentation for the Veilborn
Chronicles tabletop RPG system.

---

## Table of Contents

1. [Overview](#overview)
2. [Core Types](#core-types)
3. [Character Creation API](#character-creation-api)
4. [Combat System API](#combat-system-api)
5. [Abilities API](#abilities-api)
6. [Game State API](#game-state-api)
7. [Multiplayer API](#multiplayer-api)

---

## Overview

The Veilborn Chronicles engine is built as a modular TypeScript/JavaScript
library providing:

- **Character Creation**: Template-based character generation with point-buy
  systems
- **Combat System**: Hex-grid tactical combat with Tide initiative
- **Abilities**: Status effects, cooldowns, channeling, and environmental
  hazards
- **Game State**: Session management with undo/redo and synchronization
- **Multiplayer**: Real-time WebSocket-based multiplayer support

### Installation

```bash
npm install @veilborn/core
```

### Basic Import

```typescript
import {
  createCharacterFromTemplate,
  CombatManager,
  MultiplayerService,
  GameStateManager,
} from '@veilborn/core';
```

---

## Core Types

### Resonance Types

The five fundamental Resonances that define Veilborn abilities:

```typescript
type ResonanceType = 'clarity' | 'flow' | 'presence' | 'root' | 'void';
```

| Resonance  | Domain            | Description                            |
| ---------- | ----------------- | -------------------------------------- |
| `clarity`  | Perception, Truth | Seeing through illusion, understanding |
| `flow`     | Change, Time      | Transformation, probability, destiny   |
| `presence` | Will, Spirit      | Emotional influence, leadership        |
| `root`     | Stability, Matter | Physical endurance, grounding          |
| `void`     | Emptiness, Shadow | Boundaries, dissolution, stealth       |

### Path Names

The twelve character Paths:

```typescript
type PathName =
  | 'seer'
  | 'sage'
  | 'oracle' // Clarity Paths
  | 'weaver'
  | 'herald' // Flow Paths
  | 'champion'
  | 'exemplar' // Presence Paths
  | 'guardian'
  | 'warden' // Root Paths
  | 'shadow'
  | 'mystic'
  | 'harbinger'; // Void Paths
```

### Character Interface

```typescript
interface Character {
  id: string;
  name: string;
  path: PathName;
  awakening: string;
  level: number;
  experience: number;
  resonances: Record<ResonanceType, number>;
  derivedStats: DerivedStats;
  abilities: Ability[];
  inventory: Item[];
  background: Background;
  notes: string;
  createdAt: string;
  updatedAt: string;
}
```

### Derived Stats

```typescript
interface DerivedStats {
  health: { current: number; max: number };
  veilPoints: { current: number; max: number };
  defense: number;
  initiative: number;
  movement: number;
  resonancePool: number;
}
```

---

## Character Creation API

### `createCharacterFromTemplate()`

Creates a new character using the template-based system.

```typescript
function createCharacterFromTemplate(template: CharacterTemplate): Character;
```

**Parameters:**

- `template`: Configuration object for the new character

**Returns:** Complete `Character` object

**Example:**

```typescript
const character = createCharacterFromTemplate({
  name: 'Kelis the Wanderer',
  path: 'weaver',
  awakening: 'thread_dancer',
  resonanceAllocation: {
    clarity: 5,
    flow: 7,
    presence: 4,
    root: 3,
    void: 6,
  },
  backgroundChoice: 'wanderer',
  startingAbilities: ['probability_shift', 'thread_sight'],
});
```

### `validateCharacter()`

Validates a character against game rules.

```typescript
function validateCharacter(character: Character): ValidationResult;

interface ValidationResult {
  valid: boolean;
  errors: string[];
  warnings: string[];
}
```

### `levelUpCharacter()`

Advances a character by one level.

```typescript
function levelUpCharacter(
  character: Character,
  choices: LevelUpChoices
): Character;
```

### Point-Buy System

Characters have **25 points** to distribute among Resonances:

| Resonance Value | Cost          |
| --------------- | ------------- |
| 1-3             | 1 point each  |
| 4-5             | 2 points each |
| 6-7             | 3 points each |
| 8+              | 4 points each |

**Constraints:**

- Minimum: 1 in each Resonance
- Maximum: 8 (before Path bonuses)
- Primary Resonance: +2 bonus from Path
- Secondary Resonance: +1 bonus from Path

---

## Combat System API

### Hex Coordinates

The combat system uses a hex grid with axial coordinates:

```typescript
interface HexCoord {
  q: number; // Column
  r: number; // Row
}
```

### Hex Utility Functions

```typescript
// Calculate distance between two hexes
function hexDistance(a: HexCoord, b: HexCoord): number;

// Get six neighboring hexes
function hexNeighbors(hex: HexCoord): HexCoord[];

// Get all hexes within radius (spiral)
function hexSpiral(center: HexCoord, radius: number): HexCoord[];

// Get hexes at exact distance (ring)
function hexRing(center: HexCoord, radius: number): HexCoord[];

// Get hexes in a line between two points
function hexLine(start: HexCoord, end: HexCoord): HexCoord[];

// Convert hex to unique string key
function hexKey(hex: HexCoord): string;
```

### CombatManager Class

Main class for managing combat encounters.

```typescript
class CombatManager {
  constructor(config?: CombatConfig);

  // Combatant Management
  addCombatant(combatant: Combatant): void;
  removeCombatant(id: string): void;
  getCombatant(id: string): Combatant | undefined;

  // Initiative and Turns
  startCombat(): void;
  endCombat(): void;
  getCurrentTurn(): string | null;
  advanceTurn(): void;

  // Movement
  moveCombatant(id: string, path: HexCoord[]): MoveResult;
  getValidMoves(id: string): HexCoord[];

  // Actions
  performAction(action: CombatAction): ActionResult;
  getAvailableActions(id: string): CombatAction[];
}
```

### Combatant Interface

```typescript
interface Combatant {
  id: string;
  name: string;
  team: 'player' | 'enemy' | 'neutral';
  position: HexCoord;
  stats: CombatStats;
  conditions: StatusEffectInstance[];
  actionsRemaining: number;
  movementRemaining: number;
}

interface CombatStats {
  health: number;
  maxHealth: number;
  defense: number;
  attack: number;
  movement: number;
  initiative: number;
}
```

### Tide Initiative System

Initiative is determined by Tide levels:

```typescript
type TideLevel = 'rising' | 'high' | 'falling' | 'low' | 'slack';

interface TideState {
  level: TideLevel;
  round: number;
  momentum: number;
}
```

**Tide Cycle:**

1. **Rising** - Flow-dominant characters act first
2. **High** - Clarity and Presence excel
3. **Falling** - Root-dominant characters shine
4. **Low** - Void abilities are strongest
5. **Slack** - Normal initiative order

### Terrain System

```typescript
type TerrainType =
  | 'open' // Normal movement
  | 'difficult' // Costs 2 movement
  | 'water' // May require swimming
  | 'elevation' // Height advantage
  | 'void_touched' // Veil effects
  | 'blocked'; // Impassable

interface TerrainHex {
  coord: HexCoord;
  terrain: TerrainType;
  elevation: number;
  cover: number; // 0-100
  effects: string[];
}
```

---

## Abilities API

### Targeting System

```typescript
type TargetingType =
  | 'self'
  | 'single_ally'
  | 'single_enemy'
  | 'single_any'
  | 'area_burst'
  | 'area_cone'
  | 'area_line'
  | 'area_ring'
  | 'terrain'
  | 'direction'
  | 'none';

interface TargetingParams {
  type: TargetingType;
  range: number;
  areaSize?: number;
  areaShape?: AreaShape;
  filter: TargetFilter;
  coneAngle?: number;
}
```

### Area-of-Effect Functions

```typescript
// Circular burst area
function getBurstArea(center: HexCoord, radius: number): HexCoord[];

// Line from start to end
function getLineArea(
  start: HexCoord,
  end: HexCoord,
  width?: number
): HexCoord[];

// Cone in direction
function getConeArea(
  origin: HexCoord,
  direction: HexCoord,
  range: number,
  angle?: number
): HexCoord[];

// Ring at specific radius
function getRingArea(center: HexCoord, radius: number): HexCoord[];

// Cross pattern
function getCrossArea(center: HexCoord, length: number): HexCoord[];

// Wave pattern
function getWaveArea(
  origin: HexCoord,
  direction: HexCoord,
  range: number,
  width: number
): HexCoord[];
```

### Status Effects

```typescript
type EffectCategory =
  | 'buff'
  | 'debuff'
  | 'damage_over_time'
  | 'heal_over_time'
  | 'control'
  | 'movement'
  | 'special';

interface StatusEffectDef {
  id: string;
  name: string;
  description: string;
  category: EffectCategory;
  duration: number; // -1 for permanent
  stackingBehavior: StackingBehavior;
  maxStacks: number;
  ticksPerRound: number;
  statModifiers: StatModifier[];
  damagePerTick?: number;
  healingPerTick?: number;
  preventsMovement?: boolean;
  preventsActions?: boolean;
  isInvisible?: boolean;
}
```

### Standard Effects

| Effect      | Category | Duration | Description                |
| ----------- | -------- | -------- | -------------------------- |
| `blessed`   | buff     | 3 rounds | +2 to all rolls            |
| `haste`     | buff     | 3 rounds | +2 movement, +5 initiative |
| `weakened`  | debuff   | 3 rounds | -2 attack per stack        |
| `stunned`   | control  | 1 round  | Cannot act or react        |
| `burning`   | DoT      | 3 rounds | 2 damage per tick          |
| `poisoned`  | DoT      | 5 rounds | 1 damage per tick          |
| `invisible` | special  | 3 rounds | Cannot be seen             |

### Status Effect Functions

```typescript
// Apply effect to target
function applyStatusEffect(
  effects: StatusEffectInstance[],
  def: StatusEffectDef,
  sourceId: string,
  targetId: string,
  currentRound: number
): StatusEffectInstance[];

// Remove effect
function removeStatusEffect(
  effects: StatusEffectInstance[],
  effectId: string,
  targetId: string
): StatusEffectInstance[];

// Process end-of-round ticks
function tickEffects(
  effects: StatusEffectInstance[],
  currentRound: number,
  definitions: Map<string, StatusEffectDef>
): { effects: StatusEffectInstance[]; ticks: TickResult[] };

// Check if target has effect
function hasEffect(
  effects: StatusEffectInstance[],
  effectId: string,
  targetId: string
): boolean;
```

### Ability Definitions

```typescript
interface AbilityDef {
  id: string;
  name: string;
  description: string;
  targeting: TargetingParams;
  cost: AbilityCost;
  tideCost: number;
  cooldownType: CooldownType;
  cooldownDuration: number;
  maxCharges: number;
  damage?: DamageSpec;
  healing?: HealingSpec;
  statusEffects: StatusEffectApplication[];
  isChanneled: boolean;
  canBeInterrupted: boolean;
  requiredPath?: string;
}
```

### Environmental Effects

```typescript
interface EnvironmentalEffect {
  id: string;
  name: string;
  hexes: HexCoord[];
  hazardType?: HazardType;
  onEnter?: TriggerEffect;
  onExit?: TriggerEffect;
  onStartTurn?: TriggerEffect;
  onEndTurn?: TriggerEffect;
  duration: number;
  spreads?: boolean;
  spreadChance?: number;
  blocksLOS?: boolean;
  providesConcealment?: number;
}
```

---

## Game State API

### GameStateManager Class

Central manager for game session state.

```typescript
class GameStateManager {
  constructor(initialSession: GameSession);

  // State Access
  getSession(): GameSession;
  getVersion(): number;

  // State Updates
  update(
    updater: (session: GameSession) => GameSession,
    changeType: StateChangeType,
    changeData?: Record<string, unknown>
  ): ValidationResult;

  // Actions
  applyAction(
    action: GameAction,
    result?: Record<string, unknown>
  ): ValidationResult;

  // Undo/Redo
  undo(): boolean;
  redo(): boolean;
  canUndo(): boolean;
  canRedo(): boolean;

  // Subscriptions
  subscribe(listener: StateChangeListener): () => void;
}
```

### Session Management

```typescript
// Create new session
function createGameSession(
  name: string,
  mode: GameMode,
  gmUserId: string
): GameSession;

// Validate session
function validateSession(session: GameSession): ValidationResult;

// Serialize/Deserialize
function serializeSession(session: GameSession): string;
function deserializeSession(json: string): GameSession;
```

### Player Management

```typescript
// Add player to session
function addPlayer(
  session: GameSession,
  userId: string,
  role?: PlayerRole
): { session: GameSession; player: Player } | { error: string };

// Remove player
function removePlayer(session: GameSession, playerId: string): GameSession;

// Update player status
function updatePlayer(
  session: GameSession,
  playerId: string,
  updates: Partial<Player>
): GameSession;

// Assign character to player
function assignCharacter(
  session: GameSession,
  playerId: string,
  character: Character
): GameSession;
```

### Phase Management

```typescript
// Start the game
function startGame(session: GameSession): GameSession | { error: string };

// Change phase
function changePhase(session: GameSession, newPhase: GamePhase): GameSession;

// Advance turn
function advanceTurn(session: GameSession): GameSession;

// End game
function endGame(session: GameSession): GameSession;
```

### Snapshots

```typescript
// Create snapshot
function createStateSnapshot(
  session: GameSession,
  description?: string
): StateSnapshot;

// Restore from snapshot
function restoreFromSnapshot(snapshot: StateSnapshot): GameSession;
```

---

## Multiplayer API

### MultiplayerService Class

Main service for real-time multiplayer functionality.

```typescript
class MultiplayerService {
  constructor(config?: MultiplayerConfig);

  // Room Management
  createRoom(
    hostId: string,
    hostName: string,
    roomName: string,
    config?: Partial<RoomConfig>
  ): Room;

  joinRoom(
    roomCode: string,
    playerId: string,
    playerName: string,
    asSpectator?: boolean,
    password?: string
  ): { success: boolean; room?: Room; error?: string };

  leaveRoom(roomId: string, playerId: string): boolean;

  // Game Control
  startGame(roomId: string, initialState?: Partial<GameState>): boolean;
  submitAction(
    roomId: string,
    playerId: string,
    type: string,
    data: unknown
  ): GameAction | null;
  endTurn(roomId: string, playerId: string): boolean;

  // Communication
  sendChat(
    roomId: string,
    senderId: string,
    senderName: string,
    content: string,
    channel?: ChatChannel,
    targetId?: string
  ): ChatMessage | { error: string };
  rollDice(
    roomId: string,
    playerId: string,
    playerName: string,
    notation: string,
    reason?: string,
    isPrivate?: boolean
  ): DiceRoll | { error: string };
  sendEmote(
    roomId: string,
    playerId: string,
    playerName: string,
    emoteType: string
  ): Emote | { error: string };

  // Statistics
  getStats(): MultiplayerStats;
}
```

### Room Configuration

```typescript
interface RoomConfig {
  maxPlayers: number; // Default: 6
  allowSpectators: boolean; // Default: true
  isPrivate: boolean; // Default: false
  password?: string;
  turnTimeLimit?: number; // In milliseconds
  autoSave: boolean; // Default: true
  replayEnabled: boolean; // Default: true
}
```

### Connection Management

```typescript
class ConnectionManager {
  addConnection(playerId: string, socket: WebSocket): void;
  removeConnection(playerId: string): void;
  getConnection(playerId: string): WebSocket | undefined;
  getConnectedPlayers(): string[];
  sendToPlayer(playerId: string, message: Message): boolean;
  broadcast(message: Message, excludeIds?: string[]): number;
  getAverageLatency(playerId: string): number;
}
```

### State Synchronization

```typescript
class StateSyncManager {
  initializeState(roomId: string, initialState: GameState): void;
  getCurrentState(roomId: string): GameState | null;
  applyAction(roomId: string, action: GameAction): GameState | null;
  calculateDelta(
    roomId: string,
    fromVersion: number,
    toVersion: number
  ): StateDelta | null;
  applyDelta(state: GameState, delta: StateDelta): GameState;
}
```

### Turn Management

```typescript
class TurnManager {
  initializeTurnOrder(roomId: string, playerIds: string[]): void;
  getCurrentPlayer(roomId: string): string | null;
  advanceTurn(roomId: string): string | null;
  startTurnTimer(roomId: string, timeLimit: number): void;
  clearTurnTimer(roomId: string): void;
  getRemainingTime(roomId: string, timeLimit: number): number;
  isPlayerTurn(roomId: string, playerId: string): boolean;
}
```

### Chat System

```typescript
class ChatManager {
  sendMessage(
    roomId: string,
    senderId: string,
    senderName: string,
    content: string,
    channel?: 'global' | 'party' | 'whisper',
    targetId?: string
  ): ChatMessage | { error: string };

  getChatHistory(roomId: string, limit?: number): ChatMessage[];
  getMessagesForPlayer(roomId: string, playerId: string): ChatMessage[];
  clearHistory(roomId: string): void;
}
```

### Dice Rolling

```typescript
class DiceRollManager {
  roll(
    roomId: string,
    playerId: string,
    playerName: string,
    diceNotation: string, // e.g., "2d6+3", "1d20-1"
    reason?: string,
    isPrivate?: boolean
  ): DiceRoll | { error: string };

  getRollHistory(
    roomId: string,
    includePrivate?: boolean,
    playerId?: string
  ): DiceRoll[];
  parseDiceNotation(
    notation: string
  ): { count: number; sides: number; modifier: number } | null;
}
```

### Replay System

```typescript
class ReplayManager {
  startRecording(roomId: string): void;
  stopRecording(roomId: string): ReplayEvent[];
  isRoomRecording(roomId: string): boolean;
  recordEvent(roomId: string, type: ReplayEventType, data: unknown): void;
  getRecording(roomId: string): ReplayEvent[];
  getEventsInRange(
    roomId: string,
    startSeq: number,
    endSeq: number
  ): ReplayEvent[];
}
```

### Spectator Mode

```typescript
class SpectatorManager {
  addSpectator(roomId: string, spectatorId: string): void;
  removeSpectator(roomId: string, spectatorId: string): void;
  getSpectators(roomId: string): string[];
  getSpectatorCount(roomId: string): number;
  isSpectator(roomId: string, playerId: string): boolean;
  setSpectatorDelay(roomId: string, delayMs: number): void;
  getSpectatorDelay(roomId: string): number;
}
```

---

## Error Handling

All API functions follow consistent error handling patterns:

### Validation Results

```typescript
interface ValidationResult {
  valid: boolean;
  errors: string[]; // Critical issues that prevent operation
  warnings: string[]; // Non-critical issues that may cause problems
}
```

### Error Responses

Functions that can fail return union types:

```typescript
// Success or error
type Result<T> = T | { error: string };

// Example usage
const result = addPlayer(session, userId);
if ('error' in result) {
  console.error(result.error);
} else {
  console.log('Player added:', result.player);
}
```

---

## Constants

### Game Limits

```typescript
const MAX_PLAYERS = 12;
const MAX_HISTORY_SIZE = 1000;
const MAX_UNDO_DEPTH = 50;
const MAX_ROOMS = 1000;
const DEFAULT_TURN_TIME_LIMIT = 120000; // 2 minutes
const DEFAULT_SPECTATOR_DELAY = 5000; // 5 seconds
```

### Game Phases

```typescript
const GAME_PHASES: GamePhase[] = ['setup', 'playing', 'paused', 'completed'];
const PLAYER_ROLES: PlayerRole[] = ['player', 'gm', 'observer'];
const GAME_MODES: GameMode[] = ['rpg', 'wargame', 'hybrid'];
```

---

_For integration guides and code examples, see
[Integration Guide](02-integration-guide.md)_ _For OpenAPI specifications, see
[OpenAPI Spec](openapi.yaml)_
