@usions/sdk 2.24.1 → 3.0.0-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +45 -277
  2. package/dist/browser.global.js +1972 -0
  3. package/dist/browser.global.js.map +1 -0
  4. package/dist/index.d.ts +337 -0
  5. package/dist/index.js +1955 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/testing.d.ts +23 -0
  8. package/dist/testing.js +63 -0
  9. package/dist/testing.js.map +1 -0
  10. package/dist/types-G075L8Nl.d.ts +83 -0
  11. package/package.json +27 -43
  12. package/src/browser.js +0 -6665
  13. package/src/index.js +0 -10
  14. package/src/modules/back-button.js +0 -26
  15. package/src/modules/backend-channel.js +0 -109
  16. package/src/modules/bot.js +0 -52
  17. package/src/modules/chat.js +0 -35
  18. package/src/modules/cloud.js +0 -67
  19. package/src/modules/core.js +0 -424
  20. package/src/modules/errors.js +0 -120
  21. package/src/modules/file-storage.js +0 -46
  22. package/src/modules/game-core.js +0 -278
  23. package/src/modules/game-direct.js +0 -267
  24. package/src/modules/game-methods.js +0 -753
  25. package/src/modules/game-netcode.js +0 -349
  26. package/src/modules/game-proxy.js +0 -182
  27. package/src/modules/game-reliability.js +0 -278
  28. package/src/modules/game-resilience.js +0 -245
  29. package/src/modules/game-socket.js +0 -212
  30. package/src/modules/index.js +0 -78
  31. package/src/modules/leaderboard.js +0 -46
  32. package/src/modules/lobby.js +0 -103
  33. package/src/modules/matchmaking.js +0 -140
  34. package/src/modules/misc.js +0 -152
  35. package/src/modules/netcode/binary.js +0 -113
  36. package/src/modules/netcode/delta.js +0 -236
  37. package/src/modules/netcode/index.js +0 -43
  38. package/src/modules/netcode/interest-grid.js +0 -227
  39. package/src/modules/netcode/interpolation.js +0 -235
  40. package/src/modules/netcode/lagcomp.js +0 -104
  41. package/src/modules/netcode/lockstep.js +0 -103
  42. package/src/modules/netcode/mesh-network.js +0 -103
  43. package/src/modules/netcode/mesh.js +0 -188
  44. package/src/modules/netcode/netsim.js +0 -77
  45. package/src/modules/netcode/ping.js +0 -69
  46. package/src/modules/netcode/prediction.js +0 -113
  47. package/src/modules/netcode/sender.js +0 -102
  48. package/src/modules/netcode/webtransport.js +0 -195
  49. package/src/modules/notify.js +0 -70
  50. package/src/modules/permissions.js +0 -157
  51. package/src/modules/results.js +0 -34
  52. package/src/modules/session.js +0 -62
  53. package/src/modules/storage.js +0 -64
  54. package/src/modules/ui.js +0 -111
  55. package/src/modules/user.js +0 -61
  56. package/src/modules/wallet.js +0 -253
  57. package/types/browser.d.ts +0 -5
  58. package/types/index.d.ts +0 -1306
@@ -1,278 +0,0 @@
1
- /**
2
- * Usion SDK Game Reliability — the reconnection-lifecycle surface promised in
3
- * v2.16: sequence getters, the unified connection-state machine, and
4
- * syncedState (reconnect-safe authoritative shared state).
5
- *
6
- * Everything here rides the events the game module already dispatches
7
- * ('disconnect' / 'reconnect' / 'joined' / 'sync' / 'action'), so it behaves
8
- * identically across the socket, embedded-proxy, and direct transports.
9
- */
10
-
11
- export function applyGameReliability(game, Usion) {
12
- // ── Sequence getters ──────────────────────────────────────────────────────
13
-
14
- /** Highest action sequence seen (from joins, syncs, and live actions). */
15
- game.getLastSequence = function () { return this._lastSequence || 0; };
16
-
17
- /** Highest action sequence applied locally; trails while catching up. */
18
- game.getLastAppliedSequence = function () { return this._lastActionApplied || 0; };
19
-
20
- // ── Connection-state machine ──────────────────────────────────────────────
21
- // connected → disconnected → rejoining → reconnected → connected.
22
- // 'reconnected' is a transient notification state: observers see it, then
23
- // the machine settles back to 'connected' in the same tick.
24
-
25
- game._connState = 'disconnected';
26
- game._awaitResync = false;
27
-
28
- game._setConnState = function (state) {
29
- if (this._connState === state) return;
30
- this._connState = state;
31
- this._dispatch('connectionState', state);
32
- };
33
-
34
- /** Current connection state, synchronously. */
35
- game.getConnectionState = function () { return this._connState; };
36
-
37
- /**
38
- * Observe connection-state transitions — one hook to drive a
39
- * "Reconnecting…" overlay and gate input, identical on every transport.
40
- * Single handler (last wins); returns an unsubscribe fn. For multiple
41
- * listeners use game.on('connectionState', cb).
42
- */
43
- game.onConnectionState = function (callback) { return this._setHandler('connectionState', callback); };
44
-
45
- /**
46
- * Fires once per reconnect, after the resync completes, with
47
- * { state, lastSequence, viaSync }. Restore local state here — it does NOT
48
- * fire for a manually-requested sync.
49
- */
50
- game.onReconnected = function (callback) { return this._setHandler('reconnected', callback); };
51
-
52
- game.on('disconnect', function () {
53
- game._awaitResync = false;
54
- game._setConnState('disconnected');
55
- });
56
-
57
- game.on('reconnect', function () {
58
- if (game.roomId) {
59
- game._awaitResync = true;
60
- game._setConnState('rejoining');
61
- } else {
62
- game._setConnState('connected');
63
- }
64
- });
65
-
66
- game.on('sync', function (data) {
67
- if (!game._awaitResync) return;
68
- game._awaitResync = false;
69
- game._dispatch('reconnected', {
70
- state: (data && data.game_state) || null,
71
- lastSequence: game._lastSequence || 0,
72
- viaSync: true,
73
- });
74
- game._setConnState('reconnected');
75
- game._setConnState('connected');
76
- });
77
-
78
- // Transport-level connects (initial connect in every mode) resolve through
79
- // connect()/connectDirect() — reflect them in the state machine.
80
- function wrapConnect(name) {
81
- var orig = game[name];
82
- if (typeof orig !== 'function') return;
83
- game[name] = function () {
84
- var self = this;
85
- return orig.apply(self, arguments).then(function (result) {
86
- if (!self._awaitResync) self._setConnState('connected');
87
- return result;
88
- });
89
- };
90
- }
91
- wrapConnect('connect');
92
- wrapConnect('connectDirect');
93
-
94
- // ── Host tracking ─────────────────────────────────────────────────────────
95
- // Kept on the game module (registered at module creation, so it never
96
- // misses an event) — a syncedState created AFTER the join still knows who
97
- // the authority is.
98
-
99
- game._hostId = null;
100
- function trackHost(d) {
101
- if (!d) return;
102
- if (d.host_id) game._hostId = d.host_id;
103
- else if (d.player_ids && d.player_ids.length) game._hostId = d.player_ids[0];
104
- }
105
- game.on('joined', trackHost);
106
- game.on('playerJoined', trackHost);
107
-
108
- // ── syncedState ───────────────────────────────────────────────────────────
109
-
110
- /**
111
- * Reconnect-safe authoritative shared state. Commits are sequenced actions
112
- * applied through `reduce` on every client in the same order (deduped by
113
- * sequence); the authority (player_ids[0] by default) auto-checkpoints via
114
- * setState, and (re)joining clients recover automatically (checkpoint +
115
- * un-checkpointed tail). Degrades to local-apply in direct mode.
116
- * Full contract: SyncedStateOptions / SyncedState in types/index.d.ts.
117
- */
118
- game.syncedState = function (initial, opts) {
119
- opts = opts || {};
120
- var self = this;
121
- var reduce = typeof opts.reduce === 'function'
122
- ? opts.reduce
123
- : function (state, action) { return Object.assign({}, state, action.data); };
124
- var checkpointEvery = opts.checkpointEvery != null ? opts.checkpointEvery : 1;
125
- var authorityMode = opts.authority === 'all' ? 'all' : 'host';
126
- var defaultType = opts.type || 'update';
127
-
128
- var state = initial === undefined ? {} : initial;
129
- var appliedSeq = 0;
130
- var sinceCheckpoint = 0;
131
- var lastGapRequest = -1;
132
- var changeCbs = [];
133
- var offs = [];
134
-
135
- function notify(reason) {
136
- var copy = changeCbs.slice();
137
- for (var i = 0; i < copy.length; i++) {
138
- try { copy[i](state, reason); } catch (e) { Usion.log('syncedState onChange error: ' + e.message); }
139
- }
140
- }
141
-
142
- function isAuthority() {
143
- if (authorityMode === 'all') return true;
144
- var me = self.playerId || (Usion.user && Usion.user.getId && Usion.user.getId());
145
- return !!(me && self._hostId && me === self._hostId);
146
- }
147
-
148
- function doCheckpoint() {
149
- if (self.directMode) {
150
- return Promise.resolve({ success: false, error: 'not_supported_in_direct_mode' });
151
- }
152
- // The wrapper carries the sequence the checkpoint reflects, so recovery
153
- // knows exactly where the un-checkpointed tail starts.
154
- return self.setState({ __usionSyncedState: 1, seq: appliedSeq, state: state });
155
- }
156
-
157
- function maybeAutoCheckpoint() {
158
- if (!(checkpointEvery > 0) || !isAuthority()) return;
159
- sinceCheckpoint += 1;
160
- if (sinceCheckpoint >= checkpointEvery) {
161
- sinceCheckpoint = 0;
162
- doCheckpoint();
163
- }
164
- }
165
-
166
- function applyOne(playerId, type, data, sequence) {
167
- if (sequence !== undefined && sequence <= appliedSeq) return false; // dedupe
168
- var next;
169
- try {
170
- next = reduce(state, { playerId: playerId, type: type, data: data, sequence: sequence });
171
- } catch (e) {
172
- Usion.log('syncedState reduce error: ' + e.message);
173
- return false;
174
- }
175
- if (next !== undefined) state = next;
176
- if (sequence !== undefined) appliedSeq = sequence;
177
- return true;
178
- }
179
-
180
- function onAction(d) {
181
- if (!d) return;
182
- if (applyOne(d.player_id, d.action_type, d.action_data, d.sequence)) {
183
- notify('action');
184
- maybeAutoCheckpoint();
185
- }
186
- }
187
-
188
- // Recover from a join ack or sync payload: load the checkpoint (if it is
189
- // ours and newer), replay the action tail in order, and if the server's
190
- // sequence is still ahead of us, ask once for the missing range.
191
- function recover(d) {
192
- if (!d) return;
193
- var changed = false;
194
-
195
- var gs = d.game_state;
196
- if (gs && gs.__usionSyncedState && typeof gs.seq === 'number'
197
- && gs.seq >= appliedSeq && gs.state !== undefined) {
198
- state = gs.state;
199
- appliedSeq = gs.seq;
200
- changed = true;
201
- }
202
-
203
- var actions = d.actions;
204
- if (actions && actions.length) {
205
- var sorted = actions.slice().sort(function (a, b) {
206
- return (a.sequence || 0) - (b.sequence || 0);
207
- });
208
- for (var i = 0; i < sorted.length; i++) {
209
- var item = sorted[i];
210
- if (item && applyOne(item.player_id, item.action_type, item.action_data, item.sequence)) {
211
- changed = true;
212
- }
213
- }
214
- }
215
-
216
- if (changed) notify('recover');
217
-
218
- // Gap fill: the checkpoint may lag the room sequence (checkpointEvery>1).
219
- // Request the tail from OUR applied sequence — once per position, so a
220
- // trimmed history can't loop us.
221
- if (d.sequence !== undefined && d.sequence > appliedSeq && lastGapRequest !== appliedSeq) {
222
- lastGapRequest = appliedSeq;
223
- try { self.requestSync(appliedSeq); } catch (e) { /* non-fatal */ }
224
- }
225
- }
226
-
227
- offs.push(self.on('action', onAction));
228
- offs.push(self.on('sync', recover));
229
- offs.push(self.on('joined', recover));
230
-
231
- return {
232
- /** Current state value. */
233
- get: function () { return state; },
234
-
235
- /**
236
- * Commit a change: commit(data) with the default action type, or
237
- * commit(type, data, opts) to name it (opts forwarded to game.action,
238
- * e.g. nextTurn / queueOffline). Applied exactly once via the echo.
239
- */
240
- commit: function (typeOrData, data, actionOpts) {
241
- var t, payload, o;
242
- if (typeof typeOrData === 'string') { t = typeOrData; payload = data; o = actionOpts; }
243
- else { t = defaultType; payload = typeOrData; o = data; }
244
- if (self.directMode) {
245
- // No platform echo in direct mode — apply locally, then send.
246
- if (applyOne(self.playerId, t, payload, undefined)) notify('action');
247
- return self.action(t, payload, o);
248
- }
249
- return self.action(t, payload, o);
250
- },
251
-
252
- /** Subscribe to changes: cb(state, reason). Returns an unsubscribe fn. */
253
- onChange: function (cb) {
254
- changeCbs.push(cb);
255
- return function () {
256
- var i = changeCbs.indexOf(cb);
257
- if (i >= 0) changeCbs.splice(i, 1);
258
- };
259
- },
260
-
261
- /** Whether this client is the checkpointing authority. */
262
- isAuthority: isAuthority,
263
-
264
- /** Force a server checkpoint now (no-op result in direct mode). */
265
- checkpoint: function () { return doCheckpoint(); },
266
-
267
- /** Sequence of the last action applied into this state. */
268
- getSequence: function () { return appliedSeq; },
269
-
270
- /** Detach all listeners; the instance stops receiving updates. */
271
- destroy: function () {
272
- for (var i = 0; i < offs.length; i++) { try { offs[i](); } catch (e) { /* noop */ } }
273
- offs.length = 0;
274
- changeCbs.length = 0;
275
- },
276
- };
277
- };
278
- }
@@ -1,245 +0,0 @@
1
- /**
2
- * Usion SDK Game Resilience (SDK >= 2.24) - direct-mode liveness watchdog,
3
- * token-reuse fast reconnect, input backpressure, and network stats/quality.
4
- * State lives on game._res; game-direct.js calls the small _res* hooks here.
5
- * Relay mode gets getNetworkStats()/onNetworkQuality() too (quality from the
6
- * connection-state machine; no relay RTT measurement in this module).
7
- */
8
-
9
- /** @typedef {{probeAfterMs: number, deadAfterMs: number}} LivenessCfg */
10
-
11
- /** @param {any} game @param {any} Usion */
12
- export function applyGameResilience(game, Usion) {
13
- var res = {
14
- liveness: /** @type {LivenessCfg|null} */ ({ probeAfterMs: 4000, deadAfterMs: 12000 }),
15
- backpressureBytes: 8192,
16
- lastInboundAt: 0,
17
- lastProbeAt: 0,
18
- lastCloseCode: /** @type {number|null} */ (null),
19
- declaredDead: false,
20
- watchdogTimer: /** @type {*} */ (null),
21
- drainTimer: /** @type {*} */ (null),
22
- pendingInput: /** @type {*} */ (null),
23
- visHandler: /** @type {*} */ (null),
24
- lastVisResyncAt: 0,
25
- wrappedDisconnect: false,
26
- rtt: /** @type {number|null} */ (null),
27
- jitter: 0,
28
- quality: 'dead',
29
- };
30
- game._res = res;
31
-
32
- /** EWMA (a=0.3) over ping->pong RTT samples. @param {number} sample */
33
- function feedRtt(sample) {
34
- if (!(sample >= 0)) return;
35
- if (res.rtt == null) { res.rtt = sample; res.jitter = 0; return; }
36
- res.jitter += 0.3 * (Math.abs(sample - res.rtt) - res.jitter);
37
- res.rtt += 0.3 * (sample - res.rtt);
38
- }
39
-
40
- function measuredRtt() { // game.ping() samples count too (any transport)
41
- if (res.rtt != null) return { rtt: res.rtt, jitter: res.jitter };
42
- var m = game._pingMeter;
43
- return m && m.rtt != null ? { rtt: m.rtt, jitter: m.jitter } : { rtt: null, jitter: null };
44
- }
45
-
46
- function computeQuality() {
47
- var state = game.getConnectionState ? game.getConnectionState()
48
- : (game.connected ? 'connected' : 'disconnected');
49
- if (res.declaredDead || state === 'disconnected') return 'dead';
50
- if (game.directMode && (!game.directSocket || game.directSocket.readyState !== 1)) return 'dead';
51
- var rtt = measuredRtt().rtt || 0;
52
- var age = (game.directMode && res.lastInboundAt) ? Date.now() - res.lastInboundAt : 0;
53
- return (rtt < 150 && age < 2000) ? 'good' : (rtt < 400 && age < 5000) ? 'fair' : 'poor';
54
- }
55
-
56
- /** Dispatches networkQuality on TRANSITIONS only. */
57
- function evaluate() {
58
- var q = computeQuality();
59
- if (q === res.quality) return;
60
- var prev = res.quality;
61
- res.quality = q;
62
- game._dispatch('networkQuality', { quality: q, prev: prev, stats: game.getNetworkStats() });
63
- }
64
-
65
- /** Cheap snapshot of tracked connection-health numbers. */
66
- game.getNetworkStats = function () {
67
- var direct = !!game.directMode;
68
- var s = direct ? game.directSocket : null;
69
- var m = measuredRtt();
70
- return {
71
- transport: direct ? 'direct' : 'relay',
72
- connectionState: game.getConnectionState ? game.getConnectionState() : 'disconnected',
73
- quality: res.quality,
74
- rtt: m.rtt,
75
- jitter: m.jitter,
76
- lastInboundAgeMs: (direct && res.lastInboundAt) ? Math.max(0, Date.now() - res.lastInboundAt) : null,
77
- bufferedAmount: s ? (s.bufferedAmount || 0) : null,
78
- };
79
- };
80
-
81
- /** Quality transitions ({quality, prev, stats}); returns unsubscribe. @param {Function} callback */
82
- game.onNetworkQuality = function (callback) { return game._setHandler('networkQuality', callback); };
83
-
84
- function stopWatchdog() {
85
- if (res.watchdogTimer) { clearInterval(res.watchdogTimer); res.watchdogTimer = null; }
86
- }
87
-
88
- /** One plain RTT ping ({t}) - never {last_sequence} (that is a resync). */
89
- function sendProbe() {
90
- var s = game.directSocket;
91
- if (!s || s.readyState !== 1) return;
92
- var now = Date.now();
93
- var w = /** @type {any} */ (function () {}); // stats-only pong waiter
94
- w.sentAt = now;
95
- w.statsOnly = true;
96
- game._pongWaiters.push(w);
97
- res.lastProbeAt = now;
98
- game._sendDirect('ping', { t: now });
99
- }
100
-
101
- function watchdogTick() {
102
- var s = game.directSocket;
103
- if (!game.directMode || !s || s.readyState !== 1) { stopWatchdog(); return; }
104
- if (res.liveness) {
105
- var age = Date.now() - res.lastInboundAt;
106
- if (age >= res.liveness.deadAfterMs) {
107
- // Silent-dead: declare + close; the onclose path then reconnects.
108
- res.declaredDead = true;
109
- stopWatchdog();
110
- Usion.log('Direct socket liveness timeout - declaring dead');
111
- evaluate();
112
- game._dispatch('disconnect', 'liveness_timeout');
113
- try { s.close(); } catch (e) { /* noop */ }
114
- return;
115
- }
116
- if (age >= res.liveness.probeAfterMs
117
- && Date.now() - res.lastProbeAt >= res.liveness.probeAfterMs) sendProbe();
118
- }
119
- evaluate();
120
- }
121
-
122
- /** connectDirect(config) options -> clamped _res settings. @param {any} config */
123
- game._resConfigure = function (config) {
124
- if (config.liveness === false) {
125
- res.liveness = null;
126
- } else {
127
- var lv = (config.liveness && typeof config.liveness === 'object') ? config.liveness : {};
128
- var probe = isFinite(lv.probeAfterMs) ? Math.max(1000, lv.probeAfterMs) : 4000;
129
- var dead = isFinite(lv.deadAfterMs) ? lv.deadAfterMs : 12000;
130
- res.liveness = { probeAfterMs: probe, deadAfterMs: Math.max(dead, probe + 2000) };
131
- }
132
- if (config.backpressureBytes === false || config.backpressureBytes === 0) res.backpressureBytes = 0;
133
- else if (typeof config.backpressureBytes === 'number' && config.backpressureBytes > 0) res.backpressureBytes = config.backpressureBytes;
134
- };
135
-
136
- /** Direct socket opened: reset state, start watchdog + foreground resync. */
137
- game._resOnOpen = function () {
138
- res.declaredDead = false;
139
- res.lastCloseCode = null;
140
- res.lastInboundAt = Date.now();
141
- res.lastProbeAt = 0;
142
- stopWatchdog();
143
- res.watchdogTimer = setInterval(watchdogTick, 1000);
144
- addVisibility();
145
- if (!res.wrappedDisconnect) { // clear timers even if onclose never fires
146
- res.wrappedDisconnect = true;
147
- var orig = game.disconnect;
148
- game.disconnect = function () { teardown(); return orig.apply(game, arguments); };
149
- }
150
- evaluate();
151
- };
152
-
153
- /** @param {any} evt CloseEvent - code kept for the token-reuse decision. */
154
- game._resOnClose = function (evt) {
155
- res.lastCloseCode = (evt && typeof evt.code === 'number') ? evt.code : null;
156
- teardown();
157
- evaluate();
158
- };
159
-
160
- /** Pong: feed the stats EWMA from the matched waiter. @param {any} waiter */
161
- game._resOnPong = function (waiter) {
162
- if (waiter && typeof waiter.sentAt === 'number') feedRtt(Date.now() - waiter.sentAt);
163
- evaluate();
164
- };
165
-
166
- /** Reuse the cached room token on reconnect while safely un-expired. */
167
- game._resCanReuseToken = function () {
168
- if (res.lastCloseCode === 4401) return false; // auth reject -> refetch
169
- var cfg = game.directConfig;
170
- if (!cfg || !cfg.ws_url || !cfg.access_token) return false;
171
- var exp = parseExpiry(cfg.expires_at);
172
- return exp != null && exp - Date.now() > 30000;
173
- };
174
-
175
- /**
176
- * Backpressure for realtime 'input' frames: while the send buffer is above
177
- * the threshold hold the LATEST frame only; drain when it clears.
178
- * @param {any} payload @returns {boolean} true = held, don't send now
179
- */
180
- game._resHoldInput = function (payload) {
181
- if (!res.backpressureBytes) return false;
182
- var s = game.directSocket;
183
- if (!s || (res.pendingInput == null && !(s.bufferedAmount > res.backpressureBytes))) return false;
184
- res.pendingInput = payload; // latest-only: newer input replaces stale
185
- if (!res.drainTimer) res.drainTimer = setTimeout(drainInput, 50);
186
- return true;
187
- };
188
-
189
- function drainInput() {
190
- res.drainTimer = null;
191
- var s = game.directSocket;
192
- if (!s || s.readyState !== 1) { res.pendingInput = null; return; }
193
- if (res.pendingInput == null) return;
194
- if (s.bufferedAmount > res.backpressureBytes) { res.drainTimer = setTimeout(drainInput, 50); return; }
195
- var p = res.pendingInput;
196
- res.pendingInput = null;
197
- game._sendDirect('input', p);
198
- }
199
-
200
- /** Defensive expires_at parse (ISO or epoch); null = doubt -> refetch. @param {*} v */
201
- function parseExpiry(v) {
202
- if (typeof v === 'number' && isFinite(v)) return v > 1e12 ? v : v * 1000;
203
- if (typeof v === 'string' && v) {
204
- var t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(v) ? v : v + 'Z'); // bare ISO = UTC
205
- return isNaN(t) ? null : t;
206
- }
207
- return null;
208
- }
209
-
210
- function teardown() {
211
- stopWatchdog();
212
- if (res.drainTimer) { clearTimeout(res.drainTimer); res.drainTimer = null; }
213
- res.pendingInput = null;
214
- removeVisibility();
215
- if (game._pongWaiters && game._pongWaiters.length) {
216
- game._pongWaiters = game._pongWaiters.filter(function (/** @type {any} */ w) { return !w.statsOnly; });
217
- }
218
- }
219
-
220
- /** Foreground: probe immediately + throttled requestSync. */
221
- function addVisibility() {
222
- if (typeof document === 'undefined' || !document.addEventListener || res.visHandler) return;
223
- res.visHandler = function () {
224
- if (document.visibilityState !== 'visible' || !game.directMode || !game._joined) return;
225
- sendProbe();
226
- var now = Date.now();
227
- if (now - res.lastVisResyncAt >= 2000) {
228
- res.lastVisResyncAt = now;
229
- try { game.requestSync(game._lastSequence || 0); } catch (e) { /* non-fatal */ }
230
- }
231
- };
232
- document.addEventListener('visibilitychange', res.visHandler);
233
- }
234
-
235
- function removeVisibility() {
236
- if (res.visHandler && typeof document !== 'undefined' && document.removeEventListener) {
237
- document.removeEventListener('visibilitychange', res.visHandler);
238
- }
239
- res.visHandler = null;
240
- }
241
-
242
- // Re-evaluate quality on connection events (covers relay mode too).
243
- game.on('disconnect', evaluate);
244
- game.on('connectionState', evaluate);
245
- }