@usions/sdk 2.24.2 → 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 (59) 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 +25 -46
  12. package/src/browser.js +0 -6725
  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-ack.js +0 -32
  23. package/src/modules/game-core.js +0 -278
  24. package/src/modules/game-direct.js +0 -267
  25. package/src/modules/game-methods.js +0 -782
  26. package/src/modules/game-netcode.js +0 -349
  27. package/src/modules/game-proxy.js +0 -184
  28. package/src/modules/game-reliability.js +0 -278
  29. package/src/modules/game-resilience.js +0 -245
  30. package/src/modules/game-socket.js +0 -214
  31. package/src/modules/index.js +0 -78
  32. package/src/modules/leaderboard.js +0 -46
  33. package/src/modules/lobby.js +0 -103
  34. package/src/modules/matchmaking.js +0 -140
  35. package/src/modules/misc.js +0 -152
  36. package/src/modules/netcode/binary.js +0 -113
  37. package/src/modules/netcode/delta.js +0 -236
  38. package/src/modules/netcode/index.js +0 -43
  39. package/src/modules/netcode/interest-grid.js +0 -227
  40. package/src/modules/netcode/interpolation.js +0 -235
  41. package/src/modules/netcode/lagcomp.js +0 -104
  42. package/src/modules/netcode/lockstep.js +0 -103
  43. package/src/modules/netcode/mesh-network.js +0 -103
  44. package/src/modules/netcode/mesh.js +0 -188
  45. package/src/modules/netcode/netsim.js +0 -77
  46. package/src/modules/netcode/ping.js +0 -69
  47. package/src/modules/netcode/prediction.js +0 -113
  48. package/src/modules/netcode/sender.js +0 -102
  49. package/src/modules/netcode/webtransport.js +0 -195
  50. package/src/modules/notify.js +0 -70
  51. package/src/modules/permissions.js +0 -157
  52. package/src/modules/results.js +0 -34
  53. package/src/modules/session.js +0 -62
  54. package/src/modules/storage.js +0 -64
  55. package/src/modules/ui.js +0 -111
  56. package/src/modules/user.js +0 -61
  57. package/src/modules/wallet.js +0 -253
  58. package/types/browser.d.ts +0 -5
  59. package/types/index.d.ts +0 -1308
@@ -1,782 +0,0 @@
1
- /**
2
- * Usion SDK Game Methods — join, leave, action, realtime, sync, etc.
3
- */
4
-
5
- import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
6
- import {
7
- emitGameWithAck,
8
- GAME_JOIN_TIMEOUT_MS,
9
- } from './game-ack.js';
10
-
11
- function trackJoinPromise(game, promise) {
12
- game._joinPromise = promise;
13
- promise.catch(function() {
14
- game._joined = false;
15
- if (game._joinPromise === promise) game._joinPromise = null;
16
- });
17
- return promise;
18
- }
19
-
20
- /**
21
- * Add game action methods to game module
22
- * @param {object} game - The game module object
23
- * @param {object} Usion - Reference to the main Usion object
24
- */
25
- export function applyGameMethods(game, Usion) {
26
- /**
27
- * Join a game room
28
- * @param {string} roomId - Game room ID (optional, uses config)
29
- * @returns {Promise} Resolves with join data
30
- */
31
- game.join = function(roomId) {
32
- const self = this;
33
- roomId = roomId || Usion.config.roomId;
34
-
35
- // Coalesce in-flight/successful joins; rejected joins are cleared below.
36
- if (self.roomId === roomId && self._joinPromise) {
37
- return self._joinPromise;
38
- }
39
-
40
- self.roomId = roomId;
41
- self.playerId = Usion.user.getId();
42
-
43
- if (self.directMode) {
44
- self._joined = true;
45
- self._joinPromise = Promise.resolve({
46
- room_id: roomId,
47
- player_id: self.playerId
48
- });
49
- return self._joinPromise;
50
- }
51
-
52
- // Proxy mode: send join request to parent
53
- if (self._useProxy) {
54
- const joinPromise = new Promise(function(resolve, reject) {
55
- const rejectJoin = function(err) { reject(err); };
56
- self._proxyJoinResolve = resolve;
57
- self._proxyJoinReject = rejectJoin;
58
- Usion._post({ type: 'GAME_JOIN', room_id: roomId });
59
- setTimeout(function() {
60
- if (self._proxyJoinReject === rejectJoin) {
61
- self._proxyJoinResolve = null;
62
- self._proxyJoinReject = null;
63
- reject(new UsionError(ERROR_CODES.JOIN_TIMEOUT, 'Join timeout'));
64
- }
65
- }, GAME_JOIN_TIMEOUT_MS);
66
- });
67
- return trackJoinPromise(self, joinPromise);
68
- }
69
-
70
- let joinPromise;
71
- if (!self.socket || !self.connected) {
72
- joinPromise = Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
73
- } else if (!roomId) {
74
- joinPromise = Promise.reject(new UsionError(ERROR_CODES.NO_ROOM, 'No room ID provided'));
75
- } else {
76
- joinPromise = emitGameWithAck(
77
- self.socket, 'game:join', { room_id: roomId },
78
- GAME_JOIN_TIMEOUT_MS, ERROR_CODES.JOIN_TIMEOUT
79
- ).then(function(response) {
80
- if (response.error) {
81
- self._joined = false;
82
- throw toUsionError(response);
83
- } else {
84
- self._joined = true;
85
- if (response.sequence !== undefined) {
86
- self._lastSequence = response.sequence;
87
- // The joined state reflects everything up to this sequence —
88
- // actions at or below it must not be re-delivered (same
89
- // baseline the proxy transport sets from GAME_JOINED).
90
- self._lastActionApplied = Math.max(self._lastActionApplied, response.sequence);
91
- }
92
- // Transport parity: proxy and direct modes dispatch 'joined';
93
- // the socket transport now does too, so onJoined / recovery
94
- // logic behaves the same everywhere.
95
- self._dispatch('joined', response);
96
- return response;
97
- }
98
- });
99
- }
100
-
101
- return trackJoinPromise(self, joinPromise);
102
- };
103
-
104
- /**
105
- * Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
106
- *
107
- * World rooms (services tagged `world`) run continuously: players enter and
108
- * leave at any time instead of playing fixed matches. Placement rides the
109
- * matchmaking channel (works embedded AND standalone): the platform returns
110
- * the world you're already in, else backfills a world with space, else
111
- * creates a new one. On success `game.roomId` is set, so the usual
112
- * `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
113
- * flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
114
- *
115
- * @param {object} [opts]
116
- * @param {string} [opts.serviceId] - Defaults to the current service.
117
- * @returns {Promise<{roomId: string, playerIds: string[]}>}
118
- */
119
- game.joinWorld = function(opts) {
120
- const self = this;
121
- opts = opts || {};
122
- return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
123
- self.roomId = m.roomId;
124
- return { roomId: m.roomId, playerIds: m.players || [] };
125
- });
126
- };
127
-
128
- /**
129
- * Leave the current game room
130
- */
131
- game.leave = function() {
132
- const self = this;
133
-
134
- if (self.directMode) {
135
- if (self.roomId) self._sendDirect('leave', {});
136
- self.roomId = null;
137
- self._lastSequence = 0;
138
- self._joined = false;
139
- self._joinPromise = null;
140
- return;
141
- }
142
-
143
- if (self._useProxy) {
144
- if (self.roomId) Usion._post({ type: 'GAME_LEAVE', room_id: self.roomId });
145
- self.roomId = null;
146
- self._lastSequence = 0;
147
- self._joined = false;
148
- self._joinPromise = null;
149
- return;
150
- }
151
-
152
- if (self.socket && self.connected && self.roomId) {
153
- self.socket.emit('game:leave', { room_id: self.roomId });
154
- self.roomId = null;
155
- self._lastSequence = 0;
156
- self._joined = false;
157
- self._joinPromise = null;
158
- }
159
- };
160
-
161
- /**
162
- * Send a game action.
163
- *
164
- * RELIABILITY CONTRACT: the platform echoes every action back to the
165
- * sender (with the authoritative sequence number). Apply game state ONLY
166
- * in onAction — never optimistically on send — so every client applies
167
- * the same actions in the same order. The SDK deduplicates by sequence,
168
- * so an action is delivered exactly once even across reconnect replays.
169
- *
170
- * @param {string} actionType - Type of action (e.g., 'move')
171
- * @param {object} actionData - Action data
172
- * @param {object} [opts] - Options. opts.nextTurn: player ID whose turn
173
- * is next — the server remembers it and hands it to any (re)joining
174
- * client as current_turn, so turn state survives reconnects.
175
- * @returns {Promise} Resolves when action is processed
176
- */
177
- game.action = function(actionType, actionData, opts) {
178
- const self = this;
179
- const nextTurn = opts && opts.nextTurn;
180
- const queueOffline = !!(opts && opts.queueOffline);
181
-
182
- if (self.directMode) {
183
- self._sendDirect('action', {
184
- action_type: actionType || 'default',
185
- action_data: actionData || {}
186
- });
187
- return Promise.resolve({ success: true });
188
- }
189
-
190
- // Opt-in offline queue: instead of failing while disconnected, hold
191
- // the move and send it (in order) once the connection recovers.
192
- // Turn-based games get "your move is saved and sends when you're
193
- // back" for free; realtime games should NOT use this (stale inputs).
194
- if (queueOffline && !self.connected) {
195
- return self._queueOfflineAction(actionType, actionData, opts);
196
- }
197
-
198
- if (self._useProxy) {
199
- if (!self.connected) {
200
- return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
201
- }
202
- const proxyMsg = { type: 'GAME_ACTION', room_id: self.roomId, action_type: actionType, action_data: actionData };
203
- if (nextTurn) proxyMsg.next_turn = nextTurn;
204
- Usion._post(proxyMsg);
205
- // v2 hosts only confirm handoff; completion arrives via onAction.
206
- return Promise.resolve({ success: true, acknowledged: false });
207
- }
208
-
209
- // Gate sends while a post-reconnect rejoin is in flight, so a stale
210
- // move can't go out before the client has resynced.
211
- const gate = self._rejoinPromise || Promise.resolve();
212
- return gate.then(function() {
213
- if (!self.socket || !self.connected) {
214
- if (queueOffline) {
215
- return self._queueOfflineAction(actionType, actionData, opts);
216
- }
217
- throw new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected');
218
- }
219
- const payload = {
220
- room_id: self.roomId,
221
- action_type: actionType,
222
- action_data: actionData
223
- };
224
- if (nextTurn) payload.next_turn = nextTurn;
225
- return self._emitAction(payload, true);
226
- });
227
- };
228
-
229
- /**
230
- * @private Emit game:action and handle the ack. On NOT_IN_ROOM (the server
231
- * detected a detached socket — connected but no room membership), auto-
232
- * rejoin + resync once and retry the same action, so a move made in the
233
- * detached window is delivered instead of silently lost.
234
- */
235
- game._emitAction = function(payload, retryOnNotInRoom) {
236
- const self = this;
237
- if (!self.socket || !self.connected) {
238
- return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
239
- }
240
- return emitGameWithAck(self.socket, 'game:action', payload)
241
- .then(function(response) {
242
- if (response.error) {
243
- const ue = toUsionError(response);
244
- if (retryOnNotInRoom && ue.code === ERROR_CODES.NOT_IN_ROOM) {
245
- return self._autoRejoin()
246
- .then(function() { return self._emitAction(payload, false); });
247
- }
248
- throw ue;
249
- }
250
- if (response.sequence !== undefined) self._lastSequence = response.sequence;
251
- return response;
252
- });
253
- };
254
-
255
- /**
256
- * @private Recover a detached socket: the server said we're not in the
257
- * Socket.IO room (NOT_IN_ROOM), so rejoin + resync exactly like the
258
- * post-reconnect path, gating action() sends on _rejoinPromise meanwhile.
259
- */
260
- game._autoRejoin = function() {
261
- const self = this;
262
- if (self._rejoinPromise) return self._rejoinPromise;
263
- if (!self.roomId || !self.socket || !self.connected) return Promise.resolve();
264
- Usion.log('Server reports socket not in room - auto-rejoining ' + self.roomId);
265
- const resumeSequence = self._lastSequence || 0;
266
- self._joined = false;
267
- self._joinPromise = null;
268
- self._rejoinPromise = self.join(self.roomId)
269
- .then(function() {
270
- self.requestSync(resumeSequence);
271
- })
272
- .catch(function(err) {
273
- Usion.log('Auto-rejoin failed: ' + (err && err.message ? err.message : String(err)));
274
- })
275
- .then(function() {
276
- self._rejoinPromise = null;
277
- if (self._flushOfflineQueue) self._flushOfflineQueue();
278
- });
279
- return self._rejoinPromise;
280
- };
281
-
282
- // ── Offline action queue (opt-in via action(..., { queueOffline: true })) ──
283
-
284
- const OFFLINE_QUEUE_MAX = 20;
285
-
286
- /** @private Hold an action until the connection recovers. */
287
- game._queueOfflineAction = function(actionType, actionData, opts) {
288
- const self = this;
289
- if (!self._offlineQueue) self._offlineQueue = [];
290
- if (self._offlineQueue.length >= OFFLINE_QUEUE_MAX) {
291
- return Promise.reject(new UsionError(ERROR_CODES.QUEUE_FULL,
292
- 'Offline action queue is full (' + OFFLINE_QUEUE_MAX + ')'));
293
- }
294
- Usion.log('Queued action while offline: ' + actionType);
295
- return new Promise(function(resolve, reject) {
296
- self._offlineQueue.push({
297
- actionType: actionType,
298
- actionData: actionData,
299
- opts: Object.assign({}, opts, { queueOffline: false }),
300
- resolve: resolve,
301
- reject: reject,
302
- });
303
- self._ensureOfflineFlushHook();
304
- });
305
- };
306
-
307
- /** @private Flush queued actions, in order, once reconnected. */
308
- game._ensureOfflineFlushHook = function() {
309
- const self = this;
310
- if (self._offlineFlushHooked) return;
311
- self._offlineFlushHooked = true;
312
- self.on('reconnect', function() { self._flushOfflineQueue(); });
313
- };
314
-
315
- /** @private */
316
- game._flushOfflineQueue = function() {
317
- const self = this;
318
- const queue = self._offlineQueue;
319
- if (!queue || !queue.length) return Promise.resolve();
320
- if (self._offlineFlushPromise) return self._offlineFlushPromise;
321
- if (!self.connected || (!self._useProxy && !self.directMode && !self._joined)) {
322
- return Promise.resolve();
323
- }
324
- Usion.log('Flushing ' + queue.length + ' queued action(s) after reconnect');
325
-
326
- function sendNext() {
327
- if (!queue.length) return Promise.resolve();
328
- if (!self.connected || (!self._useProxy && !self.directMode && !self._joined)) {
329
- return Promise.resolve();
330
- }
331
-
332
- const item = queue[0];
333
- return self.action(item.actionType, item.actionData, item.opts).then(function(result) {
334
- if (queue[0] === item) queue.shift();
335
- item.resolve(result);
336
- return sendNext();
337
- }, function(err) {
338
- const ue = toUsionError(err);
339
- // Preserve only commands known not to have reached a live room.
340
- if (ue.code === ERROR_CODES.NOT_CONNECTED || ue.code === ERROR_CODES.NOT_IN_ROOM) {
341
- return;
342
- }
343
- if (queue[0] === item) queue.shift();
344
- item.reject(err);
345
- return sendNext();
346
- });
347
- }
348
-
349
- const flushPromise = Promise.resolve().then(sendNext);
350
- self._offlineFlushPromise = flushPromise;
351
- function clearFlush() {
352
- if (self._offlineFlushPromise === flushPromise) self._offlineFlushPromise = null;
353
- }
354
- flushPromise.then(clearFlush, clearFlush);
355
- return flushPromise;
356
- };
357
-
358
- /**
359
- * Checkpoint the authoritative game state on the server. Any client that
360
- * joins or rejoins the room receives the latest checkpoint as game_state
361
- * in the join ack and in game:sync — recovery becomes "load checkpoint,
362
- * replay the tail" instead of replaying every action from zero.
363
- *
364
- * Any participant in the room may call this (not just the host) — the
365
- * server only requires that you're in player_ids. This keeps the snapshot
366
- * fresh even while the host is backgrounded; the host-authority pattern
367
- * (only the host calls setState) still works for games that prefer it. The
368
- * serialized state is capped at 64 KB.
369
- *
370
- * @param {*} state - JSON-serializable authoritative game state
371
- * @returns {Promise<{success: boolean, error?: string}>}
372
- */
373
- game.setState = function(state) {
374
- const self = this;
375
-
376
- if (self.directMode) {
377
- // Direct-mode game servers own their state; no platform checkpoint.
378
- return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode', code: ERROR_CODES.UNSUPPORTED });
379
- }
380
-
381
- // The checkpoint carries the action sequence this state reflects. The
382
- // server persists it and rejects OLDER checkpoints (STALE_STATE), so two
383
- // concurrent writers can't clobber newer state with older.
384
- const checkpointSeq = self._lastSequence || 0;
385
-
386
- if (self._useProxy) {
387
- return Usion._request('GAME_SET_STATE', { room_id: self.roomId, state: state || {}, sequence: checkpointSeq })
388
- .then(function(res) {
389
- if (res && res.error) {
390
- const rue = toUsionError(res);
391
- return { success: false, error: rue.message, code: rue.code };
392
- }
393
- return res || { success: true };
394
- })
395
- .catch(function(err) {
396
- const ue = toUsionError(err, ERROR_CODES.REQUEST_TIMEOUT);
397
- return { success: false, error: ue.message, code: ue.code };
398
- });
399
- }
400
-
401
- if (!self.socket || !self.connected) {
402
- return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
403
- }
404
- return emitGameWithAck(self.socket, 'game:set_state', {
405
- room_id: self.roomId,
406
- state: state || {},
407
- sequence: checkpointSeq
408
- }).then(function(response) {
409
- if (response.error) {
410
- const ue = toUsionError(response);
411
- return { success: false, error: ue.message, code: ue.code };
412
- }
413
- return Object.keys(response).length ? response : { success: true };
414
- });
415
- };
416
-
417
- /**
418
- * Send a real-time game update (fire-and-forget).
419
- * @param {string} actionType - Type of action
420
- * @param {object} actionData - Action data
421
- */
422
- game.realtime = function(actionType, actionData) {
423
- const self = this;
424
-
425
- if (self.directMode) {
426
- self._sendDirect('input', {
427
- action_type: actionType,
428
- action_data: actionData || {}
429
- });
430
- return;
431
- }
432
-
433
- if (self._useProxy) {
434
- Usion._post({ type: 'GAME_REALTIME', room_id: self.roomId, action_type: actionType, action_data: actionData });
435
- return;
436
- }
437
-
438
- if (!self.socket || !self.connected) {
439
- return;
440
- }
441
-
442
- // Still fire-and-forget for the game, but the server now acks failures
443
- // (previously dropped silently): surface them via onError, and on
444
- // NOT_IN_ROOM (detached socket) auto-rejoin so the stream recovers.
445
- self.socket.emit('game:realtime', {
446
- room_id: self.roomId,
447
- action_type: actionType,
448
- action_data: actionData
449
- }, function(response) {
450
- if (!response || !response.error) return;
451
- const ue = toUsionError(response);
452
- self._dispatch('error', { code: ue.code, message: ue.message, source: 'realtime' });
453
- if (ue.code === ERROR_CODES.NOT_IN_ROOM) self._autoRejoin();
454
- });
455
- };
456
-
457
- /**
458
- * Request game state sync (for reconnection)
459
- * @param {number} lastSequence - Last known sequence number
460
- */
461
- game.requestSync = function(lastSequence) {
462
- const self = this;
463
- lastSequence = lastSequence !== undefined ? lastSequence : self._lastSequence;
464
-
465
- if (self.directMode) {
466
- self._sendDirect('ping', { last_sequence: lastSequence || 0 });
467
- return;
468
- }
469
-
470
- if (self._useProxy && self.roomId) {
471
- Usion._post({ type: 'GAME_SYNC_REQUEST', room_id: self.roomId, last_sequence: lastSequence || 0 });
472
- return;
473
- }
474
-
475
- if (self.socket && self.connected && self.roomId) {
476
- self.socket.emit('game:sync_request', {
477
- room_id: self.roomId,
478
- last_sequence: lastSequence || 0
479
- });
480
- }
481
- };
482
-
483
- /**
484
- * Request a rematch
485
- */
486
- game.requestRematch = function() {
487
- const self = this;
488
-
489
- if (self.directMode) {
490
- self._sendDirect('rematch', {});
491
- return;
492
- }
493
-
494
- if (self._useProxy && self.roomId) {
495
- Usion._post({ type: 'GAME_REMATCH', room_id: self.roomId });
496
- return;
497
- }
498
-
499
- if (self.socket && self.connected && self.roomId) {
500
- self.socket.emit('game:rematch', { room_id: self.roomId });
501
- }
502
- };
503
-
504
- /**
505
- * Forfeit the current game
506
- * @returns {Promise}
507
- */
508
- game.forfeit = function() {
509
- const self = this;
510
-
511
- if (self.directMode) {
512
- self._sendDirect('forfeit', {});
513
- return Promise.resolve({ success: true });
514
- }
515
-
516
- if (self._useProxy) {
517
- Usion._post({ type: 'GAME_FORFEIT', room_id: self.roomId });
518
- return Promise.resolve({ success: true });
519
- }
520
-
521
- if (!self.socket || !self.connected) {
522
- return Promise.reject(new UsionError(ERROR_CODES.NOT_CONNECTED, 'Not connected'));
523
- }
524
- return emitGameWithAck(self.socket, 'game:forfeit', { room_id: self.roomId })
525
- .then(function(response) {
526
- if (response.error) {
527
- throw toUsionError(response);
528
- }
529
- return response;
530
- });
531
- };
532
-
533
- /**
534
- * Invite friends to play in your room — like asking for money, but for players.
535
- *
536
- * Opens the host's friend/group picker (recent chats + search any user by
537
- * username + your groups, multi-select). Everyone you pick gets a game-invite
538
- * card in their chat; anyone who taps it joins THIS room and your game
539
- * receives `onPlayerJoined`.
540
- *
541
- * Works for any multiplayer-capable game. If the game was opened solo (from
542
- * Explore / the Game hub) with no room yet, the host creates one with you as
543
- * host and this method joins you to it — so register `onPlayerJoined` before
544
- * or right after calling invite(). Capacity is bounded by the game's
545
- * `max_players`; the picker caps selection at the remaining seats.
546
- *
547
- * Embedded feature (the host renders the picker). Standalone resolves
548
- * `{ success: false }`. Never rejects.
549
- *
550
- * @param {{ maxPlayers?: number, timeout?: number }} [opts]
551
- * @returns {Promise<{ success: boolean, roomId: string|null, invited: string[] }>}
552
- */
553
- game.invite = function(opts) {
554
- const self = this;
555
- opts = opts || {};
556
-
557
- const embedded = typeof window !== 'undefined' &&
558
- (!!window.ReactNativeWebView ||
559
- (!!window.parent && window.parent !== window));
560
-
561
- const currentRoom = self.roomId || (Usion.config && Usion.config.roomId) || null;
562
-
563
- if (!embedded) {
564
- try { console.warn('[Usion] game.invite needs the Usion app; resolving as not sent.'); } catch (e) { /* noop */ }
565
- return Promise.resolve({ success: false, roomId: currentRoom, invited: [] });
566
- }
567
-
568
- const reqData = { roomId: currentRoom };
569
- if (typeof opts.maxPlayers === 'number' && opts.maxPlayers > 0) {
570
- reqData.maxPlayers = opts.maxPlayers;
571
- }
572
-
573
- // Long timeout — the user may sit in the picker. Never reject: a dropped
574
- // result must not throw inside the game (mirrors permissions.request).
575
- return Usion._request('GAME_INVITE_REQUEST', reqData, opts.timeout || 120000)
576
- .then(function(res) {
577
- res = res || {};
578
- const roomId = res.roomId || currentRoom || null;
579
- const result = {
580
- success: !!res.success,
581
- roomId: roomId,
582
- invited: Array.isArray(res.invited) ? res.invited : [],
583
- };
584
- if (!result.success || !roomId) return result;
585
- // Ensure the inviter is connected + joined to the room (as host) so
586
- // they get onPlayerJoined as invitees arrive. Idempotent when the game
587
- // is already in this room; invites were sent by the host regardless.
588
- return Promise.resolve()
589
- .then(function() { return self.connect(); })
590
- .then(function() { return self.join(roomId); })
591
- .then(function() { return result; })
592
- .catch(function() { return result; });
593
- })
594
- .catch(function() {
595
- return { success: false, roomId: currentRoom, invited: [] };
596
- });
597
- };
598
-
599
- /**
600
- * Disconnect from the game socket
601
- */
602
- game.disconnect = function() {
603
- const self = this;
604
-
605
- // Always clear heartbeat
606
- if (self._heartbeatInterval) {
607
- clearInterval(self._heartbeatInterval);
608
- self._heartbeatInterval = null;
609
- }
610
-
611
- if (self.directMode) {
612
- if (self.directSocket) {
613
- try { self.directSocket.close(); } catch (e) {}
614
- }
615
- self.directSocket = null;
616
- self.connected = false;
617
- self.roomId = null;
618
- self._lastSequence = 0;
619
- self._connecting = false;
620
- self._connectPromise = null;
621
- self._joined = false;
622
- self._joinPromise = null;
623
- self.directMode = false;
624
- self.directConfig = null;
625
- self._directSeq = 0;
626
- return;
627
- }
628
-
629
- if (self._useProxy) {
630
- Usion._post({ type: 'GAME_DISCONNECT' });
631
- self.connected = false;
632
- self.roomId = null;
633
- self._lastSequence = 0;
634
- self._connecting = false;
635
- self._connectPromise = null;
636
- self._joined = false;
637
- self._joinPromise = null;
638
- self._useProxy = false;
639
- return;
640
- }
641
-
642
- if (self.socket) {
643
- self.socket.disconnect();
644
- self.socket = null;
645
- self.connected = false;
646
- self.roomId = null;
647
- self._lastSequence = 0;
648
- self._connecting = false;
649
- self._connectPromise = null;
650
- self._joined = false;
651
- self._joinPromise = null;
652
- }
653
- };
654
-
655
- // ───────────────────────────────────────────────────────────
656
- // Cross-reload state persistence
657
- // ───────────────────────────────────────────────────────────
658
- // When a mini-app's iframe is unmounted and later re-mounted (e.g. the
659
- // user navigates back to the chat and re-opens the game from the same
660
- // room), the entire JS context is destroyed. Server-side room state is
661
- // preserved, but anything the game holds in memory — board state, phase,
662
- // whose turn it is, placement choices — is lost. The platform sync
663
- // mechanism only replays raw actions; reconstructing client-visible
664
- // state from a zero baseline is fragile or impossible.
665
- //
666
- // These helpers give every game a uniform way to snapshot whatever it
667
- // needs to localStorage. Keys are scoped to (player_id, room_id) so a
668
- // single browser can hold independent state for different rooms or
669
- // accounts without collision, and "play a different match in the same
670
- // room" naturally collides — which is the correct outcome.
671
-
672
- const STATE_KEY_PREFIX = '_usion_game_state:';
673
-
674
- function _stateKey(self) {
675
- const rid = self.roomId || (Usion.config && Usion.config.roomId);
676
- const pid = self.playerId
677
- || (Usion.user && typeof Usion.user.getId === 'function' && Usion.user.getId())
678
- || (Usion.config && Usion.config.userId);
679
- if (!rid || !pid) return null;
680
- return STATE_KEY_PREFIX + pid + ':' + rid;
681
- }
682
-
683
- /**
684
- * Persist arbitrary JSON-serializable game state across iframe reloads.
685
- * The mini-app decides the schema; the SDK only stores/retrieves.
686
- * @param {*} state - Any JSON-serializable value
687
- * @returns {boolean} true if saved, false if not (no room/player yet, or storage error)
688
- */
689
- game.saveState = function(state) {
690
- const self = this;
691
- const key = _stateKey(self);
692
- if (!key) return false;
693
- try {
694
- localStorage.setItem(key, JSON.stringify({ state: state, savedAt: Date.now() }));
695
- return true;
696
- } catch (e) {
697
- // Quota exceeded, private-mode rejection, etc. — non-fatal.
698
- return false;
699
- }
700
- };
701
-
702
- /**
703
- * Retrieve previously-saved state for the current (player, room).
704
- * @returns {*} The saved state value, or null if none / unreadable.
705
- */
706
- game.loadState = function() {
707
- const self = this;
708
- const key = _stateKey(self);
709
- if (!key) return null;
710
- try {
711
- const raw = localStorage.getItem(key);
712
- if (!raw) return null;
713
- const parsed = JSON.parse(raw);
714
- return parsed && parsed.state !== undefined ? parsed.state : null;
715
- } catch (e) {
716
- return null;
717
- }
718
- };
719
-
720
- /**
721
- * Drop any persisted state for the current (player, room).
722
- * Call this when the game ends or starts fresh, so the next iframe
723
- * mount in the same room doesn't pick up stale data.
724
- */
725
- game.clearState = function() {
726
- const self = this;
727
- const key = _stateKey(self);
728
- if (!key) return;
729
- try { localStorage.removeItem(key); } catch (e) { /* non-fatal */ }
730
- };
731
-
732
- /**
733
- * Forward a debug snapshot to the parent platform. The platform renders
734
- * it in a top-right overlay when the iframe host is opened with
735
- * `?debug=1`. The payload schema is up to the game — anything JSON-
736
- * serializable. No-op when not running inside an iframe.
737
- *
738
- * Games should call this at every meaningful state transition (turn
739
- * change, action sent, action received, sync, phase change, etc.) so
740
- * the overlay reflects live state.
741
- *
742
- * @param {object} payload - Arbitrary JSON-serializable debug data
743
- */
744
- game.debug = function(payload) {
745
- try {
746
- // Must work in both web iframes (window.parent !== window) and
747
- // React Native WebView (window.parent === window, but a host bridge
748
- // exists at window.ReactNativeWebView). Usion._post handles routing
749
- // for both; this guard just avoids no-op work in standalone pages.
750
- var inFrame = window.parent && window.parent !== window;
751
- var inRNWebView = !!window.ReactNativeWebView;
752
- if (inFrame || inRNWebView) {
753
- var body = Object.assign({}, payload || {});
754
- body._diag = Usion.diagnostics ? Usion.diagnostics() : undefined;
755
- Usion._post({ type: 'GAME_DEBUG', payload: body });
756
- }
757
- } catch (e) { /* non-fatal */ }
758
- };
759
-
760
- /**
761
- * Whether this app was launched in multiplayer mode (opened from a game
762
- * invite in a chat) rather than single-player (opened from Explore / the
763
- * Game hub). Convenience wrapper over Usion.getLaunchParams().mode — use it
764
- * to branch setup, e.g. skip matchmaking and run solo when false.
765
- * @returns {boolean}
766
- */
767
- game.isMultiplayer = function() {
768
- return Usion.getLaunchParams().mode === 'multiplayer';
769
- };
770
-
771
- /**
772
- * Get connection status
773
- * @returns {boolean}
774
- */
775
- game.isConnected = function() {
776
- if (this.directMode) {
777
- return !!(this.connected && this.directSocket && this.directSocket.readyState === WebSocket.OPEN);
778
- }
779
- if (this._useProxy) return !!this.connected;
780
- return !!(this.connected && this.socket && this.socket.connected);
781
- };
782
- }