@usions/sdk 2.24.1 → 3.0.0-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +45 -277
  2. package/dist/browser.global.js +1972 -0
  3. package/dist/browser.global.js.map +1 -0
  4. package/dist/index.d.ts +337 -0
  5. package/dist/index.js +1955 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/testing.d.ts +23 -0
  8. package/dist/testing.js +63 -0
  9. package/dist/testing.js.map +1 -0
  10. package/dist/types-G075L8Nl.d.ts +83 -0
  11. package/package.json +27 -43
  12. package/src/browser.js +0 -6665
  13. package/src/index.js +0 -10
  14. package/src/modules/back-button.js +0 -26
  15. package/src/modules/backend-channel.js +0 -109
  16. package/src/modules/bot.js +0 -52
  17. package/src/modules/chat.js +0 -35
  18. package/src/modules/cloud.js +0 -67
  19. package/src/modules/core.js +0 -424
  20. package/src/modules/errors.js +0 -120
  21. package/src/modules/file-storage.js +0 -46
  22. package/src/modules/game-core.js +0 -278
  23. package/src/modules/game-direct.js +0 -267
  24. package/src/modules/game-methods.js +0 -753
  25. package/src/modules/game-netcode.js +0 -349
  26. package/src/modules/game-proxy.js +0 -182
  27. package/src/modules/game-reliability.js +0 -278
  28. package/src/modules/game-resilience.js +0 -245
  29. package/src/modules/game-socket.js +0 -212
  30. package/src/modules/index.js +0 -78
  31. package/src/modules/leaderboard.js +0 -46
  32. package/src/modules/lobby.js +0 -103
  33. package/src/modules/matchmaking.js +0 -140
  34. package/src/modules/misc.js +0 -152
  35. package/src/modules/netcode/binary.js +0 -113
  36. package/src/modules/netcode/delta.js +0 -236
  37. package/src/modules/netcode/index.js +0 -43
  38. package/src/modules/netcode/interest-grid.js +0 -227
  39. package/src/modules/netcode/interpolation.js +0 -235
  40. package/src/modules/netcode/lagcomp.js +0 -104
  41. package/src/modules/netcode/lockstep.js +0 -103
  42. package/src/modules/netcode/mesh-network.js +0 -103
  43. package/src/modules/netcode/mesh.js +0 -188
  44. package/src/modules/netcode/netsim.js +0 -77
  45. package/src/modules/netcode/ping.js +0 -69
  46. package/src/modules/netcode/prediction.js +0 -113
  47. package/src/modules/netcode/sender.js +0 -102
  48. package/src/modules/netcode/webtransport.js +0 -195
  49. package/src/modules/notify.js +0 -70
  50. package/src/modules/permissions.js +0 -157
  51. package/src/modules/results.js +0 -34
  52. package/src/modules/session.js +0 -62
  53. package/src/modules/storage.js +0 -64
  54. package/src/modules/ui.js +0 -111
  55. package/src/modules/user.js +0 -61
  56. package/src/modules/wallet.js +0 -253
  57. package/types/browser.d.ts +0 -5
  58. package/types/index.d.ts +0 -1306
package/types/index.d.ts DELETED
@@ -1,1306 +0,0 @@
1
- /**
2
- * Usion Mini App SDK v2.1 — TypeScript Declarations
3
- */
4
-
5
- // ─── Config & Init ───────────────────────────────────────────────
6
-
7
- export interface UsionConfig {
8
- userId?: string;
9
- userName?: string;
10
- userAvatar?: string;
11
- authToken?: string;
12
- sessionId?: string;
13
- sessionData?: Record<string, any>;
14
- balance?: number;
15
- results?: SavedResult[];
16
- theme?: 'light' | 'dark';
17
- language?: string;
18
- socketUrl?: string;
19
- /** HTTP/3 WebTransport endpoint for direct-mode games (lowest latency). */
20
- webTransportUrl?: string;
21
- roomId?: string;
22
- playerIds?: string[];
23
- serviceId?: string;
24
- serviceName?: string;
25
- apiUrl?: string;
26
- connectionMode?: 'platform' | 'direct';
27
- /**
28
- * Internal path the host opened this app at — set when the user taps a
29
- * notification carrying a `path`. Read via `Usion.getLaunchParams().path`.
30
- */
31
- launchPath?: string;
32
- /** Referral code the app was opened with, if any. */
33
- ref?: string;
34
- /**
35
- * How the app was launched: `'single'` (from Explore / the Game hub, solo)
36
- * or `'multiplayer'` (from a game invite in a chat). Read via
37
- * `Usion.getLaunchParams().mode`. (SDK ≥ 2.18)
38
- */
39
- mode?: 'single' | 'multiplayer';
40
- }
41
-
42
- // ─── Payment ─────────────────────────────────────────────────────
43
-
44
- export interface PaymentResponse {
45
- success: boolean;
46
- reason?: string;
47
- newBalance?: number;
48
- receiptToken?: string;
49
- transactionId?: string;
50
- }
51
-
52
- export interface PaymentOptions {
53
- /**
54
- * Optional idempotency key. When set, the host + backend dedupe on it so any
55
- * retry of the SAME intent (network error, reload, double-tap) reuses the
56
- * SAME charge instead of debiting again, and returns the same receiptToken.
57
- * Omit for the legacy one-shot behavior.
58
- */
59
- idempotencyKey?: string;
60
- [key: string]: any;
61
- }
62
-
63
- // ─── User ────────────────────────────────────────────────────────
64
-
65
- export interface UserProfile {
66
- id: string;
67
- name: string;
68
- avatar: string;
69
- }
70
-
71
- export interface UserModule {
72
- getId(): string | null;
73
- getName(): string | null;
74
- getAvatar(): string | null;
75
- getToken(): string | null;
76
- getProfile(): Promise<UserProfile>;
77
- }
78
-
79
- // ─── Storage ─────────────────────────────────────────────────────
80
-
81
- export interface StorageModule {
82
- get(key: string): Promise<any>;
83
- set(key: string, value: any): Promise<void>;
84
- remove(key: string): Promise<void>;
85
- clear(): Promise<void>;
86
- keys(): Promise<string[]>;
87
- }
88
-
89
- // ─── File Storage ───────────────────────────────────────────────
90
-
91
- export interface FileStorageModule {
92
- set(key: string, base64Data: string, mimeType: string): Promise<void>;
93
- get(key: string): Promise<{ base64Data: string; mimeType: string } | null>;
94
- remove(key: string): Promise<void>;
95
- }
96
-
97
- // ─── Wallet ──────────────────────────────────────────────────────
98
-
99
- export interface WalletModule {
100
- /** Cached after the first call; pass `{ fresh: true }` to re-query the host. */
101
- getBalance(opts?: { fresh?: boolean }): Promise<number>;
102
- hasCredits(amount: number): Promise<boolean>;
103
- requestPayment(amount: number, reason: string, data?: PaymentOptions): Promise<PaymentResponse>;
104
- onBalanceChange(callback: (balance: number) => void): UnsubscribeFn;
105
- }
106
-
107
- // ─── Session ─────────────────────────────────────────────────────
108
-
109
- export interface SessionModule {
110
- getId(): string | null;
111
- getData(key?: string): any;
112
- setData(keyOrData: string | Record<string, any>, value?: any): void;
113
- clear(): void;
114
- }
115
-
116
- // ─── Chat ────────────────────────────────────────────────────────
117
-
118
- export interface ChatCreationResult {
119
- chatId: string;
120
- peerName: string;
121
- peerUsername: string;
122
- peerAvatar: string;
123
- }
124
-
125
- export interface ChatModule {
126
- sendMessage(recipientId: string, message: string): Promise<{ success: boolean; reason?: string }>;
127
- createPersonalChat(peerUserId: string): Promise<ChatCreationResult>;
128
- }
129
-
130
- // ─── Share ────────────────────────────────────────────────────────
131
-
132
- export interface ShareMediaItem {
133
- type: 'image' | 'video' | 'audio';
134
- url: string;
135
- thumbnailUrl?: string;
136
- width?: number;
137
- height?: number;
138
- duration?: number;
139
- }
140
-
141
- export interface ShareData {
142
- text?: string;
143
- audioUrl?: string;
144
- imageUrl?: string;
145
- videoUrl?: string;
146
- thumbnailUrl?: string;
147
- width?: number;
148
- height?: number;
149
- duration?: number;
150
- media?: ShareMediaItem[];
151
- }
152
-
153
- // ─── Game ────────────────────────────────────────────────────────
154
-
155
- export interface GameJoinResult {
156
- room_id: string;
157
- player_id: string;
158
- sequence?: number;
159
- error?: string;
160
- message?: string;
161
- }
162
-
163
- export interface ActionResult {
164
- success: boolean;
165
- sequence?: number;
166
- error?: string;
167
- message?: string;
168
- }
169
-
170
- export interface DirectConnectionConfig {
171
- roomId?: string;
172
- serviceId?: string;
173
- apiUrl?: string;
174
- token?: string;
175
- protocolVersion?: string;
176
- /**
177
- * Liveness watchdog tuning, or `false` to disable probing/dead detection.
178
- * Defaults: probe after 4 s of silence, declare dead after 12 s. (SDK ≥ 2.24)
179
- */
180
- liveness?: DirectLivenessOptions | false;
181
- /**
182
- * Hold realtime 'input' frames (latest only) while the socket send buffer
183
- * exceeds this many bytes; drained as the buffer clears. Control frames
184
- * (join/action/ping/…) always send. 0 or `false` disables. Default 8192.
185
- * (SDK ≥ 2.24)
186
- */
187
- backpressureBytes?: number | false;
188
- }
189
-
190
- /** Liveness watchdog options for connectDirect. (SDK ≥ 2.24) */
191
- export interface DirectLivenessOptions {
192
- /** Silence before an RTT probe ping, ms (default 4000, clamped ≥ 1000). */
193
- probeAfterMs?: number;
194
- /** Silence before the socket is declared dead and re-dialed, ms (default 12000, clamped ≥ probeAfterMs + 2000). */
195
- deadAfterMs?: number;
196
- }
197
-
198
- /** Coarse connection quality. 'dead' = liveness-declared dead or disconnected. */
199
- export type NetworkQuality = 'good' | 'fair' | 'poor' | 'dead';
200
-
201
- /** Snapshot returned by game.getNetworkStats(). (SDK ≥ 2.24) */
202
- export interface NetworkStats {
203
- transport: 'direct' | 'relay';
204
- connectionState: GameConnectionState;
205
- quality: NetworkQuality;
206
- /** Smoothed round-trip time in ms (EWMA); null until something measured it. */
207
- rtt: number | null;
208
- /** Smoothed RTT variation in ms; null until something measured it. */
209
- jitter: number | null;
210
- /** ms since the last inbound direct-socket message; null in relay mode. */
211
- lastInboundAgeMs: number | null;
212
- /** Direct-socket send-buffer bytes; null when there is no direct socket. */
213
- bufferedAmount: number | null;
214
- }
215
-
216
- /** Payload of game.onNetworkQuality — fired on quality transitions only. */
217
- export interface NetworkQualityChange {
218
- quality: NetworkQuality;
219
- prev: NetworkQuality;
220
- stats: NetworkStats;
221
- }
222
-
223
- export interface PlayerJoinedData {
224
- room_id: string;
225
- player_id: string;
226
- player_ids: string[];
227
- status?: string;
228
- game_state?: Record<string, any>;
229
- }
230
-
231
- export interface PlayerLeftData {
232
- room_id: string;
233
- player_id: string;
234
- /** Authoritative roster (mirrors PlayerJoinedData) — reconcile membership from either event. */
235
- player_ids: string[];
236
- reason?: string;
237
- }
238
-
239
- export interface StateUpdateData {
240
- room_id: string;
241
- game_state?: Record<string, any>;
242
- current_turn?: string;
243
- status?: string;
244
- sequence?: number;
245
- [key: string]: any;
246
- }
247
-
248
- export interface GameActionData {
249
- room_id: string;
250
- player_id: string;
251
- action_type: string;
252
- action_data: Record<string, any>;
253
- sequence?: number;
254
- /** Present when the sender passed { nextTurn } — the server-remembered turn. */
255
- current_turn?: string;
256
- }
257
-
258
- /** Returned by event registrations; call to remove the handler. */
259
- export type UnsubscribeFn = () => void;
260
-
261
- export interface GameActionOptions {
262
- /**
263
- * Player ID whose turn comes after this action. The server stores it (no
264
- * game logic — a relay that remembers) and returns it as current_turn in
265
- * join acks and game:sync, so turn state survives reconnects.
266
- */
267
- nextTurn?: string;
268
- /**
269
- * Hold this action while disconnected and send it (in order) once the
270
- * connection recovers, instead of rejecting with NOT_CONNECTED — "your
271
- * move is saved and sends when you're back". For turn-based games only;
272
- * never queue realtime-style inputs. Queue cap 20 (then QUEUE_FULL).
273
- */
274
- queueOffline?: boolean;
275
- }
276
-
277
- export interface PlayerConnectionData {
278
- room_id: string;
279
- player_id: string;
280
- /**
281
- * connected — player (re)joined the room.
282
- * reconnecting — player's connection dropped; grace window running (~15s).
283
- * gone — player did not return before the grace/heartbeat expiry.
284
- */
285
- state: 'connected' | 'reconnecting' | 'gone';
286
- }
287
-
288
- export interface GameFinishedData {
289
- room_id: string;
290
- winner_ids: string[];
291
- reason?: string;
292
- forfeiter?: string;
293
- }
294
-
295
- export interface SyncData {
296
- room_id: string;
297
- actions: GameActionData[];
298
- game_state: Record<string, any>;
299
- current_turn?: string | null;
300
- sequence: number;
301
- }
302
-
303
- export interface RematchData {
304
- room_id: string;
305
- player_id: string;
306
- }
307
-
308
- /** Options for game.invite(). */
309
- export interface GameInviteOptions {
310
- /** Cap the room at this many players (otherwise the game's max_players). */
311
- maxPlayers?: number;
312
- /** Max ms to wait for the user to finish in the picker (default 120000). */
313
- timeout?: number;
314
- }
315
-
316
- /** Result of game.invite(). */
317
- export interface GameInviteResult {
318
- /** True if the user sent at least one invite. */
319
- success: boolean;
320
- /** The room invitees will join (you are host); null if nothing was sent. */
321
- roomId: string | null;
322
- /** User/group ids the invite was sent to. */
323
- invited: string[];
324
- }
325
-
326
- /** Options for game.joinWorld(). */
327
- export interface JoinWorldOptions {
328
- /** Service to place into (defaults to the current service). */
329
- serviceId?: string;
330
- }
331
-
332
- /** Result of game.joinWorld(). */
333
- export interface WorldJoinResult {
334
- /** The world room this player was placed into (also set on game.roomId). */
335
- roomId: string;
336
- /** Players in the world at placement time (this player included). */
337
- playerIds: string[];
338
- }
339
-
340
- /** Unified connection-state machine, identical across all transports. */
341
- export type GameConnectionState = 'connected' | 'disconnected' | 'rejoining' | 'reconnected';
342
-
343
- /** Payload of game.onReconnected — fires once after a reconnect's resync. */
344
- export interface ReconnectedInfo {
345
- /** The server checkpoint from the resync (may be empty). */
346
- state: Record<string, any> | null;
347
- /** Highest action sequence after the resync. */
348
- lastSequence: number;
349
- /** True when recovery came through a game:sync payload. */
350
- viaSync: boolean;
351
- }
352
-
353
- /** An action as seen by a syncedState reducer. */
354
- export interface SyncedStateAction {
355
- playerId: string;
356
- type: string;
357
- data: any;
358
- /** Authoritative sequence; undefined only for direct-mode local applies. */
359
- sequence: number | undefined;
360
- }
361
-
362
- /** Options for game.syncedState(). */
363
- export interface SyncedStateOptions<S = Record<string, any>> {
364
- /** Pure reducer applied to every action; default shallow-merges action.data. */
365
- reduce?: (state: S, action: SyncedStateAction) => S;
366
- /** Authority checkpoint cadence in actions (1 = every action; 0 disables). */
367
- checkpointEvery?: number;
368
- /** Who checkpoints: 'host' (player_ids[0], default) or 'all' participants. */
369
- authority?: 'host' | 'all';
370
- /** Default action type used by commit(data) (default 'update'). */
371
- type?: string;
372
- }
373
-
374
- /** Reconnect-safe authoritative shared state (see game.syncedState). */
375
- export interface SyncedState<S = Record<string, any>> {
376
- /** Current state value. */
377
- get(): S;
378
- /** Commit with the default action type. Applied exactly once via the echo. */
379
- commit(data: Record<string, any>): Promise<ActionResult>;
380
- /** Commit a named action; opts forwarded to game.action (nextTurn, …). */
381
- commit(type: string, data?: Record<string, any>, opts?: GameActionOptions): Promise<ActionResult>;
382
- /** Subscribe to changes: cb(state, reason). Returns an unsubscribe fn. */
383
- onChange(callback: (state: S, reason: 'action' | 'recover') => void): UnsubscribeFn;
384
- /** Whether this client is the checkpointing authority. */
385
- isAuthority(): boolean;
386
- /** Force a server checkpoint now (no-op result in direct mode). */
387
- checkpoint(): Promise<{ success: boolean; error?: string; code?: UsionErrorCode }>;
388
- /** Sequence of the last action applied into this state. */
389
- getSequence(): number;
390
- /** Detach all listeners; the instance stops receiving updates. */
391
- destroy(): void;
392
- }
393
-
394
- export interface GameModule {
395
- // Connection
396
- connect(socketUrl?: string, token?: string): Promise<void>;
397
- connectDirect(config?: DirectConnectionConfig): Promise<void>;
398
- disconnect(): void;
399
- isConnected(): boolean;
400
- /**
401
- * Whether the app was launched multiplayer (from a chat game invite) vs
402
- * single-player (from Explore / the Game hub). Wrapper over
403
- * `Usion.getLaunchParams().mode === 'multiplayer'`. (SDK ≥ 2.18)
404
- */
405
- isMultiplayer(): boolean;
406
-
407
- // Room & actions
408
- //
409
- // RELIABILITY CONTRACT (what the platform guarantees / what your game must do):
410
- // - Every action is echoed back to the sender with the authoritative
411
- // sequence number. Apply game state ONLY in onAction — never
412
- // optimistically on send — so all clients apply identical actions in
413
- // identical order. The SDK deduplicates by sequence, so each action is
414
- // delivered exactly once even across reconnect replays.
415
- // - On a connection blip the host/SDK rejoins the room and replays missed
416
- // actions via onSync automatically. Use onDisconnect/onReconnect to
417
- // pause input and show a "reconnecting" indicator.
418
- // - For turn-based games, pass { nextTurn } on each move and trust
419
- // current_turn from join/sync instead of deriving the turn locally.
420
- // - Any participant should checkpoint via setState() at meaningful
421
- // transitions so rejoining clients can restore instantly (the host
422
- // need not be the one to call it).
423
- join(roomId?: string): Promise<GameJoinResult>;
424
- /**
425
- * Place this player into a drop-in/drop-out WORLD room (services tagged
426
- * `world`). Placement rides the matchmaking channel (works embedded AND
427
- * standalone): the platform returns the world you're already in, else
428
- * backfills a world with space, else creates a new one. Sets `game.roomId`,
429
- * so the usual `connect()`+`join()` / `connectDirect()` flow works
430
- * unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s. (SDK ≥ 2.23)
431
- */
432
- joinWorld(opts?: JoinWorldOptions): Promise<WorldJoinResult>;
433
- leave(): void;
434
- action(actionType: string, actionData?: Record<string, any>, opts?: GameActionOptions): Promise<ActionResult>;
435
- realtime(actionType: string, actionData?: Record<string, any>): void;
436
- requestSync(lastSequence?: number): void;
437
- requestRematch(): void;
438
- forfeit(): Promise<{ success: boolean; error?: string }>;
439
-
440
- /**
441
- * Invite friends to play in your room. Opens the host's friend/group picker
442
- * (recent chats + username search + your groups, multi-select); each pick gets
443
- * a game-invite card in their chat, and anyone who taps it joins THIS room
444
- * (your game gets `onPlayerJoined`). Works for any multiplayer-capable game —
445
- * if launched solo with no room, the host creates one with you as host and
446
- * this joins you to it. Embedded only; standalone resolves `{success:false}`.
447
- * Never rejects. (SDK ≥ 2.19)
448
- */
449
- invite(opts?: GameInviteOptions): Promise<GameInviteResult>;
450
-
451
- /**
452
- * Checkpoint authoritative game state on the server. Any participant in the
453
- * room may call this (not just player_ids[0]/host), so the snapshot stays
454
- * fresh even while the host is backgrounded. (Re)joining clients receive the
455
- * latest checkpoint as game_state in the join ack and in game:sync. Max 64 KB
456
- * serialized.
457
- */
458
- setState(state: Record<string, any>): Promise<{ success: boolean; error?: string; code?: UsionErrorCode }>;
459
-
460
- // Persisted state — survives iframe unmount/remount.
461
- // Keyed by (player_id, room_id) in localStorage. Schema is up to the game.
462
- saveState<T = any>(state: T): boolean;
463
- loadState<T = any>(): T | null;
464
- clearState(): void;
465
-
466
- // Forward a debug snapshot to the parent. Rendered as a top-right
467
- // overlay over the iframe when the host page is opened with `?debug=1`.
468
- debug(payload: Record<string, any>): void;
469
-
470
- // Event handlers
471
- onJoined(callback: (data: GameJoinResult) => void): UnsubscribeFn;
472
- onPlayerJoined(callback: (data: PlayerJoinedData) => void): UnsubscribeFn;
473
- onPlayerLeft(callback: (data: PlayerLeftData) => void): UnsubscribeFn;
474
- onStateUpdate(callback: (data: StateUpdateData) => void): UnsubscribeFn;
475
- onSync(callback: (data: SyncData) => void): UnsubscribeFn;
476
- onAction(callback: (data: GameActionData) => void): UnsubscribeFn;
477
- onRealtime(callback: (data: Record<string, any>) => void): UnsubscribeFn;
478
- onGameFinished(callback: (data: GameFinishedData) => void): UnsubscribeFn;
479
- onGameRestarted(callback: (data: Record<string, any>) => void): UnsubscribeFn;
480
- onError(callback: (data: { message: string; code?: string }) => void): UnsubscribeFn;
481
- onRematchRequest(callback: (data: RematchData) => void): UnsubscribeFn;
482
- onDisconnect(callback: (reason: string) => void): UnsubscribeFn;
483
- onReconnect(callback: (attemptNumber: number) => void): UnsubscribeFn;
484
- onConnectionError(callback: (error: Error) => void): UnsubscribeFn;
485
- /** Peer connection lifecycle: connected / reconnecting (grace) / gone. */
486
- onPlayerConnection(callback: (data: PlayerConnectionData) => void): UnsubscribeFn;
487
- /**
488
- * Fired when the host assigns this app a room AFTER launch — the solo→host
489
- * promotion path. The user opened the game solo (launch mode 'single'), then
490
- * shared it from the host's top-bar Share button; the host created a room and
491
- * the SDK has already updated `getLaunchParams().roomId`/`.mode` and is
492
- * connecting+joining. Use this to flip a solo game into its multiplayer /
493
- * hosting UI; `onJoined` fires right after the join completes.
494
- */
495
- onRoomAssigned(callback: (data: { roomId: string }) => void): UnsubscribeFn;
496
-
497
- // ─── Reconnection lifecycle (SDK ≥ 2.21; documented since 2.16) ──────────
498
- /** Highest action sequence seen (joins, syncs, live actions). */
499
- getLastSequence(): number;
500
- /** Highest action sequence applied locally; trails while catching up. */
501
- getLastAppliedSequence(): number;
502
- /** Current connection state, synchronously. */
503
- getConnectionState(): GameConnectionState;
504
- /**
505
- * Observe connection-state transitions ('connected' → 'disconnected' →
506
- * 'rejoining' → 'reconnected' → 'connected') — identical across the socket,
507
- * embedded-proxy, and direct transports. One hook to drive a
508
- * "Reconnecting…" overlay and gate input.
509
- */
510
- onConnectionState(callback: (state: GameConnectionState) => void): UnsubscribeFn;
511
- /**
512
- * Fires once per reconnect, after the resync completes. Restore local
513
- * state here — it does NOT fire for a manually-requested sync.
514
- */
515
- onReconnected(callback: (info: ReconnectedInfo) => void): UnsubscribeFn;
516
- /**
517
- * Reconnect-safe authoritative shared state. Commits are sequenced actions
518
- * applied through `reduce` on every client in the same order (deduped by
519
- * sequence); the authority (player_ids[0] by default) auto-checkpoints via
520
- * setState, and (re)joining clients recover automatically (load checkpoint,
521
- * replay the un-checkpointed tail). Use for state that must survive a
522
- * disconnect — unlike replicate() (realtime, lossy). Degrades to
523
- * local-apply in direct mode (no platform checkpoint there).
524
- */
525
- syncedState<S = Record<string, any>>(initial: S, opts?: SyncedStateOptions<S>): SyncedState<S>;
526
-
527
- /**
528
- * Register an ADDITIONAL event listener. Unlike the onX methods this
529
- * supports multiple listeners per event, can be called before connect(),
530
- * and works in every transport. Accepts internal names ('action'), wire
531
- * names ('game:action'), or snake_case ('player_joined').
532
- * @returns Unsubscribe function.
533
- */
534
- on(event: string, callback: (data: any) => void): UnsubscribeFn;
535
-
536
- // ─── Netcode helpers (low-latency realtime) ──────────────────
537
- // JSON state delta compression.
538
- diff(prev: any, next: any): any | undefined;
539
- patch(base: any, delta: any): any;
540
- /** Round numeric fields to a fixed precision (snapshot compression). */
541
- quantize<T = any>(value: T, precision?: number): T;
542
- /** Compact binary codec (use on direct/mesh transports). */
543
- encode(value: any): Uint8Array;
544
- decode(buf: ArrayBuffer | Uint8Array): any;
545
-
546
- /** Snapshot interpolation buffer (adaptive buffer + capped extrapolation). */
547
- createInterpolation(opts?: InterpolationOptions): SnapshotInterpolation;
548
- /** Client-side prediction + reconciliation + error smoothing. */
549
- createPredictor<S = any, I = any>(opts: PredictorOptions<S, I>): Predictor<S, I>;
550
- /** Fixed-rate outbound coalescer (defaults to sending via game.realtime). */
551
- createSender(opts?: SenderOptions): Coalescer;
552
- /** Sequence-guarded, delta-compressed snapshot sender. Pair with createSnapshotReceiver. */
553
- createSnapshotSender(opts?: SnapshotSenderOptions): SnapshotSender;
554
- /** Receiver for createSnapshotSender (drops stale/out-of-order frames). */
555
- createSnapshotReceiver(opts?: SnapshotReceiverOptions): SnapshotReceiver;
556
- /** One-line WebRTC P2P (2-peer) setup; signaling over realtime. */
557
- createMesh(opts: MeshOptions): MeshConnection;
558
- /** N-peer full mesh; signaling routed per-peer over realtime. */
559
- createMeshNetwork(opts?: MeshNetworkOptions): MeshNetwork;
560
- /** WebTransport (HTTP/3) connection — lowest-latency client-server datagrams. */
561
- createWebTransport(opts?: WebTransportOptions): WebTransportConnection;
562
- /** Declarative replication (host): mutate the object, it auto-syncs. */
563
- replicate<T = any>(obj: T, opts?: ReplicateOptions): Replicated<T>;
564
- /** Declarative replication (client): receive + (optionally) interpolate. */
565
- replica<S = any>(opts?: ReplicaOptions): Replica<S>;
566
- /** Server-side lag compensation (history + rewind) for fair hit-resolution. */
567
- createLagCompensator(opts?: LagCompensatorOptions): LagCompensator;
568
- /** Deterministic lockstep (inputs-only sim + free replays). */
569
- createLockstep(opts: LockstepOptions): Lockstep;
570
- /** Spatial hash for area-of-interest filtering in world rooms. (SDK ≥ 2.23) */
571
- createInterestGrid(opts?: InterestGridOptions): InterestGrid;
572
- /** Inject latency/jitter/loss locally to test under bad networks (null = off). */
573
- simulateNetwork(opts: NetworkSimOptions | null): NetworkSim | void;
574
-
575
- /** Measure round-trip time once (single outstanding probe); ms or null. */
576
- ping(): Promise<number | null>;
577
- /** Latest smoothed round-trip time in ms (null until first ping). */
578
- getRtt(): number | null;
579
-
580
- // ─── Network resilience (SDK ≥ 2.24) ─────────────────────────
581
- /**
582
- * Cheap snapshot of connection health: transport, connection state,
583
- * quality, smoothed rtt/jitter, age of the last inbound direct frame,
584
- * and buffered (unsent) bytes. Works in every transport; relay mode
585
- * reports rtt/jitter null unless game.ping() measured them.
586
- */
587
- getNetworkStats(): NetworkStats;
588
- /**
589
- * Observe network-quality TRANSITIONS ('good'/'fair'/'poor'/'dead') —
590
- * fires only when the quality level changes, with { quality, prev, stats }.
591
- * Drive a connection-quality indicator or degrade send rates from here.
592
- */
593
- onNetworkQuality(callback: (change: NetworkQualityChange) => void): UnsubscribeFn;
594
- }
595
-
596
- // ─── Netcode toolkit ──────────────────────────────────────────────
597
-
598
- export interface NetcodeEntity {
599
- id: string | number;
600
- [key: string]: any;
601
- }
602
-
603
- export interface Snapshot {
604
- id?: string;
605
- time?: number;
606
- state: NetcodeEntity[] | { [group: string]: NetcodeEntity[] };
607
- }
608
-
609
- export interface InterpolationOptions {
610
- /** Expected snapshot rate; sets the default buffer (default 20). */
611
- serverFps?: number;
612
- /** Fixed interpolation delay in ms (default ≈ 3 server frames). */
613
- bufferMs?: number;
614
- /** Grow the buffer with measured jitter (Source cl_interp_ratio style). */
615
- adaptive?: boolean;
616
- /** Adaptive buffer clamps. */
617
- minBufferMs?: number;
618
- maxBufferMs?: number;
619
- /** Max forward extrapolation on buffer underrun, ms (0 = off; Source caps ~250). */
620
- extrapolationMs?: number;
621
- /** Render against snapshot.time (server clock domain) instead of arrival time. */
622
- serverTime?: boolean;
623
- /** Snapshot history depth (default 120). */
624
- maxSize?: number;
625
- /** Clock source override (default Date.now). */
626
- now?: () => number;
627
- }
628
-
629
- export class SnapshotInterpolation {
630
- constructor(opts?: InterpolationOptions);
631
- getBufferMs(): number;
632
- setBufferMs(ms: number): void;
633
- getJitter(): number;
634
- add(snapshot: Snapshot | NetcodeEntity[] | { [group: string]: NetcodeEntity[] }): void;
635
- /** Interpolated entities for the render instant, or null if no data yet. */
636
- calc(keys: string, group?: string): NetcodeEntity[] | null;
637
- vault: Vault;
638
- }
639
-
640
- export class Vault {
641
- constructor(maxSize?: number);
642
- add(snapshot: { time: number; state: any }): void;
643
- readonly size: number;
644
- setMaxSize(n: number): void;
645
- latest(): { time: number; state: any } | null;
646
- clear(): void;
647
- straddle(time: number): [any, any];
648
- }
649
-
650
- export interface PredictorSmoothOptions {
651
- keys?: string | string[];
652
- rate?: number;
653
- snapTo?: number;
654
- }
655
-
656
- export interface PredictorOptions<S = any, I = any> {
657
- apply: (state: S, input: I) => S;
658
- initialState?: S;
659
- /** Smoothly blend correction errors instead of snapping (Overwatch style). */
660
- smooth?: PredictorSmoothOptions | string;
661
- }
662
-
663
- export class Predictor<S = any, I = any> {
664
- constructor(opts: PredictorOptions<S, I>);
665
- readonly state: S;
666
- readonly pending: Array<{ seq: number; input: I }>;
667
- readonly lastSeq: number;
668
- predict(input: I): { seq: number; state: S };
669
- reconcile(serverState: S, ackedSeq: number): S;
670
- /** Render state: corrected + decaying error offset. Call once per frame. */
671
- view(rate?: number): S;
672
- reset(state?: S): void;
673
- }
674
-
675
- export interface CoalescerOptions {
676
- hz?: number;
677
- onFlush: (entries: Array<{ type: string; data: any }>) => void;
678
- autoStart?: boolean;
679
- setInterval?: (fn: () => void, ms: number) => any;
680
- clearInterval?: (handle: any) => void;
681
- }
682
-
683
- export class Coalescer {
684
- constructor(opts: CoalescerOptions);
685
- readonly running: boolean;
686
- /** Latest-wins: only the newest data for `type` is sent next flush. */
687
- queue(type: string, data: any): void;
688
- /** Buffered: every value for `type` is kept and sent next flush. */
689
- append(type: string, data: any): void;
690
- drain(): Array<{ type: string; data: any }>;
691
- flush(): void;
692
- start(): void;
693
- stop(): void;
694
- }
695
-
696
- export interface SenderOptions {
697
- hz?: number;
698
- autoStart?: boolean;
699
- send?: (type: string, data: any) => void;
700
- }
701
-
702
- export interface SnapshotSenderOptions extends SenderOptions {
703
- /** realtime action_type to send under (default 'state'). */
704
- channel?: string;
705
- /** Use delta compression with periodic keyframes (default true). */
706
- delta?: boolean;
707
- /** Send a full keyframe every N deltas so lost deltas self-heal (default 30). */
708
- keyframeEvery?: number;
709
- /** Quantize numeric fields to this many decimals before diffing. */
710
- precision?: number;
711
- /** Binary-encode the wire payload: true (built-in) or a custom encoder. */
712
- encode?: boolean | ((payload: any) => any);
713
- /** Auto-read state each tick from this getter (basis for game.replicate). */
714
- source?: () => any;
715
- }
716
-
717
- export interface ReplicateOptions extends SnapshotSenderOptions {}
718
-
719
- export interface Replicated<T = any> {
720
- state: T;
721
- flush(): void;
722
- start(): void;
723
- stop(): void;
724
- }
725
-
726
- export interface ReplicaOptions {
727
- channel?: string;
728
- decode?: boolean | ((buf: any) => any);
729
- /** Interpolation keys ('x y') or an InterpolationOptions object to smooth entities. */
730
- interpolate?: string | InterpolationOptions;
731
- keys?: string;
732
- group?: string;
733
- }
734
-
735
- export interface Replica<S = any> {
736
- readonly state: S;
737
- view(): any;
738
- onChange(cb: (state: S) => void): void;
739
- stop(): void;
740
- }
741
-
742
- export interface NetworkSimOptions {
743
- latencyMs?: number;
744
- jitterMs?: number;
745
- lossPct?: number;
746
- dupPct?: number;
747
- setTimeout?: (fn: () => void, ms: number) => any;
748
- clearTimeout?: (handle: any) => void;
749
- random?: () => number;
750
- }
751
-
752
- export class NetworkSim {
753
- constructor(opts?: NetworkSimOptions);
754
- latencyMs: number; jitterMs: number; lossPct: number; dupPct: number;
755
- set(opts: NetworkSimOptions): NetworkSim;
756
- wrap<F extends (...args: any[]) => any>(fn: F): F;
757
- flush(): void;
758
- }
759
-
760
- export interface LockstepOptions {
761
- playerId: string;
762
- players: string[];
763
- step: (frame: number, inputs: Record<string, any>) => void;
764
- send?: (msg: { frame: number; playerId: string; input: any }) => void;
765
- inputDelay?: number;
766
- idleInput?: any;
767
- }
768
-
769
- export class Lockstep {
770
- constructor(opts: LockstepOptions);
771
- readonly frame: number;
772
- readonly players: string[];
773
- submit(input: any): number;
774
- receive(msg: { frame: number; playerId: string; input: any }): void;
775
- tick(): number;
776
- isStalled(): boolean;
777
- getReplay(): Array<{ frame: number; inputs: Record<string, any> }>;
778
- static replay(log: Array<{ frame: number; inputs: Record<string, any> }>, step: (frame: number, inputs: Record<string, any>) => void): void;
779
- }
780
-
781
- export interface LagCompensatorOptions {
782
- historyMs?: number;
783
- maxSize?: number;
784
- now?: () => number;
785
- }
786
-
787
- export class LagCompensator {
788
- constructor(opts?: LagCompensatorOptions);
789
- readonly size: number;
790
- record(entities: Array<{ id: string | number; [k: string]: any }>, time?: number): void;
791
- rewind(time: number, keys?: string[]): Record<string, any>;
792
- rewindForClient(rttMs: number, interpBufferMs: number, opts?: { maxRewindMs?: number; keys?: string[] }): Record<string, any>;
793
- clear(): void;
794
- }
795
-
796
- export interface SnapshotSender {
797
- send(state: any): void;
798
- flush(): void;
799
- start(): void;
800
- stop(): void;
801
- reset(): void;
802
- }
803
-
804
- export interface SnapshotReceiverOptions {
805
- /** Binary-decode incoming payloads: true (built-in) or a custom decoder. */
806
- decode?: boolean | ((buf: any) => any);
807
- }
808
-
809
- export interface SnapshotReceiver {
810
- /** Apply a message from the sender; returns the reconstructed state. */
811
- receive<S = any>(msg: any): S;
812
- readonly state: any;
813
- readonly stats: { appliedSeq: number; baseSeq: number; dropped: number };
814
- reset(): void;
815
- }
816
-
817
- export interface PingMeterOptions {
818
- alpha?: number;
819
- now?: () => number;
820
- }
821
-
822
- export class PingMeter {
823
- constructor(opts?: PingMeterOptions);
824
- readonly rtt: number | null;
825
- readonly latency: number | null;
826
- readonly jitter: number;
827
- readonly last: number | null;
828
- begin(): number;
829
- end(id: number): number | null;
830
- sample(rttMs: number): number | null;
831
- reset(): void;
832
- }
833
-
834
- export interface IceServerConfig {
835
- stun?: string;
836
- turn?: string;
837
- turnUsername?: string;
838
- turnCredential?: string;
839
- }
840
-
841
- export interface MeshOptions {
842
- role: 'host' | 'guest';
843
- /** realtime action_type used for signaling (default 'signal'). */
844
- signalChannel?: string;
845
- iceServers?: RTCIceServer[];
846
- /** Drop stale/out-of-order frames on the unreliable channel (default true). */
847
- sequenced?: boolean;
848
- /** Recover via ICE restart on connection failure (host; default true). */
849
- autoReconnect?: boolean;
850
- maxRestarts?: number;
851
- RTCPeerConnection?: typeof RTCPeerConnection;
852
- setTimeout?: (fn: () => void, ms: number) => any;
853
- }
854
-
855
- export class MeshConnection {
856
- constructor(opts: MeshOptions & { sendSignal: (payload: any) => void });
857
- /** Build an iceServers array with optional TURN relay. */
858
- static iceServers(cfg?: IceServerConfig): RTCIceServer[];
859
- readonly connected: boolean;
860
- readonly role: 'host' | 'guest';
861
- onOpen: (() => void) | null;
862
- onMessage: ((data: any, channel: 'unreliable' | 'reliable') => void) | null;
863
- onClose: (() => void) | null;
864
- onError: ((err: any) => void) | null;
865
- onStateChange: ((state: string) => void) | null;
866
- start(): Promise<void>;
867
- handleSignal(payload: any): Promise<void>;
868
- send(data: any): boolean;
869
- sendReliable(data: any): boolean;
870
- close(): void;
871
- }
872
-
873
- export interface MeshNetworkOptions {
874
- selfId?: string;
875
- signalChannel?: string;
876
- iceServers?: RTCIceServer[];
877
- sequenced?: boolean;
878
- autoReconnect?: boolean;
879
- RTCPeerConnection?: typeof RTCPeerConnection;
880
- }
881
-
882
- export class MeshNetwork {
883
- constructor(opts: MeshNetworkOptions & { selfId: string; sendSignal: (toPeerId: string, payload: any) => void });
884
- readonly selfId: string;
885
- readonly peerIds: string[];
886
- readonly connectedCount: number;
887
- peer(peerId: string): MeshConnection | null;
888
- addPeer(peerId: string): Promise<MeshConnection | null>;
889
- setRoster(peerIds: string[]): Promise<void>;
890
- removePeer(peerId: string): void;
891
- handleSignal(fromPeerId: string, payload: any): Promise<void>;
892
- send(peerId: string, data: any): boolean;
893
- sendReliable(peerId: string, data: any): boolean;
894
- broadcast(data: any): void;
895
- broadcastReliable(data: any): void;
896
- onPeerOpen: ((peerId: string) => void) | null;
897
- onPeerClose: ((peerId: string) => void) | null;
898
- onMessage: ((peerId: string, data: any, channel: 'unreliable' | 'reliable') => void) | null;
899
- onError: ((peerId: string, err: any) => void) | null;
900
- close(): void;
901
- }
902
-
903
- export interface WebTransportOptions {
904
- /** https:// HTTP/3 endpoint (defaults to Usion.config.webTransportUrl). */
905
- url?: string;
906
- /** For self-signed dev certificates. */
907
- serverCertificateHashes?: Array<{ algorithm: string; value: BufferSource }>;
908
- /** Drop stale/out-of-order datagrams (default true). */
909
- sequenced?: boolean;
910
- /** Injectable WebTransport constructor (tests). */
911
- WebTransport?: any;
912
- }
913
-
914
- export class WebTransportConnection {
915
- constructor(opts: WebTransportOptions & { url: string });
916
- readonly connected: boolean;
917
- onOpen: (() => void) | null;
918
- onMessage: ((data: any, channel: 'datagram' | 'reliable') => void) | null;
919
- onClose: (() => void) | null;
920
- onError: ((err: any) => void) | null;
921
- connect(): Promise<void>;
922
- /** Send over the unreliable datagram channel (sequenced). */
923
- send(data: any): boolean;
924
- /** Send over the reliable ordered stream. */
925
- sendReliable(data: any): boolean;
926
- close(): void;
927
- }
928
-
929
- // ─── Interest grid (area-of-interest spatial hash, SDK ≥ 2.23) ───
930
-
931
- export interface InterestGridOptions {
932
- /** Cell size in world units (default 256); pick ≈ the typical query radius. */
933
- cellSize?: number;
934
- }
935
-
936
- /** Per-observer visibility diff from InterestGrid.observe(). */
937
- export interface InterestGridObservation {
938
- /** Ids visible now that were not visible on this observer's previous observe(). */
939
- entered: Array<string | number>;
940
- /** Ids visible on the previous observe() that no longer are. */
941
- left: Array<string | number>;
942
- /** All ids currently within the radius. */
943
- visible: Array<string | number>;
944
- }
945
-
946
- /**
947
- * Spatial hash for area-of-interest filtering: O(cells touched) proximity
948
- * queries plus per-observer enter/leave diffs. Pure JS (browser and Node) —
949
- * the AOI building block for world-scale rooms.
950
- */
951
- export interface InterestGrid {
952
- /** Insert an entity or move an existing one. */
953
- upsert(id: string | number, x: number, y: number): void;
954
- /** Remove an entity (unknown ids are a no-op). */
955
- remove(id: string | number): void;
956
- /** Entity ids within `radius` of (x, y) — a true circle test. */
957
- query(x: number, y: number, radius: number): Array<string | number>;
958
- /** query() diffed against this observer's previous call. */
959
- observe(observerId: string | number, x: number, y: number, radius: number): InterestGridObservation;
960
- /** Free an observer's tracking state (call when a player leaves). */
961
- dropObserver(observerId: string | number): void;
962
- /** Number of entities in the grid. */
963
- size(): number;
964
- }
965
-
966
- export interface NetcodeModule {
967
- SnapshotInterpolation: typeof SnapshotInterpolation;
968
- Vault: typeof Vault;
969
- Predictor: typeof Predictor;
970
- Coalescer: typeof Coalescer;
971
- PingMeter: typeof PingMeter;
972
- MeshConnection: typeof MeshConnection;
973
- MeshNetwork: typeof MeshNetwork;
974
- WebTransportConnection: typeof WebTransportConnection;
975
- NetworkSim: typeof NetworkSim;
976
- Lockstep: typeof Lockstep;
977
- LagCompensator: typeof LagCompensator;
978
- diff(prev: any, next: any): any | undefined;
979
- patch(base: any, delta: any): any;
980
- quantize<T = any>(value: T, precision?: number): T;
981
- encode(value: any): Uint8Array;
982
- decode(buf: ArrayBuffer | Uint8Array): any;
983
- /** Spatial hash for area-of-interest filtering in world rooms. (SDK ≥ 2.23) */
984
- createInterestGrid(opts?: InterestGridOptions): InterestGrid;
985
- }
986
-
987
- // ─── Results ────────────────────────────────────────────────────
988
-
989
- export interface SavedResult {
990
- id: string;
991
- data: string;
992
- metadata?: {
993
- thumbnail_url?: string;
994
- title?: string;
995
- type?: string;
996
- };
997
- created_at?: string;
998
- }
999
-
1000
- // ─── Bot ────────────────────────────────────────────────────────
1001
-
1002
- export interface BotMessage {
1003
- id: string;
1004
- content: string;
1005
- content_type?: string;
1006
- components?: any[];
1007
- sender_id: string;
1008
- }
1009
-
1010
- export interface BotModule {
1011
- callAction(action: string, data?: Record<string, any>): Promise<any>;
1012
- sendMessage(text: string): void;
1013
- updateContext(ctx: Record<string, any>): void;
1014
- close(result?: any): void;
1015
- onMessage(callback: (message: BotMessage) => void): UnsubscribeFn;
1016
- }
1017
-
1018
- // ─── Selection Grid ──────────────────────────────────────────────
1019
-
1020
- export interface SelectionGrid {
1021
- getSelected(): string | null;
1022
- clear(): void;
1023
- }
1024
-
1025
- // ─── Main SDK ────────────────────────────────────────────────────
1026
-
1027
- export interface UsionSDK {
1028
- version: string;
1029
- config: UsionConfig;
1030
-
1031
- // Lifecycle
1032
- /**
1033
- * Initialize the SDK. The callback fires when the host's INIT config
1034
- * arrives; every call also returns a Promise of the same config, so
1035
- * `const config = await Usion.init()` works. `opts.timeout` (ms) rejects
1036
- * the promise with UsionError(INIT_TIMEOUT) when no INIT arrives in time
1037
- * (embedded but host silent). (promise/timeout: SDK ≥ 2.22)
1038
- */
1039
- init(callback?: (config: UsionConfig) => void, opts?: { timeout?: number }): Promise<UsionConfig>;
1040
- init(opts: { timeout?: number }): Promise<UsionConfig>;
1041
- exit(options?: { backCount?: number }): void;
1042
-
1043
- // Theme & Locale
1044
- getTheme(): 'light' | 'dark';
1045
- getLanguage(): string;
1046
-
1047
- /**
1048
- * Launch parameters the host opened this app with. `path` is the deep-link
1049
- * target (e.g. from a tapped `Usion.notify` notification); route to it after
1050
- * init so the user lands on the right screen. `mode` is `'single'` (opened
1051
- * from Explore / the Game hub, solo) or `'multiplayer'` (opened from a game
1052
- * invite in a chat) — branch game setup on it. (mode: SDK ≥ 2.18)
1053
- */
1054
- getLaunchParams(): { path: string | null; ref: string | null; roomId: string | null; mode: 'single' | 'multiplayer' };
1055
-
1056
- // Payments
1057
- requestPayment(amount: number, reason: string, data?: PaymentOptions): Promise<PaymentResponse>;
1058
-
1059
- // Service communication
1060
- submit(data: Record<string, any>): void;
1061
- error(message: string): void;
1062
-
1063
- // Results (server-side persistence)
1064
- saveResult(data: string, metadata?: { thumbnail_url?: string; title?: string; type?: string; [key: string]: unknown }): Promise<SavedResult>;
1065
- deleteResult(resultId: string): Promise<void>;
1066
- getResults(): SavedResult[];
1067
-
1068
- // Back button
1069
- claimBackButton(callback: () => void): void;
1070
- releaseBackButton(): void;
1071
-
1072
- // Download
1073
- download(url: string, filename?: string): Promise<{ success?: boolean; error?: string }>;
1074
-
1075
- // Sharing
1076
- share(contentType: 'audio' | 'image' | 'video' | 'text' | 'mixed', data: ShareData): void;
1077
- shareToFeed(contentType: 'text' | 'image' | 'video' | 'audio' | 'mixed', data: {
1078
- text?: string;
1079
- media?: Array<{ type: 'image' | 'video' | 'audio'; url: string; thumbnailUrl?: string; width?: number; height?: number; duration?: number }>;
1080
- }): Promise<{ success: boolean; postId?: string; shareUrl?: string }>;
1081
-
1082
- // Logging
1083
- log(msg: string): void;
1084
-
1085
- // Generic event listener (returns an unsubscribe function)
1086
- on(type: string, callback: (data: any) => void): UnsubscribeFn;
1087
-
1088
- // UI helpers
1089
- setLoading(btn: HTMLElement | string, loading: boolean): void;
1090
- toggle(el: HTMLElement | string, show: boolean): void;
1091
- charCount(input: HTMLElement | string, counter: HTMLElement | string, max: number): void;
1092
- selectionGrid(
1093
- containerSelector: string,
1094
- itemSelector: string,
1095
- onChange: (selected: string, item: HTMLElement) => void
1096
- ): SelectionGrid;
1097
-
1098
- /** SDK version (injected from package.json at build time). */
1099
- version: string;
1100
-
1101
- /**
1102
- * Live diagnostics snapshot: version, transport, connection + sequence
1103
- * state. game.debug() attaches this automatically as payload._diag.
1104
- */
1105
- diagnostics(): {
1106
- version: string;
1107
- transport: 'socket' | 'proxy' | 'direct' | 'none';
1108
- connected: boolean;
1109
- joined: boolean;
1110
- roomId: string | null;
1111
- playerId: string | null;
1112
- lastSequence: number;
1113
- lastActionApplied: number;
1114
- rejoining: boolean;
1115
- };
1116
-
1117
- // Errors — branch on err.code (stable), never on message text.
1118
- UsionError: typeof UsionError;
1119
- ERROR_CODES: typeof ERROR_CODES;
1120
-
1121
- // Modules
1122
- user: UserModule;
1123
- storage: StorageModule;
1124
- fileStorage: FileStorageModule;
1125
- wallet: WalletModule;
1126
- session: SessionModule;
1127
- chat: ChatModule;
1128
- bot: BotModule;
1129
- game: GameModule;
1130
- lobby: LobbyModule;
1131
- leaderboard: LeaderboardModule;
1132
- matchmaking: MatchmakingModule;
1133
- cloud: CloudModule;
1134
- notify: NotifyModule;
1135
- permissions: PermissionsModule;
1136
- netcode: NetcodeModule;
1137
- }
1138
-
1139
- /**
1140
- * Send notifications to the CURRENT user that reopen this app (in-app banner
1141
- * when online, OS push when offline). `path` deep-links to a screen, read back
1142
- * via `Usion.getLaunchParams().path`. Rate-limited per user per service.
1143
- */
1144
- export interface NotifyModule {
1145
- /** Notify the current user. */
1146
- send(opts: { title: string; body: string; path?: string; serviceId?: string }): Promise<{ success: boolean; delivered?: string }>;
1147
- /** Mute/unmute notifications from this app for the current user. */
1148
- setMuted(muted: boolean, opts?: { serviceId?: string }): Promise<{ success: boolean; muted: boolean }>;
1149
- /** Whether the current user has muted this app's notifications. */
1150
- isMuted(opts?: { serviceId?: string }): Promise<boolean>;
1151
- }
1152
-
1153
- /** Result of a permission request: per-key state + whether ALL were granted. */
1154
- export interface PermissionResult {
1155
- /** True only if every requested permission ended granted. */
1156
- granted: boolean;
1157
- /** Map of each requested permission key to its resulting state. */
1158
- permissions: Record<string, boolean>;
1159
- }
1160
-
1161
- /**
1162
- * Ask the user to allow capabilities (the host shows a modal — like asking for
1163
- * money). The platform enforces grants: e.g. `notify.send` is dropped until
1164
- * `notifications` is granted. Embedded feature; standalone resolves "not
1165
- * granted". Permission keys today: `'notifications'`.
1166
- */
1167
- export interface PermissionsModule {
1168
- /** Prompt the user to allow one or more permissions. */
1169
- request(permissions: string | string[], opts?: { reason?: string }): Promise<PermissionResult>;
1170
- /** Read current state without prompting; map of key -> granted. */
1171
- query(permissions?: string | string[]): Promise<Record<string, boolean>>;
1172
- /** Convenience: is a single permission currently granted? */
1173
- has(permission: string): Promise<boolean>;
1174
- }
1175
-
1176
- /** Scoped server-persisted KV operations (per-user or shared). */
1177
- export interface CloudScope {
1178
- /** Get a value; resolves to null when the key doesn't exist. */
1179
- get(key: string, opts?: { serviceId?: string }): Promise<any>;
1180
- /** Set a JSON-serializable value (max 64 KB). Keys: 1-128 chars of A-Za-z0-9_.-:/ */
1181
- set(key: string, value: any, opts?: { serviceId?: string }): Promise<{ success: boolean; size: number }>;
1182
- /** Remove a key. */
1183
- remove(key: string, opts?: { serviceId?: string }): Promise<{ success: boolean; removed: boolean }>;
1184
- /** List keys in this scope's bucket. */
1185
- keys(opts?: { serviceId?: string }): Promise<string[]>;
1186
- }
1187
-
1188
- /**
1189
- * Server-persisted cloud storage. Per-user scope on the module itself
1190
- * (cloud saves synced across devices); `shared` is one bucket per app that
1191
- * all users read/write. Quotas: 64 KB/value, 200 keys + 1 MB per bucket.
1192
- */
1193
- export interface CloudModule extends CloudScope {
1194
- shared: CloudScope & {
1195
- /** Atomically increment a shared numeric value (default delta 1). Resolves to the new value. */
1196
- incr(key: string, delta?: number, opts?: { serviceId?: string }): Promise<number>;
1197
- };
1198
- }
1199
-
1200
- export interface Match { roomId: string; players: string[]; serviceId?: string; }
1201
-
1202
- export interface MatchmakingModule {
1203
- /**
1204
- * Join the quick-match queue; resolves when paired with online strangers.
1205
- * `opts.timeout` (ms) bounds the wait: on expiry the queue is left and the
1206
- * promise rejects with UsionError(MATCH_TIMEOUT). A newer find() rejects
1207
- * the previous one with SUPERSEDED; cancel() rejects it with CANCELLED.
1208
- * (timeout: SDK ≥ 2.22)
1209
- */
1210
- find(serviceId?: string, opts?: { size?: number; timeout?: number }): Promise<Match>;
1211
- /** Leave the queue / stop waiting. */
1212
- cancel(): Promise<any>;
1213
- /** Called whenever a match is found. */
1214
- onMatch(cb: (match: Match) => void): void;
1215
- }
1216
-
1217
- export interface LeaderboardEntry {
1218
- user_id: string;
1219
- name?: string | null;
1220
- avatar?: string | null;
1221
- score: number;
1222
- rank: number;
1223
- is_me: boolean;
1224
- metadata?: any;
1225
- }
1226
-
1227
- export interface LeaderboardModule {
1228
- /** Submit a score (best is kept per the service's order config). Opt-in per game. */
1229
- submit(score: number, metadata?: any, opts?: { serviceId?: string }): Promise<{ success: boolean; score: number; best: number; rank: number; updated: boolean }>;
1230
- /** Leaderboard of people you've messaged (plus you). */
1231
- friends(opts?: { serviceId?: string; limit?: number }): Promise<LeaderboardEntry[]>;
1232
- /** Global top N. */
1233
- top(opts?: { serviceId?: string; limit?: number }): Promise<LeaderboardEntry[]>;
1234
- /** Your own score + global rank. */
1235
- me(opts?: { serviceId?: string }): Promise<{ score: number | null; rank: number | null; total: number; metadata?: any }>;
1236
- }
1237
-
1238
- export interface LobbyMember { id: string; name?: string; ready: boolean; }
1239
- export interface LobbyState { code: string | null; host: string | null; status: string | null; members: LobbyMember[]; }
1240
-
1241
- export interface LobbyModule {
1242
- readonly state: LobbyState;
1243
- onUpdate(cb: (state: { code: string; host: string; status: string; members: LobbyMember[] }) => void): void;
1244
- onStarted(cb: (data: { room_id: string; by: string; player_ids?: string[] }) => void): void;
1245
- create(opts?: { maxPlayers?: number; public?: boolean }): Promise<{ code: string }>;
1246
- join(code: string): Promise<{ code: string }>;
1247
- leave(): Promise<void>;
1248
- setReady(ready?: boolean): Promise<any>;
1249
- allReady(): boolean;
1250
- isHost(): boolean;
1251
- start(roomId: string): Promise<any>;
1252
- queue(serviceId: string, opts?: { conversationId?: string }): Promise<any>;
1253
- }
1254
-
1255
- /**
1256
- * Stable machine-readable error codes. Part of the public API: codes are
1257
- * never removed within a major version. Messages may change — branch on
1258
- * `err.code`, never on message text.
1259
- */
1260
- export declare const ERROR_CODES: {
1261
- readonly NOT_CONNECTED: 'NOT_CONNECTED';
1262
- readonly NO_ROOM: 'NO_ROOM';
1263
- readonly ROOM_NOT_FOUND: 'ROOM_NOT_FOUND';
1264
- readonly NOT_PARTICIPANT: 'NOT_PARTICIPANT';
1265
- readonly NOT_IN_ROOM: 'NOT_IN_ROOM';
1266
- readonly NOT_AUTHORITY: 'NOT_AUTHORITY';
1267
- readonly NOT_AUTHENTICATED: 'NOT_AUTHENTICATED';
1268
- readonly JOIN_TIMEOUT: 'JOIN_TIMEOUT';
1269
- readonly CONNECT_TIMEOUT: 'CONNECT_TIMEOUT';
1270
- readonly INIT_TIMEOUT: 'INIT_TIMEOUT';
1271
- readonly MATCH_TIMEOUT: 'MATCH_TIMEOUT';
1272
- readonly STATE_TOO_LARGE: 'STATE_TOO_LARGE';
1273
- readonly INVALID_STATE: 'INVALID_STATE';
1274
- readonly STALE_STATE: 'STALE_STATE';
1275
- readonly INVALID_NEXT_TURN: 'INVALID_NEXT_TURN';
1276
- readonly INVALID_INPUT: 'INVALID_INPUT';
1277
- readonly NOT_FOUND: 'NOT_FOUND';
1278
- readonly QUOTA_EXCEEDED: 'QUOTA_EXCEEDED';
1279
- readonly VALUE_TOO_LARGE: 'VALUE_TOO_LARGE';
1280
- readonly LOBBY_FULL: 'LOBBY_FULL';
1281
- readonly LOBBY_CLOSED: 'LOBBY_CLOSED';
1282
- readonly WORLD_FULL: 'WORLD_FULL';
1283
- readonly CONFLICT: 'CONFLICT';
1284
- readonly RATE_LIMITED: 'RATE_LIMITED';
1285
- readonly REQUEST_TIMEOUT: 'REQUEST_TIMEOUT';
1286
- readonly QUEUE_FULL: 'QUEUE_FULL';
1287
- readonly CANCELLED: 'CANCELLED';
1288
- readonly SUPERSEDED: 'SUPERSEDED';
1289
- readonly UNSUPPORTED: 'UNSUPPORTED';
1290
- readonly UNKNOWN: 'UNKNOWN';
1291
- };
1292
-
1293
- export type UsionErrorCode = keyof typeof ERROR_CODES;
1294
-
1295
- export declare class UsionError extends Error {
1296
- readonly name: 'UsionError';
1297
- readonly code: UsionErrorCode;
1298
- /** Seconds until a RATE_LIMITED call may be retried (when the server sent it). */
1299
- readonly retryAfter?: number;
1300
- constructor(code: UsionErrorCode | string, message?: string);
1301
- }
1302
-
1303
- declare const Usion: UsionSDK;
1304
-
1305
- export { Usion };
1306
- export default Usion;