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