@ksaa-nlp/gamehub-sdk 0.7.0 → 3.5.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.
Files changed (74) hide show
  1. package/README.md +154 -374
  2. package/SPEC.md +865 -0
  3. package/dist/gamehub-sdk.js +164 -1163
  4. package/dist/gamehub-sdk.js.map +3 -3
  5. package/dist/src/api-client.d.ts +15 -5
  6. package/dist/src/api-client.d.ts.map +1 -1
  7. package/dist/src/api-client.js +21 -5
  8. package/dist/src/api-client.js.map +1 -1
  9. package/dist/src/bridge.d.ts +31 -14
  10. package/dist/src/bridge.d.ts.map +1 -1
  11. package/dist/src/bridge.js +148 -159
  12. package/dist/src/bridge.js.map +1 -1
  13. package/dist/src/constants.d.ts +8 -6
  14. package/dist/src/constants.d.ts.map +1 -1
  15. package/dist/src/constants.js +8 -6
  16. package/dist/src/constants.js.map +1 -1
  17. package/dist/src/init.d.ts +18 -12
  18. package/dist/src/init.d.ts.map +1 -1
  19. package/dist/src/init.js +23 -156
  20. package/dist/src/init.js.map +1 -1
  21. package/dist/src/main.d.ts +45 -85
  22. package/dist/src/main.d.ts.map +1 -1
  23. package/dist/src/main.js +27 -52
  24. package/dist/src/main.js.map +1 -1
  25. package/dist/src/match-context.d.ts.map +1 -1
  26. package/dist/src/match-context.js +0 -14
  27. package/dist/src/match-context.js.map +1 -1
  28. package/dist/src/server-dev-harness.d.ts +85 -0
  29. package/dist/src/server-dev-harness.d.ts.map +1 -0
  30. package/dist/src/server-dev-harness.js +233 -0
  31. package/dist/src/server-dev-harness.js.map +1 -0
  32. package/dist/src/server-entry.d.ts +127 -0
  33. package/dist/src/server-entry.d.ts.map +1 -0
  34. package/dist/src/server-entry.js +26 -0
  35. package/dist/src/server-entry.js.map +1 -0
  36. package/dist/src/session.d.ts +16 -9
  37. package/dist/src/session.d.ts.map +1 -1
  38. package/dist/src/session.js +38 -27
  39. package/dist/src/session.js.map +1 -1
  40. package/dist/src/state.d.ts +17 -55
  41. package/dist/src/state.d.ts.map +1 -1
  42. package/dist/src/state.js +13 -32
  43. package/dist/src/state.js.map +1 -1
  44. package/dist/src/utils.d.ts +3 -14
  45. package/dist/src/utils.d.ts.map +1 -1
  46. package/dist/src/utils.js +3 -31
  47. package/dist/src/utils.js.map +1 -1
  48. package/dist/types/bootstrap.d.ts +56 -36
  49. package/dist/types/bootstrap.d.ts.map +1 -1
  50. package/dist/types/question.d.ts +36 -0
  51. package/dist/types/question.d.ts.map +1 -0
  52. package/dist/types/question.js +21 -0
  53. package/dist/types/question.js.map +1 -0
  54. package/dist/types/session.d.ts +23 -20
  55. package/dist/types/session.d.ts.map +1 -1
  56. package/package.json +14 -4
  57. package/CHANGELOG.md +0 -467
  58. package/MIGRATION.md +0 -322
  59. package/dist/src/multiplayer-match.d.ts +0 -42
  60. package/dist/src/multiplayer-match.d.ts.map +0 -1
  61. package/dist/src/multiplayer-match.js +0 -551
  62. package/dist/src/multiplayer-match.js.map +0 -1
  63. package/dist/src/multiplayer.d.ts +0 -96
  64. package/dist/src/multiplayer.d.ts.map +0 -1
  65. package/dist/src/multiplayer.js +0 -495
  66. package/dist/src/multiplayer.js.map +0 -1
  67. package/dist/types/multiplayer-match.d.ts +0 -204
  68. package/dist/types/multiplayer-match.d.ts.map +0 -1
  69. package/dist/types/multiplayer-match.js +0 -15
  70. package/dist/types/multiplayer-match.js.map +0 -1
  71. package/dist/types/multiplayer.d.ts +0 -157
  72. package/dist/types/multiplayer.d.ts.map +0 -1
  73. package/dist/types/multiplayer.js +0 -2
  74. package/dist/types/multiplayer.js.map +0 -1
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "0.7.0";
4
+ var SDK_VERSION = "3.5.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
- var MP_MAX_RECONNECT_ATTEMPTS = 5;
8
- var MP_MAX_RECONNECT_DELAY_MS = 1e4;
7
+ var HOST_API_TIMEOUT_MS = 15e3;
9
8
  var QUESTIONS_LIMIT_CAP = 100;
10
9
 
11
10
  // src/state.ts
@@ -20,20 +19,13 @@
20
19
  leagueId: null,
21
20
  gameId: null,
22
21
  matchId: null,
23
- participant1Id: null,
24
- participant2Id: null,
25
- participant1MemberIds: [],
26
- participant2MemberIds: [],
27
- matchContext: null,
28
- matchContextPromise: null,
29
- bootstrapShareId: null,
30
- bootstrapRoomCode: null,
31
- bootstrapRoomRole: null,
32
- bootstrapRoomToken: null,
33
- bootstrapWsUrl: null,
22
+ bootstrapMode: null,
34
23
  bootstrapPlayerName: null,
35
- bootstrapPeerId: null,
36
- bootstrapMaxPlayers: null,
24
+ bootstrapPlayerCount: null,
25
+ bootstrapTeamOneName: null,
26
+ bootstrapTeamTwoName: null,
27
+ bootstrapProfileId: null,
28
+ bootstrapMultiplayer: null,
37
29
  bootstrapReceived: false,
38
30
  isInitialized: false,
39
31
  isAutoInitializing: false,
@@ -41,20 +33,8 @@
41
33
  bootstrapRequestPromise: null,
42
34
  parentOrigin: null,
43
35
  sessionStartPromise: null,
44
- lastAutoJoinShareId: null,
45
- lastAutoJoinRoomCode: null,
46
- mpSocket: null,
47
- mpReconnectTimer: null,
48
- mpReconnectAttempts: 0,
49
- mpExpectedClose: false,
50
- mpRoom: null,
51
- mpLastJoinRequest: null,
52
- mpPeers: /* @__PURE__ */ new Map(),
53
- mpHandlers: /* @__PURE__ */ new Map(),
54
- mpLastSeqByPeer: /* @__PURE__ */ new Map(),
55
- mpViewerOverride: false,
56
- mpServerOffsetMs: 0,
57
- mpServerOffsetSamples: 0
36
+ matchContext: null,
37
+ matchContextPromise: null
58
38
  };
59
39
 
60
40
  // src/utils.ts
@@ -72,16 +52,6 @@
72
52
  if (result.success && result.data) return result.data;
73
53
  return result;
74
54
  }
75
- function extractShareIdFromLink(link) {
76
- try {
77
- const parsed = new URL(link, window.location.origin);
78
- const mp = parsed.searchParams.get("mp");
79
- if (mp) return mp;
80
- return parsed.pathname.split("/").pop() || null;
81
- } catch {
82
- return null;
83
- }
84
- }
85
55
  function readQueryParam(name) {
86
56
  try {
87
57
  const params = new URLSearchParams(window.location.search);
@@ -93,130 +63,76 @@
93
63
  return match ? decodeURIComponent(match[1]) : null;
94
64
  }
95
65
  }
96
- function readCsvQueryParam(name) {
97
- const raw = readQueryParam(name) || "";
98
- return raw.split(",").map((value) => value.trim()).filter(Boolean);
99
- }
100
66
 
101
67
  // src/bridge.ts
68
+ function trimToNullable(value) {
69
+ if (value === null) return null;
70
+ if (typeof value !== "string") return void 0;
71
+ const trimmed = value.trim();
72
+ return trimmed ? trimmed : null;
73
+ }
74
+ function parseMultiplayer(value) {
75
+ if (value === null) return null;
76
+ if (!value || typeof value !== "object") return void 0;
77
+ const { reservation, wsEndpoint } = value;
78
+ if (!reservation || typeof reservation !== "object" || typeof reservation.name !== "string" || typeof reservation.sessionId !== "string" || typeof reservation.roomId !== "string" || typeof wsEndpoint !== "string") {
79
+ return void 0;
80
+ }
81
+ return {
82
+ reservation,
83
+ wsEndpoint: wsEndpoint.trim()
84
+ };
85
+ }
102
86
  function mergeBootstrapConfig(config = {}) {
103
87
  if (!config || typeof config !== "object") return;
104
- if (typeof config.gameSlug === "string" && config.gameSlug.trim()) {
105
- state.gameSlug = config.gameSlug.trim();
106
- }
107
- if (typeof config.authToken === "string") {
108
- state.authToken = config.authToken;
109
- } else if (config.authToken === null) {
110
- state.authToken = null;
111
- }
112
- if (typeof config.leagueId === "string" && config.leagueId.trim()) {
113
- state.leagueId = config.leagueId.trim();
114
- } else if (config.leagueId === null) {
115
- state.leagueId = null;
116
- }
117
- if (typeof config.gameId === "string" && config.gameId.trim()) {
118
- state.gameId = config.gameId.trim();
119
- } else if (config.gameId === null) {
120
- state.gameId = null;
121
- }
122
- if (typeof config.matchId === "string" && config.matchId.trim()) {
123
- state.matchId = config.matchId.trim();
124
- } else if (config.matchId === null) {
125
- state.matchId = null;
126
- }
127
- if (typeof config.participant1Id === "string" && config.participant1Id.trim()) {
128
- state.participant1Id = config.participant1Id.trim();
129
- } else if (config.participant1Id === null) {
130
- state.participant1Id = null;
131
- }
132
- if (typeof config.participant2Id === "string" && config.participant2Id.trim()) {
133
- state.participant2Id = config.participant2Id.trim();
134
- } else if (config.participant2Id === null) {
135
- state.participant2Id = null;
136
- }
137
- if (Array.isArray(config.participant1MemberIds)) {
138
- state.participant1MemberIds = config.participant1MemberIds.filter(Boolean);
139
- }
140
- if (Array.isArray(config.participant2MemberIds)) {
141
- state.participant2MemberIds = config.participant2MemberIds.filter(Boolean);
142
- }
143
- if (typeof config.playerName === "string" && config.playerName.trim()) {
144
- state.bootstrapPlayerName = config.playerName.trim();
145
- } else if (config.playerName === null) {
146
- state.bootstrapPlayerName = null;
147
- }
148
- if (typeof config.peerId === "string" && config.peerId.trim()) {
149
- state.bootstrapPeerId = config.peerId.trim();
150
- } else if (config.peerId === null) {
151
- state.bootstrapPeerId = null;
152
- }
153
- if (config.room && typeof config.room === "object") {
154
- const room = config.room;
155
- if (typeof room.roomCode === "string" && room.roomCode.trim()) {
156
- state.bootstrapRoomCode = room.roomCode.trim().toUpperCase();
157
- } else if (room.roomCode === null) {
158
- state.bootstrapRoomCode = null;
159
- }
160
- if (typeof room.shareId === "string" && room.shareId.trim()) {
161
- state.bootstrapShareId = room.shareId.trim();
162
- } else if (room.shareId === null) {
163
- state.bootstrapShareId = null;
164
- }
165
- if (typeof room.maxPlayers === "number" && Number.isFinite(room.maxPlayers)) {
166
- state.bootstrapMaxPlayers = room.maxPlayers;
167
- } else if (room.maxPlayers === null) {
168
- state.bootstrapMaxPlayers = null;
169
- }
170
- if (typeof room.role === "string" && room.role.trim()) {
171
- state.bootstrapRoomRole = room.role.trim();
172
- } else if (room.role === null) {
173
- state.bootstrapRoomRole = null;
174
- }
175
- if (typeof room.roomToken === "string" && room.roomToken.trim()) {
176
- state.bootstrapRoomToken = room.roomToken.trim();
177
- } else if (room.roomToken === null) {
178
- state.bootstrapRoomToken = null;
179
- }
180
- if (typeof room.wsUrl === "string" && room.wsUrl.trim()) {
181
- state.bootstrapWsUrl = room.wsUrl.trim();
182
- } else if (room.wsUrl === null) {
183
- state.bootstrapWsUrl = null;
184
- }
185
- } else if (config.room === null) {
186
- state.bootstrapRoomCode = null;
187
- state.bootstrapShareId = null;
188
- state.bootstrapMaxPlayers = null;
189
- state.bootstrapRoomRole = null;
190
- state.bootstrapRoomToken = null;
191
- state.bootstrapWsUrl = null;
192
- }
88
+ const apply = (key, raw) => {
89
+ const next = trimToNullable(raw);
90
+ if (next === void 0) return;
91
+ state[key] = next;
92
+ };
93
+ apply("gameSlug", config.gameSlug);
94
+ apply("authToken", config.authToken);
95
+ apply("leagueId", config.leagueId);
96
+ apply("gameId", config.gameId);
97
+ apply("matchId", config.matchId);
98
+ const applyBootstrap = (key, raw) => {
99
+ const next = trimToNullable(raw);
100
+ if (next === void 0) return;
101
+ state[key] = next;
102
+ };
103
+ applyBootstrap("bootstrapMode", config.mode);
104
+ applyBootstrap("bootstrapPlayerName", config.playerName);
105
+ applyBootstrap("bootstrapPlayerCount", config.playerCount);
106
+ applyBootstrap("bootstrapTeamOneName", config.teamOneName);
107
+ applyBootstrap("bootstrapTeamTwoName", config.teamTwoName);
108
+ applyBootstrap("bootstrapProfileId", config.profileId);
109
+ const mp = parseMultiplayer(config.multiplayer);
110
+ if (mp !== void 0) {
111
+ state.bootstrapMultiplayer = mp;
112
+ }
113
+ }
114
+ function snapshotBootstrap() {
115
+ return {
116
+ gameSlug: state.gameSlug,
117
+ authToken: state.authToken,
118
+ leagueId: state.leagueId,
119
+ gameId: state.gameId,
120
+ matchId: state.matchId,
121
+ mode: state.bootstrapMode,
122
+ playerName: state.bootstrapPlayerName,
123
+ playerCount: state.bootstrapPlayerCount,
124
+ teamOneName: state.bootstrapTeamOneName,
125
+ teamTwoName: state.bootstrapTeamTwoName,
126
+ profileId: state.bootstrapProfileId,
127
+ multiplayer: state.bootstrapMultiplayer
128
+ };
193
129
  }
194
130
  function requestBootstrapFromParent() {
195
131
  if (!isBrowser() || window.parent === window) {
196
132
  return Promise.resolve(null);
197
133
  }
198
134
  if (state.bootstrapReceived) {
199
- return Promise.resolve({
200
- gameSlug: state.gameSlug,
201
- authToken: state.authToken,
202
- leagueId: state.leagueId,
203
- gameId: state.gameId,
204
- matchId: state.matchId,
205
- participant1Id: state.participant1Id,
206
- participant2Id: state.participant2Id,
207
- participant1MemberIds: state.participant1MemberIds,
208
- participant2MemberIds: state.participant2MemberIds,
209
- playerName: state.bootstrapPlayerName,
210
- peerId: state.bootstrapPeerId,
211
- room: state.bootstrapRoomCode ? {
212
- roomCode: state.bootstrapRoomCode,
213
- shareId: state.bootstrapShareId,
214
- maxPlayers: state.bootstrapMaxPlayers,
215
- role: state.bootstrapRoomRole,
216
- roomToken: state.bootstrapRoomToken,
217
- wsUrl: state.bootstrapWsUrl
218
- } : null
219
- });
135
+ return Promise.resolve(snapshotBootstrap());
220
136
  }
221
137
  if (state.bootstrapRequestPromise) {
222
138
  return state.bootstrapRequestPromise;
@@ -280,14 +196,6 @@
280
196
  if (event.data.leagueId) state.leagueId = event.data.leagueId;
281
197
  if (event.data.gameId) state.gameId = event.data.gameId;
282
198
  if (event.data.matchId) state.matchId = event.data.matchId;
283
- if (event.data.participant1Id)
284
- state.participant1Id = event.data.participant1Id;
285
- if (event.data.participant2Id)
286
- state.participant2Id = event.data.participant2Id;
287
- if (Array.isArray(event.data.participant1MemberIds))
288
- state.participant1MemberIds = event.data.participant1MemberIds.filter(Boolean);
289
- if (Array.isArray(event.data.participant2MemberIds))
290
- state.participant2MemberIds = event.data.participant2MemberIds.filter(Boolean);
291
199
  resolve(event.data.token || null);
292
200
  }
293
201
  };
@@ -304,6 +212,50 @@
304
212
  }, PARENT_REQUEST_TIMEOUT_MS);
305
213
  });
306
214
  }
215
+ var apiRequestSeq = 0;
216
+ function requestApiFromParent(endpoint, options = {}) {
217
+ return new Promise((resolve, reject) => {
218
+ if (!isBrowser() || window.parent === window) {
219
+ reject(new Error("Host bridge unavailable: not running in an iframe"));
220
+ return;
221
+ }
222
+ const messageId = "api_" + Date.now().toString() + "_" + ++apiRequestSeq;
223
+ let settled = false;
224
+ let timeoutId = null;
225
+ const handler = (event) => {
226
+ if (!event.data || event.data.type !== MESSAGE_PREFIX + "_API_RESPONSE" || event.data.messageId !== messageId) {
227
+ return;
228
+ }
229
+ if (settled) return;
230
+ settled = true;
231
+ window.removeEventListener("message", handler);
232
+ if (timeoutId) clearTimeout(timeoutId);
233
+ state.parentOrigin = event.origin;
234
+ if (event.data.ok) {
235
+ resolve(event.data.result ?? {});
236
+ } else {
237
+ reject(new Error(event.data.error || "Host API request failed"));
238
+ }
239
+ };
240
+ window.addEventListener("message", handler);
241
+ window.parent.postMessage(
242
+ {
243
+ type: MESSAGE_PREFIX + "_API_REQUEST",
244
+ messageId,
245
+ endpoint,
246
+ method: options.method || "GET",
247
+ body: options.body ?? null
248
+ },
249
+ state.parentOrigin || "*"
250
+ );
251
+ timeoutId = setTimeout(() => {
252
+ if (settled) return;
253
+ settled = true;
254
+ window.removeEventListener("message", handler);
255
+ reject(new Error("Host API request timed out"));
256
+ }, HOST_API_TIMEOUT_MS);
257
+ });
258
+ }
307
259
  function sendToParent(type, data) {
308
260
  if (!isBrowser() || window.parent === window) return;
309
261
  window.parent.postMessage(
@@ -318,6 +270,9 @@
318
270
 
319
271
  // src/api-client.ts
320
272
  async function apiRequest(endpoint, options = {}) {
273
+ if (isBrowser() && window.parent !== window) {
274
+ return requestApiFromParent(endpoint, options);
275
+ }
321
276
  const url = state.apiBase + endpoint;
322
277
  const headers = {
323
278
  "Content-Type": "application/json",
@@ -335,404 +290,6 @@
335
290
  return response.json();
336
291
  }
337
292
 
338
- // src/multiplayer.ts
339
- function emit(eventName, payload) {
340
- const handlers = state.mpHandlers.get(eventName);
341
- if (handlers) {
342
- handlers.forEach((handler) => {
343
- try {
344
- handler(payload);
345
- } catch (err) {
346
- error("Multiplayer handler error:", err);
347
- }
348
- });
349
- }
350
- const allHandlers = state.mpHandlers.get("*");
351
- if (allHandlers) {
352
- allHandlers.forEach((handler) => {
353
- try {
354
- handler({ eventName, payload });
355
- } catch (err) {
356
- error("Multiplayer * handler error:", err);
357
- }
358
- });
359
- }
360
- }
361
- function clearSocket() {
362
- if (state.mpReconnectTimer) {
363
- clearTimeout(state.mpReconnectTimer);
364
- state.mpReconnectTimer = null;
365
- }
366
- if (state.mpSocket) {
367
- try {
368
- state.mpSocket.onopen = null;
369
- state.mpSocket.onclose = null;
370
- state.mpSocket.onmessage = null;
371
- state.mpSocket.onerror = null;
372
- state.mpSocket.close();
373
- } catch {
374
- }
375
- }
376
- state.mpSocket = null;
377
- }
378
- function connect(joinInfo) {
379
- clearSocket();
380
- const wsBase = joinInfo.wsUrl.replace(/\/+$/, "");
381
- const wsUrl = wsBase + "?roomToken=" + encodeURIComponent(joinInfo.roomToken) + "&gameSlug=" + encodeURIComponent(joinInfo.gameSlug) + "&sdk=2.x";
382
- state.mpExpectedClose = false;
383
- state.mpSocket = new WebSocket(wsUrl);
384
- state.mpSocket.onopen = () => {
385
- state.mpReconnectAttempts = 0;
386
- emit("connected", {
387
- roomCode: joinInfo.roomCode,
388
- peerId: joinInfo.peerId
389
- });
390
- };
391
- state.mpSocket.onmessage = (event) => {
392
- let message = null;
393
- try {
394
- message = JSON.parse(event.data);
395
- } catch {
396
- return;
397
- }
398
- if (!message || !message.type) return;
399
- if (typeof message.sentAt === "number" && message.retained !== true) {
400
- const sample = message.sentAt - Date.now();
401
- if (state.mpServerOffsetSamples === 0) {
402
- state.mpServerOffsetMs = sample;
403
- } else {
404
- state.mpServerOffsetMs = 0.85 * state.mpServerOffsetMs + 0.15 * sample;
405
- }
406
- state.mpServerOffsetSamples += 1;
407
- }
408
- if (message.type === "system") {
409
- if (message.eventName === "room_joined") {
410
- state.mpPeers.clear();
411
- const peers = message.payload?.peers || [];
412
- peers.forEach((peer) => {
413
- if (peer && peer.peerId) state.mpPeers.set(peer.peerId, peer);
414
- });
415
- }
416
- if (message.eventName === "peer_joined" && message.payload?.peerId) {
417
- state.mpPeers.set(message.payload.peerId, message.payload);
418
- }
419
- if (message.eventName === "peer_left" && message.payload?.peerId) {
420
- state.mpPeers.delete(message.payload.peerId);
421
- }
422
- if (message.eventName === "room_closed") {
423
- emit("room_left", { reason: "room_closed" });
424
- clearSocket();
425
- }
426
- emit(message.eventName, message.payload || {});
427
- return;
428
- }
429
- if (message.type === "game_event") {
430
- const isRetained = message.retained === true;
431
- if (!isRetained && typeof message.seq === "number" && typeof message.fromPeerId === "string") {
432
- const last = state.mpLastSeqByPeer.get(message.fromPeerId) || 0;
433
- if (message.seq <= last) return;
434
- state.mpLastSeqByPeer.set(message.fromPeerId, message.seq);
435
- }
436
- emit("message", {
437
- roomCode: message.roomCode,
438
- fromPeerId: message.fromPeerId,
439
- eventName: message.eventName,
440
- payload: message.payload,
441
- seq: message.seq,
442
- sentAt: message.sentAt,
443
- retained: isRetained
444
- });
445
- emit(message.eventName, {
446
- roomCode: message.roomCode,
447
- fromPeerId: message.fromPeerId,
448
- payload: message.payload,
449
- seq: message.seq,
450
- sentAt: message.sentAt,
451
- retained: isRetained
452
- });
453
- }
454
- };
455
- state.mpSocket.onclose = () => {
456
- emit("disconnected", { roomCode: joinInfo.roomCode });
457
- if (state.mpExpectedClose || !state.mpLastJoinRequest) return;
458
- if (state.mpReconnectAttempts >= MP_MAX_RECONNECT_ATTEMPTS) return;
459
- state.mpReconnectAttempts += 1;
460
- const delay = Math.min(
461
- 1e3 * Math.pow(2, state.mpReconnectAttempts - 1),
462
- MP_MAX_RECONNECT_DELAY_MS
463
- );
464
- emit("reconnecting", {
465
- attempts: state.mpReconnectAttempts,
466
- delayMs: delay
467
- });
468
- state.mpReconnectTimer = setTimeout(() => {
469
- if (!state.mpLastJoinRequest) return;
470
- connect(state.mpLastJoinRequest);
471
- }, delay);
472
- };
473
- state.mpSocket.onerror = () => {
474
- };
475
- }
476
- async function createRoom(options = {}) {
477
- await ensureInitialized();
478
- if (!state.gameSlug) {
479
- return { success: false, error: "Game slug is required" };
480
- }
481
- const result = await apiRequest("/multiplayer/rooms/create", {
482
- method: "POST",
483
- body: {
484
- gameSlug: state.gameSlug,
485
- maxPlayers: options.maxPlayers,
486
- passcode: options.passcode
487
- }
488
- });
489
- const data = unwrapResult(result);
490
- if (!result.success || !data?.roomToken) {
491
- return {
492
- success: false,
493
- error: result.error?.message || "Failed to create room"
494
- };
495
- }
496
- state.mpRoom = {
497
- roomCode: data.roomCode,
498
- shareId: data.shareId,
499
- shareUrl: data.shareUrl,
500
- peerId: data.peerId,
501
- role: data.role,
502
- gameSlug: data.gameSlug,
503
- roomToken: data.roomToken,
504
- wsUrl: data.wsUrl
505
- };
506
- state.mpLastJoinRequest = {
507
- roomCode: data.roomCode,
508
- roomToken: data.roomToken,
509
- wsUrl: data.wsUrl,
510
- gameSlug: data.gameSlug,
511
- peerId: data.peerId
512
- };
513
- connect(state.mpLastJoinRequest);
514
- return {
515
- success: true,
516
- roomCode: data.roomCode,
517
- shareId: data.shareId,
518
- shareUrl: data.shareUrl,
519
- peerId: data.peerId,
520
- roomToken: data.roomToken
521
- };
522
- }
523
- async function joinRoom(roomCode, options = {}) {
524
- await ensureInitialized();
525
- if (!state.gameSlug) {
526
- return { success: false, error: "Game slug is required" };
527
- }
528
- const result = await apiRequest("/multiplayer/rooms/join-token", {
529
- method: "POST",
530
- body: {
531
- gameSlug: state.gameSlug,
532
- roomCode,
533
- passcode: options.passcode,
534
- displayName: options.displayName
535
- }
536
- });
537
- const data = unwrapResult(result);
538
- if (!result.success || !data?.roomToken) {
539
- return {
540
- success: false,
541
- error: result.error?.message || "Failed to join room"
542
- };
543
- }
544
- const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
545
- state.mpViewerOverride = resolvedRole === "viewer";
546
- state.mpRoom = {
547
- roomCode: data.roomCode,
548
- shareId: data.shareId,
549
- peerId: data.peerId,
550
- role: resolvedRole,
551
- gameSlug: data.gameSlug,
552
- roomToken: data.roomToken,
553
- wsUrl: data.wsUrl
554
- };
555
- state.mpLastJoinRequest = {
556
- roomCode: data.roomCode,
557
- roomToken: data.roomToken,
558
- wsUrl: data.wsUrl,
559
- gameSlug: data.gameSlug,
560
- peerId: data.peerId
561
- };
562
- connect(state.mpLastJoinRequest);
563
- return {
564
- success: true,
565
- roomCode: data.roomCode,
566
- shareId: data.shareId,
567
- peerId: data.peerId,
568
- roomToken: data.roomToken
569
- };
570
- }
571
- async function joinRoomByLink(link, options = {}) {
572
- await ensureInitialized();
573
- if (!state.gameSlug) {
574
- return { success: false, error: "Game slug is required" };
575
- }
576
- const shareId = extractShareIdFromLink(link);
577
- if (!shareId) {
578
- return { success: false, error: "Invalid multiplayer link" };
579
- }
580
- const result = await apiRequest("/multiplayer/rooms/join-token", {
581
- method: "POST",
582
- body: {
583
- gameSlug: state.gameSlug,
584
- shareId,
585
- passcode: options.passcode,
586
- displayName: options.displayName
587
- }
588
- });
589
- const data = unwrapResult(result);
590
- if (!result.success || !data?.roomToken) {
591
- return {
592
- success: false,
593
- error: result.error?.message || "Failed to join room by link"
594
- };
595
- }
596
- const resolvedRole = options.asViewer && data.role !== "host" ? "viewer" : data.role;
597
- state.mpViewerOverride = resolvedRole === "viewer";
598
- state.mpRoom = {
599
- roomCode: data.roomCode,
600
- shareId: data.shareId,
601
- peerId: data.peerId,
602
- role: resolvedRole,
603
- gameSlug: data.gameSlug,
604
- roomToken: data.roomToken,
605
- wsUrl: data.wsUrl
606
- };
607
- state.mpLastJoinRequest = {
608
- roomCode: data.roomCode,
609
- roomToken: data.roomToken,
610
- wsUrl: data.wsUrl,
611
- gameSlug: data.gameSlug,
612
- peerId: data.peerId
613
- };
614
- connect(state.mpLastJoinRequest);
615
- return {
616
- success: true,
617
- roomCode: data.roomCode,
618
- shareId: data.shareId,
619
- peerId: data.peerId,
620
- roomToken: data.roomToken
621
- };
622
- }
623
- async function leaveRoom(reason = "left") {
624
- if (state.mpRoom && state.mpRoom.role === "host" && state.mpRoom.roomToken) {
625
- try {
626
- await apiRequest(
627
- "/multiplayer/rooms/" + encodeURIComponent(state.mpRoom.roomCode) + "/close",
628
- {
629
- method: "POST",
630
- body: { roomToken: state.mpRoom.roomToken }
631
- }
632
- );
633
- } catch {
634
- }
635
- }
636
- state.mpExpectedClose = true;
637
- clearSocket();
638
- state.mpRoom = null;
639
- state.mpLastJoinRequest = null;
640
- state.mpPeers.clear();
641
- state.mpLastSeqByPeer.clear();
642
- state.mpViewerOverride = false;
643
- emit("room_left", { reason });
644
- }
645
- function send(eventName, payload = {}, options = {}) {
646
- if (state.mpViewerOverride) {
647
- warn("multiplayer.send ignored: peer is a viewer");
648
- return false;
649
- }
650
- const socket = state.mpSocket;
651
- if (!socket || socket.readyState !== WebSocket.OPEN) {
652
- return false;
653
- }
654
- const frame = { eventName, payload };
655
- if (options.retain) {
656
- frame.retain = true;
657
- if (options.retainKey) frame.retainKey = options.retainKey;
658
- }
659
- if (options.to !== void 0) {
660
- frame.to = options.to;
661
- }
662
- socket.send(JSON.stringify(frame));
663
- return true;
664
- }
665
- function broadcast(eventName, payload = {}, options = {}) {
666
- if (!isHost()) {
667
- warn("multiplayer.broadcast ignored: peer is not the host");
668
- return false;
669
- }
670
- return send(eventName, payload, options);
671
- }
672
- function getRole() {
673
- return state.mpRoom ? state.mpRoom.role : null;
674
- }
675
- function isHost() {
676
- return state.mpRoom?.role === "host";
677
- }
678
- function isViewer() {
679
- return state.mpViewerOverride === true;
680
- }
681
- function selfId() {
682
- return state.mpRoom ? state.mpRoom.peerId : null;
683
- }
684
- function on(eventName, handler) {
685
- const handlers = state.mpHandlers;
686
- if (!handlers.has(eventName)) {
687
- handlers.set(eventName, /* @__PURE__ */ new Set());
688
- }
689
- handlers.get(eventName).add(handler);
690
- return () => {
691
- const set = handlers.get(eventName);
692
- if (!set) return;
693
- set.delete(handler);
694
- if (set.size === 0) handlers.delete(eventName);
695
- };
696
- }
697
- function getRoom() {
698
- return state.mpRoom ? { ...state.mpRoom } : null;
699
- }
700
- function getPeers() {
701
- return Array.from(state.mpPeers.values());
702
- }
703
- function isConnected() {
704
- const s = state.mpSocket;
705
- return Boolean(s && s.readyState === WebSocket.OPEN);
706
- }
707
- function serverNow() {
708
- return Date.now() + state.mpServerOffsetMs;
709
- }
710
-
711
- // src/match-context.ts
712
- async function fetchMatchContext() {
713
- if (!state.leagueId || !state.matchId) return null;
714
- if (state.matchContext) return state.matchContext;
715
- if (state.matchContextPromise) return await state.matchContextPromise;
716
- state.matchContextPromise = apiRequest(
717
- "/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
718
- { method: "GET" }
719
- ).then((result) => {
720
- const data = unwrapResult(result);
721
- if (result?.success && data) {
722
- state.matchContext = data;
723
- state.participant1Id = data.participant1?.participantId || state.participant1Id;
724
- state.participant2Id = data.participant2?.participantId || state.participant2Id;
725
- state.participant1MemberIds = Array.isArray(data.participant1?.members) ? data.participant1.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant1MemberIds;
726
- state.participant2MemberIds = Array.isArray(data.participant2?.members) ? data.participant2.members.map((member) => member?.leaguePlayerId).filter(Boolean) : state.participant2MemberIds;
727
- return state.matchContext;
728
- }
729
- return null;
730
- }).catch(() => null).finally(() => {
731
- state.matchContextPromise = null;
732
- });
733
- return await state.matchContextPromise;
734
- }
735
-
736
293
  // src/session.ts
737
294
  async function startSession() {
738
295
  if (!state.gameSlug) return { success: false, error: "Game slug not set" };
@@ -779,10 +336,6 @@
779
336
  error: "SDK could not initialize. Is game slug set?"
780
337
  };
781
338
  }
782
- if (state.mpRoom && state.mpRoom.role !== "host") {
783
- warn("submitScore skipped: only the multiplayer host may submit scores");
784
- return { success: true, skipped: true };
785
- }
786
339
  if (!state.sessionToken) {
787
340
  if (state.sessionStartPromise) {
788
341
  await state.sessionStartPromise;
@@ -866,26 +419,34 @@
866
419
  if (limit !== void 0 && (typeof limit !== "number" || limit < 1)) {
867
420
  return [];
868
421
  }
422
+ const profileId = options.profileId || state.bootstrapProfileId || "";
869
423
  try {
870
424
  const params = new URLSearchParams({
871
- limit: String(Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)),
425
+ limit: String(
426
+ Math.min(limit || QUESTIONS_LIMIT_CAP, QUESTIONS_LIMIT_CAP)
427
+ ),
872
428
  random: "true"
873
429
  });
874
430
  if (state.gameId) params.set("gameId", state.gameId);
875
431
  if (difficulty) params.set("difficulty", difficulty);
876
432
  if (category) params.set("category", String(category));
433
+ if (profileId) params.set("profileId", profileId);
877
434
  const result = await apiRequest(
878
435
  "/games/" + encodeURIComponent(gameIdentifier) + "/questions?" + params.toString(),
879
436
  { method: "GET" }
880
437
  );
881
438
  const data = unwrapResult(result);
882
- if (Array.isArray(data)) return data;
883
- if (!data || !Array.isArray(data.questions)) return [];
884
- return data.questions;
439
+ const raw = Array.isArray(data) ? data : Array.isArray(data?.questions) ? data.questions : [];
440
+ return raw.map(normalizeQuestion);
885
441
  } catch {
886
442
  return [];
887
443
  }
888
444
  }
445
+ function normalizeQuestion(raw) {
446
+ const q = raw;
447
+ const answer = typeof q.answer === "number" ? String(q.answer) : q.answer;
448
+ return { ...q, answer };
449
+ }
889
450
 
890
451
  // src/init.ts
891
452
  var environmentDetected = false;
@@ -905,10 +466,6 @@
905
466
  state.leagueId = readQueryParam("leagueId");
906
467
  state.gameId = readQueryParam("gameId");
907
468
  state.matchId = readQueryParam("matchId");
908
- state.participant1Id = readQueryParam("participant1Id");
909
- state.participant2Id = readQueryParam("participant2Id");
910
- state.participant1MemberIds = readCsvQueryParam("participant1MemberIds");
911
- state.participant2MemberIds = readCsvQueryParam("participant2MemberIds");
912
469
  const scripts = document.getElementsByTagName("script");
913
470
  for (let i = 0; i < scripts.length; i++) {
914
471
  const src = scripts[i].src;
@@ -940,111 +497,17 @@
940
497
  state.apiBase = state.sdkOrigin + effectiveBasePath + "/api";
941
498
  state.gameSlug = detectedSlug;
942
499
  }
943
- function getPendingShareId() {
944
- if (state.bootstrapShareId) return state.bootstrapShareId;
945
- return readQueryParam("mp");
946
- }
947
- function getPendingRoomCode() {
948
- if (state.bootstrapRoomCode) return state.bootstrapRoomCode;
949
- const roomCode = readQueryParam("roomCode");
950
- return roomCode ? roomCode.trim().toUpperCase() : null;
951
- }
952
- function getPendingRoomRole() {
953
- if (state.bootstrapRoomRole) return state.bootstrapRoomRole;
954
- const role = readQueryParam("roomRole");
955
- return role ? role.trim() : null;
956
- }
957
- function getPendingRoomToken() {
958
- if (state.bootstrapRoomToken) return state.bootstrapRoomToken;
959
- const roomToken = readQueryParam("roomToken");
960
- return roomToken ? roomToken.trim() : null;
961
- }
962
- function getPendingWsUrl() {
963
- if (state.bootstrapWsUrl) return state.bootstrapWsUrl;
964
- const wsUrl = readQueryParam("wsUrl");
965
- return wsUrl ? wsUrl.trim() : null;
966
- }
967
- function getPendingPlayerName() {
968
- if (state.bootstrapPlayerName) return state.bootstrapPlayerName;
969
- const playerName = readQueryParam("playerName");
970
- return playerName ? playerName.trim() : void 0;
971
- }
972
- function seedPeerIdFromUrl() {
973
- if (state.bootstrapPeerId) return;
974
- const fromUrl = readQueryParam("peerId");
975
- if (fromUrl) state.bootstrapPeerId = fromUrl.trim();
976
- }
977
- function resumePendingRoomFromBootstrap() {
978
- const roomCode = getPendingRoomCode();
979
- const roomToken = getPendingRoomToken();
980
- const wsUrl = getPendingWsUrl();
981
- const peerId = state.bootstrapPeerId || readQueryParam("peerId")?.trim() || null;
982
- if (!state.gameSlug || !roomCode || !roomToken || !wsUrl || !peerId) {
983
- return false;
984
- }
985
- const role = getPendingRoomRole() || "player";
986
- state.mpViewerOverride = role === "viewer";
987
- state.mpRoom = {
988
- roomCode,
989
- shareId: state.bootstrapShareId || "",
990
- peerId,
991
- role,
992
- gameSlug: state.gameSlug,
993
- roomToken,
994
- wsUrl
995
- };
996
- state.mpLastJoinRequest = {
997
- roomCode,
998
- roomToken,
999
- wsUrl,
1000
- gameSlug: state.gameSlug,
1001
- peerId
1002
- };
1003
- connect(state.mpLastJoinRequest);
1004
- return true;
1005
- }
1006
- async function autoJoinPendingShare() {
1007
- const shareId = getPendingShareId();
1008
- if (!shareId) return;
1009
- if (state.lastAutoJoinShareId === shareId) return;
1010
- try {
1011
- state.lastAutoJoinShareId = shareId;
1012
- await joinRoomByLink(shareId, {
1013
- displayName: getPendingPlayerName()
1014
- });
1015
- } catch (err) {
1016
- state.lastAutoJoinShareId = null;
1017
- warn("Auto join by link failed: " + (err?.message || err));
1018
- }
1019
- }
1020
- async function autoJoinPendingRoomCode() {
1021
- const roomCode = getPendingRoomCode();
1022
- if (!roomCode) return;
1023
- if (state.lastAutoJoinRoomCode === roomCode) return;
1024
- try {
1025
- state.lastAutoJoinRoomCode = roomCode;
1026
- if (resumePendingRoomFromBootstrap()) {
1027
- return;
1028
- }
1029
- await joinRoom(roomCode, {
1030
- displayName: getPendingPlayerName()
1031
- });
1032
- } catch (err) {
1033
- state.lastAutoJoinRoomCode = null;
1034
- warn("Auto join by room code failed: " + (err?.message || err));
1035
- }
1036
- }
1037
500
  async function autoInit() {
1038
501
  if (!isBrowser()) return false;
1039
- if (state.isInitialized || state.isAutoInitializing)
502
+ if (state.isInitialized || state.isAutoInitializing) {
1040
503
  return state.autoInitPromise;
504
+ }
1041
505
  detectEnvironment();
1042
506
  installHostMessageListener();
1043
507
  state.isAutoInitializing = true;
1044
508
  state.autoInitPromise = (async () => {
1045
509
  try {
1046
510
  await requestBootstrapFromParent();
1047
- seedPeerIdFromUrl();
1048
511
  if (!state.gameSlug) {
1049
512
  warn(
1050
513
  "Could not resolve game slug. Ensure the host page sends bootstrap config or serves the game under /games/{slug}."
@@ -1061,12 +524,9 @@
1061
524
  slug: state.gameSlug,
1062
525
  auto: true
1063
526
  });
1064
- await fetchMatchContext();
1065
527
  if (state.authToken || state.leagueId && state.gameId && state.matchId) {
1066
528
  state.sessionStartPromise = startSession();
1067
529
  }
1068
- await autoJoinPendingShare();
1069
- await autoJoinPendingRoomCode();
1070
530
  return true;
1071
531
  } catch (err) {
1072
532
  error("Auto-init failed:", err);
@@ -1092,9 +552,6 @@
1092
552
  state.parentOrigin = event.origin;
1093
553
  state.bootstrapReceived = true;
1094
554
  mergeBootstrapConfig(event.data.payload);
1095
- if (state.isInitialized && state.bootstrapShareId && !state.mpRoom) {
1096
- autoJoinPendingShare();
1097
- }
1098
555
  }
1099
556
  if (type === MESSAGE_PREFIX + "_SET_AUTH") {
1100
557
  state.authToken = event.data.token;
@@ -1115,457 +572,25 @@
1115
572
  });
1116
573
  }
1117
574
 
1118
- // src/multiplayer-match.ts
1119
- var READY_EVENT_DEFAULT = "match:peer_ready";
1120
- var START_EVENT_DEFAULT = "match:start";
1121
- var START_RETAIN_KEY_DEFAULT = "match:start";
1122
- var activeMatch = null;
1123
- function generateMatchId() {
1124
- if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
1125
- return crypto.randomUUID();
1126
- }
1127
- return `match-${Date.now()}-${Math.random().toString(36).slice(2)}`;
1128
- }
1129
- function createMatch(options) {
1130
- if (activeMatch) {
1131
- throw new Error(
1132
- "multiplayer.match: an existing match is still active. Call destroy() first."
1133
- );
1134
- }
1135
- if (!state.mpRoom) {
1136
- throw new Error(
1137
- "multiplayer.match: not in a room. Call createRoom/joinRoom first."
1138
- );
1139
- }
1140
- const expectedPeers = options.expectedPeers ?? 2;
1141
- const autoReady = options.autoReady !== false;
1142
- const startEventName = options.startEventName ?? START_EVENT_DEFAULT;
1143
- const readyEventName = options.readyEventName ?? READY_EVENT_DEFAULT;
1144
- const startRetainKey = options.startRetainKey ?? START_RETAIN_KEY_DEFAULT;
1145
- let matchState = "waiting";
1146
- let matchId = null;
1147
- let starting = false;
1148
- let destroyed = false;
1149
- let wantReady = autoReady;
1150
- const readyPeerIds = /* @__PURE__ */ new Set();
1151
- const appliedIdKeys = /* @__PURE__ */ new Set();
1152
- const stateChangeHandlers = /* @__PURE__ */ new Set();
1153
- const offHandlers = [];
1154
- function setState(next) {
1155
- if (matchState === next) return;
1156
- matchState = next;
1157
- for (const handler of stateChangeHandlers) {
1158
- try {
1159
- handler(next);
1160
- } catch (err) {
1161
- error("multiplayer.match onStateChange handler error:", err);
1162
- }
1163
- }
1164
- }
1165
- function localSelfId() {
1166
- return selfId();
1167
- }
1168
- function localIsHost() {
1169
- return isHost();
1170
- }
1171
- function localPeers() {
1172
- return getPeers();
1173
- }
1174
- function makeCtx(retained = false) {
1175
- return {
1176
- get matchId() {
1177
- return matchId ?? "";
1178
- },
1179
- get isHost() {
1180
- return localIsHost();
1181
- },
1182
- get selfId() {
1183
- return localSelfId() ?? "";
1184
- },
1185
- get peers() {
1186
- return localPeers();
1187
- },
1188
- retained,
1189
- peer(peerId) {
1190
- return localPeers().find((p) => p.peerId === peerId) ?? null;
1191
- },
1192
- intent: apiIntent,
1193
- broadcast: apiBroadcast
1194
- };
1195
- }
1196
- function eventDefFor(name) {
1197
- return options.events[name];
1198
- }
1199
- function idKeyFor(eventName, def, payload, seq) {
1200
- if (def?.idKey) {
1201
- try {
1202
- return def.idKey(payload);
1203
- } catch (err) {
1204
- error(
1205
- `multiplayer.match idKey('${eventName}') threw \u2014 falling back to seq:`,
1206
- err
1207
- );
1208
- }
1209
- }
1210
- return `${eventName}:${payload.matchId}:${seq ?? "local"}`;
1211
- }
1212
- function maybeApply(eventName, def, payload, fromPeerId, seq, retained) {
1213
- if (!def?.apply) return;
1214
- const key = idKeyFor(eventName, def, payload, seq);
1215
- if (appliedIdKeys.has(key)) return;
1216
- appliedIdKeys.add(key);
1217
- try {
1218
- def.apply(makeCtx(retained), payload, fromPeerId);
1219
- } catch (err) {
1220
- error(`multiplayer.match apply('${eventName}') threw:`, err);
1221
- }
1222
- }
1223
- function apiIntent(name, payloadIn) {
1224
- if (destroyed || matchState === "aborted" || matchState === "ended") {
1225
- warn(
1226
- `multiplayer.match.intent('${String(name)}'): match is ${matchState}`
1227
- );
1228
- return false;
1229
- }
1230
- if (matchId == null) {
1231
- warn(
1232
- `multiplayer.match.intent('${String(name)}'): match has not started yet`
1233
- );
1234
- return false;
1235
- }
1236
- const payload = { ...payloadIn, matchId };
1237
- const def = eventDefFor(String(name));
1238
- if (localIsHost() && def?.hostHandle) {
1239
- const me = localSelfId();
1240
- if (!me) return false;
1241
- try {
1242
- Promise.resolve(
1243
- def.hostHandle(makeCtx(), payload, me)
1244
- ).catch(
1245
- (err) => error(`multiplayer.match hostHandle('${String(name)}') threw:`, err)
1246
- );
1247
- } catch (err) {
1248
- error(`multiplayer.match hostHandle('${String(name)}') threw:`, err);
1249
- }
1250
- return true;
1251
- }
1252
- return send(String(name), payload);
1253
- }
1254
- function apiBroadcast(name, payloadIn, callerOptions = {}) {
1255
- if (destroyed || matchState === "aborted" || matchState === "ended") {
1256
- warn(
1257
- `multiplayer.match.broadcast('${String(name)}'): match is ${matchState}`
1258
- );
1259
- return false;
1260
- }
1261
- if (matchId == null) {
1262
- warn(
1263
- `multiplayer.match.broadcast('${String(name)}'): match has not started yet`
1264
- );
1265
- return false;
1266
- }
1267
- if (!localIsHost()) {
1268
- warn(
1269
- `multiplayer.match.broadcast('${String(name)}'): peer is not the host`
1270
- );
1271
- return false;
1272
- }
1273
- const payload = { ...payloadIn, matchId };
1274
- const def = eventDefFor(String(name));
1275
- const targeted = callerOptions.to !== void 0;
1276
- if (!targeted) {
1277
- const me = localSelfId() ?? "";
1278
- maybeApply(String(name), def, payload, me, void 0, false);
1279
- }
1280
- const retain = !targeted && (callerOptions.retain ?? def?.retain ?? false);
1281
- let retainKey;
1282
- if (retain) {
1283
- if (callerOptions.retainKey) {
1284
- retainKey = callerOptions.retainKey;
1285
- } else if (def?.retainKey) {
1286
- try {
1287
- retainKey = def.retainKey(payload);
1288
- } catch (err) {
1289
- error(
1290
- `multiplayer.match retainKey('${String(name)}') threw \u2014 using event name:`,
1291
- err
1292
- );
1293
- retainKey = String(name);
1294
- }
1295
- } else {
1296
- retainKey = String(name);
1297
- }
1298
- }
1299
- const sendOptions = {};
1300
- if (retain) {
1301
- sendOptions.retain = true;
1302
- sendOptions.retainKey = retainKey;
1303
- }
1304
- if (targeted) {
1305
- sendOptions.to = callerOptions.to;
1306
- }
1307
- return broadcast(
1308
- String(name),
1309
- payload,
1310
- Object.keys(sendOptions).length ? sendOptions : void 0
1311
- );
1312
- }
1313
- function refreshWaiting() {
1314
- if (matchId != null) return;
1315
- const present = localPeers().length;
1316
- const waiting = present < expectedPeers;
1317
- options.onWaitingForPeers?.(waiting, present, expectedPeers);
1318
- }
1319
- function announceReadyIfWanted() {
1320
- if (!wantReady) return;
1321
- if (matchId != null) return;
1322
- const me = localSelfId();
1323
- if (!me) return;
1324
- readyPeerIds.add(me);
1325
- send(readyEventName, { readyAtMs: Date.now() });
1326
- if (localIsHost()) void maybeStart();
1327
- }
1328
- async function maybeStart() {
1329
- if (matchId != null || starting) return;
1330
- if (!localIsHost()) return;
1331
- const peers = localPeers();
1332
- if (peers.length < expectedPeers) return;
1333
- if (!peers.every((p) => readyPeerIds.has(p.peerId))) return;
1334
- starting = true;
1335
- setState("starting");
1336
- try {
1337
- const built = await options.buildStart(peers);
1338
- const newMatchId = generateMatchId();
1339
- const fullPayload = { ...built, matchId: newMatchId };
1340
- broadcast(startEventName, fullPayload, {
1341
- retain: true,
1342
- retainKey: startRetainKey
1343
- });
1344
- matchId = newMatchId;
1345
- setState("active");
1346
- try {
1347
- options.onStart(makeCtx(), fullPayload);
1348
- } catch (err) {
1349
- error("multiplayer.match onStart threw:", err);
1350
- }
1351
- } catch (err) {
1352
- error("multiplayer.match buildStart threw:", err);
1353
- setState("waiting");
1354
- } finally {
1355
- starting = false;
1356
- }
1357
- }
1358
- function handleStartFrame(msg) {
1359
- if (destroyed) return;
1360
- const payload = msg?.payload ?? msg;
1361
- if (!payload || typeof payload !== "object") return;
1362
- if (typeof payload.matchId !== "string" || !payload.matchId) return;
1363
- if (matchId === payload.matchId) return;
1364
- matchId = payload.matchId;
1365
- appliedIdKeys.clear();
1366
- setState("active");
1367
- const retained = msg?.retained === true;
1368
- try {
1369
- options.onStart(makeCtx(retained), payload);
1370
- } catch (err) {
1371
- error("multiplayer.match onStart threw:", err);
1372
- }
1373
- }
1374
- function handleReadyFrame(msg) {
1375
- const fromPeerId = msg?.fromPeerId;
1376
- if (typeof fromPeerId === "string" && fromPeerId) {
1377
- readyPeerIds.add(fromPeerId);
1378
- }
1379
- if (localIsHost()) void maybeStart();
1380
- }
1381
- function handleUserEvent(eventName, msg) {
1382
- if (destroyed) return;
1383
- const payload = msg?.payload;
1384
- if (!payload || typeof payload !== "object") return;
1385
- if (matchId == null) return;
1386
- if (typeof payload.matchId !== "string" || payload.matchId !== matchId) {
1387
- return;
1388
- }
1389
- const def = eventDefFor(eventName);
1390
- const fromPeerId = msg?.fromPeerId ?? "";
1391
- const seq = msg?.seq;
1392
- const retained = msg?.retained === true;
1393
- if (def?.hostHandle && localIsHost() && fromPeerId !== localSelfId() && !retained) {
1394
- try {
1395
- Promise.resolve(
1396
- def.hostHandle(makeCtx(false), payload, fromPeerId)
1397
- ).catch(
1398
- (err) => error(
1399
- `multiplayer.match hostHandle('${eventName}') threw:`,
1400
- err
1401
- )
1402
- );
1403
- } catch (err) {
1404
- error(`multiplayer.match hostHandle('${eventName}') threw:`, err);
1405
- }
1406
- return;
1407
- }
1408
- maybeApply(eventName, def, payload, fromPeerId, seq, retained);
1409
- }
1410
- offHandlers.push(
1411
- on("peer_joined", () => {
1412
- refreshWaiting();
1413
- if (localIsHost()) void maybeStart();
1414
- })
1415
- );
1416
- offHandlers.push(
1417
- on("connected", () => {
1418
- announceReadyIfWanted();
1419
- })
1420
- );
1421
- offHandlers.push(
1422
- on("room_joined", () => {
1423
- refreshWaiting();
1424
- announceReadyIfWanted();
1425
- if (localIsHost()) void maybeStart();
1426
- })
1427
- );
1428
- offHandlers.push(
1429
- on("peer_left", (msg) => {
1430
- const leftId = msg?.peerId;
1431
- if (typeof leftId === "string") readyPeerIds.delete(leftId);
1432
- refreshWaiting();
1433
- if (matchState === "active" && options.onPeerLeft && leftId) {
1434
- try {
1435
- options.onPeerLeft(makeCtx(), leftId);
1436
- } catch (err) {
1437
- error("multiplayer.match onPeerLeft threw:", err);
1438
- }
1439
- }
1440
- if (matchId == null && localIsHost()) void maybeStart();
1441
- })
1442
- );
1443
- offHandlers.push(
1444
- on("disconnected", () => {
1445
- if (matchState === "active" || matchState === "starting") {
1446
- abort("disconnected");
1447
- }
1448
- })
1449
- );
1450
- offHandlers.push(
1451
- on("room_closed", () => {
1452
- abort("room_closed");
1453
- })
1454
- );
1455
- offHandlers.push(on(readyEventName, handleReadyFrame));
1456
- offHandlers.push(on(startEventName, handleStartFrame));
1457
- for (const eventName of Object.keys(options.events)) {
1458
- if (eventName === startEventName || eventName === readyEventName) {
1459
- continue;
1460
- }
1461
- offHandlers.push(
1462
- on(eventName, (msg) => handleUserEvent(eventName, msg))
1463
- );
1464
- }
1465
- function abort(reason) {
1466
- if (matchState === "aborted" || matchState === "ended") return;
1467
- setState("aborted");
1468
- try {
1469
- options.onAborted?.(reason, { matchId });
1470
- } catch (err) {
1471
- error("multiplayer.match onAborted threw:", err);
1472
- }
1473
- }
1474
- refreshWaiting();
1475
- announceReadyIfWanted();
1476
- const match = {
1477
- get state() {
1478
- return matchState;
1479
- },
1480
- get matchId() {
1481
- return matchId;
1482
- },
1483
- intent: apiIntent,
1484
- broadcast: apiBroadcast,
1485
- markReady() {
1486
- wantReady = true;
1487
- announceReadyIfWanted();
1488
- },
1489
- onStateChange(handler) {
1490
- stateChangeHandlers.add(handler);
1491
- return () => {
1492
- stateChangeHandlers.delete(handler);
1493
- };
1494
- },
1495
- async destroy(opts) {
1496
- if (destroyed) return;
1497
- destroyed = true;
1498
- for (const off of offHandlers) {
1499
- try {
1500
- off();
1501
- } catch {
1502
- }
1503
- }
1504
- offHandlers.length = 0;
1505
- stateChangeHandlers.clear();
1506
- readyPeerIds.clear();
1507
- appliedIdKeys.clear();
1508
- activeMatch = null;
1509
- setState("ended");
1510
- if (opts?.leaveRoom) {
1511
- await leaveRoom("match_ended");
1512
- }
1513
- }
1514
- };
1515
- activeMatch = match;
1516
- return match;
1517
- }
1518
- function assignSeats(peers, seatNames, hostPeerId) {
1519
- const peerIds = peers.map((p) => p.peerId).filter(Boolean);
1520
- const ordered = [];
1521
- if (hostPeerId && peerIds.includes(hostPeerId)) {
1522
- ordered.push(hostPeerId);
1523
- }
1524
- for (const id of [...peerIds].sort()) {
1525
- if (id !== hostPeerId) ordered.push(id);
1526
- }
1527
- const bySeat = {};
1528
- const byPeer = {};
1529
- for (let i = 0; i < ordered.length; i++) {
1530
- const seat = i < seatNames.length ? seatNames[i] : null;
1531
- if (seat != null) bySeat[seat] = ordered[i];
1532
- byPeer[ordered[i]] = seat;
1533
- }
1534
- return { bySeat, byPeer };
1535
- }
1536
- function waitForPeers(n, timeoutMs) {
1537
- return new Promise((resolve, reject) => {
1538
- let done = false;
1539
- let timer = null;
1540
- let offJoined = null;
1541
- let offJoinedSystem = null;
1542
- function cleanup() {
1543
- done = true;
1544
- if (timer != null) clearTimeout(timer);
1545
- offJoined?.();
1546
- offJoinedSystem?.();
1547
- }
1548
- function check() {
1549
- if (done) return true;
1550
- const peers = getPeers();
1551
- if (peers.length >= n) {
1552
- cleanup();
1553
- resolve(peers);
1554
- return true;
1555
- }
1556
- return false;
1557
- }
1558
- if (check()) return;
1559
- offJoined = on("peer_joined", () => check());
1560
- offJoinedSystem = on("room_joined", () => check());
1561
- if (timeoutMs && timeoutMs > 0) {
1562
- timer = setTimeout(() => {
1563
- if (done) return;
1564
- cleanup();
1565
- reject(new Error("waitForPeers: timeout"));
1566
- }, timeoutMs);
575
+ // src/match-context.ts
576
+ async function fetchMatchContext() {
577
+ if (!state.leagueId || !state.matchId) return null;
578
+ if (state.matchContext) return state.matchContext;
579
+ if (state.matchContextPromise) return await state.matchContextPromise;
580
+ state.matchContextPromise = apiRequest(
581
+ "/leagues/" + encodeURIComponent(state.leagueId) + "/matches/" + encodeURIComponent(state.matchId),
582
+ { method: "GET" }
583
+ ).then((result) => {
584
+ const data = unwrapResult(result);
585
+ if (result?.success && data) {
586
+ state.matchContext = data;
587
+ return state.matchContext;
1567
588
  }
589
+ return null;
590
+ }).catch(() => null).finally(() => {
591
+ state.matchContextPromise = null;
1568
592
  });
593
+ return await state.matchContextPromise;
1569
594
  }
1570
595
 
1571
596
  // src/main.ts
@@ -1595,8 +620,9 @@
1595
620
  submitMatchResult(result = {}) {
1596
621
  return submitMatchResult(result);
1597
622
  },
1598
- async playAgain() {
1599
- return { success: true, token: state.sessionToken };
623
+ async getMatchContext() {
624
+ await ensureInitialized();
625
+ return await fetchMatchContext();
1600
626
  },
1601
627
  notifyComplete(data = {}) {
1602
628
  sendToParent("GAME_COMPLETE", data);
@@ -1604,6 +630,13 @@
1604
630
  requestClose() {
1605
631
  sendToParent("REQUEST_CLOSE", {});
1606
632
  },
633
+ reportQuestion(data) {
634
+ sendToParent("QUESTION_REPORT", {
635
+ questionId: data.questionId,
636
+ prompt: data.prompt,
637
+ message: data.message
638
+ });
639
+ },
1607
640
  logEvent(eventName, eventData = {}) {
1608
641
  sendToParent("LOG_EVENT", {
1609
642
  event: eventName,
@@ -1626,50 +659,18 @@
1626
659
  leagueId: state.leagueId,
1627
660
  gameId: state.gameId,
1628
661
  matchId: state.matchId,
1629
- match: state.matchContext,
1630
- participant1Id: state.participant1Id,
1631
- participant2Id: state.participant2Id,
1632
- participant1MemberIds: state.participant1MemberIds,
1633
- participant2MemberIds: state.participant2MemberIds,
662
+ mode: state.bootstrapMode,
1634
663
  playerName: state.bootstrapPlayerName,
1635
- peerId: state.bootstrapPeerId,
1636
- room: state.bootstrapRoomCode ? {
1637
- roomCode: state.bootstrapRoomCode,
1638
- shareId: state.bootstrapShareId,
1639
- maxPlayers: state.bootstrapMaxPlayers,
1640
- role: state.bootstrapRoomRole,
1641
- roomToken: state.bootstrapRoomToken,
1642
- wsUrl: state.bootstrapWsUrl
1643
- } : null,
664
+ playerCount: state.bootstrapPlayerCount,
665
+ teamOneName: state.bootstrapTeamOneName,
666
+ teamTwoName: state.bootstrapTeamTwoName,
667
+ profileId: state.bootstrapProfileId,
668
+ multiplayer: state.bootstrapMultiplayer,
1644
669
  isBootstrapped: state.bootstrapReceived
1645
670
  };
1646
671
  },
1647
- async getMatchContext() {
1648
- await ensureInitialized();
1649
- return await fetchMatchContext();
1650
- },
1651
672
  getQuestions(options = {}) {
1652
673
  return getQuestions(options);
1653
- },
1654
- multiplayer: {
1655
- createRoom,
1656
- joinRoom,
1657
- joinRoomByLink,
1658
- leaveRoom,
1659
- send,
1660
- broadcast,
1661
- on,
1662
- getRoom,
1663
- getPeers,
1664
- isConnected,
1665
- getRole,
1666
- isHost,
1667
- isViewer,
1668
- selfId,
1669
- serverNow,
1670
- match: createMatch,
1671
- assignSeats,
1672
- waitForPeers
1673
674
  }
1674
675
  };
1675
676
  }