Core Concepts
Understanding these core concepts will help you effectively use the mezon-sdk.
MezonClient
The MezonClient [src] is the primary interface for interacting with the Mezon platform. It extends Node.js's EventEmitter to provide real-time event handling capabilities. The client encapsulates all the necessary functionalities, including:
- Connection management via
SocketManagerfor WebSocket communications - Authentication handling through
SessionManagerfor session management and token authentication - API calls through an internal
MezonApiinstance for REST API operations - Real-time event handling via
EventManagerandSocketManagerfor live updates - Data structure access including channels, messages, users, and clans through cached managers
- Local data caching using
CacheManagerfor performance optimization - Message persistence via
MessageDatabaseusing SQLite for offline capabilities - Rate limiting through
AsyncThrottleQueuefor managing outgoing requests - Direct messaging support with dedicated DM channel management
Key Properties and Methods
login(): Authenticates the client and establishes connectionscreateDMchannel(userId): Creates direct message channels with users- Event listeners: Comprehensive set of
on*methods for real-time events like messages, channel updates, user actions, and more - Friend management: Methods for adding, accepting, and listing friends
closeSocket(): Properly closes WebSocket connections and resets managers
Authentication (Sessions)
-
SessionManager[src]: Handles the complete authentication lifecycle:- Token-based authentication using API keys to obtain session tokens (JWT)
- Session management including storage and retrieval of active sessions
- API integration coordinates with
MezonApifor authentication requests - Automatic session handling for all authorized API calls and WebSocket communication
-
Session[src]: Represents an authenticated user session containing:- User credentials including tokens and user identification (
user_id) - Server endpoints dynamic API URL resolution from authentication response
- Token management with expiration and refresh logic
- Connection parameters used for establishing WebSocket connections
- User credentials including tokens and user identification (
Authentication Flow
The MezonClient.login() process involves:
- Initial authentication with temporary API client using login credentials
- Dynamic endpoint resolution parsing
api_urlfrom session response for optimal routing - Manager initialization setting up all SDK components with authenticated session
- WebSocket connection establishing real-time communication channel
- DM channel initialization loading existing direct message channels
- Ready state emission signaling successful authentication and setup completion
The SDK automatically handles server-side routing and load balancing through dynamic endpoint resolution, ensuring optimal connection paths.
Real-time Communication (Sockets)
-
SocketManager[src]: Establishes and maintains the WebSocket connection to the Mezon server for real-time events and messaging. It handles connection, disconnection, reconnection logic, and message serialization/deserialization using Protocol Buffers viaWebSocketAdapterPb. The manager integrates with the message queue system and database for reliable message handling. -
DefaultSocket[src]: A lower-level socket implementation used by managers. -
Real-time Events: The SDK provides extensive real-time event support through the
MezonClient's event listener methods:- Message Events:
onChannelMessage(),onMessageReaction(),onMessageButtonClicked() - Channel Events:
onChannelCreated(),onChannelUpdated(),onChannelDeleted() - User Events:
onUserChannelAdded(),onUserChannelRemoved(),onAddClanUser(),onUserClanRemoved() - Social Events:
onGiveCoffee(),onTokenSend(),onNotification() - Voice Events:
onVoiceStartedEvent(),onVoiceEndedEvent(),onVoiceJoinedEvent(),onVoiceLeavedEvent() - Streaming Events:
onStreamingJoinedEvent(),onStreamingLeavedEvent() - Role Events:
onRoleEvent(),onRoleAssign() - Interactive Events:
onDropdownBoxSelected(),onQuickMenuEvent(),onWebrtcSignalingFwd()
These events are defined in
src/constants/enum.tsand allow for comprehensive real-time application development. - Message Events:
Channels
-
ChannelManager[src]: Manages channel-related operations with specialized support for Direct Message (DM) channels. Key functionalities include:- Creating and fetching DM channels
- Initializing all DM channels during client setup via
initAllDmChannels() - Managing channel state and metadata
- Coordinating with
SocketManagerandSessionManagerfor real-time updates
-
TextChannel[src]: Represents a text-based communication channel (e.g., clan channels, DM channels, or threads). It provides methods for:- Sending messages and managing message history
- Interacting with channel properties and metadata
- Integration with message persistence through
MessageDatabase - Real-time message handling via the message queue system
Channels support various types including text, voice, and threads as defined in
ChannelTypeenum fromsrc/constants/enum.ts. TheMezonClientmaintains channels through aCacheManagerfor efficient access and automatic fetching when needed.
Messages
-
Message[src]: Represents a single message within a channel with comprehensive metadata including:- Message content, sender information, and timestamps
- Attachments, reactions, mentions, and message references
- Integration with the parent
TextChanneland rate-limited messaging viaAsyncThrottleQueue - Methods for message manipulation (reply, update, delete, react)
-
Message Initialization: Messages are created through
MessageInitDatainterface containing all necessary properties likeid,clan_id,channel_id,sender_id,content,reactions,mentions,attachments,references, andcreate_time_seconds. -
Message Formatting: Utilities like
format_message_input.tsandgenerate_reply_message.tsensure consistent message structures across different message types including special handling for token transfers. -
Message Persistence:
MessageDatabase.tsuses SQLite to store messages locally through thesaveMessage()method, enabling features like:- Offline message viewing
- Faster message history loading
- Local message caching for improved performance
- Message synchronization between sessions
-
Real-time Message Handling: The
MezonClientautomatically handles incoming messages through_initChannelMessageCache()which createsMessageinstances and updates both in-memory caches and persistent storage.
Events
-
EventManager[src]: A system for emitting and listening to custom client-side and server-pushed events. This allows different parts of your application (or your bot) to react to occurrences within the Mezon platform or the SDK itself. -
Socket Events (
src/message-socket-events/): Specific handlers for socket events likeuser_channel_addedoruser_channel_updated.
Clans & Users
-
Clan[src]: Represents a clan (server/community) on the Mezon platform containing:- Multiple channels accessible through the clan's channel collection
- Member users with role-based permissions
- Clan-specific metadata (ID, name, welcome channel)
- Integration with
MezonApi,SocketManager, andMessageDatabase - Dynamic channel loading via
loadChannels()method - A special clan with ID "0" represents the DM space for direct messaging
-
User[src]: Represents a user on the Mezon platform with comprehensive profile information:- Basic Identity: ID, username, display name, and avatar
- Clan-specific Data: clan nickname (
clan_nick) and clan avatar (clan_avatar) for different clan contexts - DM Integration: Associated DM channel ID for direct messaging capabilities
- User Actions: Methods for user-specific operations like sending direct messages
Users are managed through
UserInitDatainterface and are automatically cached by clans. TheMezonClientmaintains user data across both clan contexts and the global DM space (clan "0"), allowing for consistent user interactions regardless of context. -
User Management: The client automatically handles user caching through
_initUserClanCache()which:- Creates user instances for both clan and DM contexts
- Maintains user data consistency across different clan memberships
- Handles dynamic user loading from DM channel data
- Updates user information from real-time message events
Caching and Data Management
-
CacheManager[src]: Provides a sophisticated caching layer for frequently accessed data with automatic fetching capabilities:- Generic caching for any data type (clans, channels, users)
- Automatic fetching via constructor-provided fetch functions (e.g.,
_fetchClanFromAPI,_fetchChannelFromAPI) - Memory optimization reducing repeated API calls and improving performance
- Integrated with MezonClient through
this.clansandthis.channelscache managers - Lazy loading - data is fetched only when accessed via
fetch()orget()methods
-
AsyncThrottleQueue[src]: Critical component for managing outgoing requests and maintaining rate limits:- Rate limiting prevents server-imposed limits and ensures smooth operation
- Request queuing manages high-volume messaging and API calls
- Used extensively by MezonClient for message sending, API calls, and socket operations
- Background processing handles queued tasks without blocking main application flow
-
Collection[src]: An enhancedMaputility providing advanced data structure management:- Extended Map functionality with convenient methods for filtering, mapping, and finding items
- Used throughout SDK for managing collections of users, channels, messages, and other entities
- Performance optimized for frequent read/write operations on large datasets
- Type-safe operations maintaining TypeScript compatibility
-
MessageDatabase[src]: SQLite-based persistent storage system:- Local message storage for offline access and faster loading
- Automatic synchronization with real-time events via
saveMessage()method - Integrated caching works alongside in-memory caches for optimal performance
- Cross-session persistence maintains message history between application restarts
Social Features
The Mezon SDK provides comprehensive social interaction capabilities:
Friend System
getListFriends(): Retrieve friend lists with pagination support (limit,state,cursorparameters)addFriend(username): Send friend requests to users by usernameacceptFriend(userId, username): Accept incoming friend requests- Automatic friend request handling: The client automatically processes friend requests through notification events
Token Transfer System
sendToken(sendTokenData): Send virtual currency/tokens between usersonTokenSend(): Listen for token transfer events with automatic DM notifications- Transaction notifications: Automatic direct message generation for successful transfers
- Formatted transfer messages: Includes amount formatting and transaction notes
- Coffee system: Social interaction feature via
onGiveCoffee()events
Interactive Elements
- Message buttons: Support for interactive buttons in messages via
onMessageButtonClicked() - Dropdown selections: Handle user selections from dropdown menus via
onDropdownBoxSelected() - Quick menus: Support for quick action menus via
onQuickMenuEvent()
Voice and Video Features
- Voice channels: Complete voice session management with start, end, join, and leave events
- WebRTC signaling: Direct peer-to-peer communication support via
onWebrtcSignalingFwd() - Streaming support: Live streaming capabilities with join/leave event handling