@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.
- 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 +25 -46
- package/src/browser.js +0 -6725
- 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-ack.js +0 -32
- package/src/modules/game-core.js +0 -278
- package/src/modules/game-direct.js +0 -267
- package/src/modules/game-methods.js +0 -782
- package/src/modules/game-netcode.js +0 -349
- package/src/modules/game-proxy.js +0 -184
- package/src/modules/game-reliability.js +0 -278
- package/src/modules/game-resilience.js +0 -245
- package/src/modules/game-socket.js +0 -214
- 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 -1308
package/src/modules/game-core.js
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Game Core — game module base, connect routing, event registrations
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { applyGameDirect } from './game-direct.js';
|
|
6
|
-
import { applyGameResilience } from './game-resilience.js';
|
|
7
|
-
import { applyGameSocket } from './game-socket.js';
|
|
8
|
-
import { applyGameProxy } from './game-proxy.js';
|
|
9
|
-
import { applyGameMethods } from './game-methods.js';
|
|
10
|
-
import { applyGameNetcode } from './game-netcode.js';
|
|
11
|
-
import { applyGameReliability } from './game-reliability.js';
|
|
12
|
-
|
|
13
|
-
// Map any reasonable spelling of a game event onto the internal handler
|
|
14
|
-
// name: 'game:player_joined' / 'player_joined' / 'playerJoined' → 'playerJoined'.
|
|
15
|
-
const _EVENT_ALIASES = {
|
|
16
|
-
joined: 'joined',
|
|
17
|
-
player_joined: 'playerJoined',
|
|
18
|
-
player_left: 'playerLeft',
|
|
19
|
-
player_connection: 'playerConnection',
|
|
20
|
-
state: 'stateUpdate',
|
|
21
|
-
state_update: 'stateUpdate',
|
|
22
|
-
sync: 'sync',
|
|
23
|
-
action: 'action',
|
|
24
|
-
realtime: 'realtime',
|
|
25
|
-
finished: 'finished',
|
|
26
|
-
restarted: 'restarted',
|
|
27
|
-
error: 'error',
|
|
28
|
-
rematch_request: 'rematchRequest',
|
|
29
|
-
disconnect: 'disconnect',
|
|
30
|
-
reconnect: 'reconnect',
|
|
31
|
-
connection_error: 'connectionError',
|
|
32
|
-
room_assigned: 'roomAssigned',
|
|
33
|
-
connection_state: 'connectionState',
|
|
34
|
-
reconnected: 'reconnected',
|
|
35
|
-
network_quality: 'networkQuality',
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
function _normalizeEventName(event) {
|
|
39
|
-
let name = String(event || '');
|
|
40
|
-
if (name.indexOf('game:') === 0) name = name.slice(5);
|
|
41
|
-
if (_EVENT_ALIASES[name]) return _EVENT_ALIASES[name];
|
|
42
|
-
// camelCase passthrough ('playerJoined', 'stateUpdate', …)
|
|
43
|
-
const snake = name.replace(/([A-Z])/g, function(m) { return '_' + m.toLowerCase(); });
|
|
44
|
-
return _EVENT_ALIASES[snake] || name;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Create the game module with all sub-modules applied
|
|
49
|
-
* @param {object} Usion - Reference to the main Usion object
|
|
50
|
-
*/
|
|
51
|
-
export function createGameModule(Usion) {
|
|
52
|
-
const game = {
|
|
53
|
-
socket: null,
|
|
54
|
-
directSocket: null,
|
|
55
|
-
roomId: null,
|
|
56
|
-
playerId: null,
|
|
57
|
-
connected: false,
|
|
58
|
-
directMode: false,
|
|
59
|
-
directConfig: null,
|
|
60
|
-
_directSeq: 0,
|
|
61
|
-
_eventHandlers: {},
|
|
62
|
-
_lastSequence: 0,
|
|
63
|
-
_connecting: false,
|
|
64
|
-
_connectPromise: null,
|
|
65
|
-
_joined: false,
|
|
66
|
-
_joinPromise: null,
|
|
67
|
-
_useProxy: false,
|
|
68
|
-
_proxyListenerSetup: false,
|
|
69
|
-
_heartbeatInterval: null,
|
|
70
|
-
_pingMeter: null,
|
|
71
|
-
_pongWaiters: [],
|
|
72
|
-
// Reliability state: highest action sequence already delivered to the
|
|
73
|
-
// game (duplicate echoes/replays are dropped), and the in-flight rejoin
|
|
74
|
-
// promise that gates action() sends right after a reconnect.
|
|
75
|
-
_lastActionApplied: 0,
|
|
76
|
-
_rejoinPromise: null,
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* Connect to the game socket server
|
|
80
|
-
* @param {string} socketUrl - Socket.IO server URL (optional, uses config)
|
|
81
|
-
* @param {string} token - JWT auth token (optional, uses user.getToken())
|
|
82
|
-
* @returns {Promise} Resolves when connected
|
|
83
|
-
*/
|
|
84
|
-
connect: function(socketUrl, token) {
|
|
85
|
-
const self = this;
|
|
86
|
-
var connectionMode = (Usion.config && Usion.config.connectionMode) || 'platform';
|
|
87
|
-
if (connectionMode === 'direct') {
|
|
88
|
-
return self.connectDirect();
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// If already connected (direct or proxy), return immediately
|
|
92
|
-
if (self._useProxy && self.connected) {
|
|
93
|
-
return Promise.resolve();
|
|
94
|
-
}
|
|
95
|
-
if (self.socket && self.connected) {
|
|
96
|
-
return Promise.resolve();
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// If currently connecting, return the existing promise
|
|
100
|
-
if (self._connecting && self._connectPromise) {
|
|
101
|
-
return self._connectPromise;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// When running inside an iframe or WebView, use parent as socket proxy
|
|
105
|
-
// (checked BEFORE token validation — iframe games don't need a token)
|
|
106
|
-
var isInFrame = !!window.__USION_PROXY__
|
|
107
|
-
|| window.parent !== window
|
|
108
|
-
|| !!window.ReactNativeWebView
|
|
109
|
-
|| !!Usion._isEmbedded;
|
|
110
|
-
|
|
111
|
-
if (isInFrame) {
|
|
112
|
-
Usion.log('Running in iframe \u2013 using parent app as socket proxy');
|
|
113
|
-
return self._connectViaProxy();
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// Use config values as defaults (only for direct socket connections)
|
|
117
|
-
socketUrl = socketUrl || Usion.config.socketUrl;
|
|
118
|
-
token = token || Usion.user.getToken();
|
|
119
|
-
|
|
120
|
-
if (!socketUrl) {
|
|
121
|
-
return Promise.reject(new Error('No socket URL provided'));
|
|
122
|
-
}
|
|
123
|
-
if (!token) {
|
|
124
|
-
return Promise.reject(new Error('No auth token available'));
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
self._connecting = true;
|
|
128
|
-
self._connectPromise = new Promise(function(resolve, reject) {
|
|
129
|
-
// Check if socket.io-client is available
|
|
130
|
-
if (typeof io === 'undefined') {
|
|
131
|
-
// Load the Socket.IO client: same-origin copy first, then the
|
|
132
|
-
// platform-hosted copy (same origin as the SDK itself — reachable
|
|
133
|
-
// wherever the app is), and only then the public CDN, which
|
|
134
|
-
// restricted networks often block.
|
|
135
|
-
var sources = [
|
|
136
|
-
'/socket.io.min.js',
|
|
137
|
-
'https://usions.com/socket.io.min.js',
|
|
138
|
-
'https://cdn.socket.io/4.7.2/socket.io.min.js'
|
|
139
|
-
];
|
|
140
|
-
(function tryLoad(i) {
|
|
141
|
-
if (i >= sources.length) {
|
|
142
|
-
self._connecting = false;
|
|
143
|
-
reject(new Error('Failed to load Socket.IO client'));
|
|
144
|
-
return;
|
|
145
|
-
}
|
|
146
|
-
var script = document.createElement('script');
|
|
147
|
-
script.src = sources[i];
|
|
148
|
-
script.onload = function() {
|
|
149
|
-
self._initSocket(socketUrl, token, resolve, reject);
|
|
150
|
-
};
|
|
151
|
-
script.onerror = function() {
|
|
152
|
-
tryLoad(i + 1);
|
|
153
|
-
};
|
|
154
|
-
document.head.appendChild(script);
|
|
155
|
-
})(0);
|
|
156
|
-
} else {
|
|
157
|
-
self._initSocket(socketUrl, token, resolve, reject);
|
|
158
|
-
}
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
return self._connectPromise;
|
|
162
|
-
},
|
|
163
|
-
|
|
164
|
-
// Event handler registrations.
|
|
165
|
-
//
|
|
166
|
-
// Each onX(cb) keeps the long-standing "single handler, last one wins"
|
|
167
|
-
// behavior for back-compat, but now ALSO returns an unsubscribe
|
|
168
|
-
// function. For multiple listeners use game.on(event, cb), which
|
|
169
|
-
// supports any number of listeners, works before connect() in every
|
|
170
|
-
// transport, and returns an unsubscribe function.
|
|
171
|
-
onJoined: function(callback) { return this._setHandler('joined', callback); },
|
|
172
|
-
onPlayerJoined: function(callback) { return this._setHandler('playerJoined', callback); },
|
|
173
|
-
onPlayerLeft: function(callback) { return this._setHandler('playerLeft', callback); },
|
|
174
|
-
onStateUpdate: function(callback) { return this._setHandler('stateUpdate', callback); },
|
|
175
|
-
onSync: function(callback) { return this._setHandler('sync', callback); },
|
|
176
|
-
onAction: function(callback) { return this._setHandler('action', callback); },
|
|
177
|
-
onRealtime: function(callback) { return this._setHandler('realtime', callback); },
|
|
178
|
-
onGameFinished: function(callback) { return this._setHandler('finished', callback); },
|
|
179
|
-
onGameRestarted: function(callback) { return this._setHandler('restarted', callback); },
|
|
180
|
-
onError: function(callback) { return this._setHandler('error', callback); },
|
|
181
|
-
onRematchRequest: function(callback) { return this._setHandler('rematchRequest', callback); },
|
|
182
|
-
onDisconnect: function(callback) { return this._setHandler('disconnect', callback); },
|
|
183
|
-
onReconnect: function(callback) { return this._setHandler('reconnect', callback); },
|
|
184
|
-
onConnectionError: function(callback) { return this._setHandler('connectionError', callback); },
|
|
185
|
-
onPlayerConnection: function(callback) { return this._setHandler('playerConnection', callback); },
|
|
186
|
-
// Fired when the host assigns this app a room AFTER launch (the user opened
|
|
187
|
-
// the game solo, then shared it — see GAME_ROOM_ASSIGNED). The SDK has
|
|
188
|
-
// already updated config.roomId and is connecting+joining; use this to flip
|
|
189
|
-
// a solo game into its multiplayer/hosting UI. onJoined fires right after.
|
|
190
|
-
onRoomAssigned: function(callback) { return this._setHandler('roomAssigned', callback); },
|
|
191
|
-
|
|
192
|
-
/** @private Set the single legacy handler; returns an unsubscribe fn. */
|
|
193
|
-
_setHandler: function(name, callback) {
|
|
194
|
-
const self = this;
|
|
195
|
-
self._eventHandlers[name] = callback;
|
|
196
|
-
return function() {
|
|
197
|
-
if (self._eventHandlers[name] === callback) {
|
|
198
|
-
self._eventHandlers[name] = null;
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
},
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* @private Deliver an event to the legacy single handler and every
|
|
205
|
-
* game.on() listener. All game event delivery flows through here.
|
|
206
|
-
*/
|
|
207
|
-
_dispatch: function(name) {
|
|
208
|
-
const args = Array.prototype.slice.call(arguments, 1);
|
|
209
|
-
const single = this._eventHandlers[name];
|
|
210
|
-
if (single) {
|
|
211
|
-
try { single.apply(null, args); } catch (e) { Usion.log('game handler error (' + name + '): ' + e.message); }
|
|
212
|
-
}
|
|
213
|
-
const list = this._listeners[name];
|
|
214
|
-
if (list && list.length) {
|
|
215
|
-
const copy = list.slice();
|
|
216
|
-
for (let i = 0; i < copy.length; i++) {
|
|
217
|
-
try { copy[i].apply(null, args); } catch (e) { Usion.log('game listener error (' + name + '): ' + e.message); }
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
},
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Register an additional event listener. Unlike the onX methods this
|
|
224
|
-
* supports multiple listeners per event, can be called before
|
|
225
|
-
* connect(), and works in every transport (standalone, embedded
|
|
226
|
-
* proxy, direct). Accepts internal names ('action'), wire names
|
|
227
|
-
* ('game:action'), or snake_case ('player_joined').
|
|
228
|
-
* @param {string} event - Event name
|
|
229
|
-
* @param {function} callback - Handler function
|
|
230
|
-
* @returns {function} Unsubscribe function
|
|
231
|
-
*/
|
|
232
|
-
on: function(event, callback) {
|
|
233
|
-
const self = this;
|
|
234
|
-
const name = _normalizeEventName(event);
|
|
235
|
-
if (!self._listeners[name]) self._listeners[name] = [];
|
|
236
|
-
self._listeners[name].push(callback);
|
|
237
|
-
return function() {
|
|
238
|
-
const list = self._listeners[name];
|
|
239
|
-
if (!list) return;
|
|
240
|
-
const i = list.indexOf(callback);
|
|
241
|
-
if (i >= 0) list.splice(i, 1);
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
|
|
246
|
-
game._listeners = {};
|
|
247
|
-
|
|
248
|
-
// Apply sub-modules
|
|
249
|
-
applyGameDirect(game, Usion);
|
|
250
|
-
// Direct-mode liveness/backpressure + network stats (hooks into game-direct).
|
|
251
|
-
applyGameResilience(game, Usion);
|
|
252
|
-
applyGameSocket(game, Usion);
|
|
253
|
-
applyGameProxy(game, Usion);
|
|
254
|
-
applyGameMethods(game, Usion);
|
|
255
|
-
applyGameNetcode(game, Usion);
|
|
256
|
-
// Applied last: wraps connect/connectDirect and rides dispatched events.
|
|
257
|
-
applyGameReliability(game, Usion);
|
|
258
|
-
|
|
259
|
-
// Foreground catch-up safety net (generic across every transport).
|
|
260
|
-
//
|
|
261
|
-
// When a page/iframe is backgrounded its JS is suspended: timers freeze and
|
|
262
|
-
// relayed actions can be missed (postMessage to a frozen WebView). A brief
|
|
263
|
-
// app-switch may also never trip a socket disconnect/reconnect, so the game's
|
|
264
|
-
// onReconnect handler never fires and it silently misses moves made while it
|
|
265
|
-
// was away — leaving turn state behind and the table deadlocked. On every
|
|
266
|
-
// return to visibility, if we're in a room, request a sync so the game
|
|
267
|
-
// deterministically catches up. Per the action reliability contract, onSync
|
|
268
|
-
// is deduped by sequence, so an unnecessary resync is a no-op.
|
|
269
|
-
if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
|
|
270
|
-
document.addEventListener('visibilitychange', function() {
|
|
271
|
-
if (document.visibilityState !== 'visible') return;
|
|
272
|
-
if (!game.roomId) return;
|
|
273
|
-
try { game.requestSync(); } catch (e) { /* non-fatal */ }
|
|
274
|
-
});
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
return game;
|
|
278
|
-
}
|
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Usion SDK Game Direct — WebSocket direct connection to game server
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Add direct WebSocket connection methods to game module
|
|
7
|
-
* @param {object} game - The game module object
|
|
8
|
-
* @param {object} Usion - Reference to the main Usion object
|
|
9
|
-
*/
|
|
10
|
-
export function applyGameDirect(game, Usion) {
|
|
11
|
-
/**
|
|
12
|
-
* Connect directly to creator-controlled WebSocket server.
|
|
13
|
-
* Uses backend-issued short-lived room token.
|
|
14
|
-
* @returns {Promise}
|
|
15
|
-
*/
|
|
16
|
-
game.connectDirect = function(config) {
|
|
17
|
-
var self = this;
|
|
18
|
-
config = config || {};
|
|
19
|
-
|
|
20
|
-
if (self.directMode && self.directSocket && self.connected) {
|
|
21
|
-
return Promise.resolve();
|
|
22
|
-
}
|
|
23
|
-
if (self._connecting && self._connectPromise) {
|
|
24
|
-
return self._connectPromise;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
|
|
28
|
-
self._connecting = true;
|
|
29
|
-
self.directMode = true;
|
|
30
|
-
self._autoReconnect = config.autoReconnect !== undefined
|
|
31
|
-
? config.autoReconnect
|
|
32
|
-
: !(Usion.config && Usion.config.autoReconnect === false);
|
|
33
|
-
self._connectPromise = self._fetchDirectAccess(config)
|
|
34
|
-
.then(function(access) {
|
|
35
|
-
self.directConfig = access;
|
|
36
|
-
return self._initDirectSocket(access);
|
|
37
|
-
})
|
|
38
|
-
.then(function() {
|
|
39
|
-
self.connected = true;
|
|
40
|
-
self._connecting = false;
|
|
41
|
-
Usion.log('Direct game socket connected');
|
|
42
|
-
})
|
|
43
|
-
.catch(function(err) {
|
|
44
|
-
self._connecting = false;
|
|
45
|
-
self.connected = false;
|
|
46
|
-
self.directMode = false;
|
|
47
|
-
self._dispatch('connectionError', err);
|
|
48
|
-
throw err;
|
|
49
|
-
});
|
|
50
|
-
return self._connectPromise;
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
game._fetchDirectAccess = function(config) {
|
|
54
|
-
var roomId = config.roomId || this.roomId || Usion.config.roomId;
|
|
55
|
-
var serviceId = config.serviceId || Usion.config.serviceId;
|
|
56
|
-
var apiUrl = config.apiUrl || Usion.config.apiUrl || '';
|
|
57
|
-
var token = config.token || Usion.user.getToken();
|
|
58
|
-
|
|
59
|
-
if (!roomId) return Promise.reject(new Error('No room ID provided'));
|
|
60
|
-
if (!serviceId) return Promise.reject(new Error('No service ID provided'));
|
|
61
|
-
|
|
62
|
-
this.roomId = roomId;
|
|
63
|
-
this.playerId = Usion.user.getId();
|
|
64
|
-
|
|
65
|
-
// When embedded (iframe/WebView), proxy through parent app to avoid
|
|
66
|
-
// CORS / Private Network Access issues
|
|
67
|
-
if (Usion._isEmbedded) {
|
|
68
|
-
return Usion._request('GAME_ACCESS_REQUEST', {
|
|
69
|
-
room_id: roomId,
|
|
70
|
-
service_id: serviceId,
|
|
71
|
-
protocol_version: (config.protocolVersion || Usion.config.protocolVersion || Usion.config.protocol_version || '2')
|
|
72
|
-
}, 10000);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
if (!apiUrl) return Promise.reject(new Error('No API URL provided'));
|
|
76
|
-
if (!token) return Promise.reject(new Error('No auth token available'));
|
|
77
|
-
|
|
78
|
-
var cleanApiUrl = String(apiUrl).replace(/\/$/, '');
|
|
79
|
-
var endpoint = cleanApiUrl + '/games/rooms/' + encodeURIComponent(roomId) + '/access';
|
|
80
|
-
return fetch(endpoint, {
|
|
81
|
-
method: 'POST',
|
|
82
|
-
headers: {
|
|
83
|
-
'Content-Type': 'application/json',
|
|
84
|
-
'Authorization': 'Bearer ' + token
|
|
85
|
-
},
|
|
86
|
-
body: JSON.stringify({
|
|
87
|
-
service_id: serviceId,
|
|
88
|
-
client_type: 'iframe',
|
|
89
|
-
protocol_version: (config.protocolVersion || Usion.config.protocolVersion || Usion.config.protocol_version || '2')
|
|
90
|
-
})
|
|
91
|
-
}).then(function(res) {
|
|
92
|
-
if (!res.ok) {
|
|
93
|
-
return res.text().then(function(text) {
|
|
94
|
-
throw new Error(text || ('Direct access failed: HTTP ' + res.status));
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
return res.json();
|
|
98
|
-
});
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
game._initDirectSocket = function(access) {
|
|
102
|
-
var self = this;
|
|
103
|
-
return new Promise(function(resolve, reject) {
|
|
104
|
-
if (!access || !access.ws_url || !access.access_token) {
|
|
105
|
-
reject(new Error('Invalid direct access payload'));
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
var wsUrl = access.ws_url;
|
|
110
|
-
var separator = wsUrl.indexOf('?') === -1 ? '?' : '&';
|
|
111
|
-
var urlWithToken = wsUrl + separator + 'token=' + encodeURIComponent(access.access_token);
|
|
112
|
-
var ws = new WebSocket(urlWithToken);
|
|
113
|
-
self.directSocket = ws;
|
|
114
|
-
|
|
115
|
-
var opened = false;
|
|
116
|
-
var joinSent = false;
|
|
117
|
-
var timeout = setTimeout(function() {
|
|
118
|
-
if (!opened) {
|
|
119
|
-
try { ws.close(); } catch (e) {}
|
|
120
|
-
reject(new Error('Direct WebSocket connection timeout'));
|
|
121
|
-
}
|
|
122
|
-
}, 10000);
|
|
123
|
-
|
|
124
|
-
ws.onopen = function() {
|
|
125
|
-
opened = true;
|
|
126
|
-
clearTimeout(timeout);
|
|
127
|
-
if (!joinSent) {
|
|
128
|
-
joinSent = true;
|
|
129
|
-
self._sendDirect('join', {});
|
|
130
|
-
}
|
|
131
|
-
// Start heartbeat for direct mode
|
|
132
|
-
if (self._heartbeatInterval) clearInterval(self._heartbeatInterval);
|
|
133
|
-
self._heartbeatInterval = setInterval(function() {
|
|
134
|
-
if (self.directSocket && self.directSocket.readyState === WebSocket.OPEN) {
|
|
135
|
-
self._sendDirect('heartbeat', {});
|
|
136
|
-
}
|
|
137
|
-
}, 25000);
|
|
138
|
-
if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
|
|
139
|
-
resolve();
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
ws.onerror = function() {
|
|
143
|
-
if (!opened) {
|
|
144
|
-
clearTimeout(timeout);
|
|
145
|
-
reject(new Error('Direct WebSocket connection error'));
|
|
146
|
-
}
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
ws.onclose = function(evt) {
|
|
150
|
-
if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
|
|
151
|
-
self.connected = false;
|
|
152
|
-
self._joined = false;
|
|
153
|
-
self._joinPromise = null;
|
|
154
|
-
if (self._heartbeatInterval) {
|
|
155
|
-
clearInterval(self._heartbeatInterval);
|
|
156
|
-
self._heartbeatInterval = null;
|
|
157
|
-
}
|
|
158
|
-
self._dispatch('disconnect', evt && evt.reason ? evt.reason : 'direct socket closed');
|
|
159
|
-
// Seamless resume: if the drop wasn't an intentional disconnect()
|
|
160
|
-
// (which clears directMode), transparently re-establish + re-join +
|
|
161
|
-
// resync from the last sequence.
|
|
162
|
-
if (self.directMode && self._autoReconnect !== false) self._scheduleDirectReconnect();
|
|
163
|
-
};
|
|
164
|
-
|
|
165
|
-
ws.onmessage = function(evt) {
|
|
166
|
-
if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
|
|
167
|
-
self._handleDirectMessage(evt && evt.data);
|
|
168
|
-
};
|
|
169
|
-
});
|
|
170
|
-
};
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Reconnect a dropped direct-mode socket with capped exponential backoff,
|
|
174
|
-
* then re-join the room and request a resync (Dota-style "fetch latest
|
|
175
|
-
* snapshot = instant rejoin"). Keeps retrying while still in directMode.
|
|
176
|
-
* @private
|
|
177
|
-
*/
|
|
178
|
-
game._scheduleDirectReconnect = function() {
|
|
179
|
-
var self = this;
|
|
180
|
-
if (self._reconnecting) return;
|
|
181
|
-
self._reconnecting = true;
|
|
182
|
-
var attempt = self._reconnectAttempt || 0;
|
|
183
|
-
var go = function() {
|
|
184
|
-
if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
|
|
185
|
-
attempt += 1;
|
|
186
|
-
self._reconnectAttempt = attempt;
|
|
187
|
-
// Reuse the cached room token while valid (skips the access round trip).
|
|
188
|
-
var reuse = self._resCanReuseToken && self._resCanReuseToken();
|
|
189
|
-
(reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
|
|
190
|
-
.then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
|
|
191
|
-
.then(function() {
|
|
192
|
-
self.connected = true;
|
|
193
|
-
self._reconnecting = false;
|
|
194
|
-
self._reconnectAttempt = 0;
|
|
195
|
-
self._dispatch('reconnect', attempt);
|
|
196
|
-
if (self.roomId) self.requestSync(self._lastSequence || 0); // resync / resume
|
|
197
|
-
})
|
|
198
|
-
.catch(function() {
|
|
199
|
-
if (!self.directMode) { self._reconnecting = false; return; }
|
|
200
|
-
var delay = Math.min(1000 * Math.pow(2, attempt - 1), 15000);
|
|
201
|
-
setTimeout(go, delay);
|
|
202
|
-
});
|
|
203
|
-
};
|
|
204
|
-
setTimeout(go, 100); // fast first attempt; exponential backoff after
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
game._sendDirect = function(type, payload) {
|
|
208
|
-
if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
|
|
209
|
-
// Backpressure (input frames only): hold latest while the buffer is full.
|
|
210
|
-
if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
|
|
211
|
-
this._directSeq = this._directSeq + 1;
|
|
212
|
-
this.directSocket.send(JSON.stringify({
|
|
213
|
-
type: type,
|
|
214
|
-
room_id: this.roomId,
|
|
215
|
-
ts: Date.now(),
|
|
216
|
-
seq: this._directSeq,
|
|
217
|
-
session_id: (this.directConfig && this.directConfig.session_id) ? this.directConfig.session_id : null,
|
|
218
|
-
protocol_version: (this.directConfig && this.directConfig.protocol_version) ? this.directConfig.protocol_version : '2',
|
|
219
|
-
payload: payload || {}
|
|
220
|
-
}));
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
game._handleDirectMessage = function(raw) {
|
|
224
|
-
var data;
|
|
225
|
-
try {
|
|
226
|
-
data = typeof raw === 'string' ? JSON.parse(raw) : raw;
|
|
227
|
-
} catch (e) {
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
if (!data || !data.type) return;
|
|
231
|
-
var payload = data.payload || {};
|
|
232
|
-
|
|
233
|
-
if (data.type === 'joined') {
|
|
234
|
-
this._joined = true;
|
|
235
|
-
this._dispatch('joined', payload);
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
238
|
-
if (data.type === 'player_joined') {
|
|
239
|
-
this._dispatch('playerJoined', payload);
|
|
240
|
-
return;
|
|
241
|
-
}
|
|
242
|
-
if (data.type === 'player_left') {
|
|
243
|
-
this._dispatch('playerLeft', payload);
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
if (data.type === 'state_snapshot' || data.type === 'state_delta') {
|
|
247
|
-
this._dispatch('realtime', payload);
|
|
248
|
-
this._dispatch('stateUpdate', payload);
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
if (data.type === 'pong') {
|
|
252
|
-
// Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
|
|
253
|
-
var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
|
|
254
|
-
if (this._resOnPong) this._resOnPong(waiter);
|
|
255
|
-
if (waiter) waiter();
|
|
256
|
-
this._dispatch('sync', payload);
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
if (data.type === 'match_end') {
|
|
260
|
-
this._dispatch('finished', payload);
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
if (data.type === 'error') {
|
|
264
|
-
this._dispatch('error', payload);
|
|
265
|
-
}
|
|
266
|
-
};
|
|
267
|
-
}
|