ursamu-mud
Version:
Ursamu - Modular MUD Engine with sandboxed scripting and plugin system
571 lines (455 loc) β’ 14.5 kB
Markdown
# Ursamu - Modular MUD Engine
**Ursamu** is a next-generation Multi-User Dungeon (MUD) engine built with TypeScript, featuring a modular plugin system, sandboxed virtual machine for user scripts, hot-reload capabilities, and multi-protocol support.
[](#license)
[](#requirements)
[](#requirements)
## Table of Contents
- [Features](#features)
- [Architecture Overview](#architecture-overview)
- [Quick Start](#quick-start)
- [Core Systems](#core-systems)
- [Multi-Protocol Server](#multi-protocol-server)
- [Plugin System](#plugin-system)
- [Sandboxed Virtual Machine](#sandboxed-virtual-machine)
- [Hot-Reload System](#hot-reload-system)
- [Developer CLI](#developer-cli)
- [Getting Started](#getting-started)
- [Development](#development)
- [Configuration](#configuration)
- [API Documentation](#api-documentation)
- [Contributing](#contributing)
- [License](#license)
## Features
### ποΈ **Modular Architecture**
- Plugin-based system with automatic discovery and lifecycle management
- Hot-reload capabilities for zero-downtime updates
- Sandboxed execution environment for user scripts
- Event-driven architecture with comprehensive monitoring
### π **Multi-Protocol Support**
- **Telnet** - Traditional MUD protocol with full ANSI support
- **WebSocket** - Modern web-based connectivity with binary message support
- **HTTP/REST** - RESTful API for external integrations
- **TCP Raw** - Direct socket connections for custom protocols
### π **Security & Isolation**
- VM-based script sandboxing with resource limits
- Memory and CPU usage monitoring
- Security validation preventing dangerous code patterns
- Automatic rollback on validation failures
### β‘ **Performance & Reliability**
- Sub-50ms hot-reload target times
- Parallel compilation with dependency resolution
- State preservation across updates
- Comprehensive error handling and recovery
### π οΈ **Developer Experience**
- Powerful CLI tool for development and debugging
- Real-time script compilation and validation
- Performance profiling and analysis
- Project scaffolding and management
## Architecture Overview
```
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Multi-Protocol β β Plugin System β β Hot-Reload Core β
β Server βββββΊβ Discovery βββββΊβ File Watcher β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Connection Pool β β Lifecycle Managerβ β Compilation β
β Management β β Events & Deps β β Queue β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β Sandboxed β β Game World β β Validation β
β Virtual Machine βββββΊβ State Mgmt βββββΊβ Engine β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
```
## Quick Start
### Prerequisites
- Node.js 18.0.0 or higher
- TypeScript 5.0 or higher
- npm or yarn package manager
### Installation
```bash
# Clone the repository
git clone https://github.com/your-org/ursamu.git
cd ursamu
# Install dependencies
npm install
# Build the project
npm run build
# Start the server
npm start
# Or use the Ursamu CLI
npx ursamu-mud start
```
### Basic Usage
```typescript
import { MUDEngine } from 'ursamu-mud';
const engine = new MUDEngine({
protocols: ['telnet', 'websocket'],
hotReload: {
enabled: true,
watchPaths: ['./scripts', './plugins']
},
vm: {
memoryLimit: 64 * 1024 * 1024, // 64MB
timeoutMs: 5000
}
});
await engine.start();
console.log('Ursamu MUD engine started successfully!');
```
## Core Systems
### Multi-Protocol Server
The multi-protocol server provides seamless connectivity across different network protocols:
```typescript
// Configure multiple protocols
const protocolConfig = {
telnet: {
port: 4000,
encoding: 'utf8',
ansiSupport: true
},
websocket: {
port: 8080,
path: '/ws',
binaryMessages: true
},
http: {
port: 3000,
cors: true,
rateLimiting: true
}
};
```
**Key Features:**
- Protocol-agnostic message handling
- Connection pooling and lifecycle management
- Built-in rate limiting and security
- Real-time connection monitoring
### Plugin System
Discover and manage plugins automatically with full lifecycle control:
```typescript
// Plugin structure
export class ExamplePlugin implements Plugin {
name = 'example-plugin';
version = '1.0.0';
dependencies = ['core-engine'];
async onLoad(): Promise<void> {
console.log('Plugin loaded');
}
async onUnload(): Promise<void> {
console.log('Plugin unloaded');
}
}
```
**Features:**
- Automatic plugin discovery
- Dependency resolution and management
- Hot-loading and unloading
- Version compatibility checking
### Sandboxed Virtual Machine
Execute user scripts safely in an isolated environment:
```typescript
// VM configuration
const vmConfig = {
memoryLimit: 64 * 1024 * 1024, // 64MB
timeoutMs: 5000,
allowedModules: ['util', 'crypto'],
blockedPatterns: [/eval/, /Function/, /require/]
};
// Execute script safely
const result = await vm.executeScript(scriptCode, {
context: gameContext,
timeout: 1000
});
```
**Security Features:**
- Memory usage monitoring
- CPU time limits
- Module access control
- Dangerous pattern detection
### Hot-Reload System
Zero-downtime updates with state preservation:
```typescript
// Hot-reload configuration
const hotReloadConfig = {
enabled: true,
watchPaths: ['./scripts', './plugins', './modules'],
debounceMs: 250,
validateBeforeReload: true,
allowRollback: true,
backupOnReload: true
};
```
**Pipeline Stages:**
1. **File Watching** - Detect changes with debouncing
2. **Compilation** - Process TypeScript, JavaScript, and MUD scripts
3. **Validation** - Security and performance checks
4. **Deployment** - Atomic updates with state preservation
5. **Rollback** - Automatic recovery on failures
### Developer CLI
Comprehensive development tools for building and debugging:
```bash
# Script management
ursamu-mud script create my-script --template typescript
ursamu-mud script compile ./scripts/combat.ts
ursamu-mud script validate ./scripts/*.js
# Development server
ursamu-mud dev --hot-reload --debug
ursamu-mud debug --inspect-brk
# Performance analysis
ursamu-mud profile --script ./scripts/ai.js --duration 60s
ursamu-mud benchmark --load-test --connections 1000
# Project management
ursamu-mud init --template basic-mud
ursamu-mud plugin install combat-system
ursamu-mud deploy --environment production
```
## Getting Started
### 1. Create a New Project
```bash
# Initialize new Ursamu MUD project
ursamu-mud init my-mud-game --template typescript
# Navigate to project
cd my-mud-game
# Install dependencies
npm install
```
### 2. Configure the Engine
Edit `config/default.json`:
```json
{
"server": {
"protocols": {
"telnet": { "port": 4000, "enabled": true },
"websocket": { "port": 8080, "enabled": true },
"http": { "port": 3000, "enabled": true }
}
},
"hotReload": {
"enabled": true,
"watchPaths": ["./scripts", "./plugins"],
"debounceMs": 250,
"maxReloadTime": 50
},
"vm": {
"memoryLimit": 67108864,
"timeoutMs": 5000,
"enableProfiling": true
},
"plugins": {
"autoDiscovery": true,
"searchPaths": ["./plugins", "./node_modules/@mud/*"]
}
}
```
### 3. Create Your First Script
```typescript
// scripts/welcome.ts
export function onPlayerConnect(player: Player, context: GameContext): void {
player.send(`Welcome to ${context.world.name}!`);
player.send('Type "help" for available commands.');
}
export function helpCommand(player: Player, args: string[]): CommandResult {
const commands = [
'look - Examine your surroundings',
'inventory - Check your items',
'quit - Leave the game'
];
return {
success: true,
message: 'Available commands:\n' + commands.join('\n')
};
}
```
### 4. Start the Server
```bash
# Development mode with hot-reload
npm run dev
# Production mode
npm start
# With custom configuration
npm start -- --config ./config/production.json
```
## Development
### Building from Source
```bash
# Clone repository
git clone https://github.com/your-org/ursamu.git
cd ursamu
# Install dependencies
npm install
# Build TypeScript
npm run build
# Run tests
npm test
# Development with watch mode
npm run dev
```
### Running Tests
```bash
# Run all tests
npm test
# Run specific test suite
npm test -- --testPathPattern="hotreload"
# Run with coverage
npm run test:coverage
# Run integration tests
npm run test:integration
```
### Project Structure
```
ursamu/
βββ src/
β βββ core/ # Core engine systems
β βββ protocols/ # Multi-protocol server
β βββ plugins/ # Plugin discovery & lifecycle
β βββ vm/ # Sandboxed virtual machine
β βββ scripting/ # Hot-reload system
β βββ cli/ # Developer CLI tool (ursamu-cli)
β βββ index.ts # Main entry point
βββ scripts/ # Game scripts
βββ plugins/ # Available plugins
βββ config/ # Configuration files
βββ tests/ # Test suites
βββ docs/ # Documentation
```
## Configuration
### Environment Variables
```bash
# Server configuration
URSAMU_PORT=4000
URSAMU_HOST=0.0.0.0
# Hot-reload settings
HOT_RELOAD_ENABLED=true
HOT_RELOAD_DEBOUNCE=250
# VM security
VM_MEMORY_LIMIT=67108864
VM_TIMEOUT_MS=5000
# Development
NODE_ENV=development
DEBUG=ursamu:*
```
### Advanced Configuration
```typescript
// Advanced engine configuration
const engineConfig: MUDEngineConfig = {
protocols: {
telnet: {
port: 4000,
encoding: 'utf8',
options: {
localEcho: false,
lineMode: true
}
},
websocket: {
port: 8080,
path: '/ws',
options: {
compression: true,
maxPayload: 1024 * 1024 // 1MB
}
}
},
hotReload: {
enabled: true,
watchPaths: ['./scripts', './plugins'],
ignorePaths: ['node_modules', '.git'],
debounceMs: 250,
maxReloadTime: 50,
validateBeforeReload: true,
allowRollback: true,
backupOnReload: true
},
vm: {
memoryLimit: 64 * 1024 * 1024,
timeoutMs: 5000,
enableProfiling: true,
allowedModules: ['util', 'crypto'],
securityOptions: {
checkDangerous: true,
maxComplexity: 50,
maxMemoryUsage: 0.8
}
},
plugins: {
autoDiscovery: true,
searchPaths: ['./plugins'],
lifecycle: {
loadTimeout: 10000,
unloadTimeout: 5000
}
}
};
```
## API Documentation
### Core Engine API
```typescript
// Engine lifecycle
await engine.start();
await engine.stop();
await engine.restart();
// Plugin management
await engine.loadPlugin('combat-system');
await engine.unloadPlugin('combat-system');
const plugins = engine.getLoadedPlugins();
// Script execution
const result = await engine.executeScript(script, context);
// Hot-reload control
await engine.hotReload.start();
await engine.hotReload.reload(['script.js']);
const status = engine.hotReload.getStatus();
```
### Protocol Management
```typescript
// Protocol control
await engine.protocols.start('telnet');
await engine.protocols.stop('websocket');
// Connection management
const connections = engine.protocols.getActiveConnections();
await engine.protocols.broadcast('Hello everyone!');
// Custom protocol handlers
engine.protocols.registerHandler('telnet', customTelnetHandler);
```
### Virtual Machine API
```typescript
// Script execution
const result = await vm.executeScript(code, {
context: gameContext,
timeout: 5000,
memoryLimit: 1024 * 1024
});
// Resource monitoring
const stats = vm.getResourceUsage();
const profile = vm.getPerformanceProfile();
// Security validation
const validation = await vm.validateScript(code);
```
## Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
### Development Workflow
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-feature`
3. Make your changes and add tests
4. Run tests: `npm test`
5. Commit with conventional commits: `git commit -m "feat: add new feature"`
6. Push to your fork: `git push origin feature/new-feature`
7. Create a Pull Request
### Code Standards
- TypeScript with strict mode enabled
- ESLint configuration provided
- 100% test coverage for new features
- Comprehensive documentation for APIs
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Support
- π **Documentation**: [Full API docs](docs/)
- π **Bug Reports**: [GitHub Issues](issues/)
- π¬ **Discussions**: [GitHub Discussions](discussions/)
- π§ **Development**: [Contributing Guide](CONTRIBUTING.md)
**Ursamu - Built with β€οΈ for the MUD development community**