npm package: @gamerstake/game-platform-sdk
Description: SDK for communicating with GameStake platform
Author: GameStake
Latest version: 1.0.7

# GamerStake Platform SDK

SDK for communicating with the GamerStake platform from your game servers.

## Installation

```bash
npm install @gamerstake/game-platform-sdk
# or
yarn add @gamerstake/game-platform-sdk
# or
pnpm install @gamerstake/game-platform-sdk
```

## Quick Start

```typescript
import { GameSDK } from '@gamerstake/game-platform-sdk';

const sdk = new GameSDK({
  apiKey: process.env.GAME_API_KEY!,
  environment: 'production', // 'development', 'staging', or 'production'
  debug: false,
});

// Start match (this initializes match tracking for this SDK instance)
const matchInfo = await sdk.reportMatchStart(matchId);

// Validate player token (with automatic input validation)
const player = await sdk.validatePlayerToken(token);

// Report player join (with automatic validation)
await sdk.reportPlayerJoin(matchId, player.id);

// Report match result (with automatic validation)
await sdk.reportMatchResult(matchId, {
  players: [
    { id: 'player1', score: 100, isWinner: true },
    { id: 'player2', score: 50, isWinner: false }
  ]
});
```

## API Reference

### Main Methods

- `reportMatchStart(matchId)` - Reports match has started (returns match info, initializes single match tracking)
- `validatePlayerToken(token)` - Validates JWT token and returns player identity
- `reportPlayerJoin(matchId, playerId)` - Reports player joined the match
- `reportMatchResult(matchId, result)` - Reports final match result
- `reportMatchError(matchId, reason)` - Reports match error
- `clearCurrentMatch()` - Clears the current match (useful for testing)
- `isInitialized()` - Check if the SDK is properly initialized

### Convenience Accessors

The SDK provides convenient access to services through getters:

```typescript
// Access auth service
const player = await sdk.auth.validatePlayer(token);

// Access match service with additional methods
const matchInfo = await sdk.matches.getInfo(matchId);
const matchStatus = await sdk.matches.start(matchId);
const result = await sdk.matches.finish(matchId, result);
const cancelled = await sdk.matches.cancel(matchId);
```

### Error Handling

The SDK uses a structured error hierarchy:

- `ConfigurationError` - Configuration and initialization errors
- `AuthenticationError` - Token validation errors
- `MatchSDKError` - Match operation errors
- `NetworkError` - HTTP/Network communication errors
- `ValidationError` - Input validation errors

### Input Validation

All public methods automatically validate their inputs:

- **Match IDs**: Must be non-empty strings, max 100 chars, alphanumeric + hyphens/underscores
- **Player IDs**: Must be non-empty strings, max 100 chars
- **JWT Tokens**: Must be valid JWT format (3 base64 parts separated by dots)
- **Match Results**: Must have valid `players` array with player objects containing `id`, `score`, and `isWinner` properties
- **Error Reasons**: Must be non-empty strings, max 500 chars

You can also use the `Validator` class directly for custom validation needs.

### Configuration

The SDK supports three environments:

- `development` - Local development (http://localhost:3000)
- `staging` - Staging environment (https://dev-api.gamerstake.io)
- `production` - Production environment (https://api.gamerstake.com)

**Important**: Debug mode is automatically disabled in production environment for security.

### Types

- `PlayerIdentity` - Player information from validated token (`id`, `username`, `email?`)
- `MatchInfo` - Match rules and expected players
- `MatchResult` - Match outcome with players array containing scores and winners
- `MatchError` - Error information for failed matches
- `CurrentMatchInfo` - Current match state tracking (from MatchManager)
- `EnvironmentConfig` - Environment-specific configuration
- `GameSDKConfig` - SDK initialization configuration

## Security Notes

- SDK enforces JWT verification with platform's public key
- You must not skip steps - platform rejects out-of-order calls
- Funds are handled only by the platform - game servers cannot touch balances
- Debug mode is automatically disabled in production environment
- API keys are validated during initialization (minimum 10 characters)

## Match State Management

The SDK includes a built-in `MatchManager` that tracks the current match state:

- **NOT_STARTED** - Initial state
- **IN_PROGRESS** - Match is active and players can join
- **FINISHED** - Match completed successfully
- **ERROR** - Match encountered an error

The SDK enforces proper match flow - you cannot start a new match while one is active, and you must clear the current match before starting a new one.

## Version History

- v1.0.4 - Current version with updated documentation
- v1.0.3 - Version with enhanced match management and validation
- v1.0.0 - Initial release with core functionality