The SDK is a single dependency-free JavaScript file (about 8 KB gzipped) that defines the global window.WSG. Every async function returns a Promise; outside the portal every function still returns valid results instead of throwing because of the environment. This page covers version 1.x, served at /sdk/v1/wsg-sdk.js.
API at a glance
| API | Returns | Before init() |
|---|---|---|
WSG.version, WSG.environment | string, Environment | Works |
WSG.init(options) | Promise<InitContext> | — |
WSG.isAvailable(feature) | boolean | Returns false |
WSG.player, getToken(), login() | Player, Promise<string | null>, Promise<Player> | Methods are rejected |
loadingStart(), loadingProgress(), loadingFinished() | void | Ignored |
gameplayStart(), gameplayStop() | void | Ignored |
happyTime(intensity?) | void | Ignored |
track(name, props?) | void | Ignored |
ads.interstitial(), ads.rewarded(), ads.isBlocked() | Promise<AdResult>, boolean | Rejected (isBlocked() returns false) |
leaderboard.submit(), top(), around(), me(), show() | Promise<…> | Rejected |
storage.get(), set(), remove(), getAll() | Promise<…> | Rejected |
share(payload) | Promise<{ ok: boolean }> | Rejected |
getLocale(), getEntryParams() | string, Record<string, string> | Works |
on(event, cb), off(event, cb) | unsubscribe function, void | Works |
"Rejected" means the Promise rejects with the code not_initialized. "Ignored" means the call has no effect (turn on debug to see a console warning). Calls made while init() is still running also count as before init(), so always await WSG.init() first.
Loading the SDK and TypeScript types
Games outside the repository load the SDK with a script tag, using the root path on the games origin:
<script src="/sdk/v1/wsg-sdk.js"></script>Games inside the Leono Games repository may import the ESM build of the internal @wsg/sdk package (import { WSG } from '@wsg/sdk'), but the Phaser template still prefers the script tag so it always runs the latest SDK served by the portal. The package is not published publicly; if you use TypeScript with the script tag, copy the declaration file from TypeScript types.
Properties
WSG.version
readonly version: string;The full semver version of the running SDK, for example "1.0.0". The major version is part of the path /sdk/v1/; within a major version the SDK stays backward compatible.
WSG.environment
readonly environment: 'portal' | 'standalone' | 'disabled';The environment the SDK is running in. Until init() completes it is always 'standalone'.
| Value | When | Behavior |
|---|---|---|
portal | The game is in an iframe, the URL has wsg=1 and host=<http(s) origin>, and the portal answers the handshake within 3 seconds | Every request goes through postMessage to the portal page; the SDK only accepts messages whose source is window.parent and whose origin equals host |
standalone | The game is opened directly, the query is missing, or the portal doesn't answer within 3 seconds | Runs locally: a fake player, leaderboard and storage in localStorage, fake ads lasting 1 second |
disabled | The portal answers the handshake with { disabled: true } (for example, the play session has ended) | Every API returns defaults right away and sends nothing; pause/resume events from the portal still arrive |
Initialization
WSG.init(options)
init(options: InitOptions): Promise<InitContext>;
interface InitOptions {
gameId: string; // slug from game.json
version?: string; // your game version, e.g. "1.0.0"
debug?: boolean; // print [WSG] logs to the console
}
interface InitContext {
environment: 'portal' | 'standalone' | 'disabled';
player: Player;
locale: string; // 'vi', 'en', ...
features: Record<Feature, boolean>;
entryParams: Record<string, string>;
}gameIdis required: a non-empty string of at most 64 characters with no whitespace; otherwise the Promise rejects withinvalid_argument. Use your game'sslug. The portal comparesgameIdwith the game it opened and logs a warning on mismatch, but lets it run.versionis sent with the handshake; the portal currently doesn't use it.debug: trueprints helpful development warnings to the console: calls ignored becauseinithasn't finished, the fallback to standalone when the portal doesn't answer, invalidtracknames, scores submitted outside gameplay…- Calling
init()again returns the same Promise and result; options passed to later calls are ignored. If an earlier call was rejected because of bad options, you can call it again. init()doesn't reject because of the environment. Inside a portal iframe with no answer after 3 seconds, the SDK switches tostandalone(withdebugon you'll see a warning).ctx.playeris a snapshot of the player at init time; to read the latest values useWSG.player.ctx.locale: on the portal this is the portal UI language (vioren); in standalone mode it comes from thelangquery, thennavigator.language, and finallyen. It is always a 2–3 letter lowercase code.ctx.features: seeisAvailable().ctx.entryParams: seegetEntryParams().
const ctx = await WSG.init({ gameId: 'tap-rush', version: '1.0.0', debug: true });
if (ctx.environment === 'portal') {
console.log('Running on the portal, player', ctx.player.name, 'language', ctx.locale);
}WSG.isAvailable(feature)
isAvailable(feature: Feature): boolean;
type Feature = 'ads.interstitial' | 'ads.rewarded' | 'leaderboard' | 'storage' | 'share' | 'auth';Tells you whether a feature is enabled for your game in the current environment. Before init() it always returns false.
- Portal: a feature is on when your game declares it in the
featuresblock of thegame.jsonof the running version and the operations team has it switched on for your game in the admin page.shareis not ingame.json, so it follows the admin switch only;authis alwaysfalsebecause the portal has no sign-in yet. - Standalone: every feature is
trueexceptauth. - Disabled: every feature is
false.
When a feature is off, the portal blocks the matching calls: ads.interstitial() and ads.rewarded() resolve to { shown: false, reason: 'disabled' } (rewarded also has rewarded: false), leaderboard.* and storage.* calls are rejected with the unavailable error, and share() resolves to { ok: false }. The server enforces it too: submitting a score while the leaderboard is off returns reason: 'disabled'. The operations team can flip these switches at any time, so read the flags after init() to decide your UI, for example hiding a "Watch an ad to revive" button.
if (WSG.isAvailable('ads.rewarded')) showReviveButton();Player
WSG.player
interface Player {
id: string;
name: string;
avatarUrl: string | null;
isGuest: boolean;
}
player: Player & {
getToken(): Promise<string | null>;
login(): Promise<Player>;
};- Before
init():{ id: '', name: 'Guest', avatarUrl: null, isGuest: true }. - Portal:
idis the player's ID (a UUID) on the portal,nameis the display name (players can change it on the portal), andisGuestistruefor guest accounts. Version 1 only has guest accounts. - Standalone:
idlooks likelocal-<12 characters>and is kept inlocalStorage(keywsg:local-id);nameisGuest. - The fields are updated in place on the
authchangeevent, so readWSG.player.namewhen you need it instead of caching it once.
WSG.player.getToken()
getToken(): Promise<string | null>;- Portal: returns the RS256 JWT of the current play session, which your own game server can use to authenticate the player. The whole session shares one token; it expires 1 hour after the session started and the portal doesn't issue a new one within the same session. Claims and verification are covered in Scores and leaderboards.
- Standalone and disabled:
null.
WSG.player.login()
login(): Promise<Player>;Portal v1 has no sign-in dialog yet, so login() returns the current player. If the player info differs from WSG.player, the SDK updates WSG.player and emits authchange. In standalone mode it returns the local player.
Lifecycle
loadingStart(), loadingProgress(), loadingFinished()
loadingStart(): void;
loadingProgress(percent: number): void; // 0..100
loadingFinished(): void;percentis rounded and clamped to 0..100; non-numeric values are ignored.- The portal shows a loading overlay with the percentage you report and removes it only when it receives
loadingFinished(). The overlay covers the game and blocks input. If nothing arrives within 30 seconds, the portal removes the overlay itself and records aload_timeoutevent. - The portal records
load_start,load_end, andload_progresswhenever the percentage crosses 25, 50, 75 and 100 (not every report). loadingStart()is optional.loadingFinished()is required.
gameplayStart(), gameplayStop()
gameplayStart(): void;
gameplayStop(): void;- Call
gameplayStart()when the player actually takes control; callgameplayStop()on game over, when returning to the menu, or when the player pauses. - The SDK ignores calls that don't change the state:
gameplayStart()while running,gameplayStop()while stopped. - A
gameplayStart()made beforeinit()finishes is ignored, and a score submitted afterwards will be rejected withno_gameplay. - On the portal, the first
gameplayStart()of a session counts as one play of your game (the "most played" board) and awards XP to the player; gameplay time is converted to XP too. The portal sends these two events to the server immediately rather than batching them. - When you show an ad while gameplay is running, the SDK calls
gameplayStop()for you. If the round continues after the ad, callgameplayStart()again. - Scores are only accepted while gameplay is running or within 10 seconds after
gameplayStop().
Note
To check scores, the server adds up play time across every gameplayStop()/gameplayStart() of the session, so pausing or reviving after an ad in the middle of a run doesn't get scores rejected. See Scores and leaderboards.
happyTime(intensity?)
happyTime(intensity?: number): void; // 0..1, default 1Signals a happy moment: a new record, a cleared level, a big combo. intensity is clamped to 0..1. The portal records a happy event and keeps this signal for future effects or ads. Each call is one event and counts toward the session's event limit (see track).
Custom events
WSG.track(name, props?)
track(name: string, props?: Record<string, unknown>): void;Records an analytics event specific to your game, for example level_complete or continue_used.
namemust match^[a-z][a-z0-9_]{1,63}$: 2–64 characters of lowercase letters, digits and underscores, starting with a letter. Names starting withwsg_are reserved for the SDK. Invalid names are ignored.- Don't reuse the portal's standard event names:
load_start,load_progress,load_end,gameplay_start,gameplay_stop,happy,ad_request,ad_result,score_submit,score_rejected,share,session_end,load_timeout. The server handles these as system events (for example, atrack('gameplay_start')is treated as the start of gameplay). propsis a JSON object of at most 2048 UTF-8 bytes afterJSON.stringify. The SDK round-trips it through JSON before sending: functions andundefinedare dropped and aDatebecomes a string. If it can't be serialized or is too large, the event is dropped.- The SDK allows at most 60 events per 60-second window (starting at the window's first event); extra events are dropped and counted, then reported in the next batch as a
wsg_track_dropped { count }event. - The SDK batches events, sending after 1 second or once 20 are queued, and flushes immediately when the page is being closed (
pagehide). The portal batches again and sends to the server every 5 seconds or every 20 events. - The server accepts at most 60 events per minute per session, counting your game's events (
track,happy) together with the lifecycle events recorded by the portal (load_*,ad_*,score_submit,share); events over the limit are dropped.gameplay_startandgameplay_stophave their own limit of 30 per minute, so heavytrackuse can't dropgameplay_start. Still keep it to a handful of events per round.
WSG.track('level_complete', { level: 3, stars: 2, timeMs: 41250 });Ads
WSG.ads.interstitial(opts?)
interstitial(opts?: { placement?: string }): Promise<AdResult>;A full-screen ad between rounds. placement is an optional label (at most 64 characters) for statistics, for example 'between_rounds', 'menu', 'pause'.
WSG.ads.rewarded(opts?)
rewarded(opts?: { placement?: string }): Promise<AdResult>;An ad the player chooses to watch in exchange for a reward. The result always has a rewarded field; grant the reward only when rewarded === true, never based on shown.
WSG.ads.isBlocked()
isBlocked(): boolean;true once an ad result with reason: 'adblock' has occurred in the session; use it to hide ad-related buttons.
Results and reasons
interface AdResult {
shown: boolean;
rewarded?: boolean; // rewarded ads only
reason?: 'cooldown' | 'unfilled' | 'adblock' | 'disabled' | 'dismissed' | 'not_available' | 'error';
}What happens when you request an ad:
- If gameplay is running, the SDK calls
gameplayStop(). - The SDK emits
pauseandaudio(false). - The portal shows the ad (or answers immediately with a
reason). - The SDK emits
audio(true)andresume, then the Promise resolves.
reason | Meaning | What your game should do |
|---|---|---|
| (none) | The ad was shown | Interstitial: carry on. Rewarded: check rewarded |
cooldown | Less than 60 seconds since the previous interstitial (interstitials only) | Skip it and carry on |
not_available | Another ad is already showing | Don't stack calls; skip it |
dismissed | The player closed the rewarded ad early (shown: true, rewarded: false) | No reward |
unfilled | No ad was available | Skip it; for rewarded ads you may hide the button for a while |
adblock | An ad blocker is active; isBlocked() becomes true | Hide ad-related buttons |
disabled | The SDK is in disabled mode | Skip it |
error | An environment problem, e.g. the portal didn't answer within 120 seconds | Skip it and carry on |
- The Promise only rejects when called before
init()(not_initialized). Every other problem resolves with{ shown: false, reason: … }. - Portal: at least 60 seconds must pass between two interstitials (counted from the last one shown on the page); rewarded ads have no such limit. The portal currently uses simulated ads: an interstitial shows for 3 seconds before its Close button appears, a rewarded ad lasts 5 seconds (closing early with Esc gives
dismissed). - Standalone: waits 1 second, then returns
{ shown: true }or{ shown: true, rewarded: true }, with no cooldown. - Timing advice and a revive example are on the Ads page.
Leaderboard
type Period = 'daily' | 'weekly' | 'all';
interface LeaderboardEntry {
rank: number;
playerId: string;
name: string;
avatarUrl: string | null;
score: number;
isMe: boolean;
}WSG.leaderboard.submit(score, meta?)
submit(score: number, meta?: Record<string, unknown>): Promise<SubmitResult>;
interface SubmitResult {
accepted: boolean;
best: number; // the player's all-time best
rank: number | null; // all-time rank, starting at 1
improved: boolean; // this submission beat the all-time best
reason?: string; // only when rejected
}scoremust be a finite number, otherwise the Promise rejects withinvalid_argument. The server additionally requires an integer from 0 to 2^53; fractions or negative numbers are rejected withreason: 'invalid_score'. Round before submitting.metais an optional JSON object stored alongside accepted scores (not shown publicly). Keep it small.- A rejection does not reject the Promise: the result has
accepted: false, areasonthat is one ofinvalid_session,invalid_score,rate_limited,no_gameplay,over_max,too_fast,rate_too_high,blocked;bestandrankreflect the current state (0 andnullif the player has no score yet);improved: false. - For games with
scoreOrder: "asc"(lower is better),bestis the lowest score. - A valid submission updates all three periods (daily, weekly, all-time); the
rankin the result is the all-time rank. - With
debugon you'll get a warning when submitting outside the gameplay window; the SDK still sends it and the server returnsno_gameplay. - Standalone: always
accepted: true, with no anti-cheat checks; scores live inlocalStorage(keywsg:<gameId>:lb, one row per local player, top 100 rows kept). - Disabled:
{ accepted: false, best: 0, rank: null, improved: false, reason: 'disabled' }.
The checks and how to pick limits: Scores and leaderboards.
WSG.gameplayStop();
const result = await WSG.leaderboard.submit(Math.floor(score), { level: 7 });
if (result.accepted && result.improved) showNewRecord(result.best, result.rank);WSG.leaderboard.top(opts?)
top(opts?: { period?: Period; limit?: number }): Promise<LeaderboardEntry[]>;The top rows. period defaults to 'all' (anything other than the three periods is rejected with invalid_argument); limit is rounded and clamped to 1..100, default 10. On the portal, daily is the current day and weekly the current ISO week (starting Monday), both in Vietnam time (Asia/Ho_Chi_Minh); isMe marks the current player. In standalone mode there is a single local board and period has no effect.
WSG.leaderboard.around(opts?)
around(opts?: { period?: Period; radius?: number }): Promise<LeaderboardEntry[]>;The rows around the player: from their rank minus radius to their rank plus radius. radius is rounded and clamped to 0..10 (0 means only the player's own row); a non-numeric value falls back to the default of 5. Returns an empty array when the player has no score in that period.
WSG.leaderboard.me(period?)
me(period?: Period): Promise<LeaderboardEntry | null>;The current player's row for the period (default 'all'), or null if they have no score.
WSG.leaderboard.show(period?)
show(period?: Period): Promise<void>;Asks the portal to open your game's leaderboard (a dialog over the page) on the chosen period. The Promise resolves as soon as the portal receives the request, without waiting for the dialog to close. While the dialog is open the portal pauses your game: it receives pause when the dialog appears and resume when the player closes it (unless the tab is hidden), so don't rely on this Promise to know when to continue. In standalone mode it does nothing.
Storage
get<T = unknown>(key: string): Promise<T | null>;
set(key: string, value: unknown): Promise<void>;
set(entries: Record<string, unknown>): Promise<void>;
remove(key: string): Promise<void>;
getAll(): Promise<Record<string, unknown>>;A key-value store per player and per game, for personal bests, progress and settings.
WSG.storage.get(key)
The value of key, or null if there is none. Values you just set are readable immediately, even before they are sent.
WSG.storage.set(key, value) and set(entries)
Writes one key, or several keys at once with the object form. Setting a key to null deletes it, like remove() (on the portal and in standalone mode alike). set calls made within 500 ms are merged into one request; the Promise resolves when that request completes.
WSG.storage.remove(key)
Deletes one key.
WSG.storage.getAll()
Every key of your game for this player, including values still waiting to be sent.
Limits and behavior
- Keys are non-empty strings of at most 128 characters. Values must be JSON-serializable: the SDK round-trips them through JSON before sending (functions are dropped, a
Datebecomes a string);undefined, aBigIntor a circular object is rejected withinvalid_argument. - Setting a key to
nulldeletes it in every mode: afterwardsgetreturnsnullandgetAllno longer lists the key (even before the write is sent). Anullnested inside an object ({ a: null }) is ordinary data. - Portal: data is stored on the server and tied to the player's guest account (a cookie); clearing cookies or switching devices means a new player with an empty store. The JSON of all keys of one game may total at most 100 KB (102,400 UTF-8 bytes); beyond that the Promise rejects with
quota_exceeded. The server allows at most 30 writes per minute per player and rejects further writes withrate_limited, so save at milestones (end of a round, a settings change), not every frame. The firstget/getAllloads all data once; later reads come from the session's cache. - Standalone: stored in
localStorageunder the keywsg:<gameId>:storage:<key>, also limited to 100 KB (counting key length plus the JSON string). IflocalStorageisn't usable (private mode, blocked), data only lives in the tab's memory. - Disabled:
getreturnsnull,getAllreturns{},setandremoveresolve but save nothing.
await WSG.storage.set({ best: 1200, level: 4, settings: { music: false } });
const settings = (await WSG.storage.get('settings')) ?? { music: true };
await WSG.storage.remove('tutorialStep');Sharing
WSG.share(payload)
share(payload: { text?: string; score?: number; url?: string }): Promise<{ ok: boolean }>;- Portal: the portal page opens the operating system's share sheet (
navigator.share) or copies to the clipboard. Without aurl, the portal links to your game's page on the portal:https://leonogames.com/games/<slug>?ref=share(plus&score=<score>when you passscore); whoever opens that link findsrefandscoreingetEntryParams().okisfalseif the player cancels or the browser supports neither method. - Standalone: the game itself calls
navigator.shareor copies to the clipboard; the content istextfollowed byScore: <score>. - Disabled:
{ ok: false }. - In every mode,
textmay be at most 280 characters andurlmust be an absolutehttporhttpsURL; otherwise the Promise rejects withinvalid_argument(the SDK checks before sending, and the portal checks again). - Call it right inside a tap or click handler, because browsers only allow sharing right after a user action.
shareButton.addEventListener('click', async () => {
const { ok } = await WSG.share({ text: `I scored ${score} points!`, score });
if (!ok) showToast('Could not share');
});Locale and parameters
WSG.getLocale()
getLocale(): string;Works before init(). Returns a 2–3 letter lowercase language code. On the portal (after init()) it is the portal UI language, currently vi or en. Before init() and in standalone mode: the lang query, then navigator.language, and finally en.
WSG.getEntryParams()
getEntryParams(): Record<string, string>;Works before init(). Returns a copy of the game URL's query parameters, minus wsg, host, lang and v which belong to the portal, merged with the parameters the portal sends with the handshake (available after init()).
- Portal: the forwarded parameters are the query of your game's page on the portal. For example the default share link
https://leonogames.com/games/<slug>?ref=share&score=42gives{ ref: 'share', score: '42' }, so your game can invite the player to "Beat 42 points!". The portal drops its own parameters (wsg,host,lang,v,wsg_test,login_error) and only keeps names that start with a letter and contain letters, digits,_,.or-(at most 64 characters), values of at most 512 characters, and at most 20 parameters. In test mode you'll also seewsg_test(it travels in the iframe URL). - Standalone:
index.html?level=3gives{ level: '3' }, which is handy for jumping straight to a level while testing. - Anyone can craft a link with any query: treat the values as untrusted input, validate them before use, and never let them unlock anything that affects scores.
Events
WSG.on(event, callback) and WSG.off(event, callback)
on<K extends keyof WSGEventMap>(event: K, cb: (...args: WSGEventMap[K]) => void): () => void;
off(event: string, cb: (...args: never[]) => void): void;
interface WSGEventMap {
pause: [];
resume: [];
audio: [enabled: boolean];
authchange: [player: Player];
visibility: [visible: boolean];
}Works before init(). on() returns a function that removes the listener. Errors thrown inside a callback are caught by the SDK and printed to the console; they don't break the SDK.
| Event | Arguments | When |
|---|---|---|
pause | — | The tab is hidden; before an ad appears; the portal opens the leaderboard (leaderboard.show()) |
resume | — | The tab is visible again; after an ad closes; the player closes the leaderboard (only when no other reason to stay paused remains) |
audio | enabled | false before an ad, true after it |
visibility | visible | The page visibility changes (document.visibilitychange) |
authchange | player | The player info changed |
pause/resumeandaudionever repeat a state: twopausein a row are emitted only once.- On the portal, when the tab is hidden your game receives
visibility(false)and thenpause(except while an ad is showing, since the game is already paused); when the tab comes back it receivesvisibility(true)and thenresume. The portal also covers the game with a "Paused" overlay. - The portal only sends
resumeonce every reason to pause is gone: closing the leaderboard while the tab is still hidden doesn't restart the game. If an ad ends while the tab is hidden or the leaderboard is open, your game receivesaudio(true),resumeand thenpauseright after; the realresumecomes when the player is back. - In standalone mode the SDK emits
visibilityandpause/resumeitself ondocument.visibilitychangeand around fake ads, so you can test as you would on the portal.
const offPause = WSG.on('pause', () => loop.stop());
WSG.on('resume', () => loop.start());
WSG.on('audio', (enabled) => (sound.muted = !enabled));
WSG.on('authchange', (player) => (nameLabel.text = player.name));
// ...
offPause(); // remove one listenerErrors
Error codes
Every rejected Promise receives a WSGError: a real Error (with a stack) that also has code and message; JSON.stringify(err) gives { code, message }. The script-tag build doesn't expose the WSGError class, so check err.code.
code | When |
|---|---|
not_initialized | An async API was called before init() finished; on the portal you also get it once the play session has ended |
timeout | The portal didn't answer in time: 10 seconds for most requests (init has 3 seconds but falls back to standalone instead of rejecting) |
quota_exceeded | Storage went over 100 KB |
invalid_argument | Bad arguments: gameId, period, a storage key or value, a non-finite score, a non-object meta, share text longer than 280 characters, a share url that isn't an absolute http(s) URL; or the portal rejected the data |
rate_limited | A portal API limit was hit, for example more than 30 storage writes per minute |
unavailable | The message couldn't reach the portal, the channel is closed, or the portal couldn't reach its API (network down, access denied) |
internal | Anything else, including unknown codes returned by the portal |
Ads don't reject on problems (they return a reason), and rejected scores don't reject either (they return accepted: false). Wrap storage calls, and any call whose failure you care about, in try/catch:
try {
await WSG.storage.set('save', bigSaveObject);
} catch (err) {
if (err.code === 'quota_exceeded') trimOldSaves();
else console.warn('Could not save', err.code, err.message);
}Standalone and disabled modes
| API | Standalone | Disabled |
|---|---|---|
player | local-<id>, name Guest | The player sent by the portal (if any), otherwise defaults |
getToken() | null | null |
isAvailable() | true except auth | false |
Lifecycle, happyTime, track | Nothing is sent (track only logs with debug) | Nothing is sent |
ads.* | Waits 1 second, shown: true (rewarded adds rewarded: true) | { shown: false, reason: 'disabled' } |
leaderboard.submit | Always accepted, stored in localStorage | accepted: false, reason: 'disabled' |
top, around, me | Local board | [], [], null |
show | Does nothing | Does nothing |
storage.* | localStorage (100 KB), set(k, null) deletes the key as on the portal | Nothing saved, get returns null |
share | navigator.share or clipboard (same text/url limits as the portal) | { ok: false } |
| Events | pause/resume/visibility from the tab and fake ads | Events from the portal still arrive |
TypeScript types
If your game is written in TypeScript and loads the SDK with a script tag, add this declaration file to your project (the types match SDK v1):
export {};
declare global {
type WSGEnvironment = 'portal' | 'standalone' | 'disabled';
type WSGPeriod = 'daily' | 'weekly' | 'all';
type WSGFeature = 'ads.interstitial' | 'ads.rewarded' | 'leaderboard' | 'storage' | 'share' | 'auth';
type WSGAdReason =
'cooldown' | 'unfilled' | 'adblock' | 'disabled' | 'dismissed' | 'not_available' | 'error';
type WSGErrorCode =
| 'not_initialized'
| 'timeout'
| 'quota_exceeded'
| 'invalid_argument'
| 'rate_limited'
| 'unavailable'
| 'internal';
interface WSGPlayerInfo {
id: string;
name: string;
avatarUrl: string | null;
isGuest: boolean;
}
interface WSGInitOptions {
gameId: string;
version?: string;
debug?: boolean;
}
interface WSGInitContext {
environment: WSGEnvironment;
player: WSGPlayerInfo;
locale: string;
features: Record<WSGFeature, boolean>;
entryParams: Record<string, string>;
}
interface WSGAdResult {
shown: boolean;
rewarded?: boolean;
reason?: WSGAdReason;
}
interface WSGLeaderboardEntry {
rank: number;
playerId: string;
name: string;
avatarUrl: string | null;
score: number;
isMe: boolean;
}
interface WSGSubmitResult {
accepted: boolean;
best: number;
rank: number | null;
improved: boolean;
reason?: string;
}
interface WSGError extends Error {
code: WSGErrorCode;
}
interface WSGEventMap {
pause: [];
resume: [];
audio: [enabled: boolean];
authchange: [player: WSGPlayerInfo];
visibility: [visible: boolean];
}
interface WSGStatic {
readonly version: string;
readonly environment: WSGEnvironment;
init(options: WSGInitOptions): Promise<WSGInitContext>;
isAvailable(feature: WSGFeature): boolean;
player: WSGPlayerInfo & {
getToken(): Promise<string | null>;
login(): Promise<WSGPlayerInfo>;
};
loadingStart(): void;
loadingProgress(percent: number): void;
loadingFinished(): void;
gameplayStart(): void;
gameplayStop(): void;
happyTime(intensity?: number): void;
track(name: string, props?: Record<string, unknown>): void;
ads: {
interstitial(opts?: { placement?: string }): Promise<WSGAdResult>;
rewarded(opts?: { placement?: string }): Promise<WSGAdResult>;
isBlocked(): boolean;
};
leaderboard: {
submit(score: number, meta?: Record<string, unknown>): Promise<WSGSubmitResult>;
top(opts?: { period?: WSGPeriod; limit?: number }): Promise<WSGLeaderboardEntry[]>;
around(opts?: { period?: WSGPeriod; radius?: number }): Promise<WSGLeaderboardEntry[]>;
me(period?: WSGPeriod): Promise<WSGLeaderboardEntry | null>;
show(period?: WSGPeriod): Promise<void>;
};
storage: {
get<T = unknown>(key: string): Promise<T | null>;
set(key: string, value: unknown): Promise<void>;
set(entries: Record<string, unknown>): Promise<void>;
remove(key: string): Promise<void>;
getAll(): Promise<Record<string, unknown>>;
};
share(payload: { text?: string; score?: number; url?: string }): Promise<{ ok: boolean }>;
getLocale(): string;
getEntryParams(): Record<string, string>;
on<K extends keyof WSGEventMap>(event: K, cb: (...args: WSGEventMap[K]) => void): () => void;
off(event: string, cb: (...args: never[]) => void): void;
}
var WSG: WSGStatic;
}