@caisual/kit 0.5.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/kit.d.ts +2 -175
  2. package/dist/kit.js +1808 -76
  3. package/dist/node.d.ts +1 -88
  4. package/dist/node.js +354 -96
  5. package/dist/overlay.d.ts +1 -0
  6. package/dist/overlay.js +2074 -0
  7. package/dist/runtime.d.ts +1 -111
  8. package/dist/runtime.js +335 -67
  9. package/dist/server.d.ts +1 -71
  10. package/dist/server.js +3 -0
  11. package/dist/types/api.d.ts +25 -0
  12. package/dist/types/contracts/biglietto.d.ts +24 -0
  13. package/dist/types/contracts/device.d.ts +66 -0
  14. package/dist/types/contracts/firma.d.ts +21 -0
  15. package/dist/types/contracts/i18n.d.ts +12 -0
  16. package/dist/types/contracts/index.d.ts +13 -0
  17. package/dist/types/contracts/keys.d.ts +59 -0
  18. package/dist/types/contracts/manifest.d.ts +123 -0
  19. package/dist/types/contracts/overlay-boards.d.ts +3 -0
  20. package/dist/types/contracts/overlay.d.ts +223 -0
  21. package/dist/types/contracts/player.d.ts +1 -0
  22. package/dist/types/contracts/room-limits.d.ts +13 -0
  23. package/dist/types/contracts/runtime.d.ts +70 -0
  24. package/dist/types/contracts/server-js.d.ts +11 -0
  25. package/dist/types/contracts/slug.d.ts +5 -0
  26. package/dist/types/contracts/token-crew.d.ts +21 -0
  27. package/dist/types/daily.d.ts +3 -0
  28. package/dist/types/errors.d.ts +6 -0
  29. package/dist/types/handshake.d.ts +30 -0
  30. package/dist/types/http.d.ts +3 -0
  31. package/dist/types/index.d.ts +231 -0
  32. package/dist/types/kit.d.ts +28 -0
  33. package/dist/types/node/index.d.ts +97 -0
  34. package/dist/types/node/websocket.d.ts +29 -0
  35. package/dist/types/overlay/boards.d.ts +48 -0
  36. package/dist/types/overlay/bridge.d.ts +3 -0
  37. package/dist/types/overlay/host-bridge.d.ts +74 -0
  38. package/dist/types/overlay/i18n.d.ts +128 -0
  39. package/dist/types/overlay/index.d.ts +10 -0
  40. package/dist/types/overlay/shortcut.d.ts +4 -0
  41. package/dist/types/overlay/styles.d.ts +1 -0
  42. package/dist/types/overlay/ui-model.d.ts +45 -0
  43. package/dist/types/overlay/ui.d.ts +80 -0
  44. package/dist/types/overlay/voice-panel.d.ts +13 -0
  45. package/dist/types/protocollo.d.ts +262 -0
  46. package/dist/types/runtime/index.d.ts +128 -0
  47. package/dist/types/server/index.d.ts +76 -0
  48. package/dist/types/session/index.d.ts +49 -0
  49. package/dist/types/session/resume.d.ts +13 -0
  50. package/dist/types/standalone.d.ts +14 -0
  51. package/dist/types/stanza/index.d.ts +3 -0
  52. package/dist/types/stanza/json.d.ts +18 -0
  53. package/dist/types/stanza/nucleo.d.ts +100 -0
  54. package/dist/types/stanza/tipi.d.ts +136 -0
  55. package/dist/types/stanza-client/index.d.ts +24 -0
  56. package/dist/types/text.d.ts +2 -0
  57. package/dist/types/voce/index.d.ts +124 -0
  58. package/package.json +10 -2
package/dist/runtime.js CHANGED
@@ -1,3 +1,89 @@
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
+
36
+ // ../contracts/src/manifest.ts
37
+ function risolviModalita(manifest, mode) {
38
+ const scelta = mode === null ? void 0 : manifest.modes.find((voce) => voce.id === mode);
39
+ if (mode !== null && scelta === void 0) throw new Error("The selected game mode does not exist.");
40
+ return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
41
+ }
42
+ function modalitaLocale(manifest, mode) {
43
+ return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
44
+ }
45
+
46
+ // ../contracts/src/room-limits.ts
47
+ var MESSAGGI_GIOCO_AL_SECONDO = 20;
48
+ var MESSAGGI_SERVIZIO_AL_SECONDO = 20;
49
+ var LimiteMessaggiStanza = class {
50
+ connessioni = /* @__PURE__ */ new Map();
51
+ delete(connessione) {
52
+ this.connessioni.delete(connessione);
53
+ }
54
+ clear() {
55
+ this.connessioni.clear();
56
+ }
57
+ controlla(connessione, gioco, ora) {
58
+ let stato = this.connessioni.get(connessione);
59
+ if (stato === void 0) {
60
+ const budget2 = () => ({ accettati: [], finestra: ora, tentativi: 0, finestreAbusive: 0 });
61
+ stato = { gioco: budget2(), servizio: budget2(), ultimoErrore: -Infinity };
62
+ this.connessioni.set(connessione, stato);
63
+ }
64
+ const budget = gioco ? stato.gioco : stato.servizio;
65
+ const limite = gioco ? MESSAGGI_GIOCO_AL_SECONDO : MESSAGGI_SERVIZIO_AL_SECONDO;
66
+ if (ora - budget.finestra >= 1e3) {
67
+ budget.finestreAbusive = ora - budget.finestra < 2e3 && budget.tentativi > limite * 5 ? budget.finestreAbusive + 1 : 0;
68
+ budget.finestra += Math.floor((ora - budget.finestra) / 1e3) * 1e3;
69
+ budget.tentativi = 0;
70
+ }
71
+ budget.tentativi = Math.min(budget.tentativi + 1, limite * 5 + 1);
72
+ budget.accettati = budget.accettati.filter((at) => ora - at < 1e3);
73
+ if (budget.accettati.length < limite) {
74
+ budget.accettati.push(ora);
75
+ return { accetta: true, avvisa: false, chiudi: false };
76
+ }
77
+ const avvisa = ora - stato.ultimoErrore >= 1e3;
78
+ if (avvisa) stato.ultimoErrore = ora;
79
+ return {
80
+ accetta: false,
81
+ avvisa,
82
+ chiudi: budget.finestreAbusive >= 2 && budget.tentativi > limite * 5
83
+ };
84
+ }
85
+ };
86
+
1
87
  // src/stanza/json.ts
2
88
  function isPlainObject(value) {
3
89
  const prototype = Object.getPrototypeOf(value);
@@ -233,6 +319,7 @@ var LIMITE_DEPOSITO = 64 * 1024;
233
319
  var LIMITE_OPERAZIONI_DEPOSITO = 120;
234
320
  var GRAZIA_MS = 6e4;
235
321
  var STANZA_VUOTA_MS = 5 * 6e4;
322
+ var ATTESA_RIVINCITA_MS = 2 * 6e4;
236
323
  var COUNTDOWN_MS = 3e3;
237
324
  var RIPOSO_TICK_MS = 3e4;
238
325
  var INATTIVITA_MS = 10 * 6e4;
@@ -284,21 +371,22 @@ var NucleoStanza = class _NucleoStanza {
284
371
  this.manifest = manifest;
285
372
  this.adattatore = adattatore;
286
373
  this.dati = null;
287
- this.frequenza = /* @__PURE__ */ new Map();
374
+ this.frequenza = new LimiteMessaggiStanza();
288
375
  this.frequenzaDeposito = [];
289
376
  this.kickRichiesti = /* @__PURE__ */ new Set();
290
377
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
291
378
  this.fineRichiesta = null;
292
379
  this.applicandoAzioni = false;
293
380
  this.ultimoStatoOsservato = "";
381
+ this.tickRateSincronizzato = null;
294
382
  this.voceDaPersistire = false;
295
383
  const nucleo = this;
296
384
  const daily = {
297
385
  get day() {
298
- return giornoUtc(nucleo.adattatore.ora());
386
+ return nucleo.giornata();
299
387
  },
300
388
  get seed() {
301
- return seedGiornata(nucleo.manifest.id, giornoUtc(nucleo.adattatore.ora()));
389
+ return seedGiornata(nucleo.manifest.id, nucleo.giornata());
302
390
  }
303
391
  };
304
392
  this.room = {
@@ -352,8 +440,8 @@ var NucleoStanza = class _NucleoStanza {
352
440
  setTeam(player, team) {
353
441
  nucleo.impostaSquadraDalServer(idGiocatore(player), team);
354
442
  },
355
- end(result) {
356
- nucleo.richiediFine(result);
443
+ end(result, options) {
444
+ nucleo.richiediFine(result, options?.rematch === true);
357
445
  },
358
446
  save(key, value) {
359
447
  return nucleo.salva(key, value);
@@ -413,6 +501,7 @@ var NucleoStanza = class _NucleoStanza {
413
501
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
414
502
  if (salvato !== void 0) {
415
503
  nucleo.dati = salvato;
504
+ nucleo.tickRateSincronizzato = salvato.tickRate;
416
505
  const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
417
506
  salvato.ultimoInputAt ??= adattatore.ora();
418
507
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
@@ -440,9 +529,8 @@ var NucleoStanza = class _NucleoStanza {
440
529
  }
441
530
  async crea(id, mode, _creator) {
442
531
  if (this.dati !== null) return false;
443
- if (mode !== null && !this.manifest.modes.some((item) => item.id === mode)) {
444
- throw new Error("The selected game mode does not exist.");
445
- }
532
+ risolviModalita(this.manifest, mode);
533
+ if (modalitaLocale(this.manifest, mode)) throw new Error("Local modes cannot create rooms.");
446
534
  const ora = this.adattatore.ora();
447
535
  this.dati = {
448
536
  versione: 1,
@@ -487,6 +575,9 @@ var NucleoStanza = class _NucleoStanza {
487
575
  await this.persistiEProgramma();
488
576
  return true;
489
577
  }
578
+ get configurazione() {
579
+ return risolviModalita(this.manifest, this.dati?.mode ?? null);
580
+ }
490
581
  info(playerId) {
491
582
  if (this.dati === null) return null;
492
583
  return {
@@ -495,7 +586,7 @@ var NucleoStanza = class _NucleoStanza {
495
586
  players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
496
587
  (player) => player.connected || player.graziaFinoA !== null
497
588
  ).length,
498
- max: this.manifest.players.max,
589
+ max: this.configurazione.players.max,
499
590
  mode: this.dati.mode,
500
591
  member: playerId === void 0 ? false : this.dati.giocatori.some((player) => player.id === playerId)
501
592
  };
@@ -514,15 +605,34 @@ var NucleoStanza = class _NucleoStanza {
514
605
  );
515
606
  return player === void 0 ? null : copiaGiocatore(player);
516
607
  }
608
+ puoAscoltare(listener, speakers) {
609
+ const mode = this.manifest.voice ?? "none";
610
+ if (mode === "none") return speakers.map(() => ({ ok: false, reason: "mode" }));
611
+ const dati = this.richiediDati();
612
+ const ascoltatore = dati.giocatori.find((player) => player.id === listener);
613
+ return speakers.map((speakerId) => {
614
+ const speaker = dati.giocatori.find((player) => player.id === speakerId);
615
+ if (ascoltatore === void 0 || speaker === void 0 || listener === speakerId) {
616
+ return { ok: false, reason: "unknown" };
617
+ }
618
+ if (mode === "team" && ascoltatore.role !== "spectator" && ascoltatore.team !== speaker.team) {
619
+ return { ok: false, reason: "team" };
620
+ }
621
+ if ((dati.voceGuadagni?.[listener]?.[speakerId] ?? 1) <= 0) {
622
+ return { ok: false, reason: "gain" };
623
+ }
624
+ return { ok: true };
625
+ });
626
+ }
517
627
  puoEntrare(identity) {
518
628
  if (this.dati === null) return { ok: false, code: "room_not_found" };
519
629
  if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
520
630
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
521
631
  if (esistente !== void 0) return { ok: true };
522
- if (this.manifest.lobby && this.dati.status !== "lobby") {
632
+ if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
523
633
  return { ok: false, code: "room_playing" };
524
634
  }
525
- if (this.dati.giocatori.length >= this.manifest.players.max) {
635
+ if (this.dati.giocatori.length >= this.configurazione.players.max) {
526
636
  return { ok: false, code: "room_full" };
527
637
  }
528
638
  return { ok: true };
@@ -538,6 +648,7 @@ var NucleoStanza = class _NucleoStanza {
538
648
  const ora = this.adattatore.ora();
539
649
  let player = dati.giocatori.find((item) => item.id === identity.id);
540
650
  const nuovo = player === void 0;
651
+ const riconnesso = player !== void 0 && !player.connected;
541
652
  if (player === void 0) {
542
653
  player = {
543
654
  ...identity,
@@ -553,6 +664,7 @@ var NucleoStanza = class _NucleoStanza {
553
664
  dati.giocatori.push(player);
554
665
  } else {
555
666
  if (player.connected && player.connessione !== null && player.connessione !== connessione) {
667
+ this.frequenza.delete(player.connessione);
556
668
  this.adattatore.chiudi(player.connessione, 4006, "replaced");
557
669
  }
558
670
  player.name = identity.name;
@@ -565,7 +677,7 @@ var NucleoStanza = class _NucleoStanza {
565
677
  dati.hostId ??= player.id;
566
678
  dati.vuotaDa = null;
567
679
  dati.ultimoInputAt = ora;
568
- const primaConnessione = !this.manifest.lobby && dati.status === "lobby";
680
+ const primaConnessione = !this.configurazione.lobby && dati.status === "lobby";
569
681
  if (primaConnessione) dati.status = "playing";
570
682
  if (nuovo) {
571
683
  await this.chiama(
@@ -574,6 +686,9 @@ var NucleoStanza = class _NucleoStanza {
574
686
  copiaGiocatore(player)
575
687
  );
576
688
  }
689
+ if (riconnesso) {
690
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), true);
691
+ }
577
692
  if (primaConnessione) {
578
693
  await this.chiama(this.definizione.onStart, this.room);
579
694
  this.inviaStatus(ora);
@@ -596,14 +711,16 @@ var NucleoStanza = class _NucleoStanza {
596
711
  player.connected = false;
597
712
  player.connessione = null;
598
713
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
599
- if (this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
714
+ if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
600
715
  this.frequenza.delete(connessione);
601
716
  if (this.dati.hostId === player.id) this.assegnaHost();
602
717
  this.verificaCountdown();
718
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
719
+ await this.concludiEvento();
603
720
  this.inviaGiocatori();
604
721
  await this.persistiEProgramma();
605
722
  }
606
- async ricevi(connessione, frame) {
723
+ async ricevi(connessione, frame, limiteVerificato = false) {
607
724
  if (this.dati === null || this.dati.status === "ended") return;
608
725
  if (await this.terminaSeInattiva()) return;
609
726
  const player = this.dati.giocatori.find(
@@ -611,17 +728,10 @@ var NucleoStanza = class _NucleoStanza {
611
728
  );
612
729
  if (player === void 0) return;
613
730
  if (new TextEncoder().encode(frame).byteLength > LIMITE_FRAME) {
614
- await this.chiudiConnessione(player, 4009, "bad_message");
731
+ await this.chiudiConnessione(player, 4009, "message_too_large");
615
732
  return;
616
733
  }
617
734
  const ora = this.adattatore.ora();
618
- const recenti = (this.frequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
619
- if (recenti.length >= 20) {
620
- await this.chiudiConnessione(player, 4008, "rate_limited");
621
- return;
622
- }
623
- recenti.push(ora);
624
- this.frequenza.set(connessione, recenti);
625
735
  let message = null;
626
736
  try {
627
737
  message = record(JSON.parse(frame));
@@ -631,6 +741,14 @@ var NucleoStanza = class _NucleoStanza {
631
741
  await this.chiudiConnessione(player, 4009, "bad_message");
632
742
  return;
633
743
  }
744
+ if (!limiteVerificato) {
745
+ const limite = this.frequenza.controlla(connessione, message.t === "msg", ora);
746
+ if (!limite.accetta) {
747
+ if (limite.avvisa) this.inviaErrore(player, "rate_limited", "Too many room messages. Excess messages are dropped.");
748
+ if (limite.chiudi) await this.chiudiConnessione(player, 4008, "rate_limited");
749
+ return;
750
+ }
751
+ }
634
752
  if (message.t === "ping") {
635
753
  if (typeof message.c !== "number" || !Number.isFinite(message.c)) {
636
754
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -653,6 +771,10 @@ var NucleoStanza = class _NucleoStanza {
653
771
  await this.persistiEProgramma();
654
772
  return;
655
773
  }
774
+ if (message.t === "restart") {
775
+ await this.rivincita(player);
776
+ return;
777
+ }
656
778
  if (message.t === "ready") {
657
779
  if (typeof message.ready !== "boolean") return this.messaggioErrato(player);
658
780
  if (!this.inLobby(player)) return;
@@ -671,6 +793,26 @@ var NucleoStanza = class _NucleoStanza {
671
793
  await this.persistiEProgramma();
672
794
  return;
673
795
  }
796
+ if (message.t === "request-role") {
797
+ if (!Number.isSafeInteger(message.r) || message.r < 1 || typeof message.role !== "string") return this.messaggioErrato(player);
798
+ let code = null;
799
+ if (this.dati.status !== "playing" || this.definizione.onRoleRequest === void 0) code = "role_change_unavailable";
800
+ else if (!this.manifest.roles.some((role) => role.id === message.role)) code = "invalid_role";
801
+ else {
802
+ this.dati.ultimoInputAt = ora;
803
+ await this.chiama(this.definizione.onRoleRequest, this.room, copiaGiocatore(player), message.role);
804
+ await this.concludiEvento();
805
+ if (player.role !== message.role) code = "role_change_refused";
806
+ }
807
+ if (player.connected && player.connessione !== null) this.adattatore.invia(player.connessione, {
808
+ t: "role-result",
809
+ r: message.r,
810
+ ok: code === null,
811
+ code
812
+ });
813
+ await this.persistiEProgramma();
814
+ return;
815
+ }
674
816
  if (message.t === "team") {
675
817
  if (!Number.isInteger(message.team)) return this.messaggioErrato(player);
676
818
  if (!this.inLobby(player)) return;
@@ -704,6 +846,7 @@ var NucleoStanza = class _NucleoStanza {
704
846
  await this.persistiEProgramma();
705
847
  return;
706
848
  }
849
+ if (this.dati.status === "finished") return;
707
850
  this.dati.ultimoInputAt = ora;
708
851
  await this.chiama(
709
852
  this.definizione.onMessage,
@@ -739,23 +882,8 @@ var NucleoStanza = class _NucleoStanza {
739
882
  this.inviaGuadagniCambiati();
740
883
  const stato = await this.verificaStato();
741
884
  if (stato === null || this.stanzaTerminata()) return;
742
- const cambiato = stato.testo !== JSON.stringify(dati.statoSincronizzato);
743
- if (dati.tick % 100 === 0) {
744
- dati.state = stato.valore;
745
- this.inviaSnapshotTutti();
746
- } else if (cambiato) {
747
- const base = dati.tickSincronizzato;
748
- this.broadcast({
749
- t: "state",
750
- tick: dati.tick,
751
- serverTime: this.adattatore.ora(),
752
- base,
753
- patch: creaDiff(dati.statoSincronizzato, stato.valore)
754
- });
755
- dati.state = stato.valore;
756
- dati.statoSincronizzato = copiaJson(stato.valore);
757
- dati.tickSincronizzato = dati.tick;
758
- }
885
+ dati.state = stato.valore;
886
+ this.inviaDiff();
759
887
  if (dati.tick % 100 === 0 || this.voceDaPersistire) await this.persisti();
760
888
  await this.aggiornaProgrammazione();
761
889
  }
@@ -789,7 +917,11 @@ var NucleoStanza = class _NucleoStanza {
789
917
  if (dovuti.length > 0) {
790
918
  const ids = new Set(dovuti.map((timer) => timer.id));
791
919
  this.dati.timer = this.dati.timer.filter((timer) => !ids.has(timer.id));
792
- for (const timer of dovuti) await this.eseguiTimer(timer);
920
+ for (const timer of dovuti) {
921
+ await this.eseguiTimer(timer);
922
+ await this.applicaAzioni();
923
+ if (this.dati.status === "finished" || this.stanzaTerminata()) break;
924
+ }
793
925
  }
794
926
  await this.concludiEvento();
795
927
  if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
@@ -820,22 +952,30 @@ var NucleoStanza = class _NucleoStanza {
820
952
  return esito;
821
953
  }
822
954
  async riconciliaConnessioni() {
955
+ if (this.dati === null || this.dati.status === "ended") return;
823
956
  const dati = this.richiediDati();
824
957
  const attive = new Set(this.adattatore.connessioniAttive());
825
958
  const ora = this.adattatore.ora();
826
- let cambiato = false;
959
+ const disconnessi = [];
827
960
  for (const player of dati.giocatori) {
828
961
  if (player.connected && (player.connessione === null || !attive.has(player.connessione))) {
829
962
  player.connected = false;
963
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
830
964
  player.connessione = null;
831
965
  player.graziaFinoA = ora + GRAZIA_MS;
832
- if (this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
833
- cambiato = true;
966
+ if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
967
+ disconnessi.push(player);
834
968
  }
835
969
  }
836
- if (cambiato) {
970
+ if (disconnessi.length > 0) {
837
971
  this.assegnaHost();
838
- await this.persisti();
972
+ this.verificaCountdown();
973
+ for (const player of disconnessi) {
974
+ await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
975
+ }
976
+ await this.concludiEvento();
977
+ this.inviaGiocatori();
978
+ await this.persistiEProgramma();
839
979
  }
840
980
  }
841
981
  ruoloAutomatico() {
@@ -884,10 +1024,15 @@ var NucleoStanza = class _NucleoStanza {
884
1024
  if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
885
1025
  return { code: "role_full", message: "This role is full." };
886
1026
  }
1027
+ const ruoloPrecedente = player.role;
1028
+ const squadraPrecedente = player.team;
887
1029
  player.role = roleId;
888
1030
  if (roleId === "spectator") player.team = null;
889
1031
  else if (player.team === null) player.team = this.squadraAutomatica();
890
1032
  if (this.richiediDati().status === "lobby") player.ready = false;
1033
+ if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
1034
+ this.rivediVoce();
1035
+ }
891
1036
  this.inviaGiocatori();
892
1037
  return null;
893
1038
  }
@@ -898,8 +1043,10 @@ var NucleoStanza = class _NucleoStanza {
898
1043
  if (player.role === "spectator") {
899
1044
  return { code: "spectator", message: "Spectators cannot join a team." };
900
1045
  }
1046
+ const squadraPrecedente = player.team;
901
1047
  player.team = team;
902
1048
  if (this.richiediDati().status === "lobby") player.ready = false;
1049
+ if (player.team !== squadraPrecedente) this.rivediVoce();
903
1050
  this.inviaGiocatori();
904
1051
  return null;
905
1052
  }
@@ -923,7 +1070,7 @@ var NucleoStanza = class _NucleoStanza {
923
1070
  erroreMinimi() {
924
1071
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
925
1072
  const attivi = connessi.filter((player) => player.role !== "spectator");
926
- if (attivi.length < this.manifest.players.min) {
1073
+ if (attivi.length < this.configurazione.players.min) {
927
1074
  return { code: "not_enough_players", message: "The room does not have enough players." };
928
1075
  }
929
1076
  if (connessi.some((player) => !player.ready)) {
@@ -942,6 +1089,43 @@ var NucleoStanza = class _NucleoStanza {
942
1089
  }
943
1090
  return null;
944
1091
  }
1092
+ async rivincita(player) {
1093
+ const dati = this.richiediDati();
1094
+ if (dati.status !== "finished") {
1095
+ this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1096
+ return;
1097
+ }
1098
+ if (player.role !== "spectator" && !player.ready) {
1099
+ player.ready = true;
1100
+ this.inviaGiocatori();
1101
+ await this.persistiEProgramma();
1102
+ return;
1103
+ }
1104
+ if (dati.hostId !== player.id) return;
1105
+ const attivi = dati.giocatori.filter((item) => item.connected && item.role !== "spectator");
1106
+ if (attivi.length < this.configurazione.players.min || attivi.some((item) => !item.ready)) {
1107
+ this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1108
+ return;
1109
+ }
1110
+ dati.status = this.configurazione.lobby ? "lobby" : "playing";
1111
+ dati.rivincitaFinoA = null;
1112
+ dati.result = null;
1113
+ dati.resultAt = null;
1114
+ dati.ultimoInputAt = this.adattatore.ora();
1115
+ for (const item of dati.giocatori) item.ready = false;
1116
+ await this.chiama(this.definizione.onRestart, this.room);
1117
+ await this.applicaAzioni();
1118
+ if (dati.status === "playing") {
1119
+ await this.chiama(this.definizione.onStart, this.room);
1120
+ }
1121
+ await this.concludiEvento();
1122
+ if (dati.status === "lobby" || dati.status === "playing") {
1123
+ this.inviaSnapshotTutti();
1124
+ this.inviaGiocatori();
1125
+ this.inviaStatus(this.adattatore.ora());
1126
+ }
1127
+ await this.persistiEProgramma();
1128
+ }
945
1129
  async avviaCountdown(player) {
946
1130
  const dati = this.richiediDati();
947
1131
  if (dati.hostId !== player.id) {
@@ -978,6 +1162,8 @@ var NucleoStanza = class _NucleoStanza {
978
1162
  const indice = dati.giocatori.findIndex((item) => item.id === player.id);
979
1163
  if (indice < 0) return;
980
1164
  dati.giocatori.splice(indice, 1);
1165
+ if (player.connessione !== null) this.frequenza.delete(player.connessione);
1166
+ this.rivediVoce();
981
1167
  this.pulisciGuadagni(player.id);
982
1168
  if (dati.hostId === player.id) this.assegnaHost();
983
1169
  if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
@@ -1016,6 +1202,7 @@ var NucleoStanza = class _NucleoStanza {
1016
1202
  const json = analizzaJson(payload);
1017
1203
  if (!json.ok) throw new TypeError("Schedule payload must be valid JSON.");
1018
1204
  const dati = this.richiediDati();
1205
+ if (dati.status === "finished" || dati.status === "ended") return;
1019
1206
  dati.timer.push({
1020
1207
  id: dati.prossimoTimerId++,
1021
1208
  at: this.adattatore.ora() + milliseconds,
@@ -1023,8 +1210,11 @@ var NucleoStanza = class _NucleoStanza {
1023
1210
  payload: json.valore
1024
1211
  });
1025
1212
  }
1213
+ giornata(ora = this.adattatore.ora()) {
1214
+ return this.adattatore.giorno?.(ora) ?? giornoUtc(ora);
1215
+ }
1026
1216
  accodaPunteggio(playerId, board, score, daily) {
1027
- if (!this.richiediDati().giocatori.some((player) => player.id === playerId)) {
1217
+ if (!this.richiediDati().giocatori.some((player2) => player2.id === playerId)) {
1028
1218
  throw new Error("Player not found.");
1029
1219
  }
1030
1220
  if (!CHIAVE.test(board)) {
@@ -1033,13 +1223,28 @@ var NucleoStanza = class _NucleoStanza {
1033
1223
  if (!Number.isSafeInteger(score) || score < 0) {
1034
1224
  throw new TypeError("Score must be a non-negative safe integer.");
1035
1225
  }
1036
- this.richiediDati().punteggi.push({ playerId, board, score, daily });
1226
+ const submittedAt = this.adattatore.ora();
1227
+ const day = daily ? this.giornata(submittedAt) : null;
1228
+ this.richiediDati().punteggi.push({
1229
+ playerId,
1230
+ board,
1231
+ score,
1232
+ daily,
1233
+ submittedAt,
1234
+ day
1235
+ });
1236
+ const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
1237
+ if (player.connected && player.connessione !== null) this.adattatore.invia(player.connessione, {
1238
+ t: "score-queued",
1239
+ score: { player: playerId, board, score, day, submittedAt }
1240
+ });
1037
1241
  this.broadcast({ t: "flush" });
1038
1242
  }
1039
- richiediFine(result) {
1243
+ richiediFine(result, rematch = false) {
1040
1244
  const json = analizzaJson(result);
1041
1245
  if (!json.ok) throw new TypeError("Game result must be valid JSON.");
1042
- this.fineRichiesta = json.valore;
1246
+ if (this.dati?.status === "ended" || this.dati?.status === "finished" && rematch) return;
1247
+ this.fineRichiesta = { result: json.valore, rematch };
1043
1248
  }
1044
1249
  async salva(key, value) {
1045
1250
  if (!CHIAVE.test(key)) {
@@ -1206,24 +1411,50 @@ var NucleoStanza = class _NucleoStanza {
1206
1411
  id: dati.id,
1207
1412
  seed: seedStanza(dati.id),
1208
1413
  status: dati.status,
1414
+ result: dati.result,
1209
1415
  mode: dati.mode,
1210
1416
  tick: dati.tick,
1211
1417
  tickRate: dati.tickRate,
1212
1418
  serverTime: this.adattatore.ora(),
1213
- host: dati.hostId
1419
+ host: dati.hostId,
1420
+ countdownAt: dati.countdownAt,
1421
+ configuration: {
1422
+ players: { ...this.configurazione.players },
1423
+ lobby: this.configurazione.lobby,
1424
+ persistent: this.manifest.persistent === true,
1425
+ requestRole: this.definizione.onRoleRequest !== void 0
1426
+ }
1214
1427
  };
1215
1428
  }
1216
1429
  inviaGiocatori() {
1217
- this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
1430
+ this.broadcast({ t: "players", players: this.giocatoriProtocollo(), host: this.richiediDati().hostId });
1218
1431
  }
1219
1432
  inviaStatus(at) {
1220
1433
  const dati = this.richiediDati();
1221
1434
  this.broadcast({
1222
1435
  t: "status",
1223
1436
  status: dati.status,
1437
+ host: dati.hostId,
1438
+ countdownAt: dati.countdownAt,
1224
1439
  at,
1225
- result: dati.status === "ended" ? dati.result : null
1440
+ result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
1441
+ });
1442
+ }
1443
+ inviaDiff() {
1444
+ const dati = this.richiediDati();
1445
+ const patch = creaDiff(dati.statoSincronizzato, dati.state);
1446
+ if (patch.length === 0 && this.tickRateSincronizzato === dati.tickRate) return;
1447
+ this.tickRateSincronizzato = dati.tickRate;
1448
+ this.broadcast({
1449
+ t: "state",
1450
+ tick: dati.tick,
1451
+ tickRate: dati.tickRate,
1452
+ base: dati.tickSincronizzato,
1453
+ serverTime: this.adattatore.ora(),
1454
+ patch
1226
1455
  });
1456
+ dati.statoSincronizzato = copiaJson(dati.state);
1457
+ dati.tickSincronizzato = dati.tick;
1227
1458
  }
1228
1459
  inviaSnapshotTutti() {
1229
1460
  const dati = this.richiediDati();
@@ -1232,8 +1463,10 @@ var NucleoStanza = class _NucleoStanza {
1232
1463
  dati.state = stato.valore;
1233
1464
  dati.statoSincronizzato = copiaJson(stato.valore);
1234
1465
  dati.tickSincronizzato = dati.tick;
1466
+ this.tickRateSincronizzato = dati.tickRate;
1235
1467
  this.broadcast({
1236
1468
  t: "snapshot",
1469
+ tickRate: dati.tickRate,
1237
1470
  tick: dati.tick,
1238
1471
  serverTime: this.adattatore.ora(),
1239
1472
  state: stato.valore
@@ -1244,7 +1477,7 @@ var NucleoStanza = class _NucleoStanza {
1244
1477
  try {
1245
1478
  await callback(...args);
1246
1479
  } catch {
1247
- this.fineRichiesta = { error: "callback_error" };
1480
+ this.fineRichiesta = { result: { error: "callback_error" }, rematch: false };
1248
1481
  }
1249
1482
  }
1250
1483
  async applicaAzioni() {
@@ -1263,7 +1496,7 @@ var NucleoStanza = class _NucleoStanza {
1263
1496
  if (this.fineRichiesta !== null && this.dati.status !== "ended") {
1264
1497
  const result = this.fineRichiesta;
1265
1498
  this.fineRichiesta = null;
1266
- await this.terminaInterna(result);
1499
+ await this.terminaInterna(result.result, result.rematch);
1267
1500
  }
1268
1501
  } finally {
1269
1502
  this.applicandoAzioni = false;
@@ -1279,7 +1512,7 @@ var NucleoStanza = class _NucleoStanza {
1279
1512
  this.dati.state = stato.valore;
1280
1513
  if ((this.dati.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
1281
1514
  this.dati.tick++;
1282
- this.inviaSnapshotTutti();
1515
+ this.inviaDiff();
1283
1516
  }
1284
1517
  }
1285
1518
  async verificaStato() {
@@ -1313,6 +1546,7 @@ var NucleoStanza = class _NucleoStanza {
1313
1546
  dati.voceGuadagni ??= {};
1314
1547
  const precedente = dati.voceGuadagni[playerId]?.[altroId] ?? 1;
1315
1548
  if (precedente === valore) return;
1549
+ if (precedente > 0 && valore === 0) this.rivediVoce();
1316
1550
  this.voceDaPersistire = true;
1317
1551
  if (valore === 1) {
1318
1552
  const riga = dati.voceGuadagni[playerId];
@@ -1330,6 +1564,9 @@ var NucleoStanza = class _NucleoStanza {
1330
1564
  this.voceGuadagniCambiati.set(playerId, cambi);
1331
1565
  return cambi;
1332
1566
  }
1567
+ rivediVoce() {
1568
+ if ((this.manifest.voice ?? "none") !== "none") this.adattatore.rivediVoce();
1569
+ }
1333
1570
  inviaGuadagniCambiati() {
1334
1571
  if (this.dati === null || this.voceGuadagniCambiati.size === 0) return;
1335
1572
  for (const [playerId, gains] of this.voceGuadagniCambiati) {
@@ -1358,33 +1595,42 @@ var NucleoStanza = class _NucleoStanza {
1358
1595
  dati.state = dati.statoSincronizzato;
1359
1596
  await this.terminaInterna({ error: code });
1360
1597
  }
1361
- async terminaInterna(result) {
1598
+ async terminaInterna(result, rematch = false) {
1362
1599
  const dati = this.richiediDati();
1363
1600
  if (dati.status === "ended") return;
1364
- dati.status = "ended";
1601
+ const giaFinita = dati.status === "finished";
1602
+ dati.status = rematch ? "finished" : "ended";
1603
+ dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1604
+ dati.timer = [];
1605
+ if (rematch) for (const player of dati.giocatori) player.ready = false;
1365
1606
  dati.countdownAt = null;
1366
1607
  dati.result = result;
1367
1608
  dati.resultAt = this.adattatore.ora();
1368
1609
  try {
1369
- await this.definizione.onEnd?.(this.room);
1610
+ if (!giaFinita) await this.definizione.onEnd?.(this.room);
1370
1611
  } catch {
1371
1612
  if (record(result)?.error === void 0) dati.result = { error: "callback_error" };
1613
+ dati.status = "ended";
1614
+ dati.rivincitaFinoA = null;
1372
1615
  }
1373
1616
  const stato = analizzaJson(dati.state);
1374
1617
  if (!stato.ok || stato.bytes > LIMITE_STATO) {
1375
1618
  dati.state = dati.statoSincronizzato;
1376
1619
  dati.result = { error: stato.ok ? "state_too_large" : "state_invalid" };
1620
+ dati.status = "ended";
1621
+ dati.rivincitaFinoA = null;
1377
1622
  } else if (stato.testo !== JSON.stringify(dati.statoSincronizzato)) {
1378
1623
  dati.tick++;
1379
1624
  dati.state = stato.valore;
1380
- this.inviaSnapshotTutti();
1625
+ this.inviaDiff();
1381
1626
  }
1382
1627
  const fine = { result: dati.result, at: dati.resultAt };
1383
- dati.fineInCoda = fine;
1628
+ if (dati.status === "ended") dati.fineInCoda = fine;
1629
+ if (dati.status === "finished") this.inviaGiocatori();
1384
1630
  this.inviaStatus(dati.resultAt);
1385
1631
  this.broadcast({ t: "flush" });
1386
1632
  for (const player of dati.giocatori) {
1387
- if (player.connected && player.connessione !== null) {
1633
+ if (dati.status === "ended" && player.connected && player.connessione !== null) {
1388
1634
  this.adattatore.chiudi(player.connessione, 4004, "room_ended");
1389
1635
  player.connected = false;
1390
1636
  player.connessione = null;
@@ -1399,7 +1645,7 @@ var NucleoStanza = class _NucleoStanza {
1399
1645
  if (dati.durateCpu.length > 50) dati.durateCpu.shift();
1400
1646
  dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
1401
1647
  if (dati.cpuOltreCento >= 20) {
1402
- this.fineRichiesta = { error: "cpu_budget" };
1648
+ this.fineRichiesta = { result: { error: "cpu_budget" }, rematch: false };
1403
1649
  return;
1404
1650
  }
1405
1651
  if (dati.durateCpu.length === 50) {
@@ -1430,6 +1676,11 @@ var NucleoStanza = class _NucleoStanza {
1430
1676
  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;
1431
1677
  }
1432
1678
  async terminaSeInattiva() {
1679
+ if (this.dati?.status === "finished") {
1680
+ if (this.adattatore.ora() < (this.dati.rivincitaFinoA ?? 0)) return false;
1681
+ await this.terminaInterna(this.dati.result);
1682
+ return true;
1683
+ }
1433
1684
  if (this.manifest.persistent === true) {
1434
1685
  if (this.dati?.status === "ended" || this.dati === null || this.adattatore.ora() < Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS) return false;
1435
1686
  await this.terminaInterna({ error: "expired" });
@@ -1449,6 +1700,7 @@ var NucleoStanza = class _NucleoStanza {
1449
1700
  this.serveTick() ? 1e3 / this.dati.tickRate : null
1450
1701
  );
1451
1702
  const prossime = [];
1703
+ if (this.dati.status === "finished") prossime.push(this.dati.rivincitaFinoA ?? this.adattatore.ora());
1452
1704
  if (this.manifest.persistent === true) {
1453
1705
  prossime.push(
1454
1706
  Math.max(this.dati.ultimoInputAt, this.dati.ultimoCambioStatoAt) + SCADENZA_PERSISTENTE_MS
@@ -1496,6 +1748,7 @@ var AdattatoreFacet = class {
1496
1748
  this.chiusure = [];
1497
1749
  this.sveglia = null;
1498
1750
  this.tick = false;
1751
+ this.voceRivedi = false;
1499
1752
  this.salvato = "";
1500
1753
  this.storage = new ArchivioFacet(archivio);
1501
1754
  this.tickRate = tickRate;
@@ -1539,6 +1792,9 @@ var AdattatoreFacet = class {
1539
1792
  misuraCpu() {
1540
1793
  return performance.now();
1541
1794
  }
1795
+ rivediVoce() {
1796
+ this.voceRivedi = true;
1797
+ }
1542
1798
  programmaTick(intervalloMs) {
1543
1799
  this.tick = intervalloMs !== null;
1544
1800
  if (intervalloMs !== null) this.tickRate = 1e3 / intervalloMs;
@@ -1554,11 +1810,13 @@ var AdattatoreFacet = class {
1554
1810
  sveglia: this.sveglia,
1555
1811
  tick: this.tick,
1556
1812
  tickRate: this.tickRate,
1557
- status
1813
+ status,
1814
+ voceRivedi: this.voceRivedi
1558
1815
  };
1559
1816
  this.frames = [];
1560
1817
  this.pubblici = [];
1561
1818
  this.chiusure = [];
1819
+ this.voceRivedi = false;
1562
1820
  return risultato;
1563
1821
  }
1564
1822
  };
@@ -1624,18 +1882,21 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1624
1882
  puoEntrare(identita) {
1625
1883
  return this.#serializza((nucleo) => nucleo.puoEntrare(identita));
1626
1884
  }
1885
+ puoAscoltare(listener, speakers) {
1886
+ return this.#serializza((nucleo) => nucleo.puoAscoltare(listener, speakers));
1887
+ }
1627
1888
  entra(identita, connessione) {
1628
1889
  return this.#esegui(async (nucleo) => {
1629
1890
  this.#adattatore.connessioni.add(connessione);
1630
1891
  await nucleo.entra(identita, connessione);
1631
1892
  });
1632
1893
  }
1633
- ricevi(connessione, testo) {
1894
+ ricevi(connessione, testo, limiteVerificato = false) {
1634
1895
  return this.#esegui(async (nucleo) => {
1635
1896
  if (new TextEncoder().encode(testo).byteLength > 16 * 1024) {
1636
- this.#adattatore.chiudi(connessione, 4008, "rate_limited");
1897
+ this.#adattatore.chiudi(connessione, 4009, "message_too_large");
1637
1898
  await nucleo.disconnetti(connessione);
1638
- } else await nucleo.ricevi(connessione, testo);
1899
+ } else await nucleo.ricevi(connessione, testo, limiteVerificato);
1639
1900
  });
1640
1901
  }
1641
1902
  disconnetti(connessione) {
@@ -1644,6 +1905,13 @@ function creaFacetStanza(DurableObject, definizione, manifest) {
1644
1905
  await nucleo.disconnetti(connessione);
1645
1906
  });
1646
1907
  }
1908
+ riconciliaConnessioni(connessioni) {
1909
+ return this.#esegui(async (nucleo) => {
1910
+ this.#adattatore.connessioni.clear();
1911
+ for (const connessione of connessioni) this.#adattatore.connessioni.add(connessione);
1912
+ await nucleo.riconciliaConnessioni();
1913
+ });
1914
+ }
1647
1915
  tick() {
1648
1916
  return this.#esegui((nucleo) => nucleo.eseguiTick());
1649
1917
  }