@caisual/kit 0.5.0 → 0.8.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 (54) hide show
  1. package/dist/kit.d.ts +2 -175
  2. package/dist/kit.js +1418 -48
  3. package/dist/node.d.ts +1 -88
  4. package/dist/node.js +128 -31
  5. package/dist/overlay.d.ts +1 -0
  6. package/dist/overlay.js +1846 -0
  7. package/dist/runtime.d.ts +1 -111
  8. package/dist/runtime.js +160 -32
  9. package/dist/server.d.ts +1 -71
  10. package/dist/server.js +1 -0
  11. package/dist/types/api.d.ts +25 -0
  12. package/dist/types/contracts/biglietto.d.ts +24 -0
  13. package/dist/types/contracts/device.d.ts +66 -0
  14. package/dist/types/contracts/firma.d.ts +21 -0
  15. package/dist/types/contracts/index.d.ts +10 -0
  16. package/dist/types/contracts/keys.d.ts +59 -0
  17. package/dist/types/contracts/manifest.d.ts +118 -0
  18. package/dist/types/contracts/overlay-boards.d.ts +3 -0
  19. package/dist/types/contracts/overlay.d.ts +215 -0
  20. package/dist/types/contracts/runtime.d.ts +70 -0
  21. package/dist/types/contracts/server-js.d.ts +11 -0
  22. package/dist/types/contracts/slug.d.ts +5 -0
  23. package/dist/types/contracts/token-crew.d.ts +21 -0
  24. package/dist/types/daily.d.ts +3 -0
  25. package/dist/types/errors.d.ts +6 -0
  26. package/dist/types/handshake.d.ts +26 -0
  27. package/dist/types/http.d.ts +3 -0
  28. package/dist/types/index.d.ts +217 -0
  29. package/dist/types/kit.d.ts +26 -0
  30. package/dist/types/node/index.d.ts +96 -0
  31. package/dist/types/node/websocket.d.ts +29 -0
  32. package/dist/types/overlay/boards.d.ts +48 -0
  33. package/dist/types/overlay/bridge.d.ts +3 -0
  34. package/dist/types/overlay/host-bridge.d.ts +58 -0
  35. package/dist/types/overlay/i18n.d.ts +122 -0
  36. package/dist/types/overlay/index.d.ts +9 -0
  37. package/dist/types/overlay/shortcut.d.ts +4 -0
  38. package/dist/types/overlay/styles.d.ts +1 -0
  39. package/dist/types/overlay/ui-model.d.ts +45 -0
  40. package/dist/types/overlay/ui.d.ts +80 -0
  41. package/dist/types/overlay/voice-panel.d.ts +13 -0
  42. package/dist/types/protocollo.d.ts +257 -0
  43. package/dist/types/runtime/index.d.ts +127 -0
  44. package/dist/types/server/index.d.ts +72 -0
  45. package/dist/types/session/index.d.ts +49 -0
  46. package/dist/types/session/resume.d.ts +13 -0
  47. package/dist/types/standalone.d.ts +14 -0
  48. package/dist/types/stanza/index.d.ts +3 -0
  49. package/dist/types/stanza/json.d.ts +18 -0
  50. package/dist/types/stanza/nucleo.d.ts +97 -0
  51. package/dist/types/stanza/tipi.d.ts +134 -0
  52. package/dist/types/stanza-client/index.d.ts +24 -0
  53. package/dist/types/voce/index.d.ts +124 -0
  54. package/package.json +10 -2
package/dist/kit.js CHANGED
@@ -1,4 +1,4 @@
1
- // Caisual game kit v0.5.0
1
+ // Caisual game kit v0.8.0
2
2
 
3
3
  // ../contracts/src/slug.ts
4
4
  var NOMI_RISERVATI = [
@@ -34,6 +34,550 @@ var NOMI_RISERVATI = [
34
34
  "shipz"
35
35
  ];
36
36
  var RISERVATI = new Set(NOMI_RISERVATI);
37
+ var SLUG_NUOVO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
38
+ var SLUG_STORICO = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
39
+ function isValidSlug(value) {
40
+ return value.length >= 3 && value.length <= 32 && SLUG_NUOVO.test(value) || SLUG_STORICO.test(value);
41
+ }
42
+ function isReservedSlug(value) {
43
+ return RISERVATI.has(value);
44
+ }
45
+
46
+ // ../contracts/src/manifest.ts
47
+ function risolviModalita(manifest, mode) {
48
+ const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
49
+ if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");
50
+ return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
51
+ }
52
+ function modalitaLocale(manifest, mode) {
53
+ return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
54
+ }
55
+ var TETTO_GIOCATORI = 24;
56
+ var RITARDO_SPETTATORI_MS = 3e3;
57
+ var MASSIMO_CLASSIFICHE = 32;
58
+ var CAMPI = /* @__PURE__ */ new Set([
59
+ "overlay",
60
+ "manifest",
61
+ "id",
62
+ "name",
63
+ "description",
64
+ "cover",
65
+ "screenshots",
66
+ "tags",
67
+ "language",
68
+ "platform",
69
+ "orientation",
70
+ "input",
71
+ "visibility",
72
+ "network",
73
+ "isolated",
74
+ "requires",
75
+ "players",
76
+ "lobby",
77
+ "persistent",
78
+ "spectators",
79
+ "boards",
80
+ "roles",
81
+ "teams",
82
+ "voice",
83
+ "modes"
84
+ ]);
85
+ var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
86
+ var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
87
+ var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
88
+ var VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);
89
+ var VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);
90
+ var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
91
+ var TAG = /^[a-z0-9-]+$/;
92
+ var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
93
+ var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
94
+ var ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
95
+ function oggetto(value) {
96
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
97
+ return value;
98
+ }
99
+ function percorsoRelativo(value) {
100
+ if (value === "" || value.startsWith("/") || value.includes("\\") || value.includes("\0")) return false;
101
+ if (value.includes("?") || value.includes("#")) return false;
102
+ const parti = value.split("/");
103
+ if (parti.some((parte) => parte === "" || parte === "." || parte === "..")) return false;
104
+ try {
105
+ const decoded = parti.map((parte) => decodeURIComponent(parte));
106
+ return !decoded.some((parte) => parte === "" || parte === "." || parte === ".." || parte.includes("/"));
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+ function hostValido(value) {
112
+ if (value.length === 0 || value.length > 253) return false;
113
+ if (value.includes("://") || /[/:?#@]/.test(value)) return false;
114
+ const parti = value.split(".");
115
+ return parti.every(
116
+ (parte) => parte.length >= 1 && parte.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(parte)
117
+ );
118
+ }
119
+ function interoTra(value, min, max) {
120
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
121
+ }
122
+ function stringaDefault(dati, campo, valoreDefault, errori) {
123
+ const value = dati[campo];
124
+ if (value === void 0) return valoreDefault;
125
+ if (typeof value !== "string") {
126
+ errori.push(`${campo}: must be a string.`);
127
+ return valoreDefault;
128
+ }
129
+ return value;
130
+ }
131
+ function testoFacoltativo(value, key, max, path, errors) {
132
+ if (value[key] === void 0) return void 0;
133
+ const text = value[key];
134
+ if (typeof text !== "string" || text.trim().length === 0 || text.trim().length > max || /[\r\n\u0000-\u001f]/.test(text)) {
135
+ errors.push(`${path}.${key}: must contain 1-${max} characters on one line.`);
136
+ return void 0;
137
+ }
138
+ return text.trim();
139
+ }
140
+ function validaManifest(valore) {
141
+ const errori = [];
142
+ const dati = oggetto(valore);
143
+ if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
144
+ for (const campo of Object.keys(dati)) {
145
+ if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
146
+ }
147
+ if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
148
+ else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
149
+ const id = stringaDefault(dati, "id", "", errori);
150
+ if (dati.id === void 0) errori.push("id: is required.");
151
+ else if (typeof dati.id === "string") {
152
+ if (!isValidSlug(id)) {
153
+ errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters.");
154
+ } else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");
155
+ }
156
+ const name = stringaDefault(dati, "name", "", errori);
157
+ if (dati.name === void 0) errori.push("name: is required.");
158
+ else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
159
+ errori.push("name: must contain 1-60 characters.");
160
+ }
161
+ const description = stringaDefault(dati, "description", "", errori);
162
+ if (description.length > 500) errori.push("description: must be at most 500 characters.");
163
+ let cover = null;
164
+ if (dati.cover !== void 0 && dati.cover !== null) {
165
+ if (typeof dati.cover !== "string") errori.push("cover: must be a relative file path or null.");
166
+ else if (!percorsoRelativo(dati.cover)) errori.push("cover: must be a relative file path without query, fragment, or parent segments.");
167
+ else cover = dati.cover;
168
+ }
169
+ const screenshots = [];
170
+ if (dati.screenshots !== void 0) {
171
+ if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");
172
+ else {
173
+ if (dati.screenshots.length > 8) errori.push("screenshots: must contain at most 8 paths.");
174
+ for (const [indice, value] of dati.screenshots.entries()) {
175
+ if (typeof value !== "string" || !percorsoRelativo(value)) {
176
+ errori.push(`screenshots[${indice}]: must be a relative file path without query, fragment, or parent segments.`);
177
+ } else screenshots.push(value);
178
+ }
179
+ }
180
+ }
181
+ const tags = [];
182
+ if (dati.tags !== void 0) {
183
+ if (!Array.isArray(dati.tags)) errori.push("tags: must be an array.");
184
+ else {
185
+ if (dati.tags.length > 10) errori.push("tags: must contain at most 10 tags.");
186
+ for (const [indice, value] of dati.tags.entries()) {
187
+ if (typeof value !== "string" || value.length > 24 || !TAG.test(value)) {
188
+ errori.push(`tags[${indice}]: must be 1-24 lowercase letters, digits, or hyphens.`);
189
+ } else tags.push(value);
190
+ }
191
+ }
192
+ }
193
+ const language = stringaDefault(dati, "language", "en", errori);
194
+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language)) {
195
+ errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
196
+ }
197
+ let platform = "both";
198
+ if (dati.platform === void 0) errori.push("platform: is required.");
199
+ else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
200
+ errori.push("platform: must be desktop, mobile, or both.");
201
+ } else platform = dati.platform;
202
+ let orientation = "landscape";
203
+ if (dati.orientation !== void 0) {
204
+ if (typeof dati.orientation !== "string" || !ORIENTATION.has(dati.orientation)) {
205
+ errori.push("orientation: must be landscape or portrait.");
206
+ } else orientation = dati.orientation;
207
+ }
208
+ const input = [];
209
+ if (dati.input !== void 0) {
210
+ if (!Array.isArray(dati.input)) errori.push("input: must be an array.");
211
+ else for (const [indice, value] of dati.input.entries()) {
212
+ if (typeof value !== "string" || !INPUT.has(value)) {
213
+ errori.push(`input[${indice}]: must be keyboard, mouse, touch, or gamepad.`);
214
+ } else if (input.includes(value)) errori.push(`input[${indice}]: duplicate value ${value}.`);
215
+ else input.push(value);
216
+ }
217
+ }
218
+ let visibility = "public";
219
+ if (dati.visibility !== void 0) {
220
+ if (typeof dati.visibility !== "string" || !VISIBILITY.has(dati.visibility)) {
221
+ errori.push("visibility: must be public or unlisted.");
222
+ } else visibility = dati.visibility;
223
+ }
224
+ const network = [];
225
+ if (dati.network !== void 0) {
226
+ if (!Array.isArray(dati.network)) errori.push("network: must be an array of host names.");
227
+ else for (const [indice, value] of dati.network.entries()) {
228
+ if (typeof value !== "string" || !hostValido(value)) {
229
+ errori.push(`network[${indice}]: must be a host name without scheme, port, path, query, or fragment.`);
230
+ } else if (network.includes(value)) errori.push(`network[${indice}]: duplicate host ${value}.`);
231
+ else network.push(value);
232
+ }
233
+ }
234
+ let isolated = false;
235
+ if (dati.isolated !== void 0) {
236
+ if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
237
+ else isolated = dati.isolated;
238
+ }
239
+ const requires = {
240
+ webgl2: false,
241
+ webgpu: false,
242
+ wasm: false,
243
+ threads: false,
244
+ memoryMb: null,
245
+ performance: "light"
246
+ };
247
+ if (dati.requires !== void 0) {
248
+ const value = oggetto(dati.requires);
249
+ if (value === null) errori.push("requires: must be an object.");
250
+ else {
251
+ for (const campo of Object.keys(value)) {
252
+ if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {
253
+ errori.push(`requires.${campo}: unknown field.`);
254
+ }
255
+ }
256
+ for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
257
+ if (value[campo] === void 0) continue;
258
+ if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);
259
+ else requires[campo] = value[campo];
260
+ }
261
+ if (value.memoryMb !== void 0) {
262
+ if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {
263
+ errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");
264
+ } else requires.memoryMb = value.memoryMb;
265
+ }
266
+ if (value.performance !== void 0) {
267
+ if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {
268
+ errori.push("requires.performance: must be light, medium, or heavy.");
269
+ } else requires.performance = value.performance;
270
+ }
271
+ if (requires.threads && !isolated) errori.push("requires.threads: needs isolated: true.");
272
+ }
273
+ }
274
+ let players = { min: 1, max: 1 };
275
+ if (dati.players !== void 0) {
276
+ const value = oggetto(dati.players);
277
+ if (value === null) errori.push("players: must be an object with min and max.");
278
+ else {
279
+ for (const campo of Object.keys(value)) {
280
+ if (campo !== "min" && campo !== "max") errori.push(`players.${campo}: unknown field.`);
281
+ }
282
+ if (!interoTra(value.min, 1, TETTO_GIOCATORI)) errori.push(`players.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
283
+ if (!interoTra(value.max, 1, TETTO_GIOCATORI)) errori.push(`players.max: must be an integer from 1 to ${TETTO_GIOCATORI} in manifest version 1.`);
284
+ if (interoTra(value.min, 1, TETTO_GIOCATORI) && interoTra(value.max, 1, TETTO_GIOCATORI)) {
285
+ if (value.min > value.max) errori.push("players.max: must be greater than or equal to players.min.");
286
+ else players = { min: value.min, max: value.max };
287
+ }
288
+ }
289
+ }
290
+ let lobby = false;
291
+ if (dati.lobby !== void 0) {
292
+ if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");
293
+ else lobby = dati.lobby;
294
+ }
295
+ let persistent = false;
296
+ if (dati.persistent !== void 0) {
297
+ if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
298
+ else persistent = dati.persistent;
299
+ }
300
+ let spectators = { delayMs: RITARDO_SPETTATORI_MS };
301
+ if (dati.spectators === false || dati.spectators === null) spectators = null;
302
+ else if (dati.spectators !== void 0 && dati.spectators !== true) {
303
+ const value = oggetto(dati.spectators);
304
+ if (value === null) {
305
+ errori.push("spectators: must be a boolean or an object with delayMs.");
306
+ } else {
307
+ for (const campo of Object.keys(value)) {
308
+ if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);
309
+ }
310
+ if (!interoTra(value.delayMs, 0, 3e4)) {
311
+ errori.push("spectators.delayMs: must be an integer from 0 to 30000.");
312
+ } else spectators = { delayMs: value.delayMs };
313
+ }
314
+ }
315
+ let overlay = null;
316
+ if (dati.overlay !== void 0 && dati.overlay !== null) {
317
+ const value = oggetto(dati.overlay);
318
+ if (value === null) errori.push("overlay: must be an object or null.");
319
+ else {
320
+ for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);
321
+ if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");
322
+ if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {
323
+ errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");
324
+ }
325
+ overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };
326
+ }
327
+ }
328
+ const boards = {};
329
+ if (dati.boards !== void 0) {
330
+ const value = oggetto(dati.boards);
331
+ if (value === null) errori.push("boards: must be an object of board ids.");
332
+ else {
333
+ if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {
334
+ errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);
335
+ }
336
+ for (const [id2, raw] of Object.entries(value)) {
337
+ let valido = true;
338
+ if (!ID_CLASSIFICA.test(id2)) {
339
+ errori.push(`boards.${id2}: invalid board id.`);
340
+ valido = false;
341
+ }
342
+ const board = oggetto(raw);
343
+ if (board === null) {
344
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
345
+ continue;
346
+ }
347
+ for (const campo of Object.keys(board)) {
348
+ if (!["source", "label", "periods"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
349
+ }
350
+ if (board.source !== "client" && board.source !== "server") {
351
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
352
+ valido = false;
353
+ }
354
+ const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
355
+ let periods = ["all-time"];
356
+ if (board.periods !== void 0) {
357
+ if (!Array.isArray(board.periods) || board.periods.length < 1 || board.periods.length > 2 || board.periods.some((period) => period !== "daily" && period !== "all-time") || new Set(board.periods).size !== board.periods.length) {
358
+ errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);
359
+ } else periods = [...board.periods];
360
+ }
361
+ if (valido) Object.defineProperty(boards, id2, { value: {
362
+ source: board.source,
363
+ periods,
364
+ ...label === void 0 ? {} : { label }
365
+ }, enumerable: true, configurable: true, writable: true });
366
+ }
367
+ }
368
+ }
369
+ const roles = [];
370
+ if (dati.roles !== void 0) {
371
+ if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
372
+ else {
373
+ const ids = /* @__PURE__ */ new Set();
374
+ for (const [indice, raw] of dati.roles.entries()) {
375
+ const value = oggetto(raw);
376
+ if (value === null) {
377
+ errori.push(`roles[${indice}]: must be an object.`);
378
+ continue;
379
+ }
380
+ for (const campo of Object.keys(value)) {
381
+ if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
382
+ }
383
+ const idRuolo = value.id;
384
+ const min = value.min;
385
+ const max = value.max;
386
+ let valido = true;
387
+ if (typeof idRuolo !== "string" || idRuolo.length > 32 || !ID_INTERNO.test(idRuolo)) {
388
+ errori.push(`roles[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
389
+ valido = false;
390
+ } else if (ids.has(idRuolo)) {
391
+ errori.push(`roles[${indice}].id: duplicate role ${idRuolo}.`);
392
+ valido = false;
393
+ } else ids.add(idRuolo);
394
+ if (!interoTra(min, 0, TETTO_GIOCATORI)) {
395
+ errori.push(`roles[${indice}].min: must be an integer from 0 to ${TETTO_GIOCATORI}.`);
396
+ valido = false;
397
+ }
398
+ if (max !== void 0 && !interoTra(max, 0, TETTO_GIOCATORI)) {
399
+ errori.push(`roles[${indice}].max: must be an integer from 0 to ${TETTO_GIOCATORI} when present.`);
400
+ valido = false;
401
+ }
402
+ if (typeof min === "number" && typeof max === "number" && min > max) {
403
+ errori.push(`roles[${indice}].max: must be greater than or equal to min.`);
404
+ valido = false;
405
+ }
406
+ const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);
407
+ if (valido) roles.push({
408
+ id: idRuolo,
409
+ min,
410
+ ...max === void 0 ? {} : { max },
411
+ ...label === void 0 ? {} : { label }
412
+ });
413
+ }
414
+ }
415
+ }
416
+ let teams = null;
417
+ if (dati.teams !== void 0 && dati.teams !== null) {
418
+ const value = oggetto(dati.teams);
419
+ if (value === null) errori.push("teams: must be null or an object with min and max.");
420
+ else {
421
+ for (const campo of Object.keys(value)) {
422
+ if (campo !== "min" && campo !== "max") errori.push(`teams.${campo}: unknown field.`);
423
+ }
424
+ if (!interoTra(value.min, 2, TETTO_GIOCATORI)) errori.push(`teams.min: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
425
+ if (!interoTra(value.max, 2, TETTO_GIOCATORI)) errori.push(`teams.max: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
426
+ if (interoTra(value.min, 2, TETTO_GIOCATORI) && interoTra(value.max, 2, TETTO_GIOCATORI)) {
427
+ if (value.min > value.max) errori.push("teams.max: must be greater than or equal to teams.min.");
428
+ else teams = { min: value.min, max: value.max };
429
+ }
430
+ }
431
+ }
432
+ let voice = "none";
433
+ if (dati.voice !== void 0) {
434
+ if (typeof dati.voice !== "string" || !VOICE.has(dati.voice)) {
435
+ errori.push("voice: must be none, room, team, or proximity.");
436
+ } else voice = dati.voice;
437
+ }
438
+ const modes = [];
439
+ if (dati.modes !== void 0) {
440
+ if (!Array.isArray(dati.modes)) errori.push("modes: must be an array.");
441
+ else {
442
+ const ids = /* @__PURE__ */ new Set();
443
+ for (const [indice, raw] of dati.modes.entries()) {
444
+ const value = oggetto(raw);
445
+ if (value === null) {
446
+ errori.push(`modes[${indice}]: must be an object.`);
447
+ continue;
448
+ }
449
+ for (const campo of Object.keys(value)) {
450
+ if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
451
+ }
452
+ if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
453
+ errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
454
+ continue;
455
+ }
456
+ if (ids.has(value.id)) {
457
+ errori.push(`modes[${indice}].id: duplicate mode ${value.id}.`);
458
+ continue;
459
+ }
460
+ ids.add(value.id);
461
+ const modo = { id: value.id };
462
+ for (const [key2, max] of [["label", 48], ["instructions", 160]]) {
463
+ const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);
464
+ if (text !== void 0) modo[key2] = text;
465
+ }
466
+ if (value.execution !== void 0) {
467
+ if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);
468
+ else modo.execution = value.execution;
469
+ }
470
+ if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);
471
+ if (value.players !== void 0) {
472
+ const campo = `modes[${indice}].players`;
473
+ const range = oggetto(value.players);
474
+ if (range === null) errori.push(`${campo}: must be an object with min and max.`);
475
+ else {
476
+ for (const key2 of Object.keys(range)) {
477
+ if (key2 !== "min" && key2 !== "max") errori.push(`${campo}.${key2}: unknown field.`);
478
+ }
479
+ if (!interoTra(range.min, 1, TETTO_GIOCATORI)) errori.push(`${campo}.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
480
+ if (!interoTra(range.max, 1, TETTO_GIOCATORI)) errori.push(`${campo}.max: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
481
+ if (interoTra(range.min, 1, TETTO_GIOCATORI) && interoTra(range.max, 1, TETTO_GIOCATORI)) {
482
+ if (range.min > range.max) errori.push(`${campo}.max: must be greater than or equal to min.`);
483
+ else modo.players = { min: range.min, max: range.max };
484
+ }
485
+ }
486
+ }
487
+ if (value.lobby !== void 0) {
488
+ if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);
489
+ else modo.lobby = value.lobby;
490
+ }
491
+ if (modo.execution === "local") {
492
+ const range = modo.players ?? players;
493
+ if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);
494
+ if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);
495
+ if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);
496
+ }
497
+ if (value.matchmaking === void 0) {
498
+ modes.push(modo);
499
+ continue;
500
+ }
501
+ const matchmaking = oggetto(value.matchmaking);
502
+ if (matchmaking === null) {
503
+ errori.push(`modes[${indice}].matchmaking: must be an object.`);
504
+ continue;
505
+ }
506
+ for (const campo of Object.keys(matchmaking)) {
507
+ if (!["key", "timeoutMs", "defaults"].includes(campo)) {
508
+ errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);
509
+ }
510
+ }
511
+ let valido = true;
512
+ const key = [];
513
+ if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {
514
+ errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);
515
+ valido = false;
516
+ } else for (const [keyIndice, item] of matchmaking.key.entries()) {
517
+ if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {
518
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);
519
+ valido = false;
520
+ } else if (key.includes(item)) {
521
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);
522
+ valido = false;
523
+ } else key.push(item);
524
+ }
525
+ if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {
526
+ errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);
527
+ valido = false;
528
+ }
529
+ let defaults;
530
+ if (matchmaking.defaults !== void 0) {
531
+ const values = oggetto(matchmaking.defaults);
532
+ if (values === null || Object.keys(values).length !== key.length || key.some((field) => !Object.hasOwn(values, field))) {
533
+ errori.push(`modes[${indice}].matchmaking.defaults: must contain exactly the declared key fields.`);
534
+ } else {
535
+ defaults = {};
536
+ for (const [field, value2] of Object.entries(values)) {
537
+ if (!(typeof value2 === "string" && value2.length >= 1 && value2.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value2)) && !Number.isSafeInteger(value2)) {
538
+ errori.push(`modes[${indice}].matchmaking.defaults.${field}: must be a string of 1-64 characters or a safe integer.`);
539
+ } else Object.defineProperty(defaults, field, { value: value2, enumerable: true });
540
+ }
541
+ }
542
+ }
543
+ if (valido) modes.push({ ...modo, matchmaking: {
544
+ ...defaults === void 0 ? {} : { defaults },
545
+ key,
546
+ timeoutMs: matchmaking.timeoutMs
547
+ } });
548
+ }
549
+ }
550
+ }
551
+ if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");
552
+ if (errori.length > 0) return { ok: false, errori };
553
+ return { ok: true, manifest: {
554
+ manifest: 1,
555
+ overlay,
556
+ id,
557
+ name,
558
+ description,
559
+ cover,
560
+ screenshots,
561
+ tags,
562
+ language,
563
+ platform,
564
+ orientation,
565
+ input,
566
+ visibility,
567
+ network,
568
+ isolated,
569
+ requires,
570
+ players,
571
+ lobby,
572
+ persistent,
573
+ spectators,
574
+ boards,
575
+ roles,
576
+ teams,
577
+ voice,
578
+ modes
579
+ } };
580
+ }
37
581
 
38
582
  // ../contracts/src/device.ts
39
583
  function deviceTier(report) {
@@ -165,6 +709,81 @@ async function probeDevice(globals, timeoutMs = 1500) {
165
709
  return { ...report, tier: deviceTier(report) };
166
710
  }
167
711
 
712
+ // ../contracts/src/overlay.ts
713
+ function overlayConfiguration(manifest, coverUrl = null, invite = null) {
714
+ const validated = validaManifest(manifest);
715
+ if (!validated.ok) throw new Error("The overlay manifest is invalid.");
716
+ return { manifest: validated.manifest, coverUrl, invite };
717
+ }
718
+ function record(value) {
719
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
720
+ }
721
+ function validOverlayHello(value) {
722
+ const hello = record(value), config = record(hello?.configuration);
723
+ return hello?.v === 1 && typeof hello.epoch === "string" && hello.epoch.length > 0 && hello.epoch.length <= 128 && config !== null && (config.coverUrl === null || typeof config.coverUrl === "string") && (config.invite === null || typeof config.invite === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(config.invite)) && validaManifest(config.manifest).ok;
724
+ }
725
+ function normalizeOverlayHello(value) {
726
+ if (!validOverlayHello(value)) return null;
727
+ return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite) };
728
+ }
729
+ function validOverlayView(value) {
730
+ const data = record(value);
731
+ return data !== null && Object.keys(data).every((key) => ["inputBlocked", "reservedRects", "shortcutEnabled"].includes(key)) && (data.shortcutEnabled === void 0 || typeof data.shortcutEnabled === "boolean") && typeof data.inputBlocked === "boolean" && Array.isArray(data.reservedRects) && data.reservedRects.length <= 8 && data.reservedRects.every((value2) => {
732
+ const rect = record(value2);
733
+ return rect !== null && Object.keys(rect).length === 4 && ["x", "y", "width", "height"].every((key) => typeof rect[key] === "number" && Number.isFinite(rect[key]) && rect[key] >= 0 && rect[key] <= 1e5);
734
+ });
735
+ }
736
+ function validOverlayRequest(value) {
737
+ const message = record(value), args = record(message?.args);
738
+ if (message?.type !== "caisual:overlay" || message.v !== 1 || typeof message.epoch !== "string" || message.epoch.length < 1 || message.epoch.length > 128 || typeof message.requestId !== "string" || !(/^[1-9][0-9]{0,15}$/.test(message.requestId) && Number.isSafeInteger(Number(message.requestId))) || args === null) return false;
739
+ if (Object.keys(message).some((key) => !["type", "v", "epoch", "requestId", "sessionId", "op", "args"].includes(key)) || !(message.sessionId === void 0 || message.sessionId === null || typeof message.sessionId === "string" && /^[1-9][0-9]{0,15}$/.test(message.sessionId))) return false;
740
+ const keys = (...allowed) => Object.keys(args).every((key) => allowed.includes(key));
741
+ const text = (key) => typeof args[key] === "string" && args[key].length >= 1 && args[key].length <= 64;
742
+ switch (message.op) {
743
+ case "local.start":
744
+ return keys("mode") && text("mode");
745
+ case "room.create":
746
+ return keys("mode") && (args.mode === null || text("mode"));
747
+ case "room.join":
748
+ return keys("code") && (args.code === void 0 || text("code"));
749
+ case "room.watch":
750
+ return keys("code") && text("code");
751
+ case "room.match": {
752
+ const key = record(args.key);
753
+ return keys("mode", "key") && text("mode") && (args.key === void 0 || key !== null && Object.keys(key).length <= 8 && Object.values(key).every((v) => typeof v === "string" && v.length >= 1 && v.length <= 64 || typeof v === "number" && Number.isSafeInteger(v)));
754
+ }
755
+ case "room.ready":
756
+ return keys("ready") && typeof args.ready === "boolean";
757
+ case "room.role":
758
+ case "room.requestRole":
759
+ return keys("role") && text("role");
760
+ case "room.team":
761
+ return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;
762
+ case "room.start":
763
+ case "session.cancel":
764
+ case "session.leave":
765
+ case "session.disconnect":
766
+ case "session.resume":
767
+ return keys();
768
+ case "voice.join":
769
+ case "voice.leave":
770
+ return keys() && typeof message.sessionId === "string";
771
+ case "voice.mute":
772
+ return keys("muted") && typeof args.muted === "boolean" && typeof message.sessionId === "string";
773
+ case "voice.setVolume":
774
+ return keys("playerId", "volume") && typeof message.sessionId === "string" && typeof args.playerId === "string" && args.playerId.length > 0 && args.playerId.length <= 128 && typeof args.volume === "number" && Number.isFinite(args.volume) && args.volume >= 0 && args.volume <= 1;
775
+ case "overlay.view":
776
+ return validOverlayView(args);
777
+ default:
778
+ return false;
779
+ }
780
+ }
781
+ function validBoardDay(value) {
782
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
783
+ const at = Date.parse(`${value}T00:00:00Z`);
784
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
785
+ }
786
+
168
787
  // src/errors.ts
169
788
  function creaErrore(code, message) {
170
789
  return Object.assign(new Error(message), { name: "CaisualError", code });
@@ -176,6 +795,546 @@ function codiceErrore(valore) {
176
795
  return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
177
796
  }
178
797
 
798
+ // src/session/resume.ts
799
+ var KEY = "caisual-session-v1";
800
+ function resume(value) {
801
+ const data = record(value);
802
+ if (!data || typeof data.code !== "string" || !/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(data.code) || !(data.mode === void 0 || data.mode === null || typeof data.mode === "string")) return null;
803
+ return {
804
+ version: 1,
805
+ code: data.code,
806
+ mode: typeof data.mode === "string" ? data.mode : null,
807
+ updatedAt: typeof data.updatedAt === "number" && Number.isFinite(data.updatedAt) ? data.updatedAt : 0
808
+ };
809
+ }
810
+ function createResume(save, changed) {
811
+ let current = null, error = false, work = Promise.resolve();
812
+ const write = async () => {
813
+ const value = { version: 1, imported: true, resume: current };
814
+ work = work.catch(() => void 0).then(async () => {
815
+ try {
816
+ await save.set(KEY, value);
817
+ error = false;
818
+ } catch (cause) {
819
+ error = true;
820
+ throw cause;
821
+ } finally {
822
+ changed();
823
+ }
824
+ });
825
+ return work;
826
+ };
827
+ const loaded = (async () => {
828
+ try {
829
+ const data = record(await save.get(KEY));
830
+ if (data?.version === 1 && data.imported === true) current = resume(data.resume);
831
+ else {
832
+ current = resume(await save.get("resume"));
833
+ await write();
834
+ }
835
+ } catch {
836
+ error = true;
837
+ }
838
+ changed();
839
+ })();
840
+ return {
841
+ loaded,
842
+ get value() {
843
+ return current === null ? null : { ...current };
844
+ },
845
+ get error() {
846
+ return error;
847
+ },
848
+ async set(value) {
849
+ await loaded;
850
+ current = value;
851
+ changed();
852
+ await write();
853
+ }
854
+ };
855
+ }
856
+
857
+ // src/session/index.ts
858
+ function notify(listeners, value) {
859
+ for (const listener of listeners) {
860
+ try {
861
+ listener(value);
862
+ } catch {
863
+ }
864
+ }
865
+ }
866
+ function createSession(base, configuration = null, roomsAvailable = base.connected) {
867
+ const standard = configuration?.manifest.overlay?.version === 1;
868
+ const manifest = configuration?.manifest;
869
+ let current = { kind: "idle" }, ready = false, operation = 0, identifier = 0;
870
+ let pending = null, pendingMode = null;
871
+ let waiting = null, controller = null;
872
+ let stops = [], disposed = false, lastState = "";
873
+ let view = { inputBlocked: false, reservedRects: [] };
874
+ const listeners = /* @__PURE__ */ new Set();
875
+ const viewListeners = /* @__PURE__ */ new Set();
876
+ const stateListeners = /* @__PURE__ */ new Set();
877
+ const openListeners = /* @__PURE__ */ new Set();
878
+ const errorListeners = /* @__PURE__ */ new Set();
879
+ const scoreListeners = /* @__PURE__ */ new Set();
880
+ let resumeStore = null;
881
+ const capabilities = () => ({
882
+ local: true,
883
+ rooms: roomsAvailable,
884
+ overlay: standard,
885
+ requestRole: current.kind === "room" && current.room.metadata.configuration?.requestRole === true
886
+ });
887
+ function voiceSnapshot() {
888
+ if (current.kind !== "room" || !manifest || manifest.voice === "none") return null;
889
+ const room = current.room, voice = room.voice;
890
+ if (!voice || voice.mode === "none" || room.players.find((p) => p.id === room.you)?.role === "spectator") return null;
891
+ return {
892
+ mode: voice.mode,
893
+ state: voice.state,
894
+ mic: voice.mic,
895
+ muted: voice.muted,
896
+ speaking: voice.speaking,
897
+ peers: voice.peers.map(({ id, mic, muted, speaking, volume }) => ({ id, mic, muted, speaking, volume }))
898
+ };
899
+ }
900
+ function snapshot() {
901
+ const attached = current.kind === "room" || current.kind === "watch" ? current.room : null;
902
+ const configured = attached?.metadata.configuration;
903
+ const fallback = manifest && attached && (attached.mode === null || manifest.modes.some((m) => m.id === attached.mode)) ? risolviModalita(manifest, attached.mode) : { players: { min: 1, max: 1 }, lobby: false };
904
+ return {
905
+ kind: pending ?? (current.kind === "idle" ? ready ? "home" : "boot" : current.kind),
906
+ id: current.kind === "idle" ? null : current.id,
907
+ mode: pending ? pendingMode : current.kind === "local" ? current.mode : attached?.mode ?? null,
908
+ localStatus: current.kind === "local" ? current.status : null,
909
+ ready,
910
+ capabilities: capabilities(),
911
+ room: attached ? {
912
+ code: attached.code,
913
+ mode: attached.mode,
914
+ status: attached.status,
915
+ host: attached.host,
916
+ you: current.kind === "room" ? current.room.you : null,
917
+ players: attached.players.map((p) => ({ id: p.id, name: p.name, guest: p.guest, role: p.role, team: p.team, ready: p.ready, connected: p.connected })),
918
+ countdownAt: attached.countdownAt,
919
+ connection: attached.connection,
920
+ closedCode: attached.metadata.closedCode,
921
+ limits: { ...configured?.players ?? fallback.players },
922
+ lobby: configured?.lobby ?? fallback.lobby,
923
+ persistent: configured?.persistent ?? manifest?.persistent ?? false,
924
+ delayMs: current.kind === "watch" ? current.room.delayMs : null,
925
+ requestRole: configured?.requestRole ?? false
926
+ } : null,
927
+ voice: pending ? null : voiceSnapshot(),
928
+ waiting: waiting ? { ...waiting } : null,
929
+ resume: resumeStore?.value ?? null,
930
+ resumeError: resumeStore?.error ?? false
931
+ };
932
+ }
933
+ function emit() {
934
+ if (disposed) return;
935
+ const state = snapshot(), serialized = JSON.stringify(state);
936
+ if (serialized === lastState) return;
937
+ lastState = serialized;
938
+ notify(stateListeners, state);
939
+ }
940
+ function changed() {
941
+ notify(listeners, { ...current });
942
+ emit();
943
+ }
944
+ function active() {
945
+ if (current.kind !== "room") throw creaErrore("no_room", "There is no active player room.");
946
+ return current.room;
947
+ }
948
+ function activeVoice() {
949
+ const room = active();
950
+ if (room.players.find((p) => p.id === room.you)?.role === "spectator") throw creaErrore("spectator", "Spectators cannot use voice controls.");
951
+ if (!manifest || manifest.voice === "none" || room.voice.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
952
+ return room.voice;
953
+ }
954
+ function cancel() {
955
+ operation++;
956
+ controller?.abort();
957
+ controller = null;
958
+ pending = null;
959
+ waiting = null;
960
+ emit();
961
+ }
962
+ function detach(preserve) {
963
+ stops.splice(0).forEach((stop) => stop());
964
+ if (current.kind === "room" || current.kind === "watch") {
965
+ if (preserve) current.room.disconnect();
966
+ else current.room.leave();
967
+ }
968
+ current = { kind: "idle" };
969
+ changed();
970
+ }
971
+ async function clearResume(code) {
972
+ if (resumeStore?.value?.code === code) await resumeStore.set(null).catch(() => void 0);
973
+ }
974
+ async function adopt(next, watch, token) {
975
+ if (token !== operation || disposed) {
976
+ next.leave();
977
+ throw creaErrore("cancelled", "The operation was cancelled.");
978
+ }
979
+ detach(false);
980
+ current = watch ? { kind: "watch", room: next, id: String(++identifier) } : { kind: "room", room: next, id: String(++identifier) };
981
+ const room = next;
982
+ stops = [room.onPlayers(emit), room.onMetadata(() => {
983
+ if (room.connection === "disconnected" && (current.kind === "room" || current.kind === "watch") && current.room === room) {
984
+ stops.splice(0).forEach((stop) => stop());
985
+ if (!watch && room.metadata.closedCode === 1e3) void clearResume(room.code);
986
+ current = { kind: "idle" };
987
+ changed();
988
+ } else emit();
989
+ }), room.onStatus(() => {
990
+ emit();
991
+ if (!watch && room.connection === "ended") void clearResume(room.code);
992
+ })];
993
+ if (!watch) {
994
+ const playerRoom = next;
995
+ const sessionId = current.id;
996
+ if (playerRoom.voice) stops.push(playerRoom.voice.onState(emit), playerRoom.voice.onPeers(emit));
997
+ stops.push(playerRoom.onError((error) => notify(errorListeners, { sessionId, error: { ...error } })));
998
+ stops.push(playerRoom.onScoreQueued((score) => notify(scoreListeners, { ...score })));
999
+ for (const score of playerRoom.queuedScores) notify(scoreListeners, { ...score });
1000
+ }
1001
+ pending = null;
1002
+ waiting = null;
1003
+ changed();
1004
+ if (!watch && resumeStore && room.connection !== "ended") {
1005
+ await resumeStore.set({ version: 1, code: room.code, mode: room.mode, updatedAt: base.time.now() }).catch(() => void 0);
1006
+ }
1007
+ return next;
1008
+ }
1009
+ async function run(kind, mode, work, watch = false) {
1010
+ cancel();
1011
+ const token = operation;
1012
+ controller = new AbortController();
1013
+ pending = kind;
1014
+ pendingMode = mode;
1015
+ emit();
1016
+ try {
1017
+ const next = await work(controller.signal, token);
1018
+ await adopt(next, watch, token);
1019
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1020
+ return next;
1021
+ } finally {
1022
+ if (token === operation) {
1023
+ pending = null;
1024
+ waiting = null;
1025
+ controller = null;
1026
+ emit();
1027
+ }
1028
+ }
1029
+ }
1030
+ const direct = base.room;
1031
+ const rooms = !standard ? direct : {
1032
+ invited: direct.invited,
1033
+ create(options) {
1034
+ if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot create rooms."));
1035
+ return run("attaching", options.mode, () => direct.create(options));
1036
+ },
1037
+ join(code) {
1038
+ return run("attaching", null, () => direct.join(code));
1039
+ },
1040
+ watch(code) {
1041
+ return run("attaching", null, () => direct.watch(code), true);
1042
+ },
1043
+ match(options) {
1044
+ if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot use matchmaking."));
1045
+ return run("matching", options.mode, (signal, token) => {
1046
+ const abort = () => {
1047
+ if (operation === token) cancel();
1048
+ };
1049
+ options.signal?.addEventListener("abort", abort, { once: true });
1050
+ if (options.signal?.aborted) abort();
1051
+ return direct.match({ ...options, signal, onWaiting(value) {
1052
+ if (token !== operation) return;
1053
+ waiting = { ...value };
1054
+ emit();
1055
+ options.onWaiting?.(value);
1056
+ } }).finally(() => options.signal?.removeEventListener("abort", abort));
1057
+ });
1058
+ }
1059
+ };
1060
+ if (standard) resumeStore = createResume(base.save, emit);
1061
+ const session = {
1062
+ get current() {
1063
+ return { ...current };
1064
+ },
1065
+ get capabilities() {
1066
+ return capabilities();
1067
+ },
1068
+ onChange(listener) {
1069
+ listeners.add(listener);
1070
+ notify(/* @__PURE__ */ new Set([listener]), { ...current });
1071
+ return () => {
1072
+ listeners.delete(listener);
1073
+ };
1074
+ },
1075
+ ready() {
1076
+ if (disposed || ready) return;
1077
+ ready = true;
1078
+ emit();
1079
+ },
1080
+ finish() {
1081
+ if (current.kind === "room" || current.kind === "watch") throw creaErrore("not_local", "Only a local session can be finished by the client.");
1082
+ if (current.kind === "local") {
1083
+ current = { ...current, status: "ended" };
1084
+ changed();
1085
+ }
1086
+ }
1087
+ };
1088
+ const overlay = {
1089
+ open(panel) {
1090
+ if (!["home", "room", "invite", "friends", "voice", "boards"].includes(panel)) throw creaErrore("invalid_request", "Unknown overlay panel.");
1091
+ if (standard) notify(openListeners, panel);
1092
+ },
1093
+ onChange(listener) {
1094
+ viewListeners.add(listener);
1095
+ notify(/* @__PURE__ */ new Set([listener]), structuredClone(view));
1096
+ return () => {
1097
+ viewListeners.delete(listener);
1098
+ };
1099
+ }
1100
+ };
1101
+ return {
1102
+ session,
1103
+ overlay,
1104
+ rooms,
1105
+ snapshot,
1106
+ serverTime: () => current.kind === "room" || current.kind === "watch" ? current.room.serverTime() : base.time.now(),
1107
+ onState(listener) {
1108
+ stateListeners.add(listener);
1109
+ listener(snapshot());
1110
+ return () => {
1111
+ stateListeners.delete(listener);
1112
+ };
1113
+ },
1114
+ onOpen(listener) {
1115
+ openListeners.add(listener);
1116
+ return () => {
1117
+ openListeners.delete(listener);
1118
+ };
1119
+ },
1120
+ onError(listener) {
1121
+ errorListeners.add(listener);
1122
+ return () => {
1123
+ errorListeners.delete(listener);
1124
+ };
1125
+ },
1126
+ onScore(listener) {
1127
+ scoreListeners.add(listener);
1128
+ return () => {
1129
+ scoreListeners.delete(listener);
1130
+ };
1131
+ },
1132
+ async execute(request) {
1133
+ if (!standard) throw creaErrore("overlay_disabled", "This game uses its own room flow.");
1134
+ if (request.op === "overlay.view") {
1135
+ if (!validOverlayView(request.args)) throw creaErrore("invalid_request", "The overlay geometry is invalid.");
1136
+ view = structuredClone(request.args);
1137
+ notify(viewListeners, structuredClone(view));
1138
+ return;
1139
+ }
1140
+ if (request.sessionId !== void 0 && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1141
+ if (request.op.startsWith("voice.") && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1142
+ if (!ready) throw creaErrore("game_not_ready", "The game is still loading.");
1143
+ switch (request.op) {
1144
+ case "local.start": {
1145
+ if (!manifest || !modalitaLocale(manifest, request.args.mode)) throw creaErrore("invalid_mode", "This is not a local mode.");
1146
+ cancel();
1147
+ const token = operation;
1148
+ if (current.kind === "room") await clearResume(current.room.code);
1149
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1150
+ detach(false);
1151
+ current = { kind: "local", id: String(++identifier), mode: request.args.mode, status: "playing" };
1152
+ changed();
1153
+ return;
1154
+ }
1155
+ case "room.create":
1156
+ await rooms.create(request.args);
1157
+ return;
1158
+ case "room.join":
1159
+ await rooms.join(request.args.code);
1160
+ return;
1161
+ case "room.watch":
1162
+ await rooms.watch(request.args.code);
1163
+ return;
1164
+ case "room.match": {
1165
+ const mode = manifest?.modes.find((m) => m.id === request.args.mode);
1166
+ const key = request.args.key ?? mode?.matchmaking?.defaults;
1167
+ if (!key) throw creaErrore("invalid_request", "Matchmaking needs a complete key.");
1168
+ await rooms.match({ mode: request.args.mode, key });
1169
+ return;
1170
+ }
1171
+ case "voice.join": {
1172
+ const room = active(), voice = activeVoice();
1173
+ await voice.join();
1174
+ if (current.kind !== "room" || current.room !== room) throw creaErrore("session_replaced", "The active session changed.");
1175
+ emit();
1176
+ return;
1177
+ }
1178
+ case "voice.mute":
1179
+ activeVoice().mute(request.args.muted);
1180
+ emit();
1181
+ return;
1182
+ case "voice.leave":
1183
+ activeVoice().leave();
1184
+ emit();
1185
+ return;
1186
+ case "voice.setVolume": {
1187
+ const voice = activeVoice();
1188
+ if (!voice.peers.some((peer) => peer.id === request.args.playerId)) throw creaErrore("voice_peer_missing", "This voice participant is no longer available.");
1189
+ voice.setVolume(request.args.playerId, request.args.volume);
1190
+ emit();
1191
+ return;
1192
+ }
1193
+ case "room.ready":
1194
+ active().ready(request.args.ready);
1195
+ return;
1196
+ case "room.role":
1197
+ active().setRole(request.args.role);
1198
+ return;
1199
+ case "room.requestRole":
1200
+ await active().requestRole(request.args.role);
1201
+ return;
1202
+ case "room.team":
1203
+ active().setTeam(request.args.team);
1204
+ return;
1205
+ case "room.start":
1206
+ active().start();
1207
+ return;
1208
+ case "session.cancel":
1209
+ cancel();
1210
+ return;
1211
+ case "session.resume": {
1212
+ await run("attaching", null, async (signal) => {
1213
+ await resumeStore?.loaded;
1214
+ if (signal.aborted) throw creaErrore("cancelled", "The operation was cancelled.");
1215
+ if (!resumeStore?.value) throw creaErrore("no_resume", "There is no saved room.");
1216
+ return direct.join(resumeStore.value.code);
1217
+ });
1218
+ return;
1219
+ }
1220
+ case "session.disconnect": {
1221
+ cancel();
1222
+ const token = operation;
1223
+ if (current.kind === "room" && current.room.connection !== "ended" && resumeStore) await resumeStore.set({ version: 1, code: current.room.code, mode: current.room.mode, updatedAt: base.time.now() });
1224
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1225
+ detach(true);
1226
+ return;
1227
+ }
1228
+ case "session.leave": {
1229
+ cancel();
1230
+ const token = operation;
1231
+ if (current.kind === "room") await clearResume(current.room.code);
1232
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1233
+ detach(false);
1234
+ return;
1235
+ }
1236
+ }
1237
+ },
1238
+ dispose() {
1239
+ cancel();
1240
+ detach(true);
1241
+ disposed = true;
1242
+ listeners.clear();
1243
+ viewListeners.clear();
1244
+ stateListeners.clear();
1245
+ openListeners.clear();
1246
+ scoreListeners.clear();
1247
+ errorListeners.clear();
1248
+ }
1249
+ };
1250
+ }
1251
+
1252
+ // src/overlay/shortcut.ts
1253
+ function bindOverlayShortcut(target, overlay, open) {
1254
+ let enabled = true, blocked = false;
1255
+ const stop = overlay.onChange((view) => {
1256
+ enabled = view.shortcutEnabled !== false;
1257
+ blocked = view.inputBlocked;
1258
+ });
1259
+ const listener = (event) => {
1260
+ const element = event.target;
1261
+ if (!enabled || blocked || event.repeat || event.key !== "Tab" || !event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || element?.closest?.('input,textarea,select,[contenteditable="true"]')) return;
1262
+ event.preventDefault();
1263
+ event.stopImmediatePropagation();
1264
+ open();
1265
+ };
1266
+ target.addEventListener("keydown", listener, true);
1267
+ return () => {
1268
+ stop();
1269
+ target.removeEventListener("keydown", listener, true);
1270
+ };
1271
+ }
1272
+
1273
+ // src/overlay/bridge.ts
1274
+ function attachKitBridge(port, hello, coordinator) {
1275
+ let disposed = false, seq = 0, highestRequest = 0, activeRequests = 0;
1276
+ const replies = /* @__PURE__ */ new Map();
1277
+ const send = (message) => {
1278
+ if (!disposed) try {
1279
+ port.postMessage(message);
1280
+ } catch {
1281
+ }
1282
+ };
1283
+ const stops = [
1284
+ ...hello.configuration.manifest.overlay && typeof window !== "undefined" ? [bindOverlayShortcut(window, coordinator.overlay, () => send({ type: "caisual:overlay-shortcut", v: 1, epoch: hello.epoch }))] : [],
1285
+ coordinator.onState((state) => send({ type: "caisual:overlay-state", v: 1, epoch: hello.epoch, seq: ++seq, serverTime: coordinator.serverTime(), state })),
1286
+ coordinator.onOpen((panel) => send({ type: "caisual:overlay-open", v: 1, epoch: hello.epoch, panel })),
1287
+ coordinator.onError(({ sessionId, error }) => send({ type: "caisual:overlay-error", v: 1, epoch: hello.epoch, sessionId, error })),
1288
+ coordinator.onScore((score) => send({ type: "caisual:overlay-score", v: 1, epoch: hello.epoch, score }))
1289
+ ];
1290
+ const listener = (event) => {
1291
+ const raw = record(event.data);
1292
+ if (raw?.type !== "caisual:overlay" || raw.epoch !== hello.epoch || disposed) return;
1293
+ const reply = { type: "caisual:overlay-response", v: 1, epoch: hello.epoch, requestId: typeof raw.requestId === "string" ? raw.requestId : "" };
1294
+ if (!validOverlayRequest(raw)) {
1295
+ send({ ...reply, ok: false, error: { code: "invalid_request", message: "The overlay request is invalid." } });
1296
+ return;
1297
+ }
1298
+ const fingerprint = JSON.stringify([raw.op, raw.args, raw.sessionId]);
1299
+ const previous = replies.get(raw.requestId);
1300
+ if (previous) {
1301
+ if (previous.fingerprint !== fingerprint) send({ ...reply, ok: false, error: { code: "duplicate_request", message: "The request id was already used." } });
1302
+ else void previous.response.then(send);
1303
+ return;
1304
+ }
1305
+ if (Number(raw.requestId) <= highestRequest || activeRequests >= 32) {
1306
+ send({ ...reply, ok: false, error: { code: "stale_request", message: "The request is stale or too many requests are pending." } });
1307
+ return;
1308
+ }
1309
+ highestRequest = Number(raw.requestId);
1310
+ activeRequests++;
1311
+ const response = Promise.resolve().then(() => coordinator.execute(raw)).then(
1312
+ () => ({ ...reply, ok: true }),
1313
+ (error) => ({ ...reply, ok: false, error: {
1314
+ code: typeof record(error)?.code === "string" ? record(error).code : "internal_error",
1315
+ message: error instanceof Error ? error.message : "The operation could not be completed."
1316
+ } })
1317
+ );
1318
+ replies.set(raw.requestId, { fingerprint, response });
1319
+ void response.then((value) => {
1320
+ activeRequests--;
1321
+ send(value);
1322
+ if (replies.size > 64) for (const id of replies.keys()) {
1323
+ if (Number(id) < highestRequest - 64) replies.delete(id);
1324
+ }
1325
+ });
1326
+ };
1327
+ port.addEventListener("message", listener);
1328
+ port.start();
1329
+ return () => {
1330
+ disposed = true;
1331
+ port.removeEventListener("message", listener);
1332
+ stops.forEach((stop) => stop());
1333
+ coordinator.dispose();
1334
+ replies.clear();
1335
+ };
1336
+ }
1337
+
179
1338
  // src/http.ts
180
1339
  async function leggiErrore(response) {
181
1340
  let corpo = {};
@@ -258,10 +1417,18 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
258
1417
  },
259
1418
  async boardSubmit(board, score, daily) {
260
1419
  const risultato = await richiesta("/scores", "POST", { board, score, daily });
261
- return { accepted: true, best: risultato.best, rank: risultato.rank, day: risultato.day };
1420
+ return {
1421
+ accepted: true,
1422
+ best: risultato.best,
1423
+ rank: risultato.rank,
1424
+ day: risultato.day,
1425
+ verified: risultato.verified
1426
+ };
262
1427
  },
263
1428
  async boardTop(board, opzioni) {
1429
+ if (opzioni.day !== void 0 && (!validBoardDay(opzioni.day) || opzioni.daily === false)) throw creaErrore("invalid_request", "day must be a real UTC date and cannot be combined with daily: false.");
264
1430
  const query = new URLSearchParams();
1431
+ if (opzioni.day !== void 0) query.set("day", opzioni.day);
265
1432
  if (opzioni.daily) query.set("daily", "1");
266
1433
  if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));
267
1434
  if (opzioni.guests) query.set("guests", "1");
@@ -297,11 +1464,11 @@ function creaMulberry32(seed) {
297
1464
  }
298
1465
 
299
1466
  // src/handshake.ts
300
- function record(valore) {
1467
+ function record2(valore) {
301
1468
  return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
302
1469
  }
303
1470
  function eTipo(valore, tipo) {
304
- return record(valore)?.type === tipo;
1471
+ return record2(valore)?.type === tipo;
305
1472
  }
306
1473
  function leggiOrigine(valore) {
307
1474
  if (typeof valore !== "string") return null;
@@ -315,6 +1482,7 @@ function leggiOrigine(valore) {
315
1482
  function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
316
1483
  return new Promise((resolve) => {
317
1484
  let concluso = false;
1485
+ const instance = globalThis.crypto.randomUUID();
318
1486
  const termina = (esito) => {
319
1487
  if (concluso) return;
320
1488
  concluso = true;
@@ -323,7 +1491,7 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
323
1491
  resolve(esito);
324
1492
  };
325
1493
  const segnalaPronto = () => {
326
- finestra.parent.postMessage({ type: "caisual:ready" }, appOrigin);
1494
+ finestra.parent.postMessage({ type: "caisual:ready", instance, overlayVersion: 1 }, appOrigin);
327
1495
  };
328
1496
  const ascolta = (evento) => {
329
1497
  if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;
@@ -332,11 +1500,13 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
332
1500
  return;
333
1501
  }
334
1502
  if (!eTipo(evento.data, "caisual:hello")) return;
335
- const dati = record(evento.data);
1503
+ const dati = record2(evento.data);
336
1504
  const porta = evento.ports[0];
337
1505
  if (typeof dati?.ticket !== "string" || porta === void 0) return;
338
1506
  porta.start();
1507
+ const overlay = normalizeOverlayHello(dati.overlay);
339
1508
  termina({
1509
+ ...overlay ? { overlay } : {},
340
1510
  ticket: dati.ticket,
341
1511
  live: leggiOrigine(dati.live),
342
1512
  invite: typeof dati.invite === "string" ? dati.invite : null,
@@ -356,7 +1526,7 @@ function scadenzaJwt(ticket) {
356
1526
  "="
357
1527
  );
358
1528
  try {
359
- const payload = record(JSON.parse(globalThis.atob(base64)));
1529
+ const payload = record2(JSON.parse(globalThis.atob(base64)));
360
1530
  return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
361
1531
  } catch {
362
1532
  return null;
@@ -374,7 +1544,7 @@ function chiediBiglietto(porta, finestra, timeoutMs, aud) {
374
1544
  else resolve(ticket);
375
1545
  };
376
1546
  const ascolta = (evento) => {
377
- const dati = record(evento.data);
1547
+ const dati = record2(evento.data);
378
1548
  const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;
379
1549
  if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {
380
1550
  termina(dati.ticket);
@@ -457,6 +1627,7 @@ var VoceClient = class {
457
1627
  this.riproduzioni = /* @__PURE__ */ new Map();
458
1628
  this.sfuAttive = /* @__PURE__ */ new Map();
459
1629
  this.midGiocatori = /* @__PURE__ */ new Map();
1630
+ this.negati = /* @__PURE__ */ new Set();
460
1631
  this.mesh = /* @__PURE__ */ new Map();
461
1632
  this.stream = null;
462
1633
  this.tracciaMic = null;
@@ -549,6 +1720,8 @@ var VoceClient = class {
549
1720
  }
550
1721
  this.mutedCorrente = muted;
551
1722
  this.tracciaMic.enabled = !muted;
1723
+ if (muted) this.speakingCorrente = false;
1724
+ this.notificaPeers();
552
1725
  void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
553
1726
  }
554
1727
  setVolume(playerId, volume) {
@@ -581,6 +1754,7 @@ var VoceClient = class {
581
1754
  return;
582
1755
  }
583
1756
  if (message.op === "roster") {
1757
+ this.negati.clear();
584
1758
  this.modeCorrente = message.mode;
585
1759
  const publisher = new Set(message.peers.map((peer) => peer.id));
586
1760
  this.roster = [
@@ -597,6 +1771,7 @@ var VoceClient = class {
597
1771
  return;
598
1772
  }
599
1773
  if (message.op === "gain") {
1774
+ this.negati.clear();
600
1775
  for (const [playerId, gain] of Object.entries(message.gains)) {
601
1776
  this.gains.set(playerId, limita(gain));
602
1777
  this.aggiornaZero(playerId);
@@ -606,9 +1781,24 @@ var VoceClient = class {
606
1781
  this.accodaRiconciliazione();
607
1782
  return;
608
1783
  }
1784
+ if (message.op === "closed") {
1785
+ for (const mid of message.mids) {
1786
+ const playerId = this.midGiocatori.get(mid);
1787
+ if (playerId === void 0) continue;
1788
+ const attiva = this.sfuAttive.get(playerId);
1789
+ if (attiva?.mid === mid && !this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
1790
+ if (attiva?.mid === mid) this.sfuAttive.delete(playerId);
1791
+ this.midGiocatori.delete(mid);
1792
+ this.scollegaTraccia(playerId);
1793
+ this.negati.add(playerId);
1794
+ }
1795
+ this.notificaPeers();
1796
+ return;
1797
+ }
609
1798
  if (message.op === "signal") void this.riceviSegnale(message.from, message.data);
610
1799
  }
611
1800
  giocatoriCambiati() {
1801
+ this.negati.clear();
612
1802
  const presenti = new Set(this.contesto.giocatori().map((player) => player.id));
613
1803
  for (const playerId of this.gains.keys()) {
614
1804
  if (presenti.has(playerId)) continue;
@@ -666,10 +1856,6 @@ var VoceClient = class {
666
1856
  const dipendenze = this.richiediDipendenze();
667
1857
  const audioContext = dipendenze.creaAudioContext();
668
1858
  this.audioContext = audioContext;
669
- try {
670
- await audioContext.resume();
671
- } catch {
672
- }
673
1859
  if (this.micDesiderato) {
674
1860
  let stream;
675
1861
  try {
@@ -693,6 +1879,11 @@ var VoceClient = class {
693
1879
  mic.enabled = !this.mutedCorrente;
694
1880
  this.preparaAnalizzatore(stream);
695
1881
  }
1882
+ try {
1883
+ await audioContext.resume();
1884
+ } catch {
1885
+ }
1886
+ this.controllaGenerazione(generazione);
696
1887
  const risposta = await this.richiedi({ t: "voice", op: "ice" });
697
1888
  this.controllaGenerazione(generazione);
698
1889
  if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
@@ -827,12 +2018,19 @@ var VoceClient = class {
827
2018
  }
828
2019
  const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));
829
2020
  if (nuove.length === 0) return;
830
- const risposta = await this.richiedi({
831
- t: "voice",
832
- op: "subscribe",
833
- session: sessione,
834
- tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
835
- });
2021
+ let risposta;
2022
+ try {
2023
+ risposta = await this.richiedi({
2024
+ t: "voice",
2025
+ op: "subscribe",
2026
+ session: sessione,
2027
+ tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
2028
+ });
2029
+ } catch (cause) {
2030
+ if (codiceErrore(cause) !== "not_allowed") throw cause;
2031
+ for (const peer of nuove) this.negati.add(peer.id);
2032
+ return;
2033
+ }
836
2034
  if (risposta.op !== "subscribe") {
837
2035
  throw creaErrore("voice_error", "The voice service returned an invalid response.");
838
2036
  }
@@ -840,6 +2038,7 @@ var VoceClient = class {
840
2038
  const peer = nuove.find(
841
2039
  (item) => item.session === risultato.session && item.track === risultato.track
842
2040
  );
2041
+ if (risultato.error === "not_allowed" && peer !== void 0) this.negati.add(peer.id);
843
2042
  if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;
844
2043
  this.midGiocatori.set(risultato.mid, peer.id);
845
2044
  this.sfuAttive.set(peer.id, {
@@ -946,8 +2145,17 @@ var VoceClient = class {
946
2145
  this.avviaRiconnessione();
947
2146
  }
948
2147
  }
949
- inviaSegnale(to, data) {
950
- return this.richiedi({ t: "voice", op: "signal", to, data });
2148
+ async inviaSegnale(to, data) {
2149
+ try {
2150
+ await this.richiedi({ t: "voice", op: "signal", to, data });
2151
+ } catch (cause) {
2152
+ if (codiceErrore(cause) !== "not_allowed") throw cause;
2153
+ const item = this.mesh.get(to);
2154
+ item?.pc.close();
2155
+ this.mesh.delete(to);
2156
+ this.scollegaTraccia(to);
2157
+ this.negati.add(to);
2158
+ }
951
2159
  }
952
2160
  peerDesiderati() {
953
2161
  const you = this.contesto.you();
@@ -955,6 +2163,7 @@ var VoceClient = class {
955
2163
  const player = giocatori.find((item) => item.id === you);
956
2164
  return this.roster.filter((peer) => {
957
2165
  if (peer.id === you) return false;
2166
+ if (this.negati.has(peer.id)) return false;
958
2167
  if (!this.micDesiderato && !peer.mic) return false;
959
2168
  if (this.modeCorrente === "team") {
960
2169
  const altro = giocatori.find((item) => item.id === peer.id);
@@ -1175,6 +2384,7 @@ var VoceClient = class {
1175
2384
  this.mesh.clear();
1176
2385
  this.sfuAttive.clear();
1177
2386
  this.midGiocatori.clear();
2387
+ this.negati.clear();
1178
2388
  for (const track of this.stream?.getTracks() ?? []) track.stop();
1179
2389
  this.stream = null;
1180
2390
  this.tracciaMic = null;
@@ -1265,20 +2475,20 @@ var RITARDO_FLUSH = 500;
1265
2475
  var ATTESA_ROSTER = 2e3;
1266
2476
  var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
1267
2477
  var CHIUSURE_DEFINITIVE_SPETTATORE = /* @__PURE__ */ new Set([4008, 4009]);
1268
- function record2(value) {
2478
+ function record3(value) {
1269
2479
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1270
2480
  }
1271
2481
  function ingressoValido(value) {
1272
- const dati = record2(value);
2482
+ const dati = record3(value);
1273
2483
  return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
1274
2484
  }
1275
2485
  function visioneValida(value) {
1276
- const dati = record2(value);
2486
+ const dati = record3(value);
1277
2487
  return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.watch === "string" && typeof dati.url === "string";
1278
2488
  }
1279
2489
  function rispostaMatchValida(value) {
1280
- const dati = record2(value);
1281
- const players = record2(dati?.players);
2490
+ const dati = record3(value);
2491
+ const players = record3(dati?.players);
1282
2492
  return dati !== null && typeof dati.url === "string" && Number.isInteger(dati.timeoutMs) && dati.timeoutMs >= 1e3 && dati.timeoutMs <= 3e5 && players !== null && Number.isInteger(players.min) && Number.isInteger(players.max) && players.min >= 1 && players.max >= players.min;
1283
2493
  }
1284
2494
  function copiaJson(value) {
@@ -1300,11 +2510,11 @@ function applicaPatch(state, value) {
1300
2510
  if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };
1301
2511
  contenitore = contenitore[parte];
1302
2512
  } else {
1303
- const oggetto = record2(contenitore);
1304
- if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {
2513
+ const oggetto2 = record3(contenitore);
2514
+ if (oggetto2 === null || typeof parte !== "string" || !Object.hasOwn(oggetto2, parte)) {
1305
2515
  return { ok: false };
1306
2516
  }
1307
- contenitore = oggetto[parte];
2517
+ contenitore = oggetto2[parte];
1308
2518
  }
1309
2519
  }
1310
2520
  const ultima = percorso.at(-1);
@@ -1312,13 +2522,13 @@ function applicaPatch(state, value) {
1312
2522
  if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };
1313
2523
  contenitore[ultima] = copiaJson(operazione.value);
1314
2524
  } else {
1315
- const oggetto = record2(contenitore);
1316
- if (oggetto === null || typeof ultima !== "string") return { ok: false };
2525
+ const oggetto2 = record3(contenitore);
2526
+ if (oggetto2 === null || typeof ultima !== "string") return { ok: false };
1317
2527
  if (operazione.op === "del") {
1318
- if (!Object.hasOwn(oggetto, ultima)) return { ok: false };
1319
- delete oggetto[ultima];
2528
+ if (!Object.hasOwn(oggetto2, ultima)) return { ok: false };
2529
+ delete oggetto2[ultima];
1320
2530
  } else {
1321
- Object.defineProperty(oggetto, ultima, {
2531
+ Object.defineProperty(oggetto2, ultima, {
1322
2532
  configurable: true,
1323
2533
  enumerable: true,
1324
2534
  value: copiaJson(operazione.value),
@@ -1376,6 +2586,14 @@ var StanzaClient = class {
1376
2586
  this.api = api;
1377
2587
  this.segnalaStanza = segnalaStanza;
1378
2588
  this.spettatore = spettatore;
2589
+ this.meta = { host: null, mode: null, countdownAt: null, configuration: null, connection: "connecting", closedCode: null };
2590
+ this.metaListeners = /* @__PURE__ */ new Set();
2591
+ this.connectionListeners = /* @__PURE__ */ new Set();
2592
+ this.scoreListeners = /* @__PURE__ */ new Set();
2593
+ this.scores = [];
2594
+ this.errorListeners = /* @__PURE__ */ new Set();
2595
+ this.roleId = 0;
2596
+ this.roleRequests = /* @__PURE__ */ new Map();
1379
2597
  this.statoPubblico = null;
1380
2598
  this.statoSincronizzato = null;
1381
2599
  this.tickCorrente = 0;
@@ -1426,6 +2644,100 @@ var StanzaClient = class {
1426
2644
  if (spettatore) this.rosterRicevuto = true;
1427
2645
  this.apri(url);
1428
2646
  }
2647
+ get mode() {
2648
+ return this.meta.mode;
2649
+ }
2650
+ get countdownAt() {
2651
+ return this.meta.countdownAt;
2652
+ }
2653
+ get connection() {
2654
+ return this.meta.connection;
2655
+ }
2656
+ get metadata() {
2657
+ return structuredClone(this.meta);
2658
+ }
2659
+ get queuedScores() {
2660
+ return structuredClone(this.scores);
2661
+ }
2662
+ onMetadata(listener) {
2663
+ this.metaListeners.add(listener);
2664
+ return () => this.metaListeners.delete(listener);
2665
+ }
2666
+ onConnection(listener) {
2667
+ this.connectionListeners.add(listener);
2668
+ return () => this.connectionListeners.delete(listener);
2669
+ }
2670
+ onError(listener) {
2671
+ this.errorListeners.add(listener);
2672
+ return () => this.errorListeners.delete(listener);
2673
+ }
2674
+ onScoreQueued(listener) {
2675
+ this.scoreListeners.add(listener);
2676
+ return () => this.scoreListeners.delete(listener);
2677
+ }
2678
+ metadataChanged(change) {
2679
+ const old = this.meta.connection;
2680
+ this.meta = { ...this.meta, ...change };
2681
+ this.notifica(this.metaListeners, this.metadata);
2682
+ if (old !== this.meta.connection) this.notifica(this.connectionListeners, this.meta.connection);
2683
+ }
2684
+ initialMetadata(room) {
2685
+ this.metadataChanged({
2686
+ host: room.host,
2687
+ mode: room.mode,
2688
+ countdownAt: room.countdownAt ?? null,
2689
+ configuration: room.configuration ?? null,
2690
+ connection: "connected",
2691
+ closedCode: null
2692
+ });
2693
+ }
2694
+ requestRole(role) {
2695
+ if (typeof role !== "string" || role.length < 1 || role.length > 32) return Promise.reject(creaErrore("invalid_role", "The role is not valid."));
2696
+ if (this.connection !== "connected" || this.status !== "playing" || !this.meta.configuration?.requestRole) {
2697
+ return Promise.reject(creaErrore("role_change_unavailable", "Roles cannot be requested right now."));
2698
+ }
2699
+ if (this.roleRequests.size >= 8) return Promise.reject(creaErrore("rate_limited", "Too many role requests."));
2700
+ const r = ++this.roleId;
2701
+ return new Promise((resolve, reject) => {
2702
+ const timer = this.input.setTimeout(() => {
2703
+ this.roleRequests.delete(r);
2704
+ reject(creaErrore("timeout", "The role request timed out."));
2705
+ }, 5e3);
2706
+ this.roleRequests.set(r, { resolve, reject, timer });
2707
+ try {
2708
+ this.invia({ t: "request-role", r, role });
2709
+ } catch (error) {
2710
+ this.input.clearTimeout(timer);
2711
+ this.roleRequests.delete(r);
2712
+ reject(error);
2713
+ }
2714
+ });
2715
+ }
2716
+ clearRoleRequests() {
2717
+ for (const request of this.roleRequests.values()) {
2718
+ this.input.clearTimeout(request.timer);
2719
+ request.reject(creaErrore("offline", "The room connection ended."));
2720
+ }
2721
+ this.roleRequests.clear();
2722
+ }
2723
+ disconnect() {
2724
+ if (this.lasciata) return;
2725
+ this.lasciata = true;
2726
+ const socket = this.socket;
2727
+ this.socket = null;
2728
+ this.voice.termina();
2729
+ this.fermaPing();
2730
+ this.fermaRiconnessione();
2731
+ this.clearRoleRequests();
2732
+ if (this.timerRoster !== null) this.input.clearTimeout(this.timerRoster);
2733
+ socket?.close(1e3);
2734
+ this.segnalaStanza(null);
2735
+ this.metadataChanged({ connection: "disconnected", closedCode: null });
2736
+ if (!this.prontaRisolta) {
2737
+ this.prontaRisolta = true;
2738
+ this.rifiutaPronta(creaErrore("cancelled", "The room was disconnected."));
2739
+ }
2740
+ }
1429
2741
  get state() {
1430
2742
  return this.statoPubblico;
1431
2743
  }
@@ -1579,23 +2891,36 @@ var StanzaClient = class {
1579
2891
  let dati;
1580
2892
  try {
1581
2893
  const value = JSON.parse(frame);
1582
- const oggetto = record2(value);
1583
- if (oggetto === null || typeof oggetto.t !== "string") return;
1584
- dati = oggetto;
2894
+ const oggetto2 = record3(value);
2895
+ if (oggetto2 === null || typeof oggetto2.t !== "string") return;
2896
+ dati = oggetto2;
1585
2897
  } catch {
1586
2898
  return;
1587
2899
  }
1588
2900
  try {
1589
2901
  if (dati.t === "watching") this.riceviWatching(dati);
1590
2902
  else if (dati.t === "welcome") this.riceviWelcome(dati);
1591
- else if (dati.t === "players") this.riceviGiocatori(dati.players);
2903
+ else if (dati.t === "players") this.riceviGiocatori(dati.players, dati.host);
1592
2904
  else if (dati.t === "status") this.riceviStatus(dati);
1593
2905
  else if (dati.t === "state") this.riceviDiff(dati);
1594
2906
  else if (dati.t === "snapshot") this.riceviSnapshot(dati);
1595
2907
  else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));
1596
2908
  else if (dati.t === "pong") this.riceviPong(dati);
2909
+ else if (dati.t === "error") this.notifica(this.errorListeners, { code: dati.code, message: dati.message });
1597
2910
  else if (dati.t === "flush") this.richiediFlush();
1598
- else if (dati.t === "voice") this.voice.ricevi(dati);
2911
+ else if (dati.t === "score-queued" && !this.spettatore) {
2912
+ this.scores.push(structuredClone(dati.score));
2913
+ this.scores = this.scores.slice(-32);
2914
+ this.notifica(this.scoreListeners, structuredClone(dati.score));
2915
+ } else if (dati.t === "role-result") {
2916
+ const request = this.roleRequests.get(dati.r);
2917
+ if (request) {
2918
+ this.input.clearTimeout(request.timer);
2919
+ this.roleRequests.delete(dati.r);
2920
+ if (dati.ok) request.resolve();
2921
+ else request.reject(creaErrore(dati.code ?? "role_change_refused", "The role change was not accepted."));
2922
+ }
2923
+ } else if (dati.t === "voice") this.voice.ricevi(dati);
1599
2924
  } catch {
1600
2925
  if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();
1601
2926
  }
@@ -1621,6 +2946,7 @@ var StanzaClient = class {
1621
2946
  this.resultCorrente,
1622
2947
  room.serverTime
1623
2948
  );
2949
+ this.initialMetadata(room);
1624
2950
  this.risolviProntaSePossibile();
1625
2951
  }
1626
2952
  riceviWelcome(dati) {
@@ -1653,28 +2979,38 @@ var StanzaClient = class {
1653
2979
  this.resultCorrente,
1654
2980
  room.serverTime
1655
2981
  );
2982
+ this.initialMetadata(room);
1656
2983
  this.risolviProntaSePossibile();
1657
2984
  }
1658
- riceviGiocatori(value) {
2985
+ riceviGiocatori(value, host) {
1659
2986
  this.giocatoriCorrenti = value.map((player) => ({ ...player }));
1660
- if (!this.giocatoriCorrenti.some(
2987
+ if (host !== void 0) this.hostCorrente = host;
2988
+ else if (!this.giocatoriCorrenti.some(
1661
2989
  (player) => player.id === this.hostCorrente && player.connected
1662
2990
  )) {
1663
2991
  this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;
1664
2992
  }
2993
+ this.metadataChanged({ host: this.hostCorrente });
1665
2994
  this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
1666
2995
  this.voice.giocatoriCambiati();
1667
2996
  }
1668
2997
  riceviStatus(dati) {
1669
2998
  this.statusCorrente = dati.status;
2999
+ if (dati.host !== void 0) this.hostCorrente = dati.host;
1670
3000
  this.resultCorrente = copiaJson(dati.result);
1671
3001
  if (dati.status === "ended") {
1672
3002
  this.terminata = true;
3003
+ this.clearRoleRequests();
1673
3004
  this.segnalaStanza(null);
1674
3005
  if (!this.spettatore) this.voice.termina();
1675
3006
  this.fermaPing();
1676
3007
  this.fermaRiconnessione();
1677
3008
  }
3009
+ this.metadataChanged({
3010
+ host: this.hostCorrente,
3011
+ countdownAt: dati.countdownAt ?? (dati.status === "countdown" ? dati.at : null),
3012
+ ...dati.status === "ended" ? { connection: "ended", closedCode: 4004 } : {}
3013
+ });
1678
3014
  this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
1679
3015
  }
1680
3016
  riceviDiff(dati) {
@@ -1722,11 +3058,13 @@ var StanzaClient = class {
1722
3058
  this.termina(code);
1723
3059
  return;
1724
3060
  }
3061
+ this.clearRoleRequests();
1725
3062
  if (!this.spettatore) this.voice.socketDisconnesso();
1726
3063
  this.programmaRiconnessione();
1727
3064
  }
1728
3065
  programmaRiconnessione() {
1729
3066
  if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;
3067
+ this.metadataChanged({ connection: "reconnecting" });
1730
3068
  const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);
1731
3069
  const ritardo = RITARDI_RICONNESSIONE2[indice];
1732
3070
  if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {
@@ -1744,6 +3082,7 @@ var StanzaClient = class {
1744
3082
  if (this.terminata || this.lasciata) return;
1745
3083
  try {
1746
3084
  const ingresso = this.spettatore ? await this.api.watchRoom(this.roomId) : await this.api.joinRoom(this.roomId);
3085
+ if (this.terminata || this.lasciata) return;
1747
3086
  const codiceCambiato = this.codice !== ingresso.code;
1748
3087
  this.codice = ingresso.code;
1749
3088
  if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {
@@ -1760,6 +3099,8 @@ var StanzaClient = class {
1760
3099
  this.timerRiconnessione = null;
1761
3100
  }
1762
3101
  termina(code) {
3102
+ this.clearRoleRequests();
3103
+ this.metadataChanged({ connection: code === 1e3 ? "disconnected" : code === 4006 ? "replaced" : "closed", closedCode: typeof code === "number" ? code : null });
1763
3104
  const risultato = { closed: code };
1764
3105
  const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
1765
3106
  this.terminata = true;
@@ -1869,6 +3210,21 @@ function creaGestoreStanze(input, invited) {
1869
3210
  );
1870
3211
  await stanza.pronta();
1871
3212
  return {
3213
+ get mode() {
3214
+ return stanza.mode;
3215
+ },
3216
+ get countdownAt() {
3217
+ return stanza.countdownAt;
3218
+ },
3219
+ get connection() {
3220
+ return stanza.connection;
3221
+ },
3222
+ get metadata() {
3223
+ return stanza.metadata;
3224
+ },
3225
+ onMetadata: (listener) => stanza.onMetadata(listener),
3226
+ onConnection: (listener) => stanza.onConnection(listener),
3227
+ disconnect: () => stanza.disconnect(),
1872
3228
  get state() {
1873
3229
  return stanza.state;
1874
3230
  },
@@ -1943,7 +3299,7 @@ function creaGestoreStanze(input, invited) {
1943
3299
  function ricevi(evento) {
1944
3300
  let dati = null;
1945
3301
  try {
1946
- dati = typeof evento.data === "string" ? record2(JSON.parse(evento.data)) : null;
3302
+ dati = typeof evento.data === "string" ? record3(JSON.parse(evento.data)) : null;
1947
3303
  } catch {
1948
3304
  }
1949
3305
  if (dati === null || typeof dati.t !== "string") {
@@ -2108,10 +3464,11 @@ async function creaStandalone(input, invited = null) {
2108
3464
  save: creaSave(input.archivio, input.ora),
2109
3465
  board: {
2110
3466
  async submit() {
2111
- return { accepted: false, reason: "offline" };
3467
+ return { accepted: false, reason: "offline", verified: false };
2112
3468
  },
2113
3469
  async top(_board, opzioni = {}) {
2114
- return { day: opzioni.daily ? day : null, entries: [], me: null };
3470
+ if (opzioni.day !== void 0 && (!validBoardDay(opzioni.day) || opzioni.daily === false)) throw creaErrore("invalid_request", "day must be a real UTC date and cannot be combined with daily: false.");
3471
+ return { day: opzioni.day ?? (opzioni.daily ? day : null), entries: [], me: null };
2115
3472
  }
2116
3473
  },
2117
3474
  room: creaStanzeOffline(invited)
@@ -2152,14 +3509,14 @@ async function connetti(input) {
2152
3509
  const appOrigin = leggiAppOrigin(input.documento);
2153
3510
  const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;
2154
3511
  if (appOrigin === null || senzaPadre) {
2155
- return creaStandalone(input);
3512
+ return localConnection(input);
2156
3513
  }
2157
3514
  const handshake = await attendiHandshake(
2158
3515
  input.finestra,
2159
3516
  appOrigin,
2160
3517
  input.timeoutHandshake
2161
3518
  );
2162
- if (handshake === null) return creaStandalone(input);
3519
+ if (handshake === null) return localConnection(input);
2163
3520
  const biglietto = creaGestoreBiglietto(
2164
3521
  handshake.ticket,
2165
3522
  handshake.porta,
@@ -2174,7 +3531,8 @@ async function connetti(input) {
2174
3531
  try {
2175
3532
  me = await api.me();
2176
3533
  } catch {
2177
- return creaStandalone(input, handshake.invite);
3534
+ const base2 = await creaStandalone(input, handshake.invite);
3535
+ return installSession(base2, handshake, input);
2178
3536
  }
2179
3537
  const dopo = input.ora();
2180
3538
  const scartoOrario = me.serverTime - (prima + dopo) / 2;
@@ -2208,7 +3566,7 @@ async function connetti(input) {
2208
3566
  }
2209
3567
  }
2210
3568
  }, handshake.invite);
2211
- return {
3569
+ const base = {
2212
3570
  connected: true,
2213
3571
  player: me.player,
2214
3572
  daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },
@@ -2224,7 +3582,7 @@ async function connetti(input) {
2224
3582
  try {
2225
3583
  return await api.boardSubmit(board, score, opzioni.daily === true);
2226
3584
  } catch (errore) {
2227
- if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline" };
3585
+ if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline", verified: false };
2228
3586
  throw errore;
2229
3587
  }
2230
3588
  },
@@ -2232,6 +3590,18 @@ async function connetti(input) {
2232
3590
  },
2233
3591
  room
2234
3592
  };
3593
+ return installSession(base, handshake, input);
3594
+ }
3595
+ function installSession(base, handshake, input) {
3596
+ const coordinator = createSession(base, handshake?.overlay?.configuration ?? null, base.connected && handshake?.live != null);
3597
+ if (handshake?.overlay) {
3598
+ const dispose = attachKitBridge(handshake.porta, handshake.overlay, coordinator);
3599
+ if (coordinator.session.capabilities.overlay && typeof window !== "undefined" && input?.finestra === window) window.addEventListener("pagehide", dispose, { once: true });
3600
+ }
3601
+ return { ...base, room: coordinator.rooms, session: coordinator.session, overlay: coordinator.overlay };
3602
+ }
3603
+ async function localConnection(input) {
3604
+ return installSession(await creaStandalone(input));
2235
3605
  }
2236
3606
  function dispositivoSconosciuto() {
2237
3607
  return {