@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,214 +0,0 @@
1
- /**
2
- * Usion SDK Game Socket — Socket.IO connection management
3
- */
4
-
5
- /**
6
- * Add Socket.IO 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 applyGameSocket(game, Usion) {
11
- /**
12
- * Initialize socket connection
13
- * @private
14
- */
15
- game._initSocket = function(socketUrl, token, resolve, reject) {
16
- const self = this;
17
-
18
- // Prevent creating duplicate sockets
19
- if (self.socket && self.socket.connected) {
20
- self._connecting = false;
21
- resolve();
22
- return;
23
- }
24
-
25
- // Clean up any existing disconnected socket
26
- if (self.socket) {
27
- self.socket.disconnect();
28
- self.socket = null;
29
- }
30
-
31
- try {
32
- self.socket = io(socketUrl, {
33
- path: '/socket.io',
34
- transports: ['websocket', 'polling'],
35
- auth: { token: token },
36
- autoConnect: true,
37
- reconnection: true,
38
- reconnectionAttempts: 50,
39
- reconnectionDelay: 1000,
40
- reconnectionDelayMax: 10000
41
- });
42
-
43
- // Route allow-listed backend server events (lobby, etc.) to the unified
44
- // backend channel — robust to listener registration order.
45
- if (Usion._bindBackendSocket) Usion._bindBackendSocket(self.socket);
46
-
47
- // Socket.IO v4 emits 'reconnect' on the Manager, not the Socket — a
48
- // Socket-level 'reconnect' listener never fires. Track attempts on the
49
- // Manager and treat any connect after the first (per socket) as the
50
- // reconnect signal, dispatched below AFTER rejoin gating is in place.
51
- var hadConnect = false;
52
- if (self.socket.io && typeof self.socket.io.on === 'function') {
53
- self.socket.io.on('reconnect_attempt', function(n) {
54
- self._reconnAttempts = n;
55
- });
56
- }
57
-
58
- self.socket.on('connect', function() {
59
- var isReconnect = hadConnect;
60
- hadConnect = true;
61
- self.connected = true;
62
- self._connecting = false;
63
- Usion.log('Game socket connected');
64
-
65
- // Start heartbeat to keep game session alive
66
- if (self._heartbeatInterval) clearInterval(self._heartbeatInterval);
67
- self._heartbeatInterval = setInterval(function() {
68
- if (self.socket && self.connected && self.roomId) {
69
- self.socket.emit('game:heartbeat', { room_id: self.roomId });
70
- }
71
- }, 25000);
72
-
73
- // Re-join room after reconnect. The promise is kept on
74
- // _rejoinPromise so action() can gate sends until the room
75
- // membership and sync are restored — otherwise a stale move could
76
- // go out before the client has caught up.
77
- if (self.roomId) {
78
- // Join reports the server head, so capture our replay cursor first.
79
- var resumeSequence = self._lastSequence || 0;
80
- self._joined = false;
81
- self._joinPromise = null;
82
- self._rejoinPromise = self.join(self.roomId)
83
- .then(function() {
84
- Usion.log('Reconnected - joined room ' + self.roomId);
85
- self.requestSync(resumeSequence);
86
- })
87
- .catch(function(err) {
88
- Usion.log('Rejoin failed: ' + (err && err.message ? err.message : String(err)));
89
- })
90
- .then(function() {
91
- self._rejoinPromise = null;
92
- // Send any moves queued while offline, now that membership
93
- // and sync are restored. (This connect handler is the reliable
94
- // hook — see the Manager-vs-Socket note above.)
95
- if (self._flushOfflineQueue) self._flushOfflineQueue();
96
- });
97
- }
98
-
99
- // Dispatched after _rejoinPromise is set, so anything reacting to
100
- // 'reconnect' (offline-queue flush, connection-state machine) sees
101
- // sends gated behind the rejoin+resync.
102
- if (isReconnect) {
103
- Usion.log('Game socket reconnected');
104
- self._dispatch('reconnect', self._reconnAttempts || 1);
105
- self._reconnAttempts = 0;
106
- }
107
-
108
- resolve();
109
- });
110
-
111
- self.socket.on('connect_error', function(err) {
112
- self._connecting = false;
113
- Usion.log('Game socket error: ' + err.message);
114
- self._dispatch('connectionError', err);
115
- reject(err);
116
- });
117
-
118
- self.socket.on('disconnect', function(reason) {
119
- self.connected = false;
120
- self._joined = false;
121
- self._joinPromise = null;
122
- if (self._heartbeatInterval) {
123
- clearInterval(self._heartbeatInterval);
124
- self._heartbeatInterval = null;
125
- }
126
- Usion.log('Game socket disconnected: ' + reason);
127
- self._dispatch('disconnect', reason);
128
- });
129
-
130
- // Game event handlers
131
- self.socket.on('game:joined', function(data) {
132
- if (data.sequence !== undefined) {
133
- self._lastSequence = data.sequence;
134
- // Everything up to this sequence is reflected in the joined
135
- // state — actions at or below it must not be re-delivered.
136
- self._lastActionApplied = Math.max(self._lastActionApplied, data.sequence);
137
- }
138
- self._dispatch('joined', data);
139
- });
140
-
141
- self.socket.on('game:player_joined', function(data) {
142
- self._dispatch('playerJoined', data);
143
- });
144
-
145
- self.socket.on('game:player_left', function(data) {
146
- self._dispatch('playerLeft', data);
147
- });
148
-
149
- self.socket.on('game:state', function(data) {
150
- if (data.sequence !== undefined) {
151
- self._lastSequence = Math.max(self._lastSequence, data.sequence);
152
- }
153
- self._dispatch('stateUpdate', data);
154
- });
155
-
156
- self.socket.on('game:sync', function(data) {
157
- if (data.sequence !== undefined) {
158
- self._lastSequence = data.sequence;
159
- // The sync payload carries all actions up to this sequence; a
160
- // live echo of one of them must not be applied a second time.
161
- self._lastActionApplied = Math.max(self._lastActionApplied, data.sequence);
162
- }
163
- self._dispatch('sync', data);
164
- // Also trigger stateUpdate for backwards compat
165
- self._dispatch('stateUpdate', data);
166
- });
167
-
168
- self.socket.on('game:action', function(data) {
169
- if (data.sequence !== undefined) {
170
- // Drop duplicates: actions are delivered exactly once per
171
- // sequence, whether they arrive live, as the sender's own echo,
172
- // or replayed after a reconnect.
173
- if (data.sequence <= self._lastActionApplied) return;
174
- self._lastActionApplied = data.sequence;
175
- self._lastSequence = Math.max(self._lastSequence, data.sequence);
176
- }
177
- self._dispatch('action', data);
178
- });
179
-
180
- self.socket.on('game:player_connection', function(data) {
181
- self._dispatch('playerConnection', data);
182
- });
183
-
184
- self.socket.on('game:realtime', function(data) {
185
- self._dispatch('realtime', data);
186
- });
187
-
188
- self.socket.on('game:finished', function(data) {
189
- if (data.sequence !== undefined) {
190
- self._lastSequence = data.sequence;
191
- }
192
- self._dispatch('finished', data);
193
- });
194
-
195
- self.socket.on('game:error', function(data) {
196
- Usion.log('Game error: ' + (data.message || data.code));
197
- self._dispatch('error', data);
198
- });
199
-
200
- self.socket.on('game:rematch_request', function(data) {
201
- self._dispatch('rematchRequest', data);
202
- });
203
-
204
- self.socket.on('game:restarted', function(data) {
205
- self._lastSequence = 0; // Reset sequence on rematch
206
- self._lastActionApplied = 0;
207
- self._dispatch('restarted', data);
208
- });
209
-
210
- } catch (err) {
211
- reject(err);
212
- }
213
- };
214
- }
@@ -1,78 +0,0 @@
1
- /**
2
- * Usion Mini App SDK v2.1
3
- *
4
- * JavaScript utilities for Mini Apps (Iframe Games & Services)
5
- * Import via: <script src="https://usions.com/usion-sdk.js"></script>
6
- *
7
- * Features:
8
- * - User info and authentication
9
- * - Persistent storage (per-user, per-service)
10
- * - Wallet/payment integration
11
- * - Session management
12
- * - Real-time game support via Socket.IO
13
- */
14
-
15
- import { core } from './core.js';
16
- import { createUserModule } from './user.js';
17
- import { createStorageModule } from './storage.js';
18
- import { createWalletModule } from './wallet.js';
19
- import { createSessionModule } from './session.js';
20
- import { createChatModule } from './chat.js';
21
- import { createBotModule } from './bot.js';
22
- import { createResultsMethods } from './results.js';
23
- import { createBackButtonMethods } from './back-button.js';
24
- import { uiMethods } from './ui.js';
25
- import { miscMethods } from './misc.js';
26
- import { createFileStorageModule } from './file-storage.js';
27
- import { createGameModule } from './game-core.js';
28
- import { createLobbyModule } from './lobby.js';
29
- import { createLeaderboardModule } from './leaderboard.js';
30
- import { createCloudModule } from './cloud.js';
31
- import { createMatchmakingModule } from './matchmaking.js';
32
- import { createNotifyModule } from './notify.js';
33
- import { createPermissionsModule } from './permissions.js';
34
- import { applyBackendChannel } from './backend-channel.js';
35
- import { netcode } from './netcode/index.js';
36
- import { UsionError, ERROR_CODES } from './errors.js';
37
-
38
- // Build the Usion object from core
39
- const Usion = Object.assign({}, core);
40
-
41
- // Attach sub-modules (these reference Usion internally)
42
- Usion.user = createUserModule(Usion);
43
- Usion.storage = createStorageModule(Usion);
44
- Usion.wallet = createWalletModule(Usion);
45
- Usion.session = createSessionModule(Usion);
46
- Usion.chat = createChatModule(Usion);
47
- Usion.bot = createBotModule(Usion);
48
- Usion.fileStorage = createFileStorageModule(Usion);
49
- Usion.game = createGameModule(Usion);
50
- // Stable error class + codes — developers branch on err.code, not message text.
51
- Usion.UsionError = UsionError;
52
- Usion.ERROR_CODES = ERROR_CODES;
53
- // Unified backend channel (used by lobby etc.; works standalone + embedded).
54
- applyBackendChannel(Usion);
55
- Usion.lobby = createLobbyModule(Usion);
56
- Usion.leaderboard = createLeaderboardModule(Usion);
57
- Usion.cloud = createCloudModule(Usion);
58
- Usion.matchmaking = createMatchmakingModule(Usion);
59
- Usion.notify = createNotifyModule(Usion);
60
- // Permission requests (host-mediated modal; embedded feature).
61
- Usion.permissions = createPermissionsModule(Usion);
62
-
63
- // Netcode toolkit (transport-agnostic, zero-dependency).
64
- Usion.netcode = netcode;
65
-
66
- // Attach results methods directly on Usion
67
- Object.assign(Usion, createResultsMethods(Usion));
68
-
69
- // Attach back button methods directly on Usion
70
- Object.assign(Usion, createBackButtonMethods(Usion));
71
-
72
- // Attach UI utilities directly on Usion
73
- Object.assign(Usion, uiMethods);
74
-
75
- // Attach misc methods (submit, error, exit, share, log, on, requestPayment)
76
- Object.assign(Usion, miscMethods);
77
-
78
- export default Usion;
@@ -1,46 +0,0 @@
1
- /**
2
- * Usion SDK Leaderboard — scores for mini-games.
3
- *
4
- * Opt-in per game (the service must have `leaderboard.enabled`). Rides the
5
- * unified backend channel, so it works in standalone AND embedded games.
6
- *
7
- * await Usion.leaderboard.submit(1500); // your score
8
- * const friends = await Usion.leaderboard.friends(); // your accepted friends + you
9
- * const top = await Usion.leaderboard.top(); // global top N
10
- * const me = await Usion.leaderboard.me(); // { score, rank, total }
11
- *
12
- * The **friends** board is scoped to your accepted friends (the mutual-consent
13
- * friend system) plus yourself — "see my friends' record scores".
14
- * Entries: { user_id, name, avatar, score, rank, is_me, metadata }.
15
- */
16
- export function createLeaderboardModule(Usion) {
17
- function serviceId(opts) {
18
- return (opts && opts.serviceId) || (Usion.config && Usion.config.serviceId);
19
- }
20
-
21
- return {
22
- /** Submit a score (best score is kept, per the service's order config). */
23
- submit: function (score, metadata, opts) {
24
- return Usion._backendEmit('lb:submit', { service_id: serviceId(opts), score: score, metadata: metadata != null ? metadata : null });
25
- },
26
-
27
- /** Leaderboard of your accepted friends (plus you). Returns entries[]. */
28
- friends: function (opts) {
29
- opts = opts || {};
30
- return Usion._backendEmit('lb:friends', { service_id: serviceId(opts), limit: opts.limit || 50 })
31
- .then(function (r) { return (r && r.entries) || []; });
32
- },
33
-
34
- /** Global top N. Returns entries[]. */
35
- top: function (opts) {
36
- opts = opts || {};
37
- return Usion._backendEmit('lb:top', { service_id: serviceId(opts), limit: opts.limit || 20 })
38
- .then(function (r) { return (r && r.entries) || []; });
39
- },
40
-
41
- /** Your own score + global rank: { score, rank, total }. */
42
- me: function (opts) {
43
- return Usion._backendEmit('lb:me', { service_id: serviceId(opts) });
44
- },
45
- };
46
- }
@@ -1,103 +0,0 @@
1
- /**
2
- * Usion SDK Lobby — parties, ready-up, and matchmaking.
3
- *
4
- * The social rendezvous layer that game rooms can't provide: form a party by
5
- * code, ready up together, and start as a group — plus a thin wrapper over the
6
- * platform's stranger matchmaking. Rides the platform Socket.IO connection
7
- * (Usion.game.socket), so connect first with Usion.game.connect().
8
- *
9
- * const { code } = await Usion.lobby.create({ maxPlayers: 4 });
10
- * Usion.lobby.onUpdate(({ members }) => renderLobby(members));
11
- * await Usion.lobby.setReady(true);
12
- * // host, once everyone's ready: create a room then start the party in it
13
- * const room = await Usion.lobby.queue(serviceId); // or your own room API
14
- * await Usion.lobby.start(room.id);
15
- * Usion.lobby.onStarted(({ room_id }) => Usion.game.join(room_id));
16
- *
17
- * Works in every mode: it rides the unified backend channel (Usion._backendEmit
18
- * / _backendOn), which uses the SDK's own socket when standalone and relays
19
- * through the parent app when embedded (iframe/WebView).
20
- */
21
- export function createLobbyModule(Usion) {
22
- const state = { code: null, host: null, status: null, members: [] };
23
- const handlers = {};
24
- let bound = false;
25
-
26
- function bind() {
27
- if (bound) return;
28
- bound = true;
29
- Usion._backendOn('lobby:update', function (d) {
30
- state.code = d.code; state.host = d.host; state.status = d.status; state.members = d.members || [];
31
- if (handlers.update) handlers.update(d);
32
- });
33
- Usion._backendOn('lobby:started', function (d) {
34
- state.status = 'started';
35
- if (handlers.started) handlers.started(d);
36
- });
37
- }
38
-
39
- function ack(event, data) {
40
- bind();
41
- return Usion._backendEmit(event, data);
42
- }
43
-
44
- return {
45
- get state() { return state; },
46
-
47
- /** Register a handler for lobby membership/ready changes. */
48
- onUpdate: function (cb) { handlers.update = cb; bind(); },
49
- /** Register a handler for when the host starts the party. */
50
- onStarted: function (cb) { handlers.started = cb; bind(); },
51
-
52
- /** Create a party. Resolves with { code }. You become the host. */
53
- create: async function (opts) {
54
- opts = opts || {};
55
- const r = await ack('lobby:create', { max_players: opts.maxPlayers || 8, public: !!opts.public });
56
- if (r && r.code) state.code = r.code;
57
- return r;
58
- },
59
-
60
- /** Join a party by code. */
61
- join: async function (code) {
62
- const r = await ack('lobby:join', { code: String(code || '').toUpperCase() });
63
- if (r && r.code) state.code = r.code;
64
- return r;
65
- },
66
-
67
- /** Leave the current party. */
68
- leave: function () { state.code = null; return ack('lobby:leave', {}).catch(function () {}); },
69
-
70
- /** Set your ready state. */
71
- setReady: function (ready) { return ack('lobby:ready', { ready: ready !== false }); },
72
-
73
- /** True when every member is ready. */
74
- allReady: function () { return state.members.length > 0 && state.members.every(function (m) { return m.ready; }); },
75
-
76
- /** Whether the current user is the party host. */
77
- isHost: function () {
78
- const id = Usion.user && Usion.user.getId && Usion.user.getId();
79
- return !!(state.host && id && state.host === id);
80
- },
81
-
82
- /** Host: start the party in an already-created game room. */
83
- start: function (roomId) { return ack('lobby:start', { room_id: roomId }); },
84
-
85
- /**
86
- * Stranger matchmaking — find or create a game room for a service via the
87
- * platform's REST matchmaker. Resolves with the room.
88
- */
89
- queue: async function (serviceId, opts) {
90
- opts = opts || {};
91
- const apiUrl = (Usion.config && Usion.config.apiUrl) || '';
92
- const token = Usion.user && Usion.user.getToken && Usion.user.getToken();
93
- if (!apiUrl) throw new Error('No apiUrl configured');
94
- const res = await fetch(apiUrl.replace(/\/$/, '') + '/games/matchmake', {
95
- method: 'POST',
96
- headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
97
- body: JSON.stringify({ service_id: serviceId, conversation_id: opts.conversationId || ('standalone_' + serviceId) }),
98
- });
99
- if (!res.ok) throw new Error('Matchmake failed: HTTP ' + res.status);
100
- return res.json();
101
- },
102
- };
103
- }
@@ -1,140 +0,0 @@
1
- /**
2
- * Usion SDK Matchmaking — pair up with online strangers ("quick match").
3
- *
4
- * Lets a mini-app connect players who don't know each other: join a queue, and
5
- * when enough players are waiting the platform creates a room and matches you.
6
- * Rides the unified backend channel, so it works standalone AND embedded.
7
- *
8
- * const m = await Usion.matchmaking.find(); // resolves when matched
9
- * await Usion.game.connect(); await Usion.game.join(m.roomId);
10
- * // ...or bound the wait / cancel while waiting:
11
- * const m2 = await Usion.matchmaking.find(null, { timeout: 30000 });
12
- * Usion.matchmaking.cancel();
13
- * Usion.matchmaking.onMatch(({ roomId, players }) => { ... });
14
- */
15
- import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
16
-
17
- // World placement is a single backend round-trip (no queue wait), so the
18
- // bound is fixed rather than caller-supplied like find()'s opts.timeout.
19
- const WORLD_JOIN_TIMEOUT_MS = 15000;
20
-
21
- export function createMatchmakingModule(Usion) {
22
- let pending = null; // active placement entry: { resolve, reject }
23
- let onMatchCb = null;
24
- let bound = false;
25
-
26
- function normalize(d) {
27
- return { roomId: d && d.room_id, players: (d && d.player_ids) || [], serviceId: d && d.service_id };
28
- }
29
-
30
- function bind() {
31
- if (bound) return;
32
- bound = true;
33
- Usion._backendOn('mm:matched', function (d) {
34
- const r = normalize(d);
35
- if (onMatchCb) onMatchCb(r);
36
- if (pending) { const p = pending; pending = null; p.resolve(r); }
37
- });
38
- }
39
-
40
- /**
41
- * Shared mm-channel placement used by find() (queue matches) and
42
- * game.joinWorld() (world backfill): register the resolver, bound the wait,
43
- * emit mm:join, and resolve from the immediate-placement ack
44
- * ({queued:false, matched:true, room_id, player_ids}) or the mm:matched
45
- * push — whichever arrives first.
46
- * @param {object} payload - mm:join payload
47
- * @param {number} [timeout] - ms until MATCH_TIMEOUT (falsy = wait forever)
48
- * @param {string} timeoutMessage
49
- */
50
- function place(payload, timeout, timeoutMessage) {
51
- bind();
52
-
53
- if (pending) {
54
- const old = pending; pending = null;
55
- old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
56
- }
57
-
58
- let timer = null;
59
- const entry = {};
60
- const promise = new Promise(function (resolve, reject) {
61
- entry.resolve = function (r) {
62
- if (timer) clearTimeout(timer);
63
- resolve(r);
64
- };
65
- entry.reject = function (e) {
66
- if (timer) clearTimeout(timer);
67
- if (pending === entry) pending = null;
68
- reject(e);
69
- };
70
- });
71
-
72
- // Register BEFORE emitting mm:join: when someone is already waiting in
73
- // the queue, mm:matched can arrive ahead of the join ack — registering
74
- // afterwards dropped that instant match and left find() hanging forever.
75
- pending = entry;
76
-
77
- if (timeout > 0) {
78
- timer = setTimeout(function () {
79
- timer = null;
80
- Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
81
- entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
82
- timeoutMessage + timeout + 'ms'));
83
- }, timeout);
84
- }
85
-
86
- Usion._backendEmit('mm:join', payload)
87
- .then(function (ack) {
88
- // Immediate placement (world rooms): the ack itself carries the room.
89
- // The mm:matched push may still follow; pending is already cleared,
90
- // so it can't double-resolve.
91
- if (ack && ack.matched && ack.room_id && pending === entry) {
92
- pending = null;
93
- entry.resolve(normalize(ack));
94
- }
95
- })
96
- .catch(function (err) {
97
- if (pending === entry) entry.reject(toUsionError(err));
98
- });
99
-
100
- return promise;
101
- }
102
-
103
- return {
104
- /** Register a handler called whenever a match is found. */
105
- onMatch: function (cb) { onMatchCb = cb; bind(); },
106
-
107
- /**
108
- * Join the queue for `serviceId` (defaults to the current game) and resolve
109
- * when matched with { roomId, players, serviceId }. Without `opts.timeout`
110
- * it stays pending until a match (use cancel() to stop waiting); with it,
111
- * rejects MATCH_TIMEOUT (and leaves the queue) once the wait elapses.
112
- * @param {string} [serviceId]
113
- * @param {{size?: number, timeout?: number}} [opts]
114
- */
115
- find: function (serviceId, opts) {
116
- opts = opts || {};
117
- const sid = serviceId || (Usion.config && Usion.config.serviceId);
118
- return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
119
- },
120
-
121
- /**
122
- * @private SDK-internal — use Usion.game.joinWorld(). Immediate placement
123
- * into a drop-in/drop-out world room over the same mm channel.
124
- * @param {string} [serviceId]
125
- */
126
- _joinWorld: function (serviceId) {
127
- const sid = serviceId || (Usion.config && Usion.config.serviceId);
128
- return place({ service_id: sid, mode: 'world' }, WORLD_JOIN_TIMEOUT_MS, 'No world placement within ');
129
- },
130
-
131
- /** Leave the queue / stop waiting. */
132
- cancel: function () {
133
- if (pending) {
134
- const old = pending; pending = null;
135
- old.reject(new UsionError(ERROR_CODES.CANCELLED, 'cancelled'));
136
- }
137
- return Usion._backendEmit('mm:cancel', {});
138
- },
139
- };
140
- }