@caisual/kit 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kit.js CHANGED
@@ -1,4188 +1,2 @@
1
- // Caisual game kit v0.14.0
2
-
3
- // ../contracts/src/slug.ts
4
- var NOMI_RISERVATI = [
5
- "www",
6
- "api",
7
- "app",
8
- "play",
9
- "live",
10
- "multi",
11
- "cdn",
12
- "assets",
13
- "static",
14
- "mail",
15
- "mx",
16
- "ns1",
17
- "ns2",
18
- "autodiscover",
19
- "_dmarc",
20
- "admin",
21
- "login",
22
- "account",
23
- "auth",
24
- "pay",
25
- "secure",
26
- "support",
27
- "help",
28
- "blog",
29
- "status",
30
- "dev",
31
- "staging",
32
- "test",
33
- "caisual",
34
- "shipz"
35
- ];
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
- "card",
106
- "icon",
107
- "screenshots",
108
- "tags",
109
- "languages",
110
- "language",
111
- "platform",
112
- "orientation",
113
- "input",
114
- "visibility",
115
- "network",
116
- "isolated",
117
- "requires",
118
- "players",
119
- "lobby",
120
- "persistent",
121
- "spectators",
122
- "boards",
123
- "roles",
124
- "teams",
125
- "voice",
126
- "modes"
127
- ]);
128
- var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
129
- var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
130
- var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
131
- var VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);
132
- var VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);
133
- var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
134
- var TAG = /^[a-z0-9-]+$/;
135
- var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
136
- var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
137
- var ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
138
- function oggetto(value) {
139
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
140
- return value;
141
- }
142
- function percorsoRelativo(value) {
143
- if (value === "" || value.startsWith("/") || value.includes("\\") || value.includes("\0")) return false;
144
- if (value.includes("?") || value.includes("#")) return false;
145
- const parti = value.split("/");
146
- if (parti.some((parte) => parte === "" || parte === "." || parte === "..")) return false;
147
- try {
148
- const decoded = parti.map((parte) => decodeURIComponent(parte));
149
- return !decoded.some((parte) => parte === "" || parte === "." || parte === ".." || parte.includes("/"));
150
- } catch {
151
- return false;
152
- }
153
- }
154
- function hostValido(value) {
155
- if (value.length === 0 || value.length > 253) return false;
156
- if (value.includes("://") || /[/:?#@]/.test(value)) return false;
157
- const parti = value.split(".");
158
- return parti.every(
159
- (parte) => parte.length >= 1 && parte.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(parte)
160
- );
161
- }
162
- function interoTra(value, min, max) {
163
- return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
164
- }
165
- function stringaDefault(dati, campo, valoreDefault, errori) {
166
- const value = dati[campo];
167
- if (value === void 0) return valoreDefault;
168
- if (typeof value !== "string") {
169
- errori.push(`${campo}: must be a string.`);
170
- return valoreDefault;
171
- }
172
- return value;
173
- }
174
- function testoFacoltativo(value, key, max, path, errors) {
175
- if (value[key] === void 0) return void 0;
176
- const check = (text2, field2) => {
177
- if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\r\n\u0000-\u001f]/.test(text2)) {
178
- errors.push(`${field2}: must contain 1-${max} characters on one line.`);
179
- return void 0;
180
- }
181
- return text2.trim();
182
- };
183
- const text = value[key], field = path ? `${path}.${key}` : key;
184
- if (typeof text === "string") return check(text, field);
185
- const translations = oggetto(text);
186
- if (!translations || Object.keys(translations).length === 0) {
187
- errors.push(`${field}: must be a string or a non-empty language-to-text object.`);
188
- return void 0;
189
- }
190
- const result = {};
191
- for (const [raw, text2] of Object.entries(translations)) {
192
- const tag = normalizeLanguage(raw);
193
- if (!tag) {
194
- errors.push(`${field}.${raw}: must be a BCP 47 language tag.`);
195
- continue;
196
- }
197
- if (Object.hasOwn(result, tag)) errors.push(`${field}.${raw}: duplicate language.`);
198
- const checked = check(text2, `${field}.${raw}`);
199
- if (checked !== void 0) result[tag] = checked;
200
- }
201
- return result;
202
- }
203
- function validaManifest(valore) {
204
- const errori = [];
205
- const dati = oggetto(valore);
206
- if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
207
- for (const campo of Object.keys(dati)) {
208
- if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
209
- }
210
- if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
211
- else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
212
- const id = stringaDefault(dati, "id", "", errori);
213
- if (dati.id === void 0) errori.push("id: is required.");
214
- else if (typeof dati.id === "string") {
215
- if (!isValidSlug(id)) {
216
- errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters.");
217
- } else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");
218
- }
219
- const name = stringaDefault(dati, "name", "", errori);
220
- if (dati.name === void 0) errori.push("name: is required.");
221
- else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
222
- errori.push("name: must contain 1-60 characters.");
223
- }
224
- const description = dati.description === "" ? "" : testoFacoltativo(dati, "description", 500, "", errori) ?? "";
225
- const immagini = { cover: "", card: "", icon: "" };
226
- const usati = /* @__PURE__ */ new Set();
227
- for (const campo of ["cover", "card", "icon"]) {
228
- const path = dati[campo];
229
- if (path === void 0 || path === null) errori.push(`${campo}: is required.`);
230
- else if (typeof path !== "string" || !percorsoRelativo(path)) errori.push(`${campo}: must be a relative file path inside client/ without query, fragment, or parent segments.`);
231
- else {
232
- if (!/\.(png|jpe?g|webp)$/i.test(path)) errori.push(`${campo}: must be a PNG, JPEG or WebP file.`);
233
- const canonical = decodeURIComponent(path);
234
- if (usati.has(canonical)) errori.push(`${campo}: each image must use a different file; cover, card and icon cannot share a path.`);
235
- usati.add(canonical);
236
- immagini[campo] = path;
237
- }
238
- }
239
- const { cover, card, icon } = immagini;
240
- const screenshots = [];
241
- if (dati.screenshots !== void 0) {
242
- if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");
243
- else {
244
- if (dati.screenshots.length > 8) errori.push("screenshots: must contain at most 8 paths.");
245
- for (const [indice, value] of dati.screenshots.entries()) {
246
- if (typeof value !== "string" || !percorsoRelativo(value)) {
247
- errori.push(`screenshots[${indice}]: must be a relative file path without query, fragment, or parent segments.`);
248
- } else screenshots.push(value);
249
- }
250
- }
251
- }
252
- const tags = [];
253
- if (dati.tags !== void 0) {
254
- if (!Array.isArray(dati.tags)) errori.push("tags: must be an array.");
255
- else {
256
- if (dati.tags.length > 10) errori.push("tags: must contain at most 10 tags.");
257
- for (const [indice, value] of dati.tags.entries()) {
258
- if (typeof value !== "string" || value.length > 24 || !TAG.test(value)) {
259
- errori.push(`tags[${indice}]: must be 1-24 lowercase letters, digits, or hyphens.`);
260
- } else tags.push(value);
261
- }
262
- }
263
- }
264
- const legacyLanguage = stringaDefault(dati, "language", "en", errori);
265
- if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {
266
- errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
267
- }
268
- const languages2 = [];
269
- if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
270
- errori.push("languages: must be a non-empty array of BCP 47 language tags.");
271
- } else for (const [index, raw] of dati.languages.entries()) {
272
- const tag = normalizeLanguage(raw);
273
- if (!tag) errori.push(`languages[${index}]: must be a BCP 47 language tag.`);
274
- else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);
275
- else languages2.push(tag);
276
- }
277
- if (!languages2.includes("en")) errori.push("languages: English is always required alongside the game's own languages.");
278
- const language = languages2[0] ?? legacyLanguage;
279
- if (typeof description === "object") {
280
- for (const tag of Object.keys(description)) {
281
- if (!languages2.includes(tag)) errori.push(`description.${tag}: language must be declared in languages.`);
282
- }
283
- }
284
- if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
285
- errori.push("language: must match the first entry in languages when both are present.");
286
- }
287
- let platform = "both";
288
- if (dati.platform === void 0) errori.push("platform: is required.");
289
- else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
290
- errori.push("platform: must be desktop, mobile, or both.");
291
- } else platform = dati.platform;
292
- let orientation = "landscape";
293
- if (dati.orientation !== void 0) {
294
- if (typeof dati.orientation !== "string" || !ORIENTATION.has(dati.orientation)) {
295
- errori.push("orientation: must be landscape or portrait.");
296
- } else orientation = dati.orientation;
297
- }
298
- const input = [];
299
- if (dati.input !== void 0) {
300
- if (!Array.isArray(dati.input)) errori.push("input: must be an array.");
301
- else for (const [indice, value] of dati.input.entries()) {
302
- if (typeof value !== "string" || !INPUT.has(value)) {
303
- errori.push(`input[${indice}]: must be keyboard, mouse, touch, or gamepad.`);
304
- } else if (input.includes(value)) errori.push(`input[${indice}]: duplicate value ${value}.`);
305
- else input.push(value);
306
- }
307
- }
308
- let visibility = "public";
309
- if (dati.visibility !== void 0) {
310
- if (typeof dati.visibility !== "string" || !VISIBILITY.has(dati.visibility)) {
311
- errori.push("visibility: must be public or unlisted.");
312
- } else visibility = dati.visibility;
313
- }
314
- const network = [];
315
- if (dati.network !== void 0) {
316
- if (!Array.isArray(dati.network)) errori.push("network: must be an array of host names.");
317
- else for (const [indice, value] of dati.network.entries()) {
318
- if (typeof value !== "string" || !hostValido(value)) {
319
- errori.push(`network[${indice}]: must be a host name without scheme, port, path, query, or fragment.`);
320
- } else if (network.includes(value)) errori.push(`network[${indice}]: duplicate host ${value}.`);
321
- else network.push(value);
322
- }
323
- }
324
- let isolated = false;
325
- if (dati.isolated !== void 0) {
326
- if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
327
- else isolated = dati.isolated;
328
- }
329
- const requires = {
330
- webgl2: false,
331
- webgpu: false,
332
- wasm: false,
333
- threads: false,
334
- memoryMb: null,
335
- performance: "light"
336
- };
337
- if (dati.requires !== void 0) {
338
- const value = oggetto(dati.requires);
339
- if (value === null) errori.push("requires: must be an object.");
340
- else {
341
- for (const campo of Object.keys(value)) {
342
- if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {
343
- errori.push(`requires.${campo}: unknown field.`);
344
- }
345
- }
346
- for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
347
- if (value[campo] === void 0) continue;
348
- if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);
349
- else requires[campo] = value[campo];
350
- }
351
- if (value.memoryMb !== void 0) {
352
- if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {
353
- errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");
354
- } else requires.memoryMb = value.memoryMb;
355
- }
356
- if (value.performance !== void 0) {
357
- if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {
358
- errori.push("requires.performance: must be light, medium, or heavy.");
359
- } else requires.performance = value.performance;
360
- }
361
- if (requires.threads && !isolated) errori.push("requires.threads: needs isolated: true.");
362
- }
363
- }
364
- let players = { min: 1, max: 1 };
365
- if (dati.players !== void 0) {
366
- const value = oggetto(dati.players);
367
- if (value === null) errori.push("players: must be an object with min and max.");
368
- else {
369
- for (const campo of Object.keys(value)) {
370
- if (campo !== "min" && campo !== "max") errori.push(`players.${campo}: unknown field.`);
371
- }
372
- if (!interoTra(value.min, 1, TETTO_GIOCATORI)) errori.push(`players.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
373
- if (!interoTra(value.max, 1, TETTO_GIOCATORI)) errori.push(`players.max: must be an integer from 1 to ${TETTO_GIOCATORI} in manifest version 1.`);
374
- if (interoTra(value.min, 1, TETTO_GIOCATORI) && interoTra(value.max, 1, TETTO_GIOCATORI)) {
375
- if (value.min > value.max) errori.push("players.max: must be greater than or equal to players.min.");
376
- else players = { min: value.min, max: value.max };
377
- }
378
- }
379
- }
380
- let lobby = false;
381
- if (dati.lobby !== void 0) {
382
- if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");
383
- else lobby = dati.lobby;
384
- }
385
- let persistent = false;
386
- if (dati.persistent !== void 0) {
387
- if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
388
- else persistent = dati.persistent;
389
- }
390
- let spectators = { delayMs: RITARDO_SPETTATORI_MS };
391
- if (dati.spectators === false || dati.spectators === null) spectators = null;
392
- else if (dati.spectators !== void 0 && dati.spectators !== true) {
393
- const value = oggetto(dati.spectators);
394
- if (value === null) {
395
- errori.push("spectators: must be a boolean or an object with delayMs.");
396
- } else {
397
- for (const campo of Object.keys(value)) {
398
- if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);
399
- }
400
- if (!interoTra(value.delayMs, 0, 3e4)) {
401
- errori.push("spectators.delayMs: must be an integer from 0 to 30000.");
402
- } else spectators = { delayMs: value.delayMs };
403
- }
404
- }
405
- let overlay = null;
406
- if (dati.overlay !== void 0 && dati.overlay !== null) {
407
- const value = oggetto(dati.overlay);
408
- if (value === null) errori.push("overlay: must be an object or null.");
409
- else {
410
- for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);
411
- if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");
412
- if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {
413
- errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");
414
- }
415
- overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };
416
- }
417
- }
418
- const boards = {};
419
- if (dati.boards !== void 0) {
420
- const value = oggetto(dati.boards);
421
- if (value === null) errori.push("boards: must be an object of board ids.");
422
- else {
423
- if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {
424
- errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);
425
- }
426
- for (const [id2, raw] of Object.entries(value)) {
427
- let valido = true;
428
- if (!ID_CLASSIFICA.test(id2)) {
429
- errori.push(`boards.${id2}: invalid board id.`);
430
- valido = false;
431
- }
432
- const board = oggetto(raw);
433
- if (board === null) {
434
- errori.push(`boards.${id2}.source: must be "client" or "server".`);
435
- continue;
436
- }
437
- for (const campo of Object.keys(board)) {
438
- if (!["source", "label", "periods", "day"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
439
- }
440
- if (board.source !== "client" && board.source !== "server") {
441
- errori.push(`boards.${id2}.source: must be "client" or "server".`);
442
- valido = false;
443
- }
444
- if (board.day !== void 0 && board.day !== "submit" && board.day !== "start") errori.push(`boards.${id2}.day: must be "submit" or "start".`);
445
- if (board.day === "start" && board.source !== "server") errori.push(`boards.${id2}.day: start requires source "server".`);
446
- const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
447
- let periods = ["all-time"];
448
- if (board.periods !== void 0) {
449
- 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) {
450
- errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);
451
- } else periods = [...board.periods];
452
- }
453
- if (valido) Object.defineProperty(boards, id2, { value: {
454
- source: board.source,
455
- periods,
456
- ...board.day === void 0 ? {} : { day: board.day },
457
- ...label === void 0 ? {} : { label }
458
- }, enumerable: true, configurable: true, writable: true });
459
- }
460
- }
461
- }
462
- const roles = [];
463
- if (dati.roles !== void 0) {
464
- if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
465
- else {
466
- const ids = /* @__PURE__ */ new Set();
467
- for (const [indice, raw] of dati.roles.entries()) {
468
- const value = oggetto(raw);
469
- if (value === null) {
470
- errori.push(`roles[${indice}]: must be an object.`);
471
- continue;
472
- }
473
- for (const campo of Object.keys(value)) {
474
- if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
475
- }
476
- const idRuolo = value.id;
477
- const min = value.min;
478
- const max = value.max;
479
- let valido = true;
480
- if (typeof idRuolo !== "string" || idRuolo.length > 32 || !ID_INTERNO.test(idRuolo)) {
481
- errori.push(`roles[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
482
- valido = false;
483
- } else if (ids.has(idRuolo)) {
484
- errori.push(`roles[${indice}].id: duplicate role ${idRuolo}.`);
485
- valido = false;
486
- } else ids.add(idRuolo);
487
- if (!interoTra(min, 0, TETTO_GIOCATORI)) {
488
- errori.push(`roles[${indice}].min: must be an integer from 0 to ${TETTO_GIOCATORI}.`);
489
- valido = false;
490
- }
491
- if (max !== void 0 && !interoTra(max, 0, TETTO_GIOCATORI)) {
492
- errori.push(`roles[${indice}].max: must be an integer from 0 to ${TETTO_GIOCATORI} when present.`);
493
- valido = false;
494
- }
495
- if (typeof min === "number" && typeof max === "number" && min > max) {
496
- errori.push(`roles[${indice}].max: must be greater than or equal to min.`);
497
- valido = false;
498
- }
499
- const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);
500
- if (valido) roles.push({
501
- id: idRuolo,
502
- min,
503
- ...max === void 0 ? {} : { max },
504
- ...label === void 0 ? {} : { label }
505
- });
506
- }
507
- }
508
- }
509
- let teams = null;
510
- if (dati.teams !== void 0 && dati.teams !== null) {
511
- const value = oggetto(dati.teams);
512
- if (value === null) errori.push("teams: must be null or an object with min and max.");
513
- else {
514
- for (const campo of Object.keys(value)) {
515
- if (campo !== "min" && campo !== "max") errori.push(`teams.${campo}: unknown field.`);
516
- }
517
- if (!interoTra(value.min, 2, TETTO_GIOCATORI)) errori.push(`teams.min: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
518
- if (!interoTra(value.max, 2, TETTO_GIOCATORI)) errori.push(`teams.max: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
519
- if (interoTra(value.min, 2, TETTO_GIOCATORI) && interoTra(value.max, 2, TETTO_GIOCATORI)) {
520
- if (value.min > value.max) errori.push("teams.max: must be greater than or equal to teams.min.");
521
- else teams = { min: value.min, max: value.max };
522
- }
523
- }
524
- }
525
- let voice = "none";
526
- if (dati.voice !== void 0) {
527
- if (typeof dati.voice !== "string" || !VOICE.has(dati.voice)) {
528
- errori.push("voice: must be none, room, team, or proximity.");
529
- } else voice = dati.voice;
530
- }
531
- const modes = [];
532
- if (dati.modes !== void 0) {
533
- if (!Array.isArray(dati.modes)) errori.push("modes: must be an array.");
534
- else {
535
- const ids = /* @__PURE__ */ new Set();
536
- for (const [indice, raw] of dati.modes.entries()) {
537
- const value = oggetto(raw);
538
- if (value === null) {
539
- errori.push(`modes[${indice}]: must be an object.`);
540
- continue;
541
- }
542
- for (const campo of Object.keys(value)) {
543
- if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
544
- }
545
- if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
546
- errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
547
- continue;
548
- }
549
- if (ids.has(value.id)) {
550
- errori.push(`modes[${indice}].id: duplicate mode ${value.id}.`);
551
- continue;
552
- }
553
- ids.add(value.id);
554
- const modo = { id: value.id };
555
- for (const [key2, max] of [["label", 48], ["instructions", 160]]) {
556
- const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);
557
- if (text !== void 0) modo[key2] = text;
558
- }
559
- if (value.execution !== void 0) {
560
- if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);
561
- else modo.execution = value.execution;
562
- }
563
- if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);
564
- if (value.players !== void 0) {
565
- const campo = `modes[${indice}].players`;
566
- const range = oggetto(value.players);
567
- if (range === null) errori.push(`${campo}: must be an object with min and max.`);
568
- else {
569
- for (const key2 of Object.keys(range)) {
570
- if (key2 !== "min" && key2 !== "max") errori.push(`${campo}.${key2}: unknown field.`);
571
- }
572
- if (!interoTra(range.min, 1, TETTO_GIOCATORI)) errori.push(`${campo}.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
573
- if (!interoTra(range.max, 1, TETTO_GIOCATORI)) errori.push(`${campo}.max: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
574
- if (interoTra(range.min, 1, TETTO_GIOCATORI) && interoTra(range.max, 1, TETTO_GIOCATORI)) {
575
- if (range.min > range.max) errori.push(`${campo}.max: must be greater than or equal to min.`);
576
- else modo.players = { min: range.min, max: range.max };
577
- }
578
- }
579
- }
580
- if (value.lobby !== void 0) {
581
- if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);
582
- else modo.lobby = value.lobby;
583
- }
584
- if (modo.execution === "local") {
585
- const range = modo.players ?? players;
586
- if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);
587
- if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);
588
- if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);
589
- }
590
- if (value.matchmaking === void 0) {
591
- modes.push(modo);
592
- continue;
593
- }
594
- const matchmaking = oggetto(value.matchmaking);
595
- if (matchmaking === null) {
596
- errori.push(`modes[${indice}].matchmaking: must be an object.`);
597
- continue;
598
- }
599
- for (const campo of Object.keys(matchmaking)) {
600
- if (!["key", "timeoutMs", "defaults"].includes(campo)) {
601
- errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);
602
- }
603
- }
604
- let valido = true;
605
- const key = [];
606
- if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {
607
- errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);
608
- valido = false;
609
- } else for (const [keyIndice, item] of matchmaking.key.entries()) {
610
- if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {
611
- errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);
612
- valido = false;
613
- } else if (key.includes(item)) {
614
- errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);
615
- valido = false;
616
- } else key.push(item);
617
- }
618
- if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {
619
- errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);
620
- valido = false;
621
- }
622
- let defaults;
623
- if (matchmaking.defaults !== void 0) {
624
- const values = oggetto(matchmaking.defaults);
625
- if (values === null || Object.keys(values).length !== key.length || key.some((field) => !Object.hasOwn(values, field))) {
626
- errori.push(`modes[${indice}].matchmaking.defaults: must contain exactly the declared key fields.`);
627
- } else {
628
- defaults = {};
629
- for (const [field, value2] of Object.entries(values)) {
630
- if (!(typeof value2 === "string" && value2.length >= 1 && value2.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value2)) && !Number.isSafeInteger(value2)) {
631
- errori.push(`modes[${indice}].matchmaking.defaults.${field}: must be a string of 1-64 characters or a safe integer.`);
632
- } else Object.defineProperty(defaults, field, { value: value2, enumerable: true });
633
- }
634
- }
635
- }
636
- if (valido) modes.push({ ...modo, matchmaking: {
637
- ...defaults === void 0 ? {} : { defaults },
638
- key,
639
- timeoutMs: matchmaking.timeoutMs
640
- } });
641
- }
642
- }
643
- }
644
- if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");
645
- if (errori.length > 0) return { ok: false, errori };
646
- return { ok: true, manifest: {
647
- manifest: 1,
648
- overlay,
649
- id,
650
- name,
651
- description,
652
- cover,
653
- card,
654
- icon,
655
- screenshots,
656
- tags,
657
- languages: languages2,
658
- language,
659
- platform,
660
- orientation,
661
- input,
662
- visibility,
663
- network,
664
- isolated,
665
- requires,
666
- players,
667
- lobby,
668
- persistent,
669
- spectators,
670
- boards,
671
- roles,
672
- teams,
673
- voice,
674
- modes
675
- } };
676
- }
677
-
678
- // ../contracts/src/device.ts
679
- function deviceTier(report) {
680
- if (report.gpu !== "hardware" || report.memoryMb !== null && report.memoryMb <= 2048) return "low";
681
- if (report.mobile || report.memoryMb !== null && report.memoryMb <= 4096 || report.cores !== null && report.cores <= 4) return "mid";
682
- return "high";
683
- }
684
- function perdiContesto(context) {
685
- try {
686
- context?.getExtension("WEBGL_lose_context")?.loseContext();
687
- } catch {
688
- }
689
- }
690
- function valoriSincroni(ambiente) {
691
- let navigator2;
692
- try {
693
- navigator2 = ambiente.navigator;
694
- } catch {
695
- navigator2 = void 0;
696
- }
697
- let memoryMb = null;
698
- try {
699
- const memory = navigator2?.deviceMemory;
700
- const converted = typeof memory === "number" ? memory * 1024 : NaN;
701
- if (Number.isFinite(converted)) memoryMb = converted;
702
- } catch {
703
- memoryMb = null;
704
- }
705
- let cores = null;
706
- try {
707
- const value = navigator2?.hardwareConcurrency;
708
- if (typeof value === "number" && Number.isFinite(value)) cores = value;
709
- } catch {
710
- cores = null;
711
- }
712
- let mobile = false;
713
- try {
714
- mobile = typeof navigator2?.userAgentData?.mobile === "boolean" ? navigator2.userAgentData.mobile : /Android|iPhone|iPad|iPod|Mobile/i.test(navigator2?.userAgent ?? "");
715
- } catch {
716
- mobile = false;
717
- }
718
- let isolated = false;
719
- try {
720
- isolated = ambiente.crossOriginIsolated === true;
721
- } catch {
722
- isolated = false;
723
- }
724
- return {
725
- webgl2: false,
726
- webgpu: false,
727
- wasm: false,
728
- threads: false,
729
- isolated,
730
- gpu: "none",
731
- memoryMb,
732
- cores,
733
- mobile
734
- };
735
- }
736
- async function probeDevice(globals, timeoutMs = 1500) {
737
- const ambiente = globals ?? globalThis;
738
- const report = valoriSincroni(ambiente);
739
- const webgl = Promise.resolve().then(() => {
740
- try {
741
- const canvas = ambiente.document?.createElement("canvas");
742
- if (canvas === void 0) return;
743
- const hardware = canvas.getContext("webgl2", { failIfMajorPerformanceCaveat: true });
744
- if (hardware !== null) {
745
- report.webgl2 = true;
746
- report.gpu = "hardware";
747
- perdiContesto(hardware);
748
- return;
749
- }
750
- const software = canvas.getContext("webgl2");
751
- if (software !== null) {
752
- report.webgl2 = true;
753
- report.gpu = "software";
754
- perdiContesto(software);
755
- }
756
- } catch {
757
- report.webgl2 = false;
758
- report.gpu = "none";
759
- }
760
- });
761
- const webgpu = Promise.resolve().then(async () => {
762
- let device;
763
- try {
764
- const gpu = ambiente.navigator?.gpu;
765
- if (gpu === void 0) return;
766
- const adapter = await gpu.requestAdapter();
767
- if (adapter === null) return;
768
- device = await adapter.requestDevice();
769
- report.webgpu = true;
770
- } catch {
771
- report.webgpu = false;
772
- } finally {
773
- try {
774
- device?.destroy?.();
775
- } catch {
776
- }
777
- }
778
- });
779
- const wasm = Promise.resolve().then(() => {
780
- try {
781
- report.wasm = ambiente.WebAssembly?.validate(
782
- new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
783
- ) === true;
784
- } catch {
785
- report.wasm = false;
786
- }
787
- });
788
- const threads = Promise.resolve().then(() => {
789
- try {
790
- if (ambiente.WebAssembly === void 0) return;
791
- new ambiente.WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
792
- report.threads = true;
793
- } catch {
794
- report.threads = false;
795
- }
796
- });
797
- let timer;
798
- await Promise.race([
799
- Promise.all([webgl, webgpu, wasm, threads]),
800
- new Promise((resolve) => {
801
- timer = setTimeout(resolve, Math.max(0, timeoutMs));
802
- })
803
- ]);
804
- if (timer !== void 0) clearTimeout(timer);
805
- return { ...report, tier: deviceTier(report) };
806
- }
807
-
808
- // ../contracts/src/versioni.ts
809
- function numeroVersione(value) {
810
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
811
- }
812
-
813
- // ../contracts/src/overlay.ts
814
- function overlayConfiguration(manifest, coverUrl = null, invite = null, iconUrl = null) {
815
- const validated = validaManifest(manifest);
816
- if (!validated.ok) throw new Error("The overlay manifest is invalid.");
817
- return { manifest: validated.manifest, coverUrl, iconUrl, invite };
818
- }
819
- function record(value) {
820
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
821
- }
822
- function validOverlayHello(value) {
823
- const hello = record(value), config = record(hello?.configuration);
824
- 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.iconUrl === null || typeof config.iconUrl === "string") && (config.invite === null || typeof config.invite === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(config.invite)) && validaManifest(config.manifest).ok;
825
- }
826
- function normalizeOverlayHello(value) {
827
- if (!validOverlayHello(value)) return null;
828
- return { v: 1, epoch: value.epoch, configuration: overlayConfiguration(value.configuration.manifest, value.configuration.coverUrl, value.configuration.invite, value.configuration.iconUrl) };
829
- }
830
- function validSafeArea(value) {
831
- const area = record(value);
832
- 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);
833
- }
834
- function validOverlayView(value) {
835
- const data = record(value);
836
- 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) => {
837
- const rect = record(value2);
838
- 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);
839
- });
840
- }
841
- function validOverlayRequest(value) {
842
- const message = record(value), args = record(message?.args);
843
- 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;
844
- 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;
845
- const keys = (...allowed) => Object.keys(args).every((key) => allowed.includes(key));
846
- const text = (key) => typeof args[key] === "string" && args[key].length >= 1 && args[key].length <= 64;
847
- switch (message.op) {
848
- case "local.start":
849
- return keys("mode") && text("mode");
850
- case "room.create":
851
- return keys("mode") && (args.mode === null || text("mode"));
852
- case "room.join":
853
- return keys("code") && (args.code === void 0 || text("code"));
854
- case "room.watch":
855
- return keys("code") && text("code");
856
- case "room.match": {
857
- const key = record(args.key);
858
- 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)));
859
- }
860
- case "room.ready":
861
- return keys("ready") && typeof args.ready === "boolean";
862
- case "room.role":
863
- case "room.requestRole":
864
- return keys("role") && text("role");
865
- case "room.team":
866
- return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;
867
- case "room.restart":
868
- case "room.start":
869
- case "session.cancel":
870
- case "session.leave":
871
- case "session.disconnect":
872
- case "session.resume":
873
- return keys();
874
- case "voice.join":
875
- case "voice.leave":
876
- return keys() && typeof message.sessionId === "string";
877
- case "voice.mute":
878
- return keys("muted") && typeof args.muted === "boolean" && typeof message.sessionId === "string";
879
- case "voice.setVolume":
880
- 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;
881
- case "overlay.view":
882
- return validOverlayView(args);
883
- default:
884
- return false;
885
- }
886
- }
887
- function validBoardDay(value) {
888
- if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
889
- const at = Date.parse(`${value}T00:00:00Z`);
890
- return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
891
- }
892
-
893
- // ../contracts/src/room-limits.ts
894
- var MESSAGGI_GIOCO_AL_SECONDO = 20;
895
-
896
- // ../contracts/src/match-result.ts
897
- function readMatchResult(value, playerIds) {
898
- const object = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : null;
899
- const result = object(value);
900
- if (!result || !Array.isArray(result.standings)) return null;
901
- const known = new Set(playerIds), seen = /* @__PURE__ */ new Set();
902
- const standings = [];
903
- for (const item of result.standings) {
904
- const row = object(item);
905
- if (!row || typeof row.playerId !== "string" || !known.has(row.playerId) || seen.has(row.playerId)) continue;
906
- seen.add(row.playerId);
907
- standings.push({
908
- playerId: row.playerId,
909
- ...typeof row.score === "number" && Number.isFinite(row.score) ? { score: row.score } : {},
910
- ...typeof row.rank === "number" && Number.isSafeInteger(row.rank) && row.rank > 0 ? { rank: row.rank } : {}
911
- });
912
- }
913
- if (!standings.length) return null;
914
- return {
915
- standings,
916
- ...Array.isArray(result.winners) ? { winners: [...new Set(result.winners.filter((id) => typeof id === "string" && seen.has(id)))] } : {},
917
- ...typeof result.draw === "boolean" ? { draw: result.draw } : {},
918
- ...typeof result.unit === "string" ? { unit: result.unit } : {}
919
- };
920
- }
921
-
922
- // src/overlay/i18n.ts
923
- var languages = ["en", "it", "es", "fr", "de", "pt"];
924
- var words = {
925
- gameUpdated: ["This game was updated", "Questo gioco \xE8 stato aggiornato", "Este juego se ha actualizado", "Ce jeu a \xE9t\xE9 mis \xE0 jour", "Dieses Spiel wurde aktualisiert", "Este jogo foi atualizado"],
926
- reloadGame: ["Reload game", "Ricarica il gioco", "Recargar el juego", "Recharger le jeu", "Spiel neu laden", "Recarregar o jogo"],
927
- gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo"],
928
- loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando..."],
929
- 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."],
930
- home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
931
- homeMenu: ["Menu", "Menu", "Men\xFA", "Menu", "Men\xFC", "Menu"],
932
- mode: ["Mode", "Modalit\xE0", "Modo", "Mode", "Modus", "Modo"],
933
- play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
934
- friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos"],
935
- find: ["Find players", "Trova giocatori", "Buscar jugadores", "Trouver des joueurs", "Spieler finden", "Buscar jogadores"],
936
- join: ["Join with code", "Entra con codice", "Entrar con c\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\xF3digo"],
937
- joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\xE1 sala"],
938
- watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala"],
939
- resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar"],
940
- room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala"],
941
- code: ["Room code", "Codice stanza", "C\xF3digo de sala", "Code de salle", "Raumcode", "C\xF3digo da sala"],
942
- copy: ["Copy invite", "Copia invito", "Copiar invitaci\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite"],
943
- copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\xE9", "Einladung kopiert", "Convite copiado"],
944
- copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:"],
945
- joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \xE0 la salle...", "Raum wird betreten...", "Entrando na sala..."],
946
- matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores..."],
947
- queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores"],
948
- cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar"],
949
- close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\xDFen", "Fechar"],
950
- back: ["Back", "Indietro", "Volver", "Retour", "Zur\xFCck", "Voltar"],
951
- ready: ["Ready", "Pronto", "Listo", "Pr\xEAt", "Bereit", "Pronto"],
952
- unready: ["Not ready", "Non pronto", "No listo", "Pas pr\xEAt", "Nicht bereit", "N\xE3o pronto"],
953
- start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\xE7ar"],
954
- role: ["Role", "Ruolo", "Rol", "R\xF4le", "Rolle", "Fun\xE7\xE3o"],
955
- team: ["Team", "Squadra", "Equipo", "\xC9quipe", "Team", "Equipe"],
956
- host: ["Host", "Host", "Anfitrion", "H\xF4te", "Host", "Anfitri\xE3o"],
957
- you: ["You", "Tu", "T\xFA", "Vous", "Du", "Voc\xEA"],
958
- away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente"],
959
- needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores"],
960
- 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"],
961
- 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"],
962
- needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \xE9quipes", "Teams auswahlen", "Escolha as equipes"],
963
- 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"],
964
- starting: ["Starting in", "Si inizia tra", "Empieza en", "D\xE9but dans", "Start in", "Come\xE7a em"],
965
- playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando"],
966
- ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada"],
967
- rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos"],
968
- rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche"],
969
- won: ["You won", "Hai vinto", "Has ganado", "Vous avez gagn\xE9", "Du hast gewonnen", "Voc\xEA venceu"],
970
- lost: ["You lost", "Hai perso", "Has perdido", "Vous avez perdu", "Du hast verloren", "Voc\xEA perdeu"],
971
- draw: ["Draw", "Pareggio", "Empate", "\xC9galit\xE9", "Unentschieden", "Empate"],
972
- standings: ["Standings", "Piazzamenti", "Posiciones", "R\xE9sultats", "Platzierungen", "Coloca\xE7\xF5es"],
973
- points: ["points", "punti", "puntos", "points", "Punkte", "pontos"],
974
- time: ["time", "tempo", "tiempo", "temps", "Zeit", "tempo"],
975
- distance: ["distance", "distanza", "distancia", "distance", "Distanz", "dist\xE2ncia"],
976
- again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente"],
977
- 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."],
978
- watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo"],
979
- delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\xF6gerung", "Atraso de {n}s"],
980
- exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair"],
981
- leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\xFCbergehend verlassen", "Sair por enquanto"],
982
- leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala"],
983
- 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."],
984
- 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."],
985
- 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."],
986
- reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando..."],
987
- 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"],
988
- 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."],
989
- 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."],
990
- 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."],
991
- 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."],
992
- 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."],
993
- 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."],
994
- unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\xFCgbar", "Indisponivel agora"],
995
- 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."],
996
- 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."],
997
- boards: ["Leaderboard", "Classifica", "Clasificaci\xF3n", "Classement", "Bestenliste", "Classifica\xE7\xE3o"],
998
- board: ["Board", "Classifica", "Tabla", "Classement", "Bestenliste", "Tabela"],
999
- daily: ["Daily", "Giornaliera", "Diaria", "Du jour", "T\xE4glich", "Di\xE1ria"],
1000
- allTime: ["All time", "Di sempre", "Hist\xF3rica", "Tous les temps", "Gesamt", "Geral"],
1001
- accounts: ["Accounts", "Account", "Cuentas", "Comptes", "Konten", "Contas"],
1002
- guests: ["Guests", "Ospiti", "Invitados", "Invit\xE9s", "G\xE4ste", "Visitantes"],
1003
- category: ["Category", "Categoria", "Categoria", "Cat\xE9gorie", "Kategorie", "Categoria"],
1004
- period: ["Period", "Periodo", "Per\xEDodo", "P\xE9riode", "Zeitraum", "Per\xEDodo"],
1005
- rank: ["Rank", "Posizione", "Puesto", "Rang", "Platz", "Posicao"],
1006
- score: ["Score", "Punteggio", "Puntos", "Score", "Punkte", "Pontos"],
1007
- verified: ["Verified", "Verificato", "Verificado", "V\xE9rifi\xE9", "Verifiziert", "Verificado"],
1008
- own: ["Your best", "Il tuo record", "Tu record", "Votre record", "Dein Rekord", "Seu recorde"],
1009
- empty: ["No scores yet", "Nessun punteggio", "A\xFAn no hay puntos", "Aucun score", "Noch keine Punkte", "Ainda sem pontos"],
1010
- saving: ["Saving score...", "Salvataggio punteggio...", "Guardando puntos...", "Enregistrement du score...", "Punkte werden gespeichert...", "Salvando pontos..."],
1011
- 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"],
1012
- 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"],
1013
- refresh: ["Refresh", "Aggiorna", "Actualizar", "Actualiser", "Aktualisieren", "Atualizar"],
1014
- 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."],
1015
- friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo"],
1016
- 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."],
1017
- 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."],
1018
- online: ["Online", "Online", "En linea", "En ligne", "Online", "Online"],
1019
- noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online"],
1020
- createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\xE9er un groupe", "Gruppe erstellen", "Criar grupo"],
1021
- inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo"],
1022
- leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo"],
1023
- accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar"],
1024
- decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar"],
1025
- follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se"],
1026
- voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz"],
1027
- voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz"],
1028
- voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz"],
1029
- voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar"],
1030
- voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone"],
1031
- voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\xE9sactiv\xE9e", "Sprachchat aus", "Voz desativada"],
1032
- voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz..."],
1033
- voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\xE9e", "Sprachchat verbunden", "Voz conectada"],
1034
- voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\xE9", "Stumm", "Silenciado"],
1035
- voiceMic: ["Mic on", "Microfono attivo", "Micr\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo"],
1036
- voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\xC9coute seule", "Nur zuh\xF6ren", "Somente ouvindo"],
1037
- voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando"],
1038
- voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz"],
1039
- 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."],
1040
- voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\xE4rke f\xFCr {name}", "Volume de {name}"],
1041
- 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."],
1042
- 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."],
1043
- 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."],
1044
- 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."],
1045
- 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."],
1046
- 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."],
1047
- shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab"],
1048
- menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual"],
1049
- retry: ["Retry", "Riprova", "Reintentar", "R\xE9essayer", "Erneut versuchen", "Tentar novamente"]
1050
- };
1051
- var column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));
1052
- var dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5) };
1053
- function overlayLocale(raw) {
1054
- const tag = normalizeLanguage(raw);
1055
- return tag && languages.includes(tag.split("-")[0]) ? tag : "en";
1056
- }
1057
-
1058
- // src/text.ts
1059
- function createTextLoader(fetcher, language, pathname = "/") {
1060
- let pending;
1061
- const root = pathname.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0] ?? "/";
1062
- return () => pending ?? (pending = (async () => {
1063
- let dictionary = {};
1064
- try {
1065
- const response = await fetcher(`${root}__caisual/text/${encodeURIComponent(language)}.json`);
1066
- if (response.ok) {
1067
- const value = await response.json();
1068
- if (isTextDictionary(value)) dictionary = value;
1069
- }
1070
- } catch {
1071
- }
1072
- return (key, values = {}) => {
1073
- if (!Object.hasOwn(dictionary, key)) return key;
1074
- const text = dictionary[key];
1075
- return text.replace(/\{([^{}]+)\}/g, (placeholder, name) => Object.hasOwn(values, name) ? String(values[name]) : placeholder);
1076
- };
1077
- })());
1078
- }
1079
-
1080
- // src/errors.ts
1081
- function creaErrore(code, message, version = {}) {
1082
- return Object.assign(new Error(message), { name: "CaisualError", code, ...version });
1083
- }
1084
- function erroreOffline() {
1085
- return creaErrore("offline", "Caisual services are unavailable.");
1086
- }
1087
- function codiceErrore(valore) {
1088
- return typeof valore === "object" && valore !== null && "code" in valore ? valore.code : null;
1089
- }
1090
-
1091
- // src/session/resume.ts
1092
- var KEY = "caisual-session-v1";
1093
- function resume(value) {
1094
- const data = record(value);
1095
- if (!data || typeof data.code !== "string" || !/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(data.code) || !(data.mode === void 0 || data.mode === null || typeof data.mode === "string")) return null;
1096
- return {
1097
- version: 1,
1098
- code: data.code,
1099
- mode: typeof data.mode === "string" ? data.mode : null,
1100
- updatedAt: typeof data.updatedAt === "number" && Number.isFinite(data.updatedAt) ? data.updatedAt : 0
1101
- };
1102
- }
1103
- function createResume(save, changed) {
1104
- let current = null, error = false, work = Promise.resolve();
1105
- const write = async () => {
1106
- const value = { version: 1, imported: true, resume: current };
1107
- work = work.catch(() => void 0).then(async () => {
1108
- try {
1109
- await save.set(KEY, value);
1110
- error = false;
1111
- } catch (cause) {
1112
- error = true;
1113
- throw cause;
1114
- } finally {
1115
- changed();
1116
- }
1117
- });
1118
- return work;
1119
- };
1120
- const loaded = (async () => {
1121
- try {
1122
- const data = record(await save.get(KEY));
1123
- if (data?.version === 1 && data.imported === true) current = resume(data.resume);
1124
- else {
1125
- current = resume(await save.get("resume"));
1126
- await write();
1127
- }
1128
- } catch {
1129
- error = true;
1130
- }
1131
- changed();
1132
- })();
1133
- return {
1134
- loaded,
1135
- get value() {
1136
- return current === null ? null : { ...current };
1137
- },
1138
- get error() {
1139
- return error;
1140
- },
1141
- async set(value) {
1142
- await loaded;
1143
- current = value;
1144
- changed();
1145
- await write();
1146
- }
1147
- };
1148
- }
1149
-
1150
- // src/session/index.ts
1151
- function notify(listeners, value) {
1152
- for (const listener of listeners) {
1153
- try {
1154
- listener(value);
1155
- } catch {
1156
- }
1157
- }
1158
- }
1159
- function createSession(base, configuration = null, roomsAvailable = base.connected) {
1160
- const standard = configuration?.manifest.overlay?.version === 1;
1161
- const manifest = configuration?.manifest;
1162
- let current = { kind: "idle" }, ready = false, operation = 0, identifier = 0;
1163
- let pending = null, pendingMode = null;
1164
- let waiting = null, controller = null;
1165
- let stops = [], disposed = false, lastState = "";
1166
- let view = { inputBlocked: standard, reservedRects: [], safeArea: { top: 0, right: 0, bottom: 0, left: 0 } };
1167
- const listeners = /* @__PURE__ */ new Set();
1168
- const viewListeners = /* @__PURE__ */ new Set();
1169
- const stateListeners = /* @__PURE__ */ new Set();
1170
- const openListeners = /* @__PURE__ */ new Set();
1171
- const errorListeners = /* @__PURE__ */ new Set();
1172
- const scoreListeners = /* @__PURE__ */ new Set();
1173
- let resumeStore = null;
1174
- const capabilities = () => ({
1175
- local: true,
1176
- rooms: roomsAvailable,
1177
- overlay: standard,
1178
- requestRole: current.kind === "room" && current.room.metadata.configuration?.requestRole === true
1179
- });
1180
- function voiceSnapshot() {
1181
- if (current.kind !== "room" || !manifest || manifest.voice === "none") return null;
1182
- const room = current.room, voice = room.voice;
1183
- if (!voice || voice.mode === "none" || room.players.find((p) => p.id === room.you)?.role === "spectator") return null;
1184
- return {
1185
- mode: voice.mode,
1186
- state: voice.state,
1187
- mic: voice.mic,
1188
- muted: voice.muted,
1189
- speaking: voice.speaking,
1190
- peers: voice.peers.map(({ id, mic, muted, speaking, volume }) => ({ id, mic, muted, speaking, volume }))
1191
- };
1192
- }
1193
- function snapshot() {
1194
- const attached = current.kind === "room" || current.kind === "watch" ? current.room : null;
1195
- const configured = attached?.metadata.configuration;
1196
- const result = attached ? readMatchResult(attached.result, attached.players.map((p) => p.id)) : null;
1197
- 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 };
1198
- return {
1199
- kind: pending ?? (current.kind === "idle" ? ready ? "home" : "boot" : current.kind),
1200
- id: current.kind === "idle" ? null : current.id,
1201
- mode: pending ? pendingMode : current.kind === "local" ? current.mode : attached?.mode ?? null,
1202
- localStatus: current.kind === "local" ? current.status : null,
1203
- ready,
1204
- capabilities: capabilities(),
1205
- room: attached ? {
1206
- ...attached.metadata.rematch?.keepSetup || attached.metadata.rematch?.autoStart ? { rematch: attached.metadata.rematch } : {},
1207
- code: attached.code,
1208
- mode: attached.mode,
1209
- status: attached.status,
1210
- host: attached.host,
1211
- you: current.kind === "room" ? current.room.you : null,
1212
- 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 })),
1213
- ...result ? { result } : {},
1214
- countdownAt: attached.countdownAt,
1215
- connection: attached.connection,
1216
- closedCode: attached.metadata.closedCode,
1217
- limits: { ...configured?.players ?? fallback.players },
1218
- lobby: configured?.lobby ?? fallback.lobby,
1219
- persistent: configured?.persistent ?? manifest?.persistent ?? false,
1220
- delayMs: current.kind === "watch" ? current.room.delayMs : null,
1221
- requestRole: configured?.requestRole ?? false
1222
- } : null,
1223
- voice: pending ? null : voiceSnapshot(),
1224
- waiting: waiting ? { ...waiting } : null,
1225
- resume: resumeStore?.value ?? null,
1226
- resumeError: resumeStore?.error ?? false
1227
- };
1228
- }
1229
- function emit() {
1230
- if (disposed) return;
1231
- const state = snapshot(), serialized = JSON.stringify(state);
1232
- if (serialized === lastState) return;
1233
- lastState = serialized;
1234
- notify(stateListeners, state);
1235
- }
1236
- function changed() {
1237
- notify(listeners, { ...current });
1238
- emit();
1239
- }
1240
- function active() {
1241
- if (current.kind !== "room") throw creaErrore("no_room", "There is no active player room.");
1242
- return current.room;
1243
- }
1244
- function activeVoice() {
1245
- const room = active();
1246
- if (room.players.find((p) => p.id === room.you)?.role === "spectator") throw creaErrore("spectator", "Spectators cannot use voice controls.");
1247
- if (!manifest || manifest.voice === "none" || room.voice.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
1248
- return room.voice;
1249
- }
1250
- function cancel() {
1251
- operation++;
1252
- controller?.abort();
1253
- controller = null;
1254
- pending = null;
1255
- waiting = null;
1256
- emit();
1257
- }
1258
- function detach(preserve) {
1259
- stops.splice(0).forEach((stop) => stop());
1260
- if (current.kind === "room" || current.kind === "watch") {
1261
- if (preserve) current.room.disconnect();
1262
- else current.room.leave();
1263
- }
1264
- current = { kind: "idle" };
1265
- changed();
1266
- }
1267
- async function clearResume(code) {
1268
- if (resumeStore?.value?.code === code) await resumeStore.set(null).catch(() => void 0);
1269
- }
1270
- async function adopt(next, watch, token) {
1271
- if (token !== operation || disposed) {
1272
- next.leave();
1273
- throw creaErrore("cancelled", "The operation was cancelled.");
1274
- }
1275
- detach(false);
1276
- current = watch ? { kind: "watch", room: next, id: String(++identifier) } : { kind: "room", room: next, id: String(++identifier) };
1277
- const room = next;
1278
- stops = [room.onPlayers(emit), room.onMetadata(() => {
1279
- if (room.connection === "disconnected" && (current.kind === "room" || current.kind === "watch") && current.room === room) {
1280
- stops.splice(0).forEach((stop) => stop());
1281
- if (!watch && room.metadata.closedCode === 1e3) void clearResume(room.code);
1282
- current = { kind: "idle" };
1283
- changed();
1284
- } else emit();
1285
- }), room.onStatus(() => {
1286
- emit();
1287
- if (!watch && room.connection === "ended") void clearResume(room.code);
1288
- })];
1289
- if (!watch) {
1290
- const playerRoom = next;
1291
- const sessionId = current.id;
1292
- if (playerRoom.voice) stops.push(playerRoom.voice.onState(emit), playerRoom.voice.onPeers(emit));
1293
- stops.push(playerRoom.onError((error) => notify(errorListeners, { sessionId, error: { ...error } })));
1294
- stops.push(playerRoom.onScoreQueued((score) => notify(scoreListeners, { ...score })));
1295
- for (const score of playerRoom.queuedScores) notify(scoreListeners, { ...score });
1296
- }
1297
- pending = null;
1298
- waiting = null;
1299
- changed();
1300
- if (!watch && resumeStore && room.connection !== "ended") {
1301
- await resumeStore.set({ version: 1, code: room.code, mode: room.mode, updatedAt: base.time.now() }).catch(() => void 0);
1302
- }
1303
- return next;
1304
- }
1305
- async function run(kind, mode, work, watch = false) {
1306
- cancel();
1307
- const token = operation;
1308
- controller = new AbortController();
1309
- pending = kind;
1310
- pendingMode = mode;
1311
- emit();
1312
- try {
1313
- const next = await work(controller.signal, token);
1314
- await adopt(next, watch, token);
1315
- if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1316
- return next;
1317
- } finally {
1318
- if (token === operation) {
1319
- pending = null;
1320
- waiting = null;
1321
- controller = null;
1322
- emit();
1323
- }
1324
- }
1325
- }
1326
- const direct = base.room;
1327
- const stopVersionErrors = direct.onError((error) => {
1328
- if (!standard || disposed) return;
1329
- if (error.code === "version_mismatch") direct.reload();
1330
- else if (error.code === "version_outdated") notify(errorListeners, { sessionId: current.kind === "idle" ? null : current.id, error });
1331
- });
1332
- const rooms = !standard ? direct : {
1333
- invited: direct.invited,
1334
- reload: () => direct.reload(),
1335
- onError: (listener) => direct.onError(listener),
1336
- create(options) {
1337
- if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot create rooms."));
1338
- return run("attaching", options.mode, () => direct.create(options));
1339
- },
1340
- join(code) {
1341
- return run("attaching", null, () => direct.join(code));
1342
- },
1343
- watch(code) {
1344
- return run("attaching", null, () => direct.watch(code), true);
1345
- },
1346
- match(options) {
1347
- if (manifest && modalitaLocale(manifest, options.mode)) return Promise.reject(creaErrore("invalid_request", "Local modes cannot use matchmaking."));
1348
- return run("matching", options.mode, (signal, token) => {
1349
- const abort = () => {
1350
- if (operation === token) cancel();
1351
- };
1352
- options.signal?.addEventListener("abort", abort, { once: true });
1353
- if (options.signal?.aborted) abort();
1354
- return direct.match({ ...options, signal, onWaiting(value) {
1355
- if (token !== operation) return;
1356
- waiting = { ...value };
1357
- emit();
1358
- options.onWaiting?.(value);
1359
- } }).finally(() => options.signal?.removeEventListener("abort", abort));
1360
- });
1361
- }
1362
- };
1363
- if (standard) resumeStore = createResume(base.save, emit);
1364
- const session = {
1365
- get current() {
1366
- return { ...current };
1367
- },
1368
- get capabilities() {
1369
- return capabilities();
1370
- },
1371
- onChange(listener) {
1372
- listeners.add(listener);
1373
- notify(/* @__PURE__ */ new Set([listener]), { ...current });
1374
- return () => {
1375
- listeners.delete(listener);
1376
- };
1377
- },
1378
- ready() {
1379
- if (disposed || ready) return;
1380
- ready = true;
1381
- emit();
1382
- },
1383
- finish() {
1384
- if (current.kind === "room" || current.kind === "watch") throw creaErrore("not_local", "Only a local session can be finished by the client.");
1385
- if (current.kind === "local") {
1386
- current = { ...current, status: "ended" };
1387
- changed();
1388
- }
1389
- }
1390
- };
1391
- const overlay = {
1392
- open(panel) {
1393
- if (!["home", "room", "invite", "friends", "voice", "boards"].includes(panel)) throw creaErrore("invalid_request", "Unknown overlay panel.");
1394
- if (standard) notify(openListeners, panel);
1395
- },
1396
- onChange(listener) {
1397
- viewListeners.add(listener);
1398
- notify(/* @__PURE__ */ new Set([listener]), structuredClone(view));
1399
- return () => {
1400
- viewListeners.delete(listener);
1401
- };
1402
- }
1403
- };
1404
- return {
1405
- session,
1406
- overlay,
1407
- rooms,
1408
- snapshot,
1409
- serverTime: () => current.kind === "room" || current.kind === "watch" ? current.room.serverTime() : base.time.now(),
1410
- onState(listener) {
1411
- stateListeners.add(listener);
1412
- listener(snapshot());
1413
- return () => {
1414
- stateListeners.delete(listener);
1415
- };
1416
- },
1417
- onOpen(listener) {
1418
- openListeners.add(listener);
1419
- return () => {
1420
- openListeners.delete(listener);
1421
- };
1422
- },
1423
- onError(listener) {
1424
- errorListeners.add(listener);
1425
- return () => {
1426
- errorListeners.delete(listener);
1427
- };
1428
- },
1429
- onScore(listener) {
1430
- scoreListeners.add(listener);
1431
- return () => {
1432
- scoreListeners.delete(listener);
1433
- };
1434
- },
1435
- async execute(request) {
1436
- if (!standard) throw creaErrore("overlay_disabled", "This game uses its own room flow.");
1437
- if (request.op === "overlay.view") {
1438
- if (!validOverlayView(request.args)) throw creaErrore("invalid_request", "The overlay geometry is invalid.");
1439
- view = { ...structuredClone(request.args), safeArea: { top: 0, right: 0, bottom: 0, left: 0, ...request.args.safeArea } };
1440
- if (typeof document !== "undefined") for (const [side, value] of Object.entries(view.safeArea)) {
1441
- document.documentElement.style.setProperty(`--caisual-safe-${side}`, `${value}px`);
1442
- }
1443
- notify(viewListeners, structuredClone(view));
1444
- return;
1445
- }
1446
- if (request.sessionId !== void 0 && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1447
- if (request.op.startsWith("voice.") && request.sessionId !== (current.kind === "idle" ? null : current.id)) throw creaErrore("session_replaced", "The active session changed.");
1448
- if (!ready) throw creaErrore("game_not_ready", "The game is still loading.");
1449
- switch (request.op) {
1450
- case "local.start": {
1451
- if (!manifest || !modalitaLocale(manifest, request.args.mode)) throw creaErrore("invalid_mode", "This is not a local mode.");
1452
- cancel();
1453
- const token = operation;
1454
- if (current.kind === "room") await clearResume(current.room.code);
1455
- if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1456
- detach(false);
1457
- current = { kind: "local", id: String(++identifier), mode: request.args.mode, status: "playing" };
1458
- changed();
1459
- return;
1460
- }
1461
- case "room.create":
1462
- await rooms.create(request.args);
1463
- return;
1464
- case "room.join":
1465
- await rooms.join(request.args.code);
1466
- return;
1467
- case "room.watch":
1468
- await rooms.watch(request.args.code);
1469
- return;
1470
- case "room.match": {
1471
- const mode = manifest?.modes.find((m) => m.id === request.args.mode);
1472
- const key = request.args.key ?? mode?.matchmaking?.defaults;
1473
- if (!key) throw creaErrore("invalid_request", "Matchmaking needs a complete key.");
1474
- await rooms.match({ mode: request.args.mode, key });
1475
- return;
1476
- }
1477
- case "voice.join": {
1478
- const room = active(), voice = activeVoice();
1479
- await voice.join();
1480
- if (current.kind !== "room" || current.room !== room) throw creaErrore("session_replaced", "The active session changed.");
1481
- emit();
1482
- return;
1483
- }
1484
- case "voice.mute":
1485
- activeVoice().mute(request.args.muted);
1486
- emit();
1487
- return;
1488
- case "voice.leave":
1489
- activeVoice().leave();
1490
- emit();
1491
- return;
1492
- case "voice.setVolume": {
1493
- const voice = activeVoice();
1494
- if (!voice.peers.some((peer) => peer.id === request.args.playerId)) throw creaErrore("voice_peer_missing", "This voice participant is no longer available.");
1495
- voice.setVolume(request.args.playerId, request.args.volume);
1496
- emit();
1497
- return;
1498
- }
1499
- case "room.ready":
1500
- active().ready(request.args.ready);
1501
- return;
1502
- case "room.role":
1503
- active().setRole(request.args.role);
1504
- return;
1505
- case "room.requestRole":
1506
- await active().requestRole(request.args.role);
1507
- return;
1508
- case "room.team":
1509
- active().setTeam(request.args.team);
1510
- return;
1511
- case "room.start":
1512
- active().start();
1513
- return;
1514
- case "room.restart":
1515
- active().restart();
1516
- return;
1517
- case "session.cancel":
1518
- cancel();
1519
- return;
1520
- case "session.resume": {
1521
- await run("attaching", null, async (signal) => {
1522
- await resumeStore?.loaded;
1523
- if (signal.aborted) throw creaErrore("cancelled", "The operation was cancelled.");
1524
- if (!resumeStore?.value) throw creaErrore("no_resume", "There is no saved room.");
1525
- return direct.join(resumeStore.value.code);
1526
- });
1527
- return;
1528
- }
1529
- case "session.disconnect": {
1530
- cancel();
1531
- const token = operation;
1532
- 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() });
1533
- if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1534
- detach(true);
1535
- return;
1536
- }
1537
- case "session.leave": {
1538
- cancel();
1539
- const token = operation;
1540
- if (current.kind === "room") await clearResume(current.room.code);
1541
- if (token !== operation || disposed) throw creaErrore("cancelled", "The operation was cancelled.");
1542
- detach(false);
1543
- return;
1544
- }
1545
- }
1546
- },
1547
- dispose() {
1548
- stopVersionErrors();
1549
- cancel();
1550
- detach(true);
1551
- disposed = true;
1552
- listeners.clear();
1553
- viewListeners.clear();
1554
- stateListeners.clear();
1555
- openListeners.clear();
1556
- scoreListeners.clear();
1557
- errorListeners.clear();
1558
- }
1559
- };
1560
- }
1561
-
1562
- // src/overlay/shortcut.ts
1563
- function bindOverlayShortcut(target, overlay, open) {
1564
- let enabled = true, blocked = false;
1565
- const stop = overlay.onChange((view) => {
1566
- enabled = view.shortcutEnabled !== false;
1567
- blocked = view.inputBlocked;
1568
- });
1569
- const listener = (event) => {
1570
- const element = event.target;
1571
- if (!enabled || blocked || event.repeat || event.key !== "Tab" || !event.shiftKey || event.ctrlKey || event.altKey || event.metaKey || element?.closest?.('input,textarea,select,[contenteditable="true"]')) return;
1572
- event.preventDefault();
1573
- event.stopImmediatePropagation();
1574
- open();
1575
- };
1576
- target.addEventListener("keydown", listener, true);
1577
- return () => {
1578
- stop();
1579
- target.removeEventListener("keydown", listener, true);
1580
- };
1581
- }
1582
-
1583
- // src/overlay/bridge.ts
1584
- function attachKitBridge(port, hello, coordinator) {
1585
- let disposed = false, seq = 0, highestRequest = 0, activeRequests = 0;
1586
- const replies = /* @__PURE__ */ new Map();
1587
- const send = (message) => {
1588
- if (!disposed) try {
1589
- port.postMessage(message);
1590
- } catch {
1591
- }
1592
- };
1593
- const stops = [
1594
- ...hello.configuration.manifest.overlay && typeof window !== "undefined" ? [bindOverlayShortcut(window, coordinator.overlay, () => send({ type: "caisual:overlay-shortcut", v: 1, epoch: hello.epoch }))] : [],
1595
- coordinator.onState((state) => send({ type: "caisual:overlay-state", v: 1, epoch: hello.epoch, seq: ++seq, serverTime: coordinator.serverTime(), state })),
1596
- coordinator.onOpen((panel) => send({ type: "caisual:overlay-open", v: 1, epoch: hello.epoch, panel })),
1597
- coordinator.onError(({ sessionId, error }) => send({ type: "caisual:overlay-error", v: 1, epoch: hello.epoch, sessionId, error })),
1598
- coordinator.onScore((score) => send({ type: "caisual:overlay-score", v: 1, epoch: hello.epoch, score }))
1599
- ];
1600
- const listener = (event) => {
1601
- const raw = record(event.data);
1602
- if (raw?.type !== "caisual:overlay" || raw.epoch !== hello.epoch || disposed) return;
1603
- const reply = { type: "caisual:overlay-response", v: 1, epoch: hello.epoch, requestId: typeof raw.requestId === "string" ? raw.requestId : "" };
1604
- if (!validOverlayRequest(raw)) {
1605
- send({ ...reply, ok: false, error: { code: "invalid_request", message: "The overlay request is invalid." } });
1606
- return;
1607
- }
1608
- const fingerprint = JSON.stringify([raw.op, raw.args, raw.sessionId]);
1609
- const previous = replies.get(raw.requestId);
1610
- if (previous) {
1611
- if (previous.fingerprint !== fingerprint) send({ ...reply, ok: false, error: { code: "duplicate_request", message: "The request id was already used." } });
1612
- else void previous.response.then(send);
1613
- return;
1614
- }
1615
- if (Number(raw.requestId) <= highestRequest || activeRequests >= 32) {
1616
- send({ ...reply, ok: false, error: { code: "stale_request", message: "The request is stale or too many requests are pending." } });
1617
- return;
1618
- }
1619
- highestRequest = Number(raw.requestId);
1620
- activeRequests++;
1621
- const response = Promise.resolve().then(() => coordinator.execute(raw)).then(
1622
- () => ({ ...reply, ok: true }),
1623
- (error) => ({ ...reply, ok: false, error: {
1624
- code: typeof record(error)?.code === "string" ? record(error).code : "internal_error",
1625
- message: error instanceof Error ? error.message : "The operation could not be completed."
1626
- } })
1627
- );
1628
- replies.set(raw.requestId, { fingerprint, response });
1629
- void response.then((value) => {
1630
- activeRequests--;
1631
- send(value);
1632
- if (replies.size > 64) for (const id of replies.keys()) {
1633
- if (Number(id) < highestRequest - 64) replies.delete(id);
1634
- }
1635
- });
1636
- };
1637
- port.addEventListener("message", listener);
1638
- port.start();
1639
- return () => {
1640
- disposed = true;
1641
- port.removeEventListener("message", listener);
1642
- stops.forEach((stop) => stop());
1643
- coordinator.dispose();
1644
- replies.clear();
1645
- };
1646
- }
1647
-
1648
- // src/http.ts
1649
- async function leggiErrore(response) {
1650
- let corpo = {};
1651
- try {
1652
- corpo = await response.json();
1653
- } catch {
1654
- }
1655
- return creaErrore(
1656
- typeof corpo.error?.code === "string" ? corpo.error.code : response.status === 401 ? "invalid_ticket" : "internal_error",
1657
- typeof corpo.error?.message === "string" ? corpo.error.message : `The request failed with status ${response.status}.`,
1658
- { currentVersion: corpo.error?.currentVersion, roomVersion: corpo.error?.roomVersion }
1659
- );
1660
- }
1661
- function creaRichiedente(origin, prefix, fetcher, biglietto) {
1662
- async function manda(path, metodo, ticket, corpo) {
1663
- const headers = new Headers({ Authorization: `Bearer ${ticket}` });
1664
- let body;
1665
- if (corpo !== void 0) {
1666
- headers.set("Content-Type", "application/json");
1667
- try {
1668
- body = JSON.stringify(corpo);
1669
- } catch {
1670
- throw creaErrore("invalid_request", "The value must be valid JSON.");
1671
- }
1672
- }
1673
- try {
1674
- return await fetcher(new URL(prefix + path, origin), {
1675
- method: metodo,
1676
- headers,
1677
- body,
1678
- credentials: "omit"
1679
- });
1680
- } catch {
1681
- throw erroreOffline();
1682
- }
1683
- }
1684
- return async function richiesta(path, metodo, corpo, forzaRinnovo = false) {
1685
- let ticket;
1686
- try {
1687
- ticket = forzaRinnovo ? await biglietto.rinnova() : await biglietto.ottieni();
1688
- } catch {
1689
- throw erroreOffline();
1690
- }
1691
- let response = await manda(path, metodo, ticket, corpo);
1692
- if (response.status === 401) {
1693
- try {
1694
- ticket = await biglietto.rinnova();
1695
- } catch {
1696
- throw erroreOffline();
1697
- }
1698
- response = await manda(path, metodo, ticket, corpo);
1699
- }
1700
- if (!response.ok) throw await leggiErrore(response);
1701
- try {
1702
- return await response.json();
1703
- } catch {
1704
- throw creaErrore("internal_error", "The service returned an invalid response.");
1705
- }
1706
- };
1707
- }
1708
-
1709
- // src/api.ts
1710
- function creaClienteApi(appOrigin, fetcher, biglietto) {
1711
- const richiesta = creaRichiedente(appOrigin, "/api/kit", fetcher, biglietto);
1712
- return {
1713
- me: () => richiesta("/me", "GET"),
1714
- saveSet: (key, value) => richiesta(`/saves/${encodeURIComponent(key)}`, "PUT", { value }),
1715
- async saveGet(key) {
1716
- try {
1717
- return (await richiesta(`/saves/${encodeURIComponent(key)}`, "GET")).value;
1718
- } catch (errore) {
1719
- if (codiceErrore(errore) === "not_found") return null;
1720
- throw errore;
1721
- }
1722
- },
1723
- async saveRemove(key) {
1724
- await richiesta(`/saves/${encodeURIComponent(key)}`, "DELETE");
1725
- },
1726
- async saveList() {
1727
- return (await richiesta("/saves", "GET")).saves;
1728
- },
1729
- async boardSubmit(board, score, daily) {
1730
- const risultato = await richiesta("/scores", "POST", { board, score, daily });
1731
- return {
1732
- accepted: true,
1733
- best: risultato.best,
1734
- rank: risultato.rank,
1735
- day: risultato.day,
1736
- verified: risultato.verified
1737
- };
1738
- },
1739
- async boardTop(board, opzioni) {
1740
- 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.");
1741
- const query = new URLSearchParams();
1742
- if (opzioni.day !== void 0) query.set("day", opzioni.day);
1743
- if (opzioni.daily) query.set("daily", "1");
1744
- if (opzioni.limit !== void 0) query.set("limit", String(opzioni.limit));
1745
- if (opzioni.guests) query.set("guests", "1");
1746
- const suffisso = query.size === 0 ? "" : `?${query.toString()}`;
1747
- const { day, entries, me } = await richiesta(
1748
- `/scores/${encodeURIComponent(board)}${suffisso}`,
1749
- "GET"
1750
- );
1751
- return { day, entries, me };
1752
- }
1753
- };
1754
- }
1755
-
1756
- // src/daily.ts
1757
- var DIVISORE_UINT32 = 4294967296;
1758
- function prossimaMezzanotteUtc(ora) {
1759
- return (Math.floor(ora / 864e5) + 1) * 864e5;
1760
- }
1761
- function creaDaily(initial, now, refresh) {
1762
- const listeners = /* @__PURE__ */ new Set();
1763
- let current = { ...initial }, timer, pending = false;
1764
- function schedule() {
1765
- if (!listeners.size || timer !== void 0 || pending) return;
1766
- timer = setTimeout(check, Math.max(0, Math.min(2147483647, current.expiresAt - now())));
1767
- timer.unref?.();
1768
- }
1769
- async function check() {
1770
- timer = void 0;
1771
- pending = true;
1772
- try {
1773
- const next = await refresh(), changed = next.day !== current.day;
1774
- current = { ...next };
1775
- if (changed) for (const listener of [...listeners]) {
1776
- try {
1777
- listener({ ...next });
1778
- } catch {
1779
- }
1780
- }
1781
- } catch {
1782
- } finally {
1783
- pending = false;
1784
- if (current.expiresAt <= now()) current.expiresAt = now() + 3e4;
1785
- schedule();
1786
- }
1787
- }
1788
- return {
1789
- ...initial,
1790
- random: creaMulberry32(initial.seed),
1791
- rng: () => creaMulberry32(initial.seed),
1792
- onChange(listener) {
1793
- listeners.add(listener);
1794
- schedule();
1795
- return () => {
1796
- listeners.delete(listener);
1797
- if (!listeners.size && timer !== void 0) {
1798
- clearTimeout(timer);
1799
- timer = void 0;
1800
- }
1801
- };
1802
- }
1803
- };
1804
- }
1805
- function giornoUtc(ora) {
1806
- return new Date(ora).toISOString().slice(0, 10);
1807
- }
1808
- async function calcolaSeed(gioco, giorno, subtle) {
1809
- const dati = new TextEncoder().encode(`caisual:${gioco}:${giorno}`);
1810
- const digest = new Uint8Array(await subtle.digest("SHA-256", dati));
1811
- return (digest[0] ?? 0) * 16777216 + ((digest[1] ?? 0) << 16) + ((digest[2] ?? 0) << 8) + (digest[3] ?? 0) >>> 0;
1812
- }
1813
- function creaMulberry32(seed) {
1814
- let stato = seed >>> 0;
1815
- return () => {
1816
- stato = stato + 1831565813 >>> 0;
1817
- let valore = stato;
1818
- valore = Math.imul(valore ^ valore >>> 15, valore | 1);
1819
- valore ^= valore + Math.imul(valore ^ valore >>> 7, valore | 61);
1820
- return ((valore ^ valore >>> 14) >>> 0) / DIVISORE_UINT32;
1821
- };
1822
- }
1823
-
1824
- // src/handshake.ts
1825
- function record2(valore) {
1826
- return typeof valore === "object" && valore !== null && !Array.isArray(valore) ? valore : null;
1827
- }
1828
- function eTipo(valore, tipo) {
1829
- return record2(valore)?.type === tipo;
1830
- }
1831
- function leggiOrigine(valore) {
1832
- if (typeof valore !== "string") return null;
1833
- try {
1834
- const url = new URL(valore);
1835
- return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;
1836
- } catch {
1837
- return null;
1838
- }
1839
- }
1840
- function attendiHandshake(finestra, appOrigin, timeoutMs = 3e3) {
1841
- return new Promise((resolve) => {
1842
- let concluso = false;
1843
- const instance = globalThis.crypto.randomUUID();
1844
- const termina = (esito) => {
1845
- if (concluso) return;
1846
- concluso = true;
1847
- finestra.removeEventListener("message", ascolta);
1848
- finestra.clearTimeout(scadenza);
1849
- resolve(esito);
1850
- };
1851
- const segnalaPronto = () => {
1852
- finestra.parent.postMessage({ type: "caisual:ready", instance, overlayVersion: 1 }, appOrigin);
1853
- };
1854
- const ascolta = (evento) => {
1855
- if (evento.origin !== appOrigin || evento.source !== finestra.parent) return;
1856
- if (eTipo(evento.data, "caisual:ready?")) {
1857
- segnalaPronto();
1858
- return;
1859
- }
1860
- if (!eTipo(evento.data, "caisual:hello")) return;
1861
- const dati = record2(evento.data);
1862
- const porta = evento.ports[0];
1863
- if (typeof dati?.ticket !== "string" || !numeroVersione(dati.n) || porta === void 0) return;
1864
- porta.start();
1865
- const overlay = normalizeOverlayHello(dati.overlay);
1866
- const tags = (value) => Array.isArray(value) ? value.map(normalizeLanguage).filter((tag) => tag !== null) : void 0;
1867
- termina({
1868
- ...overlay ? { overlay } : {},
1869
- ...normalizeLanguage(dati.language) ? { language: normalizeLanguage(dati.language) } : {},
1870
- uiLanguage: normalizeLanguage(dati.uiLanguage) ?? void 0,
1871
- languagePreferences: tags(dati.languagePreferences),
1872
- gameLanguages: tags(dati.gameLanguages),
1873
- ticket: dati.ticket,
1874
- n: dati.n,
1875
- live: leggiOrigine(dati.live),
1876
- invite: typeof dati.invite === "string" ? dati.invite : null,
1877
- porta
1878
- });
1879
- };
1880
- finestra.addEventListener("message", ascolta);
1881
- const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
1882
- segnalaPronto();
1883
- });
1884
- }
1885
- function scadenzaJwt(ticket) {
1886
- const parte = ticket.split(".")[1];
1887
- if (parte === void 0) return null;
1888
- const base64 = parte.replace(/-/g, "+").replace(/_/g, "/").padEnd(
1889
- Math.ceil(parte.length / 4) * 4,
1890
- "="
1891
- );
1892
- try {
1893
- const payload = record2(JSON.parse(globalThis.atob(base64)));
1894
- return typeof payload?.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
1895
- } catch {
1896
- return null;
1897
- }
1898
- }
1899
- function chiediBiglietto(porta, finestra, timeoutMs, aud) {
1900
- return new Promise((resolve, reject) => {
1901
- let concluso = false;
1902
- const termina = (ticket) => {
1903
- if (concluso) return;
1904
- concluso = true;
1905
- porta.removeEventListener("message", ascolta);
1906
- finestra.clearTimeout(scadenza);
1907
- if (ticket === null) reject(new Error("Ticket refresh timed out."));
1908
- else resolve(ticket);
1909
- };
1910
- const ascolta = (evento) => {
1911
- const dati = record2(evento.data);
1912
- const destinatario = dati?.aud === void 0 ? "portal" : dati.aud;
1913
- if (dati?.type === "caisual:ticket" && destinatario === aud && typeof dati.ticket === "string") {
1914
- termina(dati.ticket);
1915
- }
1916
- };
1917
- porta.addEventListener("message", ascolta);
1918
- const scadenza = finestra.setTimeout(() => termina(null), timeoutMs);
1919
- try {
1920
- porta.postMessage(aud === "live" ? { type: "caisual:ticket", aud: "live" } : { type: "caisual:ticket" });
1921
- } catch {
1922
- termina(null);
1923
- }
1924
- });
1925
- }
1926
- function creaGestoreBiglietto(ticketIniziale, porta, finestra, ora, timeoutMs = 3e3, aud = "portal") {
1927
- let ticket = ticketIniziale;
1928
- let rinnovo = null;
1929
- const rinnova = () => {
1930
- if (rinnovo !== null) return rinnovo;
1931
- const richiesta = chiediBiglietto(porta, finestra, timeoutMs, aud).then((nuovo) => {
1932
- ticket = nuovo;
1933
- return nuovo;
1934
- });
1935
- const completa = richiesta.finally(() => {
1936
- if (rinnovo === completa) rinnovo = null;
1937
- });
1938
- rinnovo = completa;
1939
- return completa;
1940
- };
1941
- return {
1942
- async ottieni() {
1943
- if (ticket === null) return rinnova();
1944
- const scadenza = scadenzaJwt(ticket);
1945
- return scadenza !== null && scadenza - ora() < 3e4 ? rinnova() : ticket;
1946
- },
1947
- rinnova
1948
- };
1949
- }
1950
-
1951
- // src/voce/index.ts
1952
- var SOGLIA_AUDIO = 0.02;
1953
- var DURATA_PARLANTE = 300;
1954
- var INTERVALLO_AUDIO = 200;
1955
- var DURATA_ZERO = 3e3;
1956
- var TIMEOUT_CONNESSIONE = 1e4;
1957
- var RITARDI_RICONNESSIONE = [1e3, 2e3, 4e3];
1958
- function limita(value) {
1959
- return Number.isNaN(value) ? 1 : Math.min(1, Math.max(0, value));
1960
- }
1961
- function dipendenzeReali(input) {
1962
- const globali = globalThis;
1963
- const AudioContextClass = globali.AudioContext ?? globali.webkitAudioContext;
1964
- if (typeof RTCPeerConnection === "undefined" || typeof MediaStream === "undefined" || AudioContextClass === void 0 || typeof navigator === "undefined" || navigator.mediaDevices?.getUserMedia === void 0 || typeof document === "undefined") return null;
1965
- return {
1966
- ...input,
1967
- creaPeerConnection: (configuration) => new RTCPeerConnection(configuration),
1968
- getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),
1969
- creaAudioContext: () => new AudioContextClass(),
1970
- creaAudioElement: () => document.createElement("audio"),
1971
- creaMediaStream: (tracks) => new MediaStream(tracks)
1972
- };
1973
- }
1974
- var VoceClient = class {
1975
- constructor(contesto, timer, dipendenze) {
1976
- this.contesto = contesto;
1977
- this.modeCorrente = "none";
1978
- this.stateCorrente = "off";
1979
- this.mutedCorrente = false;
1980
- this.speakingCorrente = false;
1981
- this.roster = [];
1982
- this.gains = /* @__PURE__ */ new Map();
1983
- this.volumi = /* @__PURE__ */ new Map();
1984
- this.speakingPeers = /* @__PURE__ */ new Map();
1985
- this.ultimoAudio = /* @__PURE__ */ new Map();
1986
- this.zeroDa = /* @__PURE__ */ new Map();
1987
- this.timerZero = /* @__PURE__ */ new Map();
1988
- this.ascoltatoriPeers = /* @__PURE__ */ new Set();
1989
- this.ascoltatoriState = /* @__PURE__ */ new Set();
1990
- this.richieste = /* @__PURE__ */ new Map();
1991
- this.riproduzioni = /* @__PURE__ */ new Map();
1992
- this.sfuAttive = /* @__PURE__ */ new Map();
1993
- this.midGiocatori = /* @__PURE__ */ new Map();
1994
- this.negati = /* @__PURE__ */ new Set();
1995
- this.mesh = /* @__PURE__ */ new Map();
1996
- this.stream = null;
1997
- this.tracciaMic = null;
1998
- this.audioContext = null;
1999
- this.analyser = null;
2000
- this.peerSfu = null;
2001
- this.sessioneSfu = null;
2002
- this.connessioneSfuAttesa = false;
2003
- this.trasporto = null;
2004
- this.intervalloAudio = null;
2005
- this.timerConnessione = null;
2006
- this.cancellaAttesaConnessione = null;
2007
- this.timerRiconnessione = null;
2008
- this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
2009
- this.sequenzaRichieste = 0;
2010
- this.generazione = 0;
2011
- this.tentativoRiconnessione = 0;
2012
- this.desiderata = false;
2013
- this.micDesiderato = true;
2014
- this.promessaIngresso = null;
2015
- this.negoziazione = Promise.resolve();
2016
- this.dipendenze = dipendenze ?? dipendenzeReali(timer);
2017
- }
2018
- get mode() {
2019
- return this.modeCorrente;
2020
- }
2021
- get state() {
2022
- return this.stateCorrente;
2023
- }
2024
- get mic() {
2025
- return this.stateCorrente === "on" && this.tracciaMic !== null;
2026
- }
2027
- get muted() {
2028
- return this.mutedCorrente;
2029
- }
2030
- get speaking() {
2031
- return this.speakingCorrente;
2032
- }
2033
- get peers() {
2034
- return this.copiaPeers();
2035
- }
2036
- async join(options = {}) {
2037
- if (this.stateCorrente === "on") return;
2038
- if (this.stateCorrente === "joining") {
2039
- if (this.promessaIngresso !== null) await this.promessaIngresso;
2040
- return;
2041
- }
2042
- if (this.stateCorrente === "reconnecting" && this.desiderata) return;
2043
- const mic = this.scegliMic(options);
2044
- this.verificaIngresso(mic);
2045
- this.micDesiderato = mic;
2046
- this.desiderata = true;
2047
- this.tentativoRiconnessione = 0;
2048
- this.aggiornaState("joining");
2049
- const generazione = ++this.generazione;
2050
- const promessa = this.completaIngresso(generazione);
2051
- this.promessaIngresso = promessa;
2052
- try {
2053
- await promessa;
2054
- } finally {
2055
- if (this.promessaIngresso === promessa) this.promessaIngresso = null;
2056
- }
2057
- }
2058
- async completaIngresso(generazione) {
2059
- try {
2060
- await this.entra(generazione);
2061
- } catch (cause) {
2062
- if (generazione !== this.generazione) return;
2063
- this.desiderata = false;
2064
- this.chiudiRisorse();
2065
- this.aggiornaState("off");
2066
- throw this.mappaErrore(cause);
2067
- }
2068
- }
2069
- leave() {
2070
- const deveFermare = this.desiderata || this.stateCorrente !== "off";
2071
- this.desiderata = false;
2072
- this.generazione++;
2073
- this.fermaRiconnessione();
2074
- if (deveFermare && this.contesto.connessa()) {
2075
- void this.richiedi({ t: "voice", op: "stop" }).catch(() => void 0);
2076
- }
2077
- this.rifiutaRichieste(creaErrore("offline", "Voice has stopped."));
2078
- this.chiudiRisorse();
2079
- this.aggiornaState("off");
2080
- }
2081
- mute(muted = true) {
2082
- if (this.stateCorrente !== "on" || this.tracciaMic === null) {
2083
- throw creaErrore("not_publishing", "Join voice before changing mute.");
2084
- }
2085
- this.mutedCorrente = muted;
2086
- this.tracciaMic.enabled = !muted;
2087
- if (muted) this.speakingCorrente = false;
2088
- this.notificaPeers();
2089
- void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
2090
- }
2091
- setVolume(playerId, volume) {
2092
- const valore = limita(volume);
2093
- this.volumi.set(playerId, valore);
2094
- this.aggiornaGuadagno(playerId);
2095
- this.notificaPeers();
2096
- }
2097
- onPeers(listener) {
2098
- this.ascoltatoriPeers.add(listener);
2099
- return () => {
2100
- this.ascoltatoriPeers.delete(listener);
2101
- };
2102
- }
2103
- onState(listener) {
2104
- this.ascoltatoriState.add(listener);
2105
- return () => {
2106
- this.ascoltatoriState.delete(listener);
2107
- };
2108
- }
2109
- ricevi(message) {
2110
- if ("r" in message) {
2111
- const pending = this.richieste.get(message.r);
2112
- if (pending !== void 0) {
2113
- this.richieste.delete(message.r);
2114
- if ("error" in message) {
2115
- pending.reject(creaErrore(message.error.code, message.error.message));
2116
- } else pending.resolve(message);
2117
- }
2118
- return;
2119
- }
2120
- if (message.op === "roster") {
2121
- this.negati.clear();
2122
- this.modeCorrente = message.mode;
2123
- const publisher = new Set(message.peers.map((peer) => peer.id));
2124
- this.roster = [
2125
- ...message.peers.map((peer) => ({ ...peer, mic: true })),
2126
- ...message.listeners.flatMap((id) => publisher.has(id) ? [] : [{ id, mic: false, muted: true }])
2127
- ];
2128
- for (const peer of this.roster) {
2129
- if (peer.muted) this.speakingPeers.set(peer.id, false);
2130
- }
2131
- this.pulisciPeerAssenti();
2132
- this.contesto.rosterPronto();
2133
- this.notificaPeers();
2134
- this.accodaRiconciliazione();
2135
- return;
2136
- }
2137
- if (message.op === "gain") {
2138
- this.negati.clear();
2139
- for (const [playerId, gain] of Object.entries(message.gains)) {
2140
- this.gains.set(playerId, limita(gain));
2141
- this.aggiornaZero(playerId);
2142
- this.aggiornaGuadagno(playerId);
2143
- }
2144
- this.notificaPeers();
2145
- this.accodaRiconciliazione();
2146
- return;
2147
- }
2148
- if (message.op === "closed") {
2149
- for (const mid of message.mids) {
2150
- const playerId = this.midGiocatori.get(mid);
2151
- if (playerId === void 0) continue;
2152
- const attiva = this.sfuAttive.get(playerId);
2153
- if (attiva?.mid === mid && !this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
2154
- if (attiva?.mid === mid) this.sfuAttive.delete(playerId);
2155
- this.midGiocatori.delete(mid);
2156
- this.scollegaTraccia(playerId);
2157
- this.negati.add(playerId);
2158
- }
2159
- this.notificaPeers();
2160
- return;
2161
- }
2162
- if (message.op === "signal") void this.riceviSegnale(message.from, message.data);
2163
- }
2164
- giocatoriCambiati() {
2165
- this.negati.clear();
2166
- const presenti = new Set(this.contesto.giocatori().map((player) => player.id));
2167
- for (const playerId of this.gains.keys()) {
2168
- if (presenti.has(playerId)) continue;
2169
- this.gains.delete(playerId);
2170
- this.zeroDa.delete(playerId);
2171
- const timer = this.timerZero.get(playerId);
2172
- if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
2173
- this.timerZero.delete(playerId);
2174
- this.aggiornaGuadagno(playerId);
2175
- }
2176
- this.notificaPeers();
2177
- this.accodaRiconciliazione();
2178
- }
2179
- socketDisconnesso() {
2180
- this.sequenzaRichieste = 0;
2181
- this.rifiutaRichieste(creaErrore("offline", "The room is reconnecting."));
2182
- if (!this.desiderata) return;
2183
- this.generazione++;
2184
- this.chiudiRisorse();
2185
- this.tentativoRiconnessione = 0;
2186
- this.aggiornaState("reconnecting");
2187
- }
2188
- socketRiconnesso() {
2189
- this.sequenzaRichieste = 0;
2190
- if (this.desiderata && this.stateCorrente === "reconnecting") this.programmaRiconnessione();
2191
- }
2192
- termina() {
2193
- this.desiderata = false;
2194
- this.generazione++;
2195
- this.fermaRiconnessione();
2196
- this.rifiutaRichieste(creaErrore("offline", "The room connection ended."));
2197
- this.chiudiRisorse();
2198
- this.aggiornaState("off");
2199
- }
2200
- scegliMic(options) {
2201
- if (options.mic !== void 0) return options.mic;
2202
- const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
2203
- return you?.role !== "spectator";
2204
- }
2205
- verificaIngresso(mic = this.micDesiderato) {
2206
- if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");
2207
- if (this.modeCorrente === "none") {
2208
- throw creaErrore("voice_disabled", "Voice is disabled for this room.");
2209
- }
2210
- const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
2211
- if (you?.role === "spectator" && mic) {
2212
- throw creaErrore("spectator", "Spectators cannot publish voice.");
2213
- }
2214
- if (this.dipendenze === null) {
2215
- throw creaErrore("unsupported", "Voice is not supported in this browser.");
2216
- }
2217
- }
2218
- async entra(generazione) {
2219
- this.verificaIngresso();
2220
- const dipendenze = this.richiediDipendenze();
2221
- const audioContext = dipendenze.creaAudioContext();
2222
- this.audioContext = audioContext;
2223
- if (this.micDesiderato) {
2224
- let stream;
2225
- try {
2226
- stream = await dipendenze.getUserMedia({ audio: true });
2227
- } catch (cause) {
2228
- if (this.permessoNegato(cause)) {
2229
- throw creaErrore("permission_denied", "Microphone permission was denied.");
2230
- }
2231
- throw creaErrore("voice_error", "The microphone could not be opened.");
2232
- }
2233
- try {
2234
- this.controllaGenerazione(generazione);
2235
- } catch (cause) {
2236
- for (const track of stream.getTracks()) track.stop();
2237
- throw cause;
2238
- }
2239
- const mic = stream.getAudioTracks()[0];
2240
- if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");
2241
- this.stream = stream;
2242
- this.tracciaMic = mic;
2243
- mic.enabled = !this.mutedCorrente;
2244
- this.preparaAnalizzatore(stream);
2245
- }
2246
- try {
2247
- await audioContext.resume();
2248
- } catch {
2249
- }
2250
- this.controllaGenerazione(generazione);
2251
- const risposta = await this.richiedi({ t: "voice", op: "ice" });
2252
- this.controllaGenerazione(generazione);
2253
- if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
2254
- this.modeCorrente = risposta.mode;
2255
- if (risposta.mode === "none") throw creaErrore("voice_disabled", "Voice is disabled for this room.");
2256
- this.trasporto = risposta.transport;
2257
- if (risposta.transport === "sfu") {
2258
- await this.entraSfu(risposta.iceServers, generazione);
2259
- } else {
2260
- await this.richiedi({ t: "voice", op: "publish", mic: this.micDesiderato });
2261
- }
2262
- if (this.micDesiderato && this.mutedCorrente) {
2263
- await this.richiedi({ t: "voice", op: "mute", muted: true });
2264
- }
2265
- this.controllaGenerazione(generazione);
2266
- this.tentativoRiconnessione = 0;
2267
- this.aggiornaState("on");
2268
- this.avviaMisuraAudio();
2269
- for (const playerId of this.gains.keys()) this.aggiornaZero(playerId);
2270
- this.accodaRiconciliazione();
2271
- }
2272
- async entraSfu(iceServers, generazione) {
2273
- const pc = this.richiediDipendenze().creaPeerConnection({
2274
- iceServers,
2275
- bundlePolicy: "max-bundle"
2276
- });
2277
- this.peerSfu = pc;
2278
- pc.ontrack = (event) => {
2279
- const mid = event.transceiver.mid;
2280
- const playerId = mid === null ? void 0 : this.midGiocatori.get(mid);
2281
- if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);
2282
- };
2283
- this.osservaCaduta(pc);
2284
- let risposta;
2285
- if (this.micDesiderato) {
2286
- const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });
2287
- const offer = await pc.createOffer();
2288
- await pc.setLocalDescription(offer);
2289
- this.controllaGenerazione(generazione);
2290
- const mid = transceiver.mid;
2291
- const sdp = pc.localDescription?.sdp;
2292
- if (mid === null || sdp === void 0) {
2293
- throw creaErrore("voice_error", "The voice connection could not create an offer.");
2294
- }
2295
- risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });
2296
- } else {
2297
- risposta = await this.richiedi({ t: "voice", op: "session" });
2298
- }
2299
- if (risposta.op !== "session") {
2300
- throw creaErrore("voice_error", "The voice service returned an invalid response.");
2301
- }
2302
- this.sessioneSfu = risposta.session;
2303
- if (this.micDesiderato) {
2304
- if (risposta.sdp === null) {
2305
- throw creaErrore("voice_error", "The voice service returned an invalid response.");
2306
- }
2307
- await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });
2308
- await this.attendiConnessione(pc, generazione);
2309
- this.connessioneSfuAttesa = true;
2310
- return;
2311
- }
2312
- if (risposta.sdp !== null) {
2313
- throw creaErrore("voice_error", "The voice service returned an invalid response.");
2314
- }
2315
- if (this.publisherDesiderati().length > 0) {
2316
- await this.riconciliaSfu();
2317
- }
2318
- }
2319
- attendiConnessione(pc, generazione) {
2320
- if (pc.connectionState === "connected") return Promise.resolve();
2321
- const dipendenze = this.richiediDipendenze();
2322
- return new Promise((resolve, reject) => {
2323
- const pulisci = () => {
2324
- pc.removeEventListener("connectionstatechange", cambiata);
2325
- if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
2326
- this.timerConnessione = null;
2327
- this.cancellaAttesaConnessione = null;
2328
- };
2329
- const cambiata = () => {
2330
- if (generazione !== this.generazione) {
2331
- pulisci();
2332
- reject(creaErrore("offline", "Voice was stopped."));
2333
- } else if (pc.connectionState === "connected") {
2334
- pulisci();
2335
- resolve();
2336
- } else if (pc.connectionState === "failed" || pc.connectionState === "closed") {
2337
- pulisci();
2338
- reject(creaErrore("voice_error", "The voice connection failed."));
2339
- }
2340
- };
2341
- pc.addEventListener("connectionstatechange", cambiata);
2342
- this.cancellaAttesaConnessione = () => {
2343
- pulisci();
2344
- reject(creaErrore("offline", "Voice was stopped."));
2345
- };
2346
- this.timerConnessione = dipendenze.setTimeout(() => {
2347
- pulisci();
2348
- reject(creaErrore("voice_error", "The voice connection timed out."));
2349
- }, TIMEOUT_CONNESSIONE);
2350
- });
2351
- }
2352
- accodaRiconciliazione() {
2353
- if (this.stateCorrente !== "on") return;
2354
- this.negoziazione = this.negoziazione.then(async () => {
2355
- if (this.stateCorrente !== "on") return;
2356
- if (this.trasporto === "sfu") await this.riconciliaSfu();
2357
- else if (this.trasporto === "mesh") this.riconciliaMesh();
2358
- }).catch(() => this.avviaRiconnessione());
2359
- }
2360
- async riconciliaSfu() {
2361
- const sessione = this.sessioneSfu;
2362
- const pc = this.peerSfu;
2363
- if (sessione === null || pc === null) return;
2364
- const desiderati = new Map(this.publisherDesiderati().map((peer) => [peer.id, peer]));
2365
- const daChiudere = [];
2366
- for (const [playerId, attiva] of this.sfuAttive) {
2367
- const peer = desiderati.get(playerId);
2368
- if (peer !== void 0 && peer.session === attiva.session && peer.track === attiva.track) continue;
2369
- daChiudere.push(attiva);
2370
- if (!this.riproduzioni.has(playerId)) attiva.receiver?.track.stop();
2371
- this.sfuAttive.delete(playerId);
2372
- this.midGiocatori.delete(attiva.mid);
2373
- this.scollegaTraccia(playerId);
2374
- }
2375
- if (daChiudere.length > 0) {
2376
- await this.richiedi({
2377
- t: "voice",
2378
- op: "close",
2379
- session: sessione,
2380
- mids: daChiudere.map((item) => item.mid)
2381
- });
2382
- }
2383
- const nuove = [...desiderati.values()].filter((peer) => !this.sfuAttive.has(peer.id));
2384
- if (nuove.length === 0) return;
2385
- let risposta;
2386
- try {
2387
- risposta = await this.richiedi({
2388
- t: "voice",
2389
- op: "subscribe",
2390
- session: sessione,
2391
- tracks: nuove.map((peer) => ({ session: peer.session, track: peer.track }))
2392
- });
2393
- } catch (cause) {
2394
- if (codiceErrore(cause) !== "not_allowed") throw cause;
2395
- for (const peer of nuove) this.negati.add(peer.id);
2396
- return;
2397
- }
2398
- if (risposta.op !== "subscribe") {
2399
- throw creaErrore("voice_error", "The voice service returned an invalid response.");
2400
- }
2401
- for (const risultato of risposta.tracks) {
2402
- const peer = nuove.find(
2403
- (item) => item.session === risultato.session && item.track === risultato.track
2404
- );
2405
- if (risultato.error === "not_allowed" && peer !== void 0) this.negati.add(peer.id);
2406
- if (risultato?.mid === null || risultato?.mid === void 0 || risultato.error !== null || peer === void 0) continue;
2407
- this.midGiocatori.set(risultato.mid, peer.id);
2408
- this.sfuAttive.set(peer.id, {
2409
- session: peer.session,
2410
- track: peer.track,
2411
- mid: risultato.mid,
2412
- receiver: null
2413
- });
2414
- }
2415
- await pc.setRemoteDescription({ type: "offer", sdp: risposta.sdp });
2416
- const answer = await pc.createAnswer();
2417
- await pc.setLocalDescription(answer);
2418
- const sdp = pc.localDescription?.sdp;
2419
- if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");
2420
- await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });
2421
- if (!this.connessioneSfuAttesa) {
2422
- await this.attendiConnessione(pc, this.generazione);
2423
- this.connessioneSfuAttesa = true;
2424
- }
2425
- }
2426
- riconciliaMesh() {
2427
- const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
2428
- for (const [playerId, item] of this.mesh) {
2429
- if (desiderati.has(playerId)) continue;
2430
- item.pc.close();
2431
- this.mesh.delete(playerId);
2432
- this.scollegaTraccia(playerId);
2433
- }
2434
- for (const peer of desiderati.values()) {
2435
- if (!this.mesh.has(peer.id)) this.creaMesh(peer);
2436
- }
2437
- }
2438
- creaMesh(peer) {
2439
- const playerId = peer.id;
2440
- const pc = this.richiediDipendenze().creaPeerConnection();
2441
- const item = {
2442
- pc,
2443
- makingOffer: false,
2444
- ignoreOffer: false,
2445
- settingRemoteAnswer: false,
2446
- polite: this.contesto.you() > playerId,
2447
- receiver: null
2448
- };
2449
- this.mesh.set(playerId, item);
2450
- pc.onicecandidate = (event) => {
2451
- if (event.candidate === null) return;
2452
- void this.inviaSegnale(playerId, { kind: "candidate", candidate: event.candidate.toJSON() });
2453
- };
2454
- if (!item.polite) pc.onnegotiationneeded = () => {
2455
- void this.offriMesh(playerId, item);
2456
- };
2457
- pc.ontrack = (event) => {
2458
- item.receiver = event.receiver;
2459
- this.collegaTraccia(playerId, event.track, event.receiver);
2460
- };
2461
- this.osservaCaduta(pc);
2462
- if (this.micDesiderato) {
2463
- pc.addTransceiver(this.richiediMic(), {
2464
- direction: peer.mic ? "sendrecv" : "sendonly"
2465
- });
2466
- } else {
2467
- pc.addTransceiver("audio", { direction: "recvonly" });
2468
- }
2469
- }
2470
- async offriMesh(playerId, item) {
2471
- try {
2472
- item.makingOffer = true;
2473
- const offer = await item.pc.createOffer();
2474
- await item.pc.setLocalDescription(offer);
2475
- const sdp = item.pc.localDescription?.sdp;
2476
- if (sdp !== void 0) await this.inviaSegnale(playerId, { kind: "offer", sdp });
2477
- } finally {
2478
- item.makingOffer = false;
2479
- }
2480
- }
2481
- async riceviSegnale(from, data) {
2482
- if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;
2483
- const peer = this.peerDesiderati().find((item2) => item2.id === from);
2484
- if (peer === void 0) return;
2485
- if (!this.mesh.has(from)) this.creaMesh(peer);
2486
- const item = this.mesh.get(from);
2487
- if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;
2488
- const segnale = data;
2489
- try {
2490
- if (segnale.kind === "candidate") {
2491
- if (!item.ignoreOffer) await item.pc.addIceCandidate(segnale.candidate);
2492
- return;
2493
- }
2494
- if (segnale.kind !== "offer" && segnale.kind !== "answer" || typeof segnale.sdp !== "string") return;
2495
- const pronta = !item.makingOffer && (item.pc.signalingState === "stable" || item.settingRemoteAnswer);
2496
- const collisione = segnale.kind === "offer" && !pronta;
2497
- item.ignoreOffer = !item.polite && collisione;
2498
- if (item.ignoreOffer) return;
2499
- item.settingRemoteAnswer = segnale.kind === "answer";
2500
- await item.pc.setRemoteDescription({ type: segnale.kind, sdp: segnale.sdp });
2501
- item.settingRemoteAnswer = false;
2502
- if (segnale.kind === "offer") {
2503
- const answer = await item.pc.createAnswer();
2504
- await item.pc.setLocalDescription(answer);
2505
- const sdp = item.pc.localDescription?.sdp;
2506
- if (sdp !== void 0) await this.inviaSegnale(from, { kind: "answer", sdp });
2507
- }
2508
- } catch {
2509
- this.avviaRiconnessione();
2510
- }
2511
- }
2512
- async inviaSegnale(to, data) {
2513
- try {
2514
- await this.richiedi({ t: "voice", op: "signal", to, data });
2515
- } catch (cause) {
2516
- if (codiceErrore(cause) !== "not_allowed") throw cause;
2517
- const item = this.mesh.get(to);
2518
- item?.pc.close();
2519
- this.mesh.delete(to);
2520
- this.scollegaTraccia(to);
2521
- this.negati.add(to);
2522
- }
2523
- }
2524
- peerDesiderati() {
2525
- const you = this.contesto.you();
2526
- const giocatori = this.contesto.giocatori();
2527
- const player = giocatori.find((item) => item.id === you);
2528
- return this.roster.filter((peer) => {
2529
- if (peer.id === you) return false;
2530
- if (this.negati.has(peer.id)) return false;
2531
- if (!this.micDesiderato && !peer.mic) return false;
2532
- if (this.modeCorrente === "team") {
2533
- const altro = giocatori.find((item) => item.id === peer.id);
2534
- if (player?.role !== "spectator" && altro?.team !== player?.team) return false;
2535
- }
2536
- return true;
2537
- });
2538
- }
2539
- publisherDesiderati() {
2540
- return this.peerDesiderati().filter(
2541
- (peer) => {
2542
- if (!peer.mic) return false;
2543
- const zeroAt = this.zeroDa.get(peer.id);
2544
- return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;
2545
- }
2546
- );
2547
- }
2548
- aggiornaZero(playerId) {
2549
- const dipendenze = this.dipendenze;
2550
- if (dipendenze === null) return;
2551
- const precedente = this.timerZero.get(playerId);
2552
- if (precedente !== void 0) dipendenze.clearTimeout(precedente);
2553
- this.timerZero.delete(playerId);
2554
- if ((this.gains.get(playerId) ?? 1) > 0) {
2555
- this.zeroDa.delete(playerId);
2556
- return;
2557
- }
2558
- if (!this.zeroDa.has(playerId)) this.zeroDa.set(playerId, dipendenze.ora());
2559
- const trascorso = dipendenze.ora() - (this.zeroDa.get(playerId) ?? dipendenze.ora());
2560
- const timer = dipendenze.setTimeout(() => {
2561
- this.timerZero.delete(playerId);
2562
- this.accodaRiconciliazione();
2563
- }, Math.max(0, DURATA_ZERO - trascorso));
2564
- this.timerZero.set(playerId, timer);
2565
- }
2566
- collegaTraccia(playerId, track, receiver) {
2567
- this.scollegaTraccia(playerId);
2568
- const dipendenze = this.richiediDipendenze();
2569
- const media = dipendenze.creaMediaStream([track]);
2570
- const source = this.richiediAudioContext().createMediaStreamSource(media);
2571
- const gain = this.richiediAudioContext().createGain();
2572
- source.connect(gain);
2573
- gain.connect(this.richiediAudioContext().destination);
2574
- let analyser = null;
2575
- try {
2576
- analyser = this.richiediAudioContext().createAnalyser();
2577
- analyser.fftSize = 256;
2578
- source.connect(analyser);
2579
- } catch {
2580
- analyser = null;
2581
- }
2582
- const audio = dipendenze.creaAudioElement();
2583
- audio.srcObject = media;
2584
- audio.muted = true;
2585
- audio.playsInline = true;
2586
- void audio.play().catch(() => void 0);
2587
- this.riproduzioni.set(playerId, { source, gain, analyser, audio, track, receiver });
2588
- const attiva = this.sfuAttive.get(playerId);
2589
- if (attiva !== void 0) attiva.receiver = receiver;
2590
- this.aggiornaGuadagno(playerId);
2591
- }
2592
- scollegaTraccia(playerId) {
2593
- const riproduzione = this.riproduzioni.get(playerId);
2594
- if (riproduzione === void 0) return;
2595
- riproduzione.source.disconnect();
2596
- riproduzione.gain.disconnect();
2597
- riproduzione.analyser?.disconnect();
2598
- riproduzione.track.stop();
2599
- riproduzione.audio.pause();
2600
- riproduzione.audio.srcObject = null;
2601
- this.riproduzioni.delete(playerId);
2602
- this.speakingPeers.delete(playerId);
2603
- this.ultimoAudio.delete(playerId);
2604
- }
2605
- aggiornaGuadagno(playerId) {
2606
- const riproduzione = this.riproduzioni.get(playerId);
2607
- if (riproduzione !== void 0) {
2608
- riproduzione.gain.gain.value = (this.volumi.get(playerId) ?? 1) * (this.gains.get(playerId) ?? 1);
2609
- }
2610
- }
2611
- preparaAnalizzatore(stream) {
2612
- const context = this.richiediAudioContext();
2613
- const analyser = context.createAnalyser();
2614
- analyser.fftSize = 256;
2615
- context.createMediaStreamSource(stream).connect(analyser);
2616
- this.analyser = analyser;
2617
- }
2618
- avviaMisuraAudio() {
2619
- const dipendenze = this.richiediDipendenze();
2620
- if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
2621
- this.intervalloAudio = dipendenze.setInterval(() => this.misuraAudio(), INTERVALLO_AUDIO);
2622
- }
2623
- misuraAudio() {
2624
- const dipendenze = this.dipendenze;
2625
- if (dipendenze === null) return;
2626
- let sopraSoglia = false;
2627
- if (this.analyser !== null) sopraSoglia = this.livelloAnalizzatore(this.analyser) > SOGLIA_AUDIO;
2628
- if (sopraSoglia) this.ultimoAudioMic = dipendenze.ora();
2629
- const parlando = !this.mutedCorrente && dipendenze.ora() - this.ultimoAudioMic <= DURATA_PARLANTE;
2630
- if (parlando !== this.speakingCorrente) {
2631
- this.speakingCorrente = parlando;
2632
- this.notificaPeers();
2633
- }
2634
- let cambiato = false;
2635
- for (const peer of this.copiaPeers()) {
2636
- const riproduzione = this.riproduzioni.get(peer.id);
2637
- if (this.livelloAnalizzatore(riproduzione?.analyser ?? null) > SOGLIA_AUDIO) {
2638
- this.ultimoAudio.set(peer.id, dipendenze.ora());
2639
- } else if (riproduzione?.analyser === null || riproduzione?.analyser === void 0) {
2640
- const sources = riproduzione?.receiver?.getSynchronizationSources?.() ?? [];
2641
- if (sources.some((source) => (source.audioLevel ?? 0) > SOGLIA_AUDIO)) {
2642
- this.ultimoAudio.set(peer.id, dipendenze.ora());
2643
- }
2644
- }
2645
- const speaking = !peer.muted && dipendenze.ora() - (this.ultimoAudio.get(peer.id) ?? 0) <= DURATA_PARLANTE;
2646
- if ((this.speakingPeers.get(peer.id) ?? false) !== speaking) {
2647
- this.speakingPeers.set(peer.id, speaking);
2648
- cambiato = true;
2649
- }
2650
- }
2651
- if (cambiato) this.notificaPeers();
2652
- }
2653
- livelloAnalizzatore(analyser) {
2654
- const nodo = analyser;
2655
- if (nodo?.getFloatTimeDomainData === void 0) return 0;
2656
- const campioni = new Float32Array(nodo.fftSize);
2657
- nodo.getFloatTimeDomainData(campioni);
2658
- return Math.sqrt(campioni.reduce((somma, valore) => somma + valore * valore, 0) / Math.max(1, campioni.length));
2659
- }
2660
- copiaPeers() {
2661
- const you = this.contesto.you();
2662
- const giocatori = this.contesto.giocatori();
2663
- const player = giocatori.find((item) => item.id === you);
2664
- return this.roster.flatMap((peer) => {
2665
- if (peer.id === you) return [];
2666
- if (this.modeCorrente === "team") {
2667
- const altro = giocatori.find((item) => item.id === peer.id);
2668
- if (player?.role !== "spectator" && altro?.team !== player?.team) return [];
2669
- }
2670
- return [{
2671
- id: peer.id,
2672
- mic: peer.mic,
2673
- muted: peer.muted,
2674
- speaking: peer.mic && !peer.muted && (this.speakingPeers.get(peer.id) ?? false),
2675
- volume: this.volumi.get(peer.id) ?? 1,
2676
- gain: this.gains.get(peer.id) ?? 1
2677
- }];
2678
- });
2679
- }
2680
- pulisciPeerAssenti() {
2681
- const presenti = new Set(this.roster.map((peer) => peer.id));
2682
- for (const playerId of this.speakingPeers.keys()) {
2683
- if (!presenti.has(playerId)) this.speakingPeers.delete(playerId);
2684
- }
2685
- for (const playerId of this.zeroDa.keys()) {
2686
- if (presenti.has(playerId)) continue;
2687
- this.zeroDa.delete(playerId);
2688
- const timer = this.timerZero.get(playerId);
2689
- if (timer !== void 0) this.dipendenze?.clearTimeout(timer);
2690
- this.timerZero.delete(playerId);
2691
- }
2692
- }
2693
- osservaCaduta(pc) {
2694
- pc.addEventListener("connectionstatechange", () => {
2695
- if (this.stateCorrente === "on" && (pc.connectionState === "failed" || pc.connectionState === "disconnected")) this.avviaRiconnessione();
2696
- });
2697
- }
2698
- avviaRiconnessione() {
2699
- if (!this.desiderata || this.stateCorrente === "reconnecting") return;
2700
- this.generazione++;
2701
- this.rifiutaRichieste(creaErrore("voice_error", "The voice connection was restarted."));
2702
- this.chiudiRisorse();
2703
- this.tentativoRiconnessione = 0;
2704
- this.aggiornaState("reconnecting");
2705
- this.programmaRiconnessione();
2706
- }
2707
- programmaRiconnessione() {
2708
- if (!this.desiderata || !this.contesto.connessa() || this.timerRiconnessione !== null || this.stateCorrente !== "reconnecting") return;
2709
- const ritardo = RITARDI_RICONNESSIONE[this.tentativoRiconnessione];
2710
- if (ritardo === void 0) {
2711
- this.desiderata = false;
2712
- this.aggiornaState("off");
2713
- return;
2714
- }
2715
- this.tentativoRiconnessione++;
2716
- this.timerRiconnessione = this.richiediDipendenze().setTimeout(() => {
2717
- this.timerRiconnessione = null;
2718
- const generazione = ++this.generazione;
2719
- void this.entra(generazione).catch(() => {
2720
- if (generazione !== this.generazione || !this.desiderata) return;
2721
- this.chiudiRisorse();
2722
- this.aggiornaState("reconnecting");
2723
- this.programmaRiconnessione();
2724
- });
2725
- }, ritardo);
2726
- }
2727
- fermaRiconnessione() {
2728
- if (this.timerRiconnessione === null || this.dipendenze === null) return;
2729
- this.dipendenze.clearTimeout(this.timerRiconnessione);
2730
- this.timerRiconnessione = null;
2731
- }
2732
- chiudiRisorse() {
2733
- const dipendenze = this.dipendenze;
2734
- this.cancellaAttesaConnessione?.();
2735
- this.cancellaAttesaConnessione = null;
2736
- if (dipendenze !== null) {
2737
- if (this.intervalloAudio !== null) dipendenze.clearInterval(this.intervalloAudio);
2738
- if (this.timerConnessione !== null) dipendenze.clearTimeout(this.timerConnessione);
2739
- for (const timer of this.timerZero.values()) dipendenze.clearTimeout(timer);
2740
- }
2741
- this.intervalloAudio = null;
2742
- this.timerConnessione = null;
2743
- this.timerZero.clear();
2744
- for (const playerId of [...this.riproduzioni.keys()]) this.scollegaTraccia(playerId);
2745
- this.peerSfu?.close();
2746
- this.peerSfu = null;
2747
- for (const item of this.mesh.values()) item.pc.close();
2748
- this.mesh.clear();
2749
- this.sfuAttive.clear();
2750
- this.midGiocatori.clear();
2751
- this.negati.clear();
2752
- for (const track of this.stream?.getTracks() ?? []) track.stop();
2753
- this.stream = null;
2754
- this.tracciaMic = null;
2755
- this.analyser = null;
2756
- void this.audioContext?.close().catch(() => void 0);
2757
- this.audioContext = null;
2758
- this.sessioneSfu = null;
2759
- this.connessioneSfuAttesa = false;
2760
- this.trasporto = null;
2761
- this.speakingCorrente = false;
2762
- this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
2763
- this.speakingPeers.clear();
2764
- this.ultimoAudio.clear();
2765
- this.negoziazione = Promise.resolve();
2766
- }
2767
- richiedi(message) {
2768
- if (!this.contesto.connessa()) return Promise.reject(creaErrore("offline", "The room is reconnecting."));
2769
- const r = ++this.sequenzaRichieste;
2770
- return new Promise((resolve, reject) => {
2771
- this.richieste.set(r, { resolve, reject });
2772
- try {
2773
- this.contesto.invia({ ...message, r });
2774
- } catch (cause) {
2775
- this.richieste.delete(r);
2776
- reject(cause);
2777
- }
2778
- });
2779
- }
2780
- rifiutaRichieste(reason) {
2781
- for (const richiesta of this.richieste.values()) richiesta.reject(reason);
2782
- this.richieste.clear();
2783
- }
2784
- aggiornaState(state) {
2785
- if (state === this.stateCorrente) return;
2786
- this.stateCorrente = state;
2787
- for (const listener of this.ascoltatoriState) {
2788
- try {
2789
- listener(state);
2790
- } catch {
2791
- }
2792
- }
2793
- }
2794
- notificaPeers() {
2795
- const peers = this.copiaPeers();
2796
- for (const listener of this.ascoltatoriPeers) {
2797
- try {
2798
- listener(peers);
2799
- } catch {
2800
- }
2801
- }
2802
- }
2803
- controllaGenerazione(generazione) {
2804
- if (generazione !== this.generazione || !this.desiderata) {
2805
- throw creaErrore("offline", "Voice was stopped.");
2806
- }
2807
- }
2808
- richiediDipendenze() {
2809
- if (this.dipendenze === null) throw creaErrore("unsupported", "Voice is not supported.");
2810
- return this.dipendenze;
2811
- }
2812
- richiediMic() {
2813
- if (this.tracciaMic === null) throw creaErrore("voice_error", "The microphone is not ready.");
2814
- return this.tracciaMic;
2815
- }
2816
- richiediAudioContext() {
2817
- if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");
2818
- return this.audioContext;
2819
- }
2820
- permessoNegato(cause) {
2821
- return typeof cause === "object" && cause !== null && "name" in cause && (cause.name === "NotAllowedError" || cause.name === "SecurityError");
2822
- }
2823
- mappaErrore(cause) {
2824
- if (typeof cause === "object" && cause !== null && "code" in cause) {
2825
- const code = cause.code;
2826
- if (code === "voice_disabled" || code === "permission_denied" || code === "unsupported" || code === "spectator" || code === "offline" || code === "voice_error") return cause;
2827
- return creaErrore("voice_error", "Voice could not be started.");
2828
- }
2829
- return creaErrore("voice_error", "Voice could not be started.");
2830
- }
2831
- };
2832
-
2833
- // src/stanza-client/index.ts
2834
- var APERTO = 1;
2835
- var RITARDI_RICONNESSIONE2 = [1e3, 2e3, 4e3, 8e3];
2836
- var GRAZIA_RICONNESSIONE = 6e4;
2837
- var INTERVALLO_PING = 5e3;
2838
- var RITARDO_FLUSH = 500;
2839
- var ATTESA_ROSTER = 2e3;
2840
- var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006, 4008, 4009]);
2841
- function record3(value) {
2842
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2843
- }
2844
- function ingressoValido(value) {
2845
- const dati = record3(value);
2846
- return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
2847
- }
2848
- function visioneValida(value) {
2849
- const dati = record3(value);
2850
- return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.watch === "string" && typeof dati.url === "string";
2851
- }
2852
- function rispostaMatchValida(value) {
2853
- const dati = record3(value);
2854
- const players = record3(dati?.players);
2855
- 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;
2856
- }
2857
- function copiaJson(value) {
2858
- return JSON.parse(JSON.stringify(value));
2859
- }
2860
- function applicaPatch(state, value) {
2861
- let risultato = copiaJson(state);
2862
- for (const operazione of value) {
2863
- if (operazione.path.length === 0) {
2864
- if (operazione.op !== "set") return { ok: false };
2865
- risultato = copiaJson(operazione.value);
2866
- continue;
2867
- }
2868
- let contenitore = risultato;
2869
- const percorso = operazione.path;
2870
- for (let indice = 0; indice < percorso.length - 1; indice++) {
2871
- const parte = percorso[indice];
2872
- if (Array.isArray(contenitore)) {
2873
- if (typeof parte !== "number" || parte >= contenitore.length) return { ok: false };
2874
- contenitore = contenitore[parte];
2875
- } else {
2876
- const oggetto2 = record3(contenitore);
2877
- if (oggetto2 === null || typeof parte !== "string" || !Object.hasOwn(oggetto2, parte)) {
2878
- return { ok: false };
2879
- }
2880
- contenitore = oggetto2[parte];
2881
- }
2882
- }
2883
- const ultima = percorso.at(-1);
2884
- if (Array.isArray(contenitore)) {
2885
- if (operazione.op !== "set" || typeof ultima !== "number" || ultima >= contenitore.length) return { ok: false };
2886
- contenitore[ultima] = copiaJson(operazione.value);
2887
- } else {
2888
- const oggetto2 = record3(contenitore);
2889
- if (oggetto2 === null || typeof ultima !== "string") return { ok: false };
2890
- if (operazione.op === "del") {
2891
- if (!Object.hasOwn(oggetto2, ultima)) return { ok: false };
2892
- delete oggetto2[ultima];
2893
- } else {
2894
- Object.defineProperty(oggetto2, ultima, {
2895
- configurable: true,
2896
- enumerable: true,
2897
- value: copiaJson(operazione.value),
2898
- writable: true
2899
- });
2900
- }
2901
- }
2902
- }
2903
- return { ok: true, state: risultato };
2904
- }
2905
- function creaApiLive(input) {
2906
- const richiedi = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);
2907
- const richiesta = async (path, method, body, renew) => {
2908
- try {
2909
- return await richiedi(path, method, { ...record3(body), n: input.n }, renew);
2910
- } catch (error) {
2911
- if (error instanceof Error && "code" in error && ["version_outdated", "version_mismatch"].includes(String(error.code))) {
2912
- const value = record3(body);
2913
- const code = typeof value?.code === "string" ? value.code.toUpperCase().replace(/[\s-]/g, "") : void 0;
2914
- const roomId = typeof value?.roomId === "string" ? value.roomId : void 0;
2915
- input.onVersionError?.(error, error.code === "version_mismatch" ? { code, roomId, watch: path === "/rooms/watch" } : void 0);
2916
- }
2917
- throw error;
2918
- }
2919
- };
2920
- async function ingresso(path, body, rinnova = false) {
2921
- const value = await richiesta(path, "POST", body, rinnova);
2922
- if (!ingressoValido(value)) {
2923
- throw creaErrore("internal_error", "The room service returned an invalid response.");
2924
- }
2925
- return value;
2926
- }
2927
- async function match(options) {
2928
- const value = await richiesta("/match", "POST", {
2929
- mode: options.mode,
2930
- key: options.key
2931
- });
2932
- if (!rispostaMatchValida(value)) {
2933
- throw creaErrore("internal_error", "The matchmaking service returned an invalid response.");
2934
- }
2935
- return value;
2936
- }
2937
- async function visione(body, rinnova = false) {
2938
- const value = await richiesta("/rooms/watch", "POST", body, rinnova);
2939
- if (!visioneValida(value)) {
2940
- throw creaErrore("internal_error", "The room service returned an invalid response.");
2941
- }
2942
- return value;
2943
- }
2944
- return {
2945
- create: (mode) => ingresso("/rooms", { mode }),
2946
- joinCode: (code) => ingresso("/rooms/join", { code }),
2947
- joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),
2948
- watchCode: (code) => visione({ code }),
2949
- watchRoom: (roomId) => visione({ roomId }, true),
2950
- match,
2951
- flush: (roomId) => richiesta(
2952
- `/rooms/${encodeURIComponent(roomId)}/flush`,
2953
- "POST"
2954
- )
2955
- };
2956
- }
2957
- var StanzaClient = class {
2958
- constructor(roomId, codice, url, dipendenze, api, segnalaStanza, spettatore = false) {
2959
- this.roomId = roomId;
2960
- this.codice = codice;
2961
- this.dipendenze = dipendenze;
2962
- this.api = api;
2963
- this.segnalaStanza = segnalaStanza;
2964
- this.spettatore = spettatore;
2965
- this.meta = { host: null, mode: null, countdownAt: null, configuration: null, connection: "connecting", closedCode: null };
2966
- this.metaListeners = /* @__PURE__ */ new Set();
2967
- this.connectionListeners = /* @__PURE__ */ new Set();
2968
- this.scoreListeners = /* @__PURE__ */ new Set();
2969
- this.scores = [];
2970
- this.errorListeners = /* @__PURE__ */ new Set();
2971
- this.roleId = 0;
2972
- this.roleRequests = /* @__PURE__ */ new Map();
2973
- this.statoPubblico = null;
2974
- this.statoSincronizzato = null;
2975
- this.tickCorrente = 0;
2976
- this.tickRateCorrente = 0;
2977
- this.latenzaCorrente = null;
2978
- this.ultimoInput = null;
2979
- this.inputInviato = null;
2980
- this.timerInput = null;
2981
- this.ultimoInvioGioco = -Infinity;
2982
- this.inviiGioco = [];
2983
- this.seedCorrente = 0;
2984
- this.statusCorrente = "lobby";
2985
- this.giocatoriCorrenti = [];
2986
- this.youCorrente = "";
2987
- this.hostCorrente = null;
2988
- this.resultCorrente = null;
2989
- this.delaySpettatore = 0;
2990
- this.socket = null;
2991
- this.seq = 0;
2992
- this.scartoOrario = 0;
2993
- this.timerPing = null;
2994
- this.timerRiconnessione = null;
2995
- this.timerFlush = null;
2996
- this.flushInCorso = false;
2997
- this.flushRichiesto = false;
2998
- this.ritardoIndice = 0;
2999
- this.tempoRiconnessione = 0;
3000
- this.resyncRichiesto = false;
3001
- this.terminata = false;
3002
- this.lasciata = false;
3003
- this.prontaRisolta = false;
3004
- this.welcomeRicevuto = false;
3005
- this.rosterRicevuto = false;
3006
- this.timerRoster = null;
3007
- this.risolviPronta = () => void 0;
3008
- this.rifiutaPronta = () => void 0;
3009
- this.ascoltatoriStato = /* @__PURE__ */ new Set();
3010
- this.ascoltatoriGiocatori = /* @__PURE__ */ new Set();
3011
- this.ascoltatoriStatus = /* @__PURE__ */ new Set();
3012
- this.ascoltatoriMessaggi = /* @__PURE__ */ new Set();
3013
- this.promessaPronta = new Promise((resolve, reject) => {
3014
- this.risolviPronta = resolve;
3015
- this.rifiutaPronta = reject;
3016
- });
3017
- this.voice = new VoceClient({
3018
- invia: (message) => this.invia(message),
3019
- connessa: () => this.socket?.readyState === APERTO && this.welcomeRicevuto && !this.terminata && !this.lasciata,
3020
- you: () => this.youCorrente,
3021
- giocatori: () => this.copiaGiocatori(),
3022
- rosterPronto: () => {
3023
- this.rosterRicevuto = true;
3024
- this.risolviProntaSePossibile();
3025
- }
3026
- }, dipendenze, dipendenze.voce);
3027
- if (spettatore) this.rosterRicevuto = true;
3028
- this.apri(url);
3029
- }
3030
- get mode() {
3031
- return this.meta.mode;
3032
- }
3033
- get countdownAt() {
3034
- return this.meta.countdownAt;
3035
- }
3036
- get connection() {
3037
- return this.meta.connection;
3038
- }
3039
- get metadata() {
3040
- return structuredClone(this.meta);
3041
- }
3042
- get queuedScores() {
3043
- return structuredClone(this.scores);
3044
- }
3045
- onMetadata(listener) {
3046
- this.metaListeners.add(listener);
3047
- return () => this.metaListeners.delete(listener);
3048
- }
3049
- onConnection(listener) {
3050
- this.connectionListeners.add(listener);
3051
- return () => this.connectionListeners.delete(listener);
3052
- }
3053
- onError(listener) {
3054
- this.errorListeners.add(listener);
3055
- return () => this.errorListeners.delete(listener);
3056
- }
3057
- onScoreQueued(listener) {
3058
- this.scoreListeners.add(listener);
3059
- return () => this.scoreListeners.delete(listener);
3060
- }
3061
- metadataChanged(change) {
3062
- const old = this.meta.connection;
3063
- this.meta = { ...this.meta, ...change };
3064
- this.notifica(this.metaListeners, this.metadata);
3065
- if (old !== this.meta.connection) this.notifica(this.connectionListeners, this.meta.connection);
3066
- }
3067
- initialMetadata(room) {
3068
- this.metadataChanged({
3069
- host: room.host,
3070
- mode: room.mode,
3071
- countdownAt: room.countdownAt ?? null,
3072
- rematch: room.rematch ?? null,
3073
- configuration: room.configuration ?? null,
3074
- connection: "connected",
3075
- closedCode: null
3076
- });
3077
- }
3078
- requestRole(role) {
3079
- if (typeof role !== "string" || role.length < 1 || role.length > 32) return Promise.reject(creaErrore("invalid_role", "The role is not valid."));
3080
- if (this.connection !== "connected" || this.status !== "playing" || !this.meta.configuration?.requestRole) {
3081
- return Promise.reject(creaErrore("role_change_unavailable", "Roles cannot be requested right now."));
3082
- }
3083
- if (this.roleRequests.size >= 8) return Promise.reject(creaErrore("rate_limited", "Too many role requests."));
3084
- const r = ++this.roleId;
3085
- return new Promise((resolve, reject) => {
3086
- const timer = this.dipendenze.setTimeout(() => {
3087
- this.roleRequests.delete(r);
3088
- reject(creaErrore("timeout", "The role request timed out."));
3089
- }, 5e3);
3090
- this.roleRequests.set(r, { resolve, reject, timer });
3091
- try {
3092
- this.invia({ t: "request-role", r, role });
3093
- } catch (error) {
3094
- this.dipendenze.clearTimeout(timer);
3095
- this.roleRequests.delete(r);
3096
- reject(error);
3097
- }
3098
- });
3099
- }
3100
- clearRoleRequests() {
3101
- for (const request of this.roleRequests.values()) {
3102
- this.dipendenze.clearTimeout(request.timer);
3103
- request.reject(creaErrore("offline", "The room connection ended."));
3104
- }
3105
- this.roleRequests.clear();
3106
- }
3107
- disconnect() {
3108
- if (this.lasciata) return;
3109
- this.lasciata = true;
3110
- const socket = this.socket;
3111
- this.socket = null;
3112
- this.voice.termina();
3113
- this.fermaInput();
3114
- this.fermaPing();
3115
- this.fermaRiconnessione();
3116
- this.clearRoleRequests();
3117
- if (this.timerRoster !== null) this.dipendenze.clearTimeout(this.timerRoster);
3118
- socket?.close(1e3);
3119
- this.segnalaStanza(null);
3120
- this.metadataChanged({ connection: "disconnected", closedCode: null });
3121
- if (!this.prontaRisolta) {
3122
- this.prontaRisolta = true;
3123
- this.rifiutaPronta(creaErrore("cancelled", "The room was disconnected."));
3124
- }
3125
- }
3126
- get state() {
3127
- return this.statoPubblico;
3128
- }
3129
- get tick() {
3130
- return this.tickCorrente;
3131
- }
3132
- get tickRate() {
3133
- return this.tickRateCorrente;
3134
- }
3135
- get latency() {
3136
- return this.latenzaCorrente;
3137
- }
3138
- get seed() {
3139
- return this.seedCorrente;
3140
- }
3141
- get status() {
3142
- return this.statusCorrente;
3143
- }
3144
- get players() {
3145
- return this.copiaGiocatori();
3146
- }
3147
- get you() {
3148
- return this.youCorrente;
3149
- }
3150
- get host() {
3151
- return this.hostCorrente;
3152
- }
3153
- get code() {
3154
- return this.codice;
3155
- }
3156
- get result() {
3157
- return this.resultCorrente;
3158
- }
3159
- get delayMs() {
3160
- return this.delaySpettatore;
3161
- }
3162
- pronta() {
3163
- return this.promessaPronta;
3164
- }
3165
- invite() {
3166
- return { code: this.codice, url: new URL(`/r/${this.codice}`, this.dipendenze.appOrigin).href };
3167
- }
3168
- onState(listener) {
3169
- this.ascoltatoriStato.add(listener);
3170
- return () => {
3171
- this.ascoltatoriStato.delete(listener);
3172
- };
3173
- }
3174
- onPlayers(listener) {
3175
- this.ascoltatoriGiocatori.add(listener);
3176
- return () => {
3177
- this.ascoltatoriGiocatori.delete(listener);
3178
- };
3179
- }
3180
- onStatus(listener) {
3181
- this.ascoltatoriStatus.add(listener);
3182
- return () => {
3183
- this.ascoltatoriStatus.delete(listener);
3184
- };
3185
- }
3186
- onMessage(listener) {
3187
- this.ascoltatoriMessaggi.add(listener);
3188
- return () => {
3189
- this.ascoltatoriMessaggi.delete(listener);
3190
- };
3191
- }
3192
- send(message) {
3193
- if (this.statusCorrente === "finished") return;
3194
- const prossimo = this.seq + 1;
3195
- this.invia({ t: "msg", seq: prossimo, m: message });
3196
- this.seq = prossimo;
3197
- this.ultimoInvioGioco = this.dipendenze.ora();
3198
- this.inviiGioco = [...this.inviiGioco.slice(-(MESSAGGI_GIOCO_AL_SECONDO - 1)), this.ultimoInvioGioco];
3199
- }
3200
- input(value) {
3201
- if (this.terminata || this.lasciata || this.statusCorrente === "finished") return;
3202
- try {
3203
- const serializzato = JSON.stringify(value);
3204
- if (serializzato === void 0) throw new TypeError();
3205
- this.ultimoInput = serializzato;
3206
- } catch {
3207
- throw creaErrore("invalid_request", "Room input must be valid JSON.");
3208
- }
3209
- this.programmaInput();
3210
- }
3211
- pulisciInput() {
3212
- this.fermaInput();
3213
- this.ultimoInput = this.inputInviato = null;
3214
- this.ultimoInvioGioco = -Infinity;
3215
- this.inviiGioco = [];
3216
- }
3217
- fermaInput() {
3218
- if (this.timerInput !== null) this.dipendenze.clearTimeout(this.timerInput);
3219
- this.timerInput = null;
3220
- }
3221
- programmaInput() {
3222
- if (this.timerInput !== null || this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3223
- const ora = this.dipendenze.ora();
3224
- const frequenza = this.tickRateCorrente > 0 ? Math.min(MESSAGGI_GIOCO_AL_SECONDO, this.tickRateCorrente) : MESSAGGI_GIOCO_AL_SECONDO;
3225
- const periodo = 1e3 / frequenza;
3226
- this.inviiGioco = this.inviiGioco.filter((at) => ora - at < 1e3);
3227
- const spazio = this.inviiGioco.length >= MESSAGGI_GIOCO_AL_SECONDO ? this.inviiGioco[0] + 1e3 : ora;
3228
- const prossimo = Number.isFinite(this.ultimoInvioGioco) ? this.ultimoInvioGioco + periodo : ora + periodo;
3229
- this.timerInput = this.dipendenze.setTimeout(() => {
3230
- this.timerInput = null;
3231
- if (this.ultimoInput === null || this.ultimoInput === this.inputInviato || !this.welcomeRicevuto || this.socket?.readyState !== APERTO || this.terminata || this.lasciata) return;
3232
- const adesso = this.dipendenze.ora();
3233
- if (adesso < this.ultimoInvioGioco + periodo || this.inviiGioco.filter((at) => adesso - at < 1e3).length >= MESSAGGI_GIOCO_AL_SECONDO) {
3234
- this.programmaInput();
3235
- return;
3236
- }
3237
- const valore = this.ultimoInput;
3238
- try {
3239
- this.send(JSON.parse(valore));
3240
- this.inputInviato = valore;
3241
- } catch {
3242
- }
3243
- }, Math.max(0, Math.ceil(Math.max(prossimo, spazio) - ora)));
3244
- }
3245
- aggiornaTickRate(value) {
3246
- if (value === void 0 || !Number.isInteger(value) || value < 0 || value > 60 || value === this.tickRateCorrente) return;
3247
- this.tickRateCorrente = value;
3248
- this.fermaInput();
3249
- this.programmaInput();
3250
- }
3251
- ready(ready) {
3252
- this.invia({ t: "ready", ready });
3253
- }
3254
- setRole(role) {
3255
- this.invia({ t: "role", role });
3256
- }
3257
- setTeam(team) {
3258
- this.invia({ t: "team", team });
3259
- }
3260
- start() {
3261
- this.invia({ t: "start" });
3262
- }
3263
- restart() {
3264
- if (this.statusCorrente !== "finished") throw creaErrore("rematch_unavailable", "This room is not waiting for a rematch.");
3265
- this.invia({ t: "restart" });
3266
- }
3267
- leave() {
3268
- if (this.lasciata) return;
3269
- if (!this.spettatore) this.voice.leave();
3270
- this.lasciata = true;
3271
- this.segnalaStanza(null);
3272
- if (this.socket?.readyState === APERTO) {
3273
- const socket = this.socket;
3274
- this.invia({ t: "leave" });
3275
- if (this.spettatore) socket.close(1e3);
3276
- }
3277
- this.termina(1e3);
3278
- }
3279
- serverTime() {
3280
- return this.dipendenze.ora() + this.scartoOrario;
3281
- }
3282
- copiaGiocatori() {
3283
- return this.giocatoriCorrenti.map((player) => ({ ...player }));
3284
- }
3285
- notifica(listeners, ...args) {
3286
- for (const listener of listeners) {
3287
- try {
3288
- listener(...args);
3289
- } catch {
3290
- }
3291
- }
3292
- }
3293
- invia(message) {
3294
- if (this.socket?.readyState !== APERTO) {
3295
- throw creaErrore("offline", "The room is reconnecting.");
3296
- }
3297
- let frame;
3298
- try {
3299
- frame = JSON.stringify(message);
3300
- } catch {
3301
- throw creaErrore("invalid_request", "Room messages must be valid JSON.");
3302
- }
3303
- this.socket.send(frame);
3304
- }
3305
- apri(url) {
3306
- let socket;
3307
- try {
3308
- socket = this.dipendenze.apriSocket(url);
3309
- } catch {
3310
- this.programmaRiconnessione();
3311
- return;
3312
- }
3313
- this.socket = socket;
3314
- socket.addEventListener("open", () => {
3315
- if (this.socket === socket) this.avviaPing();
3316
- });
3317
- socket.addEventListener("message", (evento) => {
3318
- if (this.socket === socket && typeof evento.data === "string") this.ricevi(evento.data);
3319
- });
3320
- socket.addEventListener("close", (evento) => {
3321
- if (this.socket === socket) this.chiuso(evento.code, evento.reason);
3322
- });
3323
- }
3324
- avviaPing() {
3325
- if (this.timerPing !== null) this.dipendenze.clearInterval(this.timerPing);
3326
- this.timerPing = this.dipendenze.setInterval(() => {
3327
- if (this.socket?.readyState !== APERTO) return;
3328
- try {
3329
- this.invia({ t: "ping", c: this.dipendenze.ora() });
3330
- } catch {
3331
- }
3332
- }, INTERVALLO_PING);
3333
- }
3334
- fermaPing() {
3335
- if (this.timerPing === null) return;
3336
- this.dipendenze.clearInterval(this.timerPing);
3337
- this.timerPing = null;
3338
- }
3339
- ricevi(frame) {
3340
- let dati;
3341
- try {
3342
- const value = JSON.parse(frame);
3343
- const oggetto2 = record3(value);
3344
- if (oggetto2 === null || typeof oggetto2.t !== "string") return;
3345
- dati = oggetto2;
3346
- } catch {
3347
- return;
3348
- }
3349
- try {
3350
- if (dati.t === "watching") this.riceviWatching(dati);
3351
- else if (dati.t === "welcome") this.riceviWelcome(dati);
3352
- else if (dati.t === "players") this.riceviGiocatori(dati.players, dati.host);
3353
- else if (dati.t === "status") this.riceviStatus(dati);
3354
- else if (dati.t === "state") this.riceviDiff(dati);
3355
- else if (dati.t === "snapshot") this.riceviSnapshot(dati);
3356
- else if (dati.t === "msg") this.notifica(this.ascoltatoriMessaggi, copiaJson(dati.m));
3357
- else if (dati.t === "pong") this.riceviPong(dati);
3358
- else if (dati.t === "error") this.notifica(this.errorListeners, { code: dati.code, message: dati.message });
3359
- else if (dati.t === "flush") this.richiediFlush();
3360
- else if (dati.t === "score-queued" && !this.spettatore) {
3361
- this.scores.push(structuredClone(dati.score));
3362
- this.scores = this.scores.slice(-32);
3363
- this.notifica(this.scoreListeners, structuredClone(dati.score));
3364
- } else if (dati.t === "role-result") {
3365
- const request = this.roleRequests.get(dati.r);
3366
- if (request) {
3367
- this.dipendenze.clearTimeout(request.timer);
3368
- this.roleRequests.delete(dati.r);
3369
- if (dati.ok) request.resolve();
3370
- else request.reject(creaErrore(dati.code ?? "role_change_refused", "The role change was not accepted."));
3371
- }
3372
- } else if (dati.t === "voice") this.voice.ricevi(dati);
3373
- } catch {
3374
- if (dati.t === "state" || dati.t === "snapshot") this.chiediResync();
3375
- }
3376
- }
3377
- riceviWatching(dati) {
3378
- const room = dati.room;
3379
- if (!this.spettatore || room.id !== this.roomId) return;
3380
- this.aggiornaTickRate(room.tickRate);
3381
- this.seedCorrente = room.seed;
3382
- this.hostCorrente = room.host;
3383
- this.statusCorrente = room.status;
3384
- this.resultCorrente = copiaJson(room.result ?? null);
3385
- if (room.status === "finished") this.pulisciInput();
3386
- this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
3387
- this.delaySpettatore = dati.delayMs;
3388
- this.aggiornaStato(dati.state, room.tick, room.serverTime);
3389
- this.scartoOrario = room.serverTime - this.dipendenze.ora();
3390
- this.resyncRichiesto = false;
3391
- this.welcomeRicevuto = true;
3392
- this.ritardoIndice = 0;
3393
- this.tempoRiconnessione = 0;
3394
- this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
3395
- this.notifica(
3396
- this.ascoltatoriStatus,
3397
- this.statusCorrente,
3398
- this.resultCorrente,
3399
- room.serverTime
3400
- );
3401
- this.initialMetadata(room);
3402
- this.programmaInput();
3403
- this.risolviProntaSePossibile();
3404
- }
3405
- riceviWelcome(dati) {
3406
- const room = dati.room;
3407
- if (room.id !== this.roomId) return;
3408
- this.youCorrente = dati.you;
3409
- this.aggiornaTickRate(room.tickRate);
3410
- this.seedCorrente = room.seed;
3411
- this.hostCorrente = room.host;
3412
- this.statusCorrente = room.status;
3413
- this.resultCorrente = copiaJson(room.result ?? null);
3414
- if (room.status === "finished") this.pulisciInput();
3415
- this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
3416
- this.aggiornaStato(dati.state, room.tick, room.serverTime);
3417
- this.scartoOrario = room.serverTime - this.dipendenze.ora();
3418
- this.resyncRichiesto = false;
3419
- this.welcomeRicevuto = true;
3420
- if (!this.rosterRicevuto && this.timerRoster === null) {
3421
- this.timerRoster = this.dipendenze.setTimeout(() => {
3422
- this.timerRoster = null;
3423
- this.rosterRicevuto = true;
3424
- this.risolviProntaSePossibile();
3425
- }, ATTESA_ROSTER);
3426
- }
3427
- this.ritardoIndice = 0;
3428
- this.tempoRiconnessione = 0;
3429
- this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
3430
- this.voice.giocatoriCambiati();
3431
- this.voice.socketRiconnesso();
3432
- this.notifica(
3433
- this.ascoltatoriStatus,
3434
- this.statusCorrente,
3435
- this.resultCorrente,
3436
- room.serverTime
3437
- );
3438
- this.initialMetadata(room);
3439
- this.programmaInput();
3440
- this.risolviProntaSePossibile();
3441
- }
3442
- riceviGiocatori(value, host) {
3443
- this.giocatoriCorrenti = value.map((player) => ({ ...player }));
3444
- if (host !== void 0) this.hostCorrente = host;
3445
- else if (!this.giocatoriCorrenti.some(
3446
- (player) => player.id === this.hostCorrente && player.connected
3447
- )) {
3448
- this.hostCorrente = this.giocatoriCorrenti.find((player) => player.connected)?.id ?? null;
3449
- }
3450
- this.metadataChanged({ host: this.hostCorrente });
3451
- this.notifica(this.ascoltatoriGiocatori, this.copiaGiocatori());
3452
- this.voice.giocatoriCambiati();
3453
- }
3454
- riceviStatus(dati) {
3455
- this.statusCorrente = dati.status;
3456
- if (dati.host !== void 0) this.hostCorrente = dati.host;
3457
- this.resultCorrente = copiaJson(dati.result);
3458
- if (dati.status === "finished") {
3459
- this.pulisciInput();
3460
- this.clearRoleRequests();
3461
- }
3462
- if (dati.status === "ended") {
3463
- this.terminata = true;
3464
- this.clearRoleRequests();
3465
- this.segnalaStanza(null);
3466
- if (!this.spettatore) this.voice.termina();
3467
- this.fermaPing();
3468
- this.fermaRiconnessione();
3469
- this.fermaInput();
3470
- this.ultimoInput = null;
3471
- }
3472
- this.metadataChanged({
3473
- rematch: dati.rematch ?? null,
3474
- host: this.hostCorrente,
3475
- countdownAt: dati.countdownAt ?? (dati.status === "countdown" ? dati.at : null),
3476
- ...dati.status === "ended" ? { connection: "ended", closedCode: 4004 } : {}
3477
- });
3478
- this.notifica(this.ascoltatoriStatus, this.statusCorrente, this.resultCorrente, dati.at);
3479
- }
3480
- riceviDiff(dati) {
3481
- this.aggiornaTickRate(dati.tickRate);
3482
- if (dati.base !== this.tickCorrente) {
3483
- this.chiediResync();
3484
- return;
3485
- }
3486
- const risultato = applicaPatch(this.statoSincronizzato, dati.patch);
3487
- if (!risultato.ok) {
3488
- this.chiediResync();
3489
- return;
3490
- }
3491
- this.resyncRichiesto = false;
3492
- this.aggiornaStato(risultato.state, dati.tick, dati.serverTime);
3493
- }
3494
- riceviSnapshot(dati) {
3495
- if (dati.tick < this.tickCorrente) return;
3496
- this.aggiornaTickRate(dati.tickRate);
3497
- this.resyncRichiesto = false;
3498
- this.aggiornaStato(dati.state, dati.tick, dati.serverTime);
3499
- }
3500
- aggiornaStato(state, tick, serverTime) {
3501
- this.statoSincronizzato = copiaJson(state);
3502
- this.statoPubblico = copiaJson(state);
3503
- this.tickCorrente = tick;
3504
- this.notifica(this.ascoltatoriStato, this.statoPubblico, tick, serverTime);
3505
- }
3506
- chiediResync() {
3507
- if (this.resyncRichiesto || this.socket?.readyState !== APERTO) return;
3508
- this.resyncRichiesto = true;
3509
- try {
3510
- this.invia({ t: "resync" });
3511
- } catch {
3512
- this.resyncRichiesto = false;
3513
- }
3514
- }
3515
- riceviPong(dati) {
3516
- const ora = this.dipendenze.ora();
3517
- if (!Number.isFinite(dati.c) || !Number.isFinite(dati.s) || dati.c > ora) return;
3518
- const rtt = ora - dati.c;
3519
- this.latenzaCorrente = this.latenzaCorrente === null ? rtt : this.latenzaCorrente * 0.8 + rtt * 0.2;
3520
- this.scartoOrario = dati.s - (dati.c + ora) / 2;
3521
- }
3522
- chiuso(code, reason) {
3523
- this.socket = null;
3524
- this.welcomeRicevuto = false;
3525
- this.latenzaCorrente = null;
3526
- this.fermaInput();
3527
- this.inputInviato = null;
3528
- this.ultimoInvioGioco = -Infinity;
3529
- this.inviiGioco = [];
3530
- this.fermaPing();
3531
- if (this.lasciata || this.terminata) return;
3532
- if (CHIUSURE_DEFINITIVE.has(code)) {
3533
- const errore = code === 4009 && reason === "message_too_large" ? "message_too_large" : void 0;
3534
- if (errore) this.notifica(this.errorListeners, { code: errore, message: "The room message is too large." });
3535
- this.termina(code, errore);
3536
- return;
3537
- }
3538
- this.clearRoleRequests();
3539
- if (!this.spettatore) this.voice.socketDisconnesso();
3540
- this.programmaRiconnessione();
3541
- }
3542
- programmaRiconnessione() {
3543
- if (this.terminata || this.lasciata || this.timerRiconnessione !== null) return;
3544
- this.metadataChanged({ connection: "reconnecting" });
3545
- const indice = Math.min(this.ritardoIndice, RITARDI_RICONNESSIONE2.length - 1);
3546
- const ritardo = RITARDI_RICONNESSIONE2[indice];
3547
- if (this.tempoRiconnessione + ritardo > GRAZIA_RICONNESSIONE) {
3548
- this.termina("timeout");
3549
- return;
3550
- }
3551
- this.ritardoIndice++;
3552
- this.tempoRiconnessione += ritardo;
3553
- this.timerRiconnessione = this.dipendenze.setTimeout(() => {
3554
- this.timerRiconnessione = null;
3555
- void this.riconnetti();
3556
- }, ritardo);
3557
- }
3558
- async riconnetti() {
3559
- if (this.terminata || this.lasciata) return;
3560
- try {
3561
- const ingresso = this.spettatore ? await this.api.watchRoom(this.roomId) : await this.api.joinRoom(this.roomId);
3562
- if (this.terminata || this.lasciata) return;
3563
- const codiceCambiato = this.codice !== ingresso.code;
3564
- this.codice = ingresso.code;
3565
- if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {
3566
- this.segnalaStanza({ code: this.codice });
3567
- }
3568
- this.apri(ingresso.url);
3569
- } catch (error) {
3570
- if (error instanceof Error && "code" in error && ["version_mismatch", "version_outdated", "room_not_found"].includes(String(error.code))) {
3571
- this.notifica(this.errorListeners, { code: String(error.code), message: error.message });
3572
- this.termina(4004, String(error.code));
3573
- } else this.programmaRiconnessione();
3574
- }
3575
- }
3576
- fermaRiconnessione() {
3577
- if (this.timerRiconnessione === null) return;
3578
- this.dipendenze.clearTimeout(this.timerRiconnessione);
3579
- this.timerRiconnessione = null;
3580
- }
3581
- termina(code, errore) {
3582
- this.clearRoleRequests();
3583
- this.metadataChanged({ connection: code === 1e3 ? "disconnected" : code === 4006 ? "replaced" : "closed", closedCode: typeof code === "number" ? code : null });
3584
- const risultato = { closed: code };
3585
- const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
3586
- this.terminata = true;
3587
- this.fermaInput();
3588
- this.ultimoInput = null;
3589
- this.segnalaStanza(null);
3590
- this.statusCorrente = "ended";
3591
- this.resultCorrente = risultato;
3592
- if (!this.spettatore) this.voice.termina();
3593
- this.fermaPing();
3594
- this.fermaRiconnessione();
3595
- if (cambiato) this.notifica(this.ascoltatoriStatus, "ended", risultato, this.serverTime());
3596
- if (!this.prontaRisolta) {
3597
- this.prontaRisolta = true;
3598
- const codici = {
3599
- 4003: "kicked",
3600
- 4004: "room_ended",
3601
- 4005: "version_closed",
3602
- 4006: "replaced",
3603
- 4008: "rate_limited",
3604
- 4009: "invalid_request"
3605
- };
3606
- const erroreCode = errore ?? (typeof code === "number" ? codici[code] ?? "offline" : "offline");
3607
- this.rifiutaPronta(creaErrore(erroreCode, "The room connection ended."));
3608
- }
3609
- }
3610
- risolviProntaSePossibile() {
3611
- if (this.prontaRisolta || !this.welcomeRicevuto || !this.rosterRicevuto) return;
3612
- if (this.timerRoster !== null) {
3613
- this.dipendenze.clearTimeout(this.timerRoster);
3614
- this.timerRoster = null;
3615
- }
3616
- this.prontaRisolta = true;
3617
- if (!this.spettatore && !this.terminata && !this.lasciata) {
3618
- this.segnalaStanza({ code: this.codice });
3619
- }
3620
- this.risolviPronta();
3621
- }
3622
- richiediFlush() {
3623
- this.flushRichiesto = true;
3624
- if (this.flushInCorso || this.timerFlush !== null) return;
3625
- this.timerFlush = this.dipendenze.setTimeout(() => {
3626
- this.timerFlush = null;
3627
- void this.eseguiFlush();
3628
- }, RITARDO_FLUSH);
3629
- }
3630
- async eseguiFlush() {
3631
- if (this.flushInCorso || !this.flushRichiesto) return;
3632
- this.flushInCorso = true;
3633
- this.flushRichiesto = false;
3634
- try {
3635
- await this.api.flush(this.roomId);
3636
- } catch {
3637
- } finally {
3638
- this.flushInCorso = false;
3639
- if (this.flushRichiesto) this.richiediFlush();
3640
- }
3641
- }
3642
- };
3643
- function creaStanzeOffline(invited = null) {
3644
- return {
3645
- invited,
3646
- reload() {
3647
- if (typeof window !== "undefined") window.location.reload();
3648
- },
3649
- onError() {
3650
- return () => {
3651
- };
3652
- },
3653
- async create() {
3654
- throw erroreOffline();
3655
- },
3656
- async join() {
3657
- throw erroreOffline();
3658
- },
3659
- async watch() {
3660
- throw erroreOffline();
3661
- },
3662
- async match() {
3663
- throw erroreOffline();
3664
- }
3665
- };
3666
- }
3667
- function creaGestoreStanze(input, invited) {
3668
- let reloadTarget;
3669
- const errors = /* @__PURE__ */ new Set();
3670
- const api = creaApiLive({ ...input, onVersionError(error, target) {
3671
- reloadTarget = target;
3672
- for (const listener of errors) {
3673
- try {
3674
- listener(error);
3675
- } catch {
3676
- }
3677
- }
3678
- } });
3679
- let haSegnalato = false;
3680
- let ultimoCodice = null;
3681
- const segnalaStanza = (room) => {
3682
- const codice = room?.code ?? null;
3683
- if (haSegnalato && codice === ultimoCodice) return;
3684
- haSegnalato = true;
3685
- ultimoCodice = codice;
3686
- input.segnalaStanza?.(room);
3687
- };
3688
- const collega = async (ingresso) => {
3689
- const stanza = new StanzaClient(
3690
- ingresso.roomId,
3691
- ingresso.code,
3692
- ingresso.url,
3693
- input,
3694
- api,
3695
- segnalaStanza
3696
- );
3697
- await stanza.pronta();
3698
- return stanza;
3699
- };
3700
- const guarda = async (ingresso) => {
3701
- const stanza = new StanzaClient(
3702
- ingresso.roomId,
3703
- ingresso.code,
3704
- ingresso.url,
3705
- input,
3706
- api,
3707
- () => void 0,
3708
- true
3709
- );
3710
- await stanza.pronta();
3711
- return {
3712
- get mode() {
3713
- return stanza.mode;
3714
- },
3715
- get countdownAt() {
3716
- return stanza.countdownAt;
3717
- },
3718
- get connection() {
3719
- return stanza.connection;
3720
- },
3721
- get metadata() {
3722
- return stanza.metadata;
3723
- },
3724
- onMetadata: (listener) => stanza.onMetadata(listener),
3725
- onConnection: (listener) => stanza.onConnection(listener),
3726
- disconnect: () => stanza.disconnect(),
3727
- get state() {
3728
- return stanza.state;
3729
- },
3730
- get tick() {
3731
- return stanza.tick;
3732
- },
3733
- get tickRate() {
3734
- return stanza.tickRate;
3735
- },
3736
- get latency() {
3737
- return stanza.latency;
3738
- },
3739
- get seed() {
3740
- return stanza.seed;
3741
- },
3742
- get status() {
3743
- return stanza.status;
3744
- },
3745
- get players() {
3746
- return stanza.players;
3747
- },
3748
- get host() {
3749
- return stanza.host;
3750
- },
3751
- get code() {
3752
- return stanza.code;
3753
- },
3754
- get result() {
3755
- return stanza.result;
3756
- },
3757
- get delayMs() {
3758
- return stanza.delayMs;
3759
- },
3760
- onState: (listener) => stanza.onState(listener),
3761
- onPlayers: (listener) => stanza.onPlayers(listener),
3762
- onStatus: (listener) => stanza.onStatus(listener),
3763
- onMessage: (listener) => stanza.onMessage(listener),
3764
- leave: () => {
3765
- stanza.leave();
3766
- },
3767
- serverTime: () => stanza.serverTime()
3768
- };
3769
- };
3770
- const attendiMatch = (url, options) => new Promise((resolve, reject) => {
3771
- let socket;
3772
- let conclusa = false;
3773
- const pulisci = () => {
3774
- socket.removeEventListener("message", ricevi);
3775
- socket.removeEventListener("close", chiuso);
3776
- socket.removeEventListener("error", caduto);
3777
- options.signal?.removeEventListener("abort", annulla);
3778
- };
3779
- const chiudi = () => {
3780
- try {
3781
- socket.close(1e3);
3782
- } catch {
3783
- }
3784
- };
3785
- const fallisci = (errore, chiudiSocket) => {
3786
- if (conclusa) return;
3787
- conclusa = true;
3788
- pulisci();
3789
- if (chiudiSocket) chiudi();
3790
- reject(errore);
3791
- };
3792
- function annulla() {
3793
- fallisci(
3794
- creaErrore("cancelled", "The matchmaking search was cancelled."),
3795
- true
3796
- );
3797
- }
3798
- function chiuso() {
3799
- fallisci(erroreOffline(), false);
3800
- }
3801
- function caduto() {
3802
- fallisci(erroreOffline(), true);
3803
- }
3804
- function ricevi(evento) {
3805
- let dati = null;
3806
- try {
3807
- dati = typeof evento.data === "string" ? record3(JSON.parse(evento.data)) : null;
3808
- } catch {
3809
- }
3810
- if (dati === null || typeof dati.t !== "string") {
3811
- fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
3812
- return;
3813
- }
3814
- if (dati.t === "waiting") {
3815
- if (!Number.isInteger(dati.players) || !Number.isInteger(dati.min) || !Number.isInteger(dati.max)) {
3816
- fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
3817
- return;
3818
- }
3819
- try {
3820
- options.onWaiting?.({
3821
- players: dati.players,
3822
- min: dati.min,
3823
- max: dati.max
3824
- });
3825
- } catch {
3826
- }
3827
- return;
3828
- }
3829
- if (dati.t === "matched") {
3830
- if (!ingressoValido(dati)) {
3831
- fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
3832
- return;
3833
- }
3834
- conclusa = true;
3835
- pulisci();
3836
- chiudi();
3837
- resolve(dati);
3838
- return;
3839
- }
3840
- if (dati.t === "no_match") {
3841
- fallisci(creaErrore("no_match", "No match was found before the timeout."), true);
3842
- return;
3843
- }
3844
- if (dati.t === "error") {
3845
- fallisci(creaErrore(
3846
- typeof dati.code === "string" ? dati.code : "internal_error",
3847
- typeof dati.message === "string" ? dati.message : "The matchmaking service could not complete the search."
3848
- ), true);
3849
- return;
3850
- }
3851
- if (dati.t !== "pong") {
3852
- fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
3853
- }
3854
- }
3855
- try {
3856
- socket = input.apriSocket(url);
3857
- } catch {
3858
- reject(erroreOffline());
3859
- return;
3860
- }
3861
- socket.addEventListener("message", ricevi);
3862
- socket.addEventListener("close", chiuso);
3863
- socket.addEventListener("error", caduto);
3864
- options.signal?.addEventListener("abort", annulla, { once: true });
3865
- if (options.signal?.aborted === true) annulla();
3866
- });
3867
- return {
3868
- invited,
3869
- reload() {
3870
- input.reload?.(reloadTarget);
3871
- },
3872
- onError(listener) {
3873
- errors.add(listener);
3874
- return () => {
3875
- errors.delete(listener);
3876
- };
3877
- },
3878
- async create(options) {
3879
- return collega(await api.create(options.mode));
3880
- },
3881
- async join(code) {
3882
- const scelto = code ?? invited;
3883
- if (scelto === null || scelto === void 0 || scelto.length === 0) {
3884
- throw creaErrore("invalid_request", "A room invitation code is required.");
3885
- }
3886
- return collega(await api.joinCode(scelto));
3887
- },
3888
- async watch(code) {
3889
- if (typeof code !== "string" || code.length === 0) {
3890
- throw creaErrore("invalid_request", "A room invitation code is required.");
3891
- }
3892
- return guarda(await api.watchCode(code));
3893
- },
3894
- async match(options) {
3895
- const annullata = () => options.signal?.aborted === true;
3896
- if (annullata()) {
3897
- throw creaErrore("cancelled", "The matchmaking search was cancelled.");
3898
- }
3899
- const risposta = await api.match(options);
3900
- if (annullata()) {
3901
- throw creaErrore("cancelled", "The matchmaking search was cancelled.");
3902
- }
3903
- return collega(await attendiMatch(risposta.url, options));
3904
- }
3905
- };
3906
- }
3907
-
3908
- // src/standalone.ts
3909
- var PREFISSO = "caisual:save:";
3910
- var CHIAVE_VALIDA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
3911
- function verificaChiave(key) {
3912
- if (!CHIAVE_VALIDA.test(key)) {
3913
- throw creaErrore("invalid_request", "Save keys must use lowercase letters, numbers, underscores, or hyphens.");
3914
- }
3915
- }
3916
- function leggiSalvataggio(testo) {
3917
- if (testo === null) return null;
3918
- try {
3919
- return JSON.parse(testo);
3920
- } catch {
3921
- return null;
3922
- }
3923
- }
3924
- function chiavi(archivio) {
3925
- const risultato = [];
3926
- for (let indice = 0; indice < archivio.length; indice++) {
3927
- const key = archivio.key(indice);
3928
- if (key?.startsWith(PREFISSO)) risultato.push(key.slice(PREFISSO.length));
3929
- }
3930
- return risultato;
3931
- }
3932
- function creaSave(archivio, ora) {
3933
- const disponibile = () => {
3934
- if (archivio === null) throw erroreOffline();
3935
- return archivio;
3936
- };
3937
- return {
3938
- async set(key, value) {
3939
- verificaChiave(key);
3940
- const locale = disponibile();
3941
- const corpo = JSON.stringify({ value });
3942
- const bytes = new TextEncoder().encode(corpo).byteLength;
3943
- if (bytes > 262144) {
3944
- throw creaErrore("payload_too_large", "The save is larger than 262144 bytes.");
3945
- }
3946
- if (locale.getItem(PREFISSO + key) === null && chiavi(locale).length >= 32) {
3947
- throw creaErrore("save_limit", "A game can store at most 32 save keys.");
3948
- }
3949
- const voce = { value, bytes, updatedAt: ora() };
3950
- locale.setItem(PREFISSO + key, JSON.stringify(voce));
3951
- return { key, bytes, updatedAt: voce.updatedAt };
3952
- },
3953
- async get(key) {
3954
- verificaChiave(key);
3955
- return leggiSalvataggio(disponibile().getItem(PREFISSO + key))?.value ?? null;
3956
- },
3957
- async remove(key) {
3958
- verificaChiave(key);
3959
- disponibile().removeItem(PREFISSO + key);
3960
- },
3961
- async list() {
3962
- const locale = disponibile();
3963
- return chiavi(locale).flatMap((key) => {
3964
- const voce = leggiSalvataggio(locale.getItem(PREFISSO + key));
3965
- return voce === null ? [] : [{ key, bytes: voce.bytes, updatedAt: voce.updatedAt }];
3966
- }).sort((a, b) => a.key.localeCompare(b.key));
3967
- }
3968
- };
3969
- }
3970
- async function creaStandalone(input, invited = null) {
3971
- const startedAt = input.ora(), day = giornoUtc(startedAt);
3972
- const seed = await calcolaSeed(input.hostname, day, input.subtle);
3973
- return {
3974
- connected: false,
3975
- player: { id: "local", name: "Guest", guest: true },
3976
- daily: creaDaily({ day, seed, expiresAt: prossimaMezzanotteUtc(startedAt) }, input.ora, async () => {
3977
- const now = input.ora(), day2 = giornoUtc(now);
3978
- return { day: day2, seed: await calcolaSeed(input.hostname, day2, input.subtle), expiresAt: prossimaMezzanotteUtc(now) };
3979
- }),
3980
- time: { now: input.ora },
3981
- save: creaSave(input.archivio, input.ora),
3982
- board: {
3983
- async submit() {
3984
- return { accepted: false, reason: "offline", verified: false };
3985
- },
3986
- async top(_board, opzioni = {}) {
3987
- 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.");
3988
- return { day: opzioni.day ?? (opzioni.daily ? day : null), entries: [], me: null };
3989
- }
3990
- },
3991
- room: creaStanzeOffline(invited)
3992
- };
3993
- }
3994
-
3995
- // src/kit.ts
3996
- function leggiAppOrigin(documento) {
3997
- const valore = documento?.querySelector('meta[name="caisual-app"]')?.getAttribute("content");
3998
- if (valore === null || valore === void 0) return null;
3999
- try {
4000
- const url = new URL(valore);
4001
- return url.origin === valore && (url.protocol === "https:" || url.protocol === "http:") ? valore : null;
4002
- } catch {
4003
- return null;
4004
- }
4005
- }
4006
- function archivioReale() {
4007
- try {
4008
- return typeof localStorage === "undefined" ? null : localStorage;
4009
- } catch {
4010
- return null;
4011
- }
4012
- }
4013
- function dipendenzeReali2() {
4014
- return {
4015
- finestra: typeof window === "undefined" ? null : window,
4016
- documento: typeof document === "undefined" ? null : document,
4017
- fetcher: (input, init) => globalThis.fetch(input, init),
4018
- archivio: archivioReale(),
4019
- language: typeof navigator === "undefined" ? "en" : navigator.language,
4020
- pathname: typeof location === "undefined" ? "/" : location.pathname,
4021
- hostname: typeof location === "undefined" ? "" : location.hostname,
4022
- subtle: globalThis.crypto.subtle,
4023
- ora: Date.now,
4024
- sonda: () => probeDevice()
4025
- };
4026
- }
4027
- async function connetti(input) {
4028
- const appOrigin = leggiAppOrigin(input.documento);
4029
- const senzaPadre = input.finestra === null || input.finestra.parent === input.finestra;
4030
- if (appOrigin === null || senzaPadre) {
4031
- return localConnection(input);
4032
- }
4033
- const handshake = await attendiHandshake(
4034
- input.finestra,
4035
- appOrigin,
4036
- input.timeoutHandshake
4037
- );
4038
- if (handshake === null) return localConnection(input);
4039
- const biglietto = creaGestoreBiglietto(
4040
- handshake.ticket,
4041
- handshake.porta,
4042
- input.finestra,
4043
- input.ora,
4044
- input.timeoutRinnovo,
4045
- "portal"
4046
- );
4047
- const api = creaClienteApi(appOrigin, input.fetcher, biglietto);
4048
- const prima = input.ora();
4049
- let me;
4050
- try {
4051
- me = await api.me();
4052
- } catch {
4053
- const base2 = await creaStandalone(input, handshake.invite);
4054
- return installSession(base2, handshake, input);
4055
- }
4056
- const dopo = input.ora();
4057
- const scartoOrario = me.serverTime - (prima + dopo) / 2;
4058
- const room = handshake.live === null ? creaStanzeOffline(handshake.invite) : creaGestoreStanze({
4059
- appOrigin,
4060
- n: handshake.n,
4061
- reload: (target) => handshake.porta.postMessage({ type: "caisual:reload", target }),
4062
- liveOrigin: handshake.live,
4063
- fetcher: input.fetcher,
4064
- biglietto: creaGestoreBiglietto(
4065
- null,
4066
- handshake.porta,
4067
- input.finestra,
4068
- input.ora,
4069
- input.timeoutRinnovo,
4070
- "live"
4071
- ),
4072
- apriSocket(url) {
4073
- if (input.apriSocket !== void 0) return input.apriSocket(url);
4074
- if (typeof WebSocket === "undefined") throw erroreOffline();
4075
- return new WebSocket(url);
4076
- },
4077
- ora: input.ora,
4078
- setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout),
4079
- clearTimeout: (id) => globalThis.clearTimeout(id),
4080
- setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),
4081
- clearInterval: (id) => globalThis.clearInterval(id),
4082
- voce: input.voce,
4083
- segnalaStanza(room2) {
4084
- try {
4085
- handshake.porta.postMessage({ type: "caisual:room", room: room2 });
4086
- } catch {
4087
- }
4088
- }
4089
- }, handshake.invite);
4090
- const base = {
4091
- connected: true,
4092
- player: me.player,
4093
- daily: creaDaily(
4094
- { day: me.day, seed: me.seed, expiresAt: me.expiresAt ?? prossimaMezzanotteUtc(me.serverTime) },
4095
- () => input.ora() + scartoOrario,
4096
- async () => {
4097
- const next = await api.me();
4098
- return { day: next.day, seed: next.seed, expiresAt: next.expiresAt ?? prossimaMezzanotteUtc(next.serverTime) };
4099
- }
4100
- ),
4101
- time: { now: () => input.ora() + scartoOrario },
4102
- save: {
4103
- set: (key, value) => api.saveSet(key, value),
4104
- get: (key) => api.saveGet(key),
4105
- remove: (key) => api.saveRemove(key),
4106
- list: () => api.saveList()
4107
- },
4108
- board: {
4109
- async submit(board, score, opzioni = {}) {
4110
- try {
4111
- return await api.boardSubmit(board, score, opzioni.daily === true);
4112
- } catch (errore) {
4113
- if (typeof errore === "object" && errore !== null && "code" in errore && errore.code === "offline") return { accepted: false, reason: "offline", verified: false };
4114
- throw errore;
4115
- }
4116
- },
4117
- top: (board, opzioni = {}) => api.boardTop(board, opzioni)
4118
- },
4119
- room
4120
- };
4121
- return installSession(base, handshake, input);
4122
- }
4123
- function installSession(base, handshake, input) {
4124
- const coordinator = createSession(base, handshake?.overlay?.configuration ?? null, base.connected && handshake?.live != null);
4125
- if (handshake?.overlay) {
4126
- const dispose = attachKitBridge(handshake.porta, handshake.overlay, coordinator);
4127
- if (coordinator.session.capabilities.overlay && typeof window !== "undefined" && input?.finestra === window) window.addEventListener("pagehide", dispose, { once: true });
4128
- }
4129
- const preferences = handshake?.languagePreferences?.length ? handshake.languagePreferences : [handshake?.language ?? input?.language ?? "en"];
4130
- const language = resolveGameLanguage(preferences, handshake?.gameLanguages ?? (handshake?.overlay ? manifestLanguages(handshake.overlay.configuration.manifest) : void 0));
4131
- const uiLanguage = overlayLocale(handshake?.uiLanguage ?? handshake?.language ?? input?.language);
4132
- return {
4133
- ...base,
4134
- player: { ...base.player, language, uiLanguage },
4135
- text: createTextLoader(input?.fetcher ?? globalThis.fetch, language, input?.pathname),
4136
- room: coordinator.rooms,
4137
- session: coordinator.session,
4138
- overlay: coordinator.overlay
4139
- };
4140
- }
4141
- async function localConnection(input) {
4142
- return installSession(await creaStandalone(input), void 0, input);
4143
- }
4144
- function dispositivoSconosciuto() {
4145
- return {
4146
- webgl2: false,
4147
- webgpu: false,
4148
- wasm: false,
4149
- threads: false,
4150
- isolated: false,
4151
- gpu: "none",
4152
- memoryMb: null,
4153
- cores: null,
4154
- mobile: false,
4155
- tier: "low"
4156
- };
4157
- }
4158
- async function attendiSonda(sonda) {
4159
- let timer;
4160
- try {
4161
- return await Promise.race([
4162
- Promise.resolve().then(sonda).catch(() => dispositivoSconosciuto()),
4163
- new Promise((resolve) => {
4164
- timer = globalThis.setTimeout(() => resolve(dispositivoSconosciuto()), 1500);
4165
- })
4166
- ]);
4167
- } finally {
4168
- if (timer !== void 0) globalThis.clearTimeout(timer);
4169
- }
4170
- }
4171
- function creaKit(input = dipendenzeReali2()) {
4172
- let promessa = null;
4173
- return {
4174
- connect() {
4175
- promessa ?? (promessa = Promise.all([connetti(input), attendiSonda(input.sonda)]).then(([connessione, device]) => ({ ...connessione, device })));
4176
- return promessa;
4177
- }
4178
- };
4179
- }
4180
-
4181
- // src/index.ts
4182
- var caisual = creaKit();
4183
- globalThis.caisual = caisual;
4184
- var index_default = caisual;
4185
- export {
4186
- caisual,
4187
- index_default as default
4188
- };
1
+ // Caisual game kit v0.15.0
2
+ var ft=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],ht=new Set(ft),gt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,vt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function de(n){return n.length>=3&&n.length<=32&&gt.test(n)||vt.test(n)}function Oe(n){return ht.has(n)}function q(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function we(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function yt(n,e="en"){let t=[],i=q(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(q(e)??e),[...new Set(t)]}function Ee(n,e=[]){let t=e.map(q).filter(r=>r!==null),i=n.map(q).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let o of yt(r,r))if(t.includes(o))return o;return t[0]}function Ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function je(n,e){let t=e===null?void 0:n.modes.find(i=>i.id===e);if(e!==null&&t===void 0)throw new Error("The selected game mode does not exist.");return{players:{...t?.players??n.players},lobby:t?.lobby??n.lobby}}function pe(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var T=24;var bt=3e3,_e=32,wt=new Set(["overlay","manifest","id","name","description","cover","card","icon","screenshots","tags","languages","language","platform","orientation","input","visibility","network","isolated","requires","players","lobby","persistent","spectators","boards","roles","teams","voice","modes"]),St=new Set(["keyboard","mouse","touch","gamepad"]),Rt=new Set(["desktop","mobile","both"]),xt=new Set(["landscape","portrait"]),kt=new Set(["public","unlisted"]),Ct=new Set(["none","room","team","proximity"]),Pt=new Set(["light","medium","heavy"]),At=/^[a-z0-9-]+$/,De=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Tt=/^[a-z0-9][a-z0-9-]{0,31}$/,Mt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Le(n){if(n===""||n.startsWith("/")||n.includes("\\")||n.includes("\0")||n.includes("?")||n.includes("#"))return!1;let e=n.split("/");if(e.some(t=>t===""||t==="."||t===".."))return!1;try{return!e.map(i=>decodeURIComponent(i)).some(i=>i===""||i==="."||i===".."||i.includes("/"))}catch{return!1}}function It(n){return n.length===0||n.length>253||n.includes("://")||/[/:?#@]/.test(n)?!1:n.split(".").every(t=>t.length>=1&&t.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(t))}function _(n,e,t){return typeof n=="number"&&Number.isInteger(n)&&n>=e&&n<=t}function Se(n,e,t,i){let r=n[e];return r===void 0?t:typeof r!="string"?(i.push(`${e}: must be a string.`),t):r}function me(n,e,t,i,r){if(n[e]===void 0)return;let o=(g,d)=>{if(typeof g!="string"||g.trim().length===0||g.trim().length>t||/[\r\n\u0000-\u001f]/.test(g)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return g.trim()},s=n[e],a=i?`${i}.${e}`:e;if(typeof s=="string")return o(s,a);let u=J(s);if(!u||Object.keys(u).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[g,d]of Object.entries(u)){let c=q(g);if(!c){r.push(`${a}.${g}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,c)&&r.push(`${a}.${g}: duplicate language.`);let y=o(d,`${a}.${g}`);y!==void 0&&(m[c]=y)}return m}function Re(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let h of Object.keys(t))wt.has(h)||e.push(`${h}: unknown field.`);t.manifest===void 0?e.push("manifest: is required and must be 1."):t.manifest!==1&&e.push("manifest: must be exactly 1.");let i=Se(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(de(i)?Oe(i)&&e.push("id: this slug is reserved."):e.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters."));let r=Se(t,"name","",e);t.name===void 0?e.push("name: is required."):typeof t.name=="string"&&(r.trim()===""||r.length>60)&&e.push("name: must contain 1-60 characters.");let o=t.description===""?"":me(t,"description",500,"",e)??"",s={cover:"",card:"",icon:""},a=new Set;for(let h of["cover","card","icon"]){let p=t[h];if(p==null)e.push(`${h}: is required.`);else if(typeof p!="string"||!Le(p))e.push(`${h}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\.(png|jpe?g|webp)$/i.test(p)||e.push(`${h}: must be a PNG, JPEG or WebP file.`);let z=decodeURIComponent(p);a.has(z)&&e.push(`${h}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(z),s[h]=p}}let{cover:u,card:m,icon:g}=s,d=[];if(t.screenshots!==void 0)if(!Array.isArray(t.screenshots))e.push("screenshots: must be an array of relative file paths.");else{t.screenshots.length>8&&e.push("screenshots: must contain at most 8 paths.");for(let[h,p]of t.screenshots.entries())typeof p!="string"||!Le(p)?e.push(`screenshots[${h}]: must be a relative file path without query, fragment, or parent segments.`):d.push(p)}let c=[];if(t.tags!==void 0)if(!Array.isArray(t.tags))e.push("tags: must be an array.");else{t.tags.length>10&&e.push("tags: must contain at most 10 tags.");for(let[h,p]of t.tags.entries())typeof p!="string"||p.length>24||!At.test(p)?e.push(`tags[${h}]: must be 1-24 lowercase letters, digits, or hyphens.`):c.push(p)}let y=Se(t,"language","en",e);/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(y)||e.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");let k=[];if(!Array.isArray(t.languages)||t.languages.length===0)e.push("languages: must be a non-empty array of BCP 47 language tags.");else for(let[h,p]of t.languages.entries()){let z=q(p);z?k.includes(z)?e.push(`languages[${h}]: duplicate language ${z}.`):k.push(z):e.push(`languages[${h}]: must be a BCP 47 language tag.`)}k.includes("en")||e.push("languages: English is always required alongside the game's own languages.");let C=k[0]??y;if(typeof o=="object")for(let h of Object.keys(o))k.includes(h)||e.push(`description.${h}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&y.toLowerCase()!==C.toLowerCase()&&e.push("language: must match the first entry in languages when both are present.");let D="both";t.platform===void 0?e.push("platform: is required."):typeof t.platform!="string"||!Rt.has(t.platform)?e.push("platform: must be desktop, mobile, or both."):D=t.platform;let E="landscape";t.orientation!==void 0&&(typeof t.orientation!="string"||!xt.has(t.orientation)?e.push("orientation: must be landscape or portrait."):E=t.orientation);let $=[];if(t.input!==void 0)if(!Array.isArray(t.input))e.push("input: must be an array.");else for(let[h,p]of t.input.entries())typeof p!="string"||!St.has(p)?e.push(`input[${h}]: must be keyboard, mouse, touch, or gamepad.`):$.includes(p)?e.push(`input[${h}]: duplicate value ${p}.`):$.push(p);let V="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!kt.has(t.visibility)?e.push("visibility: must be public or unlisted."):V=t.visibility);let B=[];if(t.network!==void 0)if(!Array.isArray(t.network))e.push("network: must be an array of host names.");else for(let[h,p]of t.network.entries())typeof p!="string"||!It(p)?e.push(`network[${h}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(p)?e.push(`network[${h}]: duplicate host ${p}.`):B.push(p);let U=!1;t.isolated!==void 0&&(typeof t.isolated!="boolean"?e.push("isolated: must be a boolean."):U=t.isolated);let G={webgl2:!1,webgpu:!1,wasm:!1,threads:!1,memoryMb:null,performance:"light"};if(t.requires!==void 0){let h=J(t.requires);if(h===null)e.push("requires: must be an object.");else{for(let p of Object.keys(h))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(p)||e.push(`requires.${p}: unknown field.`);for(let p of["webgl2","webgpu","wasm","threads"])h[p]!==void 0&&(typeof h[p]!="boolean"?e.push(`requires.${p}: must be a boolean.`):G[p]=h[p]);h.memoryMb!==void 0&&(h.memoryMb!==null&&(!_(h.memoryMb,512,32768)||h.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):G.memoryMb=h.memoryMb),h.performance!==void 0&&(typeof h.performance!="string"||!Pt.has(h.performance)?e.push("requires.performance: must be light, medium, or heavy."):G.performance=h.performance),G.threads&&!U&&e.push("requires.threads: needs isolated: true.")}}let I={min:1,max:1};if(t.players!==void 0){let h=J(t.players);if(h===null)e.push("players: must be an object with min and max.");else{for(let p of Object.keys(h))p!=="min"&&p!=="max"&&e.push(`players.${p}: unknown field.`);_(h.min,1,T)||e.push(`players.min: must be an integer from 1 to ${T}.`),_(h.max,1,T)||e.push(`players.max: must be an integer from 1 to ${T} in manifest version 1.`),_(h.min,1,T)&&_(h.max,1,T)&&(h.min>h.max?e.push("players.max: must be greater than or equal to players.min."):I={min:h.min,max:h.max})}}let F=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):F=t.lobby);let P=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):P=t.persistent);let te={delayMs:bt};if(t.spectators===!1||t.spectators===null)te=null;else if(t.spectators!==void 0&&t.spectators!==!0){let h=J(t.spectators);if(h===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let p of Object.keys(h))p!=="delayMs"&&e.push(`spectators.${p}: unknown field.`);_(h.delayMs,0,3e4)?te={delayMs:h.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let M=null;if(t.overlay!==void 0&&t.overlay!==null){let h=J(t.overlay);if(h===null)e.push("overlay: must be an object or null.");else{for(let p of Object.keys(h))["version","accent"].includes(p)||e.push(`overlay.${p}: unknown field.`);h.version!==1&&e.push("overlay.version: must be exactly 1."),h.accent!==void 0&&(typeof h.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(h.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),M={version:1,...typeof h.accent=="string"?{accent:h.accent}:{}}}}let X={};if(t.boards!==void 0){let h=J(t.boards);if(h===null)e.push("boards: must be an object of board ids.");else{Object.keys(h).length>_e&&e.push(`boards: at most ${_e} boards.`);for(let[p,z]of Object.entries(h)){let b=!0;Mt.test(p)||(e.push(`boards.${p}: invalid board id.`),b=!1);let S=J(z);if(S===null){e.push(`boards.${p}.source: must be "client" or "server".`);continue}for(let O of Object.keys(S))["source","label","periods","day"].includes(O)||e.push(`boards.${p}.${O}: unknown field.`);S.source!=="client"&&S.source!=="server"&&(e.push(`boards.${p}.source: must be "client" or "server".`),b=!1),S.day!==void 0&&S.day!=="submit"&&S.day!=="start"&&e.push(`boards.${p}.day: must be "submit" or "start".`),S.day==="start"&&S.source!=="server"&&e.push(`boards.${p}.day: start requires source "server".`);let A=me(S,"label",48,`boards.${p}`,e),L=["all-time"];S.periods!==void 0&&(!Array.isArray(S.periods)||S.periods.length<1||S.periods.length>2||S.periods.some(O=>O!=="daily"&&O!=="all-time")||new Set(S.periods).size!==S.periods.length?e.push(`boards.${p}.periods: must contain daily, all-time, or both without duplicates.`):L=[...S.periods]),b&&Object.defineProperty(X,p,{value:{source:S.source,periods:L,...S.day===void 0?{}:{day:S.day},...A===void 0?{}:{label:A}},enumerable:!0,configurable:!0,writable:!0})}}}let H=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let h=new Set;for(let[p,z]of t.roles.entries()){let b=J(z);if(b===null){e.push(`roles[${p}]: must be an object.`);continue}for(let v of Object.keys(b))["id","min","max","label"].includes(v)||e.push(`roles[${p}].${v}: unknown field.`);let S=b.id,A=b.min,L=b.max,O=!0;typeof S!="string"||S.length>32||!De.test(S)?(e.push(`roles[${p}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),O=!1):h.has(S)?(e.push(`roles[${p}].id: duplicate role ${S}.`),O=!1):h.add(S),_(A,0,T)||(e.push(`roles[${p}].min: must be an integer from 0 to ${T}.`),O=!1),L!==void 0&&!_(L,0,T)&&(e.push(`roles[${p}].max: must be an integer from 0 to ${T} when present.`),O=!1),typeof A=="number"&&typeof L=="number"&&A>L&&(e.push(`roles[${p}].max: must be greater than or equal to min.`),O=!1);let l=me(b,"label",32,`roles[${p}]`,e);O&&H.push({id:S,min:A,...L===void 0?{}:{max:L},...l===void 0?{}:{label:l}})}}let ie=null;if(t.teams!==void 0&&t.teams!==null){let h=J(t.teams);if(h===null)e.push("teams: must be null or an object with min and max.");else{for(let p of Object.keys(h))p!=="min"&&p!=="max"&&e.push(`teams.${p}: unknown field.`);_(h.min,2,T)||e.push(`teams.min: must be an integer from 2 to ${T}.`),_(h.max,2,T)||e.push(`teams.max: must be an integer from 2 to ${T}.`),_(h.min,2,T)&&_(h.max,2,T)&&(h.min>h.max?e.push("teams.max: must be greater than or equal to teams.min."):ie={min:h.min,max:h.max})}}let K="none";t.voice!==void 0&&(typeof t.voice!="string"||!Ct.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):K=t.voice);let W=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let h=new Set;for(let[p,z]of t.modes.entries()){let b=J(z);if(b===null){e.push(`modes[${p}]: must be an object.`);continue}for(let v of Object.keys(b))["id","players","lobby","matchmaking","execution","label","instructions"].includes(v)||e.push(`modes[${p}].${v}: unknown field.`);if(typeof b.id!="string"||b.id.length>32||!De.test(b.id)){e.push(`modes[${p}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(h.has(b.id)){e.push(`modes[${p}].id: duplicate mode ${b.id}.`);continue}h.add(b.id);let S={id:b.id};for(let[v,w]of[["label",48],["instructions",160]]){let R=me(b,v,w,`modes[${p}]`,e);R!==void 0&&(S[v]=R)}if(b.execution!==void 0&&(b.execution!=="local"&&b.execution!=="room"?e.push(`modes[${p}].execution: must be local or room.`):S.execution=b.execution),M!==null&&S.execution===void 0&&e.push(`modes[${p}].execution: is required with the standard overlay.`),b.players!==void 0){let v=`modes[${p}].players`,w=J(b.players);if(w===null)e.push(`${v}: must be an object with min and max.`);else{for(let R of Object.keys(w))R!=="min"&&R!=="max"&&e.push(`${v}.${R}: unknown field.`);_(w.min,1,T)||e.push(`${v}.min: must be an integer from 1 to ${T}.`),_(w.max,1,T)||e.push(`${v}.max: must be an integer from 1 to ${T}.`),_(w.min,1,T)&&_(w.max,1,T)&&(w.min>w.max?e.push(`${v}.max: must be greater than or equal to min.`):S.players={min:w.min,max:w.max})}}if(b.lobby!==void 0&&(typeof b.lobby!="boolean"?e.push(`modes[${p}].lobby: must be a boolean.`):S.lobby=b.lobby),S.execution==="local"){let v=S.players??I;(v.min!==1||v.max!==1)&&e.push(`modes[${p}].players: local execution requires min and max to be 1.`),(S.lobby??F)&&e.push(`modes[${p}].lobby: local execution requires false.`),b.matchmaking!==void 0&&e.push(`modes[${p}].matchmaking: local execution cannot use matchmaking.`)}if(b.matchmaking===void 0){W.push(S);continue}let A=J(b.matchmaking);if(A===null){e.push(`modes[${p}].matchmaking: must be an object.`);continue}for(let v of Object.keys(A))["key","timeoutMs","defaults"].includes(v)||e.push(`modes[${p}].matchmaking.${v}: unknown field.`);let L=!0,O=[];if(!Array.isArray(A.key)||A.key.length<1||A.key.length>8)e.push(`modes[${p}].matchmaking.key: must contain from 1 to 8 fields.`),L=!1;else for(let[v,w]of A.key.entries())typeof w!="string"||!Tt.test(w)?(e.push(`modes[${p}].matchmaking.key[${v}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),L=!1):O.includes(w)?(e.push(`modes[${p}].matchmaking.key[${v}]: duplicate field ${w}.`),L=!1):O.push(w);_(A.timeoutMs,1e3,3e5)||(e.push(`modes[${p}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),L=!1);let l;if(A.defaults!==void 0){let v=J(A.defaults);if(v===null||Object.keys(v).length!==O.length||O.some(w=>!Object.hasOwn(v,w)))e.push(`modes[${p}].matchmaking.defaults: must contain exactly the declared key fields.`);else{l={};for(let[w,R]of Object.entries(v))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${p}].matchmaking.defaults.${w}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(l,w,{value:R,enumerable:!0})}}L&&W.push({...S,matchmaking:{...l===void 0?{}:{defaults:l},key:O,timeoutMs:A.timeoutMs}})}}return M!==null&&W.length===0&&e.push("modes: at least one explicit mode is required with the standard overlay."),e.length>0?{ok:!1,errori:e}:{ok:!0,manifest:{manifest:1,overlay:M,id:i,name:r,description:o,cover:u,card:m,icon:g,screenshots:d,tags:c,languages:k,language:C,platform:D,orientation:E,input:$,visibility:V,network:B,isolated:U,requires:G,players:I,lobby:F,persistent:P,spectators:te,boards:X,roles:H,teams:ie,voice:K,modes:W}}}function zt(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function Ne(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Ot(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let s=e?.deviceMemory,a=typeof s=="number"?s*1024:NaN;Number.isFinite(a)&&(t=a)}catch{t=null}let i=null;try{let s=e?.hardwareConcurrency;typeof s=="number"&&Number.isFinite(s)&&(i=s)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let o=!1;try{o=n.crossOriginIsolated===!0}catch{o=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:o,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function $e(n,e=1500){let t=n??globalThis,i=Ot(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let g=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(g!==null){i.webgl2=!0,i.gpu="hardware",Ne(g);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Ne(d))}catch{i.webgl2=!1,i.gpu="none"}}),o=Promise.resolve().then(async()=>{let m;try{let g=t.navigator?.gpu;if(g===void 0)return;let d=await g.requestAdapter();if(d===null)return;m=await d.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),s=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),a=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),u;return await Promise.race([Promise.all([r,o,s,a]),new Promise(m=>{u=setTimeout(m,Math.max(0,e))})]),u!==void 0&&clearTimeout(u),{...i,tier:zt(i)}}function xe(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function _t(n,e=null,t=null,i=null){let r=Re(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");return{manifest:r.manifest,coverUrl:e,iconUrl:i,invite:t}}function N(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Dt(n){let e=N(n),t=N(e?.configuration);return e?.v===1&&typeof e.epoch=="string"&&e.epoch.length>0&&e.epoch.length<=128&&t!==null&&(t.coverUrl===null||typeof t.coverUrl=="string")&&(t.iconUrl===null||typeof t.iconUrl=="string")&&(t.invite===null||typeof t.invite=="string"&&/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(t.invite))&&Re(t.manifest).ok}function Ge(n){return Dt(n)?{v:1,epoch:n.epoch,configuration:_t(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Lt(n){let e=N(n);return e!==null&&Object.keys(e).length===4&&["top","right","bottom","left"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])&&Number(e[t])>=0&&Number(e[t])<=1e5)}function ke(n){let e=N(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Lt(e.safeArea))&&(e.shortcutEnabled===void 0||typeof e.shortcutEnabled=="boolean")&&typeof e.inputBlocked=="boolean"&&Array.isArray(e.reservedRects)&&e.reservedRects.length<=8&&e.reservedRects.every(t=>{let i=N(t);return i!==null&&Object.keys(i).length===4&&["x","y","width","height"].every(r=>typeof i[r]=="number"&&Number.isFinite(i[r])&&i[r]>=0&&i[r]<=1e5)})}function qe(n){let e=N(n),t=N(e?.args);if(e?.type!=="caisual:overlay"||e.v!==1||typeof e.epoch!="string"||e.epoch.length<1||e.epoch.length>128||typeof e.requestId!="string"||!(/^[1-9][0-9]{0,15}$/.test(e.requestId)&&Number.isSafeInteger(Number(e.requestId)))||t===null||Object.keys(e).some(o=>!["type","v","epoch","requestId","sessionId","op","args"].includes(o))||!(e.sessionId===void 0||e.sessionId===null||typeof e.sessionId=="string"&&/^[1-9][0-9]{0,15}$/.test(e.sessionId)))return!1;let i=(...o)=>Object.keys(t).every(s=>o.includes(s)),r=o=>typeof t[o]=="string"&&t[o].length>=1&&t[o].length<=64;switch(e.op){case"local.start":return i("mode")&&r("mode");case"room.create":return i("mode")&&(t.mode===null||r("mode"));case"room.join":return i("code")&&(t.code===void 0||r("code"));case"room.watch":return i("code")&&r("code");case"room.match":{let o=N(t.key);return i("mode","key")&&r("mode")&&(t.key===void 0||o!==null&&Object.keys(o).length<=8&&Object.values(o).every(s=>typeof s=="string"&&s.length>=1&&s.length<=64||typeof s=="number"&&Number.isSafeInteger(s)))}case"room.ready":return i("ready")&&typeof t.ready=="boolean";case"room.role":case"room.requestRole":return i("role")&&r("role");case"room.team":return i("team")&&Number.isInteger(t.team)&&t.team>=1&&t.team<=24;case"room.restart":case"room.start":case"session.cancel":case"session.leave":case"session.disconnect":case"session.resume":return i();case"voice.join":case"voice.leave":return i()&&typeof e.sessionId=="string";case"voice.mute":return i("muted")&&typeof t.muted=="boolean"&&typeof e.sessionId=="string";case"voice.setVolume":return i("playerId","volume")&&typeof e.sessionId=="string"&&typeof t.playerId=="string"&&t.playerId.length>0&&t.playerId.length<=128&&typeof t.volume=="number"&&Number.isFinite(t.volume)&&t.volume>=0&&t.volume<=1;case"overlay.view":return ke(t);default:return!1}}function le(n){if(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isFinite(e)&&new Date(e).toISOString().slice(0,10)===n}function Je(n,e){let t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,i=t(n);if(!i||!Array.isArray(i.standings))return null;let r=new Set(e),o=new Set,s=[];for(let a of i.standings){let u=t(a);!u||typeof u.playerId!="string"||!r.has(u.playerId)||o.has(u.playerId)||(o.add(u.playerId),s.push({playerId:u.playerId,...typeof u.score=="number"&&Number.isFinite(u.score)?{score:u.score}:{},...typeof u.rank=="number"&&Number.isSafeInteger(u.rank)&&u.rank>0?{rank:u.rank}:{}}))}return s.length?{standings:s,...Array.isArray(i.winners)?{winners:[...new Set(i.winners.filter(a=>typeof a=="string"&&o.has(a)))]}:{},...typeof i.draw=="boolean"?{draw:i.draw}:{},...typeof i.unit=="string"?{unit:i.unit}:{}}:null}var jt=["en","it","es","fr","de","pt"],Nt={gameUpdated:["This game was updated","Questo gioco \xE8 stato aggiornato","Este juego se ha actualizado","Ce jeu a \xE9t\xE9 mis \xE0 jour","Dieses Spiel wurde aktualisiert","Este jogo foi atualizado"],reloadGame:["Reload game","Ricarica il gioco","Recargar el juego","Recharger le jeu","Spiel neu laden","Recarregar o jogo"],gameLanguages:["Game languages","Lingue del gioco","Idiomas del juego","Langues du jeu","Spielsprachen","Idiomas do jogo"],loading:["Loading game...","Caricamento...","Cargando...","Chargement...","Spiel wird geladen...","Carregando..."],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."],home:["Play","Gioca","Jugar","Jouer","Spielen","Jogar"],homeMenu:["Menu","Menu","Men\xFA","Menu","Men\xFC","Menu"],mode:["Mode","Modalit\xE0","Modo","Mode","Modus","Modo"],play:["Play","Gioca","Jugar","Jouer","Spielen","Jogar"],friendsPlay:["Play with friends","Gioca con amici","Jugar con amigos","Jouer entre amis","Mit Freunden spielen","Jogar com amigos"],find:["Find players","Trova giocatori","Buscar jugadores","Trouver des joueurs","Spieler finden","Buscar jogadores"],join:["Join with code","Entra con codice","Entrar con c\xF3digo","Rejoindre avec un code","Mit Code beitreten","Entrar com c\xF3digo"],joinInvite:["Join this room","Entra in questa stanza","Entrar en est\xE1 sala","Rejoindre cette salle","Diesem Raum beitreten","Entrar nest\xE1 sala"],watch:["Watch a room","Guarda una stanza","Observar una sala","Regarder une salle","Raum ansehen","Assistir a uma sala"],resume:["Resume","Riprendi","Continuar","Reprendre","Fortsetzen","Continuar"],room:["Room","Stanza","Sala","Salle","Raum","Sala"],code:["Room code","Codice stanza","C\xF3digo de sala","Code de salle","Raumcode","C\xF3digo da sala"],copy:["Copy invite","Copia invito","Copiar invitaci\xF3n","Copier le lien","Einladung kopieren","Copiar convite"],copied:["Invite copied","Invito copiato","Invitacion copiada","Lien copi\xE9","Einladung kopiert","Convite copiado"],copyFailed:["Copy this link:","Copia questo link:","Copia este enlace:","Copiez ce lien :","Diesen Link kopieren:","Copie este link:"],joining:["Joining room...","Ingresso nella stanza...","Entrando en la sala...","Connexion \xE0 la salle...","Raum wird betreten...","Entrando na sala..."],matching:["Finding your people...","Ricerca giocatori...","Buscando jugadores...","Recherche de joueurs...","Spieler werden gesucht...","Buscando jogadores..."],queue:["{n} / {max} players","{n} / {max} giocatori","{n} / {max} jugadores","{n} / {max} joueurs","{n} / {max} Spieler","{n} / {max} jogadores"],cancel:["Cancel","Annulla","Cancelar","Annuler","Abbrechen","Cancelar"],close:["Close","Chiudi","Cerrar","Fermer","Schlie\xDFen","Fechar"],back:["Back","Indietro","Volver","Retour","Zur\xFCck","Voltar"],ready:["Ready","Pronto","Listo","Pr\xEAt","Bereit","Pronto"],unready:["Not ready","Non pronto","No listo","Pas pr\xEAt","Nicht bereit","N\xE3o pronto"],start:["Start","Inizia","Empezar","Commencer","Starten","Come\xE7ar"],role:["Role","Ruolo","Rol","R\xF4le","Rolle","Fun\xE7\xE3o"],team:["Team","Squadra","Equipo","\xC9quipe","Team","Equipe"],host:["Host","Host","Anfitrion","H\xF4te","Host","Anfitri\xE3o"],you:["You","Tu","T\xFA","Vous","Du","Voc\xEA"],away:["Away","Assente","Ausente","Absent","Abwesend","Ausente"],needPlayers:["Waiting for more players","In attesa di giocatori","Esperando m\xE1s jugadores","En attente de joueurs","Weitere Spieler fehlen","Esperando mais jogadores"],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"],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"],needTeams:["Choose the required teams","Scegli le squadre richieste","Elige los equipos","Choisissez les \xE9quipes","Teams auswahlen","Escolha as equipes"],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"],starting:["Starting in","Si inizia tra","Empieza en","D\xE9but dans","Start in","Come\xE7a em"],playing:["Playing","In partita","Jugando","En jeu","Im Spiel","Jogando"],ended:["Game finished","Partita conclusa","Partida terminada","Partie termin\xE9e","Spiel beendet","Partida encerrada"],rematchReady:["{n}/{max} ready","{n}/{max} pronti","{n}/{max} listos","{n}/{max} pr\xEAts","{n}/{max} bereit","{n}/{max} prontos"],rematchStart:["Start rematch","Avvia rivincita","Iniciar revancha","Lancer la revanche","Revanche starten","Iniciar revanche"],won:["You won","Hai vinto","Has ganado","Vous avez gagn\xE9","Du hast gewonnen","Voc\xEA venceu"],lost:["You lost","Hai perso","Has perdido","Vous avez perdu","Du hast verloren","Voc\xEA perdeu"],draw:["Draw","Pareggio","Empate","\xC9galit\xE9","Unentschieden","Empate"],standings:["Standings","Piazzamenti","Posiciones","R\xE9sultats","Platzierungen","Coloca\xE7\xF5es"],points:["points","punti","puntos","points","Punkte","pontos"],time:["time","tempo","tiempo","temps","Zeit","tempo"],distance:["distance","distanza","distancia","distance","Distanz","dist\xE2ncia"],again:["Play again","Gioca ancora","Jugar de nuevo","Rejouer","Erneut spielen","Jogar novamente"],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."],watching:["Watching","In osservazione","Observando","Spectateur","Zuschauen","Assistindo"],delay:["{n}s delay","Ritardo {n}s","Retraso de {n}s","Retard de {n}s","{n}s Verz\xF6gerung","Atraso de {n}s"],exit:["Exit","Esci","Salir","Quitter","Verlassen","Sair"],leaveNow:["Leave for now","Esci per ora","Salir por ahora","Quitter pour le moment","Vor\xFCbergehend verlassen","Sair por enquanto"],leaveRoom:["Leave room","Lascia la stanza","Abandonar sala","Abandonner la salle","Raum verlassen","Deixar a sala"],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."],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."],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."],reconnecting:["Reconnecting...","Riconnessione...","Reconectando...","Reconnexion...","Verbindung wird erneuert...","Reconectando..."],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"],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."],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."],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."],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."],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."],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."],unavailable:["Unavailable right now","Non disponibile ora","No disponible ahora","Indisponible pour le moment","Derzeit nicht verf\xFCgbar","Indisponivel agora"],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."],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."],boards:["Leaderboard","Classifica","Clasificaci\xF3n","Classement","Bestenliste","Classifica\xE7\xE3o"],board:["Board","Classifica","Tabla","Classement","Bestenliste","Tabela"],daily:["Daily","Giornaliera","Diaria","Du jour","T\xE4glich","Di\xE1ria"],allTime:["All time","Di sempre","Hist\xF3rica","Tous les temps","Gesamt","Geral"],accounts:["Accounts","Account","Cuentas","Comptes","Konten","Contas"],guests:["Guests","Ospiti","Invitados","Invit\xE9s","G\xE4ste","Visitantes"],category:["Category","Categoria","Categoria","Cat\xE9gorie","Kategorie","Categoria"],period:["Period","Periodo","Per\xEDodo","P\xE9riode","Zeitraum","Per\xEDodo"],rank:["Rank","Posizione","Puesto","Rang","Platz","Posicao"],score:["Score","Punteggio","Puntos","Score","Punkte","Pontos"],verified:["Verified","Verificato","Verificado","V\xE9rifi\xE9","Verifiziert","Verificado"],own:["Your best","Il tuo record","Tu record","Votre record","Dein Rekord","Seu recorde"],empty:["No scores yet","Nessun punteggio","A\xFAn no hay puntos","Aucun score","Noch keine Punkte","Ainda sem pontos"],saving:["Saving score...","Salvataggio punteggio...","Guardando puntos...","Enregistrement du score...","Punkte werden gespeichert...","Salvando pontos..."],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"],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"],refresh:["Refresh","Aggiorna","Actualizar","Actualiser","Aktualisieren","Atualizar"],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."],friends:["Friends & party","Amici e gruppo","Amigos y grupo","Amis et groupe","Freunde & Gruppe","Amigos e grupo"],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."],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."],online:["Online","Online","En linea","En ligne","Online","Online"],noFriends:["No friends online","Nessun amico online","Sin amigos en linea","Aucun ami en ligne","Keine Freunde online","Nenhum amigo online"],createParty:["Create party","Crea gruppo","Crear grupo","Cr\xE9er un groupe","Gruppe erstellen","Criar grupo"],inviteParty:["Invite to party","Invita nel gruppo","Invitar al grupo","Inviter au groupe","In Gruppe einladen","Convidar para o grupo"],leaveParty:["Leave party","Lascia gruppo","Salir del grupo","Quitter le groupe","Gruppe verlassen","Sair do grupo"],accept:["Accept","Accetta","Aceptar","Accepter","Annehmen","Aceitar"],decline:["Decline","Rifiuta","Rechazar","Refuser","Ablehnen","Recusar"],follow:["Join them","Raggiungi","Unirse","Rejoindre","Beitreten","Juntar-se"],voice:["Voice","Voce","Voz","Voix","Sprache","Voz"],voiceJoin:["Join voice","Entra in voce","Unirse a voz","Activer la voix","Sprachchat beitreten","Entrar na voz"],voiceLeave:["Leave voice","Esci dalla voce","Salir de voz","Quitter la voix","Sprachchat verlassen","Sair da voz"],voiceMute:["Mute","Disattiva microfono","Silenciar","Couper le micro","Stummschalten","Silenciar"],voiceUnmute:["Unmute","Attiva microfono","Activar micr\xF3fono","Activer le micro","Mikrofon aktivieren","Ativar microfone"],voiceOff:["Voice off","Voce disattivata","Voz desactivada","Voix d\xE9sactiv\xE9e","Sprachchat aus","Voz desativada"],voiceJoining:["Joining voice...","Connessione voce...","Conectando voz...","Connexion vocale...","Sprachchat verbindet...","Conectando voz..."],voiceOn:["Voice connected","Voce connessa","Voz conectada","Voix connect\xE9e","Sprachchat verbunden","Voz conectada"],voiceMuted:["Muted","Microfono disattivato","Silenciado","Micro coup\xE9","Stumm","Silenciado"],voiceMic:["Mic on","Microfono attivo","Micr\xF3fono activo","Micro actif","Mikrofon an","Microfone ativo"],voiceListening:["Listening only","Solo ascolto","Solo escucha","\xC9coute seule","Nur zuh\xF6ren","Somente ouvindo"],voiceSpeaking:["Speaking","Sta parlando","Hablando","Parle","Spricht","Falando"],voicePeers:["Voice participants","Partecipanti in voce","Participantes de voz","Participants vocaux","Sprachteilnehmer","Participantes de voz"],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."],voiceVolume:["Volume for {name}","Volume di {name}","Volumen de {name}","Volume de {name}","Lautst\xE4rke f\xFCr {name}","Volume de {name}"],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."],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."],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."],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."],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."],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."],shortcut:["Shift+Tab shortcut","Scorciatoia Shift+Tab","Atajo Shift+Tab","Raccourci Maj+Tab","Umschalt+Tab-Kurzbefehl","Atalho Shift+Tab"],menu:["Caisual menu","Menu Caisual","Menu Caisual","Menu Caisual","Caisual-Menu","Menu Caisual"],retry:["Retry","Riprova","Reintentar","R\xE9essayer","Erneut versuchen","Tentar novamente"]},se=n=>Object.fromEntries(Object.entries(Nt).map(([e,t])=>[e,t[n]])),sn={en:se(0),it:se(1),es:se(2),fr:se(3),de:se(4),pt:se(5)};function Be(n){let e=q(n);return e&&jt.includes(e.split("-")[0])?e:"en"}function Ue(n,e,t="/"){let i,r=t.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0]??"/";return()=>i??(i=(async()=>{let o={};try{let s=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(s.ok){let a=await s.json();Ve(a)&&(o=a)}}catch{}return(s,a={})=>Object.hasOwn(o,s)?o[s].replace(/\{([^{}]+)\}/g,(m,g)=>Object.hasOwn(a,g)?String(a[g]):m):s})())}function f(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function j(){return f("offline","Caisual services are unavailable.")}function ce(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}var Fe="caisual-session-v1";function He(n){let e=N(n);return!e||typeof e.code!="string"||!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(e.code)||!(e.mode===void 0||e.mode===null||typeof e.mode=="string")?null:{version:1,code:e.code,mode:typeof e.mode=="string"?e.mode:null,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}}function Ke(n,e){let t=null,i=!1,r=Promise.resolve(),o=async()=>{let a={version:1,imported:!0,resume:t};return r=r.catch(()=>{}).then(async()=>{try{await n.set(Fe,a),i=!1}catch(u){throw i=!0,u}finally{e()}}),r},s=(async()=>{try{let a=await n.get(Fe),u=N(a);if(u?.version===1&&u.imported===!0)t=He(u.resume);else{let m=await n.get("resume");t=He(m),(a!==null||m!==null)&&await o()}}catch{i=!0}e()})();return{loaded:s,get value(){return t===null?null:{...t}},get error(){return i},async set(a){await s,t=a,e(),await o()}}}function Z(n,e){for(let t of n)try{t(e)}catch{}}function We(n,e=null,t=n.connected){let i=e?.manifest.overlay?.version===1,r=e?.manifest,o={kind:"idle"},s=!1,a=0,u=0,m=null,g=null,d=null,c=null,y=[],k=!1,C="",D={inputBlocked:i,reservedRects:[],safeArea:{top:0,right:0,bottom:0,left:0}},E=new Set,$=new Set,V=new Set,B=new Set,U=new Set,G=new Set,I=null,F=()=>({local:!0,rooms:t,overlay:i,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function P(){if(o.kind!=="room"||!r||r.voice==="none")return null;let l=o.room,v=l.voice;return!v||v.mode==="none"||l.players.find(w=>w.id===l.you)?.role==="spectator"?null:{mode:v.mode,state:v.state,mic:v.mic,muted:v.muted,speaking:v.speaking,peers:v.peers.map(({id:w,mic:R,muted:x,speaking:re,volume:ne})=>({id:w,mic:R,muted:x,speaking:re,volume:ne}))}}function te(){let l=o.kind==="room"||o.kind==="watch"?o.room:null,v=l?.metadata.configuration,w=l?Je(l.result,l.players.map(x=>x.id)):null,R=r&&l&&(l.mode===null||r.modes.some(x=>x.id===l.mode))?je(r,l.mode):{players:{min:1,max:1},lobby:!1};return{kind:m??(o.kind==="idle"?s?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:m?g:o.kind==="local"?o.mode:l?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:s,capabilities:F(),room:l?{...l.metadata.rematch?.keepSetup||l.metadata.rematch?.autoStart?{rematch:l.metadata.rematch}:{},code:l.code,mode:l.mode,status:l.status,host:l.host,you:o.kind==="room"?o.room.you:null,players:l.players.map(x=>({id:x.id,name:x.name,guest:x.guest,role:x.role,team:x.team,ready:x.ready,connected:x.connected})),...w?{result:w}:{},countdownAt:l.countdownAt,connection:l.connection,closedCode:l.metadata.closedCode,limits:{...v?.players??R.players},lobby:v?.lobby??R.lobby,persistent:v?.persistent??r?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:v?.requestRole??!1}:null,voice:m?null:P(),waiting:d?{...d}:null,resume:I?.value??null,resumeError:I?.error??!1}}function M(){if(k)return;let l=te(),v=JSON.stringify(l);v!==C&&(C=v,Z(V,l))}function X(){Z(E,{...o}),M()}function H(){if(o.kind!=="room")throw f("no_room","There is no active player room.");return o.room}function ie(){let l=H();if(l.players.find(v=>v.id===l.you)?.role==="spectator")throw f("spectator","Spectators cannot use voice controls.");if(!r||r.voice==="none"||l.voice.mode==="none")throw f("voice_disabled","Voice is disabled for this room.");return l.voice}function K(){a++,c?.abort(),c=null,m=null,d=null,M()}function W(l){y.splice(0).forEach(v=>v()),(o.kind==="room"||o.kind==="watch")&&(l?o.room.disconnect():o.room.leave()),o={kind:"idle"},X()}async function h(l){I?.value?.code===l&&await I.set(null).catch(()=>{})}async function p(l,v,w){if(w!==a||k)throw l.leave(),f("cancelled","The operation was cancelled.");W(!1),o=v?{kind:"watch",room:l,id:String(++u)}:{kind:"room",room:l,id:String(++u)};let R=l;if(y=[R.onPlayers(M),R.onMetadata(()=>{R.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===R?(y.splice(0).forEach(x=>x()),!v&&R.metadata.closedCode===1e3&&h(R.code),o={kind:"idle"},X()):M()}),R.onStatus(()=>{M(),!v&&R.connection==="ended"&&h(R.code)})],!v){let x=l,re=o.id;x.voice&&y.push(x.voice.onState(M),x.voice.onPeers(M)),y.push(x.onError(ne=>Z(U,{sessionId:re,error:{...ne}}))),y.push(x.onScoreQueued(ne=>Z(G,{...ne})));for(let ne of x.queuedScores)Z(G,{...ne})}return m=null,d=null,X(),!v&&I&&R.connection!=="ended"&&await I.set({version:1,code:R.code,mode:R.mode,updatedAt:n.time.now()}).catch(()=>{}),l}async function z(l,v,w,R=!1){K();let x=a;c=new AbortController,m=l,g=v,M();try{let re=await w(c.signal,x);if(await p(re,R,x),x!==a||k)throw f("cancelled","The operation was cancelled.");return re}finally{x===a&&(m=null,d=null,c=null,M())}}let b=n.room,S=b.onError(l=>{!i||k||(l.code==="version_mismatch"?b.reload():l.code==="version_outdated"&&Z(U,{sessionId:o.kind==="idle"?null:o.id,error:l}))}),A=i?{invited:b.invited,reload:()=>b.reload(),onError:l=>b.onError(l),create(l){return r&&pe(r,l.mode)?Promise.reject(f("invalid_request","Local modes cannot create rooms.")):z("attaching",l.mode,()=>b.create(l))},join(l){return z("attaching",null,()=>b.join(l))},watch(l){return z("attaching",null,()=>b.watch(l),!0)},match(l){return r&&pe(r,l.mode)?Promise.reject(f("invalid_request","Local modes cannot use matchmaking.")):z("matching",l.mode,(v,w)=>{let R=()=>{a===w&&K()};return l.signal?.addEventListener("abort",R,{once:!0}),l.signal?.aborted&&R(),b.match({...l,signal:v,onWaiting(x){w===a&&(d={...x},M(),l.onWaiting?.(x))}}).finally(()=>l.signal?.removeEventListener("abort",R))})}}:b;return i&&(I=Ke(n.save,M)),{session:{get current(){return{...o}},get capabilities(){return F()},onChange(l){return E.add(l),Z(new Set([l]),{...o}),()=>{E.delete(l)}},ready(){k||s||(s=!0,M())},finish(){if(o.kind==="room"||o.kind==="watch")throw f("not_local","Only a local session can be finished by the client.");o.kind==="local"&&(o={...o,status:"ended"},X())}},overlay:{open(l){if(!["home","room","invite","friends","voice","boards"].includes(l))throw f("invalid_request","Unknown overlay panel.");i&&Z(B,l)},onChange(l){return $.add(l),Z(new Set([l]),structuredClone(D)),()=>{$.delete(l)}}},rooms:A,snapshot:te,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(l){return V.add(l),l(te()),()=>{V.delete(l)}},onOpen(l){return B.add(l),()=>{B.delete(l)}},onError(l){return U.add(l),()=>{U.delete(l)}},onScore(l){return G.add(l),()=>{G.delete(l)}},async execute(l){if(!i)throw f("overlay_disabled","This game uses its own room flow.");if(l.op==="overlay.view"){if(!ke(l.args))throw f("invalid_request","The overlay geometry is invalid.");if(D={...structuredClone(l.args),safeArea:{top:0,right:0,bottom:0,left:0,...l.args.safeArea}},typeof document<"u")for(let[v,w]of Object.entries(D.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${v}`,`${w}px`);Z($,structuredClone(D));return}if(l.sessionId!==void 0&&l.sessionId!==(o.kind==="idle"?null:o.id))throw f("session_replaced","The active session changed.");if(l.op.startsWith("voice.")&&l.sessionId!==(o.kind==="idle"?null:o.id))throw f("session_replaced","The active session changed.");if(!s)throw f("game_not_ready","The game is still loading.");switch(l.op){case"local.start":{if(!r||!pe(r,l.args.mode))throw f("invalid_mode","This is not a local mode.");K();let v=a;if(o.kind==="room"&&await h(o.room.code),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!1),o={kind:"local",id:String(++u),mode:l.args.mode,status:"playing"},X();return}case"room.create":await A.create(l.args);return;case"room.join":await A.join(l.args.code);return;case"room.watch":await A.watch(l.args.code);return;case"room.match":{let v=r?.modes.find(R=>R.id===l.args.mode),w=l.args.key??v?.matchmaking?.defaults;if(!w)throw f("invalid_request","Matchmaking needs a complete key.");await A.match({mode:l.args.mode,key:w});return}case"voice.join":{let v=H();if(await ie().join(),o.kind!=="room"||o.room!==v)throw f("session_replaced","The active session changed.");M();return}case"voice.mute":ie().mute(l.args.muted),M();return;case"voice.leave":ie().leave(),M();return;case"voice.setVolume":{let v=ie();if(!v.peers.some(w=>w.id===l.args.playerId))throw f("voice_peer_missing","This voice participant is no longer available.");v.setVolume(l.args.playerId,l.args.volume),M();return}case"room.ready":H().ready(l.args.ready);return;case"room.role":H().setRole(l.args.role);return;case"room.requestRole":await H().requestRole(l.args.role);return;case"room.team":H().setTeam(l.args.team);return;case"room.start":H().start();return;case"room.restart":H().restart();return;case"session.cancel":K();return;case"session.resume":{await z("attaching",null,async v=>{if(await I?.loaded,v.aborted)throw f("cancelled","The operation was cancelled.");if(!I?.value)throw f("no_resume","There is no saved room.");return b.join(I.value.code)});return}case"session.disconnect":{K();let v=a;if(o.kind==="room"&&o.room.connection!=="ended"&&I&&await I.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!0);return}case"session.leave":{K();let v=a;if(o.kind==="room"&&await h(o.room.code),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!1);return}}},dispose(){S(),K(),W(!0),k=!0,E.clear(),$.clear(),V.clear(),B.clear(),G.clear(),U.clear()}}}function Ze(n,e,t){let i=!0,r=!1,o=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),s=a=>{let u=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||u?.closest?.('input,textarea,select,[contenteditable="true"]')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",s,!0),()=>{o(),n.removeEventListener("keydown",s,!0)}}function Qe(n,e,t){let i=!1,r=0,o=0,s=0,a=new Map,u=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[Ze(window,t.overlay,()=>u({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>u({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>u({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:c})=>u({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:c})),t.onScore(d=>u({type:"caisual:overlay-score",v:1,epoch:e.epoch,score:d}))],g=d=>{let c=N(d.data);if(c?.type!=="caisual:overlay"||c.epoch!==e.epoch||i)return;let y={type:"caisual:overlay-response",v:1,epoch:e.epoch,requestId:typeof c.requestId=="string"?c.requestId:""};if(!qe(c)){u({...y,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let k=JSON.stringify([c.op,c.args,c.sessionId]),C=a.get(c.requestId);if(C){C.fingerprint!==k?u({...y,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):C.response.then(u);return}if(Number(c.requestId)<=o||s>=32){u({...y,ok:!1,error:{code:"stale_request",message:"The request is stale or too many requests are pending."}});return}o=Number(c.requestId),s++;let D=Promise.resolve().then(()=>t.execute(c)).then(()=>({...y,ok:!0}),E=>({...y,ok:!1,error:{code:typeof N(E)?.code=="string"?N(E).code:"internal_error",message:E instanceof Error?E.message:"The operation could not be completed."}}));a.set(c.requestId,{fingerprint:k,response:D}),D.then(E=>{if(s--,u(E),a.size>64)for(let $ of a.keys())Number($)<o-64&&a.delete($)})};return n.addEventListener("message",g),n.start(),()=>{i=!0,n.removeEventListener("message",g),m.forEach(d=>d()),t.dispose(),a.clear()}}async function $t(n){let e={};try{e=await n.json()}catch{}return f(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function fe(n,e,t,i){async function r(o,s,a,u){let m=new Headers({Authorization:`Bearer ${a}`}),g;if(u!==void 0){m.set("Content-Type","application/json");try{g=JSON.stringify(u)}catch{throw f("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+o,n),{method:s,headers:m,body:g,credentials:"omit"})}catch{throw j()}}return async function(s,a,u,m=!1){let g;try{g=m?await i.rinnova():await i.ottieni()}catch{throw j()}let d=await r(s,a,g,u);if(d.status===401){try{g=await i.rinnova()}catch{throw j()}d=await r(s,a,g,u)}if(!d.ok)throw await $t(d);try{return await d.json()}catch{throw f("internal_error","The service returned an invalid response.")}}}function Ye(n,e,t){let i=fe(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,o)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:o}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(o){if(ce(o)==="not_found")return null;throw o}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves},async boardSubmit(r,o,s){let a=await i("/scores","POST",{board:r,score:o,daily:s});return{accepted:!0,best:a.best,rank:a.rank,day:a.day,verified:a.verified}},async boardTop(r,o){if(o.day!==void 0&&(!le(o.day)||o.daily===!1))throw f("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");let s=new URLSearchParams;o.day!==void 0&&s.set("day",o.day),o.daily&&s.set("daily","1"),o.limit!==void 0&&s.set("limit",String(o.limit)),o.guests&&s.set("guests","1");let a=s.size===0?"":`?${s.toString()}`,{day:u,entries:m,me:g}=await i(`/scores/${encodeURIComponent(r)}${a}`,"GET");return{day:u,entries:m,me:g}}}}function ae(n){return(Math.floor(n/864e5)+1)*864e5}function he(n,e,t){let i=new Set,r={...n},o,s=!1;function a(){!i.size||o!==void 0||s||(o=setTimeout(u,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),o.unref?.())}async function u(){o=void 0,s=!0;try{let m=await t(),g=m.day!==r.day;if(r={...m},g)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{s=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:Xe(n.seed),rng:()=>Xe(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&o!==void 0&&(clearTimeout(o),o=void 0)}}}}function Ce(n){return new Date(n).toISOString().slice(0,10)}async function Pe(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function Xe(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function et(n,e){return ge(n)?.type===e}function Gt(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function tt(n,e,t=3e3){return new Promise(i=>{let r=!1,o=globalThis.crypto.randomUUID(),s=g=>{r||(r=!0,n.removeEventListener("message",u),n.clearTimeout(m),i(g))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:o,overlayVersion:1},e)},u=g=>{if(g.origin!==e||g.source!==n.parent)return;if(et(g.data,"caisual:ready?")){a();return}if(!et(g.data,"caisual:hello"))return;let d=ge(g.data),c=g.ports[0];if(typeof d?.ticket!="string"||!xe(d.n)||c===void 0)return;c.start();let y=Ge(d.overlay),k=C=>Array.isArray(C)?C.map(q).filter(D=>D!==null):void 0;s({...y?{overlay:y}:{},...q(d.language)?{language:q(d.language)}:{},uiLanguage:q(d.uiLanguage)??void 0,languagePreferences:k(d.languagePreferences),gameLanguages:k(d.gameLanguages),ticket:d.ticket,n:d.n,live:Gt(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:c})};n.addEventListener("message",u);let m=n.setTimeout(()=>s(null),t);a()})}function qt(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=ge(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function Jt(n,e,t,i){return new Promise((r,o)=>{let s=!1,a=g=>{s||(s=!0,n.removeEventListener("message",u),e.clearTimeout(m),g===null?o(new Error("Ticket refresh timed out.")):r(g))},u=g=>{let d=ge(g.data),c=d?.aud===void 0?"portal":d.aud;d?.type==="caisual:ticket"&&c===i&&typeof d.ticket=="string"&&a(d.ticket)};n.addEventListener("message",u);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function Ae(n,e,t,i,r=3e3,o="portal"){let s=n,a=null,u=()=>{if(a!==null)return a;let g=Jt(e,t,r,o).then(d=>(s=d,d)).finally(()=>{a===g&&(a=null)});return a=g,g};return{async ottieni(){if(s===null)return u();let m=qt(s);return m!==null&&m-i()<3e4?u():s},rinnova:u}}var Te=.02,it=300,Bt=200,nt=3e3,Ut=1e4,Ft=[1e3,2e3,4e3];function ot(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Ht(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var ve=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Ht(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=this.scegliMic(e);this.verificaIngresso(t),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(f("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw f("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=ot(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(f(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,ot(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(f("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(f("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}scegliMic(e){return e.mic!==void 0?e.mic:this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role!=="spectator"}verificaIngresso(e=this.micDesiderato){if(!this.contesto.connessa())throw f("offline","The room is not connected.");if(this.modeCorrente==="none")throw f("voice_disabled","Voice is disabled for this room.");if(this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role==="spectator"&&e)throw f("spectator","Spectators cannot publish voice.");if(this.dipendenze===null)throw f("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let o;try{o=await t.getUserMedia({audio:!0})}catch(a){throw this.permessoNegato(a)?f("permission_denied","Microphone permission was denied."):f("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(a){for(let u of o.getTracks())u.stop();throw a}let s=o.getAudioTracks()[0];if(s===void 0)throw f("voice_error","The microphone has no audio track.");this.stream=o,this.tracciaMic=s,s.enabled=!this.mutedCorrente,this.preparaAnalizzatore(o)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw f("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw f("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let o of this.gains.keys())this.aggiornaZero(o);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=o=>{let s=o.transceiver.mid,a=s===null?void 0:this.midGiocatori.get(s);a!==void 0&&this.collegaTraccia(a,o.track,o.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let o=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),s=await i.createOffer();await i.setLocalDescription(s),this.controllaGenerazione(t);let a=o.mid,u=i.localDescription?.sdp;if(a===null||u===void 0)throw f("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:u,mid:a})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw f("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw f("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw f("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,o)=>{let s=()=>{e.removeEventListener("connectionstatechange",a),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},a=()=>{t!==this.generazione?(s(),o(f("offline","Voice was stopped."))):e.connectionState==="connected"?(s(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(s(),o(f("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",a),this.cancellaAttesaConnessione=()=>{s(),o(f("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{s(),o(f("voice_error","The voice connection timed out."))},Ut)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(m=>[m.id,m])),r=[];for(let[m,g]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===g.session&&d.track===g.track||(r.push(g),this.riproduzioni.has(m)||g.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(g.mid),this.scollegaTraccia(m))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(m=>m.mid)});let o=[...i.values()].filter(m=>!this.sfuAttive.has(m.id));if(o.length===0)return;let s;try{s=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:o.map(m=>({session:m.session,track:m.track}))})}catch(m){if(ce(m)!=="not_allowed")throw m;for(let g of o)this.negati.add(g.id);return}if(s.op!=="subscribe")throw f("voice_error","The voice service returned an invalid response.");for(let m of s.tracks){let g=o.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&g!==void 0&&this.negati.add(g.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||g===void 0)&&(this.midGiocatori.set(m.mid,g.id),this.sfuAttive.set(g.id,{session:g.session,track:g.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:s.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let u=t.localDescription?.sdp;if(u===void 0)throw f("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:u}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=o=>{o.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:o.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=o=>{r.receiver=o.receiver,this.collegaTraccia(t,o.track,o.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(s=>s.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let o=t;try{if(o.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(o.candidate);return}if(o.kind!=="offer"&&o.kind!=="answer"||typeof o.sdp!="string")return;let s=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),a=o.kind==="offer"&&!s;if(r.ignoreOffer=!r.polite&&a,r.ignoreOffer)return;if(r.settingRemoteAnswer=o.kind==="answer",await r.pc.setRemoteDescription({type:o.kind,sdp:o.sdp}),r.settingRemoteAnswer=!1,o.kind==="offer"){let u=await r.pc.createAnswer();await r.pc.setLocalDescription(u);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(ce(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>{if(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic)return!1;if(this.modeCorrente==="team"){let o=t.find(s=>s.id===r.id);if(i?.role!=="spectator"&&o?.team!==i?.team)return!1}return!0})}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<nt})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),o=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,nt-r));this.timerZero.set(e,o)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),o=r.creaMediaStream([t]),s=this.richiediAudioContext().createMediaStreamSource(o),a=this.richiediAudioContext().createGain();s.connect(a),a.connect(this.richiediAudioContext().destination);let u=null;try{u=this.richiediAudioContext().createAnalyser(),u.fftSize=256,s.connect(u)}catch{u=null}let m=r.creaAudioElement();m.srcObject=o,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:s,gain:a,analyser:u,audio:m,track:t,receiver:i});let g=this.sfuAttive.get(e);g!==void 0&&(g.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Bt)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Te),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=it;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let o of this.copiaPeers()){let s=this.riproduzioni.get(o.id);this.livelloAnalizzatore(s?.analyser??null)>Te?this.ultimoAudio.set(o.id,e.ora()):(s?.analyser===null||s?.analyser===void 0)&&(s?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Te)&&this.ultimoAudio.set(o.id,e.ora());let a=!o.muted&&e.ora()-(this.ultimoAudio.get(o.id)??0)<=it;(this.speakingPeers.get(o.id)??!1)!==a&&(this.speakingPeers.set(o.id,a),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,o)=>r+o*o,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>{if(r.id===e)return[];if(this.modeCorrente==="team"){let o=t.find(s=>s.id===r.id);if(i?.role!=="spectator"&&o?.team!==i?.team)return[]}return[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}]})}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(f("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Ft[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(f("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(o){this.richieste.delete(t),r(o)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw f("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw f("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw f("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw f("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="spectator"||t==="offline"||t==="voice_error"?e:f("voice_error","Voice could not be started.")}return f("voice_error","Voice could not be started.")}};var ee=1,rt=[1e3,2e3,4e3,8e3],Kt=6e4,Wt=5e3,Zt=2e4,Qt=500,Yt=2e3,Xt=new Set([4003,4004,4005,4006,4008,4009]);function Y(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function st(n){let e=Y(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ei(n){let e=Y(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function ti(n){let e=Y(n),t=Y(e?.players);return e!==null&&typeof e.url=="string"&&Number.isInteger(e.timeoutMs)&&e.timeoutMs>=1e3&&e.timeoutMs<=3e5&&t!==null&&Number.isInteger(t.min)&&Number.isInteger(t.max)&&t.min>=1&&t.max>=t.min}function Q(n){return JSON.parse(JSON.stringify(n))}function ii(n,e){let t=Q(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Q(i.value);continue}let r=t,o=i.path;for(let a=0;a<o.length-1;a++){let u=o[a];if(Array.isArray(r)){if(typeof u!="number"||u>=r.length)return{ok:!1};r=r[u]}else{let m=Y(r);if(m===null||typeof u!="string"||!Object.hasOwn(m,u))return{ok:!1};r=m[u]}}let s=o.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof s!="number"||s>=r.length)return{ok:!1};r[s]=Q(i.value)}else{let a=Y(r);if(a===null||typeof s!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(a,s))return{ok:!1};delete a[s]}else Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:Q(i.value),writable:!0})}}return{ok:!0,state:t}}function ni(n){let e=fe(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(s,a,u,m)=>{try{return await e(s,a,{...Y(u),n:n.n},m)}catch(g){if(g instanceof Error&&"code"in g&&["version_outdated","version_mismatch"].includes(String(g.code))){let d=Y(u),c=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\s-]/g,""):void 0,y=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(g,g.code==="version_mismatch"?{code:c,roomId:y,watch:s==="/rooms/watch"}:void 0)}throw g}};async function i(s,a,u=!1){let m=await t(s,"POST",a,u);if(!st(m))throw f("internal_error","The room service returned an invalid response.");return m}async function r(s){let a=await t("/match","POST",{mode:s.mode,key:s.key});if(!ti(a))throw f("internal_error","The matchmaking service returned an invalid response.");return a}async function o(s,a=!1){let u=await t("/rooms/watch","POST",s,a);if(!ei(u))throw f("internal_error","The room service returned an invalid response.");return u}return{create:s=>i("/rooms",{mode:s}),joinCode:s=>i("/rooms/join",{code:s}),joinRoom:s=>i("/rooms/join",{roomId:s},!0),watchCode:s=>o({code:s}),watchRoom:s=>o({roomId:s},!0),match:r,flush:s=>t(`/rooms/${encodeURIComponent(s)}/flush`,"POST")}}var ye=class{constructor(e,t,i,r,o,s,a=!1){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=o;this.segnalaStanza=s;this.spettatore=a;this.meta={host:null,mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.scoreListeners=new Set;this.scores=[];this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.hostCorrente=null;this.resultCorrente=null;this.delaySpettatore=0;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.promessaPronta=new Promise((u,m)=>{this.risolviPronta=u,this.rifiutaPronta=m}),this.voice=new ve({invia:u=>this.invia(u),connessa:()=>this.socket?.readyState===ee&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),a&&(this.rosterRicevuto=!0),this.apri(i)}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}get queuedScores(){return structuredClone(this.scores)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onScoreQueued(e){return this.scoreListeners.add(e),()=>this.scoreListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.metadataChanged({host:e.host,mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(f("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(f("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(f("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let o=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(f("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:o});try{this.invia({t:"request-role",r:t,role:e})}catch(s){this.dipendenze.clearTimeout(o),this.roleRequests.delete(t),r(s)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(f("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(f("cancelled","The room was disconnected.")))}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get host(){return this.hostCorrente}get code(){return this.codice}get result(){return this.resultCorrente}get delayMs(){return this.delaySpettatore}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-19),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw f("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(20,this.tickRateCorrente):20);this.inviiGioco=this.inviiGioco.filter(s=>e-s<1e3);let r=this.inviiGioco.length>=20?this.inviiGioco[0]+1e3:e,o=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let s=this.dipendenze.ora();if(s<this.ultimoInvioGioco+i||this.inviiGioco.filter(u=>s-u<1e3).length>=20){this.programmaInput();return}let a=this.ultimoInput;try{this.send(JSON.parse(a)),this.inputInviato=a}catch{}},Math.max(0,Math.ceil(Math.max(o,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}start(){this.invia({t:"start"})}restart(){if(this.statusCorrente!=="finished")throw f("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){if(!this.lasciata){if(this.spettatore||this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===ee){let e=this.socket;this.invia({t:"leave"}),this.spettatore&&e.close(1e3)}this.termina(1e3)}}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==ee)throw f("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw f("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Wt:Zt;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===ee)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=Y(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="watching")this.riceviWatching(t);else if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="players")this.riceviGiocatori(t.players,t.host);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,Q(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="score-queued"&&!this.spettatore)this.scores.push(structuredClone(t.score)),this.scores=this.scores.slice(-32),this.notifica(this.scoreListeners,structuredClone(t.score));else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(f(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWatching(e){let t=e.room;!this.spettatore||t.id!==this.roomId||(this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Q(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.delaySpettatore=e.delayMs,this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Q(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},Yt)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e,t){this.giocatoriCorrenti=e.map(i=>({...i})),t!==void 0?this.hostCorrente=t:this.giocatoriCorrenti.some(i=>i.id===this.hostCorrente&&i.connected)||(this.hostCorrente=this.giocatoriCorrenti.find(i=>i.connected)?.id??null),this.metadataChanged({host:this.hostCorrente}),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){this.statusCorrente=e.status,e.host!==void 0&&(this.hostCorrente=e.host),this.resultCorrente=Q(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,host:this.hostCorrente,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=ii(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=Q(e),this.statoPubblico=Q(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==ee)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(Xt.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.spettatore||this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,rt.length-1),t=rt[e];if(this.tempoRiconnessione+t>Kt){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=this.spettatore?await this.api.watchRoom(this.roomId):await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let s=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(f(s,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.spettatore&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},Qt))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function be(n=null){return{invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw j()},async join(){throw j()},async watch(){throw j()},async match(){throw j()}}}function at(n,e){let t,i=new Set,r=ni({...n,onVersionError(d,c){t=c;for(let y of i)try{y(d)}catch{}}}),o=!1,s=null,a=d=>{let c=d?.code??null;o&&c===s||(o=!0,s=c,n.segnalaStanza?.(d))},u=async d=>{let c=new ye(d.roomId,d.code,d.url,n,r,a);return await c.pronta(),c},m=async d=>{let c=new ye(d.roomId,d.code,d.url,n,r,()=>{},!0);return await c.pronta(),{get mode(){return c.mode},get countdownAt(){return c.countdownAt},get connection(){return c.connection},get metadata(){return c.metadata},onMetadata:y=>c.onMetadata(y),onConnection:y=>c.onConnection(y),disconnect:()=>c.disconnect(),get state(){return c.state},get tick(){return c.tick},get tickRate(){return c.tickRate},get latency(){return c.latency},get seed(){return c.seed},get status(){return c.status},get players(){return c.players},get host(){return c.host},get code(){return c.code},get result(){return c.result},get delayMs(){return c.delayMs},onState:y=>c.onState(y),onPlayers:y=>c.onPlayers(y),onStatus:y=>c.onStatus(y),onMessage:y=>c.onMessage(y),leave:()=>{c.leave()},serverTime:()=>c.serverTime()}},g=(d,c)=>new Promise((y,k)=>{let C,D=!1,E=()=>{C.removeEventListener("message",I),C.removeEventListener("close",U),C.removeEventListener("error",G),c.signal?.removeEventListener("abort",B)},$=()=>{try{C.close(1e3)}catch{}},V=(F,P)=>{D||(D=!0,E(),P&&$(),k(F))};function B(){V(f("cancelled","The matchmaking search was cancelled."),!0)}function U(){V(j(),!1)}function G(){V(j(),!0)}function I(F){let P=null;try{P=typeof F.data=="string"?Y(JSON.parse(F.data)):null}catch{}if(P===null||typeof P.t!="string"){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}if(P.t==="waiting"){if(!Number.isInteger(P.players)||!Number.isInteger(P.min)||!Number.isInteger(P.max)){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}try{c.onWaiting?.({players:P.players,min:P.min,max:P.max})}catch{}return}if(P.t==="matched"){if(!st(P)){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}D=!0,E(),$(),y(P);return}if(P.t==="no_match"){V(f("no_match","No match was found before the timeout."),!0);return}if(P.t==="error"){V(f(typeof P.code=="string"?P.code:"internal_error",typeof P.message=="string"?P.message:"The matchmaking service could not complete the search."),!0);return}P.t!=="pong"&&V(f("internal_error","The matchmaking service sent an invalid message."),!0)}try{C=n.apriSocket(d)}catch{k(j());return}C.addEventListener("message",I),C.addEventListener("close",U),C.addEventListener("error",G),c.signal?.addEventListener("abort",B,{once:!0}),c.signal?.aborted===!0&&B()});return{invited:e,reload(){n.reload?.(t)},onError(d){return i.add(d),()=>{i.delete(d)}},async create(d){return u(await r.create(d.mode))},async join(d){let c=d??e;if(c==null||c.length===0)throw f("invalid_request","A room invitation code is required.");return u(await r.joinCode(c))},async watch(d){if(typeof d!="string"||d.length===0)throw f("invalid_request","A room invitation code is required.");return m(await r.watchCode(d))},async match(d){let c=()=>d.signal?.aborted===!0;if(c())throw f("cancelled","The matchmaking search was cancelled.");let y=await r.match(d);if(c())throw f("cancelled","The matchmaking search was cancelled.");return u(await g(y.url,d))}}}var oe="caisual:save:",oi=/^[a-z0-9][a-z0-9_-]{0,31}$/;function Me(n){if(!oi.test(n))throw f("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function lt(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function ct(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(oe)&&e.push(i.slice(oe.length))}return e}function ri(n,e){let t=()=>{if(n===null)throw j();return n};return{async set(i,r){Me(i);let o=t(),s=JSON.stringify({value:r}),a=new TextEncoder().encode(s).byteLength;if(a>262144)throw f("payload_too_large","The save is larger than 262144 bytes.");if(o.getItem(oe+i)===null&&ct(o).length>=32)throw f("save_limit","A game can store at most 32 save keys.");let u={value:r,bytes:a,updatedAt:e()};return o.setItem(oe+i,JSON.stringify(u)),{key:i,bytes:a,updatedAt:u.updatedAt}},async get(i){return Me(i),lt(t().getItem(oe+i))?.value??null},async remove(i){Me(i),t().removeItem(oe+i)},async list(){let i=t();return ct(i).flatMap(r=>{let o=lt(i.getItem(oe+r));return o===null?[]:[{key:r,bytes:o.bytes,updatedAt:o.updatedAt}]}).sort((r,o)=>r.key.localeCompare(o.key))}}}async function Ie(n,e=null){let t=n.ora(),i=Ce(t),r=await Pe(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:he({day:i,seed:r,expiresAt:ae(t)},n.ora,async()=>{let o=n.ora(),s=Ce(o);return{day:s,seed:await Pe(n.hostname,s,n.subtle),expiresAt:ae(o)}}),time:{now:n.ora},save:ri(n.archivio,n.ora),board:{async submit(){return{accepted:!1,reason:"offline",verified:!1}},async top(o,s={}){if(s.day!==void 0&&(!le(s.day)||s.daily===!1))throw f("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");return{day:s.day??(s.daily?i:null),entries:[],me:null}}},room:be(e)}}function si(n){let e=n?.querySelector('meta[name="caisual-app"]')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function ai(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function li(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:ai(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>$e()}}async function ci(n){let e=si(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return ut(n);let i=await tt(n.finestra,e,n.timeoutHandshake);if(i===null)return ut(n);let r=Ae(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),o=Ye(e,n.fetcher,r),s=n.ora(),a;try{a=await o.me()}catch{let c=await Ie(n,i.invite);return ze(c,i,n)}let u=n.ora(),m=a.serverTime-(s+u)/2,g=i.live===null?be(i.invite):at({appOrigin:e,n:i.n,reload:c=>i.porta.postMessage({type:"caisual:reload",target:c}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:Ae(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(c){if(n.apriSocket!==void 0)return n.apriSocket(c);if(typeof WebSocket>"u")throw j();return new WebSocket(c)},ora:n.ora,setTimeout:(c,y)=>globalThis.setTimeout(c,y),clearTimeout:c=>globalThis.clearTimeout(c),setInterval:(c,y)=>globalThis.setInterval(c,y),clearInterval:c=>globalThis.clearInterval(c),voce:n.voce,segnalaStanza(c){try{i.porta.postMessage({type:"caisual:room",room:c})}catch{}}},i.invite),d={connected:!0,player:a.player,daily:he({day:a.day,seed:a.seed,expiresAt:a.expiresAt??ae(a.serverTime)},()=>n.ora()+m,async()=>{let c=await o.me();return{day:c.day,seed:c.seed,expiresAt:c.expiresAt??ae(c.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(c,y)=>o.saveSet(c,y),get:c=>o.saveGet(c),remove:c=>o.saveRemove(c),list:()=>o.saveList()},board:{async submit(c,y,k={}){try{return await o.boardSubmit(c,y,k.daily===!0)}catch(C){if(typeof C=="object"&&C!==null&&"code"in C&&C.code==="offline")return{accepted:!1,reason:"offline",verified:!1};throw C}},top:(c,y={})=>o.boardTop(c,y)},room:g};return ze(d,i,n)}function ze(n,e,t){let i=We(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null);if(e?.overlay){let a=Qe(e.porta,e.overlay,i);i.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",a,{once:!0})}let r=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=Ee(r,e?.gameLanguages??(e?.overlay?we(e.overlay.configuration.manifest):void 0)),s=Be(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:s},text:Ue(t?.fetcher??globalThis.fetch,o,t?.pathname),room:i.rooms,session:i.session,overlay:i.overlay}}async function ut(n){return ze(await Ie(n),void 0,n)}function dt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function ui(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>dt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(dt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function mt(n=li()){let e=null;return{connect(){return e??(e=Promise.all([ci(n),ui(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var pt=mt();globalThis.caisual=pt;var to=pt;export{pt as caisual,to as default};