@ksaa-nlp/gamehub-sdk 4.5.0 → 5.5.1

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 (73) hide show
  1. package/README.md +103 -48
  2. package/SPEC.md +230 -57
  3. package/dist/gamehub-sdk.js +1 -1458
  4. package/dist/gamehub-sdk.js.map +4 -4
  5. package/dist/src/answers.d.ts +22 -0
  6. package/dist/src/answers.d.ts.map +1 -0
  7. package/dist/src/answers.js +139 -0
  8. package/dist/src/answers.js.map +1 -0
  9. package/dist/src/bot-driver.d.ts +2 -1
  10. package/dist/src/bot-driver.d.ts.map +1 -1
  11. package/dist/src/bot-driver.js +11 -1
  12. package/dist/src/bot-driver.js.map +1 -1
  13. package/dist/src/bridge.d.ts.map +1 -1
  14. package/dist/src/bridge.js +2 -35
  15. package/dist/src/bridge.js.map +1 -1
  16. package/dist/src/constants.d.ts +1 -1
  17. package/dist/src/constants.js +1 -1
  18. package/dist/src/init.js +7 -7
  19. package/dist/src/init.js.map +1 -1
  20. package/dist/src/loading.d.ts +5 -0
  21. package/dist/src/loading.d.ts.map +1 -0
  22. package/dist/src/loading.js +54 -0
  23. package/dist/src/loading.js.map +1 -0
  24. package/dist/src/main.d.ts +14 -3
  25. package/dist/src/main.d.ts.map +1 -1
  26. package/dist/src/main.js +12 -4
  27. package/dist/src/main.js.map +1 -1
  28. package/dist/src/multiplayer-client.d.ts +52 -0
  29. package/dist/src/multiplayer-client.d.ts.map +1 -0
  30. package/dist/src/multiplayer-client.js +286 -0
  31. package/dist/src/multiplayer-client.js.map +1 -0
  32. package/dist/src/multiplayer-entry.d.ts +9 -0
  33. package/dist/src/multiplayer-entry.d.ts.map +1 -0
  34. package/dist/src/multiplayer-entry.js +9 -0
  35. package/dist/src/multiplayer-entry.js.map +1 -0
  36. package/dist/src/multiplayer-session.d.ts.map +1 -1
  37. package/dist/src/multiplayer-session.js +3 -3
  38. package/dist/src/multiplayer-session.js.map +1 -1
  39. package/dist/src/multiplayer.d.ts.map +1 -1
  40. package/dist/src/multiplayer.js +2 -1
  41. package/dist/src/multiplayer.js.map +1 -1
  42. package/dist/src/session.d.ts.map +1 -1
  43. package/dist/src/session.js +28 -7
  44. package/dist/src/session.js.map +1 -1
  45. package/dist/src/state.d.ts +1 -2
  46. package/dist/src/state.d.ts.map +1 -1
  47. package/dist/src/state.js +0 -1
  48. package/dist/src/state.js.map +1 -1
  49. package/dist/types/bootstrap.d.ts +8 -45
  50. package/dist/types/bootstrap.d.ts.map +1 -1
  51. package/dist/types/loading.d.ts +6 -0
  52. package/dist/types/loading.d.ts.map +1 -0
  53. package/dist/types/loading.js +2 -0
  54. package/dist/types/loading.js.map +1 -0
  55. package/dist/types/multiplayer-session.d.ts +9 -8
  56. package/dist/types/multiplayer-session.d.ts.map +1 -1
  57. package/dist/types/question.d.ts +0 -1
  58. package/dist/types/question.d.ts.map +1 -1
  59. package/dist/types/question.js +0 -1
  60. package/dist/types/question.js.map +1 -1
  61. package/dist/types/session.d.ts +16 -0
  62. package/dist/types/session.d.ts.map +1 -1
  63. package/dist/vendor/colyseus-schemas/clock.d.ts +15 -0
  64. package/dist/vendor/colyseus-schemas/clock.js +67 -0
  65. package/dist/vendor/colyseus-schemas/common.d.ts +35 -0
  66. package/dist/vendor/colyseus-schemas/common.js +15 -0
  67. package/dist/vendor/colyseus-schemas/multiplayer.d.ts +8 -0
  68. package/dist/vendor/colyseus-schemas/multiplayer.js +26 -0
  69. package/dist/vendor/colyseus-schemas/ugc.d.ts +53 -0
  70. package/dist/vendor/colyseus-schemas/ugc.js +124 -0
  71. package/dist/vendor/gamehub-multiplayer-contracts/index.d.ts +200 -0
  72. package/dist/vendor/gamehub-multiplayer-contracts/index.js +289 -0
  73. package/package.json +34 -4
@@ -0,0 +1,289 @@
1
+ /** Plain-data v2 wire contract. This entry must remain dependency and side-effect free. */
2
+ export const LAUNCH_VERSION = 2;
3
+ export const MULTIPLAYER_CAPABILITY = 'multiplayer.launch.v2';
4
+ export const MULTIPLAYER_LOBBY_CAPABILITY = 'multiplayer.lobby.v2';
5
+ export const CONTROL_TIMEOUT_MS = 10000;
6
+ export const ARRIVAL_WINDOW_MS = 90000;
7
+ export const RECOVERY_GRACE_MS = 60000;
8
+ export const RESERVATION_LEASE_MS = 15000;
9
+ export const BOT_LEVELS = ['easy', 'medium', 'hard'];
10
+ /** Bots stored before levels existed play at `medium`. */
11
+ export const DEFAULT_BOT_LEVEL = 'medium';
12
+ export const isBotLevel = (value) => BOT_LEVELS.includes(value);
13
+ /** UGC bots are game-owned; quiz bots are played by the built-in engine. Relay has none. */
14
+ export const BOT_ENGINES = ['ugc', 'quiz-template'];
15
+ /** Missing policy identifies an existing two-human v2 package/round. */
16
+ export function playerPolicy(binding) {
17
+ return (binding.playerPolicy ?? {
18
+ minPlayers: 2,
19
+ maxPlayers: 2,
20
+ minHumanPlayers: 1,
21
+ maxBots: 0,
22
+ maxSpectators: 16,
23
+ });
24
+ }
25
+ export function parsePlayerPolicy(manifest, ceiling = 256) {
26
+ const minPlayers = manifest.minPlayers;
27
+ const maxPlayers = manifest.maxPlayers;
28
+ const minHumanPlayers = (manifest.minHumanPlayers ?? 1);
29
+ const maxBots = (manifest.maxBots ?? 0);
30
+ if (![minPlayers, maxPlayers, minHumanPlayers, maxBots].every(Number.isSafeInteger) ||
31
+ minPlayers < 1 ||
32
+ maxPlayers < minPlayers ||
33
+ maxPlayers > ceiling ||
34
+ minHumanPlayers < 1 ||
35
+ minHumanPlayers > maxPlayers ||
36
+ maxBots < 0 ||
37
+ maxBots > maxPlayers - minHumanPlayers ||
38
+ typeof manifest.spectators !== 'boolean' ||
39
+ (maxBots > 0 && !BOT_ENGINES.includes(manifest.engine)))
40
+ throw new MultiplayerFault('PROTOCOL_UNSUPPORTED');
41
+ return {
42
+ minPlayers,
43
+ maxPlayers,
44
+ minHumanPlayers,
45
+ maxBots,
46
+ maxSpectators: manifest.spectators ? 16 : 0,
47
+ };
48
+ }
49
+ export const ERROR_CODES = [
50
+ 'INVALID_REQUEST',
51
+ 'UNAUTHORIZED',
52
+ 'LOGIN_REQUIRED',
53
+ 'FORBIDDEN',
54
+ 'NOT_FOUND',
55
+ 'GAME_MISMATCH',
56
+ 'GAME_UNAVAILABLE',
57
+ 'NO_QUESTIONS',
58
+ 'PROTOCOL_UNSUPPORTED',
59
+ 'PASSCODE_REQUIRED',
60
+ 'INVALID_PASSCODE',
61
+ 'ROOM_FULL',
62
+ 'SEAT_REMOVED',
63
+ 'SEAT_LEFT',
64
+ 'ROSTER_FROZEN',
65
+ 'NOT_HOST',
66
+ 'STALE_REVISION',
67
+ 'NOT_READY',
68
+ 'STALE_ATTEMPT',
69
+ 'STALE_GENERATION',
70
+ 'ALREADY_CONNECTED',
71
+ 'LAUNCH_PENDING',
72
+ 'LAUNCH_EXPIRED',
73
+ 'ARRIVAL_TIMEOUT',
74
+ 'RECOVERY_EXPIRED',
75
+ 'INTERRUPTED',
76
+ 'ROUND_TERMINAL',
77
+ 'RESULT_CONFLICT',
78
+ 'INVALID_RESULT',
79
+ 'RATE_LIMITED',
80
+ 'UNAVAILABLE',
81
+ 'CANCELLED',
82
+ 'STORAGE_UNAVAILABLE',
83
+ ];
84
+ export class MultiplayerFault extends Error {
85
+ constructor(code, retryable = false, status = 409) {
86
+ super(errorMessage(code));
87
+ this.code = code;
88
+ this.retryable = retryable;
89
+ this.status = status;
90
+ }
91
+ toJSON() {
92
+ return {
93
+ code: this.code,
94
+ message: this.message,
95
+ retryable: this.retryable,
96
+ };
97
+ }
98
+ }
99
+ export const terminalRound = (phase) => ['completed', 'aborted', 'interrupted'].includes(phase);
100
+ const transitions = {
101
+ preparing: ['loading', 'aborted'],
102
+ loading: ['playing', 'aborted'],
103
+ playing: ['finishing', 'interrupted'],
104
+ finishing: ['completed', 'interrupted'],
105
+ completed: [],
106
+ aborted: [],
107
+ interrupted: [],
108
+ };
109
+ export function canTransition(from, to) {
110
+ return transitions[from]?.includes(to) ?? false;
111
+ }
112
+ export function isRecord(value) {
113
+ return (!!value &&
114
+ typeof value === 'object' &&
115
+ !Array.isArray(value) &&
116
+ (Object.getPrototypeOf(value) === Object.prototype ||
117
+ Object.getPrototypeOf(value) === null));
118
+ }
119
+ export function isBoundedId(value) {
120
+ return typeof value === 'string' && /^[a-zA-Z0-9_-]{1,160}$/.test(value);
121
+ }
122
+ export function isLaunchReference(value) {
123
+ if (!isRecord(value) ||
124
+ value.version !== 2 ||
125
+ (value.recoveryGraceMs !== undefined &&
126
+ (!Number.isSafeInteger(value.recoveryGraceMs) ||
127
+ Number(value.recoveryGraceMs) < 1000 ||
128
+ Number(value.recoveryGraceMs) > 120000)))
129
+ return false;
130
+ return ([
131
+ 'multiplayerSessionId',
132
+ 'roundId',
133
+ 'attemptId',
134
+ 'seatId',
135
+ 'hostInstanceId',
136
+ ].every((k) => isBoundedId(value[k])) &&
137
+ typeof value.gameUrl === 'string' &&
138
+ value.gameUrl.startsWith('/games/') &&
139
+ value.gameUrl.length < 2048 &&
140
+ (value.scoreAuthority === 'server' || value.scoreAuthority === 'unverified'));
141
+ }
142
+ export function isLaunchOutcome(value) {
143
+ if (!isRecord(value))
144
+ return false;
145
+ if (value.status === 'reserved')
146
+ return (isLaunchReference(value.launch) &&
147
+ isRecord(value.reservation) &&
148
+ ['name', 'roomId', 'sessionId'].every((k) => isBoundedId(value.reservation[k])) &&
149
+ typeof value.wsEndpoint === 'string' &&
150
+ /^wss?:\/\//.test(value.wsEndpoint) &&
151
+ value.wsEndpoint.length < 2048 &&
152
+ Number.isSafeInteger(value.generation) &&
153
+ Number(value.generation) > 0 &&
154
+ Number.isSafeInteger(value.expiresAt));
155
+ return ((value.status === 'terminal' || value.status === 'recoverable') &&
156
+ isRecord(value.error) &&
157
+ ERROR_CODES.includes(value.error.code) &&
158
+ typeof value.error.retryable === 'boolean' &&
159
+ typeof value.error.message === 'string' &&
160
+ value.error.message.length <= 1000);
161
+ }
162
+ export function parseResultProposal(value, participantSeatIds) {
163
+ if (!isRecord(value) ||
164
+ value.version !== 2 ||
165
+ !isRecord(value.scores) ||
166
+ !Array.isArray(value.winnerSeatIds) ||
167
+ !['win', 'draw', 'forfeit', 'abort'].includes(String(value.reason)))
168
+ throw new MultiplayerFault('INVALID_RESULT');
169
+ const allowed = new Set(participantSeatIds);
170
+ if (allowed.size !== participantSeatIds.length || !allowed.size)
171
+ throw new MultiplayerFault('INVALID_RESULT');
172
+ const scores = {};
173
+ for (const [seat, score] of Object.entries(value.scores)) {
174
+ if (!allowed.has(seat) ||
175
+ typeof score !== 'number' ||
176
+ !Number.isFinite(score) ||
177
+ Math.abs(score) > 1000000000)
178
+ throw new MultiplayerFault('INVALID_RESULT');
179
+ scores[seat] = score;
180
+ }
181
+ if (Object.keys(scores).length !== allowed.size ||
182
+ new Set(value.winnerSeatIds).size !== value.winnerSeatIds.length ||
183
+ value.winnerSeatIds.some((id) => typeof id !== 'string' || !allowed.has(id)) ||
184
+ (value.reason === 'draw' && value.winnerSeatIds.length !== 0) ||
185
+ (value.reason === 'win' && value.winnerSeatIds.length === 0))
186
+ throw new MultiplayerFault('INVALID_RESULT');
187
+ let metadata;
188
+ if (value.metadata !== undefined) {
189
+ if (!isRecord(value.metadata) ||
190
+ JSON.stringify(value.metadata).length > 4096 ||
191
+ Object.keys(value.metadata).length > 32 ||
192
+ Object.values(value.metadata).some((v) => (v !== null && !['string', 'number', 'boolean'].includes(typeof v)) ||
193
+ (typeof v === 'number' && !Number.isFinite(v))))
194
+ throw new MultiplayerFault('INVALID_RESULT');
195
+ metadata = value.metadata;
196
+ }
197
+ return {
198
+ version: 2,
199
+ scores,
200
+ winnerSeatIds: [...value.winnerSeatIds].sort(),
201
+ reason: value.reason,
202
+ ...(metadata ? { metadata } : {}),
203
+ };
204
+ }
205
+ /** Stable, bounded canonical JSON; callers validate their domain payload first. */
206
+ export function canonicalJson(value) {
207
+ if (Array.isArray(value))
208
+ return '[' + value.map(canonicalJson).join(',') + ']';
209
+ if (isRecord(value))
210
+ return ('{' +
211
+ Object.keys(value)
212
+ .sort()
213
+ .map((k) => JSON.stringify(k) + ':' + canonicalJson(value[k]))
214
+ .join(',') +
215
+ '}');
216
+ const encoded = JSON.stringify(value);
217
+ if (encoded === undefined)
218
+ throw new MultiplayerFault('INVALID_REQUEST');
219
+ return encoded;
220
+ }
221
+ export function normalizeError(error) {
222
+ if (error instanceof MultiplayerFault)
223
+ return error.toJSON();
224
+ const numeric = {
225
+ 4210: 'ROUND_TERMINAL',
226
+ 4211: 'SEAT_REMOVED',
227
+ 4212: 'STALE_GENERATION',
228
+ 4213: 'ALREADY_CONNECTED',
229
+ 4214: 'RECOVERY_EXPIRED',
230
+ 4215: 'ARRIVAL_TIMEOUT',
231
+ 4216: 'INTERRUPTED',
232
+ 4217: 'GAME_UNAVAILABLE',
233
+ 4218: 'INVALID_RESULT',
234
+ 4219: 'NOT_READY',
235
+ 4220: 'LOGIN_REQUIRED',
236
+ 4221: 'UNAVAILABLE',
237
+ 522: 'LAUNCH_EXPIRED',
238
+ };
239
+ const raw = isRecord(error)
240
+ ? error
241
+ : error instanceof Error
242
+ ? {
243
+ code: error.code,
244
+ message: error.message,
245
+ }
246
+ : {};
247
+ const code = typeof raw.code === 'number'
248
+ ? numeric[raw.code]
249
+ : ERROR_CODES.includes(raw.code)
250
+ ? raw.code
251
+ : undefined;
252
+ return {
253
+ code: code ?? 'UNAVAILABLE',
254
+ message: code
255
+ ? errorMessage(code)
256
+ : 'Connection unavailable. Check your network and retry.',
257
+ retryable: !code ||
258
+ ['LAUNCH_EXPIRED', 'UNAVAILABLE', 'LAUNCH_PENDING'].includes(code),
259
+ };
260
+ }
261
+ export function errorMessage(code) {
262
+ const messages = {
263
+ UNAUTHORIZED: 'Sign in, or rejoin with this host’s original guest session.',
264
+ LOGIN_REQUIRED: 'Sign in to play or spectate this game.',
265
+ GAME_MISMATCH: 'This invitation belongs to a different game. Open its invitation link.',
266
+ GAME_UNAVAILABLE: 'This game or its approved package is unavailable. Return to the lobby.',
267
+ NO_QUESTIONS: 'The selected profile has no published questions. Add questions or choose another profile.',
268
+ PROTOCOL_UNSUPPORTED: 'This game and host do not support the same multiplayer version.',
269
+ PASSCODE_REQUIRED: 'Enter the room passcode to join, including as a spectator.',
270
+ INVALID_PASSCODE: 'The passcode is incorrect. Check it and retry.',
271
+ ROOM_FULL: 'There are no free seats of this type.',
272
+ NOT_HOST: 'Only the current lobby host can start or rematch.',
273
+ NOT_READY: 'Meet the required player counts and keep human players connected. Confirm readiness only when this lobby requires it.',
274
+ STALE_REVISION: 'The lobby changed. Refresh its status and retry.',
275
+ ROSTER_FROZEN: 'This round has already selected its players. Join as a spectator or wait for a rematch.',
276
+ LAUNCH_PENDING: 'Your launch is being prepared. Retry shortly.',
277
+ LAUNCH_EXPIRED: 'The reservation expired. Request a fresh launch.',
278
+ ALREADY_CONNECTED: 'This seat is already connected in another tab. Return to that tab.',
279
+ ARRIVAL_TIMEOUT: 'A required player did not arrive in time. Return to the lobby and rematch.',
280
+ RECOVERY_EXPIRED: 'The reconnect window ended. Return to the lobby for a new round.',
281
+ SEAT_REMOVED: 'This seat has left or was removed and cannot reconnect.',
282
+ SEAT_LEFT: 'Your lobby membership ended. Rejoin the room if it is still available.',
283
+ INTERRUPTED: 'The round was interrupted before its result was saved. Return to the lobby.',
284
+ ROUND_TERMINAL: 'This round has ended. Return to the lobby.',
285
+ RATE_LIMITED: 'Too many requests. Wait a moment and retry.',
286
+ UNAVAILABLE: 'The service is temporarily unavailable. Retry or leave the session.',
287
+ };
288
+ return messages[code] ?? code;
289
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ksaa-nlp/gamehub-sdk",
3
- "version": "4.5.0",
4
- "description": "ESM SDK that lets GameHub-hosted games talk to the platform (auth, sessions, scores, bootstrap pipeline). Includes types and a Node-only dev harness for authoring UGC server bundles (`./server`, `./server/dev`). Transport-agnostic — games open their own realtime connection (e.g. via @colyseus/sdk).",
3
+ "version": "5.5.1",
4
+ "description": "ESM SDK that lets GameHub-hosted games talk to the platform (auth, sessions, scores, bootstrap pipeline). The main entry and IIFE bundle are transport-agnostic; the opt-in `./multiplayer` subpath adds the game-owned Colyseus connection for v2 rounds (optional peers @colyseus/sdk and @colyseus/schema). Includes types and a Node-only dev harness for authoring UGC server bundles (`./server`, `./server/dev`).",
5
5
  "type": "module",
6
6
  "main": "./dist/src/main.js",
7
7
  "module": "./dist/src/main.js",
@@ -17,6 +17,11 @@
17
17
  "import": "./dist/src/browser-entry.js",
18
18
  "default": "./dist/src/browser-entry.js"
19
19
  },
20
+ "./multiplayer": {
21
+ "types": "./dist/src/multiplayer-entry.d.ts",
22
+ "import": "./dist/src/multiplayer-entry.js",
23
+ "default": "./dist/src/multiplayer-entry.js"
24
+ },
20
25
  "./server": {
21
26
  "types": "./dist/src/server-entry.d.ts",
22
27
  "import": "./dist/src/server-entry.js",
@@ -30,6 +35,16 @@
30
35
  "./gamehub-sdk.js": "./dist/gamehub-sdk.js",
31
36
  "./package.json": "./package.json"
32
37
  },
38
+ "imports": {
39
+ "#multiplayer-contracts": {
40
+ "types": "./dist/vendor/gamehub-multiplayer-contracts/index.d.ts",
41
+ "default": "./dist/vendor/gamehub-multiplayer-contracts/index.js"
42
+ },
43
+ "#colyseus-schemas/*": {
44
+ "types": "./dist/vendor/colyseus-schemas/*.d.ts",
45
+ "default": "./dist/vendor/colyseus-schemas/*.js"
46
+ }
47
+ },
33
48
  "sideEffects": [
34
49
  "./dist/src/browser-entry.js",
35
50
  "./dist/gamehub-sdk.js"
@@ -41,8 +56,9 @@
41
56
  ],
42
57
  "scripts": {
43
58
  "format": "prettier --write \"**/*.{ts,tsx,js,jsx,md,json}\"",
44
- "build:tsc": "tsc -p ./tsconfig.json",
45
- "build:bundle": "esbuild src/browser-entry.ts --bundle --format=iife --platform=browser --target=es2020 --outfile=dist/gamehub-sdk.js --sourcemap",
59
+ "build:vendor": "npm --prefix ../gamehub-multiplayer-contracts run build && npm --prefix ../colyseus-schemas run build && node scripts/vendor-workspace.mjs",
60
+ "build:tsc": "npm run build:vendor && tsc -p ./tsconfig.json",
61
+ "build:bundle": "esbuild src/browser-entry.ts --bundle --format=iife --platform=browser --target=es2020 --minify --outfile=dist/gamehub-sdk.js --sourcemap",
46
62
  "build": "npm run build:tsc && npm run build:bundle",
47
63
  "test": "npm run build:tsc && node --test test/*.test.mjs",
48
64
  "prepack": "npm run build",
@@ -50,7 +66,21 @@
50
66
  },
51
67
  "author": "KSAANLP",
52
68
  "license": "ISC",
69
+ "peerDependencies": {
70
+ "@colyseus/schema": "^5.0.36",
71
+ "@colyseus/sdk": "^0.18.5"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "@colyseus/schema": {
75
+ "optional": true
76
+ },
77
+ "@colyseus/sdk": {
78
+ "optional": true
79
+ }
80
+ },
53
81
  "devDependencies": {
82
+ "@colyseus/schema": "^5.0.36",
83
+ "@colyseus/sdk": "^0.18.5",
54
84
  "esbuild": "^0.25.0",
55
85
  "typescript": "^6.0.3"
56
86
  }