funnisdk
v1.0.0
Published
[](https://www.npmjs.com/package/funnisdk) [](https://opensource.org/licenses/ISC)
Readme
FunniGames SDK
A lightweight, type-safe TypeScript/JavaScript SDK for seamless integration with the FunniGames platform. Built with modern web standards, this SDK enables your game to communicate with the FunniGames host environment via secure postMessage API.
🎮 Features
- 🔒 Secure Communication - Built on postMessage API for safe cross-origin communication
- 📦 Lightweight - Minimal bundle size with zero dependencies
- 🎯 TypeScript First - Full TypeScript support with comprehensive type definitions
- 🚀 Easy Integration - Simple initialization and intuitive API
- 👤 User Profiles - Access and manage player profiles
- 🏆 Leaderboard Support - Built-in leaderboard functionality
- 🎲 Game Lifecycle - Manage game saves
📦 Installation
npm install funnisdk🚀 Quick Start
import FunniGamesSDK from 'funnisdk';
async function initializeGame() {
// Initialize SDK with required features
const initialized = await FunniGamesSDK.initialize({
leaderboard: true,
gameplay: true,
});
if (!initialized) {
console.error('Failed to initialize SDK');
return;
}
// Start game session
await FunniGamesSDK.gameplay.start();
// Get user profile
const profile = await FunniGamesSDK.profile.getProfile();
console.log('Player:', profile.data.full_name);
console.log('Coins:', profile.data.totalCoins);
// Add score to leaderboard
await FunniGamesSDK.leaderboard.addScore(1000);
// Save game progress
await FunniGamesSDK.profile.saveData('progress', JSON.stringify({
level: 5,
score: 1000,
completedAt: new Date().toISOString()
}));
}
initializeGame().catch(console.error);📚 Table of Contents
🎯 Initialization
initialize(config: InitConfig): Promise<boolean>
Initialize the SDK with the features your game needs. This must be called before using any other SDK features.
Parameters:
interface InitConfig {
leaderboard?: boolean; // Enable leaderboard functionality
gameplay?: boolean; // Enable gameplay state management
}Returns: Promise<boolean> - Returns true if initialization succeeded, false otherwise.
Example:
const success = await FunniGamesSDK.initialize({
leaderboard: true,
gameplay: true
});
if (success) {
console.log('SDK initialized successfully');
} else {
console.error('SDK initialization failed');
}Note: The Profile component is always initialized by default, regardless of the config.
📖 API Reference
Profile API
Manage user profiles, coins, and save/load game data.
getProfile(): Promise<ResponseModel & { data: UserProfile }>
Retrieve the current user's profile information.
Response:
{
status: boolean;
message: string | null;
version: number;
data: {
account_id: string;
full_name: string;
totalPoints: number;
totalCoins: number;
timeWallet: {
freeTimeRemaining: number;
todayTimeRemaining: number;
totalTimeRemaining: number;
eligiblePlay: boolean;
todayUsedTime: number;
}
;
moneyWalletBalance: number;
images: {
proAvatar: string | null;
avatar: string;
}
;
pro: {
startedDate: string;
expirationDate: string;
}
;
isGuest: boolean;
isActive: boolean;
}
}Example:
const profile = await FunniGamesSDK.profile.getProfile();
console.log(`Welcome ${profile.data.full_name}!`);
console.log(`You have ${profile.data.totalCoins} coins`);addPoint(amount: number): Promise<ResponseModel & { data: AddPointInterface }>
Add coins to the user's account.
Parameters:
amount(number) - Number of coins to add (must be positive)
Example:
await FunniGamesSDK.profile.addPoint(50);
console.log('Added 50 coins to user account');saveData(key: string, data: string): Promise<ResponseModel & { data: SaveData }>
Save custom game data associated with a key.
Parameters:
key(string) - Unique identifier for the datadata(string) - Data to save (must be a string, use JSON.stringify for objects)
Example:
const gameData = {
level: 5,
health: 100,
inventory: ['sword', 'shield']
};
await FunniGamesSDK.profile.saveData(
'player_progress',
JSON.stringify(gameData)
);getData(key: string): Promise<ResponseModel & { data: GetData }>
Retrieve previously saved game data.
Parameters:
key(string) - The key used when saving the data
Example:
const response = await FunniGamesSDK.profile.getData('player_progress');
if (response.status) {
const gameData = JSON.parse(response.data);
console.log('Current level:', gameData.level);
}Leaderboard API
Manage game scores and retrieve leaderboard rankings.
addScore(score: number): Promise<ResponseModel>
Submit a score to the leaderboard.
Parameters:
score(number) - The score to submit
Example:
await FunniGamesSDK.leaderboard.addScore(1500);
console.log('Score submitted successfully');getLeaderboard(): Promise<ResponseModel & { data: LeaderboardInterface }>
Retrieve the current leaderboard standings.
Response:
{
status: boolean;
message: string | null;
version: number;
data: {
leaderboard: [
{
userId: string;
userName: string;
totalPoints: number;
rank: number;
images? : {
avatar? : string;
proAvatar? : string;
};
uniqueId: string;
isPro: boolean;
}
];
userRecord: {
_id: string;
name ? : string;
registrationId: string;
images ? : {
avatar? : string;
proAvatar? : string;
};
uniqueId: string;
pro: {
startedDate ? : Date | null;
expirationDate ? : Date | null;
}
}
}
}Example:
const leaderboard = await FunniGamesSDK.leaderboard.getLeaderboard();
console.log('Top player:', leaderboard.data.leaderboard[0]);
console.log('Your rank:', leaderboard.data.userRecord);📝 Type Definitions
ResponseModel
interface ResponseModel {
status: boolean;
message: string | null;
version: number;
data?: any;
}InitConfig
interface InitConfig {
leaderboard?: boolean;
gameplay?: boolean;
}UserProfile
interface UserProfile {
account_id: string;
full_name: string;
totalPoints: number;
totalCoins: number;
timeWallet: TimeWallet;
moneyWalletBalance: number;
images: Images;
pro: Pro;
isGuest: boolean;
isActive: boolean;
}For complete type definitions, see the TypeScript declarations included in the package.
⚠️ Error Handling
All SDK methods return promises and may throw errors. Always use try-catch blocks or .catch() handlers.
Common error scenarios:
- SDK not initialized (call
initialize()first) - Parent window not available (game not embedded in FunniGames platform)
- Network/communication failures
- Invalid parameters
Example:
try {
const profile = await FunniGamesSDK.profile.getProfile();
console.log('Profile loaded:', profile.data);
} catch (error) {
console.error('Failed to load profile:', error.message);
// Handle error appropriately (show message to user, retry, etc.)
}🌍 Environment Requirements
- Platform: Must be embedded in an iframe within the FunniGames platform
- Parent Window: Parent window must implement required postMessage handlers
- Browser: Modern browser with ES2018+ support
- Node: >=14.0.0 (for development)
🛠️ Build & Development
Development Setup
# Clone the repository
git clone <repository-url>
# Navigate to the SDK directory
cd jsSDK
# Install dependencies
npm install
# Start development build with watch mode
npm run devBuilding
# Clean build artifacts
npm run clean
# Build the SDK
npm run build
# Prepare for publishing
npm run prepare-publishBuild Output
The SDK is built in multiple formats:
- ESM (
dist/index.js) - ES Module format - CommonJS (
dist/index.cjs) - CommonJS format - IIFE (
dist/game-platform.min.js) - Browser-ready bundle - Types (
dist/index.d.ts) - TypeScript type definitions
💡 Examples
Complete Game Integration
import FunniGamesSDK from 'funnisdk';
import {FlowType, ProgressionStatus} from 'funnisdk';
class Game {
async init() {
// Initialize SDK
const success = await FunniGamesSDK.initialize({
leaderboard: true,
gameplay: true
});
if (!success) {
throw new Error('Failed to initialize FunniGames SDK');
}
// Get player info
const profile = await FunniGamesSDK.profile.getProfile();
this.displayPlayerInfo(profile.data);
// Load saved progress
try {
const savedData = await FunniGamesSDK.profile.getData('game_progress');
this.loadProgress(JSON.parse(savedData.data));
} catch (error) {
// No saved data, start fresh
this.startNewGame();
}
}
async startLevel(level: number) {
// Signal game start
await FunniGamesSDK.gameplay.start();
// Track level start
await FunniGamesSDK.analytics.progressionEvent(
ProgressionStatus.Start,
`Level${level}`,
'',
''
);
}
async completeLevel(level: number, score: number, coinsEarned: number) {
// Submit score
await FunniGamesSDK.leaderboard.addScore(score);
// Add coins
await FunniGamesSDK.profile.addPoint(coinsEarned);
// Track resource gain
await FunniGamesSDK.analytics.resourceEvent(
FlowType.Source,
'currency',
'coins',
coinsEarned,
'coins'
);
// Track progression
await FunniGamesSDK.analytics.progressionEvent(
ProgressionStatus.Complete,
`Level${level}`,
'',
'',
score
);
// Save progress
await this.saveProgress();
}
async purchaseItem(itemId: string, cost: number) {
try {
const transaction = await FunniGamesSDK.wallet.spendFunniCoin(itemId, cost);
// Deliver item to player
this.giveItemToPlayer(itemId);
// Consume transaction
await FunniGamesSDK.wallet.consume(transaction.Transaction.TransactionId);
// Track spending
await FunniGamesSDK.analytics.resourceEvent(
FlowType.Sink,
'item',
itemId,
cost,
'coins'
);
return true;
} catch (error) {
console.error('Purchase failed:', error);
return false;
}
}
async saveProgress() {
const progress = {
level: this.currentLevel,
score: this.totalScore,
inventory: this.inventory,
savedAt: new Date().toISOString()
};
await FunniGamesSDK.profile.saveData(
'game_progress',
JSON.stringify(progress)
);
}
async endGame() {
await this.saveProgress();
await FunniGamesSDK.gameplay.stop();
}
}📄 License
Proprietary License - see the LICENSE file for details.
📞 Support
- Email [email protected]
🔄 Changelog
v1.0.0 (Current)
- Initial release
- Profile management
- Leaderboard integration
- Game save management
Made with ❤️ by the FunniGames Team
