Skip to content
Docs pages

Developers · Reference

SDK reference

Every API of SDK v1 — TypeScript signatures, behavior on the portal and in standalone mode, limits, events and error codes.

On this page

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

APIReturnsBefore init()
WSG.version, WSG.environmentstring, EnvironmentWorks
WSG.init(options)Promise<InitContext>—
WSG.isAvailable(feature)booleanReturns false
WSG.player, getToken(), login()Player, Promise<string | null>, Promise<Player>Methods are rejected
loadingStart(), loadingProgress(), loadingFinished()voidIgnored
gameplayStart(), gameplayStop()voidIgnored
happyTime(intensity?)voidIgnored
track(name, props?)voidIgnored
ads.interstitial(), ads.rewarded(), ads.isBlocked()Promise<AdResult>, booleanRejected (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, voidWorks

"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:

HTML
<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

TypeScript
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

TypeScript
readonly environment: 'portal' | 'standalone' | 'disabled';

The environment the SDK is running in. Until init() completes it is always 'standalone'.

ValueWhenBehavior
portalThe game is in an iframe, the URL has wsg=1 and host=<http(s) origin>, and the portal answers the handshake within 3 secondsEvery request goes through postMessage to the portal page; the SDK only accepts messages whose source is window.parent and whose origin equals host
standaloneThe game is opened directly, the query is missing, or the portal doesn't answer within 3 secondsRuns locally: a fake player, leaderboard and storage in localStorage, fake ads lasting 1 second
disabledThe 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)

TypeScript
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>;
}
  • gameId is required: a non-empty string of at most 64 characters with no whitespace; otherwise the Promise rejects with invalid_argument. Use your game's slug. The portal compares gameId with the game it opened and logs a warning on mismatch, but lets it run.
  • version is sent with the handshake; the portal currently doesn't use it.
  • debug: true prints helpful development warnings to the console: calls ignored because init hasn't finished, the fallback to standalone when the portal doesn't answer, invalid track names, 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 to standalone (with debug on you'll see a warning).
  • ctx.player is a snapshot of the player at init time; to read the latest values use WSG.player.
  • ctx.locale: on the portal this is the portal UI language (vi or en); in standalone mode it comes from the lang query, then navigator.language, and finally en. It is always a 2–3 letter lowercase code.
  • ctx.features: see isAvailable(). ctx.entryParams: see getEntryParams().
JavaScript
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)

TypeScript
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 features block of the game.json of the running version and the operations team has it switched on for your game in the admin page. share is not in game.json, so it follows the admin switch only; auth is always false because the portal has no sign-in yet.
  • Standalone: every feature is true except auth.
  • 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.

JavaScript
if (WSG.isAvailable('ads.rewarded')) showReviveButton();

Player

WSG.player

TypeScript
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: id is the player's ID (a UUID) on the portal, name is the display name (players can change it on the portal), and isGuest is true for guest accounts. Version 1 only has guest accounts.
  • Standalone: id looks like local-<12 characters> and is kept in localStorage (key wsg:local-id); name is Guest.
  • The fields are updated in place on the authchange event, so read WSG.player.name when you need it instead of caching it once.

WSG.player.getToken()

TypeScript
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()

TypeScript
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()

TypeScript
loadingStart(): void;
loadingProgress(percent: number): void; // 0..100
loadingFinished(): void;
  • percent is 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 a load_timeout event.
  • The portal records load_start, load_end, and load_progress whenever the percentage crosses 25, 50, 75 and 100 (not every report).
  • loadingStart() is optional. loadingFinished() is required.

gameplayStart(), gameplayStop()

TypeScript
gameplayStart(): void;
gameplayStop(): void;
  • Call gameplayStart() when the player actually takes control; call gameplayStop() 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 before init() finishes is ignored, and a score submitted afterwards will be rejected with no_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, call gameplayStart() 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?)

TypeScript
happyTime(intensity?: number): void; // 0..1, default 1

Signals 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?)

TypeScript
track(name: string, props?: Record<string, unknown>): void;

Records an analytics event specific to your game, for example level_complete or continue_used.

  • name must match ^[a-z][a-z0-9_]{1,63}$: 2–64 characters of lowercase letters, digits and underscores, starting with a letter. Names starting with wsg_ 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, a track('gameplay_start') is treated as the start of gameplay).
  • props is a JSON object of at most 2048 UTF-8 bytes after JSON.stringify. The SDK round-trips it through JSON before sending: functions and undefined are dropped and a Date becomes 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_start and gameplay_stop have their own limit of 30 per minute, so heavy track use can't drop gameplay_start. Still keep it to a handful of events per round.
JavaScript
WSG.track('level_complete', { level: 3, stars: 2, timeMs: 41250 });

Ads

WSG.ads.interstitial(opts?)

TypeScript
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?)

TypeScript
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()

TypeScript
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

TypeScript
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:

  1. If gameplay is running, the SDK calls gameplayStop().
  2. The SDK emits pause and audio(false).
  3. The portal shows the ad (or answers immediately with a reason).
  4. The SDK emits audio(true) and resume, then the Promise resolves.
reasonMeaningWhat your game should do
(none)The ad was shownInterstitial: carry on. Rewarded: check rewarded
cooldownLess than 60 seconds since the previous interstitial (interstitials only)Skip it and carry on
not_availableAnother ad is already showingDon't stack calls; skip it
dismissedThe player closed the rewarded ad early (shown: true, rewarded: false)No reward
unfilledNo ad was availableSkip it; for rewarded ads you may hide the button for a while
adblockAn ad blocker is active; isBlocked() becomes trueHide ad-related buttons
disabledThe SDK is in disabled modeSkip it
errorAn environment problem, e.g. the portal didn't answer within 120 secondsSkip 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

TypeScript
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?)

TypeScript
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
}
  • score must be a finite number, otherwise the Promise rejects with invalid_argument. The server additionally requires an integer from 0 to 2^53; fractions or negative numbers are rejected with reason: 'invalid_score'. Round before submitting.
  • meta is 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, a reason that is one of invalid_session, invalid_score, rate_limited, no_gameplay, over_max, too_fast, rate_too_high, blocked; best and rank reflect the current state (0 and null if the player has no score yet); improved: false.
  • For games with scoreOrder: "asc" (lower is better), best is the lowest score.
  • A valid submission updates all three periods (daily, weekly, all-time); the rank in the result is the all-time rank.
  • With debug on you'll get a warning when submitting outside the gameplay window; the SDK still sends it and the server returns no_gameplay.
  • Standalone: always accepted: true, with no anti-cheat checks; scores live in localStorage (key wsg:<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.

JavaScript
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?)

TypeScript
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?)

TypeScript
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?)

TypeScript
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?)

TypeScript
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

TypeScript
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 Date becomes a string); undefined, a BigInt or a circular object is rejected with invalid_argument.
  • Setting a key to null deletes it in every mode: afterwards get returns null and getAll no longer lists the key (even before the write is sent). A null nested 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 with rate_limited, so save at milestones (end of a round, a settings change), not every frame. The first get/getAll loads all data once; later reads come from the session's cache.
  • Standalone: stored in localStorage under the key wsg:<gameId>:storage:<key>, also limited to 100 KB (counting key length plus the JSON string). If localStorage isn't usable (private mode, blocked), data only lives in the tab's memory.
  • Disabled: get returns null, getAll returns {}, set and remove resolve but save nothing.
JavaScript
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)

TypeScript
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 a url, the portal links to your game's page on the portal: https://leonogames.com/games/<slug>?ref=share (plus &score=<score> when you pass score); whoever opens that link finds ref and score in getEntryParams(). ok is false if the player cancels or the browser supports neither method.
  • Standalone: the game itself calls navigator.share or copies to the clipboard; the content is text followed by Score: <score>.
  • Disabled: { ok: false }.
  • In every mode, text may be at most 280 characters and url must be an absolute http or https URL; otherwise the Promise rejects with invalid_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.
JavaScript
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()

TypeScript
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()

TypeScript
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=42 gives { 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 see wsg_test (it travels in the iframe URL).
  • Standalone: index.html?level=3 gives { 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)

TypeScript
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.

EventArgumentsWhen
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)
audioenabledfalse before an ad, true after it
visibilityvisibleThe page visibility changes (document.visibilitychange)
authchangeplayerThe player info changed
  • pause/resume and audio never repeat a state: two pause in a row are emitted only once.
  • On the portal, when the tab is hidden your game receives visibility(false) and then pause (except while an ad is showing, since the game is already paused); when the tab comes back it receives visibility(true) and then resume. The portal also covers the game with a "Paused" overlay.
  • The portal only sends resume once 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 receives audio(true), resume and then pause right after; the real resume comes when the player is back.
  • In standalone mode the SDK emits visibility and pause/resume itself on document.visibilitychange and around fake ads, so you can test as you would on the portal.
JavaScript
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 listener

Errors

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.

codeWhen
not_initializedAn async API was called before init() finished; on the portal you also get it once the play session has ended
timeoutThe portal didn't answer in time: 10 seconds for most requests (init has 3 seconds but falls back to standalone instead of rejecting)
quota_exceededStorage went over 100 KB
invalid_argumentBad 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_limitedA portal API limit was hit, for example more than 30 storage writes per minute
unavailableThe message couldn't reach the portal, the channel is closed, or the portal couldn't reach its API (network down, access denied)
internalAnything 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:

JavaScript
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

APIStandaloneDisabled
playerlocal-<id>, name GuestThe player sent by the portal (if any), otherwise defaults
getToken()nullnull
isAvailable()true except authfalse
Lifecycle, happyTime, trackNothing 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.submitAlways accepted, stored in localStorageaccepted: false, reason: 'disabled'
top, around, meLocal board[], [], null
showDoes nothingDoes nothing
storage.*localStorage (100 KB), set(k, null) deletes the key as on the portalNothing saved, get returns null
sharenavigator.share or clipboard (same text/url limits as the portal){ ok: false }
Eventspause/resume/visibility from the tab and fake adsEvents 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):

TypeScriptwsg.d.ts
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;
}