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, LANGUAGE_CODE, FULFILL_PURCHASE_STATUS, PAID_CONTENT_TYPE, GameLaunchParams, SDKPeer, IFrameEventPayloadMap, IFRAME_MESSAGE_TYPE, SDKUser, SDKConfig } 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; } /** * Applies host volume and mute updates from 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 * audio state and fans it out to every attached frame. */ declare class AudioManager extends WavedashManager { private _volume; private frames; private unsubscribeFrames; private captureTap; private NativeAudioContext; private ignoredMedia; constructor(sdk: WavedashSDK, initialVolume?: number); isMuted(): boolean; getVolume(): number; /** * Build a MediaStream audio tap of everything the game plays, for gameplay * capture (see ScreenCaptureManager). Returns the tap's audio tracks plus a * `dispose()` that tears down the capture-only graph edges. One tap at a * time; creating a new one disposes the previous. * * Everything already funnels through the per-context master GainNodes each * frame's shim owns, so capture is just: master gain → mixer. The mixer is * a dedicated, unshimmed context; every game context (across frames too) * is bridged into it via MediaStream nodes, since Web Audio nodes can't * connect across contexts directly. Because the recording rides the master * gains, captured audio respects the user's volume/mute — matching what * they actually hear. * * The tap stays open for the whole recording: contexts the game creates * and media it starts mid-recording join it as they appear. */ createCaptureTap(): { tracks: MediaStreamTrack[]; dispose: () => void; } | null; isCapturing(): boolean; /** Exempt an SDK-internal media element from all audio shimming. */ ignoreMediaElement(el: HTMLMediaElement): void; isIgnoredMedia(el: HTMLMediaElement): boolean; /** Called by frame shims when a context appears while a tap is open. */ joinCapture(ctx: AudioContext, gain: GainNode): void; private handleVolume; destroy(): void; } /** * Owns the gameplay JWT: fetches it from /auth/refresh, caches it, and feeds * it to the Convex client. * * Convex quirks this works around: a rejected fetcher leaves its socket * paused, and a `null` token drops it into a terminal `noAuth` state where it * never asks again. So the fetcher never rejects, returns the cached JWT on * failure (Convex keeps a good token, or rejects a bad one itself), and we run * our own backoff retry that re-arms Convex via `setAuth` on success. A 401 * means the session is gone for good (only a reload mints a new one), so * retries stop there, the host is told so it can prompt a reload, and the game * keeps running offline. */ declare class AuthManager extends WavedashManager { private jwt; readonly firstAuthenticatedAt: Promise; private resolveFirstAuthenticatedAt; private jwtPromise; private retryTimeout; private retryAttempt; private sessionExpired; private destroyed; constructor(sdk: WavedashSDK); /** * Cached gameplay JWT, awaiting any in-flight fetch. Concurrent callers share * one fetch; a forced refresh serializes behind it (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 */ getToken(forceRefresh?: boolean): Promise; private setupConvexAuth; /** Exponential backoff; the counter resets only on a successful fetch */ private scheduleRetry; private clearRetry; 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; /** * Standard campaign parameters (Urchin/GA). `referral` is the medium for * traffic handed off from another product, as opposed to `cpc` or `email`. * Source and medium are overwritten: this platform is who sent the visit. * Campaign, term, and content describe the game's own link, so they stay. */ private withAttribution; 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"; /** @deprecated Use PURCHASE_COMPLETED, which also covers consumables. */ readonly ENTITLEMENTS_GRANTED: "EntitlementsGranted"; readonly PURCHASE_COMPLETED: "PurchaseCompleted"; }; /** 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 LanguageCode = (typeof LANGUAGE_CODE)[keyof typeof LANGUAGE_CODE]; 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 PurchaseType = (typeof PAID_CONTENT_TYPE)[keyof typeof PAID_CONTENT_TYPE]; type UGCVisibility = (typeof UGC_VISIBILITY)[keyof typeof UGC_VISIBILITY]; /** * What fulfillPurchase did. FULFILLED: marked just now. ALREADY_FULFILLED: an * earlier call from the game or its backend got there first, or it's a * durable (fulfilled when granted); treat it as success. NOT_FOUND: no * such purchase for this player, or it was refunded; don't grant it. */ type FulfillPurchaseStatus = (typeof FULFILL_PURCHASE_STATUS)[keyof typeof FULFILL_PURCHASE_STATUS]; /** fulfillPurchase's result: `status` says what happened. */ type FulfillPurchaseResult = FunctionReturnType; type UserId = GenericId<"users">; type LobbyId = GenericId<"lobbies">; type LobbyMessageId = GenericId<"lobbyMessages">; type LobbyInviteId = GenericId<"notifications">; type LeaderboardId = GenericId<"leaderboards">; type LeaderboardEntryId = GenericId<"leaderboardEntries">; type UGCId = GenericId<"userGeneratedContent">; /** Identifies one purchase: dedupe grants on it and pass it to fulfillPurchase. */ type PurchaseId = GenericId<"userPaidContent">; type WithPublicIds = T extends UserId ? UserId : T extends LobbyId ? LobbyId : T extends LobbyMessageId ? LobbyMessageId : T extends LobbyInviteId ? LobbyInviteId : T extends LeaderboardId ? LeaderboardId : T extends LeaderboardEntryId ? LeaderboardEntryId : T extends UGCId ? UGCId : T extends PurchaseId ? PurchaseId : T extends object ? { [K in keyof T]: WithPublicIds; } : T; type UpdateUGCItemArgs = Omit>, "ugcId" | "createPresignedUploadUrl"> & { filePath?: string; }; type UGCItem = PaginatedUGCItems["page"][0]; type PaginatedUGCItems = WithPublicIds>; type RawListUGCItemsArgs = WithPublicIds>; type ListUGCItemsArgs = Omit & NonNullable; type LobbyUser = WithPublicIds[0]>; type LobbyMessage = WithPublicIds[0]>; type Lobby = WithPublicIds[0]>; type LobbyJoinResponse = WithPublicIds>; type LobbyInvite = WithPublicIds[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 = WithPublicIds[0]>; type Purchase = WithPublicIds[number]>; type Leaderboard = WithPublicIds>; type LeaderboardEntries = WithPublicIds["entries"]>; type UpsertedLeaderboardEntry = WithPublicIds["entry"]> & { userId: UserId; 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: LobbyId; hostId: UserId; 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: LobbyId; 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. commitTs * is the SDK's sync cursor (a bigint, which engine bridges can't JSON-encode). */ type LobbyMessagePayload = Omit; /** 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: UserId; username: string; } /** Payload for P2PConnectionFailed event */ interface P2PConnectionFailedPayload { userId: UserId; username: string; error: string; } /** Payload for P2PPeerDisconnected event */ interface P2PPeerDisconnectedPayload { userId: UserId; username: string; } /** Payload for P2PPeerReconnecting event */ interface P2PPeerReconnectingPayload { userId: UserId; username: string; } /** Payload for P2PPeerReconnected event */ interface P2PPeerReconnectedPayload { userId: UserId; 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 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[]; } /** * Payload for PurchaseCompleted event - one per purchase made while the game is * running (in-game paywall, game page, gift, another tab), plus, at launch, one * per consumable still unfulfilled. Durables arrive `fulfilled: true` * (Wavedash already granted them) and aren't redelivered at launch: read * ownership with isEntitled(). For a consumable, grant it (or confirm your * backend did from the purchase webhook), then call fulfillPurchase(purchaseId); * until then it's redelivered every launch, so dedupe on purchaseId if you * persist grants. `receiptJwt` is the same signed JWT the purchase.completed * webhook sends; verify it against the Wavedash JWKS on your backend. */ type PurchaseCompletedPayload = Purchase; 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.ENTITLEMENTS_GRANTED]: EntitlementsGrantedPayload; [WavedashEvents.PURCHASE_COMPLETED]: PurchaseCompletedPayload; }; interface P2PPeer { userId: UserId; username: string; } interface P2PConnection { lobbyId: LobbyId; peers: Record; } interface P2PMessage { fromUserId: UserId; 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; private rateLimitedUntil; private pendingUploads; 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 getUploadUrl; 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 (Wavedash default avatar if none is set), or null if user not cached */ getUserAvatarUrl(userId: UserId, 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: UserId): string | null; /** * List all friends for the logged in user * @returns Array<{ * avatarUrl?: string; * isOnline: boolean; * userId: UserId; * username: string; * }> */ listFriends(): Promise; } /** * FullscreenManager * * Wavedash owns the fullscreen target on the host page. 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; private escapeHoldTimer; private escapeKeyHeld; 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 installEscapeHold; private handleEscapeKeyDown; private handleEscapeKeyUp; private handleVisibilityChange; private cancelEscapeHold; private installCompatShims; destroy(): void; } 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 */ type PresenceData = Record; 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 cachedPresenceData; private lastSentPresenceData; private pendingPresenceData; private pendingPresenceWaiters; private presenceSender; 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: PresenceData): Promise; isCurrentlyConnected(): boolean; /** * The gameplay session is gone for good: report a terminal disconnect, * since testConnection won't run again to observe it, then tear down. * Call before the Convex client is swapped out. */ endExpiredSession(): void; /** Full teardown — stops intervals and removes all listeners */ destroy(): void; private sendPresence; private tickHeartbeat; private sendHeartbeat; private handleVisibilityChange; private handleUserInput; /** * Polls connected gamepads; any activity counts as user input and * (re)starts the heartbeat. */ private pollGamepads; /** * Tests the connection to the backend */ private testConnection; } /** * LaunchParamManager * * Single owner of the game's launch params. Two sources feed it: * * - `SDKConfig.launchParams`, minted by the host at sign-in and reused for the * whole session. * - The frame's own URL: every `wvdsh_`-prefixed query param (see * `LAUNCH_PARAM_PREFIX`). Standalone (`wavedash dev`) this is the only * source, since the page the player opened is the game itself. * * They are merged with the URL taking priority — the URL reflects what the * player actually navigated to, while the config can be stale by the time a * page is (re)loaded. * * Writes go through `set()`, which updates the in-memory params and, when * running standalone, mirrors the change onto the page URL via * `history.replaceState` so a reload or a copied link lands the player back in * the same state. Hosted in an iframe the URL is left alone: the host tracks * lobby state through the iframe messenger and owns its own URL. */ declare class LaunchParamManager extends WavedashManager { private params; constructor(sdk: WavedashSDK, configParams?: GameLaunchParams); /** Snapshot of the current launch params. */ get(): GameLaunchParams; /** * Set (or clear, with `null`) a launch param and sync it to the frame URL. * `key` is the bare name (e.g. `"lobby"`); the prefix is applied on the URL. */ set(key: string, value: string | null): void; private readFromUrl; private writeToUrl; } /** * Leaderboard service * * Implements each of the leaderboard methods of the Wavedash SDK */ declare class LeaderboardManager extends WavedashManager { private static readonly ENTRIES_CACHE_TTL_MS; private static readonly HANDLE_CACHE_TTL_MS; private leaderboardCache; private totalEntriesUpdatedAt; private leaderboardIdsByName; private pendingGetLeaderboard; private pendingGetOrCreateLeaderboard; private entryReadCaches; constructor(sdk: WavedashSDK); getLeaderboard(name: string): Promise; getOrCreateLeaderboard(name: string, sortOrder: LeaderboardSortOrder, displayType: LeaderboardDisplayType): Promise; getLeaderboardEntryCount(leaderboardId: LeaderboardId): number; getMyLeaderboardEntries(leaderboardId: LeaderboardId): Promise; listLeaderboardEntriesAroundUser(leaderboardId: LeaderboardId, countAhead: number, countBehind: number, friendsOnly?: boolean): Promise; listLeaderboardEntries(leaderboardId: LeaderboardId, offset: number, limit: number, friendsOnly?: boolean): Promise; uploadLeaderboardScore(leaderboardId: LeaderboardId, score: number, keepBest: boolean, ugcId?: UGCId, metadata?: LeaderboardEntryMetadata): Promise; /** Reads nothing player-specific, so every player shares one cached result */ private findLeaderboard; private cacheLeaderboard; /** * A copy of the cached leaderboard for a name, or null if its totalEntries * is older than HANDLE_CACHE_TTL_MS so the caller refetches it */ private getCachedLeaderboardByName; /** * Run an entries query through its leaderboard's short-lived read cache, * keyed by the full args. totalEntries is recorded once per network fetch, * and skipped if an upload invalidated the cache while the fetch was in * flight (the upload's own count is newer). */ private readEntries; 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 lobbyMessagesCursor; private maybeBeingDeletedLobbyIds; private resetMaybeBeingDeletedLobbyIdTimeouts; private static readonly METADATA_UPDATE_THROTTLE_MS; private cachedLobbies; private static readonly LOBBY_LIST_CACHE_TTL_MS; private lobbyListCache; 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: LobbyId): Promise; getLobbyUsers(lobbyId: LobbyId): LobbyUser[]; getHostId(lobbyId: LobbyId): UserId | null; getLobbyData(lobbyId: LobbyId, key: string): LobbyDataValue | null; deleteLobbyData(lobbyId: LobbyId, key: string): boolean; setLobbyData(lobbyId: LobbyId, key: string, value: LobbyDataUpdate): boolean; getLobbyMaxPlayers(lobbyId: LobbyId): number; getNumLobbyUsers(lobbyId: LobbyId): number; leaveLobby(lobbyId: LobbyId): Promise; listAvailableLobbies(friendsOnly?: boolean): Promise; getLobby(lobbyId: LobbyId): Promise; sendLobbyMessage(lobbyId: LobbyId, message: string): boolean; inviteUserToLobby(lobbyId: LobbyId, userId: UserId): Promise; getLobbyInviteLink(copyToClipboard?: boolean): Promise; /** * Update the current lobby id and mirror it onto the `lobby` launch param so * the frame URL (and any link copied from it) tracks lobby membership. */ private setLobbyId; /** * 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; /** * A lobby mutation failing with "not a member" means the server already * removed us. Treat it as a kick so we stop querying and mutating the lobby, * in case the subscription errors haven't arrived (or were missed). * Ignored when the mutation targeted a lobby other than the current one. */ private handleLobbyMutationError; /** * Clean up lobby state without emitting events * Used internally by handleLobbyJoin() and handleLobbyKicked() * @param nextLobbyId - The lobby being joined in place of the current one, if any */ 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 metadataSender; private setMetadata; /** * Process user updates and emit individual user events * @param newUsers - The updated list of lobby users */ private processUserUpdates; private onLobbySubscriptionError; /** * (Re)subscribe to lobby messages from the current cursor: the latest 10 * until we've emitted one, then only messages committed after the last. */ private subscribeToLobbyMessages; private processMessageUpdates; private processInviteUpdates; /** * Update P2P connections when lobby membership changes * @param newUsers - The updated list of lobby users */ private updateP2PConnections; } /** * 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 iceRestartTimers; private readonly MAX_ICE_RESTART_ATTEMPTS; private readonly ICE_RESTART_BASE_TIMEOUT_MS; private readonly ICE_RESTART_MAX_TIMEOUT_MS; private readonly ICE_DISCONNECTED_GRACE_MS; private currentOfferIds; private answeringOffers; private answeredOffers; private applyingAnswers; private candidateBatchPeers; private queuedIceCandidates; private iceCandidateSendsInFlight; private reconnectingPeers; private establishedPeers; private packetDropTrackers; private readonly PACKET_DROP_WINDOW_MS; private readonly turnCredentials; private unsubscribeFromSignalingMessages; private signalingCursor; 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; isMeshEnabled(): boolean; initializeP2PForCurrentLobby(lobbyId: LobbyId, members: SDKPeer[]): Promise; /** * Internal method that performs the actual P2P initialization. * Called by initializeP2PForCurrentLobby with proper locking. */ private doInitializeP2P; private updateP2PConnection; private establishWebRTCConnections; /** * Start a new signaling session (on lobby join): only messages committed * after `joinCommitTs` are delivered. */ setSignalingCursor(joinCommitTs: bigint): void; private subscribeToSignalingMessages; /** * (Re)subscribe from the current cursor, so each query only reads and sends * messages newer than what we've already handled. */ private subscribeToSignalingMessagesAfterCursor; private stopSignalingMessageSubscription; private processSignalingMessages; private handleSignalingMessage; /** * Add a peer's ICE candidates, buffering them until its remote description * is set. Each is added on its own, so one bad candidate doesn't cost the * rest; re-adding one the pc already has is a harmless no-op. */ private addRemoteIceCandidates; /** * The candidates inside an SDP (a=candidate lines), as the peer would have * trickled them. Each carries its section's ICE ufrag, so a browser rejects * it (rather than applying it to other credentials) if that SDP is no longer * the pc's remote description by the time it's added. */ private candidatesInSdp; /** * 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; private updateCandidateBatching; private queueIceCandidate; /** * Send everything queued for a peer connection as one message, then repeat * for whatever was queued while that send was in flight, until none is left * or the connection has been replaced. */ private sendQueuedIceCandidates; /** * Attempt to restart ICE when connection fails. * Only the peer with the lower userId initiates the restart to avoid conflicts. */ private attemptIceRestart; /** * Make the next ICE restart attempt (or give up) if ICE to this peer still * isn't connected after `timeout`. Replaces any retry already scheduled. */ private scheduleIceRetry; private clearIceRestartTimer; private markPeerReconnecting; /** * Close and forget a peer's connection and everything tied to it, but keep * them as a member: a later member update (or their offer) connects afresh. * Channel maps are cleared before closing, so the closing channels' * onclose handlers see they're no longer current. */ private dropPeerConnection; private setupDataChannelHandlers; sendP2PMessage(toUserId: UserId | undefined, appChannel: number | undefined, reliable: boolean | undefined, payload: Uint8Array, payloadSize?: number): boolean; private sendSignalingMessage; disconnectP2P(): void; isPeerReady(userId: UserId): boolean; isBroadcastReady(reliable: boolean): boolean; getPeerStatuses(): Record; 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; private restoreGamepads; private seenPurchaseIds; private purchaseUpdates; private entitlementChecks; private unsubscribePurchases; private unsubscribeEntitlements; private destroyed; constructor(sdk: WavedashSDK); /** * One stream for launch and live delivery, so no purchase falls between * them, and it works with or without a host (`wavedash dev` included). Like * StoreKit's transaction listener: the first result delivers every * unfulfilled consumable (bought while the game was closed, or never * fulfilled) plus durables bought this session; after that, each new * id is a purchase from any source (paywall, game page, gift, another tab). * Events queue until the game is ready for them. */ private handlePurchasesUpdate; /** * Make sure the gameplay JWT entitles every new durable first, so * isEntitled() is already true by the time the game receives the events. * New durables also fire the deprecated EntitlementsGranted, one * event per update so a bundle's contents arrive together. */ private notifyPurchasesCompleted; /** Force-refresh the gameplay JWT only if its `ents` lacks any of these identifiers. */ private ensureJwtEntitles; private refreshJwtUnless; watchSharedEntitlements(): void; isEntitled(contentIdentifier: string): Promise; getEntitlements(): Promise; getUnfulfilledPurchases(): Promise; fulfillPurchase(purchaseId: PurchaseId): Promise; triggerPaywall(contentIdentifier: string): Promise; isPaywallOpen(): boolean; destroy(): void; } declare class ScreenCaptureManager extends WavedashManager { private active; private stopping; private pendingStart; private hotkey; private hotkeyWindows; private unsubscribeFrames; constructor(sdk: WavedashSDK, recordingHotkey?: string); private handleRecordingChanged; private handleHotkeyChanged; private handleKeyDown; private start; private stop; private finish; private postFailure; private postToParent; private createFixedSizeCapture; private pickCanvas; private removeKeyListener; destroy(): void; } declare class StatsManager extends WavedashManager { private stats; private unlockedAchievements; private dirtyStats; private dirtyAchievements; private knownStatIds; private knownAchievementIds; private loaded; private subscriptions; constructor(sdk: WavedashSDK); destroy(): void; private isReady; private subscribe; requestStats(): Promise; private persistSender; storeStats(): boolean; 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: UGCId, updates?: UpdateUGCItemArgs): Promise; deleteUGCItem(ugcId: UGCId): Promise; downloadUGCItem(ugcId: UGCId, 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; } type FrameWindow = Window & typeof globalThis; interface FrameListener { attach: (win: FrameWindow) => void; detach: (win: FrameWindow) => void; } declare class SameOriginFrames { private listeners; private frames; private iframeBindings; private iframeLoadHandlers; constructor(); subscribe(listener: FrameListener): () => void; private notify; private attachFrame; private detachFrame; private iframesIn; private bindIframe; private unbindIframe; private attachIframe; private detachIframe; destroy(): void; } /** * 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 destroyed; private warnedEntitlementsGranted; 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 ENTITLEMENTS_GRANTED: "EntitlementsGranted"; readonly PURCHASE_COMPLETED: "PurchaseCompleted"; }; LanguageCode: { readonly ARABIC: "ar"; readonly BULGARIAN: "bg"; readonly CATALAN: "ca"; readonly CHINESE_SIMPLIFIED: "zh-CN"; readonly CHINESE_TRADITIONAL: "zh-TW"; readonly CROATIAN: "hr"; readonly CZECH: "cs"; readonly DANISH: "da"; readonly DUTCH: "nl"; readonly ENGLISH: "en"; readonly ESPERANTO: "eo"; readonly FINNISH: "fi"; readonly FRENCH: "fr"; readonly GALICIAN: "gl"; readonly GERMAN: "de"; readonly GREEK: "el"; readonly HUNGARIAN: "hu"; readonly INDONESIAN: "id"; readonly ITALIAN: "it"; readonly JAPANESE: "ja"; readonly KOREAN: "ko"; readonly LATVIAN: "lv"; readonly LITHUANIAN: "lt"; readonly MALAY: "ms"; readonly NORWEGIAN: "no"; readonly POLISH: "pl"; readonly PORTUGUESE: "pt"; readonly PORTUGUESE_BRAZIL: "pt-BR"; readonly ROMANIAN: "ro"; readonly RUSSIAN: "ru"; readonly SPANISH: "es"; readonly SPANISH_LATIN_AMERICA: "es-419"; readonly SWEDISH: "sv"; readonly THAI: "th"; readonly TURKISH: "tr"; readonly UKRAINIAN: "uk"; readonly VIETNAMESE: "vi"; }; 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"; }; PurchaseType: { readonly DURABLE: "DURABLE"; readonly CONSUMABLE: "CONSUMABLE"; }; FulfillPurchaseStatus: { readonly FULFILLED: "FULFILLED"; readonly ALREADY_FULFILLED: "ALREADY_FULFILLED"; readonly NOT_FOUND: "NOT_FOUND"; }; 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"]; pageViewId: SDKConfig["pageViewId"]; fileSystemManager: FileSystemManager; authManager: AuthManager; convexClient: ConvexClient; engineCallbackReceiver: string; engineInstance: EngineInstance | null; iframeMessenger: IFrameMessenger; swMessenger: SwMessenger; p2pManager: P2PManager; fullscreenManager: FullscreenManager; sameOriginFrames: SameOriginFrames; audioManager: AudioManager; screenCaptureManager: ScreenCaptureManager; paidContentManager: PaidContentManager; externalLinkManager: ExternalLinkManager; launchParamManager: LaunchParamManager; private managers; private setupWarningTimeout; ugcHost: string; uploadsHost: string; staticHost: 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; /** * Whether the game is currently presented in fullscreen. Mirrored from the * Wavedash host page, which owns the real fullscreen target. */ 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; 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: UserId): string | null; getUserId(): UserId; getUserLanguage(): LanguageCode; /** * 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 - Size in pixels: a Wavedash.AvatarSize preset (SMALL=64, MEDIUM=128, LARGE=256) or a custom value. Defaults to MEDIUM. * @returns CDN URL with size transformation (Wavedash default avatar if none is set), or null if user not cached */ getUserAvatarUrl(userId: UserId, size?: number): string | null; getLeaderboard(name: string): Promise>; getOrCreateLeaderboard(name: string, sortOrder: LeaderboardSortOrder, displayType: LeaderboardDisplayType): Promise>; getLeaderboardEntryCount(leaderboardId: LeaderboardId): number; getMyLeaderboardEntries(leaderboardId: LeaderboardId): Promise>; listLeaderboardEntriesAroundUser(leaderboardId: LeaderboardId, countAhead: number, countBehind: number, friendsOnly?: boolean): Promise>; listLeaderboardEntries(leaderboardId: LeaderboardId, offset: number, limit: number, friendsOnly?: boolean): Promise>; uploadLeaderboardScore(leaderboardId: LeaderboardId, score: number, keepBest: boolean, ugcId?: UGCId, 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: UGCId, 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: UGCId): Promise>; downloadUGCItem(ugcId: UGCId, 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 * @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 (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 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 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: UserId | 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: LobbyId): Promise>; listAvailableLobbies(friendsOnly?: boolean): Promise>; getLobby(lobbyId: LobbyId): Promise>; getLobbyUsers(lobbyId: LobbyId): LobbyUser[]; getNumLobbyUsers(lobbyId: LobbyId): number; getLobbyHostId(lobbyId: LobbyId): UserId | null; getLobbyData(lobbyId: LobbyId, key: string): LobbyDataValue | null; setLobbyData(lobbyId: LobbyId, key: string, value: LobbyDataUpdate): boolean; deleteLobbyData(lobbyId: LobbyId, key: string): boolean; leaveLobby(lobbyId: LobbyId): Promise>; sendLobbyMessage(lobbyId: LobbyId, message: string): boolean; inviteUserToLobby(lobbyId: LobbyId, userId: UserId): 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. For a consumable, grant it * from the PurchaseCompleted event rather than from this result. */ triggerPaywall(contentIdentifier: string): Promise>; triggerPaywall_EXPERIMENTAL(contentIdentifier: string): Promise>; /** * Consumable purchases the game hasn't fulfilled, oldest first. These already * arrive as PurchaseCompleted events at launch (register the listener before * init(), or pass deferEvents), but each purchase fires once per session: use * this to retry one whose fulfillPurchase call failed. */ getUnfulfilledPurchases(): Promise>; /** * Mark a consumable purchase fulfilled once the grant is saved, so it stops * being redelivered. A game's backend can do the same with * POST /api/purchases/{purchaseId}/fulfill and the webhook's JWT; both are * idempotent, so calling either or both is safe. Resolves with `status`: * FULFILLED, ALREADY_FULFILLED (also success), or NOT_FOUND (unknown or * refunded: don't grant it). */ fulfillPurchase(purchaseId: PurchaseId): 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>; isMuted(): boolean; requestMute(_muted: boolean): Promise; toggleMute(): Promise; toggleOverlay(): void; private _isGodot; private _formatResponse; private _ensureInit; private _apiCall; private _apiCallSync; 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 { WavedashSDK, setupWavedashSDK }; export type { BackendConnectionPayload, EngineInstance, EntitlementsGrantedPayload, Friend, FulfillPurchaseResult, FulfillPurchaseStatus, FullscreenChangedPayload, LanguageCode, Leaderboard, LeaderboardDisplayType, LeaderboardEntries, LeaderboardEntryId, LeaderboardEntryMetadata, LeaderboardId, LeaderboardSortOrder, ListUGCItemsArgs, Lobby, LobbyDataUpdate, LobbyDataUpdatedPayload, LobbyDataValue, LobbyId, LobbyInvite, LobbyInviteId, LobbyInvitePayload, LobbyJoinResponse, LobbyJoinedPayload, LobbyKickedPayload, LobbyKickedReason, LobbyMessage, LobbyMessageId, LobbyMessagePayload, LobbyUser, LobbyUserChangeType, LobbyUsersUpdatedPayload, LobbyVisibility, P2PConfig, P2PConnection, P2PConnectionEstablishedPayload, P2PConnectionFailedPayload, P2PMessage, P2PPacketDropReason, P2PPacketDroppedPayload, P2PPeer, P2PPeerDisconnectedPayload, P2PPeerReconnectedPayload, P2PPeerReconnectingPayload, PaginatedUGCItems, Purchase, PurchaseCompletedPayload, PurchaseId, PurchaseType, RemoteFileMetadata, StatsStoredPayload, UGCId, UGCItem, UGCType, UGCVisibility, UpdateUGCItemArgs, UpsertedLeaderboardEntry, UserId, WavedashConfig, WavedashEvent, WavedashEventMap, WavedashResponse };