@caisual/kit 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js ADDED
@@ -0,0 +1,2131 @@
1
+ // src/node/index.ts
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+
7
+ // src/stanza/json.ts
8
+ function isPlainObject(value) {
9
+ const prototype = Object.getPrototypeOf(value);
10
+ return prototype === Object.prototype || prototype === null;
11
+ }
12
+ function verificaValore(value, visitati) {
13
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
14
+ if (typeof value === "number") return Number.isFinite(value);
15
+ if (typeof value !== "object") return false;
16
+ if (visitati.has(value)) return false;
17
+ visitati.add(value);
18
+ let valido = true;
19
+ if (Array.isArray(value)) {
20
+ const chiavi = Reflect.ownKeys(value);
21
+ if (chiavi.some((key) => {
22
+ if (key === "length") return false;
23
+ if (typeof key !== "string" || !/^(0|[1-9][0-9]*)$/.test(key)) return true;
24
+ const indice = Number(key);
25
+ return !Number.isSafeInteger(indice) || indice >= value.length;
26
+ })) valido = false;
27
+ for (let indice = 0; indice < value.length; indice++) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(indice));
29
+ if (!valido || descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor) || !verificaValore(descriptor.value, visitati)) {
30
+ valido = false;
31
+ break;
32
+ }
33
+ }
34
+ } else if (isPlainObject(value)) {
35
+ for (const key of Reflect.ownKeys(value)) {
36
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
37
+ if (typeof key !== "string" || descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor) || !verificaValore(descriptor.value, visitati)) {
38
+ valido = false;
39
+ break;
40
+ }
41
+ }
42
+ } else {
43
+ valido = false;
44
+ }
45
+ visitati.delete(value);
46
+ return valido;
47
+ }
48
+ function analizzaJson(value) {
49
+ if (!verificaValore(value, /* @__PURE__ */ new Set())) return { ok: false, code: "state_invalid" };
50
+ const testo = JSON.stringify(value);
51
+ return {
52
+ ok: true,
53
+ testo,
54
+ valore: JSON.parse(testo),
55
+ bytes: new TextEncoder().encode(testo).byteLength
56
+ };
57
+ }
58
+ function isObject(value) {
59
+ return typeof value === "object" && value !== null && !Array.isArray(value);
60
+ }
61
+ function visitaDiff(prima, dopo, path, patch) {
62
+ if (Array.isArray(prima) && Array.isArray(dopo)) {
63
+ if (prima.length !== dopo.length) {
64
+ patch.push({ op: "set", path, value: dopo });
65
+ return;
66
+ }
67
+ for (let indice = 0; indice < dopo.length; indice++) {
68
+ visitaDiff(prima[indice], dopo[indice], [...path, indice], patch);
69
+ }
70
+ return;
71
+ }
72
+ if (isObject(prima) && isObject(dopo)) {
73
+ for (const key of Object.keys(prima)) {
74
+ if (!(key in dopo)) patch.push({ op: "del", path: [...path, key] });
75
+ }
76
+ for (const [key, value] of Object.entries(dopo)) {
77
+ if (!(key in prima)) patch.push({ op: "set", path: [...path, key], value });
78
+ else visitaDiff(prima[key], value, [...path, key], patch);
79
+ }
80
+ return;
81
+ }
82
+ if (!Object.is(prima, dopo)) patch.push({ op: "set", path, value: dopo });
83
+ }
84
+ function creaDiff(prima, dopo) {
85
+ const patch = [];
86
+ visitaDiff(prima, dopo, [], patch);
87
+ return patch;
88
+ }
89
+ function giornoUtc(ora) {
90
+ return new Date(ora).toISOString().slice(0, 10);
91
+ }
92
+ var COSTANTI_SHA256 = [
93
+ 1116352408,
94
+ 1899447441,
95
+ 3049323471,
96
+ 3921009573,
97
+ 961987163,
98
+ 1508970993,
99
+ 2453635748,
100
+ 2870763221,
101
+ 3624381080,
102
+ 310598401,
103
+ 607225278,
104
+ 1426881987,
105
+ 1925078388,
106
+ 2162078206,
107
+ 2614888103,
108
+ 3248222580,
109
+ 3835390401,
110
+ 4022224774,
111
+ 264347078,
112
+ 604807628,
113
+ 770255983,
114
+ 1249150122,
115
+ 1555081692,
116
+ 1996064986,
117
+ 2554220882,
118
+ 2821834349,
119
+ 2952996808,
120
+ 3210313671,
121
+ 3336571891,
122
+ 3584528711,
123
+ 113926993,
124
+ 338241895,
125
+ 666307205,
126
+ 773529912,
127
+ 1294757372,
128
+ 1396182291,
129
+ 1695183700,
130
+ 1986661051,
131
+ 2177026350,
132
+ 2456956037,
133
+ 2730485921,
134
+ 2820302411,
135
+ 3259730800,
136
+ 3345764771,
137
+ 3516065817,
138
+ 3600352804,
139
+ 4094571909,
140
+ 275423344,
141
+ 430227734,
142
+ 506948616,
143
+ 659060556,
144
+ 883997877,
145
+ 958139571,
146
+ 1322822218,
147
+ 1537002063,
148
+ 1747873779,
149
+ 1955562222,
150
+ 2024104815,
151
+ 2227730452,
152
+ 2361852424,
153
+ 2428436474,
154
+ 2756734187,
155
+ 3204031479,
156
+ 3329325298
157
+ ];
158
+ function ruotaDestra(value, bits) {
159
+ return value >>> bits | value << 32 - bits;
160
+ }
161
+ function hashSeed(testo) {
162
+ const bytes = Array.from(new TextEncoder().encode(testo));
163
+ const bitLength = bytes.length * 8;
164
+ bytes.push(128);
165
+ while (bytes.length % 64 !== 56) bytes.push(0);
166
+ for (let indice = 7; indice >= 0; indice--) {
167
+ bytes.push(indice < 4 ? bitLength >>> indice * 8 & 255 : 0);
168
+ }
169
+ let h0 = 1779033703;
170
+ let h1 = 3144134277;
171
+ let h2 = 1013904242;
172
+ let h3 = 2773480762;
173
+ let h4 = 1359893119;
174
+ let h5 = 2600822924;
175
+ let h6 = 528734635;
176
+ let h7 = 1541459225;
177
+ const parole = new Uint32Array(64);
178
+ for (let blocco = 0; blocco < bytes.length; blocco += 64) {
179
+ for (let indice = 0; indice < 16; indice++) {
180
+ const offset = blocco + indice * 4;
181
+ parole[indice] = ((bytes[offset] ?? 0) << 24 | (bytes[offset + 1] ?? 0) << 16 | (bytes[offset + 2] ?? 0) << 8 | (bytes[offset + 3] ?? 0)) >>> 0;
182
+ }
183
+ for (let indice = 16; indice < 64; indice++) {
184
+ const x = parole[indice - 15] ?? 0;
185
+ const y = parole[indice - 2] ?? 0;
186
+ const s0 = ruotaDestra(x, 7) ^ ruotaDestra(x, 18) ^ x >>> 3;
187
+ const s1 = ruotaDestra(y, 17) ^ ruotaDestra(y, 19) ^ y >>> 10;
188
+ parole[indice] = (parole[indice - 16] ?? 0) + s0 + (parole[indice - 7] ?? 0) + s1 >>> 0;
189
+ }
190
+ let a = h0;
191
+ let b = h1;
192
+ let c = h2;
193
+ let d = h3;
194
+ let e = h4;
195
+ let f = h5;
196
+ let g = h6;
197
+ let h = h7;
198
+ for (let indice = 0; indice < 64; indice++) {
199
+ const s1 = ruotaDestra(e, 6) ^ ruotaDestra(e, 11) ^ ruotaDestra(e, 25);
200
+ const scelta = e & f ^ ~e & g;
201
+ const temp1 = h + s1 + scelta + (COSTANTI_SHA256[indice] ?? 0) + (parole[indice] ?? 0) >>> 0;
202
+ const s0 = ruotaDestra(a, 2) ^ ruotaDestra(a, 13) ^ ruotaDestra(a, 22);
203
+ const maggioranza = a & b ^ a & c ^ b & c;
204
+ const temp2 = s0 + maggioranza >>> 0;
205
+ h = g;
206
+ g = f;
207
+ f = e;
208
+ e = d + temp1 >>> 0;
209
+ d = c;
210
+ c = b;
211
+ b = a;
212
+ a = temp1 + temp2 >>> 0;
213
+ }
214
+ h0 = h0 + a >>> 0;
215
+ h1 = h1 + b >>> 0;
216
+ h2 = h2 + c >>> 0;
217
+ h3 = h3 + d >>> 0;
218
+ h4 = h4 + e >>> 0;
219
+ h5 = h5 + f >>> 0;
220
+ h6 = h6 + g >>> 0;
221
+ h7 = h7 + h >>> 0;
222
+ }
223
+ return h0 >>> 0;
224
+ }
225
+ function seedGiornata(slug, day) {
226
+ return hashSeed(`caisual:${slug}:${day}`);
227
+ }
228
+ function seedStanza(roomId) {
229
+ return hashSeed(`caisual:room:${roomId}`);
230
+ }
231
+
232
+ // src/stanza/nucleo.ts
233
+ var CHIAVE_NUCLEO = "nucleo";
234
+ var PREFISSO_SAVE = "save:";
235
+ var LIMITE_FRAME = 16 * 1024;
236
+ var LIMITE_STATO = 256 * 1024;
237
+ var LIMITE_SAVE = 128 * 1024;
238
+ var LIMITE_DEPOSITO = 64 * 1024;
239
+ var LIMITE_OPERAZIONI_DEPOSITO = 120;
240
+ var GRAZIA_MS = 6e4;
241
+ var STANZA_VUOTA_MS = 5 * 6e4;
242
+ var COUNTDOWN_MS = 3e3;
243
+ var RIPOSO_TICK_MS = 3e4;
244
+ var INATTIVITA_MS = 10 * 6e4;
245
+ var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
246
+ var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
247
+ var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
248
+ var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
249
+ var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
250
+ "store_invalid_key",
251
+ "store_too_large",
252
+ "store_full",
253
+ "store_not_integer",
254
+ "store_unavailable",
255
+ "store_rate_limited"
256
+ ]);
257
+ function record(value) {
258
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
259
+ }
260
+ function definizioneValida(value) {
261
+ return record(value)?.[GAME_DEFINITION] === true;
262
+ }
263
+ function idGiocatore(player) {
264
+ return typeof player === "string" ? player : player.id;
265
+ }
266
+ function copiaGiocatore(player) {
267
+ return {
268
+ id: player.id,
269
+ name: player.name,
270
+ guest: player.guest,
271
+ role: player.role,
272
+ team: player.team,
273
+ connected: player.connected
274
+ };
275
+ }
276
+ function copiaJson(value) {
277
+ return JSON.parse(JSON.stringify(value));
278
+ }
279
+ function erroreConCodice(code, message) {
280
+ return Object.assign(new Error(message), { code });
281
+ }
282
+ function codiceIngresso(code) {
283
+ if (code === "room_not_found") return 4001;
284
+ if (code === "room_full") return 4e3;
285
+ return 4004;
286
+ }
287
+ var NucleoStanza = class _NucleoStanza {
288
+ constructor(definizione, manifest, adattatore) {
289
+ this.definizione = definizione;
290
+ this.manifest = manifest;
291
+ this.adattatore = adattatore;
292
+ this.dati = null;
293
+ this.frequenza = /* @__PURE__ */ new Map();
294
+ this.frequenzaDeposito = [];
295
+ this.kickRichiesti = /* @__PURE__ */ new Set();
296
+ this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
297
+ this.fineRichiesta = null;
298
+ this.applicandoAzioni = false;
299
+ this.ultimoStatoOsservato = "";
300
+ this.voceDaPersistire = false;
301
+ const nucleo = this;
302
+ const daily = {
303
+ get day() {
304
+ return giornoUtc(nucleo.adattatore.ora());
305
+ },
306
+ get seed() {
307
+ return seedGiornata(nucleo.manifest.id, giornoUtc(nucleo.adattatore.ora()));
308
+ }
309
+ };
310
+ this.room = {
311
+ get id() {
312
+ return nucleo.richiediDati().id;
313
+ },
314
+ get seed() {
315
+ return seedStanza(nucleo.richiediDati().id);
316
+ },
317
+ get mode() {
318
+ return nucleo.richiediDati().mode;
319
+ },
320
+ get status() {
321
+ return nucleo.richiediDati().status;
322
+ },
323
+ get tick() {
324
+ return nucleo.richiediDati().tick;
325
+ },
326
+ get tickRate() {
327
+ return nucleo.richiediDati().tickRate;
328
+ },
329
+ get result() {
330
+ return nucleo.richiediDati().result;
331
+ },
332
+ get state() {
333
+ return nucleo.richiediDati().state;
334
+ },
335
+ set state(value) {
336
+ nucleo.richiediDati().state = value;
337
+ },
338
+ get players() {
339
+ return nucleo.richiediDati().giocatori.map(copiaGiocatore);
340
+ },
341
+ get host() {
342
+ const dati = nucleo.richiediDati();
343
+ const host = dati.giocatori.find((player) => player.id === dati.hostId);
344
+ return host === void 0 ? null : copiaGiocatore(host);
345
+ },
346
+ broadcast(message) {
347
+ nucleo.broadcastCreatore(message);
348
+ },
349
+ send(player, message) {
350
+ nucleo.inviaCreatore(idGiocatore(player), message);
351
+ },
352
+ kick(player) {
353
+ nucleo.kickRichiesti.add(idGiocatore(player));
354
+ },
355
+ setRole(player, role) {
356
+ nucleo.impostaRuoloDalServer(idGiocatore(player), role);
357
+ },
358
+ setTeam(player, team) {
359
+ nucleo.impostaSquadraDalServer(idGiocatore(player), team);
360
+ },
361
+ end(result) {
362
+ nucleo.richiediFine(result);
363
+ },
364
+ save(key, value) {
365
+ return nucleo.salva(key, value);
366
+ },
367
+ load(key) {
368
+ return nucleo.caricaSave(key);
369
+ },
370
+ shared: {
371
+ get(key) {
372
+ return nucleo.leggiDeposito(key);
373
+ },
374
+ set(key, value) {
375
+ return nucleo.scriviDeposito(key, value);
376
+ },
377
+ delete(key) {
378
+ return nucleo.eliminaDeposito(key);
379
+ },
380
+ list(prefix) {
381
+ return nucleo.elencaDeposito(prefix);
382
+ },
383
+ increment(key, amount = 1) {
384
+ return nucleo.incrementaDeposito(key, amount);
385
+ }
386
+ },
387
+ schedule(milliseconds, handler, payload) {
388
+ nucleo.pianifica(milliseconds, handler, payload);
389
+ },
390
+ board: {
391
+ submit(player, board, score, options = {}) {
392
+ nucleo.accodaPunteggio(idGiocatore(player), board, score, options.daily === true);
393
+ }
394
+ },
395
+ daily,
396
+ time: { now: () => nucleo.adattatore.ora() },
397
+ voice: {
398
+ get mode() {
399
+ return nucleo.manifest.voice ?? "none";
400
+ },
401
+ setGain(listener, speaker, gain) {
402
+ nucleo.impostaGuadagno(idGiocatore(listener), idGiocatore(speaker), gain);
403
+ },
404
+ setProximity(a, b, gain) {
405
+ const primo = idGiocatore(a);
406
+ const secondo = idGiocatore(b);
407
+ nucleo.impostaGuadagno(primo, secondo, gain);
408
+ nucleo.impostaGuadagno(secondo, primo, gain);
409
+ }
410
+ }
411
+ };
412
+ }
413
+ static async apri(definizione, manifest, adattatore) {
414
+ if (!definizioneValida(definizione)) {
415
+ throw new TypeError("The game server must export a definition created with defineGame.");
416
+ }
417
+ _NucleoStanza.verificaManifest(manifest);
418
+ const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
419
+ const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
420
+ if (salvato !== void 0) {
421
+ nucleo.dati = salvato;
422
+ const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
423
+ salvato.ultimoInputAt ??= adattatore.ora();
424
+ salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
425
+ nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
426
+ await nucleo.riconciliaConnessioni();
427
+ if (daAggiornare) await nucleo.persisti();
428
+ }
429
+ await nucleo.aggiornaProgrammazione();
430
+ return nucleo;
431
+ }
432
+ static verificaManifest(manifest) {
433
+ if (typeof manifest?.id !== "string" || !Number.isInteger(manifest.players?.min) || !Number.isInteger(manifest.players?.max) || manifest.players.min < 1 || manifest.players.max < manifest.players.min || typeof manifest.lobby !== "boolean" || manifest.persistent !== void 0 && typeof manifest.persistent !== "boolean" || !Array.isArray(manifest.roles) || !Array.isArray(manifest.modes) || manifest.voice !== void 0 && !["none", "room", "team", "proximity"].includes(manifest.voice)) {
434
+ throw new TypeError("The room manifest is invalid.");
435
+ }
436
+ }
437
+ richiediDati() {
438
+ if (this.dati === null) throw new Error("The room has not been created.");
439
+ return this.dati;
440
+ }
441
+ stanzaTerminata() {
442
+ return this.dati?.status === "ended";
443
+ }
444
+ get esiste() {
445
+ return this.dati !== null;
446
+ }
447
+ async crea(id, mode, _creator) {
448
+ if (this.dati !== null) return false;
449
+ if (mode !== null && !this.manifest.modes.some((item) => item.id === mode)) {
450
+ throw new Error("The selected game mode does not exist.");
451
+ }
452
+ const ora = this.adattatore.ora();
453
+ this.dati = {
454
+ versione: 1,
455
+ id,
456
+ mode,
457
+ status: "lobby",
458
+ tick: 0,
459
+ tickRate: this.definizione.tickRate,
460
+ ultimoInputAt: ora,
461
+ ultimoCambioStatoAt: ora,
462
+ state: {},
463
+ giocatori: [],
464
+ hostId: null,
465
+ result: null,
466
+ resultAt: null,
467
+ countdownAt: null,
468
+ timer: [],
469
+ prossimoTimerId: 1,
470
+ punteggi: [],
471
+ fineInCoda: null,
472
+ vuotaDa: ora,
473
+ cancellaDopoFlush: false,
474
+ tickSincronizzato: 0,
475
+ statoSincronizzato: {},
476
+ durateCpu: [],
477
+ cpuOltreCento: 0,
478
+ voceGuadagni: {}
479
+ };
480
+ await this.chiama(this.definizione.onCreate, this.room);
481
+ await this.applicaAzioni();
482
+ this.inviaGuadagniCambiati();
483
+ if (this.dati.status !== "ended") {
484
+ const stato = analizzaJson(this.dati.state);
485
+ if (!stato.ok || stato.bytes > LIMITE_STATO) {
486
+ await this.terminaPerStato(stato.ok ? "state_too_large" : "state_invalid");
487
+ } else {
488
+ this.dati.state = stato.valore;
489
+ this.dati.statoSincronizzato = copiaJson(stato.valore);
490
+ this.ultimoStatoOsservato = stato.testo;
491
+ }
492
+ }
493
+ await this.persistiEProgramma();
494
+ return true;
495
+ }
496
+ info(playerId) {
497
+ if (this.dati === null) return null;
498
+ return {
499
+ roomId: this.dati.id,
500
+ status: this.dati.status,
501
+ players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
502
+ (player) => player.connected || player.graziaFinoA !== null
503
+ ).length,
504
+ max: this.manifest.players.max,
505
+ mode: this.dati.mode,
506
+ member: playerId === void 0 ? false : this.dati.giocatori.some((player) => player.id === playerId)
507
+ };
508
+ }
509
+ giocatoreConnesso(connessione) {
510
+ const player = this.dati?.giocatori.find(
511
+ (item) => item.connected && item.connessione === connessione
512
+ );
513
+ return player === void 0 ? null : copiaGiocatore(player);
514
+ }
515
+ puoEntrare(identity) {
516
+ if (this.dati === null) return { ok: false, code: "room_not_found" };
517
+ if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
518
+ const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
519
+ if (esistente !== void 0) return { ok: true };
520
+ if (this.manifest.lobby && this.dati.status !== "lobby") {
521
+ return { ok: false, code: "room_playing" };
522
+ }
523
+ if (this.dati.giocatori.length >= this.manifest.players.max) {
524
+ return { ok: false, code: "room_full" };
525
+ }
526
+ return { ok: true };
527
+ }
528
+ async entra(identity, connessione) {
529
+ await this.terminaSeInattiva();
530
+ const permesso = this.puoEntrare(identity);
531
+ if (!permesso.ok) {
532
+ this.adattatore.chiudi(connessione, codiceIngresso(permesso.code), permesso.code);
533
+ return permesso;
534
+ }
535
+ const dati = this.richiediDati();
536
+ const ora = this.adattatore.ora();
537
+ let player = dati.giocatori.find((item) => item.id === identity.id);
538
+ const nuovo = player === void 0;
539
+ if (player === void 0) {
540
+ player = {
541
+ ...identity,
542
+ role: this.ruoloAutomatico(),
543
+ team: this.squadraAutomatica(),
544
+ ready: false,
545
+ connected: true,
546
+ entratoAt: ora,
547
+ graziaFinoA: null,
548
+ connessione,
549
+ seq: 0
550
+ };
551
+ dati.giocatori.push(player);
552
+ } else {
553
+ if (player.connected && player.connessione !== null && player.connessione !== connessione) {
554
+ this.adattatore.chiudi(player.connessione, 4006, "replaced");
555
+ }
556
+ player.name = identity.name;
557
+ player.guest = identity.guest;
558
+ player.connected = true;
559
+ player.graziaFinoA = null;
560
+ player.connessione = connessione;
561
+ player.seq = 0;
562
+ }
563
+ dati.hostId ??= player.id;
564
+ dati.vuotaDa = null;
565
+ dati.ultimoInputAt = ora;
566
+ const primaConnessione = !this.manifest.lobby && dati.status === "lobby";
567
+ if (primaConnessione) dati.status = "playing";
568
+ if (nuovo) {
569
+ await this.chiama(
570
+ this.definizione.onJoin,
571
+ this.room,
572
+ copiaGiocatore(player)
573
+ );
574
+ }
575
+ if (primaConnessione) {
576
+ await this.chiama(this.definizione.onStart, this.room);
577
+ this.inviaStatus(ora);
578
+ }
579
+ await this.concludiEvento();
580
+ if (dati.status !== "ended") {
581
+ this.inviaWelcome(player);
582
+ this.inviaSnapshotTutti();
583
+ this.inviaGiocatori();
584
+ }
585
+ await this.persistiEProgramma();
586
+ return { ok: true };
587
+ }
588
+ async disconnetti(connessione) {
589
+ if (this.dati === null || this.dati.status === "ended") return;
590
+ const player = this.dati.giocatori.find(
591
+ (item) => item.connected && item.connessione === connessione
592
+ );
593
+ if (player === void 0) return;
594
+ player.connected = false;
595
+ player.connessione = null;
596
+ player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
597
+ if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
598
+ this.frequenza.delete(connessione);
599
+ if (this.dati.hostId === player.id) this.assegnaHost();
600
+ this.verificaCountdown();
601
+ this.inviaGiocatori();
602
+ await this.persistiEProgramma();
603
+ }
604
+ async ricevi(connessione, frame) {
605
+ if (this.dati === null || this.dati.status === "ended") return;
606
+ if (await this.terminaSeInattiva()) return;
607
+ const player = this.dati.giocatori.find(
608
+ (item) => item.connected && item.connessione === connessione
609
+ );
610
+ if (player === void 0) return;
611
+ if (new TextEncoder().encode(frame).byteLength > LIMITE_FRAME) {
612
+ await this.chiudiConnessione(player, 4009, "bad_message");
613
+ return;
614
+ }
615
+ const ora = this.adattatore.ora();
616
+ const recenti = (this.frequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
617
+ if (recenti.length >= 20) {
618
+ await this.chiudiConnessione(player, 4008, "rate_limited");
619
+ return;
620
+ }
621
+ recenti.push(ora);
622
+ this.frequenza.set(connessione, recenti);
623
+ let message = null;
624
+ try {
625
+ message = record(JSON.parse(frame));
626
+ } catch {
627
+ }
628
+ if (message === null || typeof message.t !== "string") {
629
+ await this.chiudiConnessione(player, 4009, "bad_message");
630
+ return;
631
+ }
632
+ if (message.t === "ping") {
633
+ if (typeof message.c !== "number" || !Number.isFinite(message.c)) {
634
+ await this.chiudiConnessione(player, 4009, "bad_message");
635
+ return;
636
+ }
637
+ this.adattatore.invia(connessione, { t: "pong", c: message.c, s: ora });
638
+ return;
639
+ }
640
+ if (message.t === "resync") {
641
+ this.inviaSnapshotTutti();
642
+ await this.persistiEProgramma();
643
+ return;
644
+ }
645
+ if (message.t === "leave") {
646
+ this.dati.ultimoInputAt = ora;
647
+ await this.rimuoviGiocatore(player, "left");
648
+ this.adattatore.chiudi(connessione, 1e3, "left");
649
+ await this.concludiEvento();
650
+ this.inviaGiocatori();
651
+ await this.persistiEProgramma();
652
+ return;
653
+ }
654
+ if (message.t === "ready") {
655
+ if (typeof message.ready !== "boolean") return this.messaggioErrato(player);
656
+ if (!this.inLobby(player)) return;
657
+ this.dati.ultimoInputAt = ora;
658
+ player.ready = message.ready;
659
+ this.inviaGiocatori();
660
+ await this.persistiEProgramma();
661
+ return;
662
+ }
663
+ if (message.t === "role") {
664
+ if (typeof message.role !== "string") return this.messaggioErrato(player);
665
+ if (!this.inLobby(player)) return;
666
+ this.dati.ultimoInputAt = ora;
667
+ const errore = this.cambiaRuolo(player, message.role);
668
+ if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
669
+ await this.persistiEProgramma();
670
+ return;
671
+ }
672
+ if (message.t === "team") {
673
+ if (!Number.isInteger(message.team)) return this.messaggioErrato(player);
674
+ if (!this.inLobby(player)) return;
675
+ this.dati.ultimoInputAt = ora;
676
+ const errore = this.cambiaSquadra(player, message.team);
677
+ if (errore !== null) this.inviaErrore(player, errore.code, errore.message);
678
+ await this.persistiEProgramma();
679
+ return;
680
+ }
681
+ if (message.t === "start") {
682
+ if (!this.inLobby(player)) return;
683
+ this.dati.ultimoInputAt = ora;
684
+ await this.avviaCountdown(player);
685
+ return;
686
+ }
687
+ if (message.t === "msg") {
688
+ if (!Number.isSafeInteger(message.seq) || message.seq < 1) {
689
+ await this.messaggioErrato(player);
690
+ return;
691
+ }
692
+ const seq = message.seq;
693
+ if (seq <= player.seq) return;
694
+ const contenuto = analizzaJson(message.m);
695
+ if (!contenuto.ok) {
696
+ await this.messaggioErrato(player);
697
+ return;
698
+ }
699
+ player.seq = seq;
700
+ if (player.role === "spectator") {
701
+ this.inviaErrore(player, "spectator", "Spectators cannot send game input.");
702
+ await this.persistiEProgramma();
703
+ return;
704
+ }
705
+ this.dati.ultimoInputAt = ora;
706
+ await this.chiama(
707
+ this.definizione.onMessage,
708
+ this.room,
709
+ copiaGiocatore(player),
710
+ contenuto.valore
711
+ );
712
+ await this.concludiEvento();
713
+ await this.persistiEProgramma();
714
+ return;
715
+ }
716
+ await this.messaggioErrato(player);
717
+ }
718
+ async eseguiTick() {
719
+ if (this.dati === null || this.dati.status !== "playing" || this.dati.tickRate === 0) return;
720
+ if (await this.terminaSeInattiva()) return;
721
+ if (!this.serveTick()) {
722
+ await this.persistiEProgramma();
723
+ return;
724
+ }
725
+ const dati = this.dati;
726
+ dati.tick++;
727
+ const inizio = this.adattatore.misuraCpu();
728
+ await this.chiama(
729
+ this.definizione.onTick,
730
+ this.room,
731
+ 1 / dati.tickRate
732
+ );
733
+ const durata = Math.max(0, this.adattatore.misuraCpu() - inizio);
734
+ this.registraCpu(durata);
735
+ await this.applicaAzioni();
736
+ if (dati.status === "ended") return;
737
+ this.inviaGuadagniCambiati();
738
+ const stato = await this.verificaStato();
739
+ if (stato === null || this.stanzaTerminata()) return;
740
+ const cambiato = stato.testo !== JSON.stringify(dati.statoSincronizzato);
741
+ if (dati.tick % 100 === 0) {
742
+ dati.state = stato.valore;
743
+ this.inviaSnapshotTutti();
744
+ } else if (cambiato) {
745
+ const base = dati.tickSincronizzato;
746
+ this.broadcast({
747
+ t: "state",
748
+ tick: dati.tick,
749
+ serverTime: this.adattatore.ora(),
750
+ base,
751
+ patch: creaDiff(dati.statoSincronizzato, stato.valore)
752
+ });
753
+ dati.state = stato.valore;
754
+ dati.statoSincronizzato = copiaJson(stato.valore);
755
+ dati.tickSincronizzato = dati.tick;
756
+ }
757
+ if (dati.tick % 100 === 0 || this.voceDaPersistire) await this.persisti();
758
+ await this.aggiornaProgrammazione();
759
+ }
760
+ async sveglia() {
761
+ if (this.dati === null || this.dati.status === "ended") return;
762
+ if (await this.terminaSeInattiva()) return;
763
+ const ora = this.adattatore.ora();
764
+ const scaduti = this.dati.giocatori.filter(
765
+ (player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
766
+ );
767
+ for (const player of scaduti) {
768
+ if (this.manifest.persistent === true) player.graziaFinoA = null;
769
+ else await this.rimuoviGiocatore(player, "timeout");
770
+ }
771
+ if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
772
+ const errore = this.erroreMinimi();
773
+ if (errore !== null) {
774
+ this.dati.status = "lobby";
775
+ this.dati.countdownAt = null;
776
+ this.broadcast({ t: "error", code: errore.code, message: errore.message });
777
+ this.inviaStatus(ora);
778
+ } else {
779
+ this.dati.status = "playing";
780
+ this.dati.ultimoInputAt = ora;
781
+ this.dati.countdownAt = null;
782
+ await this.chiama(this.definizione.onStart, this.room);
783
+ this.inviaStatus(ora);
784
+ }
785
+ }
786
+ const dovuti = this.dati.timer.filter((timer) => timer.at <= ora).sort((a, b) => a.at - b.at || a.id - b.id);
787
+ if (dovuti.length > 0) {
788
+ const ids = new Set(dovuti.map((timer) => timer.id));
789
+ this.dati.timer = this.dati.timer.filter((timer) => !ids.has(timer.id));
790
+ for (const timer of dovuti) await this.eseguiTimer(timer);
791
+ }
792
+ await this.concludiEvento();
793
+ if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
794
+ this.dati.cancellaDopoFlush = true;
795
+ await this.terminaInterna(null);
796
+ }
797
+ if (scaduti.length > 0) this.inviaGiocatori();
798
+ await this.concludiEvento();
799
+ await this.persistiEProgramma();
800
+ }
801
+ async flush() {
802
+ const dati = this.richiediDati();
803
+ const esito = {
804
+ scores: dati.punteggi.map((score) => ({ ...score })),
805
+ ended: dati.fineInCoda === null ? null : { result: dati.fineInCoda.result, at: dati.fineInCoda.at }
806
+ };
807
+ dati.punteggi = [];
808
+ dati.fineInCoda = null;
809
+ if (dati.cancellaDopoFlush && dati.status === "ended") {
810
+ const chiavi = await this.adattatore.storage.list();
811
+ for (const key of chiavi.keys()) await this.adattatore.storage.delete(key);
812
+ this.dati = null;
813
+ this.adattatore.programmaTick(null);
814
+ await this.adattatore.programmaSveglia(null);
815
+ } else {
816
+ await this.persistiEProgramma();
817
+ }
818
+ return esito;
819
+ }
820
+ async riconciliaConnessioni() {
821
+ const dati = this.richiediDati();
822
+ const attive = new Set(this.adattatore.connessioniAttive());
823
+ const ora = this.adattatore.ora();
824
+ let cambiato = false;
825
+ for (const player of dati.giocatori) {
826
+ if (player.connected && (player.connessione === null || !attive.has(player.connessione))) {
827
+ player.connected = false;
828
+ player.connessione = null;
829
+ player.graziaFinoA = ora + GRAZIA_MS;
830
+ if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
831
+ cambiato = true;
832
+ }
833
+ }
834
+ if (cambiato) {
835
+ this.assegnaHost();
836
+ await this.persisti();
837
+ }
838
+ }
839
+ ruoloAutomatico() {
840
+ if (this.manifest.roles.length === 0) return null;
841
+ const dati = this.richiediDati();
842
+ const candidati = this.manifest.roles.filter((role) => {
843
+ const count = dati.giocatori.filter((player) => player.role === role.id).length;
844
+ return role.max === void 0 || count < role.max;
845
+ });
846
+ candidati.sort((a, b) => {
847
+ const countA = dati.giocatori.filter((player) => player.role === a.id).length;
848
+ const countB = dati.giocatori.filter((player) => player.role === b.id).length;
849
+ const mancaA = countA < a.min ? 0 : 1;
850
+ const mancaB = countB < b.min ? 0 : 1;
851
+ return mancaA - mancaB || countA - countB;
852
+ });
853
+ return candidati[0]?.id ?? "spectator";
854
+ }
855
+ squadraAutomatica() {
856
+ if (this.manifest.teams === null) return null;
857
+ const dati = this.richiediDati();
858
+ let scelta = 1;
859
+ let minimo = Number.POSITIVE_INFINITY;
860
+ for (let team = 1; team <= this.manifest.teams.min; team++) {
861
+ const count = dati.giocatori.filter((player) => player.team === team).length;
862
+ if (count < minimo) {
863
+ minimo = count;
864
+ scelta = team;
865
+ }
866
+ }
867
+ return scelta;
868
+ }
869
+ inLobby(player) {
870
+ if (this.richiediDati().status === "lobby") return true;
871
+ this.inviaErrore(player, "not_in_lobby", "This action is only available in the lobby.");
872
+ return false;
873
+ }
874
+ cambiaRuolo(player, roleId) {
875
+ const ruolo = this.manifest.roles.find((item) => item.id === roleId);
876
+ if (ruolo === void 0 && roleId !== "spectator") {
877
+ return { code: "invalid_role", message: "This role does not exist." };
878
+ }
879
+ const occupati = this.richiediDati().giocatori.filter(
880
+ (item) => item.id !== player.id && item.role === roleId
881
+ ).length;
882
+ if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
883
+ return { code: "role_full", message: "This role is full." };
884
+ }
885
+ player.role = roleId;
886
+ if (roleId === "spectator") player.team = null;
887
+ else if (player.team === null) player.team = this.squadraAutomatica();
888
+ if (this.richiediDati().status === "lobby") player.ready = false;
889
+ this.inviaGiocatori();
890
+ return null;
891
+ }
892
+ cambiaSquadra(player, team) {
893
+ if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
894
+ return { code: "invalid_team", message: "This team does not exist." };
895
+ }
896
+ if (player.role === "spectator") {
897
+ return { code: "spectator", message: "Spectators cannot join a team." };
898
+ }
899
+ player.team = team;
900
+ if (this.richiediDati().status === "lobby") player.ready = false;
901
+ this.inviaGiocatori();
902
+ return null;
903
+ }
904
+ impostaRuoloDalServer(playerId, roleId) {
905
+ const player = this.giocatorePerModificaDalServer(playerId);
906
+ const errore = this.cambiaRuolo(player, roleId);
907
+ if (errore !== null) throw erroreConCodice(errore.code, errore.message);
908
+ }
909
+ impostaSquadraDalServer(playerId, team) {
910
+ const player = this.giocatorePerModificaDalServer(playerId);
911
+ const errore = this.cambiaSquadra(player, team);
912
+ if (errore !== null) throw erroreConCodice(errore.code, errore.message);
913
+ }
914
+ giocatorePerModificaDalServer(playerId) {
915
+ const dati = this.richiediDati();
916
+ if (dati.status === "ended") throw new Error("The room has ended.");
917
+ const player = dati.giocatori.find((item) => item.id === playerId);
918
+ if (player === void 0) throw erroreConCodice("player_not_found", "Player not found.");
919
+ return player;
920
+ }
921
+ erroreMinimi() {
922
+ const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
923
+ const attivi = connessi.filter((player) => player.role !== "spectator");
924
+ if (attivi.length < this.manifest.players.min) {
925
+ return { code: "not_enough_players", message: "The room does not have enough players." };
926
+ }
927
+ if (connessi.some((player) => !player.ready)) {
928
+ return { code: "players_not_ready", message: "Every connected player must be ready." };
929
+ }
930
+ for (const role of this.manifest.roles) {
931
+ if (attivi.filter((player) => player.role === role.id).length < role.min) {
932
+ return { code: "role_minimum", message: `Role ${role.id} does not meet its minimum.` };
933
+ }
934
+ }
935
+ if (this.manifest.teams !== null) {
936
+ const squadre = new Set(attivi.map((player) => player.team).filter((team) => team !== null));
937
+ if (attivi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
938
+ return { code: "team_minimum", message: "The room does not have enough teams." };
939
+ }
940
+ }
941
+ return null;
942
+ }
943
+ async avviaCountdown(player) {
944
+ const dati = this.richiediDati();
945
+ if (dati.hostId !== player.id) {
946
+ this.inviaErrore(player, "not_host", "Only the host can start the game.");
947
+ return;
948
+ }
949
+ const errore = this.erroreMinimi();
950
+ if (errore !== null) {
951
+ this.inviaErrore(player, errore.code, errore.message);
952
+ return;
953
+ }
954
+ dati.status = "countdown";
955
+ dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
956
+ this.inviaStatus(dati.countdownAt);
957
+ await this.persistiEProgramma();
958
+ }
959
+ verificaCountdown() {
960
+ const dati = this.richiediDati();
961
+ if (dati.status !== "countdown" || this.erroreMinimi() === null) return;
962
+ dati.status = "lobby";
963
+ dati.countdownAt = null;
964
+ this.inviaStatus(this.adattatore.ora());
965
+ }
966
+ async messaggioErrato(player) {
967
+ await this.chiudiConnessione(player, 4009, "bad_message");
968
+ }
969
+ async chiudiConnessione(player, codice, motivo) {
970
+ const connessione = player.connessione;
971
+ if (connessione !== null) this.adattatore.chiudi(connessione, codice, motivo);
972
+ await this.disconnetti(connessione ?? "");
973
+ }
974
+ async rimuoviGiocatore(player, reason) {
975
+ const dati = this.richiediDati();
976
+ const indice = dati.giocatori.findIndex((item) => item.id === player.id);
977
+ if (indice < 0) return;
978
+ dati.giocatori.splice(indice, 1);
979
+ this.pulisciGuadagni(player.id);
980
+ if (dati.hostId === player.id) this.assegnaHost();
981
+ if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
982
+ await this.chiama(
983
+ this.definizione.onLeave,
984
+ this.room,
985
+ copiaGiocatore({ ...player, connected: false, connessione: null }),
986
+ reason
987
+ );
988
+ this.verificaCountdown();
989
+ }
990
+ assegnaHost() {
991
+ const dati = this.richiediDati();
992
+ const host = dati.giocatori.filter((player) => player.connected).sort((a, b) => a.entratoAt - b.entratoAt)[0];
993
+ dati.hostId = host?.id ?? null;
994
+ }
995
+ async eseguiTimer(timer) {
996
+ const value = this.definizione[timer.handler];
997
+ await this.chiama(
998
+ typeof value === "function" ? value : void 0,
999
+ this.room,
1000
+ timer.payload
1001
+ );
1002
+ }
1003
+ pianifica(milliseconds, handler, payload) {
1004
+ if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) {
1005
+ throw new TypeError("Schedule delay must be a non-negative integer.");
1006
+ }
1007
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(handler)) {
1008
+ throw new TypeError("Schedule handler must be a method name.");
1009
+ }
1010
+ const callback = this.definizione[handler];
1011
+ if (typeof callback !== "function") {
1012
+ throw new TypeError(`Schedule handler ${handler} is not defined.`);
1013
+ }
1014
+ const json = analizzaJson(payload);
1015
+ if (!json.ok) throw new TypeError("Schedule payload must be valid JSON.");
1016
+ const dati = this.richiediDati();
1017
+ dati.timer.push({
1018
+ id: dati.prossimoTimerId++,
1019
+ at: this.adattatore.ora() + milliseconds,
1020
+ handler,
1021
+ payload: json.valore
1022
+ });
1023
+ }
1024
+ accodaPunteggio(playerId, board, score, daily) {
1025
+ if (!this.richiediDati().giocatori.some((player) => player.id === playerId)) {
1026
+ throw new Error("Player not found.");
1027
+ }
1028
+ if (!CHIAVE.test(board)) {
1029
+ throw new TypeError("Board names must use lowercase letters, numbers, underscores, or hyphens.");
1030
+ }
1031
+ if (!Number.isSafeInteger(score) || score < 0) {
1032
+ throw new TypeError("Score must be a non-negative safe integer.");
1033
+ }
1034
+ this.richiediDati().punteggi.push({ playerId, board, score, daily });
1035
+ this.broadcast({ t: "flush" });
1036
+ }
1037
+ richiediFine(result) {
1038
+ const json = analizzaJson(result);
1039
+ if (!json.ok) throw new TypeError("Game result must be valid JSON.");
1040
+ this.fineRichiesta = json.valore;
1041
+ }
1042
+ async salva(key, value) {
1043
+ if (!CHIAVE.test(key)) {
1044
+ throw new TypeError("Save keys must use lowercase letters, numbers, underscores, or hyphens.");
1045
+ }
1046
+ const json = analizzaJson(value);
1047
+ if (!json.ok) throw new TypeError("Saved values must be valid JSON.");
1048
+ if (json.bytes > LIMITE_SAVE) {
1049
+ throw new RangeError("Saved values must be at most 131072 bytes.");
1050
+ }
1051
+ await this.adattatore.storage.put(PREFISSO_SAVE + key, json.valore);
1052
+ }
1053
+ async caricaSave(key) {
1054
+ if (!CHIAVE.test(key)) {
1055
+ throw new TypeError("Save keys must use lowercase letters, numbers, underscores, or hyphens.");
1056
+ }
1057
+ const value = await this.adattatore.storage.get(PREFISSO_SAVE + key);
1058
+ if (value === void 0) return null;
1059
+ const json = analizzaJson(value);
1060
+ if (!json.ok) throw new Error("The saved value is invalid.");
1061
+ return json.valore;
1062
+ }
1063
+ verificaChiaveDeposito(key) {
1064
+ if (typeof key !== "string" || !CHIAVE.test(key)) {
1065
+ throw erroreConCodice(
1066
+ "store_invalid_key",
1067
+ "Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
1068
+ );
1069
+ }
1070
+ }
1071
+ verificaPrefissoDeposito(prefix) {
1072
+ if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
1073
+ throw erroreConCodice(
1074
+ "store_invalid_key",
1075
+ "Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
1076
+ );
1077
+ }
1078
+ }
1079
+ contaOperazioneDeposito() {
1080
+ const ora = this.adattatore.ora();
1081
+ this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
1082
+ if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
1083
+ throw erroreConCodice(
1084
+ "store_rate_limited",
1085
+ "The shared store allows at most 120 operations per minute for each room."
1086
+ );
1087
+ }
1088
+ this.frequenzaDeposito.push(ora);
1089
+ }
1090
+ async usaDeposito(operazione) {
1091
+ this.contaOperazioneDeposito();
1092
+ const deposito = this.adattatore.deposito;
1093
+ if (deposito === null) {
1094
+ throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1095
+ }
1096
+ try {
1097
+ return await operazione(deposito);
1098
+ } catch (cause) {
1099
+ const code = cause instanceof Error ? cause.code : void 0;
1100
+ if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
1101
+ throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1102
+ }
1103
+ }
1104
+ async leggiDeposito(key) {
1105
+ this.verificaChiaveDeposito(key);
1106
+ const value = await this.usaDeposito((deposito) => deposito.get(key));
1107
+ if (value === null) return null;
1108
+ try {
1109
+ return JSON.parse(JSON.stringify(value));
1110
+ } catch {
1111
+ throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
1112
+ }
1113
+ }
1114
+ async scriviDeposito(key, value) {
1115
+ this.verificaChiaveDeposito(key);
1116
+ const json = analizzaJson(value);
1117
+ if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
1118
+ throw erroreConCodice(
1119
+ "store_too_large",
1120
+ "Shared store values must be valid JSON of at most 65536 bytes."
1121
+ );
1122
+ }
1123
+ await this.usaDeposito((deposito) => deposito.set(key, json.valore));
1124
+ }
1125
+ async eliminaDeposito(key) {
1126
+ this.verificaChiaveDeposito(key);
1127
+ await this.usaDeposito((deposito) => deposito.delete(key));
1128
+ }
1129
+ async elencaDeposito(prefix) {
1130
+ this.verificaPrefissoDeposito(prefix);
1131
+ const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
1132
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
1133
+ throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
1134
+ }
1135
+ return [...keys].sort().slice(0, 1024);
1136
+ }
1137
+ async incrementaDeposito(key, amount) {
1138
+ this.verificaChiaveDeposito(key);
1139
+ if (!Number.isSafeInteger(amount)) {
1140
+ throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
1141
+ }
1142
+ const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
1143
+ if (!Number.isSafeInteger(value)) {
1144
+ throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
1145
+ }
1146
+ return value;
1147
+ }
1148
+ broadcastCreatore(message) {
1149
+ const json = analizzaJson(message);
1150
+ if (!json.ok) throw new TypeError("Messages must be valid JSON.");
1151
+ this.broadcast({ t: "msg", m: json.valore });
1152
+ }
1153
+ inviaCreatore(playerId, message) {
1154
+ const json = analizzaJson(message);
1155
+ if (!json.ok) throw new TypeError("Messages must be valid JSON.");
1156
+ const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
1157
+ if (player === void 0) throw new Error("Player not found.");
1158
+ if (player.connected && player.connessione !== null) {
1159
+ this.adattatore.invia(player.connessione, { t: "msg", m: json.valore });
1160
+ }
1161
+ }
1162
+ broadcast(message) {
1163
+ for (const player of this.richiediDati().giocatori) {
1164
+ if (player.connected && player.connessione !== null) {
1165
+ this.adattatore.invia(player.connessione, message);
1166
+ }
1167
+ }
1168
+ }
1169
+ inviaErrore(player, code, message) {
1170
+ if (player.connected && player.connessione !== null) {
1171
+ this.adattatore.invia(player.connessione, { t: "error", code, message });
1172
+ }
1173
+ }
1174
+ giocatoriProtocollo() {
1175
+ return this.richiediDati().giocatori.map((player) => ({
1176
+ id: player.id,
1177
+ name: player.name,
1178
+ guest: player.guest,
1179
+ role: player.role,
1180
+ team: player.team,
1181
+ ready: player.ready,
1182
+ connected: player.connected
1183
+ }));
1184
+ }
1185
+ inviaWelcome(player) {
1186
+ if (!player.connected || player.connessione === null) return;
1187
+ const dati = this.richiediDati();
1188
+ this.adattatore.invia(player.connessione, {
1189
+ t: "welcome",
1190
+ you: player.id,
1191
+ room: {
1192
+ id: dati.id,
1193
+ seed: seedStanza(dati.id),
1194
+ status: dati.status,
1195
+ mode: dati.mode,
1196
+ tick: dati.tick,
1197
+ tickRate: dati.tickRate,
1198
+ serverTime: this.adattatore.ora(),
1199
+ host: dati.hostId
1200
+ },
1201
+ players: this.giocatoriProtocollo(),
1202
+ state: dati.state
1203
+ });
1204
+ const gains = dati.voceGuadagni?.[player.id];
1205
+ if (gains !== void 0 && Object.keys(gains).length > 0) {
1206
+ this.adattatore.invia(player.connessione, { t: "voice", op: "gain", gains: { ...gains } });
1207
+ }
1208
+ }
1209
+ inviaGiocatori() {
1210
+ this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
1211
+ }
1212
+ inviaStatus(at) {
1213
+ const dati = this.richiediDati();
1214
+ this.broadcast({
1215
+ t: "status",
1216
+ status: dati.status,
1217
+ at,
1218
+ result: dati.status === "ended" ? dati.result : null
1219
+ });
1220
+ }
1221
+ inviaSnapshotTutti() {
1222
+ const dati = this.richiediDati();
1223
+ const stato = analizzaJson(dati.state);
1224
+ if (!stato.ok || stato.bytes > LIMITE_STATO) return;
1225
+ dati.state = stato.valore;
1226
+ dati.statoSincronizzato = copiaJson(stato.valore);
1227
+ dati.tickSincronizzato = dati.tick;
1228
+ this.broadcast({
1229
+ t: "snapshot",
1230
+ tick: dati.tick,
1231
+ serverTime: this.adattatore.ora(),
1232
+ state: stato.valore
1233
+ });
1234
+ }
1235
+ async chiama(callback, ...args) {
1236
+ if (callback === void 0 || this.dati?.status === "ended") return;
1237
+ try {
1238
+ await callback(...args);
1239
+ } catch {
1240
+ this.fineRichiesta = { error: "callback_error" };
1241
+ }
1242
+ }
1243
+ async applicaAzioni() {
1244
+ if (this.applicandoAzioni || this.dati === null) return;
1245
+ this.applicandoAzioni = true;
1246
+ try {
1247
+ while (this.kickRichiesti.size > 0 && this.dati.status !== "ended") {
1248
+ const playerId = this.kickRichiesti.values().next().value;
1249
+ if (playerId === void 0) break;
1250
+ this.kickRichiesti.delete(playerId);
1251
+ const player = this.dati.giocatori.find((item) => item.id === playerId);
1252
+ if (player === void 0) continue;
1253
+ if (player.connessione !== null) this.adattatore.chiudi(player.connessione, 4003, "kicked");
1254
+ await this.rimuoviGiocatore(player, "kicked");
1255
+ }
1256
+ if (this.fineRichiesta !== null && this.dati.status !== "ended") {
1257
+ const result = this.fineRichiesta;
1258
+ this.fineRichiesta = null;
1259
+ await this.terminaInterna(result);
1260
+ }
1261
+ } finally {
1262
+ this.applicandoAzioni = false;
1263
+ }
1264
+ }
1265
+ async concludiEvento() {
1266
+ await this.applicaAzioni();
1267
+ if (this.dati === null || this.dati.status === "ended") return;
1268
+ this.inviaGuadagniCambiati();
1269
+ const stato = await this.verificaStato();
1270
+ if (stato === null || this.stanzaTerminata()) return;
1271
+ const precedente = JSON.stringify(this.dati.statoSincronizzato);
1272
+ this.dati.state = stato.valore;
1273
+ if ((this.dati.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
1274
+ this.dati.tick++;
1275
+ this.inviaSnapshotTutti();
1276
+ }
1277
+ }
1278
+ async verificaStato() {
1279
+ const stato = analizzaJson(this.richiediDati().state);
1280
+ if (!stato.ok) {
1281
+ await this.terminaPerStato("state_invalid");
1282
+ return null;
1283
+ }
1284
+ if (stato.bytes > LIMITE_STATO) {
1285
+ await this.terminaPerStato("state_too_large");
1286
+ return null;
1287
+ }
1288
+ if (stato.testo !== this.ultimoStatoOsservato) {
1289
+ this.richiediDati().ultimoCambioStatoAt = this.adattatore.ora();
1290
+ this.ultimoStatoOsservato = stato.testo;
1291
+ }
1292
+ return stato;
1293
+ }
1294
+ impostaGuadagno(listener, speaker, gain) {
1295
+ if ((this.manifest.voice ?? "none") === "none") return;
1296
+ const dati = this.richiediDati();
1297
+ if (!dati.giocatori.some((player) => player.id === listener) || !dati.giocatori.some((player) => player.id === speaker)) throw new Error("Player not found.");
1298
+ if (Number.isNaN(gain)) throw new TypeError("Voice gain must be a number.");
1299
+ if (listener === speaker) return;
1300
+ const valore = Math.round(Math.min(1, Math.max(0, gain)) * 100) / 100;
1301
+ dati.voceGuadagni ??= {};
1302
+ this.salvaGuadagno(listener, speaker, valore);
1303
+ }
1304
+ salvaGuadagno(playerId, altroId, valore) {
1305
+ const dati = this.richiediDati();
1306
+ dati.voceGuadagni ??= {};
1307
+ const precedente = dati.voceGuadagni[playerId]?.[altroId] ?? 1;
1308
+ if (precedente === valore) return;
1309
+ this.voceDaPersistire = true;
1310
+ if (valore === 1) {
1311
+ const riga = dati.voceGuadagni[playerId];
1312
+ if (riga !== void 0) {
1313
+ delete riga[altroId];
1314
+ if (Object.keys(riga).length === 0) delete dati.voceGuadagni[playerId];
1315
+ }
1316
+ } else {
1317
+ (dati.voceGuadagni[playerId] ??= {})[altroId] = valore;
1318
+ }
1319
+ (this.voceGuadagniCambiati.get(playerId) ?? this.creaCambiVoce(playerId))[altroId] = valore;
1320
+ }
1321
+ creaCambiVoce(playerId) {
1322
+ const cambi = {};
1323
+ this.voceGuadagniCambiati.set(playerId, cambi);
1324
+ return cambi;
1325
+ }
1326
+ inviaGuadagniCambiati() {
1327
+ if (this.dati === null || this.voceGuadagniCambiati.size === 0) return;
1328
+ for (const [playerId, gains] of this.voceGuadagniCambiati) {
1329
+ const player = this.dati.giocatori.find((item) => item.id === playerId);
1330
+ if (player?.connected && player.connessione !== null) {
1331
+ this.adattatore.invia(player.connessione, { t: "voice", op: "gain", gains: { ...gains } });
1332
+ }
1333
+ }
1334
+ this.voceGuadagniCambiati.clear();
1335
+ }
1336
+ pulisciGuadagni(playerId) {
1337
+ const guadagni = this.richiediDati().voceGuadagni;
1338
+ if (guadagni === void 0) return;
1339
+ let cambiato = Object.hasOwn(guadagni, playerId);
1340
+ delete guadagni[playerId];
1341
+ this.voceGuadagniCambiati.delete(playerId);
1342
+ for (const [altroId, riga] of Object.entries(guadagni)) {
1343
+ cambiato = Object.hasOwn(riga, playerId) || cambiato;
1344
+ delete riga[playerId];
1345
+ if (Object.keys(riga).length === 0) delete guadagni[altroId];
1346
+ }
1347
+ if (cambiato) this.voceDaPersistire = true;
1348
+ }
1349
+ async terminaPerStato(code) {
1350
+ const dati = this.richiediDati();
1351
+ dati.state = dati.statoSincronizzato;
1352
+ await this.terminaInterna({ error: code });
1353
+ }
1354
+ async terminaInterna(result) {
1355
+ const dati = this.richiediDati();
1356
+ if (dati.status === "ended") return;
1357
+ dati.status = "ended";
1358
+ dati.countdownAt = null;
1359
+ dati.result = result;
1360
+ dati.resultAt = this.adattatore.ora();
1361
+ try {
1362
+ await this.definizione.onEnd?.(this.room);
1363
+ } catch {
1364
+ if (record(result)?.error === void 0) dati.result = { error: "callback_error" };
1365
+ }
1366
+ const stato = analizzaJson(dati.state);
1367
+ if (!stato.ok || stato.bytes > LIMITE_STATO) {
1368
+ dati.state = dati.statoSincronizzato;
1369
+ dati.result = { error: stato.ok ? "state_too_large" : "state_invalid" };
1370
+ } else if (stato.testo !== JSON.stringify(dati.statoSincronizzato)) {
1371
+ dati.tick++;
1372
+ dati.state = stato.valore;
1373
+ this.inviaSnapshotTutti();
1374
+ }
1375
+ const fine = { result: dati.result, at: dati.resultAt };
1376
+ dati.fineInCoda = fine;
1377
+ this.inviaStatus(dati.resultAt);
1378
+ this.broadcast({ t: "flush" });
1379
+ for (const player of dati.giocatori) {
1380
+ if (player.connected && player.connessione !== null) {
1381
+ this.adattatore.chiudi(player.connessione, 4004, "room_ended");
1382
+ player.connected = false;
1383
+ player.connessione = null;
1384
+ player.graziaFinoA = null;
1385
+ }
1386
+ }
1387
+ await this.persistiEProgramma();
1388
+ }
1389
+ registraCpu(durata) {
1390
+ const dati = this.richiediDati();
1391
+ dati.durateCpu.push(durata);
1392
+ if (dati.durateCpu.length > 50) dati.durateCpu.shift();
1393
+ dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
1394
+ if (dati.cpuOltreCento >= 20) {
1395
+ this.fineRichiesta = { error: "cpu_budget" };
1396
+ return;
1397
+ }
1398
+ if (dati.durateCpu.length === 50) {
1399
+ const media = dati.durateCpu.reduce((somma, value) => somma + value, 0) / 50;
1400
+ if (media > 20 && dati.tickRate > 5) {
1401
+ dati.tickRate = Math.max(5, Math.floor(dati.tickRate / 2));
1402
+ dati.durateCpu = [];
1403
+ this.broadcast({
1404
+ t: "error",
1405
+ code: "tick_rate_reduced",
1406
+ message: `Tick rate reduced to ${dati.tickRate} because the game exceeded its CPU budget.`
1407
+ });
1408
+ }
1409
+ }
1410
+ }
1411
+ async persisti() {
1412
+ if (this.dati !== null) {
1413
+ await this.adattatore.storage.put(CHIAVE_NUCLEO, this.dati);
1414
+ this.voceDaPersistire = false;
1415
+ }
1416
+ }
1417
+ async persistiEProgramma() {
1418
+ await this.persisti();
1419
+ await this.aggiornaProgrammazione();
1420
+ }
1421
+ serveTick() {
1422
+ const dati = this.dati;
1423
+ return dati !== null && dati.status === "playing" && dati.tickRate > 0 && dati.giocatori.some((player) => player.connected) && this.adattatore.ora() - Math.max(dati.ultimoInputAt, dati.ultimoCambioStatoAt) < RIPOSO_TICK_MS;
1424
+ }
1425
+ async terminaSeInattiva() {
1426
+ if (this.manifest.persistent === true) {
1427
+ if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
1428
+ await this.terminaInterna({ error: "expired" });
1429
+ return true;
1430
+ }
1431
+ if (this.dati?.status !== "playing" || this.adattatore.ora() < this.dati.ultimoInputAt + INATTIVITA_MS) return false;
1432
+ await this.terminaInterna({ error: "idle" });
1433
+ return true;
1434
+ }
1435
+ async aggiornaProgrammazione() {
1436
+ if (this.dati === null || this.dati.status === "ended") {
1437
+ this.adattatore.programmaTick(null);
1438
+ await this.adattatore.programmaSveglia(null);
1439
+ return;
1440
+ }
1441
+ this.adattatore.programmaTick(
1442
+ this.serveTick() ? 1e3 / this.dati.tickRate : null
1443
+ );
1444
+ const prossime = [];
1445
+ if (this.manifest.persistent === true) {
1446
+ prossime.push(
1447
+ Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
1448
+ );
1449
+ } else if (this.dati.status === "playing") {
1450
+ prossime.push(this.dati.ultimoInputAt + INATTIVITA_MS);
1451
+ }
1452
+ if (this.dati.countdownAt !== null) prossime.push(this.dati.countdownAt);
1453
+ for (const player of this.dati.giocatori) {
1454
+ if (!player.connected && player.graziaFinoA !== null) prossime.push(player.graziaFinoA);
1455
+ }
1456
+ for (const timer of this.dati.timer) prossime.push(timer.at);
1457
+ if (this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null) {
1458
+ prossime.push(this.dati.vuotaDa + STANZA_VUOTA_MS);
1459
+ }
1460
+ await this.adattatore.programmaSveglia(prossime.length === 0 ? null : Math.min(...prossime));
1461
+ }
1462
+ };
1463
+
1464
+ // src/node/websocket.ts
1465
+ import { createHash } from "node:crypto";
1466
+ import { EventEmitter } from "node:events";
1467
+ var GUID_WEBSOCKET = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1468
+ var MASSIMO_MESSAGGIO = 1e6;
1469
+ function contieneToken(value, token) {
1470
+ return value?.split(",").some((parte) => parte.trim().toLowerCase() === token) === true;
1471
+ }
1472
+ function chiaveValida(value) {
1473
+ if (value === void 0 || !/^[A-Za-z0-9+/]{22}==$/.test(value)) return false;
1474
+ return Buffer.from(value, "base64").byteLength === 16;
1475
+ }
1476
+ function creaFrame(opcode, payload) {
1477
+ const primo = Buffer.from([128 | opcode]);
1478
+ if (payload.byteLength < 126) {
1479
+ return Buffer.concat([primo, Buffer.from([payload.byteLength]), payload]);
1480
+ }
1481
+ if (payload.byteLength <= 65535) {
1482
+ const header2 = Buffer.allocUnsafe(3);
1483
+ header2[0] = 126;
1484
+ header2.writeUInt16BE(payload.byteLength, 1);
1485
+ return Buffer.concat([primo, header2, payload]);
1486
+ }
1487
+ const header = Buffer.allocUnsafe(9);
1488
+ header[0] = 127;
1489
+ header.writeBigUInt64BE(BigInt(payload.byteLength), 1);
1490
+ return Buffer.concat([primo, header, payload]);
1491
+ }
1492
+ function testoUtf8(payload) {
1493
+ try {
1494
+ return new TextDecoder("utf-8", { fatal: true }).decode(payload);
1495
+ } catch {
1496
+ return null;
1497
+ }
1498
+ }
1499
+ var NodeWebSocket = class extends EventEmitter {
1500
+ constructor(socket, head, massimoMessaggio = MASSIMO_MESSAGGIO) {
1501
+ super();
1502
+ this.socket = socket;
1503
+ this.massimoMessaggio = massimoMessaggio;
1504
+ this.buffer = Buffer.alloc(0);
1505
+ this.frammenti = [];
1506
+ this.byteFrammenti = 0;
1507
+ this.frammentando = false;
1508
+ this.chiusuraInviata = false;
1509
+ this.terminato = false;
1510
+ socket.on("data", (chunk) => this.aggiungi(chunk));
1511
+ socket.on("end", () => this.termina());
1512
+ socket.on("close", () => this.termina());
1513
+ socket.on("error", () => this.termina());
1514
+ if (head.byteLength > 0) queueMicrotask(() => this.aggiungi(head));
1515
+ }
1516
+ send(message) {
1517
+ if (this.chiusuraInviata || this.terminato) return;
1518
+ this.socket.write(creaFrame(1, Buffer.from(message, "utf8")));
1519
+ }
1520
+ close(code = 1e3, reason = "") {
1521
+ if (this.chiusuraInviata || this.terminato) return;
1522
+ const motivo = Buffer.from(reason, "utf8");
1523
+ if (motivo.byteLength > 123) throw new RangeError("WebSocket close reasons must be at most 123 bytes.");
1524
+ const payload = Buffer.allocUnsafe(2 + motivo.byteLength);
1525
+ payload.writeUInt16BE(code, 0);
1526
+ motivo.copy(payload, 2);
1527
+ this.chiusuraInviata = true;
1528
+ this.socket.write(creaFrame(8, payload), () => this.socket.end());
1529
+ }
1530
+ termina() {
1531
+ if (this.terminato) return;
1532
+ this.terminato = true;
1533
+ this.emit("close");
1534
+ }
1535
+ erroreProtocollo(code, reason) {
1536
+ this.close(code, reason);
1537
+ }
1538
+ aggiungi(chunk) {
1539
+ if (this.terminato) return;
1540
+ this.buffer = this.buffer.byteLength === 0 ? chunk : Buffer.concat([this.buffer, chunk]);
1541
+ this.leggiFrame();
1542
+ }
1543
+ leggiFrame() {
1544
+ while (!this.terminato && this.buffer.byteLength >= 2) {
1545
+ const primo = this.buffer[0] ?? 0;
1546
+ const secondo = this.buffer[1] ?? 0;
1547
+ const fin = (primo & 128) !== 0;
1548
+ const opcode = primo & 15;
1549
+ const controllo = opcode >= 8;
1550
+ if ((primo & 112) !== 0 || ![0, 1, 8, 9, 10].includes(opcode)) {
1551
+ this.erroreProtocollo(1002, "protocol_error");
1552
+ return;
1553
+ }
1554
+ if ((secondo & 128) === 0 || controllo && !fin) {
1555
+ this.erroreProtocollo(1002, "protocol_error");
1556
+ return;
1557
+ }
1558
+ let lunghezza = secondo & 127;
1559
+ let offset = 2;
1560
+ if (lunghezza === 126) {
1561
+ if (this.buffer.byteLength < 4) return;
1562
+ lunghezza = this.buffer.readUInt16BE(2);
1563
+ offset = 4;
1564
+ } else if (lunghezza === 127) {
1565
+ if (this.buffer.byteLength < 10) return;
1566
+ const grande = this.buffer.readBigUInt64BE(2);
1567
+ if (grande > BigInt(Number.MAX_SAFE_INTEGER)) {
1568
+ this.erroreProtocollo(1009, "message_too_large");
1569
+ return;
1570
+ }
1571
+ lunghezza = Number(grande);
1572
+ offset = 10;
1573
+ }
1574
+ if (controllo && lunghezza > 125) {
1575
+ this.erroreProtocollo(1002, "protocol_error");
1576
+ return;
1577
+ }
1578
+ if (this.buffer.byteLength < offset + 4 + lunghezza) return;
1579
+ const maschera = this.buffer.subarray(offset, offset + 4);
1580
+ const payload = Buffer.from(this.buffer.subarray(offset + 4, offset + 4 + lunghezza));
1581
+ this.buffer = this.buffer.subarray(offset + 4 + lunghezza);
1582
+ for (let indice = 0; indice < payload.byteLength; indice += 1) {
1583
+ payload[indice] = (payload[indice] ?? 0) ^ (maschera[indice % 4] ?? 0);
1584
+ }
1585
+ if (controllo) {
1586
+ this.gestisciControllo(opcode, payload);
1587
+ continue;
1588
+ }
1589
+ this.gestisciDati(opcode, fin, payload);
1590
+ }
1591
+ }
1592
+ gestisciControllo(opcode, payload) {
1593
+ if (opcode === 9) {
1594
+ if (!this.chiusuraInviata) this.socket.write(creaFrame(10, payload));
1595
+ return;
1596
+ }
1597
+ if (opcode === 10) return;
1598
+ if (payload.byteLength === 1) {
1599
+ this.erroreProtocollo(1002, "protocol_error");
1600
+ return;
1601
+ }
1602
+ if (!this.chiusuraInviata) {
1603
+ this.chiusuraInviata = true;
1604
+ this.socket.write(creaFrame(8, payload), () => this.socket.end());
1605
+ } else {
1606
+ this.socket.end();
1607
+ }
1608
+ }
1609
+ gestisciDati(opcode, fin, payload) {
1610
+ if (opcode === 1 && this.frammentando) {
1611
+ this.erroreProtocollo(1002, "protocol_error");
1612
+ return;
1613
+ }
1614
+ if (opcode === 0 && !this.frammentando) {
1615
+ this.erroreProtocollo(1002, "protocol_error");
1616
+ return;
1617
+ }
1618
+ if (opcode === 1 && !fin) this.frammentando = true;
1619
+ this.frammenti.push(payload);
1620
+ this.byteFrammenti += payload.byteLength;
1621
+ if (this.byteFrammenti > this.massimoMessaggio) {
1622
+ this.erroreProtocollo(1009, "message_too_large");
1623
+ return;
1624
+ }
1625
+ if (!fin) return;
1626
+ const completo = this.frammenti.length === 1 ? this.frammenti[0] ?? Buffer.alloc(0) : Buffer.concat(this.frammenti, this.byteFrammenti);
1627
+ this.frammenti = [];
1628
+ this.byteFrammenti = 0;
1629
+ this.frammentando = false;
1630
+ const testo = testoUtf8(completo);
1631
+ if (testo === null) {
1632
+ this.erroreProtocollo(1007, "invalid_utf8");
1633
+ return;
1634
+ }
1635
+ this.emit("message", testo);
1636
+ }
1637
+ };
1638
+ function acceptNodeWebSocket(request, socket, head = Buffer.alloc(0)) {
1639
+ const key = request.headers["sec-websocket-key"];
1640
+ if (request.method !== "GET" || request.headers.upgrade?.toLowerCase() !== "websocket" || !contieneToken(request.headers.connection, "upgrade") || request.headers["sec-websocket-version"] !== "13" || !chiaveValida(key)) {
1641
+ throw new TypeError("The WebSocket upgrade request is invalid.");
1642
+ }
1643
+ const accept = createHash("sha1").update(key + GUID_WEBSOCKET).digest("base64");
1644
+ socket.write(
1645
+ `HTTP/1.1 101 Switching Protocols\r
1646
+ Upgrade: websocket\r
1647
+ Connection: Upgrade\r
1648
+ Sec-WebSocket-Accept: ${accept}\r
1649
+ \r
1650
+ `
1651
+ );
1652
+ return new NodeWebSocket(socket, head);
1653
+ }
1654
+
1655
+ // src/node/index.ts
1656
+ function acceptNodeWebSocket2(request, socket, head = Buffer.alloc(0)) {
1657
+ return acceptNodeWebSocket(request, socket, head);
1658
+ }
1659
+ function documentoValido(value) {
1660
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1661
+ const dati = value;
1662
+ return dati.version === 1 && typeof dati.values === "object" && dati.values !== null && !Array.isArray(dati.values);
1663
+ }
1664
+ var ArchivioNode = class _ArchivioNode {
1665
+ constructor(file) {
1666
+ this.file = file;
1667
+ this.valori = /* @__PURE__ */ new Map();
1668
+ this.scritture = Promise.resolve();
1669
+ }
1670
+ static async apri(file) {
1671
+ const archivio = new _ArchivioNode(file);
1672
+ if (file === null) return archivio;
1673
+ let source;
1674
+ try {
1675
+ source = await readFile(file, "utf8");
1676
+ } catch (cause) {
1677
+ if (cause.code === "ENOENT") return archivio;
1678
+ throw cause;
1679
+ }
1680
+ let parsed;
1681
+ try {
1682
+ parsed = JSON.parse(source);
1683
+ } catch {
1684
+ throw new Error(`The room storage file is not valid JSON: ${file}`);
1685
+ }
1686
+ if (!documentoValido(parsed)) throw new Error(`The room storage file is invalid: ${file}`);
1687
+ for (const [key, value] of Object.entries(parsed.values)) {
1688
+ archivio.valori.set(key, structuredClone(value));
1689
+ }
1690
+ return archivio;
1691
+ }
1692
+ async get(key) {
1693
+ const value = this.valori.get(key);
1694
+ return value === void 0 ? void 0 : structuredClone(value);
1695
+ }
1696
+ async put(key, value) {
1697
+ this.valori.set(key, structuredClone(value));
1698
+ await this.persisti();
1699
+ }
1700
+ async delete(key) {
1701
+ this.valori.delete(key);
1702
+ await this.persisti();
1703
+ }
1704
+ async list(prefix = "") {
1705
+ return new Map([...this.valori].flatMap(
1706
+ ([key, value]) => key.startsWith(prefix) ? [[key, structuredClone(value)]] : []
1707
+ ));
1708
+ }
1709
+ persisti() {
1710
+ if (this.file === null) return Promise.resolve();
1711
+ const file = this.file;
1712
+ const documento = {
1713
+ version: 1,
1714
+ values: Object.fromEntries([...this.valori].map(([key, value]) => [key, structuredClone(value)]))
1715
+ };
1716
+ const operazione = this.scritture.then(async () => {
1717
+ await mkdir(dirname(file), { recursive: true });
1718
+ const temporaneo = `${file}.${process.pid}.${randomUUID()}.tmp`;
1719
+ try {
1720
+ await writeFile(temporaneo, `${JSON.stringify(documento, null, 2)}
1721
+ `, "utf8");
1722
+ await rename(temporaneo, file);
1723
+ } finally {
1724
+ await rm(temporaneo, { force: true });
1725
+ }
1726
+ });
1727
+ this.scritture = operazione.catch(() => void 0);
1728
+ return operazione;
1729
+ }
1730
+ };
1731
+ var AdattatoreNode = class {
1732
+ constructor(storage, deposito) {
1733
+ this.storage = storage;
1734
+ this.deposito = deposito;
1735
+ this.connessioni = /* @__PURE__ */ new Map();
1736
+ this.tickTimer = null;
1737
+ this.tickIntervallo = null;
1738
+ this.tickGenerazione = 0;
1739
+ this.svegliaTimer = null;
1740
+ this.svegliaAt = null;
1741
+ this.eseguiTick = async () => void 0;
1742
+ this.eseguiSveglia = async () => void 0;
1743
+ }
1744
+ collega(input) {
1745
+ this.eseguiTick = input.tick;
1746
+ this.eseguiSveglia = input.sveglia;
1747
+ }
1748
+ aggiungi(id, socket) {
1749
+ this.connessioni.set(id, socket);
1750
+ }
1751
+ rimuovi(id) {
1752
+ this.connessioni.delete(id);
1753
+ }
1754
+ elencoConnessioni() {
1755
+ return [...this.connessioni];
1756
+ }
1757
+ invia(connessione, messaggio) {
1758
+ this.connessioni.get(connessione)?.send(JSON.stringify(messaggio));
1759
+ }
1760
+ chiudi(connessione, codice, motivo) {
1761
+ this.connessioni.get(connessione)?.close(codice, motivo);
1762
+ }
1763
+ connessioniAttive() {
1764
+ return [...this.connessioni.keys()];
1765
+ }
1766
+ ora() {
1767
+ return Date.now();
1768
+ }
1769
+ misuraCpu() {
1770
+ return performance.now();
1771
+ }
1772
+ programmaTick(intervalloMs) {
1773
+ if (this.tickIntervallo === intervalloMs) return;
1774
+ this.tickIntervallo = intervalloMs;
1775
+ this.tickGenerazione += 1;
1776
+ if (this.tickTimer !== null) clearTimeout(this.tickTimer);
1777
+ this.tickTimer = null;
1778
+ if (intervalloMs !== null) this.pianificaTick(this.tickGenerazione);
1779
+ }
1780
+ async programmaSveglia(ora) {
1781
+ this.svegliaAt = ora;
1782
+ if (this.svegliaTimer !== null) clearTimeout(this.svegliaTimer);
1783
+ this.svegliaTimer = null;
1784
+ if (ora !== null) this.pianificaSveglia();
1785
+ }
1786
+ fermaTimer() {
1787
+ this.tickIntervallo = null;
1788
+ this.svegliaAt = null;
1789
+ this.tickGenerazione += 1;
1790
+ if (this.tickTimer !== null) clearTimeout(this.tickTimer);
1791
+ if (this.svegliaTimer !== null) clearTimeout(this.svegliaTimer);
1792
+ this.tickTimer = null;
1793
+ this.svegliaTimer = null;
1794
+ }
1795
+ pianificaTick(generazione) {
1796
+ const intervallo = this.tickIntervallo;
1797
+ if (intervallo === null) return;
1798
+ this.tickTimer = setTimeout(() => {
1799
+ this.tickTimer = null;
1800
+ void this.eseguiTick().finally(() => {
1801
+ if (this.tickGenerazione === generazione && this.tickIntervallo !== null) {
1802
+ this.pianificaTick(generazione);
1803
+ }
1804
+ });
1805
+ }, intervallo);
1806
+ this.tickTimer.unref();
1807
+ }
1808
+ pianificaSveglia() {
1809
+ const ora = this.svegliaAt;
1810
+ if (ora === null) return;
1811
+ const attesa = Math.min(Math.max(0, ora - Date.now()), 2147483647);
1812
+ this.svegliaTimer = setTimeout(() => {
1813
+ this.svegliaTimer = null;
1814
+ if (this.svegliaAt !== null && this.svegliaAt > Date.now()) {
1815
+ this.pianificaSveglia();
1816
+ return;
1817
+ }
1818
+ void this.eseguiSveglia();
1819
+ }, attesa);
1820
+ this.svegliaTimer.unref();
1821
+ }
1822
+ };
1823
+ var StanzaNode = class {
1824
+ constructor(nucleo, adattatore, manifest) {
1825
+ this.nucleo = nucleo;
1826
+ this.adattatore = adattatore;
1827
+ this.manifest = manifest;
1828
+ this.coda = Promise.resolve();
1829
+ this.voceRoster = /* @__PURE__ */ new Map();
1830
+ this.voceListeners = /* @__PURE__ */ new Map();
1831
+ this.voceFrequenza = /* @__PURE__ */ new Map();
1832
+ this.voceUltimaRichiesta = /* @__PURE__ */ new Map();
1833
+ this.frameFrequenza = /* @__PURE__ */ new Map();
1834
+ this.connessioniGiocatori = /* @__PURE__ */ new Map();
1835
+ this.giocatoriConnessioni = /* @__PURE__ */ new Map();
1836
+ adattatore.collega({
1837
+ tick: () => this.serializza(() => nucleo.eseguiTick()),
1838
+ sveglia: () => this.serializza(() => nucleo.sveglia())
1839
+ });
1840
+ }
1841
+ create(roomId, mode, creator) {
1842
+ return this.serializza(() => this.nucleo.crea(roomId, mode, creator));
1843
+ }
1844
+ info() {
1845
+ return this.serializza(() => Promise.resolve(this.nucleo.info()));
1846
+ }
1847
+ canJoin(identity) {
1848
+ return this.serializza(() => Promise.resolve(this.nucleo.puoEntrare(identity)));
1849
+ }
1850
+ async connect(socket, identity) {
1851
+ const connessione = randomUUID();
1852
+ this.adattatore.aggiungi(connessione, socket);
1853
+ this.connessioniGiocatori.set(connessione, identity.id);
1854
+ socket.on("message", (message) => {
1855
+ void this.serializza(() => this.ricevi(connessione, message));
1856
+ });
1857
+ socket.on("close", () => {
1858
+ this.adattatore.rimuovi(connessione);
1859
+ void this.serializza(async () => {
1860
+ this.rimuoviConnessione(connessione);
1861
+ await this.nucleo.disconnetti(connessione);
1862
+ });
1863
+ });
1864
+ try {
1865
+ return await this.serializza(async () => {
1866
+ const precedente = this.giocatoriConnessioni.get(identity.id);
1867
+ if (precedente !== void 0 && precedente !== connessione) this.rimuoviConnessione(precedente);
1868
+ this.giocatoriConnessioni.set(identity.id, connessione);
1869
+ const esito = await this.nucleo.entra(identity, connessione);
1870
+ if (esito.ok) this.inviaRoster(connessione);
1871
+ return esito;
1872
+ });
1873
+ } catch (cause) {
1874
+ this.adattatore.rimuovi(connessione);
1875
+ this.rimuoviConnessione(connessione);
1876
+ socket.close(1011, "room_error");
1877
+ throw cause;
1878
+ }
1879
+ }
1880
+ flush() {
1881
+ return this.serializza(() => this.nucleo.flush());
1882
+ }
1883
+ wake() {
1884
+ return this.serializza(() => this.nucleo.sveglia());
1885
+ }
1886
+ async close() {
1887
+ this.adattatore.fermaTimer();
1888
+ for (const [connessione, socket] of this.adattatore.elencoConnessioni()) {
1889
+ this.adattatore.rimuovi(connessione);
1890
+ this.rimuoviConnessione(connessione);
1891
+ socket.close(1001, "server_shutdown");
1892
+ await this.serializza(() => this.nucleo.disconnetti(connessione));
1893
+ }
1894
+ }
1895
+ serializza(operazione) {
1896
+ const risultato = this.coda.then(operazione);
1897
+ this.coda = risultato.then(() => void 0, () => void 0);
1898
+ return risultato;
1899
+ }
1900
+ async ricevi(connessione, frame) {
1901
+ const player = this.nucleo.giocatoreConnesso(connessione);
1902
+ if (player === null) return;
1903
+ const ora = Date.now();
1904
+ const frames = (this.frameFrequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
1905
+ if (frames.length >= 20) {
1906
+ this.adattatore.chiudi(connessione, 4008, "rate_limited");
1907
+ this.rimuoviConnessione(connessione);
1908
+ await this.nucleo.disconnetti(connessione);
1909
+ return;
1910
+ }
1911
+ frames.push(ora);
1912
+ this.frameFrequenza.set(connessione, frames);
1913
+ let value;
1914
+ try {
1915
+ value = JSON.parse(frame);
1916
+ } catch {
1917
+ await this.nucleo.ricevi(connessione, frame);
1918
+ return;
1919
+ }
1920
+ const message = typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1921
+ if (message?.t !== "voice") {
1922
+ await this.nucleo.ricevi(connessione, frame);
1923
+ this.riconciliaRoster();
1924
+ return;
1925
+ }
1926
+ if (Buffer.byteLength(frame, "utf8") > 64 * 1024) {
1927
+ this.adattatore.chiudi(connessione, 4009, "bad_message");
1928
+ this.rimuoviConnessione(connessione);
1929
+ await this.nucleo.disconnetti(connessione);
1930
+ return;
1931
+ }
1932
+ await this.riceviVoce(connessione, player.id, player.role, message);
1933
+ }
1934
+ async riceviVoce(connessione, playerId, role, value) {
1935
+ const richiesta = this.richiestaVoce(value);
1936
+ if (richiesta === null) {
1937
+ this.inviaErroreVoce(connessione, value, "invalid_request", "The voice request is invalid.");
1938
+ return;
1939
+ }
1940
+ const ultima = this.voceUltimaRichiesta.get(connessione) ?? 0;
1941
+ if (richiesta.r <= ultima) {
1942
+ this.inviaErroreVoce(
1943
+ connessione,
1944
+ richiesta,
1945
+ "invalid_request",
1946
+ "Voice request numbers must increase."
1947
+ );
1948
+ return;
1949
+ }
1950
+ this.voceUltimaRichiesta.set(connessione, richiesta.r);
1951
+ const ora = Date.now();
1952
+ const recenti = (this.voceFrequenza.get(connessione) ?? []).filter((at) => ora - at < 1e4);
1953
+ if (recenti.length >= 30) {
1954
+ this.inviaErroreVoce(
1955
+ connessione,
1956
+ richiesta,
1957
+ "rate_limited",
1958
+ "Too many voice requests. Try again later."
1959
+ );
1960
+ return;
1961
+ }
1962
+ recenti.push(ora);
1963
+ this.voceFrequenza.set(connessione, recenti);
1964
+ const mode = this.modoVoce();
1965
+ if (mode === "none") {
1966
+ this.inviaErroreVoce(connessione, richiesta, "voice_disabled", "Voice is disabled for this room.");
1967
+ return;
1968
+ }
1969
+ if (richiesta.op === "ice") {
1970
+ this.adattatore.invia(connessione, {
1971
+ t: "voice",
1972
+ op: "ice",
1973
+ r: richiesta.r,
1974
+ transport: "mesh",
1975
+ mode,
1976
+ iceServers: []
1977
+ });
1978
+ return;
1979
+ }
1980
+ if (richiesta.op === "publish") {
1981
+ const mic = richiesta.mic !== false;
1982
+ if (role === "spectator" && mic) {
1983
+ this.inviaErroreVoce(connessione, richiesta, "spectator", "Spectators cannot join voice.");
1984
+ return;
1985
+ }
1986
+ if (mic) {
1987
+ this.voceListeners.delete(playerId);
1988
+ this.voceRoster.set(playerId, {
1989
+ id: playerId,
1990
+ session: "mesh",
1991
+ track: "mic",
1992
+ muted: false,
1993
+ connessione
1994
+ });
1995
+ } else {
1996
+ this.voceRoster.delete(playerId);
1997
+ this.voceListeners.set(playerId, connessione);
1998
+ }
1999
+ this.adattatore.invia(connessione, { t: "voice", op: "publish", r: richiesta.r });
2000
+ this.broadcastRoster();
2001
+ return;
2002
+ }
2003
+ if (richiesta.op === "signal") {
2004
+ const destinazione = this.giocatoriConnessioni.get(richiesta.to);
2005
+ if (destinazione !== void 0) {
2006
+ this.adattatore.invia(destinazione, {
2007
+ t: "voice",
2008
+ op: "signal",
2009
+ from: playerId,
2010
+ data: richiesta.data
2011
+ });
2012
+ }
2013
+ this.adattatore.invia(connessione, { t: "voice", op: "signal", r: richiesta.r });
2014
+ return;
2015
+ }
2016
+ if (richiesta.op === "mute") {
2017
+ const peer = this.voceRoster.get(playerId);
2018
+ if (peer === void 0 || peer.connessione !== connessione) {
2019
+ this.inviaErroreVoce(
2020
+ connessione,
2021
+ richiesta,
2022
+ "not_publishing",
2023
+ "Join voice before changing mute."
2024
+ );
2025
+ return;
2026
+ }
2027
+ peer.muted = richiesta.muted;
2028
+ this.adattatore.invia(connessione, { t: "voice", op: "mute", r: richiesta.r });
2029
+ this.broadcastRoster();
2030
+ return;
2031
+ }
2032
+ if (richiesta.op === "stop") {
2033
+ const peer = this.voceRoster.get(playerId);
2034
+ const listener = this.voceListeners.get(playerId);
2035
+ const rimossaPeer = peer?.connessione === connessione && this.voceRoster.delete(playerId);
2036
+ const rimossoListener = listener === connessione && this.voceListeners.delete(playerId);
2037
+ this.adattatore.invia(connessione, { t: "voice", op: "stop", r: richiesta.r });
2038
+ if (rimossaPeer || rimossoListener) this.broadcastRoster();
2039
+ return;
2040
+ }
2041
+ this.inviaErroreVoce(connessione, richiesta, "invalid_request", "The voice request is invalid.");
2042
+ }
2043
+ richiestaVoce(value) {
2044
+ if (!Number.isSafeInteger(value.r) || value.r < 1 || typeof value.op !== "string") {
2045
+ return null;
2046
+ }
2047
+ const base = { t: "voice", r: value.r };
2048
+ if (value.op === "ice" || value.op === "stop") {
2049
+ return { ...base, op: value.op };
2050
+ }
2051
+ if (value.op === "publish" && (value.mic === void 0 || typeof value.mic === "boolean")) {
2052
+ return { ...base, op: "publish", ...value.mic === void 0 ? {} : { mic: value.mic } };
2053
+ }
2054
+ if (value.op === "mute" && typeof value.muted === "boolean") {
2055
+ return { ...base, op: "mute", muted: value.muted };
2056
+ }
2057
+ if (value.op === "signal" && typeof value.to === "string" && Object.hasOwn(value, "data")) {
2058
+ return { ...base, op: "signal", to: value.to, data: value.data };
2059
+ }
2060
+ if (["session", "subscribe", "answer", "close"].includes(value.op)) {
2061
+ return value;
2062
+ }
2063
+ return null;
2064
+ }
2065
+ modoVoce() {
2066
+ return this.manifest.voice ?? "none";
2067
+ }
2068
+ rosterPubblico() {
2069
+ return [...this.voceRoster.values()].map(({ connessione: _connessione, ...peer }) => peer);
2070
+ }
2071
+ inviaRoster(connessione) {
2072
+ this.adattatore.invia(connessione, {
2073
+ t: "voice",
2074
+ op: "roster",
2075
+ mode: this.modoVoce(),
2076
+ peers: this.rosterPubblico(),
2077
+ listeners: [...this.voceListeners.keys()].sort((a, b) => a.localeCompare(b))
2078
+ });
2079
+ }
2080
+ broadcastRoster() {
2081
+ for (const connessione of this.adattatore.connessioniAttive()) this.inviaRoster(connessione);
2082
+ }
2083
+ riconciliaRoster() {
2084
+ let cambiato = false;
2085
+ for (const [playerId, peer] of this.voceRoster) {
2086
+ const player = this.nucleo.giocatoreConnesso(peer.connessione);
2087
+ if (player?.id === playerId && player.role !== "spectator") continue;
2088
+ this.voceRoster.delete(playerId);
2089
+ cambiato = true;
2090
+ }
2091
+ for (const [playerId, connessione] of this.voceListeners) {
2092
+ if (this.nucleo.giocatoreConnesso(connessione)?.id === playerId) continue;
2093
+ this.voceListeners.delete(playerId);
2094
+ cambiato = true;
2095
+ }
2096
+ if (cambiato) this.broadcastRoster();
2097
+ }
2098
+ rimuoviConnessione(connessione) {
2099
+ const playerId = this.connessioniGiocatori.get(connessione);
2100
+ this.connessioniGiocatori.delete(connessione);
2101
+ this.voceFrequenza.delete(connessione);
2102
+ this.voceUltimaRichiesta.delete(connessione);
2103
+ this.frameFrequenza.delete(connessione);
2104
+ if (playerId === void 0) return;
2105
+ if (this.giocatoriConnessioni.get(playerId) === connessione) {
2106
+ this.giocatoriConnessioni.delete(playerId);
2107
+ }
2108
+ if (this.voceRoster.get(playerId)?.connessione === connessione) {
2109
+ this.voceRoster.delete(playerId);
2110
+ this.broadcastRoster();
2111
+ } else if (this.voceListeners.get(playerId) === connessione) {
2112
+ this.voceListeners.delete(playerId);
2113
+ this.broadcastRoster();
2114
+ }
2115
+ }
2116
+ inviaErroreVoce(connessione, richiesta, code, message) {
2117
+ const op = typeof richiesta.op === "string" ? richiesta.op : "ice";
2118
+ const r = Number.isSafeInteger(richiesta.r) && richiesta.r >= 1 ? richiesta.r : 1;
2119
+ this.adattatore.invia(connessione, { t: "voice", op, r, error: { code, message } });
2120
+ }
2121
+ };
2122
+ async function createNodeRoom(definition, manifest, options = {}) {
2123
+ const storage = await ArchivioNode.apri(options.storageFile ?? null);
2124
+ const adattatore = new AdattatoreNode(storage, options.deposito ?? null);
2125
+ const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
2126
+ return new StanzaNode(nucleo, adattatore, manifest);
2127
+ }
2128
+ export {
2129
+ acceptNodeWebSocket2 as acceptNodeWebSocket,
2130
+ createNodeRoom
2131
+ };