Package Exports
- playe-developer-sdk
- playe-developer-sdk/package.json
Readme
Playe Developer SDK
A comprehensive browser-based SDK for integrating games with the Playe platform. This SDK provides easy-to-use APIs for game session management, campaign integration, leaderboards, and anti-cheat validation.
Features
- 🎮 Game Session Management - Initialize, start, update, and complete game sessions
- 🛡️ Integrity Verification - Built-in session integrity with cryptographic hashing and validation
- 🏆 Campaign Integration - Access campaign information, leaderboards, and player attempts
- 🔄 Anti-Cheat Protection - Advanced validation, heartbeat mechanisms, and session monitoring
- 📱 Device Detection - Automatic device information and fingerprinting
- 🔧 Developer Tools - Test game sessions and comprehensive debugging utilities
- 📊 Real-time Updates - Progress tracking and live leaderboards
- ⚡ Browser Optimized - Lightweight and fast for web games with automatic retry logic
Installation
NPM (Recommended)
npm install playe-developer-sdk
# or
yarn add playe-developer-sdk
# or
pnpm add playe-developer-sdkCDN (No build tools required)
<!-- For production -->
<script src="https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>
<!-- Alternative CDN -->
<script src="https://cdn.jsdelivr.net/npm/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>Workspace (Internal development)
{
"dependencies": {
"@workspace/playe-developer-sdk": "workspace:*"
}
}Quick Start
NPM Usage
import { createPlayeSDK } from "playe-developer-sdk";
// Initialize the SDK
const sdk = createPlayeSDK({
apiBaseUrl: "https://api.playe.com",
apiKey: "your-api-key",
enableDebugMode: true, // Enable for development
});
// Initialize a game session (gets sessionId from URL query parameter)
const session = await sdk.initializeGameSession();
console.log("Game session initialized:", {
sessionId: session.sessionId,
campaignId: session.campaign.id,
playerId: session.player.id,
});
// Start the game
await sdk.startGameSession({
difficulty: "normal",
mode: "classic",
});
// Update progress during gameplay (includes automatic integrity verification)
await sdk.updateGameProgress({
currentScore: 1500,
elapsedTime: 120, // seconds
gameState: {
level: 3,
lives: 2,
powerUps: ["speed", "shield"],
},
achievements: [
{
id: "level-3",
name: "Level 3 Complete",
unlockedAt: new Date().toISOString(),
},
],
});
// Complete the game (includes integrity verification)
const result = await sdk.completeGame({
finalScore: 2500,
validationChecksum: "client-checksum",
gameMetrics: {
totalPlayTime: 300,
actionsPerformed: 150,
powerUpsUsed: 5,
levelsCompleted: 5,
},
finalGameState: {
level: 5,
finalLives: 1,
},
});
console.log("Game completed!", {
isWinner: result.isWinner,
finalRank: result.finalRank,
prizeAmount: result.prizeAmount,
});CDN Usage
<script src="https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js"></script>
<script>
// SDK is available as global PlayeSDK
const sdk = PlayeSDK.createPlayeSDK({
apiBaseUrl: 'https://api.playe.com',
apiKey: 'your-api-key',
enableDebugMode: true,
});
// All utilities are available
const fingerprint = PlayeSDK.DeviceUtils.generateFingerprint();
// Same API as NPM version
const session = await sdk.initializeGameSession(); // Gets sessionId from URL
console.log('Session initialized:', session.sessionId);
</script>API Reference
SDK Configuration
interface SDKConfig {
apiBaseUrl: string; // Required: API base URL
apiKey?: string; // Optional: API key for authentication
enableDebugMode?: boolean; // Optional: Enable debug logging
retryAttempts?: number; // Optional: Number of retry attempts (default: 3)
timeoutMs?: number; // Optional: Request timeout in ms (default: 30000)
enableOfflineMode?: boolean; // Optional: Enable offline mode (default: false)
}Core Methods
Game Session Management
// Initialize game session (gets sessionId from URL query parameter)
const session = await sdk.initializeGameSession(): Promise<GameSessionResponse>;
// Start the game session
await sdk.startGameSession(config?: Record<string, any>): Promise<GameSessionResponse>;
// Update game progress with integrity verification
await sdk.updateGameProgress({
currentScore: number;
gameState?: Record<string, any>; // Automatically hashed for integrity
elapsedTime: number;
achievements?: Achievement[];
clientTimestamp?: string;
}): Promise<ProgressUpdateResponse>;
// Complete the game with integrity verification
await sdk.completeGame({
finalScore: number;
validationChecksum: string;
gameMetrics?: GameMetrics;
finalGameState?: Record<string, any>; // Automatically hashed for integrity
}): Promise<GameCompletionResponse>;
// Abandon the game
await sdk.abandonGame(reason?: string, lastKnownScore?: number): Promise<AbandonGameResponse>;Campaign Information
// Get campaign status
await sdk.getCampaignStatus(campaignId: string, playerId?: string): Promise<CampaignStatusResponse>;
// Get leaderboard
await sdk.getLeaderboard(campaignId: string, limit?: number, playerId?: string): Promise<LeaderboardResponse>;
// Get player attempts
await sdk.getPlayerAttempts(campaignId: string, playerId: string): Promise<PlayerAttemptsResponse>;Validation & Anti-Cheat
// Validate game session with integrity verification
await sdk.validateGameSession({
clientChecksum: string;
stateSnapshot?: Record<string, unknown>; // Automatically hashed
timingData?: unknown;
behaviorMetrics?: unknown;
}): Promise<ValidationResponse>;
// Send heartbeat (usually handled automatically)
await sdk.sendHeartbeat(currentScore?: number): Promise<HeartbeatResponse>;Developer Tools
// Create test game session for development
await sdk.createTestGameSession(testConfig?: Record<string, any>): Promise<TestGameResponse>;Utility Methods
// Test SDK functionality
sdk.test('Custom test message'): void;
// Check if running in demo mode
const isDemoMode = sdk.isDemo(): boolean;
// Game lifecycle events
sdk.gameLoadingStart(): void; // Emit loading start event
sdk.gameLoadingFinished(): void; // Emit loading finished event
sdk.gamePlayStop(): void; // Stop heartbeat and emit stop event
// Clean up resources
sdk.destroy(): void; // Clean up session artifacts and stop heartbeatIntegrity Verification Utilities
import { canonicalStringify, sha256Hex, buildIntegrityHeaders, computeGameStateHash } from "playe-developer-sdk";
// Canonical JSON stringification (deterministic)
const canonical = canonicalStringify({ b: 1, a: 2 }); // '{"a":2,"b":1}'
// SHA-256 hashing
const hash = await sha256Hex("data to hash");
// Build integrity headers (used internally)
const headers = buildIntegrityHeaders(sessionToken);
// Compute game state hash with session salt
const gameStateHash = await computeGameStateHash(gameState, sessionSalt);Device Utilities
import { DeviceUtils } from "@workspace/playe-developer-sdk";
// Get device information
const deviceInfo = DeviceUtils.getDeviceInfo();
// Get geolocation
const location = await DeviceUtils.getGeolocationData();
// Generate fingerprint
const fingerprint = DeviceUtils.generateFingerprint();
// Check browser support
const isSupported = DeviceUtils.isBrowser();
const features = DeviceUtils.getFeatureSupport();Error Handling
import {
PlayeSDKError,
ValidationError,
NetworkError,
AuthenticationError,
GameSessionError,
} from "@workspace/playe-developer-sdk";
try {
await sdk.initializeGameSession(params);
} catch (error) {
if (error instanceof ValidationError) {
console.error("Validation failed:", error.message);
} else if (error instanceof NetworkError) {
console.error("Network error:", error.message);
} else if (error instanceof AuthenticationError) {
console.error("Authentication failed:", error.message);
} else if (error instanceof PlayeSDKError) {
console.error("SDK error:", error.toJSON());
}
}Campaign Styles
The SDK supports different campaign styles:
- SingleWinner: One winner takes all
- FixedPool: Fixed number of winners
- Leaderboard: Winners based on ranking
- RewardForAll: Everyone gets rewards
Events
The SDK emits custom browser events for tracking:
// Listen for SDK events
window.addEventListener("playe:game-loading-start", () => {
console.log("Game loading started");
});
window.addEventListener("playe:game-loading-finished", () => {
console.log("Game loading finished");
});
window.addEventListener("playe:game-play-stop", () => {
console.log("Game play stopped");
});Integrity Verification
The SDK includes built-in integrity verification to prevent cheating and ensure fair play:
Automatic Features
- Session Integrity: Each game session includes a unique session token and salt
- Game State Hashing: Game states are automatically hashed using SHA-256 with session salt
- Integrity Headers: All authenticated requests include cryptographic integrity headers
- Retry Logic: Failed requests due to integrity issues are automatically retried with fresh headers
How It Works
- Session Initialization: SDK receives session token and salt from server
- State Hashing: Game states are canonicalized and hashed with session salt
- Request Signing: Integrity headers are built with timestamp, nonce, and session token
- Server Validation: Server verifies hashes and headers to detect tampering
Manual Verification (Advanced)
// Manually validate game session
const validation = await sdk.validateGameSession({
clientChecksum: "calculated-checksum",
stateSnapshot: currentGameState,
timingData: { avgResponseTime: 250 },
behaviorMetrics: { clicksPerSecond: 5.2 },
});
if (!validation.isValid) {
console.log("Validation issues:", validation.validationIssues);
}Development
Testing
// Create a test game session for development
const testSession = await sdk.createTestGameSession({
testConfig: {
mockCampaign: true,
mockPlayers: 10,
testScenario: "leaderboard",
},
});
console.log("Test session created:", testSession.testSessionId);Debug Mode
Enable debug mode to see detailed logging:
const sdk = createPlayeSDK({
apiBaseUrl: "https://api.playe.com",
enableDebugMode: true, // This will log all API calls, integrity operations, and responses
});URL Requirements
For initializeGameSession() to work, the page URL must include a sessionId query parameter:
https://yourgame.com/play?sessionId=abc123-def456-ghi789The SDK will automatically extract this sessionId and initialize the session.
Browser Compatibility
- Chrome 60+
- Firefox 55+
- Safari 12+
- Edge 79+
Distribution
The SDK is available in multiple formats:
- NPM Package:
npm install playe-developer-sdk - CDN (UMD):
https://unpkg.com/playe-developer-sdk@latest/dist/playe-sdk.umd.min.js - Workspace:
@workspace/playe-developer-sdk(internal development)
Bundle Sizes
- ESM: 27.3KB (8KB gzipped)
- CommonJS: 27.6KB (8KB gzipped)
- UMD: 30.8KB (9KB gzipped)
- UMD Minified: 13.7KB (5KB gzipped)
For detailed distribution information, see DISTRIBUTION.md.
TypeScript Support
This SDK is written in TypeScript and includes full type definitions. No additional @types packages are needed.
License
MIT License - see LICENSE file for details.
Support
For support, please contact the Playe development team or create an issue in the repository.