@caisual/kit 0.5.0 → 0.10.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 (58) hide show
  1. package/dist/kit.d.ts +2 -175
  2. package/dist/kit.js +1808 -76
  3. package/dist/node.d.ts +1 -88
  4. package/dist/node.js +354 -96
  5. package/dist/overlay.d.ts +1 -0
  6. package/dist/overlay.js +2074 -0
  7. package/dist/runtime.d.ts +1 -111
  8. package/dist/runtime.js +335 -67
  9. package/dist/server.d.ts +1 -71
  10. package/dist/server.js +3 -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/i18n.d.ts +12 -0
  16. package/dist/types/contracts/index.d.ts +13 -0
  17. package/dist/types/contracts/keys.d.ts +59 -0
  18. package/dist/types/contracts/manifest.d.ts +123 -0
  19. package/dist/types/contracts/overlay-boards.d.ts +3 -0
  20. package/dist/types/contracts/overlay.d.ts +223 -0
  21. package/dist/types/contracts/player.d.ts +1 -0
  22. package/dist/types/contracts/room-limits.d.ts +13 -0
  23. package/dist/types/contracts/runtime.d.ts +70 -0
  24. package/dist/types/contracts/server-js.d.ts +11 -0
  25. package/dist/types/contracts/slug.d.ts +5 -0
  26. package/dist/types/contracts/token-crew.d.ts +21 -0
  27. package/dist/types/daily.d.ts +3 -0
  28. package/dist/types/errors.d.ts +6 -0
  29. package/dist/types/handshake.d.ts +30 -0
  30. package/dist/types/http.d.ts +3 -0
  31. package/dist/types/index.d.ts +231 -0
  32. package/dist/types/kit.d.ts +28 -0
  33. package/dist/types/node/index.d.ts +97 -0
  34. package/dist/types/node/websocket.d.ts +29 -0
  35. package/dist/types/overlay/boards.d.ts +48 -0
  36. package/dist/types/overlay/bridge.d.ts +3 -0
  37. package/dist/types/overlay/host-bridge.d.ts +74 -0
  38. package/dist/types/overlay/i18n.d.ts +128 -0
  39. package/dist/types/overlay/index.d.ts +10 -0
  40. package/dist/types/overlay/shortcut.d.ts +4 -0
  41. package/dist/types/overlay/styles.d.ts +1 -0
  42. package/dist/types/overlay/ui-model.d.ts +45 -0
  43. package/dist/types/overlay/ui.d.ts +80 -0
  44. package/dist/types/overlay/voice-panel.d.ts +13 -0
  45. package/dist/types/protocollo.d.ts +262 -0
  46. package/dist/types/runtime/index.d.ts +128 -0
  47. package/dist/types/server/index.d.ts +76 -0
  48. package/dist/types/session/index.d.ts +49 -0
  49. package/dist/types/session/resume.d.ts +13 -0
  50. package/dist/types/standalone.d.ts +14 -0
  51. package/dist/types/stanza/index.d.ts +3 -0
  52. package/dist/types/stanza/json.d.ts +18 -0
  53. package/dist/types/stanza/nucleo.d.ts +100 -0
  54. package/dist/types/stanza/tipi.d.ts +136 -0
  55. package/dist/types/stanza-client/index.d.ts +24 -0
  56. package/dist/types/text.d.ts +2 -0
  57. package/dist/types/voce/index.d.ts +124 -0
  58. 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.10.0
2
2
 
3
3
  // ../contracts/src/slug.ts
4
4
  var NOMI_RISERVATI = [
@@ -34,6 +34,626 @@ 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/i18n.ts
47
+ function normalizeLanguage(value) {
48
+ if (typeof value !== "string" || value.length > 128) return null;
49
+ try {
50
+ return Intl.getCanonicalLocales(value)[0] ?? null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ function manifestLanguages(manifest) {
56
+ return manifest.languages?.length ? [...manifest.languages] : [manifest.language ?? "en"];
57
+ }
58
+ function languageFallbacks(language, defaultLanguage = "en") {
59
+ const result = [];
60
+ let tag = normalizeLanguage(language);
61
+ while (tag) {
62
+ result.push(tag);
63
+ const parts = tag.split("-");
64
+ parts.pop();
65
+ if (parts.at(-1)?.length === 1) parts.pop();
66
+ tag = parts.join("-");
67
+ }
68
+ result.push(normalizeLanguage(defaultLanguage) ?? defaultLanguage);
69
+ return [...new Set(result)];
70
+ }
71
+ function resolveGameLanguage(preferences, languages2 = []) {
72
+ const declared = languages2.map(normalizeLanguage).filter((tag) => tag !== null);
73
+ const preferred = preferences.map(normalizeLanguage).filter((tag) => tag !== null);
74
+ if (!declared.length) return preferred[0] ?? "en";
75
+ for (const preference of preferred) {
76
+ for (const tag of languageFallbacks(preference, preference)) {
77
+ if (declared.includes(tag)) return tag;
78
+ }
79
+ }
80
+ return declared[0];
81
+ }
82
+ function isTextDictionary(value) {
83
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every((text) => typeof text === "string");
84
+ }
85
+
86
+ // ../contracts/src/manifest.ts
87
+ function risolviModalita(manifest, mode) {
88
+ const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
89
+ if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");
90
+ return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
91
+ }
92
+ function modalitaLocale(manifest, mode) {
93
+ return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
94
+ }
95
+ var TETTO_GIOCATORI = 24;
96
+ var RITARDO_SPETTATORI_MS = 3e3;
97
+ var MASSIMO_CLASSIFICHE = 32;
98
+ var CAMPI = /* @__PURE__ */ new Set([
99
+ "overlay",
100
+ "manifest",
101
+ "id",
102
+ "name",
103
+ "description",
104
+ "cover",
105
+ "screenshots",
106
+ "tags",
107
+ "languages",
108
+ "language",
109
+ "platform",
110
+ "orientation",
111
+ "input",
112
+ "visibility",
113
+ "network",
114
+ "isolated",
115
+ "requires",
116
+ "players",
117
+ "lobby",
118
+ "persistent",
119
+ "spectators",
120
+ "boards",
121
+ "roles",
122
+ "teams",
123
+ "voice",
124
+ "modes"
125
+ ]);
126
+ var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
127
+ var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
128
+ var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
129
+ var VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);
130
+ var VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);
131
+ var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
132
+ var TAG = /^[a-z0-9-]+$/;
133
+ var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
134
+ var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
135
+ var ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
136
+ function oggetto(value) {
137
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
138
+ return value;
139
+ }
140
+ function percorsoRelativo(value) {
141
+ if (value === "" || value.startsWith("/") || value.includes("\\") || value.includes("\0")) return false;
142
+ if (value.includes("?") || value.includes("#")) return false;
143
+ const parti = value.split("/");
144
+ if (parti.some((parte) => parte === "" || parte === "." || parte === "..")) return false;
145
+ try {
146
+ const decoded = parti.map((parte) => decodeURIComponent(parte));
147
+ return !decoded.some((parte) => parte === "" || parte === "." || parte === ".." || parte.includes("/"));
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+ function hostValido(value) {
153
+ if (value.length === 0 || value.length > 253) return false;
154
+ if (value.includes("://") || /[/:?#@]/.test(value)) return false;
155
+ const parti = value.split(".");
156
+ return parti.every(
157
+ (parte) => parte.length >= 1 && parte.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(parte)
158
+ );
159
+ }
160
+ function interoTra(value, min, max) {
161
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
162
+ }
163
+ function stringaDefault(dati, campo, valoreDefault, errori) {
164
+ const value = dati[campo];
165
+ if (value === void 0) return valoreDefault;
166
+ if (typeof value !== "string") {
167
+ errori.push(`${campo}: must be a string.`);
168
+ return valoreDefault;
169
+ }
170
+ return value;
171
+ }
172
+ function testoFacoltativo(value, key, max, path, errors) {
173
+ if (value[key] === void 0) return void 0;
174
+ const check = (text2, field2) => {
175
+ if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\r\n\u0000-\u001f]/.test(text2)) {
176
+ errors.push(`${field2}: must contain 1-${max} characters on one line.`);
177
+ return void 0;
178
+ }
179
+ return text2.trim();
180
+ };
181
+ const text = value[key], field = `${path}.${key}`;
182
+ if (typeof text === "string") return check(text, field);
183
+ const translations = oggetto(text);
184
+ if (!translations || Object.keys(translations).length === 0) {
185
+ errors.push(`${field}: must be a string or a non-empty language-to-text object.`);
186
+ return void 0;
187
+ }
188
+ const result = {};
189
+ for (const [raw, text2] of Object.entries(translations)) {
190
+ const tag = normalizeLanguage(raw);
191
+ if (!tag) {
192
+ errors.push(`${field}.${raw}: must be a BCP 47 language tag.`);
193
+ continue;
194
+ }
195
+ if (Object.hasOwn(result, tag)) errors.push(`${field}.${raw}: duplicate language.`);
196
+ const checked = check(text2, `${field}.${raw}`);
197
+ if (checked !== void 0) result[tag] = checked;
198
+ }
199
+ return result;
200
+ }
201
+ function validaManifest(valore) {
202
+ const errori = [];
203
+ const dati = oggetto(valore);
204
+ if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
205
+ for (const campo of Object.keys(dati)) {
206
+ if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
207
+ }
208
+ if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
209
+ else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
210
+ const id = stringaDefault(dati, "id", "", errori);
211
+ if (dati.id === void 0) errori.push("id: is required.");
212
+ else if (typeof dati.id === "string") {
213
+ if (!isValidSlug(id)) {
214
+ errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters.");
215
+ } else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");
216
+ }
217
+ const name = stringaDefault(dati, "name", "", errori);
218
+ if (dati.name === void 0) errori.push("name: is required.");
219
+ else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
220
+ errori.push("name: must contain 1-60 characters.");
221
+ }
222
+ const description = stringaDefault(dati, "description", "", errori);
223
+ if (description.length > 500) errori.push("description: must be at most 500 characters.");
224
+ let cover = null;
225
+ if (dati.cover !== void 0 && dati.cover !== null) {
226
+ if (typeof dati.cover !== "string") errori.push("cover: must be a relative file path or null.");
227
+ else if (!percorsoRelativo(dati.cover)) errori.push("cover: must be a relative file path without query, fragment, or parent segments.");
228
+ else cover = dati.cover;
229
+ }
230
+ const screenshots = [];
231
+ if (dati.screenshots !== void 0) {
232
+ if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");
233
+ else {
234
+ if (dati.screenshots.length > 8) errori.push("screenshots: must contain at most 8 paths.");
235
+ for (const [indice, value] of dati.screenshots.entries()) {
236
+ if (typeof value !== "string" || !percorsoRelativo(value)) {
237
+ errori.push(`screenshots[${indice}]: must be a relative file path without query, fragment, or parent segments.`);
238
+ } else screenshots.push(value);
239
+ }
240
+ }
241
+ }
242
+ const tags = [];
243
+ if (dati.tags !== void 0) {
244
+ if (!Array.isArray(dati.tags)) errori.push("tags: must be an array.");
245
+ else {
246
+ if (dati.tags.length > 10) errori.push("tags: must contain at most 10 tags.");
247
+ for (const [indice, value] of dati.tags.entries()) {
248
+ if (typeof value !== "string" || value.length > 24 || !TAG.test(value)) {
249
+ errori.push(`tags[${indice}]: must be 1-24 lowercase letters, digits, or hyphens.`);
250
+ } else tags.push(value);
251
+ }
252
+ }
253
+ }
254
+ const legacyLanguage = stringaDefault(dati, "language", "en", errori);
255
+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {
256
+ errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
257
+ }
258
+ const languages2 = [];
259
+ if (dati.languages === void 0) languages2.push(normalizeLanguage(legacyLanguage) ?? legacyLanguage);
260
+ else if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
261
+ errori.push("languages: must be a non-empty array of BCP 47 language tags.");
262
+ } else for (const [index, raw] of dati.languages.entries()) {
263
+ const tag = normalizeLanguage(raw);
264
+ if (!tag) errori.push(`languages[${index}]: must be a BCP 47 language tag.`);
265
+ else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);
266
+ else languages2.push(tag);
267
+ }
268
+ const language = languages2[0] ?? legacyLanguage;
269
+ if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
270
+ errori.push("language: must match the first entry in languages when both are present.");
271
+ }
272
+ let platform = "both";
273
+ if (dati.platform === void 0) errori.push("platform: is required.");
274
+ else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
275
+ errori.push("platform: must be desktop, mobile, or both.");
276
+ } else platform = dati.platform;
277
+ let orientation = "landscape";
278
+ if (dati.orientation !== void 0) {
279
+ if (typeof dati.orientation !== "string" || !ORIENTATION.has(dati.orientation)) {
280
+ errori.push("orientation: must be landscape or portrait.");
281
+ } else orientation = dati.orientation;
282
+ }
283
+ const input = [];
284
+ if (dati.input !== void 0) {
285
+ if (!Array.isArray(dati.input)) errori.push("input: must be an array.");
286
+ else for (const [indice, value] of dati.input.entries()) {
287
+ if (typeof value !== "string" || !INPUT.has(value)) {
288
+ errori.push(`input[${indice}]: must be keyboard, mouse, touch, or gamepad.`);
289
+ } else if (input.includes(value)) errori.push(`input[${indice}]: duplicate value ${value}.`);
290
+ else input.push(value);
291
+ }
292
+ }
293
+ let visibility = "public";
294
+ if (dati.visibility !== void 0) {
295
+ if (typeof dati.visibility !== "string" || !VISIBILITY.has(dati.visibility)) {
296
+ errori.push("visibility: must be public or unlisted.");
297
+ } else visibility = dati.visibility;
298
+ }
299
+ const network = [];
300
+ if (dati.network !== void 0) {
301
+ if (!Array.isArray(dati.network)) errori.push("network: must be an array of host names.");
302
+ else for (const [indice, value] of dati.network.entries()) {
303
+ if (typeof value !== "string" || !hostValido(value)) {
304
+ errori.push(`network[${indice}]: must be a host name without scheme, port, path, query, or fragment.`);
305
+ } else if (network.includes(value)) errori.push(`network[${indice}]: duplicate host ${value}.`);
306
+ else network.push(value);
307
+ }
308
+ }
309
+ let isolated = false;
310
+ if (dati.isolated !== void 0) {
311
+ if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
312
+ else isolated = dati.isolated;
313
+ }
314
+ const requires = {
315
+ webgl2: false,
316
+ webgpu: false,
317
+ wasm: false,
318
+ threads: false,
319
+ memoryMb: null,
320
+ performance: "light"
321
+ };
322
+ if (dati.requires !== void 0) {
323
+ const value = oggetto(dati.requires);
324
+ if (value === null) errori.push("requires: must be an object.");
325
+ else {
326
+ for (const campo of Object.keys(value)) {
327
+ if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {
328
+ errori.push(`requires.${campo}: unknown field.`);
329
+ }
330
+ }
331
+ for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
332
+ if (value[campo] === void 0) continue;
333
+ if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);
334
+ else requires[campo] = value[campo];
335
+ }
336
+ if (value.memoryMb !== void 0) {
337
+ if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {
338
+ errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");
339
+ } else requires.memoryMb = value.memoryMb;
340
+ }
341
+ if (value.performance !== void 0) {
342
+ if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {
343
+ errori.push("requires.performance: must be light, medium, or heavy.");
344
+ } else requires.performance = value.performance;
345
+ }
346
+ if (requires.threads && !isolated) errori.push("requires.threads: needs isolated: true.");
347
+ }
348
+ }
349
+ let players = { min: 1, max: 1 };
350
+ if (dati.players !== void 0) {
351
+ const value = oggetto(dati.players);
352
+ if (value === null) errori.push("players: must be an object with min and max.");
353
+ else {
354
+ for (const campo of Object.keys(value)) {
355
+ if (campo !== "min" && campo !== "max") errori.push(`players.${campo}: unknown field.`);
356
+ }
357
+ if (!interoTra(value.min, 1, TETTO_GIOCATORI)) errori.push(`players.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
358
+ if (!interoTra(value.max, 1, TETTO_GIOCATORI)) errori.push(`players.max: must be an integer from 1 to ${TETTO_GIOCATORI} in manifest version 1.`);
359
+ if (interoTra(value.min, 1, TETTO_GIOCATORI) && interoTra(value.max, 1, TETTO_GIOCATORI)) {
360
+ if (value.min > value.max) errori.push("players.max: must be greater than or equal to players.min.");
361
+ else players = { min: value.min, max: value.max };
362
+ }
363
+ }
364
+ }
365
+ let lobby = false;
366
+ if (dati.lobby !== void 0) {
367
+ if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");
368
+ else lobby = dati.lobby;
369
+ }
370
+ let persistent = false;
371
+ if (dati.persistent !== void 0) {
372
+ if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
373
+ else persistent = dati.persistent;
374
+ }
375
+ let spectators = { delayMs: RITARDO_SPETTATORI_MS };
376
+ if (dati.spectators === false || dati.spectators === null) spectators = null;
377
+ else if (dati.spectators !== void 0 && dati.spectators !== true) {
378
+ const value = oggetto(dati.spectators);
379
+ if (value === null) {
380
+ errori.push("spectators: must be a boolean or an object with delayMs.");
381
+ } else {
382
+ for (const campo of Object.keys(value)) {
383
+ if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);
384
+ }
385
+ if (!interoTra(value.delayMs, 0, 3e4)) {
386
+ errori.push("spectators.delayMs: must be an integer from 0 to 30000.");
387
+ } else spectators = { delayMs: value.delayMs };
388
+ }
389
+ }
390
+ let overlay = null;
391
+ if (dati.overlay !== void 0 && dati.overlay !== null) {
392
+ const value = oggetto(dati.overlay);
393
+ if (value === null) errori.push("overlay: must be an object or null.");
394
+ else {
395
+ for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);
396
+ if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");
397
+ if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {
398
+ errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");
399
+ }
400
+ overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };
401
+ }
402
+ }
403
+ const boards = {};
404
+ if (dati.boards !== void 0) {
405
+ const value = oggetto(dati.boards);
406
+ if (value === null) errori.push("boards: must be an object of board ids.");
407
+ else {
408
+ if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {
409
+ errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);
410
+ }
411
+ for (const [id2, raw] of Object.entries(value)) {
412
+ let valido = true;
413
+ if (!ID_CLASSIFICA.test(id2)) {
414
+ errori.push(`boards.${id2}: invalid board id.`);
415
+ valido = false;
416
+ }
417
+ const board = oggetto(raw);
418
+ if (board === null) {
419
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
420
+ continue;
421
+ }
422
+ for (const campo of Object.keys(board)) {
423
+ if (!["source", "label", "periods"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
424
+ }
425
+ if (board.source !== "client" && board.source !== "server") {
426
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
427
+ valido = false;
428
+ }
429
+ const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
430
+ let periods = ["all-time"];
431
+ if (board.periods !== void 0) {
432
+ 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) {
433
+ errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);
434
+ } else periods = [...board.periods];
435
+ }
436
+ if (valido) Object.defineProperty(boards, id2, { value: {
437
+ source: board.source,
438
+ periods,
439
+ ...label === void 0 ? {} : { label }
440
+ }, enumerable: true, configurable: true, writable: true });
441
+ }
442
+ }
443
+ }
444
+ const roles = [];
445
+ if (dati.roles !== void 0) {
446
+ if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
447
+ else {
448
+ const ids = /* @__PURE__ */ new Set();
449
+ for (const [indice, raw] of dati.roles.entries()) {
450
+ const value = oggetto(raw);
451
+ if (value === null) {
452
+ errori.push(`roles[${indice}]: must be an object.`);
453
+ continue;
454
+ }
455
+ for (const campo of Object.keys(value)) {
456
+ if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
457
+ }
458
+ const idRuolo = value.id;
459
+ const min = value.min;
460
+ const max = value.max;
461
+ let valido = true;
462
+ if (typeof idRuolo !== "string" || idRuolo.length > 32 || !ID_INTERNO.test(idRuolo)) {
463
+ errori.push(`roles[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
464
+ valido = false;
465
+ } else if (ids.has(idRuolo)) {
466
+ errori.push(`roles[${indice}].id: duplicate role ${idRuolo}.`);
467
+ valido = false;
468
+ } else ids.add(idRuolo);
469
+ if (!interoTra(min, 0, TETTO_GIOCATORI)) {
470
+ errori.push(`roles[${indice}].min: must be an integer from 0 to ${TETTO_GIOCATORI}.`);
471
+ valido = false;
472
+ }
473
+ if (max !== void 0 && !interoTra(max, 0, TETTO_GIOCATORI)) {
474
+ errori.push(`roles[${indice}].max: must be an integer from 0 to ${TETTO_GIOCATORI} when present.`);
475
+ valido = false;
476
+ }
477
+ if (typeof min === "number" && typeof max === "number" && min > max) {
478
+ errori.push(`roles[${indice}].max: must be greater than or equal to min.`);
479
+ valido = false;
480
+ }
481
+ const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);
482
+ if (valido) roles.push({
483
+ id: idRuolo,
484
+ min,
485
+ ...max === void 0 ? {} : { max },
486
+ ...label === void 0 ? {} : { label }
487
+ });
488
+ }
489
+ }
490
+ }
491
+ let teams = null;
492
+ if (dati.teams !== void 0 && dati.teams !== null) {
493
+ const value = oggetto(dati.teams);
494
+ if (value === null) errori.push("teams: must be null or an object with min and max.");
495
+ else {
496
+ for (const campo of Object.keys(value)) {
497
+ if (campo !== "min" && campo !== "max") errori.push(`teams.${campo}: unknown field.`);
498
+ }
499
+ if (!interoTra(value.min, 2, TETTO_GIOCATORI)) errori.push(`teams.min: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
500
+ if (!interoTra(value.max, 2, TETTO_GIOCATORI)) errori.push(`teams.max: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
501
+ if (interoTra(value.min, 2, TETTO_GIOCATORI) && interoTra(value.max, 2, TETTO_GIOCATORI)) {
502
+ if (value.min > value.max) errori.push("teams.max: must be greater than or equal to teams.min.");
503
+ else teams = { min: value.min, max: value.max };
504
+ }
505
+ }
506
+ }
507
+ let voice = "none";
508
+ if (dati.voice !== void 0) {
509
+ if (typeof dati.voice !== "string" || !VOICE.has(dati.voice)) {
510
+ errori.push("voice: must be none, room, team, or proximity.");
511
+ } else voice = dati.voice;
512
+ }
513
+ const modes = [];
514
+ if (dati.modes !== void 0) {
515
+ if (!Array.isArray(dati.modes)) errori.push("modes: must be an array.");
516
+ else {
517
+ const ids = /* @__PURE__ */ new Set();
518
+ for (const [indice, raw] of dati.modes.entries()) {
519
+ const value = oggetto(raw);
520
+ if (value === null) {
521
+ errori.push(`modes[${indice}]: must be an object.`);
522
+ continue;
523
+ }
524
+ for (const campo of Object.keys(value)) {
525
+ if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
526
+ }
527
+ if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
528
+ errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
529
+ continue;
530
+ }
531
+ if (ids.has(value.id)) {
532
+ errori.push(`modes[${indice}].id: duplicate mode ${value.id}.`);
533
+ continue;
534
+ }
535
+ ids.add(value.id);
536
+ const modo = { id: value.id };
537
+ for (const [key2, max] of [["label", 48], ["instructions", 160]]) {
538
+ const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);
539
+ if (text !== void 0) modo[key2] = text;
540
+ }
541
+ if (value.execution !== void 0) {
542
+ if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);
543
+ else modo.execution = value.execution;
544
+ }
545
+ if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);
546
+ if (value.players !== void 0) {
547
+ const campo = `modes[${indice}].players`;
548
+ const range = oggetto(value.players);
549
+ if (range === null) errori.push(`${campo}: must be an object with min and max.`);
550
+ else {
551
+ for (const key2 of Object.keys(range)) {
552
+ if (key2 !== "min" && key2 !== "max") errori.push(`${campo}.${key2}: unknown field.`);
553
+ }
554
+ if (!interoTra(range.min, 1, TETTO_GIOCATORI)) errori.push(`${campo}.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
555
+ if (!interoTra(range.max, 1, TETTO_GIOCATORI)) errori.push(`${campo}.max: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
556
+ if (interoTra(range.min, 1, TETTO_GIOCATORI) && interoTra(range.max, 1, TETTO_GIOCATORI)) {
557
+ if (range.min > range.max) errori.push(`${campo}.max: must be greater than or equal to min.`);
558
+ else modo.players = { min: range.min, max: range.max };
559
+ }
560
+ }
561
+ }
562
+ if (value.lobby !== void 0) {
563
+ if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);
564
+ else modo.lobby = value.lobby;
565
+ }
566
+ if (modo.execution === "local") {
567
+ const range = modo.players ?? players;
568
+ if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);
569
+ if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);
570
+ if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);
571
+ }
572
+ if (value.matchmaking === void 0) {
573
+ modes.push(modo);
574
+ continue;
575
+ }
576
+ const matchmaking = oggetto(value.matchmaking);
577
+ if (matchmaking === null) {
578
+ errori.push(`modes[${indice}].matchmaking: must be an object.`);
579
+ continue;
580
+ }
581
+ for (const campo of Object.keys(matchmaking)) {
582
+ if (!["key", "timeoutMs", "defaults"].includes(campo)) {
583
+ errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);
584
+ }
585
+ }
586
+ let valido = true;
587
+ const key = [];
588
+ if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {
589
+ errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);
590
+ valido = false;
591
+ } else for (const [keyIndice, item] of matchmaking.key.entries()) {
592
+ if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {
593
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);
594
+ valido = false;
595
+ } else if (key.includes(item)) {
596
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);
597
+ valido = false;
598
+ } else key.push(item);
599
+ }
600
+ if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {
601
+ errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);
602
+ valido = false;
603
+ }
604
+ let defaults;
605
+ if (matchmaking.defaults !== void 0) {
606
+ const values = oggetto(matchmaking.defaults);
607
+ if (values === null || Object.keys(values).length !== key.length || key.some((field) => !Object.hasOwn(values, field))) {
608
+ errori.push(`modes[${indice}].matchmaking.defaults: must contain exactly the declared key fields.`);
609
+ } else {
610
+ defaults = {};
611
+ for (const [field, value2] of Object.entries(values)) {
612
+ if (!(typeof value2 === "string" && value2.length >= 1 && value2.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value2)) && !Number.isSafeInteger(value2)) {
613
+ errori.push(`modes[${indice}].matchmaking.defaults.${field}: must be a string of 1-64 characters or a safe integer.`);
614
+ } else Object.defineProperty(defaults, field, { value: value2, enumerable: true });
615
+ }
616
+ }
617
+ }
618
+ if (valido) modes.push({ ...modo, matchmaking: {
619
+ ...defaults === void 0 ? {} : { defaults },
620
+ key,
621
+ timeoutMs: matchmaking.timeoutMs
622
+ } });
623
+ }
624
+ }
625
+ }
626
+ if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");
627
+ if (errori.length > 0) return { ok: false, errori };
628
+ return { ok: true, manifest: {
629
+ manifest: 1,
630
+ overlay,
631
+ id,
632
+ name,
633
+ description,
634
+ cover,
635
+ screenshots,
636
+ tags,
637
+ languages: languages2,
638
+ language,
639
+ platform,
640
+ orientation,
641
+ input,
642
+ visibility,
643
+ network,
644
+ isolated,
645
+ requires,
646
+ players,
647
+ lobby,
648
+ persistent,
649
+ spectators,
650
+ boards,
651
+ roles,
652
+ teams,
653
+ voice,
654
+ modes
655
+ } };
656
+ }
37
657
 
38
658
  // ../contracts/src/device.ts
39
659
  function deviceTier(report) {
@@ -165,6 +785,238 @@ async function probeDevice(globals, timeoutMs = 1500) {
165
785
  return { ...report, tier: deviceTier(report) };
166
786
  }
167
787
 
788
+ // ../contracts/src/overlay.ts
789
+ function overlayConfiguration(manifest, coverUrl = null, invite = null) {
790
+ const validated = validaManifest(manifest);
791
+ if (!validated.ok) throw new Error("The overlay manifest is invalid.");
792
+ return { manifest: validated.manifest, coverUrl, invite };
793
+ }
794
+ function record(value) {
795
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
796
+ }
797
+ function validOverlayHello(value) {
798
+ const hello = record(value), config = record(hello?.configuration);
799
+ 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;
800
+ }
801
+ function normalizeOverlayHello(value) {
802
+ if (!validOverlayHello(value)) return null;
803
+ return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite) };
804
+ }
805
+ function validSafeArea(value) {
806
+ const area = record(value);
807
+ return area !== null && Object.keys(area).length === 4 && ["top", "right", "bottom", "left"].every((key) => typeof area[key] === "number" && Number.isFinite(area[key]) && Number(area[key]) >= 0 && Number(area[key]) <= 1e5);
808
+ }
809
+ function validOverlayView(value) {
810
+ const data = record(value);
811
+ return data !== null && Object.keys(data).every((key) => ["inputBlocked", "reservedRects", "safeArea", "shortcutEnabled"].includes(key)) && (data.safeArea === void 0 || validSafeArea(data.safeArea)) && (data.shortcutEnabled === void 0 || typeof data.shortcutEnabled === "boolean") && typeof data.inputBlocked === "boolean" && Array.isArray(data.reservedRects) && data.reservedRects.length <= 8 && data.reservedRects.every((value2) => {
812
+ const rect = record(value2);
813
+ 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);
814
+ });
815
+ }
816
+ function validOverlayRequest(value) {
817
+ const message = record(value), args = record(message?.args);
818
+ 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;
819
+ 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;
820
+ const keys = (...allowed) => Object.keys(args).every((key) => allowed.includes(key));
821
+ const text = (key) => typeof args[key] === "string" && args[key].length >= 1 && args[key].length <= 64;
822
+ switch (message.op) {
823
+ case "local.start":
824
+ return keys("mode") && text("mode");
825
+ case "room.create":
826
+ return keys("mode") && (args.mode === null || text("mode"));
827
+ case "room.join":
828
+ return keys("code") && (args.code === void 0 || text("code"));
829
+ case "room.watch":
830
+ return keys("code") && text("code");
831
+ case "room.match": {
832
+ const key = record(args.key);
833
+ 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)));
834
+ }
835
+ case "room.ready":
836
+ return keys("ready") && typeof args.ready === "boolean";
837
+ case "room.role":
838
+ case "room.requestRole":
839
+ return keys("role") && text("role");
840
+ case "room.team":
841
+ return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;
842
+ case "room.restart":
843
+ case "room.start":
844
+ case "session.cancel":
845
+ case "session.leave":
846
+ case "session.disconnect":
847
+ case "session.resume":
848
+ return keys();
849
+ case "voice.join":
850
+ case "voice.leave":
851
+ return keys() && typeof message.sessionId === "string";
852
+ case "voice.mute":
853
+ return keys("muted") && typeof args.muted === "boolean" && typeof message.sessionId === "string";
854
+ case "voice.setVolume":
855
+ 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;
856
+ case "overlay.view":
857
+ return validOverlayView(args);
858
+ default:
859
+ return false;
860
+ }
861
+ }
862
+ function validBoardDay(value) {
863
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
864
+ const at = Date.parse(`${value}T00:00:00Z`);
865
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
866
+ }
867
+
868
+ // ../contracts/src/room-limits.ts
869
+ var MESSAGGI_GIOCO_AL_SECONDO = 20;
870
+
871
+ // src/overlay/i18n.ts
872
+ var languages = ["en", "it", "es", "fr", "de", "pt"];
873
+ var words = {
874
+ gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo"],
875
+ loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando..."],
876
+ loadingSlow: ["This game is taking longer than expected. You can wait a little longer or try again.", "Il gioco ci sta mettendo pi\xF9 del previsto. Puoi aspettare ancora un po\u2019 o riprovare.", "El juego est\xE1 tardando m\xE1s de lo esperado. Puedes esperar un poco m\xE1s o volver a intentarlo.", "Le jeu met plus de temps que pr\xE9vu. Vous pouvez patienter encore un peu ou r\xE9essayer.", "Das Spiel braucht l\xE4nger als erwartet. Du kannst noch etwas warten oder es erneut versuchen.", "O jogo est\xE1 demorando mais do que o esperado. Voc\xEA pode esperar mais um pouco ou tentar novamente."],
877
+ home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
878
+ homeMenu: ["Menu", "Menu", "Men\xFA", "Menu", "Men\xFC", "Menu"],
879
+ mode: ["Mode", "Modalit\xE0", "Modo", "Mode", "Modus", "Modo"],
880
+ play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
881
+ friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos"],
882
+ find: ["Find players", "Trova giocatori", "Buscar jugadores", "Trouver des joueurs", "Spieler finden", "Buscar jogadores"],
883
+ join: ["Join with code", "Entra con codice", "Entrar con c\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\xF3digo"],
884
+ joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\xE1 sala"],
885
+ watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala"],
886
+ resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar"],
887
+ room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala"],
888
+ code: ["Room code", "Codice stanza", "C\xF3digo de sala", "Code de salle", "Raumcode", "C\xF3digo da sala"],
889
+ copy: ["Copy invite", "Copia invito", "Copiar invitaci\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite"],
890
+ copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\xE9", "Einladung kopiert", "Convite copiado"],
891
+ copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:"],
892
+ joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \xE0 la salle...", "Raum wird betreten...", "Entrando na sala..."],
893
+ matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores..."],
894
+ queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores"],
895
+ cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar"],
896
+ close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\xDFen", "Fechar"],
897
+ back: ["Back", "Indietro", "Volver", "Retour", "Zur\xFCck", "Voltar"],
898
+ ready: ["Ready", "Pronto", "Listo", "Pr\xEAt", "Bereit", "Pronto"],
899
+ unready: ["Not ready", "Non pronto", "No listo", "Pas pr\xEAt", "Nicht bereit", "N\xE3o pronto"],
900
+ start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\xE7ar"],
901
+ role: ["Role", "Ruolo", "Rol", "R\xF4le", "Rolle", "Fun\xE7\xE3o"],
902
+ team: ["Team", "Squadra", "Equipo", "\xC9quipe", "Team", "Equipe"],
903
+ host: ["Host", "Host", "Anfitrion", "H\xF4te", "Host", "Anfitri\xE3o"],
904
+ you: ["You", "Tu", "T\xFA", "Vous", "Du", "Voc\xEA"],
905
+ away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente"],
906
+ needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores"],
907
+ needReady: ["Everyone needs to be ready", "Tutti devono essere pronti", "Todos deben estar listos", "Tout le monde doit \xEAtre pr\xEAt", "Alle m\xFCssen bereit sein", "Todos precisam estar prontos"],
908
+ needRoles: ["Fill the required roles", "Completa i ruoli richiesti", "Completa los roles", "Compl\xE9tez les r\xF4les", "Ben\xF6tigte Rollen besetzen", "Complete as fun\xE7\xF5es"],
909
+ needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \xE9quipes", "Teams auswahlen", "Escolha as equipes"],
910
+ waitHost: ["Waiting for the host", "In attesa dell'host", "Esperando al anfitrion", "En attente de l\u2019h\xF4te", "Warten auf den Host", "Esperando o anfitri\xE3o"],
911
+ starting: ["Starting in", "Si inizia tra", "Empieza en", "D\xE9but dans", "Start in", "Come\xE7a em"],
912
+ playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando"],
913
+ ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada"],
914
+ rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos"],
915
+ rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche"],
916
+ again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente"],
917
+ newRoom: ["New room. Share the new invite.", "Nuova stanza. Condividi il nuovo invito.", "Nueva sala. Comparte la invitaci\xF3n.", "Nouvelle salle. Partagez le lien.", "Neuer Raum. Neue Einladung teilen.", "Nova sala. Compartilhe o convite."],
918
+ watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo"],
919
+ delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\xF6gerung", "Atraso de {n}s"],
920
+ exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair"],
921
+ leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\xFCbergehend verlassen", "Sair por enquanto"],
922
+ leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala"],
923
+ leaveHint: ["Your room stays available for Resume.", "La stanza resta disponibile con Riprendi.", "Podr\xE1s volver a est\xE1 sala.", "Vous pourrez reprendre cette salle.", "Du kannst den Raum fortsetzen.", "Voc\xEA pode voltar a est\xE1 sala."],
924
+ temporaryHint: ["The game continues. Rejoining may only be possible briefly.", "La partita continua. Il rientro pu\xF2 essere disponibile solo per poco.", "La partida continua. Volver puede ser posible solo por poco tiempo.", "La partie continue. Le retour peut \xEAtre limit\xE9.", "Das Spiel l\xE4uft weiter. R\xFCckkehr nur kurz m\xF6glich.", "A partida continua. O retorno pode ser limitado."],
925
+ abandonHint: ["Leave room gives up your place.", "Lascia la stanza libera il tuo posto.", "Abandonar libera tu plaza.", "Abandonner lib\xE8re votre place.", "Raum verlassen gibt deinen Platz frei.", "Deixar a sala libera sua vaga."],
926
+ reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando..."],
927
+ replaced: ["Opened in another tab", "Aperta in un\u2019altra scheda", "Abierta en otra pest\xE1na", "Ouverte dans un autre onglet", "In anderem Tab ge\xF6ffnet", "Aberta em outra aba"],
928
+ error: ["Something went wrong. Try again.", "Qualcosa non va. Riprova.", "Algo sali\xF3 mal. Reintenta.", "Une erreur est survenue. R\xE9essayez.", "Etwas ist schiefgelaufen. Erneut versuchen.", "Algo deu errado. Tente novamente."],
929
+ noRoom: ["This room is no longer available.", "Questa stanza non \xE8 pi\xF9 disponibile.", "Esta sala ya no est\xE1 disponible.", "Cette salle n'est plus disponible.", "Dieser Raum ist nicht mehr verf\xFCgbar.", "Esta sala n\xE3o est\xE1 mais disponivel."],
930
+ full: ["This room is full.", "La stanza \xE8 piena.", "La sala est\xE1 llena.", "Cette salle est pleine.", "Dieser Raum ist voll.", "Esta sala est\xE1 cheia."],
931
+ noMatch: ["No match this time. Try again.", "Nessun gruppo trovato. Riprova.", "No hay grupo. Reintenta.", "Aucun groupe trouv\xE9. R\xE9essayez.", "Keine Gruppe gefunden. Erneut versuchen.", "Nenhum grupo encontrado. Tente novamente."],
932
+ invalidCode: ["Enter a six-character room code.", "Inserisci un codice di sei caratteri.", "Escribe un c\xF3digo de seis caracteres.", "Entrez un code de six caracteres.", "Sechsstelligen Raumcode eingeben.", "Digite um c\xF3digo de seis caracteres."],
933
+ refused: ["The room did not accept that change.", "La stanza ha rifiutato la modifica.", "La sala rechaz\xF3 el cambio.", "La salle a refus\xE9 ce changement.", "Der Raum hat die \xC4nderung abgelehnt.", "A sala recusou a altera\xE7\xE3o."],
934
+ unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\xFCgbar", "Indisponivel agora"],
935
+ offline: ["Connection unavailable. Try again.", "Connessione non disponibile. Riprova.", "Sin conexi\xF3n. Reintenta.", "Connexion indisponible. R\xE9essayez.", "Keine Verbindung. Erneut versuchen.", "Sem conex\xE3o. Tente novamente."],
936
+ saveFailed: ["Keep the room code. Resume could not be saved.", "Conserva il codice. Riprendi non \xE8 stato salvato.", "Guarda el c\xF3digo. No se pudo guardar el regreso.", "Gardez le code. La reprise ne peut pas \xEAtre enregistr\xE9e.", "Raumcode aufbewahren. Fortsetzen nicht gespeichert.", "Guarde o c\xF3digo. O retorno n\xE3o foi salvo."],
937
+ boards: ["Leaderboard", "Classifica", "Clasificaci\xF3n", "Classement", "Bestenliste", "Classifica\xE7\xE3o"],
938
+ board: ["Board", "Classifica", "Tabla", "Classement", "Bestenliste", "Tabela"],
939
+ daily: ["Daily", "Giornaliera", "Diaria", "Du jour", "T\xE4glich", "Di\xE1ria"],
940
+ allTime: ["All time", "Di sempre", "Hist\xF3rica", "Tous les temps", "Gesamt", "Geral"],
941
+ accounts: ["Accounts", "Account", "Cuentas", "Comptes", "Konten", "Contas"],
942
+ guests: ["Guests", "Ospiti", "Invitados", "Invit\xE9s", "G\xE4ste", "Visitantes"],
943
+ category: ["Category", "Categoria", "Categoria", "Cat\xE9gorie", "Kategorie", "Categoria"],
944
+ period: ["Period", "Periodo", "Per\xEDodo", "P\xE9riode", "Zeitraum", "Per\xEDodo"],
945
+ rank: ["Rank", "Posizione", "Puesto", "Rang", "Platz", "Posicao"],
946
+ score: ["Score", "Punteggio", "Puntos", "Score", "Punkte", "Pontos"],
947
+ verified: ["Verified", "Verificato", "Verificado", "V\xE9rifi\xE9", "Verifiziert", "Verificado"],
948
+ own: ["Your best", "Il tuo record", "Tu record", "Votre record", "Dein Rekord", "Seu recorde"],
949
+ empty: ["No scores yet", "Nessun punteggio", "A\xFAn no hay puntos", "Aucun score", "Noch keine Punkte", "Ainda sem pontos"],
950
+ saving: ["Saving score...", "Salvataggio punteggio...", "Guardando puntos...", "Enregistrement du score...", "Punkte werden gespeichert...", "Salvando pontos..."],
951
+ saved: ["Your best is on the board", "Il tuo record \xE8 in classifica", "Tu record est\xE1 en la tabla", "Votre record est au classement", "Dein Rekord ist eingetragen", "Seu recorde est\xE1 na tabela"],
952
+ bestAlready: ["Your best is already on the board", "Il tuo record era gi\xE0 in classifica", "Tu record ya estaba en la tabla", "Votre record est d\xE9j\xE0 au classement", "Dein Rekord ist bereits eingetragen", "Seu recorde j\xE1 est\xE1 na tabela"],
953
+ refresh: ["Refresh", "Aggiorna", "Actualizar", "Actualiser", "Aktualisieren", "Atualizar"],
954
+ refreshHint: ["Score not visible yet. Refresh to check.", "Punteggio non ancora visibile. Aggiorna per controllare.", "Puntos a\xFAn no visibles. Actualiza.", "Score pas encore visible. Actualisez.", "Punkte noch nicht sichtbar. Aktualisieren.", "Pontos ainda n\xE3o visiveis. Atualize."],
955
+ friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo"],
956
+ localCrew: ["Friends and party are unavailable in local preview.", "Amici e gruppo non disponibili in anteprima locale.", "Amigos y grupo no disponibles en la vista local.", "Amis et groupe indisponibles en aper\xE7u local.", "Freunde und Gruppe in lokaler Vorschau nicht verf\xFCgbar.", "Amigos e grupo indispon\xEDveis na pr\xE9via local."],
957
+ loginCrew: ["Sign in on Caisual to use friends and party.", "Accedi a Caisual per amici e gruppo.", "Inicia sesion para amigos y grupo.", "Connectez-vous pour utiliser amis et groupe.", "F\xFCr Freunde und Gruppe bei Caisual anmelden.", "Entre no Caisual para amigos e grupo."],
958
+ online: ["Online", "Online", "En linea", "En ligne", "Online", "Online"],
959
+ noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online"],
960
+ createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\xE9er un groupe", "Gruppe erstellen", "Criar grupo"],
961
+ inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo"],
962
+ leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo"],
963
+ accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar"],
964
+ decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar"],
965
+ follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se"],
966
+ voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz"],
967
+ voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz"],
968
+ voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz"],
969
+ voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar"],
970
+ voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone"],
971
+ voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\xE9sactiv\xE9e", "Sprachchat aus", "Voz desativada"],
972
+ voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz..."],
973
+ voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\xE9e", "Sprachchat verbunden", "Voz conectada"],
974
+ voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\xE9", "Stumm", "Silenciado"],
975
+ voiceMic: ["Mic on", "Microfono attivo", "Micr\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo"],
976
+ voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\xC9coute seule", "Nur zuh\xF6ren", "Somente ouvindo"],
977
+ voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando"],
978
+ voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz"],
979
+ voiceEmpty: ["No one else in voice yet.", "Nessun altro in voce per ora.", "A\xFAn no hay nadie m\xE1s en voz.", "Personne d\u2019autre en voix pour le moment.", "Noch niemand im Sprachchat.", "Ningu\xE9m mais na voz ainda."],
980
+ voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\xE4rke f\xFCr {name}", "Volume de {name}"],
981
+ voiceUnavailable: ["Join a room with voice to use these controls.", "Entra in una stanza con voce per usare questi controlli.", "Entra en una sala con voz para usar estos controles.", "Rejoignez une salle vocale pour utiliser ces commandes.", "Diese Steuerung braucht einen Raum mit Sprachchat.", "Entre em uma sala com voz para usar estes controles."],
982
+ voiceWatch: ["Voice is unavailable while watching.", "La voce non e' disponibile in osservazione.", "La voz no est\xE1 disponible al observar.", "La voix est indisponible en observation.", "Beim Zuschauen ist kein Sprachchat verf\xFCgbar.", "A voz n\xE3o est\xE1 dispon\xEDvel ao assistir."],
983
+ voiceDenied: ["Microphone permission denied. Allow it in your browser, then try again.", "Permesso microfono negato. Consenti l'accesso nel browser e riprova.", "Permiso de micr\xF3fono denegado. Act\xEDvalo en el navegador e int\xE9ntalo de nuevo.", "Acc\xE8s au micro refus\xE9. Autorisez-le dans le navigateur, puis r\xE9essayez.", "Mikrofonzugriff verweigert. Im Browser erlauben und erneut versuchen.", "Permiss\xE3o do microfone negada. Permita no navegador e tente novamente."],
984
+ voiceUnsupported: ["Voice is not supported in this browser.", "Questo browser non supporta la voce.", "Este navegador no admite voz.", "Ce navigateur ne prend pas en charge la voix.", "Dieser Browser unterst\xFCtzt keinen Sprachchat.", "Este navegador n\xE3o oferece suporte a voz."],
985
+ voiceFailed: ["Voice could not connect. Try again.", "Connessione voce non riuscita. Riprova.", "No se pudo conectar la voz. Int\xE9ntalo de nuevo.", "Connexion vocale impossible. R\xE9essayez.", "Sprachverbindung fehlgeschlagen. Erneut versuchen.", "N\xE3o foi poss\xEDvel conectar a voz. Tente novamente."],
986
+ voicePeerGone: ["This participant has left voice.", "Questo partecipante e' uscito dalla voce.", "Este participante sali\xF3 de voz.", "Ce participant a quitt\xE9 la voix.", "Diese Person hat den Sprachchat verlassen.", "Este participante saiu da voz."],
987
+ shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab"],
988
+ menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual"],
989
+ retry: ["Retry", "Riprova", "Reintentar", "R\xE9essayer", "Erneut versuchen", "Tentar novamente"]
990
+ };
991
+ var column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));
992
+ var dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5) };
993
+ function overlayLocale(raw) {
994
+ const tag = normalizeLanguage(raw);
995
+ return tag && languages.includes(tag.split("-")[0]) ? tag : "en";
996
+ }
997
+
998
+ // src/text.ts
999
+ function createTextLoader(fetcher, language, pathname = "/") {
1000
+ let pending;
1001
+ const root = pathname.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0] ?? "/";
1002
+ return () => pending ?? (pending = (async () => {
1003
+ let dictionary = {};
1004
+ try {
1005
+ const response = await fetcher(`${root}__caisual/text/${encodeURIComponent(language)}.json`);
1006
+ if (response.ok) {
1007
+ const value = await response.json();
1008
+ if (isTextDictionary(value)) dictionary = value;
1009
+ }
1010
+ } catch {
1011
+ }
1012
+ return (key, values = {}) => {
1013
+ if (!Object.hasOwn(dictionary, key)) return key;
1014
+ const text = dictionary[key];
1015
+ return text.replace(/\{([^{}]+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
1016
+ };
1017
+ })());
1018
+ }
1019
+
168
1020
  // src/errors.ts
169
1021
  function creaErrore(code, message) {
170
1022
  return Object.assign(new Error(message), { name: "CaisualError", code });
@@ -176,6 +1028,552 @@ function codiceErrore(valore) {
176
1028
  return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
177
1029
  }
178
1030
 
1031
+ // src/session/resume.ts
1032
+ var KEY = "caisual-session-v1";
1033
+ function resume(value) {
1034
+ const data = record(value);
1035
+ if (!data || typeof data.code !== "string" || !/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(data.code) || !(data.mode === void 0 || data.mode === null || typeof data.mode === "string")) return null;
1036
+ return {
1037
+ version: 1,
1038
+ code: data.code,
1039
+ mode: typeof data.mode === "string" ? data.mode : null,
1040
+ updatedAt: typeof data.updatedAt === "number" && Number.isFinite(data.updatedAt) ? data.updatedAt : 0
1041
+ };
1042
+ }
1043
+ function createResume(save, changed) {
1044
+ let current = null, error = false, work = Promise.resolve();
1045
+ const write = async () => {
1046
+ const value = { version: 1, imported: true, resume: current };
1047
+ work = work.catch(() => void 0).then(async () => {
1048
+ try {
1049
+ await save.set(KEY, value);
1050
+ error = false;
1051
+ } catch (cause) {
1052
+ error = true;
1053
+ throw cause;
1054
+ } finally {
1055
+ changed();
1056
+ }
1057
+ });
1058
+ return work;
1059
+ };
1060
+ const loaded = (async () => {
1061
+ try {
1062
+ const data = record(await save.get(KEY));
1063
+ if (data?.version === 1 && data.imported === true) current = resume(data.resume);
1064
+ else {
1065
+ current = resume(await save.get("resume"));
1066
+ await write();
1067
+ }
1068
+ } catch {
1069
+ error = true;
1070
+ }
1071
+ changed();
1072
+ })();
1073
+ return {
1074
+ loaded,
1075
+ get value() {
1076
+ return current === null ? null : { ...current };
1077
+ },
1078
+ get error() {
1079
+ return error;
1080
+ },
1081
+ async set(value) {
1082
+ await loaded;
1083
+ current = value;
1084
+ changed();
1085
+ await write();
1086
+ }
1087
+ };
1088
+ }
1089
+
1090
+ // src/session/index.ts
1091
+ function notify(listeners, value) {
1092
+ for (const listener of listeners) {
1093
+ try {
1094
+ listener(value);
1095
+ } catch {
1096
+ }
1097
+ }
1098
+ }
1099
+ function createSession(base, configuration = null, roomsAvailable = base.connected) {
1100
+ const standard = configuration?.manifest.overlay?.version === 1;
1101
+ const manifest = configuration?.manifest;
1102
+ let current = { kind: "idle" }, ready = false, operation = 0, identifier = 0;
1103
+ let pending = null, pendingMode = null;
1104
+ let waiting = null, controller = null;
1105
+ let stops = [], disposed = false, lastState = "";
1106
+ let view = { inputBlocked: standard, reservedRects: [], safeArea: { top: 0, right: 0, bottom: 0, left: 0 } };
1107
+ const listeners = /* @__PURE__ */ new Set();
1108
+ const viewListeners = /* @__PURE__ */ new Set();
1109
+ const stateListeners = /* @__PURE__ */ new Set();
1110
+ const openListeners = /* @__PURE__ */ new Set();
1111
+ const errorListeners = /* @__PURE__ */ new Set();
1112
+ const scoreListeners = /* @__PURE__ */ new Set();
1113
+ let resumeStore = null;
1114
+ const capabilities = () => ({
1115
+ local: true,
1116
+ rooms: roomsAvailable,
1117
+ overlay: standard,
1118
+ requestRole: current.kind === "room" && current.room.metadata.configuration?.requestRole === true
1119
+ });
1120
+ function voiceSnapshot() {
1121
+ if (current.kind !== "room" || !manifest || manifest.voice === "none") return null;
1122
+ const room = current.room, voice = room.voice;
1123
+ if (!voice || voice.mode === "none" || room.players.find((p) => p.id === room.you)?.role === "spectator") return null;
1124
+ return {
1125
+ mode: voice.mode,
1126
+ state: voice.state,
1127
+ mic: voice.mic,
1128
+ muted: voice.muted,
1129
+ speaking: voice.speaking,
1130
+ peers: voice.peers.map(({ id, mic, muted, speaking, volume }) => ({ id, mic, muted, speaking, volume }))
1131
+ };
1132
+ }
1133
+ function snapshot() {
1134
+ const attached = current.kind === "room" || current.kind === "watch" ? current.room : null;
1135
+ const configured = attached?.metadata.configuration;
1136
+ 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 };
1137
+ return {
1138
+ kind: pending ?? (current.kind === "idle" ? ready ? "home" : "boot" : current.kind),
1139
+ id: current.kind === "idle" ? null : current.id,
1140
+ mode: pending ? pendingMode : current.kind === "local" ? current.mode : attached?.mode ?? null,
1141
+ localStatus: current.kind === "local" ? current.status : null,
1142
+ ready,
1143
+ capabilities: capabilities(),
1144
+ room: attached ? {
1145
+ code: attached.code,
1146
+ mode: attached.mode,
1147
+ status: attached.status,
1148
+ host: attached.host,
1149
+ you: current.kind === "room" ? current.room.you : null,
1150
+ 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 })),
1151
+ countdownAt: attached.countdownAt,
1152
+ connection: attached.connection,
1153
+ closedCode: attached.metadata.closedCode,
1154
+ limits: { ...configured?.players ?? fallback.players },
1155
+ lobby: configured?.lobby ?? fallback.lobby,
1156
+ persistent: configured?.persistent ?? manifest?.persistent ?? false,
1157
+ delayMs: current.kind === "watch" ? current.room.delayMs : null,
1158
+ requestRole: configured?.requestRole ?? false
1159
+ } : null,
1160
+ voice: pending ? null : voiceSnapshot(),
1161
+ waiting: waiting ? { ...waiting } : null,
1162
+ resume: resumeStore?.value ?? null,
1163
+ resumeError: resumeStore?.error ?? false
1164
+ };
1165
+ }
1166
+ function emit() {
1167
+ if (disposed) return;
1168
+ const state = snapshot(), serialized = JSON.stringify(state);
1169
+ if (serialized === lastState) return;
1170
+ lastState = serialized;
1171
+ notify(stateListeners, state);
1172
+ }
1173
+ function changed() {
1174
+ notify(listeners, { ...current });
1175
+ emit();
1176
+ }
1177
+ function active() {
1178
+ if (current.kind !== "room") throw creaErrore("no_room", "There is no active player room.");
1179
+ return current.room;
1180
+ }
1181
+ function activeVoice() {
1182
+ const room = active();
1183
+ if (room.players.find((p) => p.id === room.you)?.role === "spectator") throw creaErrore("spectator", "Spectators cannot use voice controls.");
1184
+ if (!manifest || manifest.voice === "none" || room.voice.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
1185
+ return room.voice;
1186
+ }
1187
+ function cancel() {
1188
+ operation++;
1189
+ controller?.abort();
1190
+ controller = null;
1191
+ pending = null;
1192
+ waiting = null;
1193
+ emit();
1194
+ }
1195
+ function detach(preserve) {
1196
+ stops.splice(0).forEach((stop) => stop());
1197
+ if (current.kind === "room" || current.kind === "watch") {
1198
+ if (preserve) current.room.disconnect();
1199
+ else current.room.leave();
1200
+ }
1201
+ current = { kind: "idle" };
1202
+ changed();
1203
+ }
1204
+ async function clearResume(code) {
1205
+ if (resumeStore?.value?.code === code) await resumeStore.set(null).catch(() => void 0);
1206
+ }
1207
+ async function adopt(next, watch, token) {
1208
+ if (token !== operation || disposed) {
1209
+ next.leave();
1210
+ throw creaErrore("cancelled", "The operation was cancelled.");
1211
+ }
1212
+ detach(false);
1213
+ current = watch ? { kind: "watch", room: next, id: String(++identifier) } : { kind: "room", room: next, id: String(++identifier) };
1214
+ const room = next;
1215
+ stops = [room.onPlayers(emit), room.onMetadata(() => {
1216
+ if (room.connection === "disconnected" && (current.kind === "room" || current.kind === "watch") && current.room === room) {
1217
+ stops.splice(0).forEach((stop) => stop());
1218
+ if (!watch && room.metadata.closedCode === 1e3) void clearResume(room.code);
1219
+ current = { kind: "idle" };
1220
+ changed();
1221
+ } else emit();
1222
+ }), room.onStatus(() => {
1223
+ emit();
1224
+ if (!watch && room.connection === "ended") void clearResume(room.code);
1225
+ })];
1226
+ if (!watch) {
1227
+ const playerRoom = next;
1228
+ const sessionId = current.id;
1229
+ if (playerRoom.voice) stops.push(playerRoom.voice.onState(emit), playerRoom.voice.onPeers(emit));
1230
+ stops.push(playerRoom.onError((error) => notify(errorListeners, { sessionId, error: { ...error } })));
1231
+ stops.push(playerRoom.onScoreQueued((score) => notify(scoreListeners, { ...score })));
1232
+ for (const score of playerRoom.queuedScores) notify(scoreListeners, { ...score });
1233
+ }
1234
+ pending = null;
1235
+ waiting = null;
1236
+ changed();
1237
+ if (!watch && resumeStore && room.connection !== "ended") {
1238
+ await resumeStore.set({ version: 1, code: room.code, mode: room.mode, updatedAt: base.time.now() }).catch(() => void 0);
1239
+ }
1240
+ return next;
1241
+ }
1242
+ async function run(kind, mode, work, watch = false) {
1243
+ cancel();
1244
+ const token = operation;
1245
+ controller = new AbortController();
1246
+ pending = kind;
1247
+ pendingMode = mode;
1248
+ emit();
1249
+ try {
1250
+ const next = await work(controller.signal, token);
1251
+ await adopt(next, watch, token);
1252
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1253
+ return next;
1254
+ } finally {
1255
+ if (token === operation) {
1256
+ pending = null;
1257
+ waiting = null;
1258
+ controller = null;
1259
+ emit();
1260
+ }
1261
+ }
1262
+ }
1263
+ const direct = base.room;
1264
+ const rooms = !standard ? direct : {
1265
+ invited: direct.invited,
1266
+ create(options) {
1267
+ if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot create rooms."));
1268
+ return run("attaching", options.mode, () => direct.create(options));
1269
+ },
1270
+ join(code) {
1271
+ return run("attaching", null, () => direct.join(code));
1272
+ },
1273
+ watch(code) {
1274
+ return run("attaching", null, () => direct.watch(code), true);
1275
+ },
1276
+ match(options) {
1277
+ if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot use matchmaking."));
1278
+ return run("matching", options.mode, (signal, token) => {
1279
+ const abort = () => {
1280
+ if (operation === token) cancel();
1281
+ };
1282
+ options.signal?.addEventListener("abort", abort, { once: true });
1283
+ if (options.signal?.aborted) abort();
1284
+ return direct.match({ ...options, signal, onWaiting(value) {
1285
+ if (token !== operation) return;
1286
+ waiting = { ...value };
1287
+ emit();
1288
+ options.onWaiting?.(value);
1289
+ } }).finally(() => options.signal?.removeEventListener("abort", abort));
1290
+ });
1291
+ }
1292
+ };
1293
+ if (standard) resumeStore = createResume(base.save, emit);
1294
+ const session = {
1295
+ get current() {
1296
+ return { ...current };
1297
+ },
1298
+ get capabilities() {
1299
+ return capabilities();
1300
+ },
1301
+ onChange(listener) {
1302
+ listeners.add(listener);
1303
+ notify(/* @__PURE__ */ new Set([listener]), { ...current });
1304
+ return () => {
1305
+ listeners.delete(listener);
1306
+ };
1307
+ },
1308
+ ready() {
1309
+ if (disposed || ready) return;
1310
+ ready = true;
1311
+ emit();
1312
+ },
1313
+ finish() {
1314
+ if (current.kind === "room" || current.kind === "watch") throw creaErrore("not_local", "Only a local session can be finished by the client.");
1315
+ if (current.kind === "local") {
1316
+ current = { ...current, status: "ended" };
1317
+ changed();
1318
+ }
1319
+ }
1320
+ };
1321
+ const overlay = {
1322
+ open(panel) {
1323
+ if (!["home", "room", "invite", "friends", "voice", "boards"].includes(panel)) throw creaErrore("invalid_request", "Unknown overlay panel.");
1324
+ if (standard) notify(openListeners, panel);
1325
+ },
1326
+ onChange(listener) {
1327
+ viewListeners.add(listener);
1328
+ notify(/* @__PURE__ */ new Set([listener]), structuredClone(view));
1329
+ return () => {
1330
+ viewListeners.delete(listener);
1331
+ };
1332
+ }
1333
+ };
1334
+ return {
1335
+ session,
1336
+ overlay,
1337
+ rooms,
1338
+ snapshot,
1339
+ serverTime: () => current.kind === "room" || current.kind === "watch" ? current.room.serverTime() : base.time.now(),
1340
+ onState(listener) {
1341
+ stateListeners.add(listener);
1342
+ listener(snapshot());
1343
+ return () => {
1344
+ stateListeners.delete(listener);
1345
+ };
1346
+ },
1347
+ onOpen(listener) {
1348
+ openListeners.add(listener);
1349
+ return () => {
1350
+ openListeners.delete(listener);
1351
+ };
1352
+ },
1353
+ onError(listener) {
1354
+ errorListeners.add(listener);
1355
+ return () => {
1356
+ errorListeners.delete(listener);
1357
+ };
1358
+ },
1359
+ onScore(listener) {
1360
+ scoreListeners.add(listener);
1361
+ return () => {
1362
+ scoreListeners.delete(listener);
1363
+ };
1364
+ },
1365
+ async execute(request) {
1366
+ if (!standard) throw creaErrore("overlay_disabled", "This game uses its own room flow.");
1367
+ if (request.op === "overlay.view") {
1368
+ if (!validOverlayView(request.args)) throw creaErrore("invalid_request", "The overlay geometry is invalid.");
1369
+ view = { ...structuredClone(request.args), safeArea: { top: 0, right: 0, bottom: 0, left: 0, ...request.args.safeArea } };
1370
+ if (typeof document !== "undefined") for (const [side, value] of Object.entries(view.safeArea)) {
1371
+ document.documentElement.style.setProperty(`--caisual-safe-${side}`, `${value}px`);
1372
+ }
1373
+ notify(viewListeners, structuredClone(view));
1374
+ return;
1375
+ }
1376
+ if (request.sessionId !== void 0 && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1377
+ if (request.op.startsWith("voice.") && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1378
+ if (!ready) throw creaErrore("game_not_ready", "The game is still loading.");
1379
+ switch (request.op) {
1380
+ case "local.start": {
1381
+ if (!manifest || !modalitaLocale(manifest, request.args.mode)) throw creaErrore("invalid_mode", "This is not a local mode.");
1382
+ cancel();
1383
+ const token = operation;
1384
+ if (current.kind === "room") await clearResume(current.room.code);
1385
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1386
+ detach(false);
1387
+ current = { kind: "local", id: String(++identifier), mode: request.args.mode, status: "playing" };
1388
+ changed();
1389
+ return;
1390
+ }
1391
+ case "room.create":
1392
+ await rooms.create(request.args);
1393
+ return;
1394
+ case "room.join":
1395
+ await rooms.join(request.args.code);
1396
+ return;
1397
+ case "room.watch":
1398
+ await rooms.watch(request.args.code);
1399
+ return;
1400
+ case "room.match": {
1401
+ const mode = manifest?.modes.find((m) => m.id === request.args.mode);
1402
+ const key = request.args.key ?? mode?.matchmaking?.defaults;
1403
+ if (!key) throw creaErrore("invalid_request", "Matchmaking needs a complete key.");
1404
+ await rooms.match({ mode: request.args.mode, key });
1405
+ return;
1406
+ }
1407
+ case "voice.join": {
1408
+ const room = active(), voice = activeVoice();
1409
+ await voice.join();
1410
+ if (current.kind !== "room" || current.room !== room) throw creaErrore("session_replaced", "The active session changed.");
1411
+ emit();
1412
+ return;
1413
+ }
1414
+ case "voice.mute":
1415
+ activeVoice().mute(request.args.muted);
1416
+ emit();
1417
+ return;
1418
+ case "voice.leave":
1419
+ activeVoice().leave();
1420
+ emit();
1421
+ return;
1422
+ case "voice.setVolume": {
1423
+ const voice = activeVoice();
1424
+ if (!voice.peers.some((peer) => peer.id === request.args.playerId)) throw creaErrore("voice_peer_missing", "This voice participant is no longer available.");
1425
+ voice.setVolume(request.args.playerId, request.args.volume);
1426
+ emit();
1427
+ return;
1428
+ }
1429
+ case "room.ready":
1430
+ active().ready(request.args.ready);
1431
+ return;
1432
+ case "room.role":
1433
+ active().setRole(request.args.role);
1434
+ return;
1435
+ case "room.requestRole":
1436
+ await active().requestRole(request.args.role);
1437
+ return;
1438
+ case "room.team":
1439
+ active().setTeam(request.args.team);
1440
+ return;
1441
+ case "room.start":
1442
+ active().start();
1443
+ return;
1444
+ case "room.restart":
1445
+ active().restart();
1446
+ return;
1447
+ case "session.cancel":
1448
+ cancel();
1449
+ return;
1450
+ case "session.resume": {
1451
+ await run("attaching", null, async (signal) => {
1452
+ await resumeStore?.loaded;
1453
+ if (signal.aborted) throw creaErrore("cancelled", "The operation was cancelled.");
1454
+ if (!resumeStore?.value) throw creaErrore("no_resume", "There is no saved room.");
1455
+ return direct.join(resumeStore.value.code);
1456
+ });
1457
+ return;
1458
+ }
1459
+ case "session.disconnect": {
1460
+ cancel();
1461
+ const token = operation;
1462
+ 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() });
1463
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1464
+ detach(true);
1465
+ return;
1466
+ }
1467
+ case "session.leave": {
1468
+ cancel();
1469
+ const token = operation;
1470
+ if (current.kind === "room") await clearResume(current.room.code);
1471
+ if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1472
+ detach(false);
1473
+ return;
1474
+ }
1475
+ }
1476
+ },
1477
+ dispose() {
1478
+ cancel();
1479
+ detach(true);
1480
+ disposed = true;
1481
+ listeners.clear();
1482
+ viewListeners.clear();
1483
+ stateListeners.clear();
1484
+ openListeners.clear();
1485
+ scoreListeners.clear();
1486
+ errorListeners.clear();
1487
+ }
1488
+ };
1489
+ }
1490
+
1491
+ // src/overlay/shortcut.ts
1492
+ function bindOverlayShortcut(target, overlay, open) {
1493
+ let enabled = true, blocked = false;
1494
+ const stop = overlay.onChange((view) => {
1495
+ enabled = view.shortcutEnabled !== false;
1496
+ blocked = view.inputBlocked;
1497
+ });
1498
+ const listener = (event) => {
1499
+ const element = event.target;
1500
+ if (!enabled || blocked || event.repeat || event.key !== "Tab" || !event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || element?.closest?.('input,textarea,select,[contenteditable="true"]')) return;
1501
+ event.preventDefault();
1502
+ event.stopImmediatePropagation();
1503
+ open();
1504
+ };
1505
+ target.addEventListener("keydown", listener, true);
1506
+ return () => {
1507
+ stop();
1508
+ target.removeEventListener("keydown", listener, true);
1509
+ };
1510
+ }
1511
+
1512
+ // src/overlay/bridge.ts
1513
+ function attachKitBridge(port, hello, coordinator) {
1514
+ let disposed = false, seq = 0, highestRequest = 0, activeRequests = 0;
1515
+ const replies = /* @__PURE__ */ new Map();
1516
+ const send = (message) => {
1517
+ if (!disposed) try {
1518
+ port.postMessage(message);
1519
+ } catch {
1520
+ }
1521
+ };
1522
+ const stops = [
1523
+ ...hello.configuration.manifest.overlay && typeof window !== "undefined" ? [bindOverlayShortcut(window, coordinator.overlay, () => send({ type: "caisual:overlay-shortcut", v: 1, epoch: hello.epoch }))] : [],
1524
+ coordinator.onState((state) => send({ type: "caisual:overlay-state", v: 1, epoch: hello.epoch, seq: ++seq, serverTime: coordinator.serverTime(), state })),
1525
+ coordinator.onOpen((panel) => send({ type: "caisual:overlay-open", v: 1, epoch: hello.epoch, panel })),
1526
+ coordinator.onError(({ sessionId, error }) => send({ type: "caisual:overlay-error", v: 1, epoch: hello.epoch, sessionId, error })),
1527
+ coordinator.onScore((score) => send({ type: "caisual:overlay-score", v: 1, epoch: hello.epoch, score }))
1528
+ ];
1529
+ const listener = (event) => {
1530
+ const raw = record(event.data);
1531
+ if (raw?.type !== "caisual:overlay" || raw.epoch !== hello.epoch || disposed) return;
1532
+ const reply = { type: "caisual:overlay-response", v: 1, epoch: hello.epoch, requestId: typeof raw.requestId === "string" ? raw.requestId : "" };
1533
+ if (!validOverlayRequest(raw)) {
1534
+ send({ ...reply, ok: false, error: { code: "invalid_request", message: "The overlay request is invalid." } });
1535
+ return;
1536
+ }
1537
+ const fingerprint = JSON.stringify([raw.op, raw.args, raw.sessionId]);
1538
+ const previous = replies.get(raw.requestId);
1539
+ if (previous) {
1540
+ if (previous.fingerprint !== fingerprint) send({ ...reply, ok: false, error: { code: "duplicate_request", message: "The request id was already used." } });
1541
+ else void previous.response.then(send);
1542
+ return;
1543
+ }
1544
+ if (Number(raw.requestId) <= highestRequest || activeRequests >= 32) {
1545
+ send({ ...reply, ok: false, error: { code: "stale_request", message: "The request is stale or too many requests are pending." } });
1546
+ return;
1547
+ }
1548
+ highestRequest = Number(raw.requestId);
1549
+ activeRequests++;
1550
+ const response = Promise.resolve().then(() => coordinator.execute(raw)).then(
1551
+ () => ({ ...reply, ok: true }),
1552
+ (error) => ({ ...reply, ok: false, error: {
1553
+ code: typeof record(error)?.code === "string" ? record(error).code : "internal_error",
1554
+ message: error instanceof Error ? error.message : "The operation could not be completed."
1555
+ } })
1556
+ );
1557
+ replies.set(raw.requestId, { fingerprint, response });
1558
+ void response.then((value) => {
1559
+ activeRequests--;
1560
+ send(value);
1561
+ if (replies.size > 64) for (const id of replies.keys()) {
1562
+ if (Number(id) < highestRequest - 64) replies.delete(id);
1563
+ }
1564
+ });
1565
+ };
1566
+ port.addEventListener("message", listener);
1567
+ port.start();
1568
+ return () => {
1569
+ disposed = true;
1570
+ port.removeEventListener("message", listener);
1571
+ stops.forEach((stop) => stop());
1572
+ coordinator.dispose();
1573
+ replies.clear();
1574
+ };
1575
+ }
1576
+
179
1577
  // src/http.ts
180
1578
  async function leggiErrore(response) {
181
1579
  let corpo = {};
@@ -258,10 +1656,18 @@ function creaClienteApi(appOrigin, fetcher, biglietto) {
258
1656
  },
259
1657
  async boardSubmit(board, score, daily) {
260
1658
  const risultato = await richiesta("/scores", "POST", { board, score, daily });
261
- return { accepted: true, best: risultato.best, rank: risultato.rank, day: risultato.day };
1659
+ return {
1660
+ accepted: true,
1661
+ best: risultato.best,
1662
+ rank: risultato.rank,
1663
+ day: risultato.day,
1664
+ verified: risultato.verified
1665
+ };
262
1666
  },
263
1667
  async boardTop(board, opzioni) {
1668
+ 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
1669
  const query = new URLSearchParams();
1670
+ if (opzioni.day !== void 0) query.set("day", opzioni.day);
265
1671
  if (opzioni.daily) query.set("daily", "1");
266
1672
  if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));
267
1673
  if (opzioni.guests) query.set("guests", "1");
@@ -297,11 +1703,11 @@ function creaMulberry32(seed) {
297
1703
  }
298
1704
 
299
1705
  // src/handshake.ts
300
- function record(valore) {
1706
+ function record2(valore) {
301
1707
  return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
302
1708
  }
303
1709
  function eTipo(valore, tipo) {
304
- return record(valore)?.type === tipo;
1710
+ return record2(valore)?.type === tipo;
305
1711
  }
306
1712
  function leggiOrigine(valore) {
307
1713
  if (typeof valore !== "string") return null;
@@ -315,6 +1721,7 @@ function leggiOrigine(valore) {
315
1721
  function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
316
1722
  return new Promise((resolve) => {
317
1723
  let concluso = false;
1724
+ const instance = globalThis.crypto.randomUUID();
318
1725
  const termina = (esito) => {
319
1726
  if (concluso) return;
320
1727
  concluso = true;
@@ -323,7 +1730,7 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
323
1730
  resolve(esito);
324
1731
  };
325
1732
  const segnalaPronto = () => {
326
- finestra.parent.postMessage({ type: "caisual:ready" }, appOrigin);
1733
+ finestra.parent.postMessage({ type: "caisual:ready", instance, overlayVersion: 1 }, appOrigin);
327
1734
  };
328
1735
  const ascolta = (evento) => {
329
1736
  if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;
@@ -332,11 +1739,18 @@ function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
332
1739
  return;
333
1740
  }
334
1741
  if (!eTipo(evento.data, "caisual:hello")) return;
335
- const dati = record(evento.data);
1742
+ const dati = record2(evento.data);
336
1743
  const porta = evento.ports[0];
337
1744
  if (typeof dati?.ticket !== "string" || porta === void 0) return;
338
1745
  porta.start();
1746
+ const overlay = normalizeOverlayHello(dati.overlay);
1747
+ const tags = (value) => Array.isArray(value) ? value.map(normalizeLanguage).filter((tag) => tag !== null) : void 0;
339
1748
  termina({
1749
+ ...overlay ? { overlay } : {},
1750
+ ...normalizeLanguage(dati.language) ? { language: normalizeLanguage(dati.language) } : {},
1751
+ uiLanguage: normalizeLanguage(dati.uiLanguage) ?? void 0,
1752
+ languagePreferences: tags(dati.languagePreferences),
1753
+ gameLanguages: tags(dati.gameLanguages),
340
1754
  ticket: dati.ticket,
341
1755
  live: leggiOrigine(dati.live),
342
1756
  invite: typeof dati.invite === "string" ? dati.invite : null,
@@ -356,7 +1770,7 @@ function scadenzaJwt(ticket) {
356
1770
  "="
357
1771
  );
358
1772
  try {
359
- const payload = record(JSON.parse(globalThis.atob(base64)));
1773
+ const payload = record2(JSON.parse(globalThis.atob(base64)));
360
1774
  return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
361
1775
  } catch {
362
1776
  return null;
@@ -374,7 +1788,7 @@ function chiediBiglietto(porta, finestra, timeoutMs, aud) {
374
1788
  else resolve(ticket);
375
1789
  };
376
1790
  const ascolta = (evento) => {
377
- const dati = record(evento.data);
1791
+ const dati = record2(evento.data);
378
1792
  const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;
379
1793
  if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {
380
1794
  termina(dati.ticket);
@@ -457,6 +1871,7 @@ var VoceClient = class {
457
1871
  this.riproduzioni = /* @__PURE__ */ new Map();
458
1872
  this.sfuAttive = /* @__PURE__ */ new Map();
459
1873
  this.midGiocatori = /* @__PURE__ */ new Map();
1874
+ this.negati = /* @__PURE__ */ new Set();
460
1875
  this.mesh = /* @__PURE__ */ new Map();
461
1876
  this.stream = null;
462
1877
  this.tracciaMic = null;
@@ -549,6 +1964,8 @@ var VoceClient = class {
549
1964
  }
550
1965
  this.mutedCorrente = muted;
551
1966
  this.tracciaMic.enabled = !muted;
1967
+ if (muted) this.speakingCorrente = false;
1968
+ this.notificaPeers();
552
1969
  void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
553
1970
  }
554
1971
  setVolume(playerId, volume) {
@@ -581,6 +1998,7 @@ var VoceClient = class {
581
1998
  return;
582
1999
  }
583
2000
  if (message.op === "roster") {
2001
+ this.negati.clear();
584
2002
  this.modeCorrente = message.mode;
585
2003
  const publisher = new Set(message.peers.map((peer) => peer.id));
586
2004
  this.roster = [
@@ -597,6 +2015,7 @@ var VoceClient = class {
597
2015
  return;
598
2016
  }
599
2017
  if (message.op === "gain") {
2018
+ this.negati.clear();
600
2019
  for (const [playerId, gain] of Object.entries(message.gains)) {
601
2020
  this.gains.set(playerId, limita(gain));
602
2021
  this.aggiornaZero(playerId);
@@ -606,9 +2025,24 @@ var VoceClient = class {
606
2025
  this.accodaRiconciliazione();
607
2026
  return;
608
2027
  }
2028
+ if (message.op === "closed") {
2029
+ for (const mid of message.mids) {
2030
+ const playerId = this.midGiocatori.get(mid);
2031
+ if (playerId === void 0) continue;
2032
+ const attiva = this.sfuAttive.get(playerId);
2033
+ if (attiva?.mid === mid && !this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
2034
+ if (attiva?.mid === mid) this.sfuAttive.delete(playerId);
2035
+ this.midGiocatori.delete(mid);
2036
+ this.scollegaTraccia(playerId);
2037
+ this.negati.add(playerId);
2038
+ }
2039
+ this.notificaPeers();
2040
+ return;
2041
+ }
609
2042
  if (message.op === "signal") void this.riceviSegnale(message.from, message.data);
610
2043
  }
611
2044
  giocatoriCambiati() {
2045
+ this.negati.clear();
612
2046
  const presenti = new Set(this.contesto.giocatori().map((player) => player.id));
613
2047
  for (const playerId of this.gains.keys()) {
614
2048
  if (presenti.has(playerId)) continue;
@@ -666,10 +2100,6 @@ var VoceClient = class {
666
2100
  const dipendenze = this.richiediDipendenze();
667
2101
  const audioContext = dipendenze.creaAudioContext();
668
2102
  this.audioContext = audioContext;
669
- try {
670
- await audioContext.resume();
671
- } catch {
672
- }
673
2103
  if (this.micDesiderato) {
674
2104
  let stream;
675
2105
  try {
@@ -693,6 +2123,11 @@ var VoceClient = class {
693
2123
  mic.enabled = !this.mutedCorrente;
694
2124
  this.preparaAnalizzatore(stream);
695
2125
  }
2126
+ try {
2127
+ await audioContext.resume();
2128
+ } catch {
2129
+ }
2130
+ this.controllaGenerazione(generazione);
696
2131
  const risposta = await this.richiedi({ t: "voice", op: "ice" });
697
2132
  this.controllaGenerazione(generazione);
698
2133
  if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
@@ -827,12 +2262,19 @@ var VoceClient = class {
827
2262
  }
828
2263
  const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));
829
2264
  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
- });
2265
+ let risposta;
2266
+ try {
2267
+ risposta = await this.richiedi({
2268
+ t: "voice",
2269
+ op: "subscribe",
2270
+ session: sessione,
2271
+ tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
2272
+ });
2273
+ } catch (cause) {
2274
+ if (codiceErrore(cause) !== "not_allowed") throw cause;
2275
+ for (const peer of nuove) this.negati.add(peer.id);
2276
+ return;
2277
+ }
836
2278
  if (risposta.op !== "subscribe") {
837
2279
  throw creaErrore("voice_error", "The voice service returned an invalid response.");
838
2280
  }
@@ -840,6 +2282,7 @@ var VoceClient = class {
840
2282
  const peer = nuove.find(
841
2283
  (item) => item.session === risultato.session && item.track === risultato.track
842
2284
  );
2285
+ if (risultato.error === "not_allowed" && peer !== void 0) this.negati.add(peer.id);
843
2286
  if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;
844
2287
  this.midGiocatori.set(risultato.mid, peer.id);
845
2288
  this.sfuAttive.set(peer.id, {
@@ -946,8 +2389,17 @@ var VoceClient = class {
946
2389
  this.avviaRiconnessione();
947
2390
  }
948
2391
  }
949
- inviaSegnale(to, data) {
950
- return this.richiedi({ t: "voice", op: "signal", to, data });
2392
+ async inviaSegnale(to, data) {
2393
+ try {
2394
+ await this.richiedi({ t: "voice", op: "signal", to, data });
2395
+ } catch (cause) {
2396
+ if (codiceErrore(cause) !== "not_allowed") throw cause;
2397
+ const item = this.mesh.get(to);
2398
+ item?.pc.close();
2399
+ this.mesh.delete(to);
2400
+ this.scollegaTraccia(to);
2401
+ this.negati.add(to);
2402
+ }
951
2403
  }
952
2404
  peerDesiderati() {
953
2405
  const you = this.contesto.you();
@@ -955,6 +2407,7 @@ var VoceClient = class {
955
2407
  const player = giocatori.find((item) => item.id === you);
956
2408
  return this.roster.filter((peer) => {
957
2409
  if (peer.id === you) return false;
2410
+ if (this.negati.has(peer.id)) return false;
958
2411
  if (!this.micDesiderato && !peer.mic) return false;
959
2412
  if (this.modeCorrente === "team") {
960
2413
  const altro = giocatori.find((item) => item.id === peer.id);
@@ -1175,6 +2628,7 @@ var VoceClient = class {
1175
2628
  this.mesh.clear();
1176
2629
  this.sfuAttive.clear();
1177
2630
  this.midGiocatori.clear();
2631
+ this.negati.clear();
1178
2632
  for (const track of this.stream?.getTracks() ?? []) track.stop();
1179
2633
  this.stream = null;
1180
2634
  this.tracciaMic = null;
@@ -1263,22 +2717,21 @@ var GRAZIA_RICONNESSIONE = 6e4;
1263
2717
  var INTERVALLO_PING = 5e3;
1264
2718
  var RITARDO_FLUSH = 500;
1265
2719
  var ATTESA_ROSTER = 2e3;
1266
- var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
1267
- var CHIUSURE_DEFINITIVE_SPETTATORE = /* @__PURE__ */ new Set([4008, 4009]);
1268
- function record2(value) {
2720
+ var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006, 4008, 4009]);
2721
+ function record3(value) {
1269
2722
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1270
2723
  }
1271
2724
  function ingressoValido(value) {
1272
- const dati = record2(value);
2725
+ const dati = record3(value);
1273
2726
  return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
1274
2727
  }
1275
2728
  function visioneValida(value) {
1276
- const dati = record2(value);
2729
+ const dati = record3(value);
1277
2730
  return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.watch === "string" && typeof dati.url === "string";
1278
2731
  }
1279
2732
  function rispostaMatchValida(value) {
1280
- const dati = record2(value);
1281
- const players = record2(dati?.players);
2733
+ const dati = record3(value);
2734
+ const players = record3(dati?.players);
1282
2735
  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
2736
  }
1284
2737
  function copiaJson(value) {
@@ -1300,11 +2753,11 @@ function applicaPatch(state, value) {
1300
2753
  if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };
1301
2754
  contenitore = contenitore[parte];
1302
2755
  } else {
1303
- const oggetto = record2(contenitore);
1304
- if (oggetto === null || typeof parte !== "string" || !Object.hasOwn(oggetto, parte)) {
2756
+ const oggetto2 = record3(contenitore);
2757
+ if (oggetto2 === null || typeof parte !== "string" || !Object.hasOwn(oggetto2, parte)) {
1305
2758
  return { ok: false };
1306
2759
  }
1307
- contenitore = oggetto[parte];
2760
+ contenitore = oggetto2[parte];
1308
2761
  }
1309
2762
  }
1310
2763
  const ultima = percorso.at(-1);
@@ -1312,13 +2765,13 @@ function applicaPatch(state, value) {
1312
2765
  if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };
1313
2766
  contenitore[ultima] = copiaJson(operazione.value);
1314
2767
  } else {
1315
- const oggetto = record2(contenitore);
1316
- if (oggetto === null || typeof ultima !== "string") return { ok: false };
2768
+ const oggetto2 = record3(contenitore);
2769
+ if (oggetto2 === null || typeof ultima !== "string") return { ok: false };
1317
2770
  if (operazione.op === "del") {
1318
- if (!Object.hasOwn(oggetto, ultima)) return { ok: false };
1319
- delete oggetto[ultima];
2771
+ if (!Object.hasOwn(oggetto2, ultima)) return { ok: false };
2772
+ delete oggetto2[ultima];
1320
2773
  } else {
1321
- Object.defineProperty(oggetto, ultima, {
2774
+ Object.defineProperty(oggetto2, ultima, {
1322
2775
  configurable: true,
1323
2776
  enumerable: true,
1324
2777
  value: copiaJson(operazione.value),
@@ -1369,16 +2822,31 @@ function creaApiLive(input) {
1369
2822
  };
1370
2823
  }
1371
2824
  var StanzaClient = class {
1372
- constructor(roomId, codice, url, input, api, segnalaStanza, spettatore = false) {
2825
+ constructor(roomId, codice, url, dipendenze, api, segnalaStanza, spettatore = false) {
1373
2826
  this.roomId = roomId;
1374
2827
  this.codice = codice;
1375
- this.input = input;
2828
+ this.dipendenze = dipendenze;
1376
2829
  this.api = api;
1377
2830
  this.segnalaStanza = segnalaStanza;
1378
2831
  this.spettatore = spettatore;
2832
+ this.meta = { host: null, mode: null, countdownAt: null, configuration: null, connection: "connecting", closedCode: null };
2833
+ this.metaListeners = /* @__PURE__ */ new Set();
2834
+ this.connectionListeners = /* @__PURE__ */ new Set();
2835
+ this.scoreListeners = /* @__PURE__ */ new Set();
2836
+ this.scores = [];
2837
+ this.errorListeners = /* @__PURE__ */ new Set();
2838
+ this.roleId = 0;
2839
+ this.roleRequests = /* @__PURE__ */ new Map();
1379
2840
  this.statoPubblico = null;
1380
2841
  this.statoSincronizzato = null;
1381
2842
  this.tickCorrente = 0;
2843
+ this.tickRateCorrente = 0;
2844
+ this.latenzaCorrente = null;
2845
+ this.ultimoInput = null;
2846
+ this.inputInviato = null;
2847
+ this.timerInput = null;
2848
+ this.ultimoInvioGioco = -Infinity;
2849
+ this.inviiGioco = [];
1382
2850
  this.seedCorrente = 0;
1383
2851
  this.statusCorrente = "lobby";
1384
2852
  this.giocatoriCorrenti = [];
@@ -1422,16 +2890,117 @@ var StanzaClient = class {
1422
2890
  this.rosterRicevuto = true;
1423
2891
  this.risolviProntaSePossibile();
1424
2892
  }
1425
- }, input, input.voce);
2893
+ }, dipendenze, dipendenze.voce);
1426
2894
  if (spettatore) this.rosterRicevuto = true;
1427
2895
  this.apri(url);
1428
2896
  }
2897
+ get mode() {
2898
+ return this.meta.mode;
2899
+ }
2900
+ get countdownAt() {
2901
+ return this.meta.countdownAt;
2902
+ }
2903
+ get connection() {
2904
+ return this.meta.connection;
2905
+ }
2906
+ get metadata() {
2907
+ return structuredClone(this.meta);
2908
+ }
2909
+ get queuedScores() {
2910
+ return structuredClone(this.scores);
2911
+ }
2912
+ onMetadata(listener) {
2913
+ this.metaListeners.add(listener);
2914
+ return () => this.metaListeners.delete(listener);
2915
+ }
2916
+ onConnection(listener) {
2917
+ this.connectionListeners.add(listener);
2918
+ return () => this.connectionListeners.delete(listener);
2919
+ }
2920
+ onError(listener) {
2921
+ this.errorListeners.add(listener);
2922
+ return () => this.errorListeners.delete(listener);
2923
+ }
2924
+ onScoreQueued(listener) {
2925
+ this.scoreListeners.add(listener);
2926
+ return () => this.scoreListeners.delete(listener);
2927
+ }
2928
+ metadataChanged(change) {
2929
+ const old = this.meta.connection;
2930
+ this.meta = { ...this.meta, ...change };
2931
+ this.notifica(this.metaListeners, this.metadata);
2932
+ if (old !== this.meta.connection) this.notifica(this.connectionListeners, this.meta.connection);
2933
+ }
2934
+ initialMetadata(room) {
2935
+ this.metadataChanged({
2936
+ host: room.host,
2937
+ mode: room.mode,
2938
+ countdownAt: room.countdownAt ?? null,
2939
+ configuration: room.configuration ?? null,
2940
+ connection: "connected",
2941
+ closedCode: null
2942
+ });
2943
+ }
2944
+ requestRole(role) {
2945
+ if (typeof role !== "string" || role.length < 1 || role.length > 32) return Promise.reject(creaErrore("invalid_role", "The role is not valid."));
2946
+ if (this.connection !== "connected" || this.status !== "playing" || !this.meta.configuration?.requestRole) {
2947
+ return Promise.reject(creaErrore("role_change_unavailable", "Roles cannot be requested right now."));
2948
+ }
2949
+ if (this.roleRequests.size >= 8) return Promise.reject(creaErrore("rate_limited", "Too many role requests."));
2950
+ const r = ++this.roleId;
2951
+ return new Promise((resolve, reject) => {
2952
+ const timer = this.dipendenze.setTimeout(() => {
2953
+ this.roleRequests.delete(r);
2954
+ reject(creaErrore("timeout", "The role request timed out."));
2955
+ }, 5e3);
2956
+ this.roleRequests.set(r, { resolve, reject, timer });
2957
+ try {
2958
+ this.invia({ t: "request-role", r, role });
2959
+ } catch (error) {
2960
+ this.dipendenze.clearTimeout(timer);
2961
+ this.roleRequests.delete(r);
2962
+ reject(error);
2963
+ }
2964
+ });
2965
+ }
2966
+ clearRoleRequests() {
2967
+ for (const request of this.roleRequests.values()) {
2968
+ this.dipendenze.clearTimeout(request.timer);
2969
+ request.reject(creaErrore("offline", "The room connection ended."));
2970
+ }
2971
+ this.roleRequests.clear();
2972
+ }
2973
+ disconnect() {
2974
+ if (this.lasciata) return;
2975
+ this.lasciata = true;
2976
+ const socket = this.socket;
2977
+ this.socket = null;
2978
+ this.voice.termina();
2979
+ this.fermaInput();
2980
+ this.fermaPing();
2981
+ this.fermaRiconnessione();
2982
+ this.clearRoleRequests();
2983
+ if (this.timerRoster !== null) this.dipendenze.clearTimeout(this.timerRoster);
2984
+ socket?.close(1e3);
2985
+ this.segnalaStanza(null);
2986
+ this.metadataChanged({ connection: "disconnected", closedCode: null });
2987
+ if (!this.prontaRisolta) {
2988
+ this.prontaRisolta = true;
2989
+ this.rifiutaPronta(creaErrore("cancelled", "The room was disconnected."));
2990
+ }
2991
+ }
1429
2992
  get state() {
1430
2993
  return this.statoPubblico;
1431
2994
  }
1432
2995
  get tick() {
1433
2996
  return this.tickCorrente;
1434
2997
  }
2998
+ get tickRate() {
2999
+ return this.tickRateCorrente;
3000
+ }
3001
+ get latency() {
3002
+ return this.latenzaCorrente;
3003
+ }
1435
3004
  get seed() {
1436
3005
  return this.seedCorrente;
1437
3006
  }
@@ -1460,7 +3029,7 @@ var StanzaClient = class {
1460
3029
  return this.promessaPronta;
1461
3030
  }
1462
3031
  invite() {
1463
- return { code: this.codice, url: new URL(`/r/${this.codice}`, this.input.appOrigin).href };
3032
+ return { code: this.codice, url: new URL(`/r/${this.codice}`, this.dipendenze.appOrigin).href };
1464
3033
  }
1465
3034
  onState(listener) {
1466
3035
  this.ascoltatoriStato.add(listener);
@@ -1487,9 +3056,63 @@ var StanzaClient = class {
1487
3056
  };
1488
3057
  }
1489
3058
  send(message) {
3059
+ if (this.statusCorrente === "finished") return;
1490
3060
  const prossimo = this.seq + 1;
1491
3061
  this.invia({ t: "msg", seq: prossimo, m: message });
1492
3062
  this.seq = prossimo;
3063
+ this.ultimoInvioGioco = this.dipendenze.ora();
3064
+ this.inviiGioco = [...this.inviiGioco.slice(-(MESSAGGI_GIOCO_AL_SECONDO - 1)), this.ultimoInvioGioco];
3065
+ }
3066
+ input(value) {
3067
+ if (this.terminata || this.lasciata || this.statusCorrente === "finished") return;
3068
+ try {
3069
+ const serializzato = JSON.stringify(value);
3070
+ if (serializzato === void 0) throw new TypeError();
3071
+ this.ultimoInput = serializzato;
3072
+ } catch {
3073
+ throw creaErrore("invalid_request", "Room input must be valid JSON.");
3074
+ }
3075
+ this.programmaInput();
3076
+ }
3077
+ pulisciInput() {
3078
+ this.fermaInput();
3079
+ this.ultimoInput = this.inputInviato = null;
3080
+ this.ultimoInvioGioco = -Infinity;
3081
+ this.inviiGioco = [];
3082
+ }
3083
+ fermaInput() {
3084
+ if (this.timerInput !== null) this.dipendenze.clearTimeout(this.timerInput);
3085
+ this.timerInput = null;
3086
+ }
3087
+ programmaInput() {
3088
+ if (this.timerInput !== null || this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3089
+ const ora = this.dipendenze.ora();
3090
+ const frequenza = this.tickRateCorrente > 0 ? Math.min(MESSAGGI_GIOCO_AL_SECONDO, this.tickRateCorrente) : MESSAGGI_GIOCO_AL_SECONDO;
3091
+ const periodo = 1e3 / frequenza;
3092
+ this.inviiGioco = this.inviiGioco.filter((at) => ora - at < 1e3);
3093
+ const spazio = this.inviiGioco.length >= MESSAGGI_GIOCO_AL_SECONDO ? this.inviiGioco[0] + 1e3 : ora;
3094
+ const prossimo = Number.isFinite(this.ultimoInvioGioco) ? this.ultimoInvioGioco + periodo : ora + periodo;
3095
+ this.timerInput = this.dipendenze.setTimeout(() => {
3096
+ this.timerInput = null;
3097
+ if (this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3098
+ const adesso = this.dipendenze.ora();
3099
+ if (adesso < this.ultimoInvioGioco + periodo || this.inviiGioco.filter((at) => adesso - at < 1e3).length >= MESSAGGI_GIOCO_AL_SECONDO) {
3100
+ this.programmaInput();
3101
+ return;
3102
+ }
3103
+ const valore = this.ultimoInput;
3104
+ try {
3105
+ this.send(JSON.parse(valore));
3106
+ this.inputInviato = valore;
3107
+ } catch {
3108
+ }
3109
+ }, Math.max(0, Math.ceil(Math.max(prossimo, spazio) - ora)));
3110
+ }
3111
+ aggiornaTickRate(value) {
3112
+ if (value === void 0 || !Number.isInteger(value) || value < 0 || value > 60 || value === this.tickRateCorrente) return;
3113
+ this.tickRateCorrente = value;
3114
+ this.fermaInput();
3115
+ this.programmaInput();
1493
3116
  }
1494
3117
  ready(ready) {
1495
3118
  this.invia({ t: "ready", ready });
@@ -1503,6 +3126,10 @@ var StanzaClient = class {
1503
3126
  start() {
1504
3127
  this.invia({ t: "start" });
1505
3128
  }
3129
+ restart() {
3130
+ if (this.statusCorrente !== "finished") throw creaErrore("rematch_unavailable", "This room is not waiting for a rematch.");
3131
+ this.invia({ t: "restart" });
3132
+ }
1506
3133
  leave() {
1507
3134
  if (this.lasciata) return;
1508
3135
  if (!this.spettatore) this.voice.leave();
@@ -1516,7 +3143,7 @@ var StanzaClient = class {
1516
3143
  this.termina(1e3);
1517
3144
  }
1518
3145
  serverTime() {
1519
- return this.input.ora() + this.scartoOrario;
3146
+ return this.dipendenze.ora() + this.scartoOrario;
1520
3147
  }
1521
3148
  copiaGiocatori() {
1522
3149
  return this.giocatoriCorrenti.map((player) => ({ ...player }));
@@ -1544,7 +3171,7 @@ var StanzaClient = class {
1544
3171
  apri(url) {
1545
3172
  let socket;
1546
3173
  try {
1547
- socket = this.input.apriSocket(url);
3174
+ socket = this.dipendenze.apriSocket(url);
1548
3175
  } catch {
1549
3176
  this.programmaRiconnessione();
1550
3177
  return;
@@ -1557,45 +3184,58 @@ var StanzaClient = class {
1557
3184
  if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);
1558
3185
  });
1559
3186
  socket.addEventListener("close", (evento) => {
1560
- if (this.socket === socket) this.chiuso(evento.code);
3187
+ if (this.socket === socket) this.chiuso(evento.code, evento.reason);
1561
3188
  });
1562
3189
  }
1563
3190
  avviaPing() {
1564
- if (this.timerPing !== null) this.input.clearInterval(this.timerPing);
1565
- this.timerPing = this.input.setInterval(() => {
3191
+ if (this.timerPing !== null) this.dipendenze.clearInterval(this.timerPing);
3192
+ this.timerPing = this.dipendenze.setInterval(() => {
1566
3193
  if (this.socket?.readyState !== APERTO) return;
1567
3194
  try {
1568
- this.invia({ t: "ping", c: this.input.ora() });
3195
+ this.invia({ t: "ping", c: this.dipendenze.ora() });
1569
3196
  } catch {
1570
3197
  }
1571
3198
  }, INTERVALLO_PING);
1572
3199
  }
1573
3200
  fermaPing() {
1574
3201
  if (this.timerPing === null) return;
1575
- this.input.clearInterval(this.timerPing);
3202
+ this.dipendenze.clearInterval(this.timerPing);
1576
3203
  this.timerPing = null;
1577
3204
  }
1578
3205
  ricevi(frame) {
1579
3206
  let dati;
1580
3207
  try {
1581
3208
  const value = JSON.parse(frame);
1582
- const oggetto = record2(value);
1583
- if (oggetto === null || typeof oggetto.t !== "string") return;
1584
- dati = oggetto;
3209
+ const oggetto2 = record3(value);
3210
+ if (oggetto2 === null || typeof oggetto2.t !== "string") return;
3211
+ dati = oggetto2;
1585
3212
  } catch {
1586
3213
  return;
1587
3214
  }
1588
3215
  try {
1589
3216
  if (dati.t === "watching") this.riceviWatching(dati);
1590
3217
  else if (dati.t === "welcome") this.riceviWelcome(dati);
1591
- else if (dati.t === "players") this.riceviGiocatori(dati.players);
3218
+ else if (dati.t === "players") this.riceviGiocatori(dati.players, dati.host);
1592
3219
  else if (dati.t === "status") this.riceviStatus(dati);
1593
3220
  else if (dati.t === "state") this.riceviDiff(dati);
1594
3221
  else if (dati.t === "snapshot") this.riceviSnapshot(dati);
1595
3222
  else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));
1596
3223
  else if (dati.t === "pong") this.riceviPong(dati);
3224
+ else if (dati.t === "error") this.notifica(this.errorListeners, { code: dati.code, message: dati.message });
1597
3225
  else if (dati.t === "flush") this.richiediFlush();
1598
- else if (dati.t === "voice") this.voice.ricevi(dati);
3226
+ else if (dati.t === "score-queued" && !this.spettatore) {
3227
+ this.scores.push(structuredClone(dati.score));
3228
+ this.scores = this.scores.slice(-32);
3229
+ this.notifica(this.scoreListeners, structuredClone(dati.score));
3230
+ } else if (dati.t === "role-result") {
3231
+ const request = this.roleRequests.get(dati.r);
3232
+ if (request) {
3233
+ this.dipendenze.clearTimeout(request.timer);
3234
+ this.roleRequests.delete(dati.r);
3235
+ if (dati.ok) request.resolve();
3236
+ else request.reject(creaErrore(dati.code ?? "role_change_refused", "The role change was not accepted."));
3237
+ }
3238
+ } else if (dati.t === "voice") this.voice.ricevi(dati);
1599
3239
  } catch {
1600
3240
  if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();
1601
3241
  }
@@ -1603,13 +3243,16 @@ var StanzaClient = class {
1603
3243
  riceviWatching(dati) {
1604
3244
  const room = dati.room;
1605
3245
  if (!this.spettatore || room.id !== this.roomId) return;
3246
+ this.aggiornaTickRate(room.tickRate);
1606
3247
  this.seedCorrente = room.seed;
1607
3248
  this.hostCorrente = room.host;
1608
3249
  this.statusCorrente = room.status;
3250
+ this.resultCorrente = copiaJson(room.result ?? null);
3251
+ if (room.status === "finished") this.pulisciInput();
1609
3252
  this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
1610
3253
  this.delaySpettatore = dati.delayMs;
1611
3254
  this.aggiornaStato(dati.state, room.tick, room.serverTime);
1612
- this.scartoOrario = room.serverTime - this.input.ora();
3255
+ this.scartoOrario = room.serverTime - this.dipendenze.ora();
1613
3256
  this.resyncRichiesto = false;
1614
3257
  this.welcomeRicevuto = true;
1615
3258
  this.ritardoIndice = 0;
@@ -1621,22 +3264,27 @@ var StanzaClient = class {
1621
3264
  this.resultCorrente,
1622
3265
  room.serverTime
1623
3266
  );
3267
+ this.initialMetadata(room);
3268
+ this.programmaInput();
1624
3269
  this.risolviProntaSePossibile();
1625
3270
  }
1626
3271
  riceviWelcome(dati) {
1627
3272
  const room = dati.room;
1628
3273
  if (room.id !== this.roomId) return;
1629
3274
  this.youCorrente = dati.you;
3275
+ this.aggiornaTickRate(room.tickRate);
1630
3276
  this.seedCorrente = room.seed;
1631
3277
  this.hostCorrente = room.host;
1632
3278
  this.statusCorrente = room.status;
3279
+ this.resultCorrente = copiaJson(room.result ?? null);
3280
+ if (room.status === "finished") this.pulisciInput();
1633
3281
  this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
1634
3282
  this.aggiornaStato(dati.state, room.tick, room.serverTime);
1635
- this.scartoOrario = room.serverTime - this.input.ora();
3283
+ this.scartoOrario = room.serverTime - this.dipendenze.ora();
1636
3284
  this.resyncRichiesto = false;
1637
3285
  this.welcomeRicevuto = true;
1638
3286
  if (!this.rosterRicevuto && this.timerRoster === null) {
1639
- this.timerRoster = this.input.setTimeout(() => {
3287
+ this.timerRoster = this.dipendenze.setTimeout(() => {
1640
3288
  this.timerRoster = null;
1641
3289
  this.rosterRicevuto = true;
1642
3290
  this.risolviProntaSePossibile();
@@ -1653,31 +3301,49 @@ var StanzaClient = class {
1653
3301
  this.resultCorrente,
1654
3302
  room.serverTime
1655
3303
  );
3304
+ this.initialMetadata(room);
3305
+ this.programmaInput();
1656
3306
  this.risolviProntaSePossibile();
1657
3307
  }
1658
- riceviGiocatori(value) {
3308
+ riceviGiocatori(value, host) {
1659
3309
  this.giocatoriCorrenti = value.map((player) => ({ ...player }));
1660
- if (!this.giocatoriCorrenti.some(
3310
+ if (host !== void 0) this.hostCorrente = host;
3311
+ else if (!this.giocatoriCorrenti.some(
1661
3312
  (player) => player.id === this.hostCorrente && player.connected
1662
3313
  )) {
1663
3314
  this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;
1664
3315
  }
3316
+ this.metadataChanged({ host: this.hostCorrente });
1665
3317
  this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
1666
3318
  this.voice.giocatoriCambiati();
1667
3319
  }
1668
3320
  riceviStatus(dati) {
1669
3321
  this.statusCorrente = dati.status;
3322
+ if (dati.host !== void 0) this.hostCorrente = dati.host;
1670
3323
  this.resultCorrente = copiaJson(dati.result);
3324
+ if (dati.status === "finished") {
3325
+ this.pulisciInput();
3326
+ this.clearRoleRequests();
3327
+ }
1671
3328
  if (dati.status === "ended") {
1672
3329
  this.terminata = true;
3330
+ this.clearRoleRequests();
1673
3331
  this.segnalaStanza(null);
1674
3332
  if (!this.spettatore) this.voice.termina();
1675
3333
  this.fermaPing();
1676
3334
  this.fermaRiconnessione();
3335
+ this.fermaInput();
3336
+ this.ultimoInput = null;
1677
3337
  }
3338
+ this.metadataChanged({
3339
+ host: this.hostCorrente,
3340
+ countdownAt: dati.countdownAt ?? (dati.status === "countdown" ? dati.at : null),
3341
+ ...dati.status === "ended" ? { connection: "ended", closedCode: 4004 } : {}
3342
+ });
1678
3343
  this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
1679
3344
  }
1680
3345
  riceviDiff(dati) {
3346
+ this.aggiornaTickRate(dati.tickRate);
1681
3347
  if (dati.base !== this.tickCorrente) {
1682
3348
  this.chiediResync();
1683
3349
  return;
@@ -1692,6 +3358,7 @@ var StanzaClient = class {
1692
3358
  }
1693
3359
  riceviSnapshot(dati) {
1694
3360
  if (dati.tick < this.tickCorrente) return;
3361
+ this.aggiornaTickRate(dati.tickRate);
1695
3362
  this.resyncRichiesto = false;
1696
3363
  this.aggiornaStato(dati.state, dati.tick, dati.serverTime);
1697
3364
  }
@@ -1711,22 +3378,35 @@ var StanzaClient = class {
1711
3378
  }
1712
3379
  }
1713
3380
  riceviPong(dati) {
1714
- this.scartoOrario = dati.s - (dati.c + this.input.ora()) / 2;
3381
+ const ora = this.dipendenze.ora();
3382
+ if (!Number.isFinite(dati.c) || !Number.isFinite(dati.s) || dati.c > ora) return;
3383
+ const rtt = ora - dati.c;
3384
+ this.latenzaCorrente = this.latenzaCorrente === null ? rtt : this.latenzaCorrente * 0.8 + rtt * 0.2;
3385
+ this.scartoOrario = dati.s - (dati.c + ora) / 2;
1715
3386
  }
1716
- chiuso(code) {
3387
+ chiuso(code, reason) {
1717
3388
  this.socket = null;
1718
3389
  this.welcomeRicevuto = false;
3390
+ this.latenzaCorrente = null;
3391
+ this.fermaInput();
3392
+ this.inputInviato = null;
3393
+ this.ultimoInvioGioco = -Infinity;
3394
+ this.inviiGioco = [];
1719
3395
  this.fermaPing();
1720
3396
  if (this.lasciata || this.terminata) return;
1721
- if (CHIUSURE_DEFINITIVE.has(code) || this.spettatore && CHIUSURE_DEFINITIVE_SPETTATORE.has(code)) {
1722
- this.termina(code);
3397
+ if (CHIUSURE_DEFINITIVE.has(code)) {
3398
+ const errore = code === 4009 && reason === "message_too_large" ? "message_too_large" : void 0;
3399
+ if (errore) this.notifica(this.errorListeners, { code: errore, message: "The room message is too large." });
3400
+ this.termina(code, errore);
1723
3401
  return;
1724
3402
  }
3403
+ this.clearRoleRequests();
1725
3404
  if (!this.spettatore) this.voice.socketDisconnesso();
1726
3405
  this.programmaRiconnessione();
1727
3406
  }
1728
3407
  programmaRiconnessione() {
1729
3408
  if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;
3409
+ this.metadataChanged({ connection: "reconnecting" });
1730
3410
  const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);
1731
3411
  const ritardo = RITARDI_RICONNESSIONE2[indice];
1732
3412
  if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {
@@ -1735,7 +3415,7 @@ var StanzaClient = class {
1735
3415
  }
1736
3416
  this.ritardoIndice++;
1737
3417
  this.tempoRiconnessione += ritardo;
1738
- this.timerRiconnessione = this.input.setTimeout(() => {
3418
+ this.timerRiconnessione = this.dipendenze.setTimeout(() => {
1739
3419
  this.timerRiconnessione = null;
1740
3420
  void this.riconnetti();
1741
3421
  }, ritardo);
@@ -1744,6 +3424,7 @@ var StanzaClient = class {
1744
3424
  if (this.terminata || this.lasciata) return;
1745
3425
  try {
1746
3426
  const ingresso = this.spettatore ? await this.api.watchRoom(this.roomId) : await this.api.joinRoom(this.roomId);
3427
+ if (this.terminata || this.lasciata) return;
1747
3428
  const codiceCambiato = this.codice !== ingresso.code;
1748
3429
  this.codice = ingresso.code;
1749
3430
  if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {
@@ -1756,13 +3437,17 @@ var StanzaClient = class {
1756
3437
  }
1757
3438
  fermaRiconnessione() {
1758
3439
  if (this.timerRiconnessione === null) return;
1759
- this.input.clearTimeout(this.timerRiconnessione);
3440
+ this.dipendenze.clearTimeout(this.timerRiconnessione);
1760
3441
  this.timerRiconnessione = null;
1761
3442
  }
1762
- termina(code) {
3443
+ termina(code, errore) {
3444
+ this.clearRoleRequests();
3445
+ this.metadataChanged({ connection: code === 1e3 ? "disconnected" : code === 4006 ? "replaced" : "closed", closedCode: typeof code === "number" ? code : null });
1763
3446
  const risultato = { closed: code };
1764
3447
  const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
1765
3448
  this.terminata = true;
3449
+ this.fermaInput();
3450
+ this.ultimoInput = null;
1766
3451
  this.segnalaStanza(null);
1767
3452
  this.statusCorrente = "ended";
1768
3453
  this.resultCorrente = risultato;
@@ -1780,14 +3465,14 @@ var StanzaClient = class {
1780
3465
  4008: "rate_limited",
1781
3466
  4009: "invalid_request"
1782
3467
  };
1783
- const erroreCode = typeof code === "number" ? codici[code] ?? "offline" : "offline";
3468
+ const erroreCode = errore ?? (typeof code === "number" ? codici[code] ?? "offline" : "offline");
1784
3469
  this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));
1785
3470
  }
1786
3471
  }
1787
3472
  risolviProntaSePossibile() {
1788
3473
  if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;
1789
3474
  if (this.timerRoster !== null) {
1790
- this.input.clearTimeout(this.timerRoster);
3475
+ this.dipendenze.clearTimeout(this.timerRoster);
1791
3476
  this.timerRoster = null;
1792
3477
  }
1793
3478
  this.prontaRisolta = true;
@@ -1799,7 +3484,7 @@ var StanzaClient = class {
1799
3484
  richiediFlush() {
1800
3485
  this.flushRichiesto = true;
1801
3486
  if (this.flushInCorso || this.timerFlush !== null) return;
1802
- this.timerFlush = this.input.setTimeout(() => {
3487
+ this.timerFlush = this.dipendenze.setTimeout(() => {
1803
3488
  this.timerFlush = null;
1804
3489
  void this.eseguiFlush();
1805
3490
  }, RITARDO_FLUSH);
@@ -1869,12 +3554,33 @@ function creaGestoreStanze(input, invited) {
1869
3554
  );
1870
3555
  await stanza.pronta();
1871
3556
  return {
3557
+ get mode() {
3558
+ return stanza.mode;
3559
+ },
3560
+ get countdownAt() {
3561
+ return stanza.countdownAt;
3562
+ },
3563
+ get connection() {
3564
+ return stanza.connection;
3565
+ },
3566
+ get metadata() {
3567
+ return stanza.metadata;
3568
+ },
3569
+ onMetadata: (listener) => stanza.onMetadata(listener),
3570
+ onConnection: (listener) => stanza.onConnection(listener),
3571
+ disconnect: () => stanza.disconnect(),
1872
3572
  get state() {
1873
3573
  return stanza.state;
1874
3574
  },
1875
3575
  get tick() {
1876
3576
  return stanza.tick;
1877
3577
  },
3578
+ get tickRate() {
3579
+ return stanza.tickRate;
3580
+ },
3581
+ get latency() {
3582
+ return stanza.latency;
3583
+ },
1878
3584
  get seed() {
1879
3585
  return stanza.seed;
1880
3586
  },
@@ -1943,7 +3649,7 @@ function creaGestoreStanze(input, invited) {
1943
3649
  function ricevi(evento) {
1944
3650
  let dati = null;
1945
3651
  try {
1946
- dati = typeof evento.data === "string" ? record2(JSON.parse(evento.data)) : null;
3652
+ dati = typeof evento.data === "string" ? record3(JSON.parse(evento.data)) : null;
1947
3653
  } catch {
1948
3654
  }
1949
3655
  if (dati === null || typeof dati.t !== "string") {
@@ -2103,15 +3809,16 @@ async function creaStandalone(input, invited = null) {
2103
3809
  return {
2104
3810
  connected: false,
2105
3811
  player: { id: "local", name: "Guest", guest: true },
2106
- daily: { day, seed, random: creaMulberry32(seed) },
3812
+ daily: { day, seed, random: creaMulberry32(seed), rng: () => creaMulberry32(seed) },
2107
3813
  time: { now: input.ora },
2108
3814
  save: creaSave(input.archivio, input.ora),
2109
3815
  board: {
2110
3816
  async submit() {
2111
- return { accepted: false, reason: "offline" };
3817
+ return { accepted: false, reason: "offline", verified: false };
2112
3818
  },
2113
3819
  async top(_board, opzioni = {}) {
2114
- return { day: opzioni.daily ? day : null, entries: [], me: null };
3820
+ 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.");
3821
+ return { day: opzioni.day ?? (opzioni.daily ? day : null), entries: [], me: null };
2115
3822
  }
2116
3823
  },
2117
3824
  room: creaStanzeOffline(invited)
@@ -2142,6 +3849,8 @@ function dipendenzeReali2() {
2142
3849
  documento: typeof document === "undefined" ? null : document,
2143
3850
  fetcher: (input, init) => globalThis.fetch(input, init),
2144
3851
  archivio: archivioReale(),
3852
+ language: typeof navigator === "undefined" ? "en" : navigator.language,
3853
+ pathname: typeof location === "undefined" ? "/" : location.pathname,
2145
3854
  hostname: typeof location === "undefined" ? "" : location.hostname,
2146
3855
  subtle: globalThis.crypto.subtle,
2147
3856
  ora: Date.now,
@@ -2152,14 +3861,14 @@ async function connetti(input) {
2152
3861
  const appOrigin = leggiAppOrigin(input.documento);
2153
3862
  const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;
2154
3863
  if (appOrigin === null || senzaPadre) {
2155
- return creaStandalone(input);
3864
+ return localConnection(input);
2156
3865
  }
2157
3866
  const handshake = await attendiHandshake(
2158
3867
  input.finestra,
2159
3868
  appOrigin,
2160
3869
  input.timeoutHandshake
2161
3870
  );
2162
- if (handshake === null) return creaStandalone(input);
3871
+ if (handshake === null) return localConnection(input);
2163
3872
  const biglietto = creaGestoreBiglietto(
2164
3873
  handshake.ticket,
2165
3874
  handshake.porta,
@@ -2174,7 +3883,8 @@ async function connetti(input) {
2174
3883
  try {
2175
3884
  me = await api.me();
2176
3885
  } catch {
2177
- return creaStandalone(input, handshake.invite);
3886
+ const base2 = await creaStandalone(input, handshake.invite);
3887
+ return installSession(base2, handshake, input);
2178
3888
  }
2179
3889
  const dopo = input.ora();
2180
3890
  const scartoOrario = me.serverTime - (prima + dopo) / 2;
@@ -2208,10 +3918,10 @@ async function connetti(input) {
2208
3918
  }
2209
3919
  }
2210
3920
  }, handshake.invite);
2211
- return {
3921
+ const base = {
2212
3922
  connected: true,
2213
3923
  player: me.player,
2214
- daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed) },
3924
+ daily: { day: me.day, seed: me.seed, random: creaMulberry32(me.seed), rng: () => creaMulberry32(me.seed) },
2215
3925
  time: { now: () => input.ora() + scartoOrario },
2216
3926
  save: {
2217
3927
  set: (key, value) => api.saveSet(key, value),
@@ -2224,7 +3934,7 @@ async function connetti(input) {
2224
3934
  try {
2225
3935
  return await api.boardSubmit(board, score, opzioni.daily === true);
2226
3936
  } catch (errore) {
2227
- if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline" };
3937
+ if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline", verified: false };
2228
3938
  throw errore;
2229
3939
  }
2230
3940
  },
@@ -2232,6 +3942,28 @@ async function connetti(input) {
2232
3942
  },
2233
3943
  room
2234
3944
  };
3945
+ return installSession(base, handshake, input);
3946
+ }
3947
+ function installSession(base, handshake, input) {
3948
+ const coordinator = createSession(base, handshake?.overlay?.configuration ?? null, base.connected && handshake?.live != null);
3949
+ if (handshake?.overlay) {
3950
+ const dispose = attachKitBridge(handshake.porta, handshake.overlay, coordinator);
3951
+ if (coordinator.session.capabilities.overlay && typeof window !== "undefined" && input?.finestra === window) window.addEventListener("pagehide", dispose, { once: true });
3952
+ }
3953
+ const preferences = handshake?.languagePreferences?.length ? handshake.languagePreferences : [handshake?.language ?? input?.language ?? "en"];
3954
+ const language = resolveGameLanguage(preferences, handshake?.gameLanguages ?? (handshake?.overlay ? manifestLanguages(handshake.overlay.configuration.manifest) : void 0));
3955
+ const uiLanguage = overlayLocale(handshake?.uiLanguage ?? handshake?.language ?? input?.language);
3956
+ return {
3957
+ ...base,
3958
+ player: { ...base.player, language, uiLanguage },
3959
+ text: createTextLoader(input?.fetcher ?? globalThis.fetch, language, input?.pathname),
3960
+ room: coordinator.rooms,
3961
+ session: coordinator.session,
3962
+ overlay: coordinator.overlay
3963
+ };
3964
+ }
3965
+ async function localConnection(input) {
3966
+ return installSession(await creaStandalone(input), void 0, input);
2235
3967
  }
2236
3968
  function dispositivoSconosciuto() {
2237
3969
  return {