@ksaa-nlp/gamehub-sdk 0.5.0 → 0.6.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/CHANGELOG.md +78 -0
- package/dist/gamehub-sdk.js +445 -2
- package/dist/gamehub-sdk.js.map +3 -3
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/main.d.ts +19 -0
- package/dist/src/main.d.ts.map +1 -1
- package/dist/src/main.js +4 -0
- package/dist/src/main.js.map +1 -1
- package/dist/src/multiplayer-match.d.ts +40 -0
- package/dist/src/multiplayer-match.d.ts.map +1 -0
- package/dist/src/multiplayer-match.js +525 -0
- package/dist/src/multiplayer-match.js.map +1 -0
- package/dist/types/multiplayer-match.d.ts +172 -0
- package/dist/types/multiplayer-match.d.ts.map +1 -0
- package/dist/types/multiplayer-match.js +15 -0
- package/dist/types/multiplayer-match.js.map +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,83 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.0 — 2026-04-30
|
|
4
|
+
|
|
5
|
+
Adds **`multiplayer.match()`** — a host-authoritative match coordinator that owns the lifecycle every multiplayer game otherwise reinvents: peer-ready handshake, host-elected match start, intent → resolve routing, matchId scoping, and idempotent reapply of broadcasts (live and retained replay alike). Plus two helpers (`assignSeats`, `waitForPeers`) that complete the picture.
|
|
6
|
+
|
|
7
|
+
### Why
|
|
8
|
+
|
|
9
|
+
Surveying the in-tree multiplayer game (link-game) showed that ~700 lines of its component file were transport plumbing, not gameplay: a `readyPeerIds` set, a `currentMatchId`, an `appliedEventKeys` set, manual `if (!this.isHostPeer()) return;` guards on every intent path, manual `if (p.matchId !== this.currentMatchId) return;` filters on every applier, and an ad-hoc switch dispatcher fanning the SDK's `'message'` channel into per-event handlers.
|
|
10
|
+
|
|
11
|
+
All of that is generic — every host-authoritative game needs the same machinery — so it belongs in the SDK.
|
|
12
|
+
|
|
13
|
+
### What changed
|
|
14
|
+
|
|
15
|
+
- **`Sdk.multiplayer.match<TMap, TStart>(options)`**. Build a Match by declaring (a) a typed event map, (b) per-event `hostHandle` / `apply` pairs, and (c) a host-only `buildStart`. Everything else lives in the reducer.
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
const match = sdk.multiplayer.match<LinkMap, MatchStartPayload>({
|
|
19
|
+
expectedPeers: 2,
|
|
20
|
+
buildStart: async (peers) => ({
|
|
21
|
+
greenPeerId: seats.bySeat.green,
|
|
22
|
+
navyPeerId: seats.bySeat.navy,
|
|
23
|
+
cellAssignments: makeGrid(),
|
|
24
|
+
startedAtMs: Date.now(),
|
|
25
|
+
}),
|
|
26
|
+
onStart: (ctx, p) => applyMatchStart(p),
|
|
27
|
+
events: {
|
|
28
|
+
'link:cell_click_request': {
|
|
29
|
+
hostHandle: (ctx, p, from) => ctx.broadcast('link:cell_opened', resolve(p, from)),
|
|
30
|
+
},
|
|
31
|
+
'link:cell_opened': {
|
|
32
|
+
apply: (ctx, p) => applyCellOpened(p),
|
|
33
|
+
idKey: (p) => `cell:${p.cellId}`,
|
|
34
|
+
retain: true,
|
|
35
|
+
retainKey: (p) => `cell:${p.cellId}`,
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
onWaitingForPeers: (waiting) => /* show overlay */,
|
|
39
|
+
onPeerLeft: (ctx, peerId) => /* show disconnect dialog */,
|
|
40
|
+
onAborted: (reason) => /* show retry/back */,
|
|
41
|
+
});
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
What the SDK enforces, so games stop writing it:
|
|
45
|
+
- `peer_ready` handshake fires automatically (or on an explicit `match.markReady()` when `autoReady: false`).
|
|
46
|
+
- Host elects start once `expectedPeers` are present and ready, calls `buildStart`, broadcasts the result with `retain: true` so reconnecting peers receive it.
|
|
47
|
+
- **`matchId` auto-injection on send + auto-verification on receive.** Frames from a previous match are dropped before user code runs.
|
|
48
|
+
- **`idKey` dedupe** — same logical event applied at most once per match. Defaults to `${event}:${matchId}:${seq}`; override per-event when retained replays need to dedupe against live frames the peer already saw (e.g. `cell:${cellId}`).
|
|
49
|
+
- **Host short-circuit** — `match.intent(...)` from the host runs `hostHandle` directly without a WS roundtrip.
|
|
50
|
+
- **`hostOnly` guarding** — `ctx.broadcast` no-ops on guests with a warning.
|
|
51
|
+
- **Lifecycle states** — `waiting | starting | active | aborted | ended`. Subscribe via `match.onStateChange(handler)`.
|
|
52
|
+
- **Reconnect resilience** — re-announces ready on every `connected`/`room_joined`, replays retained match-start + per-event snapshots automatically, idKey dedupe catches the overlap.
|
|
53
|
+
|
|
54
|
+
- **`Sdk.multiplayer.assignSeats(peers, seatNames, hostPeerId)`** — generalises link-game's `assignColors` to N seats and N peers. Sorts as `host first, then lex-asc by peerId`, returns both `bySeat` and `byPeer` maps.
|
|
55
|
+
|
|
56
|
+
- **`Sdk.multiplayer.waitForPeers(n, timeoutMs?)`** — promise-based barrier for "don't render until everyone's here".
|
|
57
|
+
|
|
58
|
+
- The match-start broadcast is **always retained** under `match:start`. Per-event retain is opt-in via `MatchEventDef.retain` / `retainKey`. The `retain` defaults are baked into the reducer so games that follow the standard pattern get transparent reconnect for free.
|
|
59
|
+
|
|
60
|
+
- New exported types: [`Match`, `MatchOptions`, `MatchCtx`, `MatchHostCtx`, `MatchEventDef`, `MatchEventMap`, `MatchScopedPayload`, `MatchBroadcastOptions`, `MatchState`, `MatchAbortReason`](./types/multiplayer-match.ts).
|
|
61
|
+
|
|
62
|
+
### Migration
|
|
63
|
+
|
|
64
|
+
The match API is purely additive — existing `multiplayer.send` / `broadcast` / `on` paths are unchanged. Games can adopt it incrementally; mixing match-managed events with raw `multiplayer.on` listeners is fine.
|
|
65
|
+
|
|
66
|
+
A typical port (link-game): the per-event switch in [link.component.ts:491](https://github.com/...) becomes the `events` map, `readyPeerIds` / `appliedEventKeys` / `currentMatchId` are deleted, every `if (p.matchId !== this.currentMatchId)` and `if (this.isHostPeer())` guard is deleted. Estimated 60–70% reduction in multiplayer-related code.
|
|
67
|
+
|
|
68
|
+
### What's verified
|
|
69
|
+
|
|
70
|
+
- TypeScript: full type-check passes; a smoke test exercises the public generics end-to-end against a realistic game-shaped event map (typed `hostHandle`, `apply`, `idKey`, `retainKey`, `assignSeats` literal-tuple inference, `match.intent`/`match.broadcast`).
|
|
71
|
+
- Build: `npm run build` ships a 53.1 KB IIFE (up from 39.8 KB at 0.5).
|
|
72
|
+
|
|
73
|
+
### Unchanged
|
|
74
|
+
|
|
75
|
+
- Wire protocol with the realtime server (the match reducer just uses the existing `send`/`broadcast` + retained-events transport from 0.5).
|
|
76
|
+
- Public `Sdk` interface beyond the three new methods.
|
|
77
|
+
- `BootstrapData` shape, `MpMessage` shape, all other multiplayer methods.
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
3
81
|
## 0.5.0 — 2026-04-30
|
|
4
82
|
|
|
5
83
|
Adds **retained ("sticky") multiplayer events** so peers that join or reconnect mid-match automatically receive the latest authoritative state before any live traffic — without games having to write a custom resync intent.
|
package/dist/gamehub-sdk.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
(() => {
|
|
3
3
|
// src/constants.ts
|
|
4
|
-
var SDK_VERSION = "0.
|
|
4
|
+
var SDK_VERSION = "0.6.0";
|
|
5
5
|
var MESSAGE_PREFIX = "GAMEHUB_SDK";
|
|
6
6
|
var PARENT_REQUEST_TIMEOUT_MS = 2e3;
|
|
7
7
|
var MP_MAX_RECONNECT_ATTEMPTS = 5;
|
|
@@ -1098,6 +1098,446 @@
|
|
|
1098
1098
|
});
|
|
1099
1099
|
}
|
|
1100
1100
|
|
|
1101
|
+
// src/multiplayer-match.ts
|
|
1102
|
+
var READY_EVENT_DEFAULT = "match:peer_ready";
|
|
1103
|
+
var START_EVENT_DEFAULT = "match:start";
|
|
1104
|
+
var START_RETAIN_KEY_DEFAULT = "match:start";
|
|
1105
|
+
var activeMatch = null;
|
|
1106
|
+
function generateMatchId() {
|
|
1107
|
+
if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
|
|
1108
|
+
return crypto.randomUUID();
|
|
1109
|
+
}
|
|
1110
|
+
return `match-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
1111
|
+
}
|
|
1112
|
+
function createMatch(options) {
|
|
1113
|
+
if (activeMatch) {
|
|
1114
|
+
throw new Error(
|
|
1115
|
+
"multiplayer.match: an existing match is still active. Call destroy() first."
|
|
1116
|
+
);
|
|
1117
|
+
}
|
|
1118
|
+
if (!state.mpRoom) {
|
|
1119
|
+
throw new Error(
|
|
1120
|
+
"multiplayer.match: not in a room. Call createRoom/joinRoom first."
|
|
1121
|
+
);
|
|
1122
|
+
}
|
|
1123
|
+
const expectedPeers = options.expectedPeers ?? 2;
|
|
1124
|
+
const autoReady = options.autoReady !== false;
|
|
1125
|
+
const startEventName = options.startEventName ?? START_EVENT_DEFAULT;
|
|
1126
|
+
const readyEventName = options.readyEventName ?? READY_EVENT_DEFAULT;
|
|
1127
|
+
const startRetainKey = options.startRetainKey ?? START_RETAIN_KEY_DEFAULT;
|
|
1128
|
+
let matchState = "waiting";
|
|
1129
|
+
let matchId = null;
|
|
1130
|
+
let starting = false;
|
|
1131
|
+
let destroyed = false;
|
|
1132
|
+
let wantReady = autoReady;
|
|
1133
|
+
const readyPeerIds = /* @__PURE__ */ new Set();
|
|
1134
|
+
const appliedIdKeys = /* @__PURE__ */ new Set();
|
|
1135
|
+
const stateChangeHandlers = /* @__PURE__ */ new Set();
|
|
1136
|
+
const offHandlers = [];
|
|
1137
|
+
function setState(next) {
|
|
1138
|
+
if (matchState === next) return;
|
|
1139
|
+
matchState = next;
|
|
1140
|
+
for (const handler of stateChangeHandlers) {
|
|
1141
|
+
try {
|
|
1142
|
+
handler(next);
|
|
1143
|
+
} catch (err) {
|
|
1144
|
+
error("multiplayer.match onStateChange handler error:", err);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
function localSelfId() {
|
|
1149
|
+
return selfId();
|
|
1150
|
+
}
|
|
1151
|
+
function localIsHost() {
|
|
1152
|
+
return isHost();
|
|
1153
|
+
}
|
|
1154
|
+
function localPeers() {
|
|
1155
|
+
return getPeers();
|
|
1156
|
+
}
|
|
1157
|
+
function makeCtx() {
|
|
1158
|
+
return {
|
|
1159
|
+
get matchId() {
|
|
1160
|
+
return matchId ?? "";
|
|
1161
|
+
},
|
|
1162
|
+
get isHost() {
|
|
1163
|
+
return localIsHost();
|
|
1164
|
+
},
|
|
1165
|
+
get selfId() {
|
|
1166
|
+
return localSelfId() ?? "";
|
|
1167
|
+
},
|
|
1168
|
+
get peers() {
|
|
1169
|
+
return localPeers();
|
|
1170
|
+
},
|
|
1171
|
+
peer(peerId) {
|
|
1172
|
+
return localPeers().find((p) => p.peerId === peerId) ?? null;
|
|
1173
|
+
},
|
|
1174
|
+
intent: apiIntent,
|
|
1175
|
+
broadcast: apiBroadcast
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
function eventDefFor(name) {
|
|
1179
|
+
return options.events[name];
|
|
1180
|
+
}
|
|
1181
|
+
function idKeyFor(eventName, def, payload, seq) {
|
|
1182
|
+
if (def?.idKey) {
|
|
1183
|
+
try {
|
|
1184
|
+
return def.idKey(payload);
|
|
1185
|
+
} catch (err) {
|
|
1186
|
+
error(
|
|
1187
|
+
`multiplayer.match idKey('${eventName}') threw \u2014 falling back to seq:`,
|
|
1188
|
+
err
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
return `${eventName}:${payload.matchId}:${seq ?? "local"}`;
|
|
1193
|
+
}
|
|
1194
|
+
function maybeApply(eventName, def, payload, fromPeerId, seq) {
|
|
1195
|
+
if (!def?.apply) return;
|
|
1196
|
+
const key = idKeyFor(eventName, def, payload, seq);
|
|
1197
|
+
if (appliedIdKeys.has(key)) return;
|
|
1198
|
+
appliedIdKeys.add(key);
|
|
1199
|
+
try {
|
|
1200
|
+
def.apply(makeCtx(), payload, fromPeerId);
|
|
1201
|
+
} catch (err) {
|
|
1202
|
+
error(`multiplayer.match apply('${eventName}') threw:`, err);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
function apiIntent(name, payloadIn) {
|
|
1206
|
+
if (destroyed || matchState === "aborted" || matchState === "ended") {
|
|
1207
|
+
warn(
|
|
1208
|
+
`multiplayer.match.intent('${String(name)}'): match is ${matchState}`
|
|
1209
|
+
);
|
|
1210
|
+
return false;
|
|
1211
|
+
}
|
|
1212
|
+
if (matchId == null) {
|
|
1213
|
+
warn(
|
|
1214
|
+
`multiplayer.match.intent('${String(name)}'): match has not started yet`
|
|
1215
|
+
);
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
const payload = { ...payloadIn, matchId };
|
|
1219
|
+
const def = eventDefFor(String(name));
|
|
1220
|
+
if (localIsHost() && def?.hostHandle) {
|
|
1221
|
+
const me = localSelfId();
|
|
1222
|
+
if (!me) return false;
|
|
1223
|
+
try {
|
|
1224
|
+
Promise.resolve(
|
|
1225
|
+
def.hostHandle(makeCtx(), payload, me)
|
|
1226
|
+
).catch(
|
|
1227
|
+
(err) => error(`multiplayer.match hostHandle('${String(name)}') threw:`, err)
|
|
1228
|
+
);
|
|
1229
|
+
} catch (err) {
|
|
1230
|
+
error(`multiplayer.match hostHandle('${String(name)}') threw:`, err);
|
|
1231
|
+
}
|
|
1232
|
+
return true;
|
|
1233
|
+
}
|
|
1234
|
+
return send(String(name), payload);
|
|
1235
|
+
}
|
|
1236
|
+
function apiBroadcast(name, payloadIn, callerOptions = {}) {
|
|
1237
|
+
if (destroyed || matchState === "aborted" || matchState === "ended") {
|
|
1238
|
+
warn(
|
|
1239
|
+
`multiplayer.match.broadcast('${String(name)}'): match is ${matchState}`
|
|
1240
|
+
);
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
if (matchId == null) {
|
|
1244
|
+
warn(
|
|
1245
|
+
`multiplayer.match.broadcast('${String(name)}'): match has not started yet`
|
|
1246
|
+
);
|
|
1247
|
+
return false;
|
|
1248
|
+
}
|
|
1249
|
+
if (!localIsHost()) {
|
|
1250
|
+
warn(
|
|
1251
|
+
`multiplayer.match.broadcast('${String(name)}'): peer is not the host`
|
|
1252
|
+
);
|
|
1253
|
+
return false;
|
|
1254
|
+
}
|
|
1255
|
+
const payload = { ...payloadIn, matchId };
|
|
1256
|
+
const def = eventDefFor(String(name));
|
|
1257
|
+
const me = localSelfId() ?? "";
|
|
1258
|
+
maybeApply(String(name), def, payload, me, void 0);
|
|
1259
|
+
const retain = callerOptions.retain ?? def?.retain ?? false;
|
|
1260
|
+
let retainKey;
|
|
1261
|
+
if (retain) {
|
|
1262
|
+
if (callerOptions.retainKey) {
|
|
1263
|
+
retainKey = callerOptions.retainKey;
|
|
1264
|
+
} else if (def?.retainKey) {
|
|
1265
|
+
try {
|
|
1266
|
+
retainKey = def.retainKey(payload);
|
|
1267
|
+
} catch (err) {
|
|
1268
|
+
error(
|
|
1269
|
+
`multiplayer.match retainKey('${String(name)}') threw \u2014 using event name:`,
|
|
1270
|
+
err
|
|
1271
|
+
);
|
|
1272
|
+
retainKey = String(name);
|
|
1273
|
+
}
|
|
1274
|
+
} else {
|
|
1275
|
+
retainKey = String(name);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
const sendOptions = retain ? { retain: true, retainKey } : void 0;
|
|
1279
|
+
return broadcast(
|
|
1280
|
+
String(name),
|
|
1281
|
+
payload,
|
|
1282
|
+
sendOptions
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
function refreshWaiting() {
|
|
1286
|
+
if (matchId != null) return;
|
|
1287
|
+
const present = localPeers().length;
|
|
1288
|
+
const waiting = present < expectedPeers;
|
|
1289
|
+
options.onWaitingForPeers?.(waiting, present, expectedPeers);
|
|
1290
|
+
}
|
|
1291
|
+
function announceReadyIfWanted() {
|
|
1292
|
+
if (!wantReady) return;
|
|
1293
|
+
if (matchId != null) return;
|
|
1294
|
+
const me = localSelfId();
|
|
1295
|
+
if (!me) return;
|
|
1296
|
+
readyPeerIds.add(me);
|
|
1297
|
+
send(readyEventName, { readyAtMs: Date.now() });
|
|
1298
|
+
if (localIsHost()) void maybeStart();
|
|
1299
|
+
}
|
|
1300
|
+
async function maybeStart() {
|
|
1301
|
+
if (matchId != null || starting) return;
|
|
1302
|
+
if (!localIsHost()) return;
|
|
1303
|
+
const peers = localPeers();
|
|
1304
|
+
if (peers.length < expectedPeers) return;
|
|
1305
|
+
if (!peers.every((p) => readyPeerIds.has(p.peerId))) return;
|
|
1306
|
+
starting = true;
|
|
1307
|
+
setState("starting");
|
|
1308
|
+
try {
|
|
1309
|
+
const built = await options.buildStart(peers);
|
|
1310
|
+
const newMatchId = generateMatchId();
|
|
1311
|
+
const fullPayload = { ...built, matchId: newMatchId };
|
|
1312
|
+
broadcast(startEventName, fullPayload, {
|
|
1313
|
+
retain: true,
|
|
1314
|
+
retainKey: startRetainKey
|
|
1315
|
+
});
|
|
1316
|
+
matchId = newMatchId;
|
|
1317
|
+
setState("active");
|
|
1318
|
+
try {
|
|
1319
|
+
options.onStart(makeCtx(), fullPayload);
|
|
1320
|
+
} catch (err) {
|
|
1321
|
+
error("multiplayer.match onStart threw:", err);
|
|
1322
|
+
}
|
|
1323
|
+
} catch (err) {
|
|
1324
|
+
error("multiplayer.match buildStart threw:", err);
|
|
1325
|
+
setState("waiting");
|
|
1326
|
+
} finally {
|
|
1327
|
+
starting = false;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function handleStartFrame(msg) {
|
|
1331
|
+
if (destroyed) return;
|
|
1332
|
+
const payload = msg?.payload ?? msg;
|
|
1333
|
+
if (!payload || typeof payload !== "object") return;
|
|
1334
|
+
if (typeof payload.matchId !== "string" || !payload.matchId) return;
|
|
1335
|
+
if (matchId === payload.matchId) return;
|
|
1336
|
+
matchId = payload.matchId;
|
|
1337
|
+
appliedIdKeys.clear();
|
|
1338
|
+
setState("active");
|
|
1339
|
+
try {
|
|
1340
|
+
options.onStart(makeCtx(), payload);
|
|
1341
|
+
} catch (err) {
|
|
1342
|
+
error("multiplayer.match onStart threw:", err);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
function handleReadyFrame(msg) {
|
|
1346
|
+
const fromPeerId = msg?.fromPeerId;
|
|
1347
|
+
if (typeof fromPeerId === "string" && fromPeerId) {
|
|
1348
|
+
readyPeerIds.add(fromPeerId);
|
|
1349
|
+
}
|
|
1350
|
+
if (localIsHost()) void maybeStart();
|
|
1351
|
+
}
|
|
1352
|
+
function handleUserEvent(eventName, msg) {
|
|
1353
|
+
if (destroyed) return;
|
|
1354
|
+
const payload = msg?.payload;
|
|
1355
|
+
if (!payload || typeof payload !== "object") return;
|
|
1356
|
+
if (matchId == null) return;
|
|
1357
|
+
if (typeof payload.matchId !== "string" || payload.matchId !== matchId) {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
const def = eventDefFor(eventName);
|
|
1361
|
+
const fromPeerId = msg?.fromPeerId ?? "";
|
|
1362
|
+
const seq = msg?.seq;
|
|
1363
|
+
if (def?.hostHandle && localIsHost() && fromPeerId !== localSelfId()) {
|
|
1364
|
+
try {
|
|
1365
|
+
Promise.resolve(
|
|
1366
|
+
def.hostHandle(makeCtx(), payload, fromPeerId)
|
|
1367
|
+
).catch(
|
|
1368
|
+
(err) => error(
|
|
1369
|
+
`multiplayer.match hostHandle('${eventName}') threw:`,
|
|
1370
|
+
err
|
|
1371
|
+
)
|
|
1372
|
+
);
|
|
1373
|
+
} catch (err) {
|
|
1374
|
+
error(`multiplayer.match hostHandle('${eventName}') threw:`, err);
|
|
1375
|
+
}
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
maybeApply(eventName, def, payload, fromPeerId, seq);
|
|
1379
|
+
}
|
|
1380
|
+
offHandlers.push(
|
|
1381
|
+
on("peer_joined", () => {
|
|
1382
|
+
refreshWaiting();
|
|
1383
|
+
if (localIsHost()) void maybeStart();
|
|
1384
|
+
})
|
|
1385
|
+
);
|
|
1386
|
+
offHandlers.push(
|
|
1387
|
+
on("connected", () => {
|
|
1388
|
+
announceReadyIfWanted();
|
|
1389
|
+
})
|
|
1390
|
+
);
|
|
1391
|
+
offHandlers.push(
|
|
1392
|
+
on("room_joined", () => {
|
|
1393
|
+
refreshWaiting();
|
|
1394
|
+
announceReadyIfWanted();
|
|
1395
|
+
if (localIsHost()) void maybeStart();
|
|
1396
|
+
})
|
|
1397
|
+
);
|
|
1398
|
+
offHandlers.push(
|
|
1399
|
+
on("peer_left", (msg) => {
|
|
1400
|
+
const leftId = msg?.peerId;
|
|
1401
|
+
if (typeof leftId === "string") readyPeerIds.delete(leftId);
|
|
1402
|
+
refreshWaiting();
|
|
1403
|
+
if (matchState === "active" && options.onPeerLeft && leftId) {
|
|
1404
|
+
try {
|
|
1405
|
+
options.onPeerLeft(makeCtx(), leftId);
|
|
1406
|
+
} catch (err) {
|
|
1407
|
+
error("multiplayer.match onPeerLeft threw:", err);
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
if (matchId == null && localIsHost()) void maybeStart();
|
|
1411
|
+
})
|
|
1412
|
+
);
|
|
1413
|
+
offHandlers.push(
|
|
1414
|
+
on("disconnected", () => {
|
|
1415
|
+
if (matchState === "active" || matchState === "starting") {
|
|
1416
|
+
abort("disconnected");
|
|
1417
|
+
}
|
|
1418
|
+
})
|
|
1419
|
+
);
|
|
1420
|
+
offHandlers.push(
|
|
1421
|
+
on("room_closed", () => {
|
|
1422
|
+
abort("room_closed");
|
|
1423
|
+
})
|
|
1424
|
+
);
|
|
1425
|
+
offHandlers.push(on(readyEventName, handleReadyFrame));
|
|
1426
|
+
offHandlers.push(on(startEventName, handleStartFrame));
|
|
1427
|
+
for (const eventName of Object.keys(options.events)) {
|
|
1428
|
+
if (eventName === startEventName || eventName === readyEventName) {
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
offHandlers.push(
|
|
1432
|
+
on(eventName, (msg) => handleUserEvent(eventName, msg))
|
|
1433
|
+
);
|
|
1434
|
+
}
|
|
1435
|
+
function abort(reason) {
|
|
1436
|
+
if (matchState === "aborted" || matchState === "ended") return;
|
|
1437
|
+
setState("aborted");
|
|
1438
|
+
try {
|
|
1439
|
+
options.onAborted?.(reason, { matchId });
|
|
1440
|
+
} catch (err) {
|
|
1441
|
+
error("multiplayer.match onAborted threw:", err);
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
refreshWaiting();
|
|
1445
|
+
announceReadyIfWanted();
|
|
1446
|
+
const match = {
|
|
1447
|
+
get state() {
|
|
1448
|
+
return matchState;
|
|
1449
|
+
},
|
|
1450
|
+
get matchId() {
|
|
1451
|
+
return matchId;
|
|
1452
|
+
},
|
|
1453
|
+
intent: apiIntent,
|
|
1454
|
+
broadcast: apiBroadcast,
|
|
1455
|
+
markReady() {
|
|
1456
|
+
wantReady = true;
|
|
1457
|
+
announceReadyIfWanted();
|
|
1458
|
+
},
|
|
1459
|
+
onStateChange(handler) {
|
|
1460
|
+
stateChangeHandlers.add(handler);
|
|
1461
|
+
return () => {
|
|
1462
|
+
stateChangeHandlers.delete(handler);
|
|
1463
|
+
};
|
|
1464
|
+
},
|
|
1465
|
+
async destroy(opts) {
|
|
1466
|
+
if (destroyed) return;
|
|
1467
|
+
destroyed = true;
|
|
1468
|
+
for (const off of offHandlers) {
|
|
1469
|
+
try {
|
|
1470
|
+
off();
|
|
1471
|
+
} catch {
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
offHandlers.length = 0;
|
|
1475
|
+
stateChangeHandlers.clear();
|
|
1476
|
+
readyPeerIds.clear();
|
|
1477
|
+
appliedIdKeys.clear();
|
|
1478
|
+
activeMatch = null;
|
|
1479
|
+
setState("ended");
|
|
1480
|
+
if (opts?.leaveRoom) {
|
|
1481
|
+
await leaveRoom("match_ended");
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
};
|
|
1485
|
+
activeMatch = match;
|
|
1486
|
+
return match;
|
|
1487
|
+
}
|
|
1488
|
+
function assignSeats(peers, seatNames, hostPeerId) {
|
|
1489
|
+
const peerIds = peers.map((p) => p.peerId).filter(Boolean);
|
|
1490
|
+
const ordered = [];
|
|
1491
|
+
if (hostPeerId && peerIds.includes(hostPeerId)) {
|
|
1492
|
+
ordered.push(hostPeerId);
|
|
1493
|
+
}
|
|
1494
|
+
for (const id of [...peerIds].sort()) {
|
|
1495
|
+
if (id !== hostPeerId) ordered.push(id);
|
|
1496
|
+
}
|
|
1497
|
+
const bySeat = {};
|
|
1498
|
+
const byPeer = {};
|
|
1499
|
+
for (let i = 0; i < ordered.length; i++) {
|
|
1500
|
+
const seat = i < seatNames.length ? seatNames[i] : null;
|
|
1501
|
+
if (seat != null) bySeat[seat] = ordered[i];
|
|
1502
|
+
byPeer[ordered[i]] = seat;
|
|
1503
|
+
}
|
|
1504
|
+
return { bySeat, byPeer };
|
|
1505
|
+
}
|
|
1506
|
+
function waitForPeers(n, timeoutMs) {
|
|
1507
|
+
return new Promise((resolve, reject) => {
|
|
1508
|
+
let done = false;
|
|
1509
|
+
let timer = null;
|
|
1510
|
+
let offJoined = null;
|
|
1511
|
+
let offJoinedSystem = null;
|
|
1512
|
+
function cleanup() {
|
|
1513
|
+
done = true;
|
|
1514
|
+
if (timer != null) clearTimeout(timer);
|
|
1515
|
+
offJoined?.();
|
|
1516
|
+
offJoinedSystem?.();
|
|
1517
|
+
}
|
|
1518
|
+
function check() {
|
|
1519
|
+
if (done) return true;
|
|
1520
|
+
const peers = getPeers();
|
|
1521
|
+
if (peers.length >= n) {
|
|
1522
|
+
cleanup();
|
|
1523
|
+
resolve(peers);
|
|
1524
|
+
return true;
|
|
1525
|
+
}
|
|
1526
|
+
return false;
|
|
1527
|
+
}
|
|
1528
|
+
if (check()) return;
|
|
1529
|
+
offJoined = on("peer_joined", () => check());
|
|
1530
|
+
offJoinedSystem = on("room_joined", () => check());
|
|
1531
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
1532
|
+
timer = setTimeout(() => {
|
|
1533
|
+
if (done) return;
|
|
1534
|
+
cleanup();
|
|
1535
|
+
reject(new Error("waitForPeers: timeout"));
|
|
1536
|
+
}, timeoutMs);
|
|
1537
|
+
}
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1101
1541
|
// src/main.ts
|
|
1102
1542
|
function createSdk() {
|
|
1103
1543
|
return {
|
|
@@ -1195,7 +1635,10 @@
|
|
|
1195
1635
|
getRole,
|
|
1196
1636
|
isHost,
|
|
1197
1637
|
isViewer,
|
|
1198
|
-
selfId
|
|
1638
|
+
selfId,
|
|
1639
|
+
match: createMatch,
|
|
1640
|
+
assignSeats,
|
|
1641
|
+
waitForPeers
|
|
1199
1642
|
}
|
|
1200
1643
|
};
|
|
1201
1644
|
}
|