@ksaa-nlp/gamehub-sdk 0.1.0
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 +546 -0
- package/dist/gamehub-sdk.d.ts +694 -0
- package/dist/gamehub-sdk.js +1693 -0
- package/dist/index.d.ts +56 -0
- package/dist/index.mjs +6 -0
- package/package.json +31 -0
- package/scripts/emit-module-entry.mjs +96 -0
- package/src/api-client.ts +33 -0
- package/src/bridge.ts +312 -0
- package/src/constants.ts +24 -0
- package/src/init.ts +335 -0
- package/src/main.ts +287 -0
- package/src/match-context.ts +52 -0
- package/src/multiplayer.ts +525 -0
- package/src/session.ts +240 -0
- package/src/state.ts +78 -0
- package/src/utils.ts +68 -0
- package/tsconfig.json +33 -0
- package/types/api.ts +21 -0
- package/types/bootstrap.ts +65 -0
- package/types/match.ts +41 -0
- package/types/multiplayer.ts +118 -0
- package/types/session.ts +67 -0
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multiplayer layer: room creation/join, WebSocket connection management,
|
|
3
|
+
* reconnection, and an event emitter for game code to listen on.
|
|
4
|
+
*/
|
|
5
|
+
namespace GameHub.Multiplayer {
|
|
6
|
+
// --- Event emitter -------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Dispatch an event to per-name listeners and the wildcard (`'*'`) listeners.
|
|
10
|
+
* Handler errors are caught and logged so a buggy listener can't break the
|
|
11
|
+
* socket loop.
|
|
12
|
+
*/
|
|
13
|
+
export function emit(eventName: string, payload: any): void {
|
|
14
|
+
const handlers = GameHub.State.mpHandlers.get(eventName);
|
|
15
|
+
if (handlers) {
|
|
16
|
+
handlers.forEach((handler) => {
|
|
17
|
+
try {
|
|
18
|
+
handler(payload);
|
|
19
|
+
} catch (err) {
|
|
20
|
+
GameHub.Utils.error('Multiplayer handler error:', err);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const allHandlers = GameHub.State.mpHandlers.get('*');
|
|
26
|
+
if (allHandlers) {
|
|
27
|
+
allHandlers.forEach((handler) => {
|
|
28
|
+
try {
|
|
29
|
+
handler({ eventName, payload });
|
|
30
|
+
} catch (err) {
|
|
31
|
+
GameHub.Utils.error('Multiplayer * handler error:', err);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// --- Connection lifecycle ------------------------------------------------
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Detach listeners from the current socket and close it. Idempotent.
|
|
41
|
+
* The caller is responsible for clearing {@link GameHub.State.mpRoom} and
|
|
42
|
+
* related state — this function only touches the transport.
|
|
43
|
+
*/
|
|
44
|
+
export function clearSocket(): void {
|
|
45
|
+
const S = GameHub.State;
|
|
46
|
+
|
|
47
|
+
if (S.mpReconnectTimer) {
|
|
48
|
+
clearTimeout(S.mpReconnectTimer);
|
|
49
|
+
S.mpReconnectTimer = null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (S.mpSocket) {
|
|
53
|
+
try {
|
|
54
|
+
S.mpSocket.onopen = null;
|
|
55
|
+
S.mpSocket.onclose = null;
|
|
56
|
+
S.mpSocket.onmessage = null;
|
|
57
|
+
S.mpSocket.onerror = null;
|
|
58
|
+
S.mpSocket.close();
|
|
59
|
+
} catch {
|
|
60
|
+
// ignore
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
S.mpSocket = null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Open a WebSocket for the given join info and wire up the message/close
|
|
69
|
+
* handlers. Automatically reconnects with exponential backoff up to
|
|
70
|
+
* {@link GameHub.MP_MAX_RECONNECT_ATTEMPTS} attempts.
|
|
71
|
+
*/
|
|
72
|
+
export function connect(joinInfo: JoinInfo): void {
|
|
73
|
+
const S = GameHub.State;
|
|
74
|
+
clearSocket();
|
|
75
|
+
|
|
76
|
+
const wsBase = joinInfo.wsUrl.replace(/\/+$/, '');
|
|
77
|
+
const wsUrl =
|
|
78
|
+
wsBase +
|
|
79
|
+
'?roomToken=' +
|
|
80
|
+
encodeURIComponent(joinInfo.roomToken) +
|
|
81
|
+
'&gameSlug=' +
|
|
82
|
+
encodeURIComponent(joinInfo.gameSlug) +
|
|
83
|
+
'&sdk=2.x';
|
|
84
|
+
|
|
85
|
+
S.mpExpectedClose = false;
|
|
86
|
+
S.mpSocket = new WebSocket(wsUrl);
|
|
87
|
+
|
|
88
|
+
S.mpSocket.onopen = () => {
|
|
89
|
+
S.mpReconnectAttempts = 0;
|
|
90
|
+
emit('connected', {
|
|
91
|
+
roomCode: joinInfo.roomCode,
|
|
92
|
+
peerId: joinInfo.peerId,
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
S.mpSocket.onmessage = (event: MessageEvent) => {
|
|
97
|
+
let message: any = null;
|
|
98
|
+
try {
|
|
99
|
+
message = JSON.parse(event.data);
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (!message || !message.type) return;
|
|
105
|
+
|
|
106
|
+
if (message.type === 'system') {
|
|
107
|
+
if (message.eventName === 'room_joined') {
|
|
108
|
+
S.mpPeers.clear();
|
|
109
|
+
const peers: Peer[] = message.payload?.peers || [];
|
|
110
|
+
peers.forEach((peer) => {
|
|
111
|
+
if (peer && peer.peerId) S.mpPeers.set(peer.peerId, peer);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (message.eventName === 'peer_joined' && message.payload?.peerId) {
|
|
116
|
+
S.mpPeers.set(message.payload.peerId, message.payload);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (message.eventName === 'peer_left' && message.payload?.peerId) {
|
|
120
|
+
S.mpPeers.delete(message.payload.peerId);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (message.eventName === 'room_closed') {
|
|
124
|
+
emit('room_left', { reason: 'room_closed' });
|
|
125
|
+
clearSocket();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
emit(message.eventName, message.payload || {});
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (message.type === 'game_event') {
|
|
133
|
+
// Reentrancy guard: drop late / duplicate frames from the same peer so
|
|
134
|
+
// a reconnect-replay or an out-of-order delivery can't double-advance
|
|
135
|
+
// game state. The server stamps a strictly-monotonic `seq` per sender.
|
|
136
|
+
if (
|
|
137
|
+
typeof message.seq === 'number' &&
|
|
138
|
+
typeof message.fromPeerId === 'string'
|
|
139
|
+
) {
|
|
140
|
+
const last = S.mpLastSeqByPeer.get(message.fromPeerId) || 0;
|
|
141
|
+
if (message.seq <= last) return;
|
|
142
|
+
S.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
emit('message', {
|
|
146
|
+
roomCode: message.roomCode,
|
|
147
|
+
fromPeerId: message.fromPeerId,
|
|
148
|
+
eventName: message.eventName,
|
|
149
|
+
payload: message.payload,
|
|
150
|
+
seq: message.seq,
|
|
151
|
+
sentAt: message.sentAt,
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// Also fan out to per-eventName subscribers so game code can do
|
|
155
|
+
// `multiplayer.on('player_move', handler)` directly instead of
|
|
156
|
+
// filtering inside a single `message` listener.
|
|
157
|
+
emit(message.eventName, {
|
|
158
|
+
roomCode: message.roomCode,
|
|
159
|
+
fromPeerId: message.fromPeerId,
|
|
160
|
+
payload: message.payload,
|
|
161
|
+
seq: message.seq,
|
|
162
|
+
sentAt: message.sentAt,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
S.mpSocket.onclose = () => {
|
|
168
|
+
emit('disconnected', { roomCode: joinInfo.roomCode });
|
|
169
|
+
if (S.mpExpectedClose || !S.mpLastJoinRequest) return;
|
|
170
|
+
if (S.mpReconnectAttempts >= GameHub.MP_MAX_RECONNECT_ATTEMPTS) return;
|
|
171
|
+
|
|
172
|
+
S.mpReconnectAttempts += 1;
|
|
173
|
+
const delay = Math.min(
|
|
174
|
+
1000 * Math.pow(2, S.mpReconnectAttempts - 1),
|
|
175
|
+
GameHub.MP_MAX_RECONNECT_DELAY_MS
|
|
176
|
+
);
|
|
177
|
+
emit('reconnecting', {
|
|
178
|
+
attempts: S.mpReconnectAttempts,
|
|
179
|
+
delayMs: delay,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
S.mpReconnectTimer = setTimeout(() => {
|
|
183
|
+
if (!S.mpLastJoinRequest) return;
|
|
184
|
+
connect(S.mpLastJoinRequest);
|
|
185
|
+
}, delay);
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
S.mpSocket.onerror = () => {
|
|
189
|
+
// The `onclose` handler owns reconnect logic; we only avoid
|
|
190
|
+
// double-triggering it here.
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// --- High-level room actions --------------------------------------------
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Create a room for the current game and connect as the host.
|
|
198
|
+
*/
|
|
199
|
+
export async function createRoom(
|
|
200
|
+
options: RoomOptions = {}
|
|
201
|
+
): Promise<CreateRoomResult> {
|
|
202
|
+
const S = GameHub.State;
|
|
203
|
+
await GameHub.Init.ensureInitialized();
|
|
204
|
+
|
|
205
|
+
if (!S.gameSlug) {
|
|
206
|
+
return { success: false, error: 'Game slug is required' };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const result = await GameHub.Api.apiRequest('/multiplayer/rooms/create', {
|
|
210
|
+
method: 'POST',
|
|
211
|
+
body: {
|
|
212
|
+
gameSlug: S.gameSlug,
|
|
213
|
+
maxPlayers: options.maxPlayers,
|
|
214
|
+
passcode: options.passcode,
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const data = GameHub.Utils.unwrapResult(result);
|
|
219
|
+
if (!result.success || !data?.roomToken) {
|
|
220
|
+
return {
|
|
221
|
+
success: false,
|
|
222
|
+
error: result.error?.message || 'Failed to create room',
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
S.mpRoom = {
|
|
227
|
+
roomCode: data.roomCode,
|
|
228
|
+
shareId: data.shareId,
|
|
229
|
+
shareUrl: data.shareUrl,
|
|
230
|
+
peerId: data.peerId,
|
|
231
|
+
role: data.role,
|
|
232
|
+
gameSlug: data.gameSlug,
|
|
233
|
+
roomToken: data.roomToken,
|
|
234
|
+
wsUrl: data.wsUrl,
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
S.mpLastJoinRequest = {
|
|
238
|
+
roomCode: data.roomCode,
|
|
239
|
+
roomToken: data.roomToken,
|
|
240
|
+
wsUrl: data.wsUrl,
|
|
241
|
+
gameSlug: data.gameSlug,
|
|
242
|
+
peerId: data.peerId,
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
connect(S.mpLastJoinRequest);
|
|
246
|
+
|
|
247
|
+
return {
|
|
248
|
+
success: true,
|
|
249
|
+
roomCode: data.roomCode,
|
|
250
|
+
shareId: data.shareId,
|
|
251
|
+
shareUrl: data.shareUrl,
|
|
252
|
+
peerId: data.peerId,
|
|
253
|
+
roomToken: data.roomToken,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Join an existing room by its short alphanumeric code.
|
|
259
|
+
*/
|
|
260
|
+
export async function joinRoom(
|
|
261
|
+
roomCode: string,
|
|
262
|
+
options: JoinOptions = {}
|
|
263
|
+
): Promise<JoinRoomResult> {
|
|
264
|
+
const S = GameHub.State;
|
|
265
|
+
await GameHub.Init.ensureInitialized();
|
|
266
|
+
|
|
267
|
+
if (!S.gameSlug) {
|
|
268
|
+
return { success: false, error: 'Game slug is required' };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const result = await GameHub.Api.apiRequest(
|
|
272
|
+
'/multiplayer/rooms/join-token',
|
|
273
|
+
{
|
|
274
|
+
method: 'POST',
|
|
275
|
+
body: {
|
|
276
|
+
gameSlug: S.gameSlug,
|
|
277
|
+
roomCode,
|
|
278
|
+
passcode: options.passcode,
|
|
279
|
+
displayName: options.displayName,
|
|
280
|
+
},
|
|
281
|
+
}
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
const data = GameHub.Utils.unwrapResult(result);
|
|
285
|
+
if (!result.success || !data?.roomToken) {
|
|
286
|
+
return {
|
|
287
|
+
success: false,
|
|
288
|
+
error: result.error?.message || 'Failed to join room',
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const resolvedRole =
|
|
293
|
+
options.asViewer && data.role !== 'host' ? 'viewer' : data.role;
|
|
294
|
+
S.mpViewerOverride = resolvedRole === 'viewer';
|
|
295
|
+
|
|
296
|
+
S.mpRoom = {
|
|
297
|
+
roomCode: data.roomCode,
|
|
298
|
+
shareId: data.shareId,
|
|
299
|
+
peerId: data.peerId,
|
|
300
|
+
role: resolvedRole,
|
|
301
|
+
gameSlug: data.gameSlug,
|
|
302
|
+
roomToken: data.roomToken,
|
|
303
|
+
wsUrl: data.wsUrl,
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
S.mpLastJoinRequest = {
|
|
307
|
+
roomCode: data.roomCode,
|
|
308
|
+
roomToken: data.roomToken,
|
|
309
|
+
wsUrl: data.wsUrl,
|
|
310
|
+
gameSlug: data.gameSlug,
|
|
311
|
+
peerId: data.peerId,
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
connect(S.mpLastJoinRequest);
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
success: true,
|
|
318
|
+
roomCode: data.roomCode,
|
|
319
|
+
shareId: data.shareId,
|
|
320
|
+
peerId: data.peerId,
|
|
321
|
+
roomToken: data.roomToken,
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Join an existing room by its share ID or full share URL.
|
|
327
|
+
*/
|
|
328
|
+
export async function joinRoomByLink(
|
|
329
|
+
link: string,
|
|
330
|
+
options: JoinOptions = {}
|
|
331
|
+
): Promise<JoinRoomResult> {
|
|
332
|
+
const S = GameHub.State;
|
|
333
|
+
await GameHub.Init.ensureInitialized();
|
|
334
|
+
|
|
335
|
+
if (!S.gameSlug) {
|
|
336
|
+
return { success: false, error: 'Game slug is required' };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const shareId = GameHub.Utils.extractShareIdFromLink(link);
|
|
340
|
+
if (!shareId) {
|
|
341
|
+
return { success: false, error: 'Invalid multiplayer link' };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const result = await GameHub.Api.apiRequest(
|
|
345
|
+
'/multiplayer/rooms/join-token',
|
|
346
|
+
{
|
|
347
|
+
method: 'POST',
|
|
348
|
+
body: {
|
|
349
|
+
gameSlug: S.gameSlug,
|
|
350
|
+
shareId,
|
|
351
|
+
passcode: options.passcode,
|
|
352
|
+
displayName: options.displayName,
|
|
353
|
+
},
|
|
354
|
+
}
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
const data = GameHub.Utils.unwrapResult(result);
|
|
358
|
+
if (!result.success || !data?.roomToken) {
|
|
359
|
+
return {
|
|
360
|
+
success: false,
|
|
361
|
+
error: result.error?.message || 'Failed to join room by link',
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const resolvedRole =
|
|
366
|
+
options.asViewer && data.role !== 'host' ? 'viewer' : data.role;
|
|
367
|
+
S.mpViewerOverride = resolvedRole === 'viewer';
|
|
368
|
+
|
|
369
|
+
S.mpRoom = {
|
|
370
|
+
roomCode: data.roomCode,
|
|
371
|
+
shareId: data.shareId,
|
|
372
|
+
peerId: data.peerId,
|
|
373
|
+
role: resolvedRole,
|
|
374
|
+
gameSlug: data.gameSlug,
|
|
375
|
+
roomToken: data.roomToken,
|
|
376
|
+
wsUrl: data.wsUrl,
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
S.mpLastJoinRequest = {
|
|
380
|
+
roomCode: data.roomCode,
|
|
381
|
+
roomToken: data.roomToken,
|
|
382
|
+
wsUrl: data.wsUrl,
|
|
383
|
+
gameSlug: data.gameSlug,
|
|
384
|
+
peerId: data.peerId,
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
connect(S.mpLastJoinRequest);
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
success: true,
|
|
391
|
+
roomCode: data.roomCode,
|
|
392
|
+
shareId: data.shareId,
|
|
393
|
+
peerId: data.peerId,
|
|
394
|
+
roomToken: data.roomToken,
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Disconnect from the current room. If we're the host, also ask the server
|
|
400
|
+
* to close the room so stragglers get booted cleanly.
|
|
401
|
+
*/
|
|
402
|
+
export async function leaveRoom(reason: string = 'left'): Promise<void> {
|
|
403
|
+
const S = GameHub.State;
|
|
404
|
+
if (S.mpRoom && S.mpRoom.role === 'host' && S.mpRoom.roomToken) {
|
|
405
|
+
try {
|
|
406
|
+
await GameHub.Api.apiRequest(
|
|
407
|
+
'/multiplayer/rooms/' +
|
|
408
|
+
encodeURIComponent(S.mpRoom.roomCode) +
|
|
409
|
+
'/close',
|
|
410
|
+
{
|
|
411
|
+
method: 'POST',
|
|
412
|
+
body: { roomToken: S.mpRoom.roomToken },
|
|
413
|
+
}
|
|
414
|
+
);
|
|
415
|
+
} catch {
|
|
416
|
+
// ignore
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
S.mpExpectedClose = true;
|
|
421
|
+
clearSocket();
|
|
422
|
+
S.mpRoom = null;
|
|
423
|
+
S.mpLastJoinRequest = null;
|
|
424
|
+
S.mpPeers.clear();
|
|
425
|
+
S.mpLastSeqByPeer.clear();
|
|
426
|
+
S.mpViewerOverride = false;
|
|
427
|
+
emit('room_left', { reason });
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Send a custom game event to every other peer in the room. Returns false
|
|
432
|
+
* when the socket isn't open or the current peer is a view-only guest.
|
|
433
|
+
*/
|
|
434
|
+
export function send(
|
|
435
|
+
eventName: string,
|
|
436
|
+
payload: Record<string, any> = {}
|
|
437
|
+
): boolean {
|
|
438
|
+
const S = GameHub.State;
|
|
439
|
+
if (S.mpViewerOverride) {
|
|
440
|
+
GameHub.Utils.warn('multiplayer.send ignored: peer is a viewer');
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
const socket = S.mpSocket;
|
|
444
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
socket.send(JSON.stringify({ eventName, payload }));
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Host-only variant of {@link send}. Silently no-ops (and logs a warning) if
|
|
453
|
+
* the current peer isn't the host. Use this for authoritative state updates
|
|
454
|
+
* — grid shuffles, turn advances, round resolution — so a guest that
|
|
455
|
+
* accidentally calls it can't corrupt the match.
|
|
456
|
+
*/
|
|
457
|
+
export function broadcast(
|
|
458
|
+
eventName: string,
|
|
459
|
+
payload: Record<string, any> = {}
|
|
460
|
+
): boolean {
|
|
461
|
+
if (!isHost()) {
|
|
462
|
+
GameHub.Utils.warn('multiplayer.broadcast ignored: peer is not the host');
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
return send(eventName, payload);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** @returns the current peer's role (`host`, `player`, `viewer`, ...) or null. */
|
|
469
|
+
export function getRole(): string | null {
|
|
470
|
+
return GameHub.State.mpRoom ? GameHub.State.mpRoom.role : null;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** @returns true when the current peer is the room's authoritative host. */
|
|
474
|
+
export function isHost(): boolean {
|
|
475
|
+
return GameHub.State.mpRoom?.role === 'host';
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** @returns true when the current peer joined with `{ asViewer: true }`. */
|
|
479
|
+
export function isViewer(): boolean {
|
|
480
|
+
return GameHub.State.mpViewerOverride === true;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Returns the peerId of the current player (self), or null if not joined.
|
|
485
|
+
* Convenience for filtering self-originated echoes inside a `message`
|
|
486
|
+
* listener: `if (msg.fromPeerId === selfId()) return;`.
|
|
487
|
+
*/
|
|
488
|
+
export function selfId(): string | null {
|
|
489
|
+
return GameHub.State.mpRoom ? GameHub.State.mpRoom.peerId : null;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Subscribe to a multiplayer event. Use `'*'` to receive every event.
|
|
494
|
+
* Returns an unsubscribe function.
|
|
495
|
+
*/
|
|
496
|
+
export function on(eventName: string, handler: MpEventHandler): () => void {
|
|
497
|
+
const handlers = GameHub.State.mpHandlers;
|
|
498
|
+
if (!handlers.has(eventName)) {
|
|
499
|
+
handlers.set(eventName, new Set());
|
|
500
|
+
}
|
|
501
|
+
handlers.get(eventName)!.add(handler);
|
|
502
|
+
return () => {
|
|
503
|
+
const set = handlers.get(eventName);
|
|
504
|
+
if (!set) return;
|
|
505
|
+
set.delete(handler);
|
|
506
|
+
if (set.size === 0) handlers.delete(eventName);
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** @returns a copy of the current room descriptor, or null if not in one. */
|
|
511
|
+
export function getRoom(): RoomInfo | null {
|
|
512
|
+
return GameHub.State.mpRoom ? { ...GameHub.State.mpRoom } : null;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** @returns every peer currently in the room (self included). */
|
|
516
|
+
export function getPeers(): Peer[] {
|
|
517
|
+
return Array.from(GameHub.State.mpPeers.values());
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** @returns whether the WebSocket is currently open. */
|
|
521
|
+
export function isConnected(): boolean {
|
|
522
|
+
const s = GameHub.State.mpSocket;
|
|
523
|
+
return Boolean(s && s.readyState === WebSocket.OPEN);
|
|
524
|
+
}
|
|
525
|
+
}
|