import { ConvexClient } from 'convex/browser'; import { GenericId } from 'convex/values'; export { GenericId as Id } from 'convex/values'; import { FunctionReturnType, FunctionArgs } from 'convex/server'; import { LOBBY_VISIBILITY, api, UGC_TYPE, UGC_VISIBILITY, LEADERBOARD_SORT_ORDER, LEADERBOARD_DISPLAY_TYPE, GAME_ENGINE, SDKUser, IFrameEventPayloadMap, IFRAME_MESSAGE_TYPE, SDKConfig, GameLaunchParams } from '@wvdsh/api'; export { GameLaunchParams } from '@wvdsh/api'; /** * Base class for SDK managers. Provides the shared `sdk` reference and a * default no-op `destroy()` so the SDK can safely iterate every manager * during teardown without each one having to define an empty stub. * * Override `destroy()` in any manager that owns ongoing state — Convex * subscriptions, intervals, peer connections, monkey-patched globals, etc. * — to make sure that state is released when the SDK is torn down. */ declare abstract class WavedashManager { protected sdk: WavedashSDK; constructor(sdk: WavedashSDK); destroy(): void; } /** * Mutes & unmutes the game in response to MUTE_CHANGED iframe messages, with no * game-side code required. * * Globals like `AudioContext` are per-frame, so we shim the SDK's own window * (where the game usually runs) plus any same-origin iframes the game adds. * * Each frame's shimming lives in {@link AudioFrameShim}; this class owns the * mute state and fans it out to every attached frame. */ declare class AudioManager extends WavedashManager { private _isMuted; private frames; private iframeBindings; private iframeLoadHandlers; private boundIframes; constructor(sdk: WavedashSDK); isMuted(): boolean; /** * Ask the host to mute (true) or unmute (false). Resolves to `true` if the * host applied the change, `false` otherwise — notably, the host rejects an * unmute when the user muted the game from the Wavedash UI, so games can't * override an explicit user mute. The resulting state arrives via the usual * MUTE_CHANGED broadcast, so `isMuted()` updates independently of this result. */ requestMute(muted: boolean): Promise; /** * Toggle mute. Like `requestMute`, the host may reject the unmute half of a * toggle if the user muted from the Wavedash UI. Resolves to `true` if the * host applied the change. */ toggleMute(): Promise; private handleMute; /** Shim a window we can reach. Same-origin only (cross-origin access throws). */ private attachWindow; /** * Start tracking an iframe: attach now (already-loaded frames) and on every * `load` (about:blank → game, and later src swaps). Idempotent. */ bindIframe(iframe: HTMLIFrameElement): void; /** Stop tracking an iframe and tear down its frame (iframe removed from DOM). */ unbindIframe(iframe: HTMLIFrameElement): void; /** * Install (or re-install) a shim for an iframe's current document. No-ops * while not yet navigated or already shimmed; replaces the previous shim when * the iframe navigates to a fresh document, and drops it when it goes * cross-origin (we can no longer reach it). */ private attachIframe; /** Remove and uninstall the shim bound to an iframe's (previous) document. */ private teardownFrame; destroy(): void; } /** * ExternalLinkManager * * The game iframe's sandbox has no `allow-popups`, so `window.open` inside the * iframe is dead. Rather than navigate the player away mid-session, Wavedash * copies the link to their clipboard and the host shows an in-game toast. * * The compat shims below are convenience, not security: game code shares this * realm and can unpatch them, but bypassing them just gets a popup the sandbox * blocks — and a game can already reach the clipboard directly, since the * iframe is granted `clipboard-write`. */ declare class ExternalLinkManager extends WavedashManager { private nativeOpen; private patchedOpen; private clickHandler; constructor(sdk: WavedashSDK); /** * Copy `url` to the player's clipboard and have the host show an in-game * toast. Resolves `false` if the clipboard write failed. Must run inside a * user gesture handler. * * The write happens here rather than in the host because * `navigator.clipboard` only honours user activation raised in the calling * frame — activation propagated up from this iframe doesn't count out there. * The iframe is granted `clipboard-write` for exactly this. */ copyLink(url: string): Promise; private installCompatShims; destroy(): void; private resolveHttpUrl; } /** * SDK-to-Engine Events * * Defines all events that the SDK sends to the game engine. * These are maintained manually in the SDK (not autogenerated from backend). * * The game engine listens for these events to react to SDK updates. */ declare const WavedashEvents: { readonly LOBBY_MESSAGE: "LobbyMessage"; readonly LOBBY_JOINED: "LobbyJoined"; readonly LOBBY_KICKED: "LobbyKicked"; readonly LOBBY_USERS_UPDATED: "LobbyUsersUpdated"; readonly LOBBY_DATA_UPDATED: "LobbyDataUpdated"; readonly LOBBY_INVITE: "LobbyInvite"; readonly P2P_CONNECTION_ESTABLISHED: "P2PConnectionEstablished"; readonly P2P_CONNECTION_FAILED: "P2PConnectionFailed"; readonly P2P_PEER_DISCONNECTED: "P2PPeerDisconnected"; readonly P2P_PEER_RECONNECTING: "P2PPeerReconnecting"; readonly P2P_PEER_RECONNECTED: "P2PPeerReconnected"; readonly P2P_PACKET_DROPPED: "P2PPacketDropped"; readonly STATS_STORED: "StatsStored"; readonly BACKEND_CONNECTED: "BackendConnected"; readonly BACKEND_DISCONNECTED: "BackendDisconnected"; readonly BACKEND_RECONNECTING: "BackendReconnecting"; readonly FULLSCREEN_CHANGED: "FullscreenChanged"; readonly MUTE_CHANGED: "MuteChanged"; readonly ENTITLEMENTS_GRANTED: "EntitlementsGranted"; }; /** Reasons why a user was kicked from a lobby */ declare const LobbyKickedReason$1: { readonly KICKED: "KICKED"; readonly ERROR: "ERROR"; }; /** Change types for lobby user updates */ declare const LobbyUserChangeType$1: { readonly JOINED: "JOINED"; readonly LEFT: "LEFT"; }; /** * Reason a P2P packet was dropped. Each reason implies a different * game-side remedy: * - QUEUE_FULL: throttle your sends, bundle updates into fewer packets, or increase p2p maxIncomingMessages config * - PAYLOAD_TOO_LARGE: reduce payload or increase p2p messageSize config * - INVALID_PAYLOAD_SIZE: programming error * - INVALID_CHANNEL: SDK version skew or malicious peer * - MALFORMED: wire data too short to parse; channel will be -1 * - PEER_NOT_READY: P2P not yet initialized, or peer was never ready / closed mid-send. If P2P hasn't been initialized, initialize it first; otherwise wait for P2P_CONNECTION_ESTABLISHED and watch P2P_PEER_DISCONNECTED/P2P_CONNECTION_FAILED/P2P_PEER_RECONNECTING for reachability. */ declare const P2PPacketDropReason$1: { readonly QUEUE_FULL: "QUEUE_FULL"; readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE"; readonly INVALID_PAYLOAD_SIZE: "INVALID_PAYLOAD_SIZE"; readonly INVALID_CHANNEL: "INVALID_CHANNEL"; readonly MALFORMED: "MALFORMED"; readonly PEER_NOT_READY: "PEER_NOT_READY"; }; /** * Public types exported from @wvdsh/sdk-js */ type LobbyVisibility = (typeof LOBBY_VISIBILITY)[keyof typeof LOBBY_VISIBILITY]; type LeaderboardSortOrder = (typeof LEADERBOARD_SORT_ORDER)[keyof typeof LEADERBOARD_SORT_ORDER]; type LeaderboardDisplayType = (typeof LEADERBOARD_DISPLAY_TYPE)[keyof typeof LEADERBOARD_DISPLAY_TYPE]; type UGCType = (typeof UGC_TYPE)[keyof typeof UGC_TYPE]; type UGCVisibility = (typeof UGC_VISIBILITY)[keyof typeof UGC_VISIBILITY]; type UpdateUGCItemArgs = Omit, "ugcId" | "createPresignedUploadUrl"> & { filePath?: string; }; type UGCItem = FunctionReturnType["page"][0]; type PaginatedUGCItems = FunctionReturnType; type RawListUGCItemsArgs = FunctionArgs; type ListUGCItemsArgs = Omit & NonNullable; type LobbyUser = FunctionReturnType[0]; type LobbyMessage = FunctionReturnType[0]; type Lobby = FunctionReturnType[0]; type LobbyJoinResponse = FunctionReturnType; type LobbyInvite = FunctionReturnType[0]; /** A value stored in lobby metadata. */ type LobbyDataValue = FunctionReturnType[string]; /** * A value accepted by `setLobbyData`, where `null` deletes the key rather than * storing a value — so `false` and "unset" stay distinguishable. Distinct from * the `null` `getLobbyData` returns, which just means the key isn't set. */ type LobbyDataUpdate = FunctionArgs["updates"][string]; type Friend = FunctionReturnType[0]; type Leaderboard = FunctionReturnType; type LeaderboardEntries = FunctionReturnType["entries"]; type UpsertedLeaderboardEntry = FunctionReturnType["entry"] & { userId: GenericId<"users">; username: string; userAvatarUrl?: string; submittedScore: number; submittedRank: number; }; type LeaderboardEntryMetadata = NonNullable["metadata"]>; type WavedashEvent = (typeof WavedashEvents)[keyof typeof WavedashEvents]; interface WavedashConfig { debug?: boolean; remoteStorageOrigin?: string; p2p?: Partial; deferEvents?: boolean; } interface RemoteFileMetadata { exists: boolean; key: string; name: string; lastModified: number; size: number; etag: string; } interface EngineInstance { type: (typeof GAME_ENGINE)[keyof typeof GAME_ENGINE]; SendMessage(objectName: string, methodName: WavedashEvent, value?: string | number): void; FS: { readFile(path: string, opts?: Record): string | Uint8Array; writeFile(path: string, data: string | ArrayBufferView, opts?: Record): void; mkdirTree(path: string, mode?: number): void; syncfs(populate: boolean, callback?: (err: unknown) => void): void; analyzePath(path: string): { exists: boolean; }; }; unityPersistentDataPath?: string; } type WavedashResponse = { success: true; data: T; } | { success: false; data: null; message: string; }; /** Payload for LobbyJoined event - emitted on successful lobby join or create */ interface LobbyJoinedPayload { lobbyId: GenericId<"lobbies">; hostId: GenericId<"users">; users: LobbyUser[]; metadata: Record; } type LobbyKickedReason = (typeof LobbyKickedReason$1)[keyof typeof LobbyKickedReason$1]; /** Payload for LobbyKicked event - emitted when removed from a lobby */ interface LobbyKickedPayload { lobbyId: GenericId<"lobbies">; reason: LobbyKickedReason; } type LobbyUserChangeType = (typeof LobbyUserChangeType$1)[keyof typeof LobbyUserChangeType$1]; /** Payload for LobbyUsersUpdated event - emitted when a user joins or leaves */ interface LobbyUsersUpdatedPayload extends LobbyUser { changeType: LobbyUserChangeType; } /** Payload for LobbyDataUpdated event - the full lobby metadata */ type LobbyDataUpdatedPayload = Record; /** Payload for LobbyMessage event - a message received in the lobby */ type LobbyMessagePayload = LobbyMessage; /** Payload for LobbyInvite event - an invite to join a lobby */ type LobbyInvitePayload = LobbyInvite; /** Payload for StatsStored event - emitted when stats/achievements are persisted */ interface StatsStoredPayload { success: boolean; message?: string; } /** Payload for P2PConnectionEstablished event */ interface P2PConnectionEstablishedPayload { userId: GenericId<"users">; username: string; } /** Payload for P2PConnectionFailed event */ interface P2PConnectionFailedPayload { userId: GenericId<"users">; username: string; error: string; } /** Payload for P2PPeerDisconnected event */ interface P2PPeerDisconnectedPayload { userId: GenericId<"users">; username: string; } /** Payload for P2PPeerReconnecting event */ interface P2PPeerReconnectingPayload { userId: GenericId<"users">; username: string; } /** Payload for P2PPeerReconnected event */ interface P2PPeerReconnectedPayload { userId: GenericId<"users">; username: string; } type P2PPacketDropReason = (typeof P2PPacketDropReason$1)[keyof typeof P2PPacketDropReason$1]; /** * Payload for P2PPacketDropped event. * * Emitted whenever the SDK drops a P2P packet — either outgoing (rejected * by local validation) or incoming (rejected by the receive-side ring * buffer / framing layer). * * Events are aggregated per `(channel, direction, reason)` tuple with a * short window so bursty drops don't flood the game, while sparse drops * still fire promptly. */ interface P2PPacketDroppedPayload { channel: number; direction: "SEND" | "RECEIVE"; reason: P2PPacketDropReason; droppedCount: number; droppedTotal: number; } /** Payload for BackendConnected, BackendDisconnected, BackendReconnecting events */ interface BackendConnectionPayload { isConnected: boolean; hasEverConnected: boolean; connectionCount: number; connectionRetries: number; } /** Payload for FullscreenChanged event - emitted when fullscreen state flips */ interface FullscreenChangedPayload { isFullscreen: boolean; } /** Payload for MuteChanged event - emitted when mute state flips */ interface MuteChangedPayload { isMuted: boolean; } /** * Payload for EntitlementsGranted event - emitted when the player is granted * paid content, regardless of source (in-game paywall, game page purchase, * gift redemption, purchase from another tab). A list so one checkout can * grant multiple contents (bundles). The gameplay JWT is refreshed before * this event fires, so `isEntitled()` is already true for every entry. */ interface EntitlementsGrantedPayload { contentIdentifiers: string[]; } type WavedashEventMap = { [WavedashEvents.LOBBY_MESSAGE]: LobbyMessagePayload; [WavedashEvents.LOBBY_JOINED]: LobbyJoinedPayload; [WavedashEvents.LOBBY_KICKED]: LobbyKickedPayload; [WavedashEvents.LOBBY_USERS_UPDATED]: LobbyUsersUpdatedPayload; [WavedashEvents.LOBBY_DATA_UPDATED]: LobbyDataUpdatedPayload; [WavedashEvents.LOBBY_INVITE]: LobbyInvitePayload; [WavedashEvents.P2P_CONNECTION_ESTABLISHED]: P2PConnectionEstablishedPayload; [WavedashEvents.P2P_CONNECTION_FAILED]: P2PConnectionFailedPayload; [WavedashEvents.P2P_PEER_DISCONNECTED]: P2PPeerDisconnectedPayload; [WavedashEvents.P2P_PEER_RECONNECTING]: P2PPeerReconnectingPayload; [WavedashEvents.P2P_PEER_RECONNECTED]: P2PPeerReconnectedPayload; [WavedashEvents.P2P_PACKET_DROPPED]: P2PPacketDroppedPayload; [WavedashEvents.STATS_STORED]: StatsStoredPayload; [WavedashEvents.BACKEND_CONNECTED]: BackendConnectionPayload; [WavedashEvents.BACKEND_DISCONNECTED]: BackendConnectionPayload; [WavedashEvents.BACKEND_RECONNECTING]: BackendConnectionPayload; [WavedashEvents.FULLSCREEN_CHANGED]: FullscreenChangedPayload; [WavedashEvents.MUTE_CHANGED]: MuteChangedPayload; [WavedashEvents.ENTITLEMENTS_GRANTED]: EntitlementsGrantedPayload; }; interface P2PPeer { userId: GenericId<"users">; username: string; } interface P2PConnection { lobbyId: GenericId<"lobbies">; peers: Record, P2PPeer>; } interface P2PMessage { fromUserId: GenericId<"users">; channel: number; payload: Uint8Array; } interface P2PConfig { enableReliableChannel: boolean; enableUnreliableChannel: boolean; messageSize?: number; maxIncomingMessages?: number; } /** * File system service * Utilities for syncing local IndexedDB files with remote storage. * * Exposes a specific remote folder for the game to save user-specific files to. * TODO: Extend this to game-level assets as well. */ declare class FileSystemManager extends WavedashManager { private remoteStorageOrigin; constructor(sdk: WavedashSDK); /** * Converts a local filesystem path into a full R2 object key. * Normalizes the Unity persistentDataPath and prepends the R2 prefix. */ private toRemoteKey; /** * Converts a full R2 object key back into the local filesystem path * the engine expects. Inverse of toRemoteKey. */ private toLocalPath; /** * Uploads a local file to remote storage * @param filePath - The path of the local file to upload * @returns The path of the remote file that the local file was uploaded to */ uploadRemoteFile(filePath: string): Promise; /** * Deletes a remote file from storage * @param filePath - The path of the remote file to delete * @returns The path of the remote file that was deleted */ deleteRemoteFile(filePath: string): Promise; /** * Downloads a remote file to a local location. * Throws on failure; the error message is the server's HTTP status (e.g. "404 (Not Found)") * or a network-level description if the server didn't respond. See also: {@link remoteFileExists} * @param filePath - The path of the remote file to download * @returns The path of the local file that the remote file was downloaded to */ downloadRemoteFile(filePath: string): Promise; /** * Checks whether a remote file exists by issuing a HEAD request. * Does NOT throw for the "file does not exist" case — returns false. * Throws only for real errors (network failure, auth failure, server error). * @param filePath - The path of the remote file to check * @returns true if the remote file exists, false otherwise */ remoteFileExists(filePath: string): Promise; /** * Lists each file in a remote directory, including its subdirectories. * Returns only file paths, no directory paths. * An empty or non-existent directory returns an empty array — not an error. * @param path - The path of the remote directory to list * @returns A list of metadata for each file in the remote directory */ listRemoteDirectory(path: string): Promise; downloadRemoteDirectory(path: string): Promise; writeLocalFile(filePath: string, data: Uint8Array): Promise; readLocalFile(filePath: string): Promise; private queuedUploads; private activeUploads; upload(presignedUploadUrl: string, filePath: string): Promise; private drainUploads; private putLocalFile; download(url: string, filePath: string): Promise; private getRemoteStorageOrigin; private getRemoteStorageUrl; private static readonly KEEPALIVE_MAX_BYTES; private static readonly UPLOAD_TIMEOUT_MS; /** * PUT a blob to its signed upload URL. Small bodies use `keepalive` so the * upload survives the page unloading mid-save; if the shared keepalive * quota is exhausted (fetch throws immediately), retry as a normal request. */ private uploadBlob; private uploadFromIndexedDb; private uploadFromFS; private readLocalFileBlob; } /** * Friends service * * Implements friend-related methods for the Wavedash SDK */ declare class FriendsManager extends WavedashManager { private userCache; private leaderboardPageUserCache; constructor(sdk: WavedashSDK); /** * Returns CDN URL with size transformation for a cached user's avatar. * @param userId - The user ID to get the avatar URL for * @param size - Pixel size for width and height. Use a value from * `AvatarSize` (SMALL=64, MEDIUM=128, LARGE=256) or any custom pixel size. * @returns CDN URL with size transformation, or null if user not cached or has no avatar */ getUserAvatarUrl(userId: GenericId<"users">, size?: number): string | null; /** * Returns the cached username for a given user ID * @param userId - The user ID to get the username for * @returns The username, or null if user not cached */ getUsername(userId: GenericId<"users">): string | null; /** * List all friends for the logged in user * @returns Array<{ * avatarUrl?: string; * isOnline: boolean; * userId: Id<"users">; * username: string; * }> */ listFriends(): Promise; } /** * FullscreenManager * * Wavedash owns the fullscreen target (a wrapper DIV on the host page that * contains both the game iframe and our overlay UI). The SDK inside the iframe * therefore can't call `requestFullscreen` directly — it asks the parent to * do it via postMessage, and the parent broadcasts state changes back through * FULLSCREEN_CHANGED so we can keep a local mirror of `isFullscreen`. * * User activation: browsers require a fresh user gesture to enter fullscreen. * The click happens in the iframe, User Activation v2 propagates transient * activation to ancestor frames, and the parent's message handler runs within * the ~5s window — so the parent's requestFullscreen call stays activated. * * Legacy compat: games that call `element.requestFullscreen()` or listen for * `fullscreenchange` directly are monkey-patched in the constructor so those * calls route through us. The iframe isn't granted the fullscreen feature * policy anymore, so without these shims those calls would silently reject. */ declare class FullscreenManager extends WavedashManager { private _isFullscreen; private listeners; constructor(sdk: WavedashSDK); isFullscreen(): boolean; /** * Ask the host to enter (true) or exit (false) fullscreen. Resolves to * `true` if the host reports the operation succeeded, `false` otherwise * (e.g. browser rejected for lack of user activation). */ requestFullscreen(fullscreen: boolean): Promise; toggleFullscreen(): Promise; /** Subscribe to state flips. Returns an unsubscribe fn. */ subscribe(listener: (isFullscreen: boolean) => void): () => void; private setState; private installCompatShims; } declare class GameEventManager extends WavedashManager { private eventQueue; constructor(sdk: WavedashSDK); notifyGame(event: WavedashEvent, payload: string | number | object): void; private sendGameEvent; flushEventQueue(): void; } /** * Heartbeat service * * Polls connection state and allows the game to update rich user presence * Lets the game know if backend connection ever changes. * Lets the game update userPresence in the backend */ declare class HeartbeatManager extends WavedashManager { private deviceFingerprint; private deviceFingerprintReady; private testConnectionInterval; private heartbeatInterval; private gamepadPollInterval; private inactivityTimeout; private isConnected; private sentDisconnectedEvent; private disconnectedAt; private lastHeartbeatTime; private lastInputResetAt; private heartbeatInFlight; private isFirstTick; private readonly TEST_CONNECTION_INTERVAL_MS; private readonly DISCONNECTED_TIMEOUT_MS; private readonly INACTIVITY_TIMEOUT_MS; private readonly INPUT_THROTTLE_MS; private readonly GAMEPAD_POLL_INTERVAL_MS; private readonly GAMEPAD_AXIS_DEADZONE; private cachedPresenceData; constructor(sdk: WavedashSDK); /** * Start (or refresh) the heartbeat. Idempotent: if intervals are already * running this just reschedules the inactivity timer. No-op if the game * hasn't loaded yet or the tab is hidden. */ start(): void; /** Stop the heartbeat and clear the inactivity timer. Idempotent. */ stop(): void; /** * Updates user presence in the backend. * @param data - Data to send to the backend * @returns true if the presence was updated successfully */ updateUserPresence(data: Record): Promise; isCurrentlyConnected(): boolean; /** Full teardown — stops intervals and removes all listeners */ destroy(): void; private tickHeartbeat; private sendHeartbeat; private handleVisibilityChange; private handleUserInput; /** * Polls connected gamepads; any pressed button or out-of-deadzone axis * counts as user activity and (re)starts the heartbeat. */ private pollGamepads; /** * Tests the connection to the backend */ private testConnection; } /** * Leaderboard service * * Implements each of the leaderboard methods of the Wavedash SDK */ declare class LeaderboardManager extends WavedashManager { private leaderboardCache; constructor(sdk: WavedashSDK); getLeaderboard(name: string): Promise; getOrCreateLeaderboard(name: string, sortOrder: LeaderboardSortOrder, displayType: LeaderboardDisplayType): Promise; getLeaderboardEntryCount(leaderboardId: GenericId<"leaderboards">): number; getMyLeaderboardEntries(leaderboardId: GenericId<"leaderboards">): Promise; listLeaderboardEntriesAroundUser(leaderboardId: GenericId<"leaderboards">, countAhead: number, countBehind: number, friendsOnly?: boolean): Promise; listLeaderboardEntries(leaderboardId: GenericId<"leaderboards">, offset: number, limit: number, friendsOnly?: boolean): Promise; uploadLeaderboardScore(leaderboardId: GenericId<"leaderboards">, score: number, keepBest: boolean, ugcId?: GenericId<"userGeneratedContent">, metadata?: LeaderboardEntryMetadata): Promise; private updateCachedTotalEntries; } /** * Lobby service * * Implements each of the lobby methods of the Wavedash SDK */ declare class LobbyManager extends WavedashManager { private unsubscribeLobbyMessages; private unsubscribeLobbyUsers; private unsubscribeLobbyData; private lobbyId; private lobbyUsers; private lobbyHostId; private lobbyMetadata; private pendingMetadataUpdates; private recentMessageIds; private maybeBeingDeletedLobbyIds; private resetMaybeBeingDeletedLobbyIdTimeouts; private static readonly METADATA_UPDATE_THROTTLE_MS; private inFlightMetadataUpdate; private cachedLobbies; private unsubscribeLobbyInvites; private seenInviteIds; private p2pUpdateQueue; constructor(sdk: WavedashSDK); createLobby(visibility: LobbyVisibility, maxPlayers?: number): Promise>; /** * Join a lobby * @param lobbyId - The ID of the lobby to join * @returns true on success. Full lobby context comes via LobbyJoined event. * @emits LobbyJoined event on success with full lobby context */ joinLobby(lobbyId: GenericId<"lobbies">): Promise; getLobbyUsers(lobbyId: GenericId<"lobbies">): LobbyUser[]; getHostId(lobbyId: GenericId<"lobbies">): GenericId<"users"> | null; getLobbyData(lobbyId: GenericId<"lobbies">, key: string): LobbyDataValue | null; deleteLobbyData(lobbyId: GenericId<"lobbies">, key: string): boolean; setLobbyData(lobbyId: GenericId<"lobbies">, key: string, value: LobbyDataUpdate): boolean; getLobbyMaxPlayers(lobbyId: GenericId<"lobbies">): number; getNumLobbyUsers(lobbyId: GenericId<"lobbies">): number; leaveLobby(lobbyId: GenericId<"lobbies">): Promise>; listAvailableLobbies(friendsOnly?: boolean): Promise; getLobby(lobbyId: GenericId<"lobbies">): Promise; sendLobbyMessage(lobbyId: GenericId<"lobbies">, message: string): boolean; inviteUserToLobby(lobbyId: GenericId<"lobbies">, userId: GenericId<"users">): Promise; getLobbyInviteLink(copyToClipboard?: boolean): Promise; /** * Initialize local lobby state and subscribe to all relevant updates. * Sets up Convex subscriptions for messages, users, and metadata. * Emits LobbyJoined event to the game engine. * @precondition - The user has already joined the lobby via mutation * @param response - The full response from createAndJoinLobby or joinLobby mutation */ private handleLobbyJoin; /** * Handle being kicked or removed from a lobby. * Called when a subscription fails with "User is not a member of this lobby". * Multiple subscriptions may error at once, so we guard against emitting multiple events. */ private handleLobbyKicked; /** * Clean up lobby state without emitting events * Used internally by handleLobbyJoin() and handleLobbyKicked() */ private cleanupLobbyState; /** * Public method to clean up lobby state without emitting events * Used for session end cleanup */ unsubscribeFromCurrentLobby(): void; /** * Fully destroy the LobbyManager, cleaning up all subscriptions and timeouts. * Called during session end to ensure no lingering listeners. */ destroy(): void; private throttledSetMetadata; private setMetadata; /** * Process user updates and emit individual user events * @param newUsers - The updated list of lobby users */ private processUserUpdates; private processMessageUpdates; private processInviteUpdates; /** * Update P2P connections when lobby membership changes * @param newUsers - The updated list of lobby users */ private updateP2PConnections; } /** * OverlayManager * * Owns the iframe ↔ parent interactions for the Wavedash overlay UI: * - Shift+Tab inside the iframe toggles the overlay on the host page * (the host owns the overlay, so we postMessage up). * - When the parent closes the overlay it sends TAKE_FOCUS, which hands * keyboard focus back to the game (see `takeFocus`). * - While the overlay is open we suspend pointer lock (the host broadcasts * OVERLAY_CHANGED) so a game can't hold/re-grab the cursor behind it. */ declare class OverlayManager extends WavedashManager { private restorePointerLock; constructor(sdk: WavedashSDK); private setOpen; toggleOverlay(): void; private handleKeyDown; destroy(): void; } /** * P2P networking service * * Handles WebRTC peer-to-peer connections for lobbies */ declare class P2PManager extends WavedashManager { private config; private currentConnection; private peerConnections; private reliableChannels; private unreliableChannels; private pendingIceCandidates; private iceRestartAttempts; private iceRestartInProgress; private readonly MAX_ICE_RESTART_ATTEMPTS; private reconnectingPeers; private establishedPeers; private packetDropTrackers; private readonly PACKET_DROP_WINDOW_MS; private turnCredentials; private turnCredentialsInitPromise; private unsubscribeFromSignalingMessages; private processedSignalingMessages; private pendingProcessedMessageIds; private initializationInProgress; private initializationLobbyId; private signalingSubscriptionReady; private signalingSubscriptionReadyResolver; private channelQueues; private readonly MESSAGE_SLOT_HEADER_SIZE; private readonly MAX_CHANNELS; private readonly USERID_SIZE; private readonly CHANNEL_SIZE; private readonly DATALENGTH_SIZE; private readonly CHANNEL_OFFSET; private readonly DATALENGTH_OFFSET; private readonly PAYLOAD_OFFSET; private readonly WIRE_CHANNEL_SIZE; private readonly WIRE_CHANNEL_OFFSET; private readonly WIRE_PAYLOAD_OFFSET; private static readonly MAX_MESSAGE_SIZE; private static readonly MEMORY_WARNING_THRESHOLD_BYTES; private QUEUE_SIZE; private MESSAGE_SIZE; private MAX_PAYLOAD_SIZE; private outgoingMessageBuffer; private textEncoder; private textDecoder; private initialized; constructor(sdk: WavedashSDK); destroy(): void; private ensureInitialized; init(config?: Partial): void; initializeP2PForCurrentLobby(lobbyId: GenericId<"lobbies">, members: SDKUser[]): Promise; /** * Internal method that performs the actual P2P initialization. * Called by initializeP2PForCurrentLobby with proper locking. */ private doInitializeP2P; /** * Get ICE servers, initializing TURN credentials if necessary. * Uses a promise to debounce concurrent calls and prevent race conditions. */ private getIceServers; private updateP2PConnection; private establishWebRTCConnections; private subscribeToSignalingMessages; private stopSignalingMessageSubscription; private processSignalingMessages; private handleSignalingMessage; /** * Flush any buffered ICE candidates for a peer after remote description is set. * This handles the race condition where ICE candidates arrive before the offer/answer. */ private flushPendingIceCandidates; private establishPeerConnections; private createOfferToPeer; private createPeerConnection; /** * Attempt to restart ICE when connection fails. * Only the peer with the lower userId initiates the restart to avoid conflicts. */ private attemptIceRestart; private setupDataChannelHandlers; sendP2PMessage(toUserId: GenericId<"users"> | undefined, appChannel: number | undefined, reliable: boolean | undefined, payload: Uint8Array, payloadSize?: number): boolean; private sendSignalingMessage; disconnectP2P(): void; isPeerReady(userId: GenericId<"users">): boolean; isBroadcastReady(): boolean; getPeerStatuses(): Record, { reliable?: string; unreliable?: string; ready: boolean; }>; private createChannelQueue; /** * Record a packet drop and emit P2P_PACKET_DROPPED with rate-limiting per * (channel, direction, reason) tuple. First drop on an idle tuple fires * immediately; subsequent drops within PACKET_DROP_WINDOW_MS are coalesced * into a single event at the end of the window. */ private reportPacketDrop; private flushPacketDropWindow; private emitPacketDropped; private clearPacketDropTrackers; private enqueueMessage; getMaxPayloadSize(): number; getMaxIncomingMessages(): number; getOutgoingMessageBuffer(): Uint8Array; readMessageFromChannel(appChannel: number): P2PMessage | null; private readRawMessage; drainChannelToBuffer(appChannel: number, buffer?: Uint8Array): Uint8Array; private encodeWireMessage; private decodeBinaryMessage; } declare class PaidContentManager extends WavedashManager { private paywallOpen; private restorePointerLock; constructor(sdk: WavedashSDK); /** * Host broadcast: the player was granted paid content, from any source (the * game's own paywall, the game page purchase list, a gift redemption, or a * purchase in another tab). Refresh the gameplay JWT first so the new * entitlement is already reflected (isEntitled(), paid-asset requests) by * the time the game receives the event. */ private handleEntitlementsGranted; isEntitled(contentIdentifier: string): Promise; getEntitlements(): Promise; triggerPaywall(contentIdentifier: string): Promise; isPaywallOpen(): boolean; destroy(): void; } declare class StatsManager extends WavedashManager { private stats; private unlockedAchievements; private dirtyStats; private dirtyAchievements; private knownStatIds; private knownAchievementIds; private loaded; private subscriptions; private inFlightPersist; private flushRequested; constructor(sdk: WavedashSDK); destroy(): void; private isReady; private subscribe; requestStats(): Promise; private throttledPersist; storeStats(): boolean; private requestPersistFlush; private persist; getStat(identifier: string): number; setStat(identifier: string, value: number, storeNow?: boolean): boolean; getAchievement(identifier: string): boolean; setAchievement(identifier: string, storeNow?: boolean): boolean; /** @destructive - Returns the pending stats and achievements and resets the dirty collections */ private getPendingData; } /** * UGC service * * Implements each of the user generated content methods of the Wavedash SDK */ declare class UGCManager extends WavedashManager { constructor(sdk: WavedashSDK); createUGCItem(ugcType: UGCType, title?: string, description?: string, visibility?: UGCVisibility, filePath?: string): Promise>; updateUGCItem(ugcId: GenericId<"userGeneratedContent">, updates?: UpdateUGCItemArgs): Promise>; deleteUGCItem(ugcId: GenericId<"userGeneratedContent">): Promise>; downloadUGCItem(ugcId: GenericId<"userGeneratedContent">, filePath: string): Promise>; listUGCItems(args?: ListUGCItemsArgs): Promise; } /** * Utilities for handling iframe messaging between the iframe'd Wavedash SDK and the parent window. * Assumes window is defined and this is only ever running inside an iframe. * * TODO: Look into Vercel's BIDC for this https://github.com/vercel/bidc */ type PushType = keyof IFrameEventPayloadMap; type PushListener = (data: IFrameEventPayloadMap[T]) => void; declare class IFrameMessenger { private pendingRequests; private requestIdCounter; private listeners; constructor(); /** * Register a handler for a one-way (no requestId) push from the parent — * e.g. FULLSCREEN_CHANGED or TAKE_FOCUS. Multiple handlers per type are * supported; `data` is typed from IFramePushMap. */ addEventListener(type: T, listener: PushListener): void; removeEventListener(type: T, listener: PushListener): void; private handleMessage; postToParent(requestType: (typeof IFRAME_MESSAGE_TYPE)[keyof typeof IFRAME_MESSAGE_TYPE], data: Record): boolean; requestFromParent(requestType: T, data?: Record, timeoutMs?: number): Promise; } /** * Utilities for messaging between the SDK and the service worker * that proxies API requests on its behalf. */ type SwMessage = { type: string; payload?: T; }; type SwReply = (message: SwMessage) => void; type SwListener = (payload: unknown, reply: SwReply) => void; declare class SwMessenger { private listeners; constructor(); /** * Register a handler for an incoming message type from the SW. The handler * receives the message payload and a `reply` function that routes the * response back via the transferred MessagePort when present, falling back * to a controller postMessage otherwise. */ addEventListener(type: string, listener: SwListener): void; removeEventListener(type: string, listener: SwListener): void; /** * Fire-and-forget message to the active service worker controller. No-op * when no SW is controlling the page (first load before activation, or * environments without SW support). */ postToServiceWorker(message: SwMessage): boolean; private handleMessage; } declare class WavedashSDK extends EventTarget { private _initialized; get initialized(): boolean; private _eventsReady; get eventsReady(): boolean; private launchParams; private destroyed; private gameFinishedLoading; private gameStartedLoading; Events: { readonly LOBBY_MESSAGE: "LobbyMessage"; readonly LOBBY_JOINED: "LobbyJoined"; readonly LOBBY_KICKED: "LobbyKicked"; readonly LOBBY_USERS_UPDATED: "LobbyUsersUpdated"; readonly LOBBY_DATA_UPDATED: "LobbyDataUpdated"; readonly LOBBY_INVITE: "LobbyInvite"; readonly P2P_CONNECTION_ESTABLISHED: "P2PConnectionEstablished"; readonly P2P_CONNECTION_FAILED: "P2PConnectionFailed"; readonly P2P_PEER_DISCONNECTED: "P2PPeerDisconnected"; readonly P2P_PEER_RECONNECTING: "P2PPeerReconnecting"; readonly P2P_PEER_RECONNECTED: "P2PPeerReconnected"; readonly P2P_PACKET_DROPPED: "P2PPacketDropped"; readonly STATS_STORED: "StatsStored"; readonly BACKEND_CONNECTED: "BackendConnected"; readonly BACKEND_DISCONNECTED: "BackendDisconnected"; readonly BACKEND_RECONNECTING: "BackendReconnecting"; readonly FULLSCREEN_CHANGED: "FullscreenChanged"; readonly MUTE_CHANGED: "MuteChanged"; readonly ENTITLEMENTS_GRANTED: "EntitlementsGranted"; }; LobbyVisibility: { readonly PUBLIC: 0; readonly FRIENDS_ONLY: 1; readonly PRIVATE: 2; }; LeaderboardSortOrder: { readonly ASC: 0; readonly DESC: 1; }; LeaderboardDisplayType: { readonly NUMERIC: 0; readonly TIME_SECONDS: 1; readonly TIME_MILLISECONDS: 2; readonly TIME_GAME_TICKS: 3; }; UGCType: { readonly SCREENSHOT: 0; readonly VIDEO: 1; readonly COMMUNITY: 2; readonly GAME_MANAGED: 3; readonly OTHER: 4; }; UGCVisibility: { readonly PUBLIC: 0; readonly PRIVATE: 2; }; AvatarSize: { readonly SMALL: 64; readonly MEDIUM: 128; readonly LARGE: 256; }; LobbyKickedReason: { readonly KICKED: "KICKED"; readonly ERROR: "ERROR"; }; LobbyUserChangeType: { readonly JOINED: "JOINED"; readonly LEFT: "LEFT"; }; P2PPacketDropReason: { readonly QUEUE_FULL: "QUEUE_FULL"; readonly PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE"; readonly INVALID_PAYLOAD_SIZE: "INVALID_PAYLOAD_SIZE"; readonly INVALID_CHANNEL: "INVALID_CHANNEL"; readonly MALFORMED: "MALFORMED"; readonly PEER_NOT_READY: "PEER_NOT_READY"; }; protected lobbyManager: LobbyManager; protected statsManager: StatsManager; protected heartbeatManager: HeartbeatManager; protected ugcManager: UGCManager; protected leaderboardManager: LeaderboardManager; gameEventManager: GameEventManager; friendsManager: FriendsManager; config: WavedashConfig | null; wavedashUser: SDKUser; gameCloudId: SDKConfig["gameCloudId"]; fileSystemManager: FileSystemManager; convexClient: ConvexClient; engineCallbackReceiver: string; engineInstance: EngineInstance | null; iframeMessenger: IFrameMessenger; swMessenger: SwMessenger; p2pManager: P2PManager; fullscreenManager: FullscreenManager; overlayManager: OverlayManager; audioManager: AudioManager; paidContentManager: PaidContentManager; externalLinkManager: ExternalLinkManager; private managers; private gameplayJwt; private gameplayJwtPromise; private setupWarningTimeout; ugcHost: string; uploadsHost: string; constructor(sdkConfig: SDKConfig); private clearSetupWarning; init(config?: WavedashConfig): boolean; /** * Signal that the game is ready to receive events (LobbyJoined, LobbyMessage, etc). * Called automatically by init() unless deferEvents: true is passed in the config. * If deferEvents is true, call this manually after your pre-game setup is complete. */ readyForEvents(): void; private listenerWrappers; /** * Subscribe to a Wavedash event with a payload-typed listener. * Returns an unsubscribe function. * * const unsubscribeLobbyJoined = Wavedash.on(Wavedash.Events.LOBBY_JOINED, (payload) => { * // payload: LobbyJoinedPayload * }); * unsubscribeLobbyJoined(); // later */ on(event: K, listener: (payload: WavedashEventMap[K]) => void): () => void; /** * Remove a listener previously registered with {@link on}. */ off(event: K, listener: (payload: WavedashEventMap[K]) => void): void; addEventListener(type: K, listener: (ev: CustomEvent) => void, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (ev: CustomEvent) => void, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void; loadScript(src: string): Promise; updateLoadProgressZeroToOne(progress: number): void; loadComplete(): void; get gameLoaded(): boolean; toggleOverlay(): void; /** * Whether the game is currently presented in fullscreen. Mirrored from the * Wavedash host page, which owns the real fullscreen target so our overlay * UI stays on top of the game. */ isFullscreen(): boolean; /** * Ask the host page to enter (true) or exit (false) fullscreen. Entering * must happen inside a user gesture handler (click / keydown / pointerdown) * for the browser to permit it. */ requestFullscreen(fullscreen: boolean): Promise; /** * Toggle fullscreen. Like `requestFullscreen(true)`, this must run inside * a user gesture handler when entering fullscreen. */ toggleFullscreen(): Promise; /** * Hand an external URL to the player: it's copied to their clipboard and * Wavedash shows an in-game toast, rather than navigating them out of the * game. Must be called inside a user gesture handler (click / keydown / * pointerdown). */ copyLink(url: string): Promise; /** * Whether the game is currently muted. Mirrored from the Wavedash host page, * which owns the mute control so its UI button and the game stay in sync. */ isMuted(): boolean; /** * Ask the host to mute (true) or unmute (false). Resolves to `true` if the * change was applied, `false` if it was rejected — the host won't let the * game unmute when the user has muted from the Wavedash UI. */ requestMute(muted: boolean): Promise; /** * Toggle mute. Resolves to `true` if the change was applied, `false` if it * was rejected (e.g. trying to unmute over an explicit user mute). */ toggleMute(): Promise; getUser(): SDKUser; /** * Get a username. Returns the logged in user's username if no ID is passed. * This can only return a username for a user the game has already interacted with, either via listFriends() or shared lobby membership. * @param userId - Optional user ID to look up. If omitted, returns the current user's username. * @returns The username, or null if a userId was passed but the user has not been seen by the game yet. */ getUsername(): string; getUsername(userId: GenericId<"users">): string | null; getUserId(): GenericId<"users">; /** * Get the current user's gameplay JWT, fetching it if not already cached. * This should be used to authenticate requests to your game's own backend, * if you have one. * @returns The user's JWT signed by the Wavedash backend */ getUserJwt(): Promise>; /** * Get the key: value mapping of all URL query params present when the game was launched * lobby - The lobby ID to join if the user launched with the intention to join a lobby * @returns Dictionary of the URL query params that were present when the game was launched */ getLaunchParams(): GameLaunchParams; listFriends(): Promise>; /** * Get avatar URL for a cached user with size transformation. * Users are cached when seen via listFriends() or lobby membership. * @param userId - The user ID to get the avatar URL for * @param size - Avatar size constant (Wavedash.AvatarSize.SMALL=0, Wavedash.AvatarSize.MEDIUM=1, Wavedash.AvatarSize.LARGE=2) * @returns CDN URL with size transformation, or null if user not cached or has no avatar */ getUserAvatarUrl(userId: GenericId<"users">, size?: number): string | null; getLeaderboard(name: string): Promise>; getOrCreateLeaderboard(name: string, sortOrder: LeaderboardSortOrder, displayType: LeaderboardDisplayType): Promise>; getLeaderboardEntryCount(leaderboardId: GenericId<"leaderboards">): number; getMyLeaderboardEntries(leaderboardId: GenericId<"leaderboards">): Promise>; listLeaderboardEntriesAroundUser(leaderboardId: GenericId<"leaderboards">, countAhead: number, countBehind: number, friendsOnly?: boolean): Promise>; listLeaderboardEntries(leaderboardId: GenericId<"leaderboards">, offset: number, limit: number, friendsOnly?: boolean): Promise>; uploadLeaderboardScore(leaderboardId: GenericId<"leaderboards">, score: number, keepBest: boolean, ugcId?: GenericId<"userGeneratedContent">, metadata?: LeaderboardEntryMetadata): Promise>; /** * Creates a new UGC item and uploads the file to the server if a filePath is provided * @param ugcType * @param title * @param description * @param visibility * @param filePath - optional IndexedDB key file path to upload to the server. If not provided, the UGC item will be created but no file will be uploaded. * @returns ugcId */ createUGCItem(ugcType: UGCType, title?: string, description?: string, visibility?: UGCVisibility, filePath?: string): Promise>>; /** * Updates a UGC item and uploads the file to the server if a filePath is provided * @param ugcId - The ID of the UGC item to update * @param updates - Object containing the fields to update. May also be passed * as a JSON string by engine bridges (Godot) that can't marshal a dict. * @returns ugcId */ updateUGCItem(ugcId: GenericId<"userGeneratedContent">, updates?: UpdateUGCItemArgs): Promise>>; /** * Delete a UGC item: removes the row, the R2 object, and frees up the * user's storage quota by the size of the deleted upload. */ deleteUGCItem(ugcId: GenericId<"userGeneratedContent">): Promise>>; downloadUGCItem(ugcId: GenericId<"userGeneratedContent">, filePath: string): Promise>>; listUGCItems(args?: ListUGCItemsArgs): Promise>; /** * Deletes a remote file from storage * @param filePath - The path of the remote file to delete * @returns The path of the remote file that was deleted */ deleteRemoteFile(filePath: string): Promise>; /** * Downloads a remote file to a local location. * Returns success=false (with the server status in `message`) if the file * doesn't exist or any other error occurs. See also: {@link remoteFileExists} * @param filePath - The path of the remote file to download * @returns The path of the local file that the remote file was downloaded to */ downloadRemoteFile(filePath: string): Promise>; /** * Checks whether a remote file exists. Sends a lightweight HEAD request to check for existence. * @param filePath - The path of the remote file to check * @returns true if the remote file exists, false if it does not. */ remoteFileExists(filePath: string): Promise>; /** * Uploads a local file to remote storage * @param filePath - The path of the local file to upload * @param uploadTo - Optionally provide a path to upload the file to, defaults to the same path as the local file * @returns The path of the remote file that the local file was uploaded to */ uploadRemoteFile(filePath: string): Promise>; /** * Lists a remote directory * @param path - The path of the remote directory to list * @returns A list of metadata for each file in the remote directory */ listRemoteDirectory(path: string): Promise>; /** * Downloads a remote directory to a local location * @param path - The path of the remote directory to download * @returns The path of the local directory that the remote directory was downloaded to */ downloadRemoteDirectory(path: string): Promise>; /** * Persists data to local file storage (IndexeDB). * For use in pure JS games. * Games built from engines should use their engine's builtin File API to read and write files. * @param filePath - The path of the local file to write * @param data - The data to write to the local file (byte array) * @returns true if the file was written successfully */ writeLocalFile(filePath: string, data: Uint8Array): Promise; /** * Reads data from local file storage (IndexedDB). * For use in pure JS games. * Games built from engines should use their engine's builtin File API to read and write files. * @param filePath - The path of the local file to read * @returns The data read from the local file (byte array) */ readLocalFile(filePath: string): Promise; getAchievement(identifier: string): boolean; getStat(identifier: string): number; setAchievement(identifier: string, storeNow?: boolean): boolean; setStat(identifier: string, value: number, storeNow?: boolean): boolean; requestStats(): Promise>; storeStats(): boolean; /** * Get the maximum payload size in bytes for a single P2P message. * This is derived from the configured messageSize minus protocol overhead. */ getP2PMaxPayloadSize(): number; /** * Get the configured max incoming messages per channel queue. */ getP2PMaxIncomingMessages(): number; /** * Get a pre-allocated scratch buffer for outgoing messages * @returns A Uint8Array buffer that can your game can write the binary payload to before calling sendP2PMessage */ getP2POutgoingMessageBuffer(): Uint8Array; /** * Send a message through P2P to a specific peer using their userId * @param toUserId - Peer userId to send to (undefined = broadcast) * @param appChannel - Optional channel for message routing. All messages still use the same P2P connection under the hood. * @param reliable - Send reliably, meaning guaranteed delivery and ordering, but slower (default: true) * @param payload - The payload to send (byte array) * @param payloadSize - How many bytes from the payload to send. Defaults to payload.length (the entire payload) * @returns true if the message was sent out successfully */ sendP2PMessage(toUserId: GenericId<"users"> | undefined, appChannel: number | undefined, reliable: boolean | undefined, payload: Uint8Array, payloadSize?: number): boolean; /** * Send the same payload to all peers in the lobby * @param appChannel - Optional app-level channel for message routing. All messages still use the same P2P connection under the hood. * @param reliable - Send reliably, meaning guaranteed delivery and ordering, but slower (default: true) * @param payload - The payload to send (byte array) * @param payloadSize - How many bytes from the payload to send. Defaults to payload.length (the entire payload) * @returns true if the message was sent out successfully */ broadcastP2PMessage(appChannel: number | undefined, reliable: boolean | undefined, payload: Uint8Array, payloadSize?: number): boolean; /** * Read one decoded P2P message from a specific channel. * Engine builds (Unity/Godot) should use drainP2PChannelToBuffer for the * hot path — it's batched and returns raw bytes without decode overhead. * @param appChannel - The channel to read from * @returns Decoded P2PMessage, or null if the channel has no pending messages. */ readP2PMessageFromChannel(appChannel: number): P2PMessage | null; /** * Drain all messages from a P2P channel into a buffer * Data will be presented in a tightly packed format: [size:4 bytes][msg:N bytes][size:4 bytes][msg:N bytes]... * JS games can just use readP2PMessageFromChannel to get decoded P2PMessages * Game engines should use drainP2PChannelToBuffer for better performance * @param appChannel - The channel to drain * @param buffer - The buffer to drain the messages into. * If provided, the buffer will be filled until full, any remaining messages will be left in the queue. * If not provided, a new buffer with all messages will be created and returned. * @returns A Uint8Array containing each message in a tightly packed format: [size:4 bytes][msg:N bytes][size:4 bytes][msg:N bytes]... */ drainP2PChannelToBuffer(appChannel: number, buffer?: Uint8Array): Uint8Array; /** * Create a new lobby and join it as the host. * @param visibility - The visibility of the lobby * @param maxPlayers - Optional maximum number of players * @returns A WavedashResponse with the created lobbyId. * Full lobby context is provided via the LobbyJoined event. * @emits LobbyJoined event on success with full lobby context */ createLobby(visibility: LobbyVisibility, maxPlayers?: number): Promise>>; /** * Join an existing lobby. * @param lobbyId - The ID of the lobby to join * @returns A WavedashResponse with success/failure. * Full lobby context is provided via the LobbyJoined event. * @emits LobbyJoined event on success with full lobby context */ joinLobby(lobbyId: GenericId<"lobbies">): Promise>; listAvailableLobbies(friendsOnly?: boolean): Promise>; getLobby(lobbyId: GenericId<"lobbies">): Promise>; getLobbyUsers(lobbyId: GenericId<"lobbies">): LobbyUser[]; getNumLobbyUsers(lobbyId: GenericId<"lobbies">): number; getLobbyHostId(lobbyId: GenericId<"lobbies">): GenericId<"users"> | null; getLobbyData(lobbyId: GenericId<"lobbies">, key: string): LobbyDataValue | null; setLobbyData(lobbyId: GenericId<"lobbies">, key: string, value: LobbyDataUpdate): boolean; deleteLobbyData(lobbyId: GenericId<"lobbies">, key: string): boolean; leaveLobby(lobbyId: GenericId<"lobbies">): Promise>>; sendLobbyMessage(lobbyId: GenericId<"lobbies">, message: string): boolean; inviteUserToLobby(lobbyId: GenericId<"lobbies">, userId: GenericId<"users">): Promise>; getLobbyInviteLink(copyToClipboard?: boolean): Promise>; /** * Returns true if the player owns the given paid content for this game. * Reads the `entitlements` claim from the gameplay JWT — this is a UX hint, not a * security check. The builds server re-verifies the JWT signature and gates * paid asset bytes on every request, so a tampered client return value * doesn't actually unlock anything. Pair with triggerPaywall() to drive * in-game UI. */ isEntitled(contentIdentifier: string): Promise>; isEntitled_EXPERIMENTAL(contentIdentifier: string): Promise>; /** * Returns the full list of paid-content identifiers the player owns for this game. * Reads the `entitlements` claim from the gameplay JWT — this is a UX hint, * not a security check (see {@link isEntitled}). Useful * for access gating multiple items at once without a call per content identifier. */ getEntitlements(): Promise>; getEntitlements_EXPERIMENTAL(): Promise>; /** * Trigger the Wavedash-rendered paywall flow for the given content. Resolves * immediately with data `true` if the player already owns it; otherwise * opens the modal and resolves with whether the user completed the purchase. * After a successful purchase the JWT is refreshed automatically so a * subsequent resource fetch is authenticated with the new purchase, and isEntitled * will return true if the purchase was successful. */ triggerPaywall(contentIdentifier: string): Promise>; triggerPaywall_EXPERIMENTAL(contentIdentifier: string): Promise>; /** * Updates rich user presence so friends can see what the player is doing in game. * Supported keys: * `status` — one-line activity shown as the primary line (e.g. "Traveling in a group") * `details` — secondary context shown beneath the status (e.g. current zone or mode) * * Pass an empty dictionary to clear all presence fields. * @param data Presence fields to update. * @returns true if the presence was updated successfully */ updateUserPresence(data: Record): Promise>; private isGodot; private formatResponse; private ensureInit; private apiCall; private apiCallSync; /** * Fetcher wired into `ConvexClient.setAuth`; other callers use * {@link ensureGameplayJwt}. Same-origin POST to /auth/refresh, authenticated * by the gameplaySession cookie. * * Concurrent callers share one in-flight fetch. A forced refresh instead * serializes behind any in-flight fetch (it may predate the event that * required it, e.g. a purchase) and becomes the current promise; only the * current promise notifies the parent, so a superseded refresh can't * broadcast a stale token */ private getAuthToken; /** * Returns the cached gameplay JWT, awaiting the in-flight fetch if one is * already running (e.g. from Convex's initial setAuth). Use this anywhere * you need to authenticate a request outside of the Convex client. */ ensureGameplayJwt(forceRefresh?: boolean): Promise; /** * Tear down every manager. Called on the parent's `END_SESSION` signal */ private destroy; private setupSessionEndListeners; /** * Respond to the service worker's creds request with the SDK's * current gameplay JWT. The SW asks when it wakes from termination with no * in-memory or IDB credentials (e.g. Safari ITP storage decay) — we're the * fastest live source. JWT only; sessionToken is owned by the SW + cookies. */ private setupSwCredsListener; } declare global { interface Window { Wavedash: WavedashSDK; } } declare function setupWavedashSDK(): WavedashSDK; export { type BackendConnectionPayload, type EngineInstance, type EntitlementsGrantedPayload, type Friend, type FullscreenChangedPayload, type Leaderboard, type LeaderboardDisplayType, type LeaderboardEntries, type LeaderboardEntryMetadata, type LeaderboardSortOrder, type ListUGCItemsArgs, type Lobby, type LobbyDataUpdate, type LobbyDataUpdatedPayload, type LobbyDataValue, type LobbyInvite, type LobbyInvitePayload, type LobbyJoinResponse, type LobbyJoinedPayload, type LobbyKickedPayload, type LobbyKickedReason, type LobbyMessage, type LobbyMessagePayload, type LobbyUser, type LobbyUserChangeType, type LobbyUsersUpdatedPayload, type LobbyVisibility, type MuteChangedPayload, type P2PConfig, type P2PConnection, type P2PConnectionEstablishedPayload, type P2PConnectionFailedPayload, type P2PMessage, type P2PPacketDropReason, type P2PPacketDroppedPayload, type P2PPeer, type P2PPeerDisconnectedPayload, type P2PPeerReconnectedPayload, type P2PPeerReconnectingPayload, type PaginatedUGCItems, type RemoteFileMetadata, type StatsStoredPayload, type UGCItem, type UGCType, type UGCVisibility, type UpdateUGCItemArgs, type UpsertedLeaderboardEntry, type WavedashConfig, type WavedashEvent, type WavedashEventMap, type WavedashResponse, WavedashSDK, setupWavedashSDK };