@caisual/kit 0.5.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/kit.d.ts +2 -175
  2. package/dist/kit.js +1808 -76
  3. package/dist/node.d.ts +1 -88
  4. package/dist/node.js +354 -96
  5. package/dist/overlay.d.ts +1 -0
  6. package/dist/overlay.js +2074 -0
  7. package/dist/runtime.d.ts +1 -111
  8. package/dist/runtime.js +335 -67
  9. package/dist/server.d.ts +1 -71
  10. package/dist/server.js +3 -0
  11. package/dist/types/api.d.ts +25 -0
  12. package/dist/types/contracts/biglietto.d.ts +24 -0
  13. package/dist/types/contracts/device.d.ts +66 -0
  14. package/dist/types/contracts/firma.d.ts +21 -0
  15. package/dist/types/contracts/i18n.d.ts +12 -0
  16. package/dist/types/contracts/index.d.ts +13 -0
  17. package/dist/types/contracts/keys.d.ts +59 -0
  18. package/dist/types/contracts/manifest.d.ts +123 -0
  19. package/dist/types/contracts/overlay-boards.d.ts +3 -0
  20. package/dist/types/contracts/overlay.d.ts +223 -0
  21. package/dist/types/contracts/player.d.ts +1 -0
  22. package/dist/types/contracts/room-limits.d.ts +13 -0
  23. package/dist/types/contracts/runtime.d.ts +70 -0
  24. package/dist/types/contracts/server-js.d.ts +11 -0
  25. package/dist/types/contracts/slug.d.ts +5 -0
  26. package/dist/types/contracts/token-crew.d.ts +21 -0
  27. package/dist/types/daily.d.ts +3 -0
  28. package/dist/types/errors.d.ts +6 -0
  29. package/dist/types/handshake.d.ts +30 -0
  30. package/dist/types/http.d.ts +3 -0
  31. package/dist/types/index.d.ts +231 -0
  32. package/dist/types/kit.d.ts +28 -0
  33. package/dist/types/node/index.d.ts +97 -0
  34. package/dist/types/node/websocket.d.ts +29 -0
  35. package/dist/types/overlay/boards.d.ts +48 -0
  36. package/dist/types/overlay/bridge.d.ts +3 -0
  37. package/dist/types/overlay/host-bridge.d.ts +74 -0
  38. package/dist/types/overlay/i18n.d.ts +128 -0
  39. package/dist/types/overlay/index.d.ts +10 -0
  40. package/dist/types/overlay/shortcut.d.ts +4 -0
  41. package/dist/types/overlay/styles.d.ts +1 -0
  42. package/dist/types/overlay/ui-model.d.ts +45 -0
  43. package/dist/types/overlay/ui.d.ts +80 -0
  44. package/dist/types/overlay/voice-panel.d.ts +13 -0
  45. package/dist/types/protocollo.d.ts +262 -0
  46. package/dist/types/runtime/index.d.ts +128 -0
  47. package/dist/types/server/index.d.ts +76 -0
  48. package/dist/types/session/index.d.ts +49 -0
  49. package/dist/types/session/resume.d.ts +13 -0
  50. package/dist/types/standalone.d.ts +14 -0
  51. package/dist/types/stanza/index.d.ts +3 -0
  52. package/dist/types/stanza/json.d.ts +18 -0
  53. package/dist/types/stanza/nucleo.d.ts +100 -0
  54. package/dist/types/stanza/tipi.d.ts +136 -0
  55. package/dist/types/stanza-client/index.d.ts +24 -0
  56. package/dist/types/text.d.ts +2 -0
  57. package/dist/types/voce/index.d.ts +124 -0
  58. package/package.json +10 -2
@@ -0,0 +1,2074 @@
1
+ // ../contracts/src/slug.ts
2
+ var NOMI_RISERVATI = [
3
+ "www",
4
+ "api",
5
+ "app",
6
+ "play",
7
+ "live",
8
+ "multi",
9
+ "cdn",
10
+ "assets",
11
+ "static",
12
+ "mail",
13
+ "mx",
14
+ "ns1",
15
+ "ns2",
16
+ "autodiscover",
17
+ "_dmarc",
18
+ "admin",
19
+ "login",
20
+ "account",
21
+ "auth",
22
+ "pay",
23
+ "secure",
24
+ "support",
25
+ "help",
26
+ "blog",
27
+ "status",
28
+ "dev",
29
+ "staging",
30
+ "test",
31
+ "caisual",
32
+ "shipz"
33
+ ];
34
+ var RISERVATI = new Set(NOMI_RISERVATI);
35
+ var SLUG_NUOVO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
36
+ 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}$/;
37
+ function isValidSlug(value) {
38
+ return value.length >= 3 && value.length <= 32 && SLUG_NUOVO.test(value) || SLUG_STORICO.test(value);
39
+ }
40
+ function isReservedSlug(value) {
41
+ return RISERVATI.has(value);
42
+ }
43
+
44
+ // ../contracts/src/i18n.ts
45
+ function normalizeLanguage(value) {
46
+ if (typeof value !== "string" || value.length > 128) return null;
47
+ try {
48
+ return Intl.getCanonicalLocales(value)[0] ?? null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ function manifestLanguages(manifest) {
54
+ return manifest.languages?.length ? [...manifest.languages] : [manifest.language ?? "en"];
55
+ }
56
+ function languageFallbacks(language, defaultLanguage = "en") {
57
+ const result = [];
58
+ let tag = normalizeLanguage(language);
59
+ while (tag) {
60
+ result.push(tag);
61
+ const parts = tag.split("-");
62
+ parts.pop();
63
+ if (parts.at(-1)?.length === 1) parts.pop();
64
+ tag = parts.join("-");
65
+ }
66
+ result.push(normalizeLanguage(defaultLanguage) ?? defaultLanguage);
67
+ return [...new Set(result)];
68
+ }
69
+ function resolveText(value, language, defaultLanguage = "en", key = "") {
70
+ if (typeof value === "string") return value;
71
+ if (value) {
72
+ for (const tag of languageFallbacks(language, defaultLanguage)) {
73
+ const name = Object.keys(value).find((name2) => name2.toLowerCase() === tag.toLowerCase());
74
+ if (name !== void 0 && typeof value[name] === "string") return value[name];
75
+ }
76
+ }
77
+ return key;
78
+ }
79
+
80
+ // ../contracts/src/manifest.ts
81
+ function risolviModalita(manifest, mode) {
82
+ const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
83
+ if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");
84
+ return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
85
+ }
86
+ function risolviPresentazione(manifest, mode, language = manifestLanguages(manifest)[0]) {
87
+ risolviModalita(manifest, mode);
88
+ const scelta = manifest.modes.find((voce) => voce.id === mode);
89
+ return {
90
+ execution: scelta?.execution ?? null,
91
+ label: resolveText(scelta?.label, language, manifestLanguages(manifest)[0], scelta?.id ?? manifest.name ?? "Play"),
92
+ instructions: resolveText(scelta?.instructions, language, manifestLanguages(manifest)[0]) || null
93
+ };
94
+ }
95
+ var TETTO_GIOCATORI = 24;
96
+ var RITARDO_SPETTATORI_MS = 3e3;
97
+ var MASSIMO_CLASSIFICHE = 32;
98
+ var CAMPI = /* @__PURE__ */ new Set([
99
+ "overlay",
100
+ "manifest",
101
+ "id",
102
+ "name",
103
+ "description",
104
+ "cover",
105
+ "screenshots",
106
+ "tags",
107
+ "languages",
108
+ "language",
109
+ "platform",
110
+ "orientation",
111
+ "input",
112
+ "visibility",
113
+ "network",
114
+ "isolated",
115
+ "requires",
116
+ "players",
117
+ "lobby",
118
+ "persistent",
119
+ "spectators",
120
+ "boards",
121
+ "roles",
122
+ "teams",
123
+ "voice",
124
+ "modes"
125
+ ]);
126
+ var INPUT = /* @__PURE__ */ new Set(["keyboard", "mouse", "touch", "gamepad"]);
127
+ var PLATFORM = /* @__PURE__ */ new Set(["desktop", "mobile", "both"]);
128
+ var ORIENTATION = /* @__PURE__ */ new Set(["landscape", "portrait"]);
129
+ var VISIBILITY = /* @__PURE__ */ new Set(["public", "unlisted"]);
130
+ var VOICE = /* @__PURE__ */ new Set(["none", "room", "team", "proximity"]);
131
+ var PERFORMANCE = /* @__PURE__ */ new Set(["light", "medium", "heavy"]);
132
+ var TAG = /^[a-z0-9-]+$/;
133
+ var ID_INTERNO = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
134
+ var CAMPO_MATCHMAKING = /^[a-z0-9][a-z0-9-]{0,31}$/;
135
+ var ID_CLASSIFICA = /^[a-z0-9][a-z0-9_-]{0,31}$/;
136
+ function oggetto(value) {
137
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
138
+ return value;
139
+ }
140
+ function percorsoRelativo(value) {
141
+ if (value === "" || value.startsWith("/") || value.includes("\\") || value.includes("\0")) return false;
142
+ if (value.includes("?") || value.includes("#")) return false;
143
+ const parti = value.split("/");
144
+ if (parti.some((parte) => parte === "" || parte === "." || parte === "..")) return false;
145
+ try {
146
+ const decoded = parti.map((parte) => decodeURIComponent(parte));
147
+ return !decoded.some((parte) => parte === "" || parte === "." || parte === ".." || parte.includes("/"));
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+ function hostValido(value) {
153
+ if (value.length === 0 || value.length > 253) return false;
154
+ if (value.includes("://") || /[/:?#@]/.test(value)) return false;
155
+ const parti = value.split(".");
156
+ return parti.every(
157
+ (parte) => parte.length >= 1 && parte.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(parte)
158
+ );
159
+ }
160
+ function interoTra(value, min, max) {
161
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
162
+ }
163
+ function stringaDefault(dati, campo, valoreDefault, errori) {
164
+ const value = dati[campo];
165
+ if (value === void 0) return valoreDefault;
166
+ if (typeof value !== "string") {
167
+ errori.push(`${campo}: must be a string.`);
168
+ return valoreDefault;
169
+ }
170
+ return value;
171
+ }
172
+ function testoFacoltativo(value, key, max, path, errors) {
173
+ if (value[key] === void 0) return void 0;
174
+ const check = (text2, field2) => {
175
+ if (typeof text2 !== "string" || text2.trim().length === 0 || text2.trim().length > max || /[\r\n\u0000-\u001f]/.test(text2)) {
176
+ errors.push(`${field2}: must contain 1-${max} characters on one line.`);
177
+ return void 0;
178
+ }
179
+ return text2.trim();
180
+ };
181
+ const text = value[key], field = `${path}.${key}`;
182
+ if (typeof text === "string") return check(text, field);
183
+ const translations = oggetto(text);
184
+ if (!translations || Object.keys(translations).length === 0) {
185
+ errors.push(`${field}: must be a string or a non-empty language-to-text object.`);
186
+ return void 0;
187
+ }
188
+ const result = {};
189
+ for (const [raw, text2] of Object.entries(translations)) {
190
+ const tag = normalizeLanguage(raw);
191
+ if (!tag) {
192
+ errors.push(`${field}.${raw}: must be a BCP 47 language tag.`);
193
+ continue;
194
+ }
195
+ if (Object.hasOwn(result, tag)) errors.push(`${field}.${raw}: duplicate language.`);
196
+ const checked = check(text2, `${field}.${raw}`);
197
+ if (checked !== void 0) result[tag] = checked;
198
+ }
199
+ return result;
200
+ }
201
+ function validaManifest(valore) {
202
+ const errori = [];
203
+ const dati = oggetto(valore);
204
+ if (dati === null) return { ok: false, errori: ["manifest: must be a JSON object."] };
205
+ for (const campo of Object.keys(dati)) {
206
+ if (!CAMPI.has(campo)) errori.push(`${campo}: unknown field.`);
207
+ }
208
+ if (dati.manifest === void 0) errori.push("manifest: is required and must be 1.");
209
+ else if (dati.manifest !== 1) errori.push("manifest: must be exactly 1.");
210
+ const id = stringaDefault(dati, "id", "", errori);
211
+ if (dati.id === void 0) errori.push("id: is required.");
212
+ else if (typeof dati.id === "string") {
213
+ if (!isValidSlug(id)) {
214
+ errori.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters.");
215
+ } else if (isReservedSlug(id)) errori.push("id: this slug is reserved.");
216
+ }
217
+ const name = stringaDefault(dati, "name", "", errori);
218
+ if (dati.name === void 0) errori.push("name: is required.");
219
+ else if (typeof dati.name === "string" && (name.trim() === "" || name.length > 60)) {
220
+ errori.push("name: must contain 1-60 characters.");
221
+ }
222
+ const description = stringaDefault(dati, "description", "", errori);
223
+ if (description.length > 500) errori.push("description: must be at most 500 characters.");
224
+ let cover = null;
225
+ if (dati.cover !== void 0 && dati.cover !== null) {
226
+ if (typeof dati.cover !== "string") errori.push("cover: must be a relative file path or null.");
227
+ else if (!percorsoRelativo(dati.cover)) errori.push("cover: must be a relative file path without query, fragment, or parent segments.");
228
+ else cover = dati.cover;
229
+ }
230
+ const screenshots = [];
231
+ if (dati.screenshots !== void 0) {
232
+ if (!Array.isArray(dati.screenshots)) errori.push("screenshots: must be an array of relative file paths.");
233
+ else {
234
+ if (dati.screenshots.length > 8) errori.push("screenshots: must contain at most 8 paths.");
235
+ for (const [indice, value] of dati.screenshots.entries()) {
236
+ if (typeof value !== "string" || !percorsoRelativo(value)) {
237
+ errori.push(`screenshots[${indice}]: must be a relative file path without query, fragment, or parent segments.`);
238
+ } else screenshots.push(value);
239
+ }
240
+ }
241
+ }
242
+ const tags = [];
243
+ if (dati.tags !== void 0) {
244
+ if (!Array.isArray(dati.tags)) errori.push("tags: must be an array.");
245
+ else {
246
+ if (dati.tags.length > 10) errori.push("tags: must contain at most 10 tags.");
247
+ for (const [indice, value] of dati.tags.entries()) {
248
+ if (typeof value !== "string" || value.length > 24 || !TAG.test(value)) {
249
+ errori.push(`tags[${indice}]: must be 1-24 lowercase letters, digits, or hyphens.`);
250
+ } else tags.push(value);
251
+ }
252
+ }
253
+ }
254
+ const legacyLanguage = stringaDefault(dati, "language", "en", errori);
255
+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(legacyLanguage)) {
256
+ errori.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");
257
+ }
258
+ const languages2 = [];
259
+ if (dati.languages === void 0) languages2.push(normalizeLanguage(legacyLanguage) ?? legacyLanguage);
260
+ else if (!Array.isArray(dati.languages) || dati.languages.length === 0) {
261
+ errori.push("languages: must be a non-empty array of BCP 47 language tags.");
262
+ } else for (const [index, raw] of dati.languages.entries()) {
263
+ const tag = normalizeLanguage(raw);
264
+ if (!tag) errori.push(`languages[${index}]: must be a BCP 47 language tag.`);
265
+ else if (languages2.includes(tag)) errori.push(`languages[${index}]: duplicate language ${tag}.`);
266
+ else languages2.push(tag);
267
+ }
268
+ const language = languages2[0] ?? legacyLanguage;
269
+ if (dati.language !== void 0 && dati.languages !== void 0 && legacyLanguage.toLowerCase() !== language.toLowerCase()) {
270
+ errori.push("language: must match the first entry in languages when both are present.");
271
+ }
272
+ let platform = "both";
273
+ if (dati.platform === void 0) errori.push("platform: is required.");
274
+ else if (typeof dati.platform !== "string" || !PLATFORM.has(dati.platform)) {
275
+ errori.push("platform: must be desktop, mobile, or both.");
276
+ } else platform = dati.platform;
277
+ let orientation = "landscape";
278
+ if (dati.orientation !== void 0) {
279
+ if (typeof dati.orientation !== "string" || !ORIENTATION.has(dati.orientation)) {
280
+ errori.push("orientation: must be landscape or portrait.");
281
+ } else orientation = dati.orientation;
282
+ }
283
+ const input = [];
284
+ if (dati.input !== void 0) {
285
+ if (!Array.isArray(dati.input)) errori.push("input: must be an array.");
286
+ else for (const [indice, value] of dati.input.entries()) {
287
+ if (typeof value !== "string" || !INPUT.has(value)) {
288
+ errori.push(`input[${indice}]: must be keyboard, mouse, touch, or gamepad.`);
289
+ } else if (input.includes(value)) errori.push(`input[${indice}]: duplicate value ${value}.`);
290
+ else input.push(value);
291
+ }
292
+ }
293
+ let visibility = "public";
294
+ if (dati.visibility !== void 0) {
295
+ if (typeof dati.visibility !== "string" || !VISIBILITY.has(dati.visibility)) {
296
+ errori.push("visibility: must be public or unlisted.");
297
+ } else visibility = dati.visibility;
298
+ }
299
+ const network = [];
300
+ if (dati.network !== void 0) {
301
+ if (!Array.isArray(dati.network)) errori.push("network: must be an array of host names.");
302
+ else for (const [indice, value] of dati.network.entries()) {
303
+ if (typeof value !== "string" || !hostValido(value)) {
304
+ errori.push(`network[${indice}]: must be a host name without scheme, port, path, query, or fragment.`);
305
+ } else if (network.includes(value)) errori.push(`network[${indice}]: duplicate host ${value}.`);
306
+ else network.push(value);
307
+ }
308
+ }
309
+ let isolated = false;
310
+ if (dati.isolated !== void 0) {
311
+ if (typeof dati.isolated !== "boolean") errori.push("isolated: must be a boolean.");
312
+ else isolated = dati.isolated;
313
+ }
314
+ const requires = {
315
+ webgl2: false,
316
+ webgpu: false,
317
+ wasm: false,
318
+ threads: false,
319
+ memoryMb: null,
320
+ performance: "light"
321
+ };
322
+ if (dati.requires !== void 0) {
323
+ const value = oggetto(dati.requires);
324
+ if (value === null) errori.push("requires: must be an object.");
325
+ else {
326
+ for (const campo of Object.keys(value)) {
327
+ if (!["webgl2", "webgpu", "wasm", "threads", "memoryMb", "performance"].includes(campo)) {
328
+ errori.push(`requires.${campo}: unknown field.`);
329
+ }
330
+ }
331
+ for (const campo of ["webgl2", "webgpu", "wasm", "threads"]) {
332
+ if (value[campo] === void 0) continue;
333
+ if (typeof value[campo] !== "boolean") errori.push(`requires.${campo}: must be a boolean.`);
334
+ else requires[campo] = value[campo];
335
+ }
336
+ if (value.memoryMb !== void 0) {
337
+ if (value.memoryMb !== null && (!interoTra(value.memoryMb, 512, 32768) || value.memoryMb % 256 !== 0)) {
338
+ errori.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null.");
339
+ } else requires.memoryMb = value.memoryMb;
340
+ }
341
+ if (value.performance !== void 0) {
342
+ if (typeof value.performance !== "string" || !PERFORMANCE.has(value.performance)) {
343
+ errori.push("requires.performance: must be light, medium, or heavy.");
344
+ } else requires.performance = value.performance;
345
+ }
346
+ if (requires.threads && !isolated) errori.push("requires.threads: needs isolated: true.");
347
+ }
348
+ }
349
+ let players = { min: 1, max: 1 };
350
+ if (dati.players !== void 0) {
351
+ const value = oggetto(dati.players);
352
+ if (value === null) errori.push("players: must be an object with min and max.");
353
+ else {
354
+ for (const campo of Object.keys(value)) {
355
+ if (campo !== "min" && campo !== "max") errori.push(`players.${campo}: unknown field.`);
356
+ }
357
+ if (!interoTra(value.min, 1, TETTO_GIOCATORI)) errori.push(`players.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
358
+ if (!interoTra(value.max, 1, TETTO_GIOCATORI)) errori.push(`players.max: must be an integer from 1 to ${TETTO_GIOCATORI} in manifest version 1.`);
359
+ if (interoTra(value.min, 1, TETTO_GIOCATORI) && interoTra(value.max, 1, TETTO_GIOCATORI)) {
360
+ if (value.min > value.max) errori.push("players.max: must be greater than or equal to players.min.");
361
+ else players = { min: value.min, max: value.max };
362
+ }
363
+ }
364
+ }
365
+ let lobby = false;
366
+ if (dati.lobby !== void 0) {
367
+ if (typeof dati.lobby !== "boolean") errori.push("lobby: must be a boolean.");
368
+ else lobby = dati.lobby;
369
+ }
370
+ let persistent = false;
371
+ if (dati.persistent !== void 0) {
372
+ if (typeof dati.persistent !== "boolean") errori.push("persistent: must be a boolean.");
373
+ else persistent = dati.persistent;
374
+ }
375
+ let spectators = { delayMs: RITARDO_SPETTATORI_MS };
376
+ if (dati.spectators === false || dati.spectators === null) spectators = null;
377
+ else if (dati.spectators !== void 0 && dati.spectators !== true) {
378
+ const value = oggetto(dati.spectators);
379
+ if (value === null) {
380
+ errori.push("spectators: must be a boolean or an object with delayMs.");
381
+ } else {
382
+ for (const campo of Object.keys(value)) {
383
+ if (campo !== "delayMs") errori.push(`spectators.${campo}: unknown field.`);
384
+ }
385
+ if (!interoTra(value.delayMs, 0, 3e4)) {
386
+ errori.push("spectators.delayMs: must be an integer from 0 to 30000.");
387
+ } else spectators = { delayMs: value.delayMs };
388
+ }
389
+ }
390
+ let overlay = null;
391
+ if (dati.overlay !== void 0 && dati.overlay !== null) {
392
+ const value = oggetto(dati.overlay);
393
+ if (value === null) errori.push("overlay: must be an object or null.");
394
+ else {
395
+ for (const key of Object.keys(value)) if (!["version", "accent"].includes(key)) errori.push(`overlay.${key}: unknown field.`);
396
+ if (value.version !== 1) errori.push("overlay.version: must be exactly 1.");
397
+ if (value.accent !== void 0 && (typeof value.accent !== "string" || !/^#[0-9a-fA-F]{6}$/.test(value.accent))) {
398
+ errori.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699.");
399
+ }
400
+ overlay = { version: 1, ...typeof value.accent === "string" ? { accent: value.accent } : {} };
401
+ }
402
+ }
403
+ const boards = {};
404
+ if (dati.boards !== void 0) {
405
+ const value = oggetto(dati.boards);
406
+ if (value === null) errori.push("boards: must be an object of board ids.");
407
+ else {
408
+ if (Object.keys(value).length > MASSIMO_CLASSIFICHE) {
409
+ errori.push(`boards: at most ${MASSIMO_CLASSIFICHE} boards.`);
410
+ }
411
+ for (const [id2, raw] of Object.entries(value)) {
412
+ let valido = true;
413
+ if (!ID_CLASSIFICA.test(id2)) {
414
+ errori.push(`boards.${id2}: invalid board id.`);
415
+ valido = false;
416
+ }
417
+ const board = oggetto(raw);
418
+ if (board === null) {
419
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
420
+ continue;
421
+ }
422
+ for (const campo of Object.keys(board)) {
423
+ if (!["source", "label", "periods"].includes(campo)) errori.push(`boards.${id2}.${campo}: unknown field.`);
424
+ }
425
+ if (board.source !== "client" && board.source !== "server") {
426
+ errori.push(`boards.${id2}.source: must be "client" or "server".`);
427
+ valido = false;
428
+ }
429
+ const label = testoFacoltativo(board, "label", 48, `boards.${id2}`, errori);
430
+ let periods = ["all-time"];
431
+ if (board.periods !== void 0) {
432
+ if (!Array.isArray(board.periods) || board.periods.length < 1 || board.periods.length > 2 || board.periods.some((period) => period !== "daily" && period !== "all-time") || new Set(board.periods).size !== board.periods.length) {
433
+ errori.push(`boards.${id2}.periods: must contain daily, all-time, or both without duplicates.`);
434
+ } else periods = [...board.periods];
435
+ }
436
+ if (valido) Object.defineProperty(boards, id2, { value: {
437
+ source: board.source,
438
+ periods,
439
+ ...label === void 0 ? {} : { label }
440
+ }, enumerable: true, configurable: true, writable: true });
441
+ }
442
+ }
443
+ }
444
+ const roles = [];
445
+ if (dati.roles !== void 0) {
446
+ if (!Array.isArray(dati.roles)) errori.push("roles: must be an array.");
447
+ else {
448
+ const ids = /* @__PURE__ */ new Set();
449
+ for (const [indice, raw] of dati.roles.entries()) {
450
+ const value = oggetto(raw);
451
+ if (value === null) {
452
+ errori.push(`roles[${indice}]: must be an object.`);
453
+ continue;
454
+ }
455
+ for (const campo of Object.keys(value)) {
456
+ if (!["id", "min", "max", "label"].includes(campo)) errori.push(`roles[${indice}].${campo}: unknown field.`);
457
+ }
458
+ const idRuolo = value.id;
459
+ const min = value.min;
460
+ const max = value.max;
461
+ let valido = true;
462
+ if (typeof idRuolo !== "string" || idRuolo.length > 32 || !ID_INTERNO.test(idRuolo)) {
463
+ errori.push(`roles[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
464
+ valido = false;
465
+ } else if (ids.has(idRuolo)) {
466
+ errori.push(`roles[${indice}].id: duplicate role ${idRuolo}.`);
467
+ valido = false;
468
+ } else ids.add(idRuolo);
469
+ if (!interoTra(min, 0, TETTO_GIOCATORI)) {
470
+ errori.push(`roles[${indice}].min: must be an integer from 0 to ${TETTO_GIOCATORI}.`);
471
+ valido = false;
472
+ }
473
+ if (max !== void 0 && !interoTra(max, 0, TETTO_GIOCATORI)) {
474
+ errori.push(`roles[${indice}].max: must be an integer from 0 to ${TETTO_GIOCATORI} when present.`);
475
+ valido = false;
476
+ }
477
+ if (typeof min === "number" && typeof max === "number" && min > max) {
478
+ errori.push(`roles[${indice}].max: must be greater than or equal to min.`);
479
+ valido = false;
480
+ }
481
+ const label = testoFacoltativo(value, "label", 32, `roles[${indice}]`, errori);
482
+ if (valido) roles.push({
483
+ id: idRuolo,
484
+ min,
485
+ ...max === void 0 ? {} : { max },
486
+ ...label === void 0 ? {} : { label }
487
+ });
488
+ }
489
+ }
490
+ }
491
+ let teams = null;
492
+ if (dati.teams !== void 0 && dati.teams !== null) {
493
+ const value = oggetto(dati.teams);
494
+ if (value === null) errori.push("teams: must be null or an object with min and max.");
495
+ else {
496
+ for (const campo of Object.keys(value)) {
497
+ if (campo !== "min" && campo !== "max") errori.push(`teams.${campo}: unknown field.`);
498
+ }
499
+ if (!interoTra(value.min, 2, TETTO_GIOCATORI)) errori.push(`teams.min: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
500
+ if (!interoTra(value.max, 2, TETTO_GIOCATORI)) errori.push(`teams.max: must be an integer from 2 to ${TETTO_GIOCATORI}.`);
501
+ if (interoTra(value.min, 2, TETTO_GIOCATORI) && interoTra(value.max, 2, TETTO_GIOCATORI)) {
502
+ if (value.min > value.max) errori.push("teams.max: must be greater than or equal to teams.min.");
503
+ else teams = { min: value.min, max: value.max };
504
+ }
505
+ }
506
+ }
507
+ let voice = "none";
508
+ if (dati.voice !== void 0) {
509
+ if (typeof dati.voice !== "string" || !VOICE.has(dati.voice)) {
510
+ errori.push("voice: must be none, room, team, or proximity.");
511
+ } else voice = dati.voice;
512
+ }
513
+ const modes = [];
514
+ if (dati.modes !== void 0) {
515
+ if (!Array.isArray(dati.modes)) errori.push("modes: must be an array.");
516
+ else {
517
+ const ids = /* @__PURE__ */ new Set();
518
+ for (const [indice, raw] of dati.modes.entries()) {
519
+ const value = oggetto(raw);
520
+ if (value === null) {
521
+ errori.push(`modes[${indice}]: must be an object.`);
522
+ continue;
523
+ }
524
+ for (const campo of Object.keys(value)) {
525
+ if (!["id", "players", "lobby", "matchmaking", "execution", "label", "instructions"].includes(campo)) errori.push(`modes[${indice}].${campo}: unknown field.`);
526
+ }
527
+ if (typeof value.id !== "string" || value.id.length > 32 || !ID_INTERNO.test(value.id)) {
528
+ errori.push(`modes[${indice}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);
529
+ continue;
530
+ }
531
+ if (ids.has(value.id)) {
532
+ errori.push(`modes[${indice}].id: duplicate mode ${value.id}.`);
533
+ continue;
534
+ }
535
+ ids.add(value.id);
536
+ const modo = { id: value.id };
537
+ for (const [key2, max] of [["label", 48], ["instructions", 160]]) {
538
+ const text = testoFacoltativo(value, key2, max, `modes[${indice}]`, errori);
539
+ if (text !== void 0) modo[key2] = text;
540
+ }
541
+ if (value.execution !== void 0) {
542
+ if (value.execution !== "local" && value.execution !== "room") errori.push(`modes[${indice}].execution: must be local or room.`);
543
+ else modo.execution = value.execution;
544
+ }
545
+ if (overlay !== null && modo.execution === void 0) errori.push(`modes[${indice}].execution: is required with the standard overlay.`);
546
+ if (value.players !== void 0) {
547
+ const campo = `modes[${indice}].players`;
548
+ const range = oggetto(value.players);
549
+ if (range === null) errori.push(`${campo}: must be an object with min and max.`);
550
+ else {
551
+ for (const key2 of Object.keys(range)) {
552
+ if (key2 !== "min" && key2 !== "max") errori.push(`${campo}.${key2}: unknown field.`);
553
+ }
554
+ if (!interoTra(range.min, 1, TETTO_GIOCATORI)) errori.push(`${campo}.min: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
555
+ if (!interoTra(range.max, 1, TETTO_GIOCATORI)) errori.push(`${campo}.max: must be an integer from 1 to ${TETTO_GIOCATORI}.`);
556
+ if (interoTra(range.min, 1, TETTO_GIOCATORI) && interoTra(range.max, 1, TETTO_GIOCATORI)) {
557
+ if (range.min > range.max) errori.push(`${campo}.max: must be greater than or equal to min.`);
558
+ else modo.players = { min: range.min, max: range.max };
559
+ }
560
+ }
561
+ }
562
+ if (value.lobby !== void 0) {
563
+ if (typeof value.lobby !== "boolean") errori.push(`modes[${indice}].lobby: must be a boolean.`);
564
+ else modo.lobby = value.lobby;
565
+ }
566
+ if (modo.execution === "local") {
567
+ const range = modo.players ?? players;
568
+ if (range.min !== 1 || range.max !== 1) errori.push(`modes[${indice}].players: local execution requires min and max to be 1.`);
569
+ if (modo.lobby ?? lobby) errori.push(`modes[${indice}].lobby: local execution requires false.`);
570
+ if (value.matchmaking !== void 0) errori.push(`modes[${indice}].matchmaking: local execution cannot use matchmaking.`);
571
+ }
572
+ if (value.matchmaking === void 0) {
573
+ modes.push(modo);
574
+ continue;
575
+ }
576
+ const matchmaking = oggetto(value.matchmaking);
577
+ if (matchmaking === null) {
578
+ errori.push(`modes[${indice}].matchmaking: must be an object.`);
579
+ continue;
580
+ }
581
+ for (const campo of Object.keys(matchmaking)) {
582
+ if (!["key", "timeoutMs", "defaults"].includes(campo)) {
583
+ errori.push(`modes[${indice}].matchmaking.${campo}: unknown field.`);
584
+ }
585
+ }
586
+ let valido = true;
587
+ const key = [];
588
+ if (!Array.isArray(matchmaking.key) || matchmaking.key.length < 1 || matchmaking.key.length > 8) {
589
+ errori.push(`modes[${indice}].matchmaking.key: must contain from 1 to 8 fields.`);
590
+ valido = false;
591
+ } else for (const [keyIndice, item] of matchmaking.key.entries()) {
592
+ if (typeof item !== "string" || !CAMPO_MATCHMAKING.test(item)) {
593
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`);
594
+ valido = false;
595
+ } else if (key.includes(item)) {
596
+ errori.push(`modes[${indice}].matchmaking.key[${keyIndice}]: duplicate field ${item}.`);
597
+ valido = false;
598
+ } else key.push(item);
599
+ }
600
+ if (!interoTra(matchmaking.timeoutMs, 1e3, 3e5)) {
601
+ errori.push(`modes[${indice}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`);
602
+ valido = false;
603
+ }
604
+ let defaults;
605
+ if (matchmaking.defaults !== void 0) {
606
+ const values = oggetto(matchmaking.defaults);
607
+ if (values === null || Object.keys(values).length !== key.length || key.some((field) => !Object.hasOwn(values, field))) {
608
+ errori.push(`modes[${indice}].matchmaking.defaults: must contain exactly the declared key fields.`);
609
+ } else {
610
+ defaults = {};
611
+ for (const [field, value2] of Object.entries(values)) {
612
+ if (!(typeof value2 === "string" && value2.length >= 1 && value2.length <= 64 && /^[A-Za-z0-9_.:-]+$/.test(value2)) && !Number.isSafeInteger(value2)) {
613
+ errori.push(`modes[${indice}].matchmaking.defaults.${field}: must be a string of 1-64 characters or a safe integer.`);
614
+ } else Object.defineProperty(defaults, field, { value: value2, enumerable: true });
615
+ }
616
+ }
617
+ }
618
+ if (valido) modes.push({ ...modo, matchmaking: {
619
+ ...defaults === void 0 ? {} : { defaults },
620
+ key,
621
+ timeoutMs: matchmaking.timeoutMs
622
+ } });
623
+ }
624
+ }
625
+ }
626
+ if (overlay !== null && modes.length === 0) errori.push("modes: at least one explicit mode is required with the standard overlay.");
627
+ if (errori.length > 0) return { ok: false, errori };
628
+ return { ok: true, manifest: {
629
+ manifest: 1,
630
+ overlay,
631
+ id,
632
+ name,
633
+ description,
634
+ cover,
635
+ screenshots,
636
+ tags,
637
+ languages: languages2,
638
+ language,
639
+ platform,
640
+ orientation,
641
+ input,
642
+ visibility,
643
+ network,
644
+ isolated,
645
+ requires,
646
+ players,
647
+ lobby,
648
+ persistent,
649
+ spectators,
650
+ boards,
651
+ roles,
652
+ teams,
653
+ voice,
654
+ modes
655
+ } };
656
+ }
657
+
658
+ // ../contracts/src/overlay.ts
659
+ var OVERLAY_PANELS = ["home", "room", "invite", "friends", "voice", "boards"];
660
+ function overlayConfiguration(manifest, coverUrl = null, invite = null) {
661
+ const validated = validaManifest(manifest);
662
+ if (!validated.ok) throw new Error("The overlay manifest is invalid.");
663
+ return { manifest: validated.manifest, coverUrl, invite };
664
+ }
665
+ function record(value) {
666
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
667
+ }
668
+ function validSafeArea(value) {
669
+ const area = record(value);
670
+ 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);
671
+ }
672
+ function validOverlayView(value) {
673
+ const data = record(value);
674
+ 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) => {
675
+ const rect = record(value2);
676
+ 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);
677
+ });
678
+ }
679
+ function validOverlayRequest(value) {
680
+ const message = record(value), args = record(message?.args);
681
+ 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;
682
+ 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;
683
+ const keys = (...allowed) => Object.keys(args).every((key) => allowed.includes(key));
684
+ const text = (key) => typeof args[key] === "string" && args[key].length >= 1 && args[key].length <= 64;
685
+ switch (message.op) {
686
+ case "local.start":
687
+ return keys("mode") && text("mode");
688
+ case "room.create":
689
+ return keys("mode") && (args.mode === null || text("mode"));
690
+ case "room.join":
691
+ return keys("code") && (args.code === void 0 || text("code"));
692
+ case "room.watch":
693
+ return keys("code") && text("code");
694
+ case "room.match": {
695
+ const key = record(args.key);
696
+ 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)));
697
+ }
698
+ case "room.ready":
699
+ return keys("ready") && typeof args.ready === "boolean";
700
+ case "room.role":
701
+ case "room.requestRole":
702
+ return keys("role") && text("role");
703
+ case "room.team":
704
+ return keys("team") && Number.isInteger(args.team) && args.team >= 1 && args.team <= 24;
705
+ case "room.restart":
706
+ case "room.start":
707
+ case "session.cancel":
708
+ case "session.leave":
709
+ case "session.disconnect":
710
+ case "session.resume":
711
+ return keys();
712
+ case "voice.join":
713
+ case "voice.leave":
714
+ return keys() && typeof message.sessionId === "string";
715
+ case "voice.mute":
716
+ return keys("muted") && typeof args.muted === "boolean" && typeof message.sessionId === "string";
717
+ case "voice.setVolume":
718
+ 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;
719
+ case "overlay.view":
720
+ return validOverlayView(args);
721
+ default:
722
+ return false;
723
+ }
724
+ }
725
+ function validBoardDay(value) {
726
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
727
+ const at = Date.parse(`${value}T00:00:00Z`);
728
+ return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
729
+ }
730
+ function validOverlaySessionState(value) {
731
+ const data = record(value);
732
+ const exact = (v, keys) => v !== null && Object.keys(v).length === keys.length && Object.keys(v).every((key) => keys.includes(key));
733
+ const text = (v) => typeof v === "string" && v.length <= 128;
734
+ const nullable = (v) => v === null || text(v);
735
+ const finite = (v) => typeof v === "number" && Number.isFinite(v);
736
+ if (!data || !exact(data, ["kind", "id", "mode", "localStatus", "ready", "capabilities", "room", "waiting", "resume", "resumeError", ..."voice" in data ? ["voice"] : []])) return false;
737
+ if (data.voice !== void 0 && data.voice !== null && (data.kind !== "room" || !record(data.room) || !validOverlayVoice(data.voice))) return false;
738
+ const capabilities = record(data.capabilities), room = record(data.room), waiting = record(data.waiting), resume = record(data.resume);
739
+ if (!["boot", "home", "attaching", "matching", "local", "room", "watch"].includes(String(data.kind)) || !nullable(data.id) || !nullable(data.mode) || ![null, "playing", "ended"].includes(data.localStatus) || typeof data.ready !== "boolean" || typeof data.resumeError !== "boolean" || !exact(capabilities, ["local", "rooms", "overlay", "requestRole"]) || !Object.values(capabilities).every((v) => typeof v === "boolean")) return false;
740
+ if (data.waiting !== null && (!exact(waiting, ["players", "min", "max"]) || !Object.values(waiting).every((v) => Number.isInteger(v) && Number(v) >= 0 && Number(v) <= 24))) return false;
741
+ if (data.resume !== null && (!exact(resume, ["version", "code", "mode", "updatedAt"]) || resume.version !== 1 || !text(resume.code) || !nullable(resume.mode) || !finite(resume.updatedAt))) return false;
742
+ if (data.room === null) return true;
743
+ if (!exact(room, ["code", "mode", "status", "host", "you", "players", "countdownAt", "connection", "closedCode", "limits", "lobby", "persistent", "delayMs", "requestRole"]) || !room) return false;
744
+ const limits = record(room.limits);
745
+ return text(room.code) && nullable(room.mode) && nullable(room.host) && nullable(room.you) && ["lobby", "countdown", "playing", "finished", "ended"].includes(String(room.status)) && ["connecting", "connected", "reconnecting", "disconnected", "ended", "closed", "replaced"].includes(String(room.connection)) && ["countdownAt", "closedCode", "delayMs"].every((key) => room[key] === null || finite(room[key])) && ["lobby", "persistent", "requestRole"].every((key) => typeof room[key] === "boolean") && exact(limits, ["min", "max"]) && Object.values(limits).every((v) => Number.isInteger(v) && Number(v) >= 1 && Number(v) <= 24) && Array.isArray(room.players) && room.players.length <= 24 && room.players.every((value2) => {
746
+ const player = record(value2);
747
+ return exact(player, ["id", "name", "guest", "role", "team", "ready", "connected"]) && player !== null && text(player.id) && text(player.name) && nullable(player.role) && (player.team === null || Number.isInteger(player.team) && Number(player.team) >= 1 && Number(player.team) <= 24) && ["guest", "ready", "connected"].every((key) => typeof player[key] === "boolean");
748
+ });
749
+ }
750
+ function validOverlayVoice(value) {
751
+ const voice = record(value);
752
+ if (!voice || Object.keys(voice).length !== 6 || !["mode", "state", "mic", "muted", "speaking", "peers"].every((key) => key in voice) || !["room", "team", "proximity"].includes(String(voice.mode)) || !["off", "joining", "on", "reconnecting"].includes(String(voice.state)) || !["mic", "muted", "speaking"].every((key) => typeof voice[key] === "boolean") || !Array.isArray(voice.peers) || voice.peers.length > 24) return false;
753
+ const ids = /* @__PURE__ */ new Set();
754
+ return voice.peers.every((value2) => {
755
+ const peer = record(value2);
756
+ if (!peer || Object.keys(peer).length !== 5 || !["id", "mic", "muted", "speaking", "volume"].every((key) => key in peer) || typeof peer.id !== "string" || !peer.id.length || peer.id.length > 128 || ids.has(peer.id) || !["mic", "muted", "speaking"].every((key) => typeof peer[key] === "boolean") || typeof peer.volume !== "number" || !Number.isFinite(peer.volume) || peer.volume < 0 || peer.volume > 1) return false;
757
+ ids.add(peer.id);
758
+ return true;
759
+ });
760
+ }
761
+
762
+ // src/errors.ts
763
+ function creaErrore(code, message) {
764
+ return Object.assign(new Error(message), { name: "CaisualError", code });
765
+ }
766
+
767
+ // src/overlay/host-bridge.ts
768
+ function eMessaggioReady(value) {
769
+ return record(value)?.type === "caisual:ready";
770
+ }
771
+ function eRichiestaBiglietto(value) {
772
+ const data = record(value);
773
+ return data?.type === "caisual:ticket" && (data.aud === void 0 || data.aud === "portal" || data.aud === "live");
774
+ }
775
+ function stanzaDaMessaggio(value) {
776
+ const data = record(value);
777
+ if (data?.type !== "caisual:room") return void 0;
778
+ if (data.room === null) return null;
779
+ const room = record(data.room);
780
+ return typeof room?.code === "string" && /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(room.code) ? { code: room.code } : void 0;
781
+ }
782
+ function creaPonteOspite(input) {
783
+ let port = null, epoch = null, instance = null;
784
+ let disposed = false, legacyReady = true, sequence = 0, requestId = 0;
785
+ let state = null, clockOffset = null;
786
+ let polling = null, pollingEnd = null;
787
+ const pending = /* @__PURE__ */ new Map();
788
+ const states = /* @__PURE__ */ new Set();
789
+ const shortcuts = /* @__PURE__ */ new Set();
790
+ const opens = /* @__PURE__ */ new Set();
791
+ const errors = /* @__PURE__ */ new Set();
792
+ const scores = /* @__PURE__ */ new Set();
793
+ const notify = (listeners, value) => {
794
+ for (const listener of listeners) try {
795
+ listener(value);
796
+ } catch {
797
+ }
798
+ };
799
+ const rejectPending = () => {
800
+ for (const value of pending.values()) {
801
+ input.finestra.clearTimeout(value.timer);
802
+ value.reject(creaErrore("session_replaced", "The game document changed."));
803
+ }
804
+ pending.clear();
805
+ };
806
+ const stopPolling = () => {
807
+ if (polling !== null) input.finestra.clearInterval(polling);
808
+ if (pollingEnd !== null) input.finestra.clearTimeout(pollingEnd);
809
+ polling = pollingEnd = null;
810
+ };
811
+ const askReady = () => {
812
+ if (!disposed && input.frame.src !== "") input.frame.contentWindow?.postMessage({ type: "caisual:ready?" }, input.origineGioco);
813
+ };
814
+ const poll = () => {
815
+ stopPolling();
816
+ polling = input.finestra.setInterval(askReady, 500);
817
+ pollingEnd = input.finestra.setTimeout(stopPolling, 1e4);
818
+ askReady();
819
+ };
820
+ const loaded = () => {
821
+ legacyReady = true;
822
+ poll();
823
+ };
824
+ const listen = (event) => {
825
+ if (disposed || event.origin !== input.origineGioco || event.source !== input.frame.contentWindow || !eMessaggioReady(event.data)) return;
826
+ const data = record(event.data);
827
+ const nextInstance = typeof data.instance === "string" && data.instance.length <= 128 ? data.instance : null;
828
+ if (port && (nextInstance !== null ? nextInstance === instance : !legacyReady)) return;
829
+ stopPolling();
830
+ legacyReady = false;
831
+ instance = nextInstance;
832
+ rejectPending();
833
+ port?.close();
834
+ input.onRoom(null);
835
+ epoch = input.epoch?.() ?? crypto.randomUUID();
836
+ sequence = requestId = 0;
837
+ state = null;
838
+ clockOffset = null;
839
+ notify(states, null);
840
+ const channel = input.creaCanale?.() ?? new MessageChannel();
841
+ const currentPort = channel.port1, currentEpoch = epoch;
842
+ port = currentPort;
843
+ const current = () => !disposed && port === currentPort && epoch === currentEpoch;
844
+ currentPort.onmessage = (event2) => {
845
+ if (!current()) return;
846
+ const data2 = record(event2.data);
847
+ if (eRichiestaBiglietto(data2)) {
848
+ const aud = data2?.aud === "live" ? "live" : "portal";
849
+ void input.rinnova(aud).then((ticket) => {
850
+ if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, ticket });
851
+ }).catch(() => {
852
+ if (current()) currentPort.postMessage({ type: "caisual:ticket", aud, error: "offline" });
853
+ });
854
+ return;
855
+ }
856
+ const room = stanzaDaMessaggio(data2);
857
+ if (room !== void 0) {
858
+ input.onRoom(room);
859
+ return;
860
+ }
861
+ if (data2?.v !== 1 || data2.epoch !== currentEpoch) return;
862
+ if (data2.type === "caisual:overlay-response" && typeof data2.requestId === "string") {
863
+ const item = pending.get(data2.requestId);
864
+ if (!item) return;
865
+ if (data2.ok !== true && (data2.ok !== false || typeof record(data2.error)?.code !== "string" || typeof record(data2.error)?.message !== "string")) return;
866
+ pending.delete(data2.requestId);
867
+ input.finestra.clearTimeout(item.timer);
868
+ const response = data2;
869
+ if (response.ok) item.resolve();
870
+ else item.reject(creaErrore(response.error.code, response.error.message));
871
+ } else if (data2.type === "caisual:overlay-state" && Number.isSafeInteger(data2.seq) && data2.seq > sequence) {
872
+ if (!validOverlaySessionState(data2.state) || typeof data2.serverTime !== "number" || !Number.isFinite(data2.serverTime)) return;
873
+ clockOffset = data2.serverTime - Date.now();
874
+ sequence = data2.seq;
875
+ state = structuredClone(data2.state);
876
+ notify(states, state);
877
+ } else if (data2.type === "caisual:overlay-error" && data2.sessionId === state?.id) {
878
+ const error = record(data2.error);
879
+ if (typeof error?.code === "string" && typeof error.message === "string") notify(errors, { sessionId: data2.sessionId, error: { code: error.code, message: error.message } });
880
+ } else if (data2.type === "caisual:overlay-shortcut") {
881
+ notify(shortcuts, void 0);
882
+ } else if (data2.type === "caisual:overlay-open" && OVERLAY_PANELS.includes(data2.panel)) {
883
+ notify(opens, data2.panel);
884
+ } else if (data2.type === "caisual:overlay-score") {
885
+ const score = record(data2.score);
886
+ if (score && typeof score.board === "string" && typeof score.player === "string" && Number.isSafeInteger(score.score) && Number.isFinite(score.submittedAt) && (score.day === null || typeof score.day === "string")) {
887
+ notify(scores, { board: score.board, player: score.player, score: score.score, day: score.day, submittedAt: score.submittedAt });
888
+ }
889
+ }
890
+ };
891
+ currentPort.start();
892
+ input.frame.contentWindow?.postMessage({
893
+ type: "caisual:hello",
894
+ ticket: input.ticket,
895
+ live: input.origineLive,
896
+ invite: input.invite,
897
+ // language resta disponibile ai kit pubblicati prima della separazione delle lingue.
898
+ ...input.language ? { language: input.language, uiLanguage: input.language } : {},
899
+ ...input.languagePreferences ? { languagePreferences: input.languagePreferences } : {},
900
+ ...input.configuration ? { gameLanguages: manifestLanguages(input.configuration.manifest) } : {},
901
+ ...input.configuration && data.overlayVersion === 1 ? { overlay: { v: 1, epoch, configuration: input.configuration } } : {}
902
+ }, input.origineGioco, [channel.port2]);
903
+ };
904
+ input.finestra.addEventListener("message", listen);
905
+ input.frame.addEventListener?.("load", loaded);
906
+ poll();
907
+ return {
908
+ get epoch() {
909
+ return epoch;
910
+ },
911
+ serverTime() {
912
+ return clockOffset === null ? null : Date.now() + clockOffset;
913
+ },
914
+ get state() {
915
+ return state === null ? null : structuredClone(state);
916
+ },
917
+ subscribe(listener) {
918
+ states.add(listener);
919
+ listener(state);
920
+ return () => {
921
+ states.delete(listener);
922
+ };
923
+ },
924
+ onShortcut(listener) {
925
+ shortcuts.add(listener);
926
+ return () => {
927
+ shortcuts.delete(listener);
928
+ };
929
+ },
930
+ onOpen(listener) {
931
+ opens.add(listener);
932
+ return () => {
933
+ opens.delete(listener);
934
+ };
935
+ },
936
+ onError(listener) {
937
+ errors.add(listener);
938
+ return () => {
939
+ errors.delete(listener);
940
+ };
941
+ },
942
+ onScore(listener) {
943
+ scores.add(listener);
944
+ return () => {
945
+ scores.delete(listener);
946
+ };
947
+ },
948
+ request(op, args) {
949
+ if (!port || !epoch || disposed) return Promise.reject(creaErrore("offline", "The game bridge is not connected."));
950
+ if (pending.size >= 32) return Promise.reject(creaErrore("rate_limited", "Too many overlay requests."));
951
+ const id = String(++requestId), request = {
952
+ type: "caisual:overlay",
953
+ v: 1,
954
+ epoch,
955
+ requestId: id,
956
+ op,
957
+ args,
958
+ ...["room.ready", "room.role", "room.requestRole", "room.team", "room.start", "room.restart", "session.leave", "session.disconnect", "voice.join", "voice.mute", "voice.leave", "voice.setVolume"].includes(op) ? { sessionId: state?.id ?? null } : {}
959
+ };
960
+ if (!validOverlayRequest(request)) return Promise.reject(creaErrore("invalid_request", "The overlay request is invalid."));
961
+ return new Promise((resolve, reject) => {
962
+ const timeout = op === "room.match" ? 31e4 : input.requestTimeoutMs ?? 15e3;
963
+ const timer = input.finestra.setTimeout(() => {
964
+ pending.delete(id);
965
+ reject(creaErrore("timeout", "The overlay request timed out."));
966
+ }, timeout);
967
+ pending.set(id, { resolve, reject, timer });
968
+ try {
969
+ port.postMessage(request);
970
+ } catch (error) {
971
+ input.finestra.clearTimeout(timer);
972
+ pending.delete(id);
973
+ reject(error);
974
+ }
975
+ });
976
+ },
977
+ dispose() {
978
+ disposed = true;
979
+ stopPolling();
980
+ rejectPending();
981
+ port?.close();
982
+ port = null;
983
+ input.finestra.removeEventListener("message", listen);
984
+ input.frame.removeEventListener?.("load", loaded);
985
+ states.clear();
986
+ opens.clear();
987
+ shortcuts.clear();
988
+ scores.clear();
989
+ errors.clear();
990
+ }
991
+ };
992
+ }
993
+ function avviaHandshake(input) {
994
+ const bridge = creaPonteOspite(input);
995
+ return () => bridge.dispose();
996
+ }
997
+ function gameViewport(frame) {
998
+ const rect = frame.getBoundingClientRect();
999
+ const zoomX = frame.offsetWidth ? rect.width / frame.offsetWidth : 1;
1000
+ const zoomY = frame.offsetHeight ? rect.height / frame.offsetHeight : 1;
1001
+ const left = rect.left + frame.clientLeft * zoomX, top = rect.top + frame.clientTop * zoomY;
1002
+ return {
1003
+ left,
1004
+ top,
1005
+ right: left + frame.clientWidth * zoomX,
1006
+ bottom: top + frame.clientHeight * zoomY,
1007
+ scaleX: zoomX ? 1 / zoomX : 1,
1008
+ scaleY: zoomY ? 1 / zoomY : 1
1009
+ };
1010
+ }
1011
+ function measureSafeArea(frame, probe) {
1012
+ const win = frame.ownerDocument.defaultView, css = win.getComputedStyle(probe), viewport = gameViewport(frame);
1013
+ const clamp = (value, max) => Math.max(0, Math.min(max, value));
1014
+ return {
1015
+ top: clamp(((parseFloat(css.paddingTop) || 0) - viewport.top) * viewport.scaleY, frame.clientHeight),
1016
+ right: clamp((viewport.right - (win.innerWidth - (parseFloat(css.paddingRight) || 0))) * viewport.scaleX, frame.clientWidth),
1017
+ bottom: clamp((viewport.bottom - (win.innerHeight - (parseFloat(css.paddingBottom) || 0))) * viewport.scaleY, frame.clientHeight),
1018
+ left: clamp(((parseFloat(css.paddingLeft) || 0) - viewport.left) * viewport.scaleX, frame.clientWidth)
1019
+ };
1020
+ }
1021
+
1022
+ // src/overlay/boards.ts
1023
+ function createBoardController(input) {
1024
+ let disposed = false, generation = 0, timer;
1025
+ const seen = /* @__PURE__ */ new Set();
1026
+ let query = null, data = null, error = false, loading = false;
1027
+ let queued = null, saving = null, reads = 0;
1028
+ const later = input.later ?? setTimeout, clear = input.clear ?? clearTimeout;
1029
+ const cancel = () => {
1030
+ if (timer !== void 0) clear(timer);
1031
+ timer = void 0;
1032
+ };
1033
+ const notify = () => {
1034
+ if (!disposed) input.changed();
1035
+ };
1036
+ const matches = () => queued && query?.board === queued.board && query.period === (queued.day ? "daily" : "all-time") && (query.day ?? queued.day) === queued.day;
1037
+ const refresh = async () => {
1038
+ if (!query || disposed) return;
1039
+ cancel();
1040
+ const current = ++generation, selected = { ...query };
1041
+ loading = true;
1042
+ error = false;
1043
+ notify();
1044
+ try {
1045
+ const result = await input.read(selected);
1046
+ if (disposed || current !== generation) return;
1047
+ data = result;
1048
+ if (matches()) {
1049
+ const own = result.me;
1050
+ if (own?.verified && own.score >= queued.score) saving = own.score === queued.score ? "saved" : "bestAlready";
1051
+ }
1052
+ } catch {
1053
+ if (!disposed && current === generation) error = true;
1054
+ }
1055
+ if (disposed || current !== generation) return;
1056
+ loading = false;
1057
+ if (matches() && saving !== "saved" && saving !== "bestAlready") {
1058
+ reads++;
1059
+ if (reads < 4) {
1060
+ saving = "saving";
1061
+ timer = later(() => {
1062
+ void refresh();
1063
+ }, [800, 1600, 3200][reads - 1]);
1064
+ } else saving = "refreshHint";
1065
+ }
1066
+ notify();
1067
+ };
1068
+ return {
1069
+ get state() {
1070
+ return { query, data, loading, error, saving: matches() ? saving : null };
1071
+ },
1072
+ select(next) {
1073
+ if (JSON.stringify(next) === JSON.stringify(query)) return;
1074
+ cancel();
1075
+ generation++;
1076
+ query = { ...next };
1077
+ data = null;
1078
+ reads = 0;
1079
+ if (matches()) saving = "saving";
1080
+ void refresh();
1081
+ },
1082
+ queued(score) {
1083
+ const board = input.manifest.boards[score.board];
1084
+ if (score.player !== input.player || !board || !Number.isSafeInteger(score.score) || score.score < 0 || score.day !== null && !validBoardDay(score.day) || !(board.periods ?? ["all-time"]).includes(score.day ? "daily" : "all-time")) return;
1085
+ const signature = JSON.stringify(score);
1086
+ if (seen.has(signature)) return;
1087
+ seen.add(signature);
1088
+ if (seen.size > 64) seen.delete(seen.values().next().value);
1089
+ queued = score;
1090
+ saving = "saving";
1091
+ reads = 0;
1092
+ this.select({ board: score.board, period: score.day ? "daily" : "all-time", guests: query?.guests ?? input.guests ?? false, ...score.day ? { day: score.day } : {} });
1093
+ if (!loading) void refresh();
1094
+ notify();
1095
+ },
1096
+ refresh,
1097
+ reset() {
1098
+ seen.clear();
1099
+ cancel();
1100
+ generation++;
1101
+ query = null;
1102
+ data = null;
1103
+ queued = null;
1104
+ saving = null;
1105
+ loading = false;
1106
+ error = false;
1107
+ },
1108
+ dispose() {
1109
+ disposed = true;
1110
+ cancel();
1111
+ generation++;
1112
+ }
1113
+ };
1114
+ }
1115
+
1116
+ // src/overlay/i18n.ts
1117
+ var languages = ["en", "it", "es", "fr", "de", "pt"];
1118
+ var words = {
1119
+ gameLanguages: ["Game languages", "Lingue del gioco", "Idiomas del juego", "Langues du jeu", "Spielsprachen", "Idiomas do jogo"],
1120
+ loading: ["Loading game...", "Caricamento...", "Cargando...", "Chargement...", "Spiel wird geladen...", "Carregando..."],
1121
+ 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."],
1122
+ home: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
1123
+ homeMenu: ["Menu", "Menu", "Men\xFA", "Menu", "Men\xFC", "Menu"],
1124
+ mode: ["Mode", "Modalit\xE0", "Modo", "Mode", "Modus", "Modo"],
1125
+ play: ["Play", "Gioca", "Jugar", "Jouer", "Spielen", "Jogar"],
1126
+ friendsPlay: ["Play with friends", "Gioca con amici", "Jugar con amigos", "Jouer entre amis", "Mit Freunden spielen", "Jogar com amigos"],
1127
+ find: ["Find players", "Trova giocatori", "Buscar jugadores", "Trouver des joueurs", "Spieler finden", "Buscar jogadores"],
1128
+ join: ["Join with code", "Entra con codice", "Entrar con c\xF3digo", "Rejoindre avec un code", "Mit Code beitreten", "Entrar com c\xF3digo"],
1129
+ joinInvite: ["Join this room", "Entra in questa stanza", "Entrar en est\xE1 sala", "Rejoindre cette salle", "Diesem Raum beitreten", "Entrar nest\xE1 sala"],
1130
+ watch: ["Watch a room", "Guarda una stanza", "Observar una sala", "Regarder une salle", "Raum ansehen", "Assistir a uma sala"],
1131
+ resume: ["Resume", "Riprendi", "Continuar", "Reprendre", "Fortsetzen", "Continuar"],
1132
+ room: ["Room", "Stanza", "Sala", "Salle", "Raum", "Sala"],
1133
+ code: ["Room code", "Codice stanza", "C\xF3digo de sala", "Code de salle", "Raumcode", "C\xF3digo da sala"],
1134
+ copy: ["Copy invite", "Copia invito", "Copiar invitaci\xF3n", "Copier le lien", "Einladung kopieren", "Copiar convite"],
1135
+ copied: ["Invite copied", "Invito copiato", "Invitacion copiada", "Lien copi\xE9", "Einladung kopiert", "Convite copiado"],
1136
+ copyFailed: ["Copy this link:", "Copia questo link:", "Copia este enlace:", "Copiez ce lien :", "Diesen Link kopieren:", "Copie este link:"],
1137
+ joining: ["Joining room...", "Ingresso nella stanza...", "Entrando en la sala...", "Connexion \xE0 la salle...", "Raum wird betreten...", "Entrando na sala..."],
1138
+ matching: ["Finding your people...", "Ricerca giocatori...", "Buscando jugadores...", "Recherche de joueurs...", "Spieler werden gesucht...", "Buscando jogadores..."],
1139
+ queue: ["{n} / {max} players", "{n} / {max} giocatori", "{n} / {max} jugadores", "{n} / {max} joueurs", "{n} / {max} Spieler", "{n} / {max} jogadores"],
1140
+ cancel: ["Cancel", "Annulla", "Cancelar", "Annuler", "Abbrechen", "Cancelar"],
1141
+ close: ["Close", "Chiudi", "Cerrar", "Fermer", "Schlie\xDFen", "Fechar"],
1142
+ back: ["Back", "Indietro", "Volver", "Retour", "Zur\xFCck", "Voltar"],
1143
+ ready: ["Ready", "Pronto", "Listo", "Pr\xEAt", "Bereit", "Pronto"],
1144
+ unready: ["Not ready", "Non pronto", "No listo", "Pas pr\xEAt", "Nicht bereit", "N\xE3o pronto"],
1145
+ start: ["Start", "Inizia", "Empezar", "Commencer", "Starten", "Come\xE7ar"],
1146
+ role: ["Role", "Ruolo", "Rol", "R\xF4le", "Rolle", "Fun\xE7\xE3o"],
1147
+ team: ["Team", "Squadra", "Equipo", "\xC9quipe", "Team", "Equipe"],
1148
+ host: ["Host", "Host", "Anfitrion", "H\xF4te", "Host", "Anfitri\xE3o"],
1149
+ you: ["You", "Tu", "T\xFA", "Vous", "Du", "Voc\xEA"],
1150
+ away: ["Away", "Assente", "Ausente", "Absent", "Abwesend", "Ausente"],
1151
+ needPlayers: ["Waiting for more players", "In attesa di giocatori", "Esperando m\xE1s jugadores", "En attente de joueurs", "Weitere Spieler fehlen", "Esperando mais jogadores"],
1152
+ 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"],
1153
+ 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"],
1154
+ needTeams: ["Choose the required teams", "Scegli le squadre richieste", "Elige los equipos", "Choisissez les \xE9quipes", "Teams auswahlen", "Escolha as equipes"],
1155
+ 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"],
1156
+ starting: ["Starting in", "Si inizia tra", "Empieza en", "D\xE9but dans", "Start in", "Come\xE7a em"],
1157
+ playing: ["Playing", "In partita", "Jugando", "En jeu", "Im Spiel", "Jogando"],
1158
+ ended: ["Game finished", "Partita conclusa", "Partida terminada", "Partie termin\xE9e", "Spiel beendet", "Partida encerrada"],
1159
+ rematchReady: ["{n}/{max} ready", "{n}/{max} pronti", "{n}/{max} listos", "{n}/{max} pr\xEAts", "{n}/{max} bereit", "{n}/{max} prontos"],
1160
+ rematchStart: ["Start rematch", "Avvia rivincita", "Iniciar revancha", "Lancer la revanche", "Revanche starten", "Iniciar revanche"],
1161
+ again: ["Play again", "Gioca ancora", "Jugar de nuevo", "Rejouer", "Erneut spielen", "Jogar novamente"],
1162
+ 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."],
1163
+ watching: ["Watching", "In osservazione", "Observando", "Spectateur", "Zuschauen", "Assistindo"],
1164
+ delay: ["{n}s delay", "Ritardo {n}s", "Retraso de {n}s", "Retard de {n}s", "{n}s Verz\xF6gerung", "Atraso de {n}s"],
1165
+ exit: ["Exit", "Esci", "Salir", "Quitter", "Verlassen", "Sair"],
1166
+ leaveNow: ["Leave for now", "Esci per ora", "Salir por ahora", "Quitter pour le moment", "Vor\xFCbergehend verlassen", "Sair por enquanto"],
1167
+ leaveRoom: ["Leave room", "Lascia la stanza", "Abandonar sala", "Abandonner la salle", "Raum verlassen", "Deixar a sala"],
1168
+ 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."],
1169
+ 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."],
1170
+ 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."],
1171
+ reconnecting: ["Reconnecting...", "Riconnessione...", "Reconectando...", "Reconnexion...", "Verbindung wird erneuert...", "Reconectando..."],
1172
+ 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"],
1173
+ 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."],
1174
+ 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."],
1175
+ 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."],
1176
+ 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."],
1177
+ 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."],
1178
+ 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."],
1179
+ unavailable: ["Unavailable right now", "Non disponibile ora", "No disponible ahora", "Indisponible pour le moment", "Derzeit nicht verf\xFCgbar", "Indisponivel agora"],
1180
+ 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."],
1181
+ 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."],
1182
+ boards: ["Leaderboard", "Classifica", "Clasificaci\xF3n", "Classement", "Bestenliste", "Classifica\xE7\xE3o"],
1183
+ board: ["Board", "Classifica", "Tabla", "Classement", "Bestenliste", "Tabela"],
1184
+ daily: ["Daily", "Giornaliera", "Diaria", "Du jour", "T\xE4glich", "Di\xE1ria"],
1185
+ allTime: ["All time", "Di sempre", "Hist\xF3rica", "Tous les temps", "Gesamt", "Geral"],
1186
+ accounts: ["Accounts", "Account", "Cuentas", "Comptes", "Konten", "Contas"],
1187
+ guests: ["Guests", "Ospiti", "Invitados", "Invit\xE9s", "G\xE4ste", "Visitantes"],
1188
+ category: ["Category", "Categoria", "Categoria", "Cat\xE9gorie", "Kategorie", "Categoria"],
1189
+ period: ["Period", "Periodo", "Per\xEDodo", "P\xE9riode", "Zeitraum", "Per\xEDodo"],
1190
+ rank: ["Rank", "Posizione", "Puesto", "Rang", "Platz", "Posicao"],
1191
+ score: ["Score", "Punteggio", "Puntos", "Score", "Punkte", "Pontos"],
1192
+ verified: ["Verified", "Verificato", "Verificado", "V\xE9rifi\xE9", "Verifiziert", "Verificado"],
1193
+ own: ["Your best", "Il tuo record", "Tu record", "Votre record", "Dein Rekord", "Seu recorde"],
1194
+ empty: ["No scores yet", "Nessun punteggio", "A\xFAn no hay puntos", "Aucun score", "Noch keine Punkte", "Ainda sem pontos"],
1195
+ saving: ["Saving score...", "Salvataggio punteggio...", "Guardando puntos...", "Enregistrement du score...", "Punkte werden gespeichert...", "Salvando pontos..."],
1196
+ 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"],
1197
+ 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"],
1198
+ refresh: ["Refresh", "Aggiorna", "Actualizar", "Actualiser", "Aktualisieren", "Atualizar"],
1199
+ 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."],
1200
+ friends: ["Friends & party", "Amici e gruppo", "Amigos y grupo", "Amis et groupe", "Freunde & Gruppe", "Amigos e grupo"],
1201
+ 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."],
1202
+ 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."],
1203
+ online: ["Online", "Online", "En linea", "En ligne", "Online", "Online"],
1204
+ noFriends: ["No friends online", "Nessun amico online", "Sin amigos en linea", "Aucun ami en ligne", "Keine Freunde online", "Nenhum amigo online"],
1205
+ createParty: ["Create party", "Crea gruppo", "Crear grupo", "Cr\xE9er un groupe", "Gruppe erstellen", "Criar grupo"],
1206
+ inviteParty: ["Invite to party", "Invita nel gruppo", "Invitar al grupo", "Inviter au groupe", "In Gruppe einladen", "Convidar para o grupo"],
1207
+ leaveParty: ["Leave party", "Lascia gruppo", "Salir del grupo", "Quitter le groupe", "Gruppe verlassen", "Sair do grupo"],
1208
+ accept: ["Accept", "Accetta", "Aceptar", "Accepter", "Annehmen", "Aceitar"],
1209
+ decline: ["Decline", "Rifiuta", "Rechazar", "Refuser", "Ablehnen", "Recusar"],
1210
+ follow: ["Join them", "Raggiungi", "Unirse", "Rejoindre", "Beitreten", "Juntar-se"],
1211
+ voice: ["Voice", "Voce", "Voz", "Voix", "Sprache", "Voz"],
1212
+ voiceJoin: ["Join voice", "Entra in voce", "Unirse a voz", "Activer la voix", "Sprachchat beitreten", "Entrar na voz"],
1213
+ voiceLeave: ["Leave voice", "Esci dalla voce", "Salir de voz", "Quitter la voix", "Sprachchat verlassen", "Sair da voz"],
1214
+ voiceMute: ["Mute", "Disattiva microfono", "Silenciar", "Couper le micro", "Stummschalten", "Silenciar"],
1215
+ voiceUnmute: ["Unmute", "Attiva microfono", "Activar micr\xF3fono", "Activer le micro", "Mikrofon aktivieren", "Ativar microfone"],
1216
+ voiceOff: ["Voice off", "Voce disattivata", "Voz desactivada", "Voix d\xE9sactiv\xE9e", "Sprachchat aus", "Voz desativada"],
1217
+ voiceJoining: ["Joining voice...", "Connessione voce...", "Conectando voz...", "Connexion vocale...", "Sprachchat verbindet...", "Conectando voz..."],
1218
+ voiceOn: ["Voice connected", "Voce connessa", "Voz conectada", "Voix connect\xE9e", "Sprachchat verbunden", "Voz conectada"],
1219
+ voiceMuted: ["Muted", "Microfono disattivato", "Silenciado", "Micro coup\xE9", "Stumm", "Silenciado"],
1220
+ voiceMic: ["Mic on", "Microfono attivo", "Micr\xF3fono activo", "Micro actif", "Mikrofon an", "Microfone ativo"],
1221
+ voiceListening: ["Listening only", "Solo ascolto", "Solo escucha", "\xC9coute seule", "Nur zuh\xF6ren", "Somente ouvindo"],
1222
+ voiceSpeaking: ["Speaking", "Sta parlando", "Hablando", "Parle", "Spricht", "Falando"],
1223
+ voicePeers: ["Voice participants", "Partecipanti in voce", "Participantes de voz", "Participants vocaux", "Sprachteilnehmer", "Participantes de voz"],
1224
+ 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."],
1225
+ voiceVolume: ["Volume for {name}", "Volume di {name}", "Volumen de {name}", "Volume de {name}", "Lautst\xE4rke f\xFCr {name}", "Volume de {name}"],
1226
+ 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."],
1227
+ 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."],
1228
+ 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."],
1229
+ 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."],
1230
+ 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."],
1231
+ 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."],
1232
+ shortcut: ["Shift+Tab shortcut", "Scorciatoia Shift+Tab", "Atajo Shift+Tab", "Raccourci Maj+Tab", "Umschalt+Tab-Kurzbefehl", "Atalho Shift+Tab"],
1233
+ menu: ["Caisual menu", "Menu Caisual", "Menu Caisual", "Menu Caisual", "Caisual-Menu", "Menu Caisual"],
1234
+ retry: ["Retry", "Riprova", "Reintentar", "R\xE9essayer", "Erneut versuchen", "Tentar novamente"]
1235
+ };
1236
+ var column = (index) => Object.fromEntries(Object.entries(words).map(([key, row]) => [key, row[index]]));
1237
+ var dictionaries = { en: column(0), it: column(1), es: column(2), fr: column(3), de: column(4), pt: column(5) };
1238
+ function overlayLanguage(raw) {
1239
+ const value = raw?.toLowerCase().split("-")[0];
1240
+ return languages.includes(value) ? value : "en";
1241
+ }
1242
+ function overlayLocale(raw) {
1243
+ const tag = normalizeLanguage(raw);
1244
+ return tag && languages.includes(tag.split("-")[0]) ? tag : "en";
1245
+ }
1246
+ function translator(language) {
1247
+ const dictionary = dictionaries[overlayLanguage(language)];
1248
+ return (key, values = {}) => dictionary[key].replace(/\{(\w+)\}/g, (_all, name) => String(values[name] ?? ""));
1249
+ }
1250
+ function errorText(code) {
1251
+ if (code === "permission_denied") return "voiceDenied";
1252
+ if (code === "unsupported") return "voiceUnsupported";
1253
+ if (code === "voice_disabled") return "voiceUnavailable";
1254
+ if (code === "voice_error") return "voiceFailed";
1255
+ if (code === "voice_peer_missing") return "voicePeerGone";
1256
+ if (code === "not_publishing") return "voiceListening";
1257
+ if (["room_not_found", "room_ended", "version_closed", "no_resume"].includes(code)) return "noRoom";
1258
+ if (["room_full", "role_full"].includes(code)) return "full";
1259
+ if (code === "replaced") return "replaced";
1260
+ if (code === "no_match") return "noMatch";
1261
+ if (code === "invalid_code") return "invalidCode";
1262
+ if (["offline", "timeout"].includes(code)) return "offline";
1263
+ if (code.startsWith("role_") || ["not_in_lobby", "not_host", "session_replaced"].includes(code)) return "refused";
1264
+ if (code === "save_failed") return "saveFailed";
1265
+ return "error";
1266
+ }
1267
+
1268
+ // src/overlay/ui-model.ts
1269
+ function phase(session) {
1270
+ if (!session || session.kind === "boot") return "boot";
1271
+ if (session.kind === "attaching" || session.kind === "matching") return session.kind;
1272
+ if (session.room && ["closed", "replaced"].includes(session.room.connection)) return "error";
1273
+ if (session.kind === "local") return session.localStatus === "ended" ? "ended" : "playing";
1274
+ if (session.room?.status === "ended" || session.room?.status === "finished") return "ended";
1275
+ if (session.kind === "watch") return "watching";
1276
+ if (session.kind === "room" && session.room) return session.room.status;
1277
+ return "home";
1278
+ }
1279
+ function initialUi(manifest) {
1280
+ return { session: null, panel: "auto", mode: manifest.modes[0]?.id ?? "", busy: false, error: null, notice: null, shortcutEnabled: true };
1281
+ }
1282
+ function reduceUi(model, action) {
1283
+ switch (action.type) {
1284
+ case "session": {
1285
+ const next = action.session, changed = next?.id !== model.session?.id || next === null;
1286
+ const pending = next?.kind === "attaching" || next?.kind === "matching";
1287
+ const nextPhase = phase(next), transition = phase(model.session) !== nextPhase;
1288
+ const automatic = transition && ["lobby", "countdown", "playing", "ended"].includes(nextPhase) && [null, "auto", "room", "invite", "home"].includes(model.panel);
1289
+ return {
1290
+ ...model,
1291
+ session: next,
1292
+ mode: next?.mode ?? model.mode,
1293
+ panel: changed || pending || automatic ? "auto" : model.panel,
1294
+ error: changed ? null : model.error,
1295
+ notice: changed ? null : model.notice
1296
+ };
1297
+ }
1298
+ case "panel":
1299
+ return { ...model, panel: action.panel, error: null, notice: null };
1300
+ case "mode":
1301
+ return { ...model, mode: action.mode, error: null };
1302
+ case "busy":
1303
+ return { ...model, busy: action.busy };
1304
+ case "error":
1305
+ return { ...model, error: action.code, busy: false };
1306
+ case "notice":
1307
+ return { ...model, notice: action.notice };
1308
+ case "shortcut":
1309
+ return { ...model, shortcutEnabled: action.enabled };
1310
+ }
1311
+ }
1312
+ function visiblePanel(model) {
1313
+ const current = phase(model.session);
1314
+ if (current === "boot" || current === "attaching" || current === "matching" || current === "error") return current;
1315
+ if (model.panel !== "auto") return model.panel;
1316
+ return current === "home" ? "home" : current === "lobby" ? "room" : current === "countdown" ? "countdown" : null;
1317
+ }
1318
+ function primaryAction(manifest, mode) {
1319
+ const selected = manifest.modes.find((item) => item.id === mode);
1320
+ if (!selected) return null;
1321
+ return {
1322
+ op: selected.execution === "local" ? "local.start" : "room.create",
1323
+ friends: selected.execution === "room" && risolviModalita(manifest, mode).players.max > 1
1324
+ };
1325
+ }
1326
+ function startReason(manifest, session) {
1327
+ const room = session?.room;
1328
+ if (!room || session.kind !== "room" || room.status !== "lobby" || room.connection !== "connected") return "unavailable";
1329
+ const connected = room.players.filter((p) => p.connected), active = connected.filter((p) => p.role !== "spectator");
1330
+ if (active.length < room.limits.min) return "needPlayers";
1331
+ if (connected.some((p) => !p.ready)) return "needReady";
1332
+ if (manifest.roles.some((role) => active.filter((p) => p.role === role.id).length < role.min)) return "needRoles";
1333
+ if (manifest.teams && (active.some((p) => p.team === null) || new Set(active.map((p) => p.team)).size < manifest.teams.min)) return "needTeams";
1334
+ return room.host !== room.you ? "waitHost" : null;
1335
+ }
1336
+ function canPlayAgain(session) {
1337
+ if (phase(session) !== "ended") return false;
1338
+ if (session?.kind === "local") return true;
1339
+ if (session?.room?.status === "finished") return session.kind === "room" && session.room.connection === "connected" && session.room.players.some((p) => p.id === session.room.you && p.connected && p.role !== "spectator" && !p.ready);
1340
+ return session?.kind === "room" && (!session.room?.lobby || session.room.host === session.room.you);
1341
+ }
1342
+ function normalizeInvite(code) {
1343
+ const value = code.toUpperCase().replace(/[\s-]/g, "");
1344
+ return /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(value) ? value : null;
1345
+ }
1346
+
1347
+ // src/overlay/styles.ts
1348
+ var styles = `
1349
+ .safe-area-probe{position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)}
1350
+ :host{all:initial;position:fixed;inset:0;z-index:10000;pointer-events:none;font:15px/1.45 system-ui,sans-serif;color:#f4f4f1;color-scheme:dark;--accent:#a8efc5}
1351
+ [data-layout],[data-surface],.sr{pointer-events:none}*{box-sizing:border-box}button,input,select{font:inherit}button,a,input,select{touch-action:manipulation}button,select,input{border:1px solid #ffffff30;background:#25292b;color:inherit;border-radius:12px;min-height:44px;padding:10px 14px}button{cursor:pointer}button:disabled{opacity:.45;cursor:default}button:hover:not(:disabled){background:#343b3a}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:3px}a{color:var(--accent)}.primary{background:var(--accent);color:var(--accent-ink,#11221b);border-color:transparent;font-weight:700}.primary:hover:not(:disabled){filter:brightness(1.1);background:var(--accent)}.quiet{background:transparent}label{display:grid;gap:6px;text-align:left}select,input{width:100%;min-width:0}h1,h2,p{margin:0}h1{font-size:clamp(26px,5vw,42px);line-height:1.1;letter-spacing:-.035em}h2{font-size:20px}small,.muted{color:#bdc5c1}.stack{display:grid;gap:16px}.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.row>*{flex:0 1 auto}.row .grow,.grow{flex:1}.split{display:grid;grid-template-columns:1fr 1fr;gap:10px}.pill{position:absolute;top:max(10px,env(safe-area-inset-top));right:max(10px,env(safe-area-inset-right));display:flex;height:44px;border:1px solid #ffffff35;border-radius:24px;background:#171e20eF;box-shadow:0 4px 20px #0004;pointer-events:auto;overflow:hidden}.pill button{border:0;border-radius:0;padding:8px 13px;background:transparent}.pill button:focus-visible{outline-offset:-4px}.pill small{margin-left:8px}.backdrop{position:absolute;inset:0;background:#0b151ce8;backdrop-filter:blur(10px);pointer-events:auto;display:grid;place-items:center;padding:max(16px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(16px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left));overflow:auto}.backdrop.home{background-color:#142127;background-size:cover;background-position:center}.dialog{position:relative;width:min(100%,540px);max-height:100%;overflow:auto;overscroll-behavior:contain;background:#141b1df5;border:1px solid #ffffff25;border-radius:22px;padding:24px;box-shadow:0 20px 80px #0005}.dialog.wide{width:min(100%,700px)}.top{display:flex;align-items:center;gap:12px;margin-bottom:18px}.top h2{flex:1}.tabs{display:flex;gap:6px;flex-wrap:wrap;border-bottom:1px solid #ffffff25;padding-bottom:12px}.tabs button{min-height:36px;padding:6px 10px}.tabs [aria-current=true]{border-color:var(--accent)}.roster{list-style:none;padding:0;margin:0;display:grid;gap:8px;max-height:32dvh;overflow:auto}.roster li{display:flex;align-items:center;gap:8px;padding:10px;background:#ffffff08;border-radius:10px}.roster .name{flex:1;overflow-wrap:anywhere}.badge{border:1px solid #ffffff30;border-radius:6px;padding:2px 6px;font-size:12px}.code{font-size:24px;letter-spacing:.13em;font-variant-numeric:tabular-nums}.notice,.error{border-radius:10px;padding:10px;background:#a8efc514;overflow-wrap:anywhere}.error{background:#ff8b7720;color:#ffd2c9}.countdown{font-size:88px;line-height:1;text-align:center;font-variant-numeric:tabular-nums}.ended{position:absolute;bottom:max(12px,env(safe-area-inset-bottom));left:50%;transform:translateX(-50%);max-width:calc(100% - 24px);width:max-content;background:#171e20f5;pointer-events:auto;border:1px solid #ffffff30;border-radius:16px;padding:10px;display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap}.ended [data-rematch-players]{max-width:100%;max-height:3.2em;overflow:auto;overflow-wrap:anywhere}.ended strong{padding:0 8px}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}.table-wrap{overflow:auto;max-height:38dvh}table{width:100%;border-collapse:collapse;text-align:left}th,td{padding:9px 6px;border-bottom:1px solid #ffffff20}td:nth-child(3){text-align:right}td small{display:block}.self{background:#ffffff0a}.checkbox{display:flex;align-items:center;gap:8px;font-size:13px}.checkbox input{width:18px;min-height:18px}.full{width:100%}
1352
+ [hidden]{display:none!important}.voice-peers{list-style:none;margin:0;padding:0;display:grid;gap:10px}.voice-peers li{border:1px solid #ffffff25;border-radius:12px;padding:12px;display:grid;gap:8px}.voice-peers [data-speaking=true]{border-color:var(--accent)}.voice-peers input{width:100%;accent-color:var(--accent);padding:0}.voice-peers label{font-size:13px}.pill .voice-toggle{width:44px;padding:8px}.voice-toggle[data-voice-state=on][data-muted=false]{color:var(--accent)}
1353
+ .boot{position:absolute;inset:0;z-index:2;isolation:isolate;display:grid;place-items:center;overflow:auto;overscroll-behavior:contain;padding:max(100px,env(safe-area-inset-top)) max(24px,env(safe-area-inset-right)) max(48px,env(safe-area-inset-bottom)) max(24px,env(safe-area-inset-left));background:#0b151c;opacity:1;transition:opacity .4s ease;pointer-events:auto;outline:none}
1354
+ .boot::before,.boot::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:-1}.boot::before{background:radial-gradient(ellipse at 50% 38%,color-mix(in srgb,var(--accent),transparent 80%),transparent 65%)}.boot::after{background:radial-gradient(ellipse at 50% 38%,#0b151c20,#0b151cd9 85%),linear-gradient(#0b151c66,#0b151cbf)}
1355
+ .boot-cover{position:fixed;inset:0;z-index:-2;width:100%;height:100%;object-fit:cover;filter:blur(20px);transform:scale(1.08);opacity:.65;pointer-events:none}
1356
+ .boot-brand{position:absolute;top:max(28px,env(safe-area-inset-top));left:max(32px,env(safe-area-inset-left));display:flex;align-items:center;gap:10px;font-size:14px;font-weight:650;letter-spacing:.02em;color:#f4f4f1b3}.boot-brand span{display:grid;place-items:center;width:36px;height:36px;border:1px solid #ffffff25;border-radius:12px;background:#171e20af;box-shadow:0 4px 20px #0004;color:var(--boot-accent);font-size:20px;font-weight:800}
1357
+ .boot-content{width:min(100%,900px);text-align:center;display:grid;justify-items:center;gap:24px}.boot h1{max-width:16ch;font-size:clamp(44px,8vw,108px);font-weight:800;line-height:1.04;letter-spacing:-.05em;overflow-wrap:anywhere;text-wrap:balance;color:var(--boot-accent);text-shadow:0 20px 80px #0005}
1358
+ .boot-progress{width:112px;height:3px;border-radius:12px;background:#ffffff20;overflow:hidden;margin-top:12px}.boot-progress span{display:block;width:44%;height:100%;border-radius:inherit;background:var(--boot-accent);animation:boot-progress 1.8s ease-in-out infinite}.boot-status{max-width:42ch;min-height:3em;font-size:14px;line-height:1.5;color:#d3dad6;text-wrap:balance}.boot-recovery{min-height:44px}.boot-recovery .row{justify-content:center}.boot-leaving{opacity:0;pointer-events:none}
1359
+ @keyframes boot-progress{0%{transform:translateX(-110%)}100%{transform:translateX(340%)}}
1360
+ @media(max-width:480px){.dialog{padding:18px;border-radius:18px}.split{grid-template-columns:1fr 1fr;gap:8px}.tabs{gap:4px}.tabs button{font-size:13px;padding:6px 8px}.pill button:focus-visible{outline-offset:-4px}.pill small{display:none}.ended{gap:6px}.ended strong{font-size:13px}.ended button{padding:8px 10px;font-size:13px}.roster{max-height:28dvh}}
1361
+ @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto}.boot{transition:none}.boot-progress span{animation:none;transform:translateX(65%)}}
1362
+ `;
1363
+
1364
+ // src/overlay/voice-panel.ts
1365
+ function voiceEligible(manifest, session) {
1366
+ return manifest.voice !== "none" && session?.kind !== "watch" && session?.room?.players.find((player) => player.id === session.room?.you)?.role !== "spectator";
1367
+ }
1368
+ function voiceStatus(voice, t) {
1369
+ const key = voice.state === "joining" ? "voiceJoining" : voice.state === "reconnecting" ? "reconnecting" : voice.state === "off" ? "voiceOff" : "voiceOn";
1370
+ return t(key);
1371
+ }
1372
+ function updateVoicePanel(container, input) {
1373
+ const { session, t } = input, voice = session?.kind === "room" ? session.voice : null;
1374
+ if (!voiceEligible(input.manifest, session) || !voice) {
1375
+ container.replaceChildren();
1376
+ const note = container.ownerDocument.createElement("p");
1377
+ note.textContent = t(session?.kind === "watch" || session?.room?.players.find((p) => p.id === session.room?.you)?.role === "spectator" ? "voiceWatch" : "voiceUnavailable");
1378
+ container.append(note);
1379
+ return;
1380
+ }
1381
+ if (!container.querySelector("[data-voice-status]")) container.innerHTML = `<p role="status" aria-live="polite" data-voice-status></p><p data-voice-self></p>
1382
+ <div class="row"><button type="button" data-action="voice-join"></button><button type="button" data-action="voice-mute"></button><button type="button" data-action="voice-leave"></button></div>
1383
+ <p class="error" role="alert" data-voice-error hidden></p><h3 data-voice-heading></h3><ul class="voice-peers" data-voice-peers></ul><p class="muted" data-voice-empty></p>`;
1384
+ const get = (selector) => container.querySelector(selector);
1385
+ const status = get("[data-voice-status]");
1386
+ status.textContent = voiceStatus(voice, t);
1387
+ status.dataset.voiceState = voice.state;
1388
+ const mic = (value) => t(!value.mic ? "voiceListening" : value.muted ? "voiceMuted" : value.speaking ? "voiceSpeaking" : "voiceMic");
1389
+ get("[data-voice-self]").textContent = voice.state === "off" ? "" : `${t("you")}: ${mic(voice)}`;
1390
+ const join = get('[data-action="voice-join"]'), mute = get('[data-action="voice-mute"]'), leave = get('[data-action="voice-leave"]');
1391
+ join.textContent = t("voiceJoin");
1392
+ join.hidden = voice.state !== "off";
1393
+ join.disabled = session?.room?.connection !== "connected" || input.pending === "voice.join";
1394
+ mute.textContent = t(voice.muted ? "voiceUnmute" : "voiceMute");
1395
+ mute.hidden = voice.state !== "on" || !voice.mic;
1396
+ mute.disabled = input.pending === "voice.mute";
1397
+ mute.setAttribute("aria-pressed", String(voice.muted));
1398
+ leave.textContent = t("voiceLeave");
1399
+ leave.hidden = voice.state === "off" && input.pending !== "voice.join";
1400
+ leave.disabled = input.pending === "voice.leave";
1401
+ const error = get("[data-voice-error]");
1402
+ error.hidden = !input.error;
1403
+ error.textContent = input.error ? t(errorText(input.error)) : "";
1404
+ get("[data-voice-heading]").textContent = t("voicePeers");
1405
+ get("[data-voice-empty]").textContent = t("voiceEmpty");
1406
+ get("[data-voice-empty]").hidden = voice.peers.length > 0;
1407
+ const list = get("[data-voice-peers]"), ids = new Set(voice.peers.map((peer) => peer.id));
1408
+ for (const row of list.querySelectorAll("[data-voice-peer]")) if (!ids.has(row.dataset.voicePeer)) row.remove();
1409
+ for (const peer of voice.peers) {
1410
+ let row = [...list.children].find((node) => node.dataset.voicePeer === peer.id);
1411
+ if (!row) {
1412
+ row = container.ownerDocument.createElement("li");
1413
+ row.dataset.voicePeer = peer.id;
1414
+ row.innerHTML = '<div class="row"><strong data-peer-name></strong><small data-peer-status></small></div><label><span data-volume-label></span><input type="range" min="0" max="1" step="0.05" data-control="voice-volume"></label>';
1415
+ row.querySelector("input").dataset.peer = peer.id;
1416
+ list.append(row);
1417
+ }
1418
+ const name = session?.room?.players.find((player) => player.id === peer.id)?.name ?? peer.id;
1419
+ row.dataset.mic = String(peer.mic);
1420
+ row.dataset.muted = String(peer.muted);
1421
+ row.dataset.speaking = String(peer.speaking);
1422
+ row.querySelector("[data-peer-name]").textContent = name;
1423
+ row.querySelector("[data-peer-status]").textContent = mic(peer);
1424
+ row.querySelector("[data-volume-label]").textContent = t("voiceVolume", { name });
1425
+ const range = row.querySelector("input");
1426
+ if (range.dataset.editing !== "true") range.value = String(peer.volume);
1427
+ range.setAttribute("aria-valuetext", `${Math.round(Number(range.value) * 100)}%`);
1428
+ range.disabled = voice.state !== "on";
1429
+ }
1430
+ }
1431
+
1432
+ // src/overlay/ui.ts
1433
+ var escape = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1434
+ function mountOverlay(input) {
1435
+ const manifest = input.configuration.manifest;
1436
+ if (manifest.overlay?.version !== 1) return null;
1437
+ const document = input.container.ownerDocument, win = document.defaultView, t = translator(input.language);
1438
+ const host = document.createElement("div");
1439
+ host.dataset.caisualOverlay = "";
1440
+ host.lang = overlayLanguage(input.language);
1441
+ host.style.setProperty("pointer-events", "none", "important");
1442
+ const root = host.attachShadow({ mode: "open" });
1443
+ if (typeof win.CSSStyleSheet?.prototype.replaceSync === "function" && "adoptedStyleSheets" in root) {
1444
+ const sheet = new win.CSSStyleSheet();
1445
+ sheet.replaceSync(styles);
1446
+ root.adoptedStyleSheets = [sheet];
1447
+ } else {
1448
+ const sheet = document.createElement("link");
1449
+ sheet.rel = "stylesheet";
1450
+ sheet.href = "/__caisual/overlay/v1.css";
1451
+ root.append(sheet);
1452
+ }
1453
+ const elements = document.createElement("div");
1454
+ elements.dataset.layout = "";
1455
+ elements.style.pointerEvents = "none";
1456
+ elements.innerHTML = `<div data-surface></div><div class="sr" role="status" aria-live="polite" data-live></div>`;
1457
+ const safeProbe = document.createElement("div");
1458
+ safeProbe.className = "safe-area-probe";
1459
+ safeProbe.setAttribute("aria-hidden", "true");
1460
+ root.append(elements, safeProbe);
1461
+ const surface = root.querySelector("[data-surface]"), live = root.querySelector("[data-live]");
1462
+ surface.style.pointerEvents = "none";
1463
+ live.style.pointerEvents = "none";
1464
+ const accent = manifest.overlay.accent ?? "#a8efc5";
1465
+ host.style.setProperty("--accent", accent);
1466
+ const rgb = [1, 3, 5].map((i) => parseInt(accent.slice(i, i + 2), 16) / 255).map((v) => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
1467
+ const luminance = rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
1468
+ host.style.setProperty("--accent-ink", luminance > 0.179 ? "#000000" : "#ffffff");
1469
+ host.style.setProperty("--boot-accent", luminance > 0.179 ? accent : `color-mix(in srgb, ${accent}, #ffffff 70%)`);
1470
+ input.container.append(host);
1471
+ let model = initialUi(manifest), disposed = false, operation = 0, lastView = "", geometryFrame = 0;
1472
+ let lastPhase = "", wasModal = false, copyFallback = null;
1473
+ let boot = null, bootTimer = 0, bootFadeTimer = 0;
1474
+ let voiceError = null, voicePending = null, voiceOperation = 0;
1475
+ let codeDraft = input.configuration.invite ?? "";
1476
+ const oldInert = Boolean(input.frame.inert), oldTabIndex = input.frame.getAttribute("tabindex");
1477
+ try {
1478
+ model.shortcutEnabled = win.localStorage.getItem("caisual-overlay-shortcut-v1") !== "off";
1479
+ } catch {
1480
+ }
1481
+ const boards = input.boards ? createBoardController({ manifest, player: input.player.id, guests: input.player.guest, read: input.boards, changed: () => render() }) : null;
1482
+ const stops = [];
1483
+ const selectedMode = () => manifest.modes.find((mode) => mode.id === model.mode);
1484
+ const disabled = () => model.busy ? " disabled" : "";
1485
+ const button = (action, key, extra = "", off = false) => `<button type="button" data-action="${action}"${extra}${off || model.busy ? " disabled" : ""}>${t(key)}</button>`;
1486
+ function resetBootWait() {
1487
+ win.clearTimeout(bootTimer);
1488
+ if (!boot || phase(model.session) !== "boot") return;
1489
+ boot.querySelector("[data-boot-message]").textContent = t("loading");
1490
+ boot.querySelector("[data-boot-recovery]").hidden = true;
1491
+ bootTimer = win.setTimeout(() => {
1492
+ bootTimer = 0;
1493
+ if (disposed || !boot) return;
1494
+ boot.querySelector("[data-boot-message]").textContent = t("loadingSlow");
1495
+ boot.querySelector("[data-boot-recovery]").hidden = false;
1496
+ }, 9e3);
1497
+ }
1498
+ function updateBoot(loading) {
1499
+ if (loading) {
1500
+ if (boot) {
1501
+ win.clearTimeout(bootFadeTimer);
1502
+ bootFadeTimer = 0;
1503
+ boot.inert = false;
1504
+ boot.removeAttribute("aria-hidden");
1505
+ boot.style.pointerEvents = "auto";
1506
+ boot.classList.remove("boot-leaving");
1507
+ return;
1508
+ }
1509
+ boot = document.createElement("section");
1510
+ boot.className = "boot";
1511
+ boot.tabIndex = -1;
1512
+ boot.setAttribute("aria-labelledby", "boot-title");
1513
+ boot.setAttribute("aria-describedby", "boot-status");
1514
+ boot.style.pointerEvents = "auto";
1515
+ boot.innerHTML = `<div class="boot-brand" aria-hidden="true"><span>C</span>Caisual</div>
1516
+ <div class="boot-content"><h1 id="boot-title">${escape(manifest.name)}</h1>
1517
+ <div class="boot-progress" aria-hidden="true"><span></span></div>
1518
+ <p class="boot-status" id="boot-status" role="status" aria-live="polite" aria-atomic="true"><span class="sr">${escape(manifest.name)}. </span><span data-boot-message></span></p>
1519
+ <div class="boot-recovery"><div class="row" data-boot-recovery hidden>${button("reload", "retry", ' class="primary"')}${button("exit-now", "exit", ' class="quiet"')}</div></div>
1520
+ </div>`;
1521
+ if (input.configuration.coverUrl) {
1522
+ const cover = document.createElement("img");
1523
+ cover.className = "boot-cover";
1524
+ cover.alt = "";
1525
+ cover.setAttribute("aria-hidden", "true");
1526
+ cover.addEventListener("error", () => {
1527
+ cover.hidden = true;
1528
+ }, { once: true });
1529
+ cover.src = input.configuration.coverUrl;
1530
+ boot.prepend(cover);
1531
+ }
1532
+ elements.append(boot);
1533
+ resetBootWait();
1534
+ } else if (boot && !boot.inert) {
1535
+ boot.inert = true;
1536
+ boot.setAttribute("aria-hidden", "true");
1537
+ boot.style.pointerEvents = "none";
1538
+ boot.classList.add("boot-leaving");
1539
+ const remove = () => {
1540
+ win.clearTimeout(bootTimer);
1541
+ bootTimer = 0;
1542
+ boot?.remove();
1543
+ boot = null;
1544
+ bootFadeTimer = 0;
1545
+ };
1546
+ if (win.matchMedia?.("(prefers-reduced-motion: reduce)").matches) remove();
1547
+ else bootFadeTimer = win.setTimeout(remove, 420);
1548
+ }
1549
+ }
1550
+ const dispatch = (action) => {
1551
+ if (disposed) return;
1552
+ model = reduceUi(model, action);
1553
+ render();
1554
+ };
1555
+ const announce = (text) => {
1556
+ if (live.textContent !== text) live.textContent = text;
1557
+ };
1558
+ const controls = () => [...root.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),[tabindex="0"]')].filter((el) => !el.closest("[hidden]"));
1559
+ const roomCode = () => model.session?.room?.code ?? null;
1560
+ const setPanel = (panel) => {
1561
+ if (panel === "boards" && boards && !boards.state.query) {
1562
+ const id = Object.keys(manifest.boards)[0];
1563
+ if (id) boards.select({ board: id, period: (manifest.boards[id].periods ?? ["all-time"])[0], guests: input.player.guest });
1564
+ }
1565
+ copyFallback = null;
1566
+ dispatch({ type: "panel", panel });
1567
+ };
1568
+ const close = () => {
1569
+ const current = phase(model.session), panel = visiblePanel(model);
1570
+ if (current === "boot") return;
1571
+ if (current === "home") setPanel("home");
1572
+ else if (current === "lobby" && panel !== "room") setPanel("room");
1573
+ else setPanel(null);
1574
+ };
1575
+ const toggle = () => {
1576
+ if (visiblePanel(model)) close();
1577
+ else setPanel(model.session?.room ? "room" : "home");
1578
+ };
1579
+ async function perform(op, args, after) {
1580
+ const token = ++operation;
1581
+ dispatch({ type: "error", code: null });
1582
+ dispatch({ type: "busy", busy: true });
1583
+ try {
1584
+ await input.bridge.request(op, args);
1585
+ if (token === operation && !disposed) await after?.();
1586
+ } catch (error) {
1587
+ if (token === operation && !disposed && error.code !== "cancelled") dispatch({ type: "error", code: error.code ?? "offline" });
1588
+ } finally {
1589
+ if (token === operation && !disposed) dispatch({ type: "busy", busy: false });
1590
+ }
1591
+ }
1592
+ function updateVoice() {
1593
+ const container = root.querySelector("[data-voice-panel]");
1594
+ if (container) updateVoicePanel(container, { manifest, session: model.session, t, error: voiceError, pending: voicePending });
1595
+ const toggle2 = root.querySelector("[data-voice-toggle]"), voice = model.session?.voice;
1596
+ if (toggle2) {
1597
+ toggle2.dataset.voiceState = voice?.state ?? "off";
1598
+ toggle2.dataset.muted = String(voice?.muted ?? false);
1599
+ toggle2.setAttribute("aria-label", `${t("voice")}: ${voice ? voiceStatus(voice, t) : t("voiceOff")}`);
1600
+ toggle2.textContent = voice?.state === "on" && !voice.muted ? "\u25CF" : "\u25CB";
1601
+ }
1602
+ }
1603
+ async function performVoice(op, args) {
1604
+ const sessionId = model.session?.id, epoch = input.bridge.epoch, volume = op === "voice.setVolume";
1605
+ const token = volume ? voiceOperation : ++voiceOperation;
1606
+ const current = () => !disposed && model.session?.id === sessionId && input.bridge.epoch === epoch && token === voiceOperation;
1607
+ voiceError = null;
1608
+ if (!volume) voicePending = op;
1609
+ updateVoice();
1610
+ try {
1611
+ await input.bridge.request(op, args);
1612
+ } catch (error) {
1613
+ if (current()) voiceError = error.code ?? "voice_error";
1614
+ } finally {
1615
+ if (current()) {
1616
+ if (!volume) voicePending = null;
1617
+ updateVoice();
1618
+ }
1619
+ }
1620
+ }
1621
+ async function copyInvite() {
1622
+ const code = roomCode();
1623
+ if (!code) return;
1624
+ const url = input.inviteUrl(code);
1625
+ try {
1626
+ await win.navigator.clipboard.writeText(url);
1627
+ dispatch({ type: "notice", notice: t("copied") });
1628
+ } catch {
1629
+ copyFallback = url;
1630
+ render();
1631
+ root.querySelector('input[data-control="invite-link"]')?.select();
1632
+ }
1633
+ }
1634
+ function invitation() {
1635
+ const code = roomCode();
1636
+ if (!code) return `<p>${t("noRoom")}</p>`;
1637
+ return `<div class="row"><div class="grow"><small>${t("code")}</small><div class="code" data-room-code>${escape(code)}</div></div>${button("copy", "copy")}</div>${copyFallback ? `<label>${t("copyFailed")}<input data-control="invite-link" readonly value="${escape(copyFallback)}"></label>` : ""}`;
1638
+ }
1639
+ function navigation(panel) {
1640
+ const items = [];
1641
+ if (model.session?.room) items.push(["room", "room"], ["invite", "copy"]);
1642
+ items.push(["friends", "friends"]);
1643
+ if (Object.keys(manifest.boards).length) items.push(["boards", "boards"]);
1644
+ if (voiceEligible(manifest, model.session)) items.push(["voice", "voice"]);
1645
+ return `<nav class="tabs" aria-label="Caisual">${items.map(([id, key]) => button(`panel:${id}`, key, ` aria-current="${id === panel}"`)).join("")}</nav>`;
1646
+ }
1647
+ function home() {
1648
+ const selected = selectedMode(), action = primaryAction(manifest, model.mode), session = model.session;
1649
+ const hasRooms = manifest.modes.some((mode) => mode.execution === "room");
1650
+ return `<h1>${escape(manifest.name)}</h1><p class="muted" data-game-languages>${t("gameLanguages")}: ${escape(manifestLanguages(manifest).join(" \xB7 "))}</p><label>${t("mode")}<select data-control="mode"${disabled()}>${manifest.modes.map((mode) => `<option value="${escape(mode.id)}"${mode.id === model.mode ? " selected" : ""}>${escape(risolviPresentazione(manifest, mode.id, input.language).label)}</option>`).join("")}</select></label>
1651
+ ${selected?.instructions ? `<p class="muted">${escape(resolveText(selected.instructions, input.language, manifestLanguages(manifest)[0]))}</p>` : ""}
1652
+ ${input.configuration.invite && phase(session) === "home" ? button("join-invite", "joinInvite", ' class="primary"', !session?.ready) : ""}
1653
+ ${action ? button("play", action.friends ? "friendsPlay" : "play", ' class="primary"', !session?.ready) : ""}
1654
+ ${selected?.matchmaking ? button("match", "find", "", !selected.matchmaking.defaults || !session?.ready) : ""}
1655
+ ${session?.resume ? button("resume", "resume", "", !session.ready) + `<small>${escape(session.resume.code)}</small>` : ""}
1656
+ ${hasRooms ? `<div class="split">${button("panel:join", "join", "", !session?.ready)}${manifest.spectators ? button("panel:watch", "watch", "", !session?.ready) : ""}</div>` : ""}
1657
+ ${navigation("home")}<label class="checkbox"><input type="checkbox" data-control="shortcut"${model.shortcutEnabled ? " checked" : ""}>${t("shortcut")}</label>`;
1658
+ }
1659
+ function room() {
1660
+ const session = model.session, room2 = session?.room;
1661
+ if (!room2) return `<p>${t("noRoom")}</p>`;
1662
+ const own = room2.players.find((player) => player.id === room2.you), lobby = room2.status === "lobby" && session?.kind === "room";
1663
+ const canRole = session?.kind === "room" && (lobby || room2.status === "playing" && room2.requestRole);
1664
+ const reason = startReason(manifest, session);
1665
+ return `${invitation()}<ul class="roster" aria-label="${t("room")}">${room2.players.map((p) => `<li data-player-id="${escape(p.id)}"><span class="name">${escape(p.name)} ${p.id === room2.you ? `<small>(${t("you")})</small>` : ""}</span>${p.id === room2.host ? `<span class="badge">${t("host")}</span>` : ""}${p.role ? `<small>${escape(resolveText(manifest.roles.find((r) => r.id === p.role)?.label, input.language, manifestLanguages(manifest)[0], p.role))}</small>` : ""}${p.team ? `<small>${t("team")} ${p.team}</small>` : ""}<small>${!p.connected ? t("away") : lobby ? t(p.ready ? "ready" : "unready") : ""}</small></li>`).join("")}</ul>
1666
+ ${canRole && manifest.roles.length ? `<label>${t("role")}<select data-control="role"${disabled()}><option value="" disabled${!own?.role ? " selected" : ""}>${t("role")}</option>${manifest.roles.map((role) => `<option value="${escape(role.id)}"${role.id === own?.role ? " selected" : ""}>${escape(resolveText(role.label, input.language, manifestLanguages(manifest)[0], role.id))}</option>`).join("")}</select></label>` : ""}
1667
+ ${lobby && manifest.teams ? `<label>${t("team")}<select data-control="team"${disabled()}><option value="" disabled${!own?.team ? " selected" : ""}>${t("team")}</option>${Array.from({ length: manifest.teams.max }, (_, i) => `<option value="${i + 1}"${own?.team === i + 1 ? " selected" : ""}>${t("team")} ${i + 1}</option>`).join("")}</select></label>` : ""}
1668
+ ${lobby ? `<div class="row">${button("ready", own?.ready ? "unready" : "ready", ' class="primary"', room2.connection !== "connected")}${room2.host === room2.you ? button("start", "start", "", reason !== null) : ""}</div>${reason ? `<p class="muted" data-start-reason>${t(reason)}</p>` : ""}` : ""}
1669
+ ${session?.kind === "watch" ? `<p>${t("watching")} \xB7 ${t("delay", { n: (room2.delayMs ?? 0) / 1e3 })}</p>` : ""}
1670
+ ${navigation("room")}<label class="checkbox"><input type="checkbox" data-control="shortcut"${model.shortcutEnabled ? " checked" : ""}>${t("shortcut")}</label>${button("panel:exit", "exit", ' class="quiet"')}`;
1671
+ }
1672
+ function crew() {
1673
+ const provider = input.crew, state = provider?.getSnapshot();
1674
+ if (!provider || provider.unavailable || !state?.you) return `<p>${t(provider?.unavailable === "local" ? "localCrew" : "loginCrew")}</p>`;
1675
+ const online = state.friends.filter((friend) => friend.online), party = state.party;
1676
+ const person = (p) => `<li><span class="name">${escape(p.name)}<small>${p.game ? ` \xB7 ${escape(p.game.name)}` : ""}</small></span>${p.room && p.game ? button("follow", "follow", ` data-code="${escape(p.room.code)}" data-game="${escape(p.game.slug)}"`) : ""}${party?.leader === state.you.id && !party.members.some((member) => member.id === p.id) ? button("party-invite", "inviteParty", ` data-player="${escape(p.id)}"`) : ""}</li>`;
1677
+ return `${!state.connected ? `<p>${t("reconnecting")}</p>` : ""}${party ? `<ul class="roster">${party.members.map(person).join("")}</ul>${button("party-leave", "leaveParty")}` : button("party-create", "createParty")}
1678
+ ${state.invites.map((invite) => `<div class="row"><span class="grow">${escape(invite.from.name)}</span>${button("party-accept", "accept", ` data-party="${escape(invite.party)}"`)}${button("party-decline", "decline", ` data-party="${escape(invite.party)}"`)}</div>`).join("")}
1679
+ ${state.follow ? `<div class="row"><span class="grow">${escape(state.follow.from.name)} \xB7 ${escape(state.follow.game.name)}</span>${button("follow", "follow", ` data-code="${escape(state.follow.code)}" data-game="${escape(state.follow.game.slug)}"`)}</div>` : ""}
1680
+ <h2>${t("online")}</h2>${online.length ? `<ul class="roster">${online.map(person).join("")}</ul>` : `<p class="muted">${t("noFriends")}</p>`}`;
1681
+ }
1682
+ function leaderboard() {
1683
+ if (!boards || !boards.state.query) return `<p>${t("unavailable")}</p>`;
1684
+ const { query, data, loading, error, saving } = boards.state;
1685
+ const board = manifest.boards[query.board];
1686
+ return `<label>${t("board")}<select data-control="board">${Object.entries(manifest.boards).map(([id, value]) => `<option value="${escape(id)}"${query.board === id ? " selected" : ""}>${escape(resolveText(value.label, input.language, manifestLanguages(manifest)[0], id))}</option>`).join("")}</select></label>
1687
+ <div class="split"><label>${t("period")}<select data-control="period">${(board.periods ?? ["all-time"]).map((period) => `<option value="${period}"${query.period === period ? " selected" : ""}>${t(period === "daily" ? "daily" : "allTime")}</option>`).join("")}</select></label><label>${t("category")}<select data-control="category"><option value="accounts"${!query.guests ? " selected" : ""}>${t("accounts")}</option><option value="guests"${query.guests ? " selected" : ""}>${t("guests")}</option></select></label></div>
1688
+ ${query.period === "daily" ? `<small data-board-day>${escape(data?.day ?? query.day ?? new Date(input.bridge.serverTime() ?? Date.now()).toISOString().slice(0, 10))}</small>` : ""}
1689
+ ${saving ? `<p role="status" data-saving>${t(saving)}</p>` : ""}${error ? `<p role="alert">${t("offline")}</p>` : ""}
1690
+ ${data ? `<div class="table-wrap"><table><thead><tr><th>${t("rank")}</th><th>${t(query.guests ? "guests" : "accounts")}</th><th>${t("score")}</th></tr></thead><tbody>${data.entries.map((entry) => `<tr${entry.me ? ' class="self"' : ""}><td>${entry.rank}</td><td>${escape(entry.name)}${entry.verified ? `<small>${t("verified")}</small>` : ""}</td><td>${entry.score}</td></tr>`).join("")}</tbody></table>${data.entries.length ? "" : `<p>${t("empty")}</p>`}</div><p data-own-score>${t("own")} (${t(data.ownGuest ? "guests" : "accounts")}): ${data.me ? `#${data.me.rank} \xB7 ${data.me.score}${data.me.verified ? ` \xB7 ${t("verified")}` : ""}` : t("empty")}</p>` : `<p>${t(loading ? "loading" : "empty")}</p>`}
1691
+ ${button("refresh", "refresh", "", loading)}`;
1692
+ }
1693
+ function content(panel) {
1694
+ switch (panel) {
1695
+ case "home":
1696
+ return home();
1697
+ case "room":
1698
+ return room();
1699
+ case "invite":
1700
+ return invitation();
1701
+ case "friends":
1702
+ return crew();
1703
+ case "voice":
1704
+ return '<div class="stack" data-voice-panel></div>';
1705
+ case "boards":
1706
+ return leaderboard();
1707
+ case "join":
1708
+ case "watch":
1709
+ return `<form class="stack" data-form="${panel}"><label>${t("code")}<input data-control="code" name="code" autocomplete="off" autocapitalize="characters" spellcheck="false" maxlength="16" value="${escape(codeDraft)}" required></label><button class="primary" type="submit"${disabled()}>${t(panel === "join" ? "join" : "watch")}</button></form>`;
1710
+ case "attaching":
1711
+ case "matching":
1712
+ return `<p role="status">${t(panel === "matching" ? "matching" : "joining")}</p>${model.session?.waiting ? `<p>${t("queue", { n: model.session.waiting.players, max: model.session.waiting.max })}</p>` : ""}<button type="button" data-action="cancel">${t("cancel")}</button>`;
1713
+ case "countdown":
1714
+ return `<p>${t("starting")}</p><div class="countdown" data-countdown></div>`;
1715
+ case "boot":
1716
+ return "";
1717
+ case "error":
1718
+ return `<p role="alert">${t(model.session?.room?.connection === "replaced" ? "replaced" : "noRoom")}</p>${button("leave", "home")}${button("exit-now", "exit")}`;
1719
+ case "exit":
1720
+ return model.session?.kind === "room" && phase(model.session) !== "ended" ? `<p>${t(model.session.room?.persistent ? "leaveHint" : "temporaryHint")}</p>${invitation()}${button("disconnect-exit", "leaveNow", ' class="primary"')}<p class="muted">${t("abandonHint")}</p>${button("leave-exit", "leaveRoom")}` : button("leave-exit", "exit", ' class="primary"');
1721
+ }
1722
+ }
1723
+ function title(panel) {
1724
+ const keys = { boot: "loading", home: "home", room: "room", invite: "copy", friends: "friends", voice: "voice", boards: "boards", join: "join", watch: "watch", attaching: "joining", matching: "matching", countdown: "starting", error: "error", exit: "exit" };
1725
+ return t(keys[panel]);
1726
+ }
1727
+ function updateCountdown() {
1728
+ const at = model.session?.room?.countdownAt, now = input.bridge.serverTime();
1729
+ const value = at === null || at === void 0 || now === null ? "..." : String(Math.max(0, Math.round((at - now) / 1e3)));
1730
+ const node = root.querySelector("[data-countdown]");
1731
+ if (node && node.textContent !== value) {
1732
+ node.textContent = value;
1733
+ announce(`${t("starting")} ${value}`);
1734
+ }
1735
+ }
1736
+ function geometry() {
1737
+ geometryFrame = 0;
1738
+ if (disposed || !input.bridge.epoch || !model.session) return;
1739
+ const frame = gameViewport(input.frame), { scaleX, scaleY } = frame;
1740
+ const reservedRects = [...root.querySelectorAll("[data-reserve]")].map((el) => {
1741
+ const rect = el.getBoundingClientRect(), left = Math.max(frame.left, rect.left), top = Math.max(frame.top, rect.top), right = Math.min(frame.right, rect.right), bottom = Math.min(frame.bottom, rect.bottom);
1742
+ return { x: Math.max(0, Math.round((left - frame.left) * scaleX)), y: Math.max(0, Math.round((top - frame.top) * scaleY)), width: Math.max(0, Math.round((right - left) * scaleX)), height: Math.max(0, Math.round((bottom - top) * scaleY)) };
1743
+ }).filter((rect) => rect.width && rect.height).slice(0, 8);
1744
+ const view = { inputBlocked: phase(model.session) === "boot" || !!visiblePanel(model), reservedRects, safeArea: measureSafeArea(input.frame, safeProbe), shortcutEnabled: model.shortcutEnabled };
1745
+ const serialized = `${input.bridge.epoch}:${JSON.stringify(view)}`;
1746
+ if (lastView === serialized) return;
1747
+ lastView = serialized;
1748
+ void input.bridge.request("overlay.view", view).catch(async (error) => {
1749
+ if (error?.code === "invalid_request" && lastView === serialized) {
1750
+ const { safeArea, ...legacy } = view;
1751
+ try {
1752
+ await input.bridge.request("overlay.view", legacy);
1753
+ return;
1754
+ } catch {
1755
+ }
1756
+ }
1757
+ if (lastView === serialized) lastView = "";
1758
+ });
1759
+ }
1760
+ function resize() {
1761
+ if (!geometryFrame) geometryFrame = win.requestAnimationFrame(geometry);
1762
+ }
1763
+ function rematchBar() {
1764
+ const session = model.session, room2 = session?.room;
1765
+ if (!room2 || room2.status !== "finished") return "";
1766
+ const active = room2.players.filter((p) => p.connected && p.role !== "spectator");
1767
+ const ready = active.filter((p) => p.ready), host2 = session.kind === "room" && room2.host === room2.you;
1768
+ const canStart = room2.connection === "connected" && active.length >= room2.limits.min && ready.length === active.length;
1769
+ return `<small role="status" data-rematch-ready>${t("rematchReady", { n: ready.length, max: active.length })}</small>
1770
+ ${ready.length ? `<small data-rematch-players>${ready.map((p) => escape(p.name)).join(", ")}</small>` : ""}
1771
+ ${host2 ? button("restart", "rematchStart", ' class="primary"', !canStart) : `<small>${t("waitHost")}</small>`}`;
1772
+ }
1773
+ function render() {
1774
+ if (disposed) return;
1775
+ const panel = visiblePanel(model), current = phase(model.session), room2 = model.session?.room;
1776
+ const focused = root.activeElement;
1777
+ const focusPeer = focused?.dataset.peer;
1778
+ const focusKey = focused?.dataset.control ? ["control", focused.dataset.control] : focused?.dataset.action ? ["action", focused.dataset.action] : null;
1779
+ const previousScroll = root.querySelector(".dialog")?.scrollTop ?? 0;
1780
+ const selection = focused?.tagName === "INPUT" ? { start: focused.selectionStart, end: focused.selectionEnd } : null;
1781
+ const crewState = input.crew?.getSnapshot(), invitations = (crewState?.invites.length ?? 0) + (crewState?.follow ? 1 : 0);
1782
+ const label = current === "watching" ? t("watching") : room2?.connection === "reconnecting" ? t("reconnecting") : room2?.code ?? "Caisual";
1783
+ surface.innerHTML = current === "boot" ? "" : `<div class="pill" data-reserve><button type="button" data-action="menu" aria-label="${t("menu")}" aria-expanded="${!!panel}">C<span aria-hidden="true"><small>${escape(label)}</small></span></button>${voiceEligible(manifest, model.session) && model.session?.kind === "room" ? `<button type="button" class="voice-toggle" data-voice-toggle data-action="panel:voice"></button>` : ""}${invitations ? `<button type="button" data-action="panel:friends" aria-label="${t("friends")} (${invitations})">${invitations}</button>` : ""}</div>
1784
+ ${current === "ended" && !panel ? `<div class="ended" data-reserve role="region" aria-label="${t("ended")}"><strong>${t("ended")}</strong>${boards?.state.saving ? `<small role="status" data-saving>${t(boards.state.saving)}</small>` : ""}${canPlayAgain(model.session) ? button("again", "again", ' class="primary"') : model.session?.kind === "room" && room2?.status !== "finished" ? `<small>${t("waitHost")}</small>` : ""}${rematchBar()}${Object.keys(manifest.boards).length ? button("panel:boards", "boards") : ""}${button("panel:home", "homeMenu")}</div>` : ""}
1785
+ ${panel ? `<div class="backdrop${panel === "home" ? " home" : ""}"><section class="dialog${panel === "boards" || panel === "friends" ? " wide" : ""}" role="dialog" aria-modal="true" aria-labelledby="panel-title" tabindex="-1"><div class="top"><h2 id="panel-title">${title(panel)}</h2><button type="button" data-action="close" aria-label="${t("close")}">\xD7</button></div><div class="stack">${content(panel)}${model.error ? `<p class="error" role="alert" data-error>${t(errorText(model.error))}</p>` : ""}${model.session?.resumeError ? `<p class="error" role="alert">${t("saveFailed")}</p>` : ""}${model.notice ? `<p class="notice" role="status">${escape(model.notice)}</p>` : ""}</div></section></div>` : ""}`;
1786
+ for (const element of surface.querySelectorAll(".pill,.backdrop,.ended")) element.style.pointerEvents = "auto";
1787
+ const backdrop = root.querySelector(".backdrop.home");
1788
+ if (backdrop && input.configuration.coverUrl) backdrop.style.backgroundImage = `linear-gradient(#0b151c99,#0b151cee),url(${JSON.stringify(input.configuration.coverUrl)})`;
1789
+ host.dataset.phase = current;
1790
+ host.dataset.panel = panel ?? "";
1791
+ input.frame.inert = !!panel || oldInert;
1792
+ if (panel) input.frame.tabIndex = -1;
1793
+ else if (oldTabIndex === null) input.frame.removeAttribute("tabindex");
1794
+ else input.frame.setAttribute("tabindex", oldTabIndex);
1795
+ updateVoice();
1796
+ updateBoot(current === "boot");
1797
+ const dialog = root.querySelector(".dialog");
1798
+ if (dialog) dialog.scrollTop = previousScroll;
1799
+ const focusPanel = current === "boot" ? boot : dialog;
1800
+ const matched = focusKey ? [...root.querySelectorAll(`[data-${focusKey[0]}]`)].find((el) => el.getAttribute(`data-${focusKey[0]}`) === focusKey[1] && el.dataset.peer === focusPeer) : null;
1801
+ if (!panel && wasModal && !input.frame.inert && input.frame.isConnected) {
1802
+ input.frame.focus({ preventScroll: true });
1803
+ input.frame.contentWindow?.focus();
1804
+ } else if (matched && (!panel || focusPanel?.contains(matched)) && !matched.hasAttribute("disabled")) {
1805
+ matched.focus({ preventScroll: true });
1806
+ if (matched.tagName === "INPUT" && selection?.start !== null && selection?.end !== null && selection) matched.setSelectionRange(selection.start, selection.end);
1807
+ } else if (panel && (!wasModal || focused)) (current === "boot" ? boot : dialog?.querySelector('select,input,button:not([data-action="close"]):not(:disabled)') ?? dialog)?.focus({ preventScroll: true });
1808
+ wasModal = !!panel;
1809
+ if (lastPhase !== current) {
1810
+ lastPhase = current;
1811
+ announce(current === "boot" ? "" : t({ home: "home", attaching: "joining", matching: "matching", lobby: "room", countdown: "starting", playing: "playing", ended: "ended", watching: "watching", error: "error" }[current]));
1812
+ }
1813
+ updateCountdown();
1814
+ resize();
1815
+ }
1816
+ const click = (event) => {
1817
+ const target = event.target.closest("button[data-action]");
1818
+ if (!target || target.disabled) return;
1819
+ const action = target.dataset.action;
1820
+ event.stopPropagation();
1821
+ if (action.startsWith("panel:")) {
1822
+ setPanel(action.slice(6));
1823
+ return;
1824
+ }
1825
+ switch (action) {
1826
+ case "menu":
1827
+ toggle();
1828
+ break;
1829
+ case "close":
1830
+ close();
1831
+ break;
1832
+ case "play": {
1833
+ const selected = primaryAction(manifest, model.mode);
1834
+ if (selected) void perform(selected.op, { mode: model.mode });
1835
+ break;
1836
+ }
1837
+ case "match":
1838
+ void perform("room.match", { mode: model.mode });
1839
+ break;
1840
+ case "join-invite":
1841
+ if (input.configuration.invite) void perform("room.join", { code: input.configuration.invite });
1842
+ break;
1843
+ case "resume":
1844
+ void perform("session.resume", {});
1845
+ break;
1846
+ case "cancel":
1847
+ void perform("session.cancel", {});
1848
+ break;
1849
+ case "ready":
1850
+ void perform("room.ready", { ready: !model.session?.room?.players.find((p) => p.id === model.session?.room?.you)?.ready });
1851
+ break;
1852
+ case "start":
1853
+ void perform("room.start", {});
1854
+ break;
1855
+ case "restart":
1856
+ void perform("room.restart", {});
1857
+ break;
1858
+ case "copy":
1859
+ void copyInvite();
1860
+ break;
1861
+ case "voice-join":
1862
+ void performVoice("voice.join", {});
1863
+ break;
1864
+ case "voice-mute":
1865
+ void performVoice("voice.mute", { muted: !model.session?.voice?.muted });
1866
+ break;
1867
+ case "voice-leave":
1868
+ void performVoice("voice.leave", {});
1869
+ break;
1870
+ case "again": {
1871
+ if (!canPlayAgain(model.session)) break;
1872
+ if (model.session?.kind === "local") void perform("local.start", { mode: model.session.mode ?? model.mode });
1873
+ else if (model.session?.room?.status === "finished") void perform("room.restart", {});
1874
+ else void perform("room.create", { mode: model.session?.room?.mode ?? null }, async () => {
1875
+ setPanel("invite");
1876
+ dispatch({ type: "notice", notice: t("newRoom") });
1877
+ await copyInvite();
1878
+ });
1879
+ break;
1880
+ }
1881
+ case "disconnect-exit":
1882
+ void perform("session.disconnect", {}, input.exit);
1883
+ break;
1884
+ case "leave-exit":
1885
+ void perform("session.leave", {}, input.exit);
1886
+ break;
1887
+ case "leave":
1888
+ void perform("session.leave", {}, () => setPanel("home"));
1889
+ break;
1890
+ case "exit-now":
1891
+ input.exit();
1892
+ break;
1893
+ case "reload":
1894
+ boot?.focus({ preventScroll: true });
1895
+ resetBootWait();
1896
+ input.frame.src = input.frame.src;
1897
+ break;
1898
+ case "refresh":
1899
+ void boards?.refresh();
1900
+ break;
1901
+ case "party-create":
1902
+ input.crew?.party.create();
1903
+ break;
1904
+ case "party-leave":
1905
+ input.crew?.party.leave();
1906
+ break;
1907
+ case "party-invite":
1908
+ input.crew?.party.invite(target.dataset.player);
1909
+ break;
1910
+ case "party-accept":
1911
+ input.crew?.party.accept(target.dataset.party);
1912
+ break;
1913
+ case "party-decline":
1914
+ input.crew?.party.decline(target.dataset.party);
1915
+ break;
1916
+ case "follow":
1917
+ input.crew?.follow(target.dataset.game, target.dataset.code);
1918
+ break;
1919
+ }
1920
+ };
1921
+ const change = (event) => {
1922
+ const target = event.target, field = target.dataset.control;
1923
+ if (field === "voice-volume") {
1924
+ target.dataset.editing = "true";
1925
+ void performVoice("voice.setVolume", { playerId: target.dataset.peer, volume: Number(target.value) }).finally(() => {
1926
+ delete target.dataset.editing;
1927
+ updateVoice();
1928
+ });
1929
+ return;
1930
+ }
1931
+ if (field === "mode") dispatch({ type: "mode", mode: target.value });
1932
+ if (field === "role") void perform(model.session?.room?.status === "lobby" ? "room.role" : "room.requestRole", { role: target.value });
1933
+ if (field === "team") void perform("room.team", { team: Number(target.value) });
1934
+ if (field === "shortcut") {
1935
+ const enabled = target.checked;
1936
+ try {
1937
+ win.localStorage.setItem("caisual-overlay-shortcut-v1", enabled ? "on" : "off");
1938
+ } catch {
1939
+ }
1940
+ dispatch({ type: "shortcut", enabled });
1941
+ }
1942
+ const query = boards?.state.query;
1943
+ if (query && ["board", "period", "category"].includes(field ?? "")) {
1944
+ const next = { ...query };
1945
+ if (field === "board") {
1946
+ next.board = target.value;
1947
+ next.period = (manifest.boards[next.board].periods ?? ["all-time"])[0];
1948
+ delete next.day;
1949
+ }
1950
+ if (field === "period") {
1951
+ next.period = target.value;
1952
+ delete next.day;
1953
+ }
1954
+ if (field === "category") next.guests = target.value === "guests";
1955
+ boards.select(next);
1956
+ }
1957
+ };
1958
+ const submit = (event) => {
1959
+ const form = event.target;
1960
+ if (!form.dataset.form) return;
1961
+ event.preventDefault();
1962
+ const code = normalizeInvite(form.querySelector('input[data-control="code"]').value);
1963
+ if (!code) {
1964
+ dispatch({ type: "error", code: "invalid_code" });
1965
+ return;
1966
+ }
1967
+ void perform(form.dataset.form === "watch" ? "room.watch" : "room.join", { code });
1968
+ };
1969
+ const keydown = (event) => {
1970
+ const panel = visiblePanel(model);
1971
+ if (panel && event.key === "Escape") {
1972
+ event.preventDefault();
1973
+ event.stopImmediatePropagation();
1974
+ close();
1975
+ return;
1976
+ }
1977
+ if (panel && event.key === "Tab") {
1978
+ const items = controls().filter((el) => el.closest(panel === "boot" ? ".boot" : ".dialog")), first = items[0], last = items.at(-1);
1979
+ if (!first) {
1980
+ event.preventDefault();
1981
+ return;
1982
+ }
1983
+ if (event.shiftKey && (root.activeElement === first || !items.includes(root.activeElement))) {
1984
+ event.preventDefault();
1985
+ last?.focus();
1986
+ } else if (!event.shiftKey && (root.activeElement === last || !items.includes(root.activeElement))) {
1987
+ event.preventDefault();
1988
+ first.focus();
1989
+ }
1990
+ } else if (!panel && model.shortcutEnabled && event.key === "Tab" && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey) {
1991
+ event.preventDefault();
1992
+ toggle();
1993
+ }
1994
+ };
1995
+ root.addEventListener("input", (event) => {
1996
+ const node = event.target;
1997
+ if (node.dataset.control === "code") codeDraft = node.value;
1998
+ if (node.dataset.control === "voice-volume") node.dataset.editing = "true";
1999
+ });
2000
+ root.addEventListener("click", click);
2001
+ root.addEventListener("change", change);
2002
+ root.addEventListener("submit", submit);
2003
+ win.addEventListener("keydown", keydown, true);
2004
+ win.addEventListener("resize", resize);
2005
+ win.addEventListener("scroll", resize, true);
2006
+ win.visualViewport?.addEventListener("resize", resize);
2007
+ win.visualViewport?.addEventListener("scroll", resize);
2008
+ const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(resize) : null;
2009
+ observer?.observe(input.frame);
2010
+ const countdownTimer = win.setInterval(updateCountdown, 250);
2011
+ stops.push(input.bridge.subscribe((session) => {
2012
+ const previous = model.session;
2013
+ if (!session || session.id !== previous?.id) {
2014
+ voiceOperation++;
2015
+ voicePending = null;
2016
+ voiceError = null;
2017
+ }
2018
+ if (!session) {
2019
+ lastView = "";
2020
+ boards?.reset();
2021
+ operation++;
2022
+ model.busy = false;
2023
+ }
2024
+ if (previous && session && JSON.stringify({ ...previous, voice: null }) === JSON.stringify({ ...session, voice: null })) {
2025
+ model = reduceUi(model, { type: "session", session });
2026
+ updateVoice();
2027
+ } else dispatch({ type: "session", session });
2028
+ }));
2029
+ stops.push(input.bridge.onOpen((panel) => setPanel(panel)), input.bridge.onShortcut(toggle), input.bridge.onError(({ error }) => {
2030
+ if (!visiblePanel(model)) setPanel("room");
2031
+ dispatch({ type: "error", code: error.code });
2032
+ }));
2033
+ stops.push(input.bridge.onScore((score) => boards?.queued(score)));
2034
+ if (input.crew) stops.push(input.crew.subscribe(() => {
2035
+ const state = input.crew.getSnapshot();
2036
+ if (state.follow || state.invites.length) announce(t("friends"));
2037
+ render();
2038
+ }));
2039
+ render();
2040
+ return { element: host, root, dispose() {
2041
+ disposed = true;
2042
+ operation++;
2043
+ stops.forEach((stop) => stop());
2044
+ boards?.dispose();
2045
+ observer?.disconnect();
2046
+ win.clearInterval(countdownTimer);
2047
+ win.cancelAnimationFrame(geometryFrame);
2048
+ win.clearTimeout(bootTimer);
2049
+ win.clearTimeout(bootFadeTimer);
2050
+ win.removeEventListener("keydown", keydown, true);
2051
+ win.removeEventListener("resize", resize);
2052
+ win.removeEventListener("scroll", resize, true);
2053
+ win.visualViewport?.removeEventListener("resize", resize);
2054
+ win.visualViewport?.removeEventListener("scroll", resize);
2055
+ input.frame.inert = oldInert;
2056
+ if (oldTabIndex === null) input.frame.removeAttribute("tabindex");
2057
+ else input.frame.setAttribute("tabindex", oldTabIndex);
2058
+ void input.bridge.request("overlay.view", { inputBlocked: false, reservedRects: [], shortcutEnabled: false }).catch(() => {
2059
+ });
2060
+ host.remove();
2061
+ } };
2062
+ }
2063
+ export {
2064
+ avviaHandshake,
2065
+ creaPonteOspite,
2066
+ eMessaggioReady,
2067
+ eRichiestaBiglietto,
2068
+ mountOverlay,
2069
+ overlayConfiguration,
2070
+ overlayLanguage,
2071
+ overlayLocale,
2072
+ styles as overlayStyles,
2073
+ stanzaDaMessaggio
2074
+ };