@caisual/kit 0.20.0 → 0.22.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 (46) hide show
  1. package/README.md +6 -9
  2. package/dist/host.d.ts +1 -0
  3. package/dist/host.js +169 -0
  4. package/dist/kit.js +2 -4
  5. package/dist/kit.js.map +4 -4
  6. package/dist/node.js +182 -457
  7. package/dist/runtime.js +236 -299
  8. package/dist/types/api.d.ts +2 -9
  9. package/dist/types/contracts/connessione.d.ts +1 -0
  10. package/dist/types/contracts/giornata.d.ts +1 -0
  11. package/dist/types/contracts/index.d.ts +3 -3
  12. package/dist/types/contracts/manifest.d.ts +6 -40
  13. package/dist/types/contracts/network-budget.d.ts +53 -0
  14. package/dist/types/contracts/versioni.d.ts +0 -1
  15. package/dist/types/crew/index.d.ts +4 -0
  16. package/dist/types/handshake.d.ts +0 -4
  17. package/dist/types/{overlay/host-bridge.d.ts → host/index.d.ts} +60 -38
  18. package/dist/types/index.d.ts +64 -90
  19. package/dist/types/node/index.d.ts +6 -27
  20. package/dist/types/protocollo.d.ts +1 -20
  21. package/dist/types/runtime/index.d.ts +8 -15
  22. package/dist/types/runtime/network-probe.d.ts +4 -0
  23. package/dist/types/server/index.d.ts +0 -20
  24. package/dist/types/stanza/nucleo.d.ts +12 -17
  25. package/dist/types/stanza/tipi.d.ts +7 -23
  26. package/dist/types/voce/index.d.ts +0 -1
  27. package/package.json +16 -19
  28. package/dist/overlay.d.ts +0 -1
  29. package/dist/overlay.js +0 -2326
  30. package/dist/overlay.js.map +0 -7
  31. package/dist/types/contracts/overlay-boards.d.ts +0 -3
  32. package/dist/types/contracts/overlay.d.ts +0 -240
  33. package/dist/types/contracts/replay.d.ts +0 -83
  34. package/dist/types/overlay/boards.d.ts +0 -48
  35. package/dist/types/overlay/bridge.d.ts +0 -3
  36. package/dist/types/overlay/i18n.d.ts +0 -146
  37. package/dist/types/overlay/index.d.ts +0 -10
  38. package/dist/types/overlay/locale.d.ts +0 -4
  39. package/dist/types/overlay/shortcut.d.ts +0 -4
  40. package/dist/types/overlay/styles.d.ts +0 -1
  41. package/dist/types/overlay/ui-model.d.ts +0 -53
  42. package/dist/types/overlay/ui.d.ts +0 -83
  43. package/dist/types/overlay/voice-panel.d.ts +0 -13
  44. package/dist/types/replay/index.d.ts +0 -65
  45. package/dist/types/session/index.d.ts +0 -50
  46. package/dist/types/session/resume.d.ts +0 -13
package/dist/node.js CHANGED
@@ -40,19 +40,12 @@ function risolviModalita(manifest, mode) {
40
40
  return { players: { ...scelta?.players ?? manifest.players }, lobby: scelta?.lobby ?? manifest.lobby };
41
41
  }
42
42
  function modalitaLocale(manifest, mode) {
43
- return mode !== null && manifest.modes.some((voce) => voce.id === mode && voce.execution === "local");
43
+ return risolviModalita(manifest, mode).players.max === 1;
44
44
  }
45
- var MASSIMO_SPETTATORI = 100;
46
- var RITARDO_SPETTATORI_MS = 3e3;
45
+ var MODE_LOCAL_MESSAGE = "Single-player modes run in the browser and have no room.";
47
46
 
48
- // ../contracts/src/replay.ts
49
- var REPLAY_MAX_BYTES = 10 * 1024 * 1024;
50
- var REPLAY_MAX_DURATION_MS = 30 * 60 * 1e3;
51
- var REPLAY_CHUNK_BYTES = 512 * 1024;
52
- var REPLAY_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
53
-
54
- // ../contracts/src/overlay.ts
55
- function validBoardDay(value) {
47
+ // ../contracts/src/giornata.ts
48
+ function validDay(value) {
56
49
  if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
57
50
  const at = Date.parse(`${value}T00:00:00Z`);
58
51
  return Number.isFinite(at) && new Date(at).toISOString().slice(0, 10) === value;
@@ -100,6 +93,83 @@ var LimiteMessaggiStanza = class {
100
93
  }
101
94
  };
102
95
 
96
+ // ../contracts/src/network-budget.ts
97
+ var NETWORK_BUDGET = Object.freeze({
98
+ recipientBytesPerSecond: 1e5,
99
+ roomBytesPerSecond: 2e6,
100
+ warningRatio: 0.8,
101
+ windowMs: 5e3,
102
+ blockingWindows: 3
103
+ });
104
+ var NETWORK_GUIDANCE = `Multiplayer budget: ${NETWORK_BUDGET.recipientBytesPerSecond / 1e3} kB/s per recipient, ${NETWORK_BUDGET.roomBytesPerSecond / 1e6} MB/s per room, before compression over 5 seconds. At 20 updates/s, budget ${NETWORK_BUDGET.recipientBytesPerSecond / 2e4} kB per update. Keep visual trails and animation on the client. Warnings start at 80%. Publication measures your server automatically; repeated excess in real matches blocks new rooms only. Game input: 30 messages/s per connection.`;
105
+ function networkLevel(measurement) {
106
+ const ratio = Math.max(
107
+ measurement.recipientBytesPerSecond / NETWORK_BUDGET.recipientBytesPerSecond,
108
+ measurement.roomBytesPerSecond / NETWORK_BUDGET.roomBytesPerSecond
109
+ );
110
+ return ratio > 1 ? "exceeded" : ratio >= NETWORK_BUDGET.warningRatio ? "warning" : "ok";
111
+ }
112
+ function networkMessage(measurement) {
113
+ return `Network ${networkLevel(measurement)}: ${measurement.recipientBytesPerSecond} B/s per recipient (limit ${NETWORK_BUDGET.recipientBytesPerSecond}), ${measurement.roomBytesPerSecond} B/s per room (limit ${NETWORK_BUDGET.roomBytesPerSecond}), before compression over 5 seconds. Send compact changes; keep visual trails and animation on the client. At 20 updates/s, budget ${NETWORK_BUDGET.recipientBytesPerSecond / 2e4} kB per update.`;
114
+ }
115
+ var NetworkMeter = class {
116
+ events = [];
117
+ head = 0;
118
+ recipients = /* @__PURE__ */ new Map();
119
+ total = 0;
120
+ peak = { recipientBytesPerSecond: 0, roomBytesPerSecond: 0 };
121
+ checkAt = null;
122
+ violations = 0;
123
+ blocked = false;
124
+ encoder = new TextEncoder();
125
+ record(recipient, text, now = Date.now()) {
126
+ this.advance(now);
127
+ const bytes = this.encoder.encode(text).byteLength;
128
+ this.events.push({ at: now, recipient, bytes });
129
+ const recipientBytes = (this.recipients.get(recipient) ?? 0) + bytes;
130
+ this.recipients.set(recipient, recipientBytes);
131
+ this.total += bytes;
132
+ this.peak.recipientBytesPerSecond = Math.max(this.peak.recipientBytesPerSecond, this.rate(recipientBytes));
133
+ this.peak.roomBytesPerSecond = Math.max(this.peak.roomBytesPerSecond, this.rate(this.total));
134
+ }
135
+ sample(now = Date.now()) {
136
+ this.advance(now);
137
+ return { current: this.current(), peak: { ...this.peak }, consecutiveViolations: this.violations, blocked: this.blocked };
138
+ }
139
+ rate(bytes) {
140
+ return Math.ceil(bytes * 1e3 / NETWORK_BUDGET.windowMs);
141
+ }
142
+ current() {
143
+ let maximum = 0;
144
+ for (const bytes of this.recipients.values()) maximum = Math.max(maximum, bytes);
145
+ return { recipientBytesPerSecond: this.rate(maximum), roomBytesPerSecond: this.rate(this.total) };
146
+ }
147
+ advance(now) {
148
+ this.checkAt ??= now;
149
+ this.expire(now - NETWORK_BUDGET.windowMs, false);
150
+ if (now - this.checkAt >= NETWORK_BUDGET.windowMs) {
151
+ if (now - this.checkAt >= NETWORK_BUDGET.windowMs * 2) this.violations = 0;
152
+ this.violations = networkLevel(this.current()) === "exceeded" ? this.violations + 1 : 0;
153
+ this.blocked ||= this.violations >= NETWORK_BUDGET.blockingWindows;
154
+ this.checkAt = now;
155
+ }
156
+ this.expire(now - NETWORK_BUDGET.windowMs, true);
157
+ if (this.head > 1024) {
158
+ this.events = this.events.slice(this.head);
159
+ this.head = 0;
160
+ }
161
+ }
162
+ expire(cutoff, inclusive) {
163
+ while (this.head < this.events.length && (inclusive ? this.events[this.head].at <= cutoff : this.events[this.head].at < cutoff)) {
164
+ const event = this.events[this.head++];
165
+ this.total -= event.bytes;
166
+ const remaining = this.recipients.get(event.recipient) - event.bytes;
167
+ if (remaining === 0) this.recipients.delete(event.recipient);
168
+ else this.recipients.set(event.recipient, remaining);
169
+ }
170
+ }
171
+ };
172
+
103
173
  // src/daily.ts
104
174
  function prossimaMezzanotteUtc(ora) {
105
175
  return (Math.floor(ora / 864e5) + 1) * 864e5;
@@ -181,10 +251,10 @@ function visitaDiff(prima, dopo, path, patch) {
181
251
  }
182
252
  if (isObject(prima) && isObject(dopo)) {
183
253
  for (const key of Object.keys(prima)) {
184
- if (!(key in dopo)) patch.push({ op: "del", path: [...path, key] });
254
+ if (!Object.hasOwn(dopo, key)) patch.push({ op: "del", path: [...path, key] });
185
255
  }
186
256
  for (const [key, value] of Object.entries(dopo)) {
187
- if (!(key in prima)) patch.push({ op: "set", path: [...path, key], value });
257
+ if (!Object.hasOwn(prima, key)) patch.push({ op: "set", path: [...path, key], value });
188
258
  else visitaDiff(prima[key], value, [...path, key], patch);
189
259
  }
190
260
  return;
@@ -345,13 +415,10 @@ var PREFISSO_SAVE = "save:";
345
415
  var LIMITE_FRAME = MASSIMO_BYTE_FRAME_STANZA;
346
416
  var LIMITE_STATO = 512 * 1024;
347
417
  var LIMITE_SAVE = 256 * 1024;
348
- var LIMITE_DEPOSITO = 256 * 1024;
349
- var LIMITE_OPERAZIONI_DEPOSITO = 120;
350
418
  var GRAZIA_MS = 6e4;
351
419
  var STANZA_VUOTA_MS = 5 * 6e4;
352
420
  var ATTESA_RIVINCITA_MS = 2 * 6e4;
353
421
  var COUNTDOWN_MS = 3e3;
354
- var GRAZIA_GIORNALIERA_MS = 10 * 6e4;
355
422
  var RIPOSO_TICK_MS = 3e4;
356
423
  var INATTIVITA_MS = 10 * 6e4;
357
424
  var SCADENZA_PERSISTENTE_MS = 30 * 24 * 60 * 6e4;
@@ -360,16 +427,7 @@ function scadenzaInattivita(ultimoEvento, durata) {
360
427
  return Math.ceil((ultimoEvento + durata) / BLOCCO_INATTIVITA_MS) * BLOCCO_INATTIVITA_MS;
361
428
  }
362
429
  var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
363
- var PREFISSO_CHIAVE = /^[a-z0-9_-]{0,32}$/;
364
430
  var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
365
- var CODICI_DEPOSITO = /* @__PURE__ */ new Set([
366
- "store_invalid_key",
367
- "store_too_large",
368
- "store_full",
369
- "store_not_integer",
370
- "store_unavailable",
371
- "store_rate_limited"
372
- ]);
373
431
  function record(value) {
374
432
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
375
433
  }
@@ -407,7 +465,6 @@ var NucleoStanza = class _NucleoStanza {
407
465
  this.adattatore = adattatore;
408
466
  this.dati = null;
409
467
  this.frequenza = new LimiteMessaggiStanza();
410
- this.frequenzaDeposito = [];
411
468
  this.kickRichiesti = /* @__PURE__ */ new Set();
412
469
  this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
413
470
  this.fineRichiesta = null;
@@ -458,11 +515,6 @@ var NucleoStanza = class _NucleoStanza {
458
515
  get players() {
459
516
  return nucleo.richiediDati().giocatori.map(copiaGiocatore);
460
517
  },
461
- get host() {
462
- const dati = nucleo.richiediDati();
463
- const host = dati.giocatori.find((player) => player.id === dati.hostId);
464
- return host === void 0 ? null : copiaGiocatore(host);
465
- },
466
518
  broadcast(message) {
467
519
  nucleo.broadcastCreatore(message);
468
520
  },
@@ -487,35 +539,9 @@ var NucleoStanza = class _NucleoStanza {
487
539
  load(key) {
488
540
  return nucleo.caricaSave(key);
489
541
  },
490
- shared: {
491
- get(key) {
492
- return nucleo.leggiDeposito(key);
493
- },
494
- set(key, value) {
495
- return nucleo.scriviDeposito(key, value);
496
- },
497
- delete(key) {
498
- return nucleo.eliminaDeposito(key);
499
- },
500
- list(prefix) {
501
- return nucleo.elencaDeposito(prefix);
502
- },
503
- increment(key, amount = 1) {
504
- return nucleo.incrementaDeposito(key, amount);
505
- }
506
- },
507
542
  schedule(milliseconds, handler, payload) {
508
543
  nucleo.pianifica(milliseconds, handler, payload);
509
544
  },
510
- board: {
511
- submit(player, board, score, options = {}) {
512
- if (typeof board === "number") {
513
- const active = nucleo.richiediDati().giocatori.filter((p) => p.role !== "spectator");
514
- if (nucleo.configurazione.players.max !== 1 || active.length !== 1) throw erroreConCodice("board_player_required", "Specify the player when submitting a multiplayer score.");
515
- nucleo.accodaPunteggio(active[0].id, player, board, typeof score === "object" ? score : {});
516
- } else nucleo.accodaPunteggio(idGiocatore(player), board, score, options);
517
- }
518
- },
519
545
  daily,
520
546
  time: { now: () => nucleo.adattatore.ora() },
521
547
  voice: {
@@ -542,9 +568,11 @@ var NucleoStanza = class _NucleoStanza {
542
568
  const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
543
569
  const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
544
570
  if (salvato !== void 0) {
571
+ if (modalitaLocale(manifest, salvato.mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE), { code: "mode_local" });
545
572
  nucleo.dati = salvato;
546
573
  nucleo.tickRateSincronizzato = salvato.tickRate;
547
- const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0;
574
+ const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0 || salvato.daily === void 0 || salvato.origin === void 0;
575
+ salvato.origin ??= "player";
548
576
  salvato.daily ??= nucleo.contestoGiornaliero();
549
577
  salvato.ultimoInputAt ??= adattatore.ora();
550
578
  salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
@@ -570,13 +598,13 @@ var NucleoStanza = class _NucleoStanza {
570
598
  get esiste() {
571
599
  return this.dati !== null;
572
600
  }
573
- async crea(id, mode, _creator) {
601
+ async crea(id, mode, _creator, origin = "player") {
574
602
  if (this.dati !== null) return false;
575
- risolviModalita(this.manifest, mode);
576
- if (modalitaLocale(this.manifest, mode)) throw new Error("Local modes cannot create rooms.");
603
+ if (modalitaLocale(this.manifest, mode)) throw Object.assign(new Error(MODE_LOCAL_MESSAGE), { code: "mode_local" });
577
604
  const ora = this.adattatore.ora();
578
605
  this.dati = {
579
606
  versione: 1,
607
+ origin,
580
608
  daily: this.contestoGiornaliero(ora),
581
609
  id,
582
610
  mode,
@@ -587,13 +615,11 @@ var NucleoStanza = class _NucleoStanza {
587
615
  ultimoCambioStatoAt: ora,
588
616
  state: {},
589
617
  giocatori: [],
590
- hostId: null,
591
618
  result: null,
592
619
  resultAt: null,
593
620
  countdownAt: null,
594
621
  timer: [],
595
622
  prossimoTimerId: 1,
596
- punteggi: [],
597
623
  fineInCoda: null,
598
624
  vuotaDa: ora,
599
625
  cancellaDopoFlush: false,
@@ -621,12 +647,14 @@ var NucleoStanza = class _NucleoStanza {
621
647
  }
622
648
  get configurazione() {
623
649
  const mode = risolviModalita(this.manifest, this.dati?.mode ?? null);
624
- return mode.players.max === 1 ? { ...mode, lobby: false } : mode;
650
+ return this.dati?.origin === "matchmaking" ? mode : { ...mode, lobby: true };
625
651
  }
626
652
  info(playerId) {
627
653
  if (this.dati === null) return null;
628
654
  return {
629
655
  roomId: this.dati.id,
656
+ origin: this.dati.origin,
657
+ lobby: this.configurazione.lobby,
630
658
  status: this.dati.status,
631
659
  players: this.manifest.persistent === true ? this.dati.giocatori.length : this.dati.giocatori.filter(
632
660
  (player) => player.connected || player.graziaFinoA !== null
@@ -660,7 +688,7 @@ var NucleoStanza = class _NucleoStanza {
660
688
  if (ascoltatore === void 0 || speaker === void 0 || listener === speakerId) {
661
689
  return { ok: false, reason: "unknown" };
662
690
  }
663
- if (mode === "team" && ascoltatore.role !== "spectator" && ascoltatore.team !== speaker.team) {
691
+ if (mode === "team" && ascoltatore.team !== speaker.team) {
664
692
  return { ok: false, reason: "team" };
665
693
  }
666
694
  if ((dati.voceGuadagni?.[listener]?.[speakerId] ?? 1) <= 0) {
@@ -674,12 +702,15 @@ var NucleoStanza = class _NucleoStanza {
674
702
  if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
675
703
  const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
676
704
  if (esistente !== void 0) return { ok: true };
677
- if (this.configurazione.lobby && !["lobby", "finished"].includes(this.dati.status)) {
705
+ if (this.configurazione.lobby && !["lobby", "countdown", "finished"].includes(this.dati.status)) {
678
706
  return { ok: false, code: "room_playing" };
679
707
  }
680
708
  if (this.dati.giocatori.length >= this.configurazione.players.max) {
681
709
  return { ok: false, code: "room_full" };
682
710
  }
711
+ if (this.manifest.roles.length > 0 && this.ruoloAutomatico() === null) {
712
+ return { ok: false, code: "room_full" };
713
+ }
683
714
  return { ok: true };
684
715
  }
685
716
  async entra(identity, connessione) {
@@ -719,7 +750,6 @@ var NucleoStanza = class _NucleoStanza {
719
750
  player.connessione = connessione;
720
751
  player.seq = 0;
721
752
  }
722
- dati.hostId ??= player.id;
723
753
  dati.vuotaDa = null;
724
754
  dati.ultimoInputAt = ora;
725
755
  const primaConnessione = !this.configurazione.lobby && dati.status === "lobby";
@@ -736,7 +766,6 @@ var NucleoStanza = class _NucleoStanza {
736
766
  }
737
767
  if (primaConnessione) {
738
768
  await this.chiama(this.definizione.onStart, this.room);
739
- this.iniziaReplay();
740
769
  this.inviaStatus(ora);
741
770
  }
742
771
  await this.concludiEvento();
@@ -744,6 +773,7 @@ var NucleoStanza = class _NucleoStanza {
744
773
  this.inviaWelcome(player);
745
774
  this.inviaSnapshotTutti();
746
775
  this.inviaGiocatori();
776
+ this.rivalutaAvvio();
747
777
  }
748
778
  await this.persistiEProgramma();
749
779
  return { ok: true };
@@ -757,10 +787,9 @@ var NucleoStanza = class _NucleoStanza {
757
787
  player.connected = false;
758
788
  player.connessione = null;
759
789
  player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
760
- if (this.dati.status === "finished" || this.manifest.persistent === true && this.dati.status === "lobby") player.ready = false;
790
+ if (this.dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(this.dati.status)) player.ready = false;
761
791
  this.frequenza.delete(connessione);
762
- if (this.dati.hostId === player.id) this.assegnaHost();
763
- this.verificaCountdown();
792
+ this.rivalutaAvvio();
764
793
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
765
794
  await this.concludiEvento();
766
795
  this.inviaGiocatori();
@@ -827,6 +856,7 @@ var NucleoStanza = class _NucleoStanza {
827
856
  this.dati.ultimoInputAt = ora;
828
857
  player.ready = message.ready;
829
858
  this.inviaGiocatori();
859
+ this.rivalutaAvvio();
830
860
  await this.persistiEProgramma();
831
861
  return;
832
862
  }
@@ -868,12 +898,6 @@ var NucleoStanza = class _NucleoStanza {
868
898
  await this.persistiEProgramma();
869
899
  return;
870
900
  }
871
- if (message.t === "start") {
872
- if (!this.inLobby(player)) return;
873
- this.dati.ultimoInputAt = ora;
874
- await this.avviaCountdown(player);
875
- return;
876
- }
877
901
  if (message.t === "msg") {
878
902
  if (!Number.isSafeInteger(message.seq) || message.seq < 1) {
879
903
  await this.messaggioErrato(player);
@@ -887,11 +911,6 @@ var NucleoStanza = class _NucleoStanza {
887
911
  return;
888
912
  }
889
913
  player.seq = seq;
890
- if (player.role === "spectator") {
891
- this.inviaErrore(player, "spectator", "Spectators cannot send game input.");
892
- await this.persistiEProgramma();
893
- return;
894
- }
895
914
  if (this.dati.status === "finished") return;
896
915
  this.dati.ultimoInputAt = ora;
897
916
  await this.chiama(
@@ -956,7 +975,6 @@ var NucleoStanza = class _NucleoStanza {
956
975
  this.dati.ultimoInputAt = ora;
957
976
  this.dati.countdownAt = null;
958
977
  await this.chiama(this.definizione.onStart, this.room);
959
- this.iniziaReplay();
960
978
  this.inviaStatus(ora);
961
979
  }
962
980
  }
@@ -979,13 +997,29 @@ var NucleoStanza = class _NucleoStanza {
979
997
  await this.concludiEvento();
980
998
  await this.persistiEProgramma();
981
999
  }
1000
+ async preparaFlush() {
1001
+ const dati = this.richiediDati();
1002
+ if (dati.flushInAttesa !== void 0) {
1003
+ await this.persistiEProgramma();
1004
+ return dati.flushInAttesa;
1005
+ }
1006
+ if (dati.fineInCoda === null) return null;
1007
+ dati.flushInAttesa = { id: crypto.randomUUID(), ended: dati.fineInCoda };
1008
+ dati.fineInCoda = null;
1009
+ await this.persistiEProgramma();
1010
+ return dati.flushInAttesa;
1011
+ }
1012
+ async confermaFlush(id) {
1013
+ const dati = this.richiediDati();
1014
+ if (dati.flushInAttesa?.id !== id) return;
1015
+ delete dati.flushInAttesa;
1016
+ await this.persistiEProgramma();
1017
+ }
982
1018
  async flush() {
983
1019
  const dati = this.richiediDati();
984
1020
  const esito = {
985
- scores: dati.punteggi.map((score) => ({ ...score })),
986
1021
  ended: dati.fineInCoda === null ? null : { result: dati.fineInCoda.result, at: dati.fineInCoda.at }
987
1022
  };
988
- dati.punteggi = [];
989
1023
  dati.fineInCoda = null;
990
1024
  if (dati.cancellaDopoFlush && dati.status === "ended") {
991
1025
  const chiavi = await this.adattatore.storage.list();
@@ -1010,13 +1044,12 @@ var NucleoStanza = class _NucleoStanza {
1010
1044
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
1011
1045
  player.connessione = null;
1012
1046
  player.graziaFinoA = ora + GRAZIA_MS;
1013
- if (dati.status === "finished" || this.manifest.persistent === true && dati.status === "lobby") player.ready = false;
1047
+ if (dati.status === "finished" || this.manifest.persistent === true && ["lobby", "countdown"].includes(dati.status)) player.ready = false;
1014
1048
  disconnessi.push(player);
1015
1049
  }
1016
1050
  }
1017
1051
  if (disconnessi.length > 0) {
1018
- this.assegnaHost();
1019
- this.verificaCountdown();
1052
+ this.rivalutaAvvio();
1020
1053
  for (const player of disconnessi) {
1021
1054
  await this.chiama(this.definizione.onConnection, this.room, copiaGiocatore(player), false);
1022
1055
  }
@@ -1039,7 +1072,7 @@ var NucleoStanza = class _NucleoStanza {
1039
1072
  const mancaB = countB < b.min ? 0 : 1;
1040
1073
  return mancaA - mancaB || countA - countB;
1041
1074
  });
1042
- return candidati[0]?.id ?? "spectator";
1075
+ return candidati[0]?.id ?? null;
1043
1076
  }
1044
1077
  squadraAutomatica() {
1045
1078
  if (this.manifest.teams === null) return null;
@@ -1062,39 +1095,37 @@ var NucleoStanza = class _NucleoStanza {
1062
1095
  }
1063
1096
  cambiaRuolo(player, roleId) {
1064
1097
  const ruolo = this.manifest.roles.find((item) => item.id === roleId);
1065
- if (ruolo === void 0 && roleId !== "spectator") {
1098
+ if (ruolo === void 0) {
1066
1099
  return { code: "invalid_role", message: "This role does not exist." };
1067
1100
  }
1068
1101
  const occupati = this.richiediDati().giocatori.filter(
1069
1102
  (item) => item.id !== player.id && item.role === roleId
1070
1103
  ).length;
1071
- if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
1104
+ if (ruolo.max !== void 0 && occupati >= ruolo.max) {
1072
1105
  return { code: "role_full", message: "This role is full." };
1073
1106
  }
1074
1107
  const ruoloPrecedente = player.role;
1075
1108
  const squadraPrecedente = player.team;
1076
1109
  player.role = roleId;
1077
- if (roleId === "spectator") player.team = null;
1078
- else if (player.team === null) player.team = this.squadraAutomatica();
1110
+ if (player.team === null) player.team = this.squadraAutomatica();
1079
1111
  if (this.richiediDati().status === "lobby") player.ready = false;
1080
1112
  if (player.role !== ruoloPrecedente || player.team !== squadraPrecedente) {
1081
1113
  this.rivediVoce();
1082
1114
  }
1083
1115
  this.inviaGiocatori();
1116
+ this.rivalutaAvvio();
1084
1117
  return null;
1085
1118
  }
1086
1119
  cambiaSquadra(player, team) {
1087
1120
  if (this.manifest.teams === null || !Number.isInteger(team) || team < 1 || team > this.manifest.teams.max) {
1088
1121
  return { code: "invalid_team", message: "This team does not exist." };
1089
1122
  }
1090
- if (player.role === "spectator") {
1091
- return { code: "spectator", message: "Spectators cannot join a team." };
1092
- }
1093
1123
  const squadraPrecedente = player.team;
1094
1124
  player.team = team;
1095
1125
  if (this.richiediDati().status === "lobby") player.ready = false;
1096
1126
  if (player.team !== squadraPrecedente) this.rivediVoce();
1097
1127
  this.inviaGiocatori();
1128
+ this.rivalutaAvvio();
1098
1129
  return null;
1099
1130
  }
1100
1131
  impostaRuoloDalServer(playerId, roleId) {
@@ -1116,21 +1147,20 @@ var NucleoStanza = class _NucleoStanza {
1116
1147
  }
1117
1148
  erroreMinimi(saltaPronti = false) {
1118
1149
  const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
1119
- const attivi = connessi.filter((player) => player.role !== "spectator");
1120
- if (attivi.length < this.configurazione.players.min) {
1150
+ if (connessi.length < this.configurazione.players.min) {
1121
1151
  return { code: "not_enough_players", message: "The room does not have enough players." };
1122
1152
  }
1123
1153
  if (!saltaPronti && connessi.some((player) => !player.ready)) {
1124
1154
  return { code: "players_not_ready", message: "Every connected player must be ready." };
1125
1155
  }
1126
1156
  for (const role of this.manifest.roles) {
1127
- if (attivi.filter((player) => player.role === role.id).length < role.min) {
1157
+ if (connessi.filter((player) => player.role === role.id).length < role.min) {
1128
1158
  return { code: "role_minimum", message: `Role ${role.id} does not meet its minimum.` };
1129
1159
  }
1130
1160
  }
1131
1161
  if (this.manifest.teams !== null) {
1132
- const squadre = new Set(attivi.map((player) => player.team).filter((team) => team !== null));
1133
- if (attivi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
1162
+ const squadre = new Set(connessi.map((player) => player.team).filter((team) => team !== null));
1163
+ if (connessi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
1134
1164
  return { code: "team_minimum", message: "The room does not have enough teams." };
1135
1165
  }
1136
1166
  }
@@ -1142,32 +1172,20 @@ var NucleoStanza = class _NucleoStanza {
1142
1172
  this.inviaErrore(player, "rematch_unavailable", "This room is not waiting for a rematch.");
1143
1173
  return;
1144
1174
  }
1145
- if (this.configurazione.players.max === 1) {
1146
- await this.avviaRivincita();
1147
- return;
1148
- }
1149
- if (player.role !== "spectator" && !player.ready) {
1150
- player.ready = true;
1151
- this.inviaGiocatori();
1152
- if (dati.rivincita?.autoStart && this.prontiRivincita()) await this.avviaRivincita();
1153
- else await this.persistiEProgramma();
1154
- return;
1155
- }
1156
- if (dati.hostId !== player.id) return;
1157
- if (!this.prontiRivincita(dati.rivincita?.autoStart === true)) {
1158
- this.inviaErrore(player, "players_not_ready", "Enough connected players must be ready for the rematch.");
1159
- return;
1160
- }
1161
- await this.avviaRivincita();
1175
+ if (player.ready) return;
1176
+ player.ready = true;
1177
+ this.inviaGiocatori();
1178
+ if (this.prontiRivincita()) await this.avviaRivincita();
1179
+ else await this.persistiEProgramma();
1162
1180
  }
1163
- prontiRivincita(anticipata = false) {
1164
- const attivi = this.richiediDati().giocatori.filter((item) => item.connected && item.role !== "spectator");
1165
- return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && (anticipata || attivi.every((item) => item.ready));
1181
+ prontiRivincita() {
1182
+ const attivi = this.richiediDati().giocatori.filter((item) => item.connected);
1183
+ return attivi.filter((item) => item.ready).length >= this.configurazione.players.min && attivi.every((item) => item.ready);
1166
1184
  }
1167
1185
  async avviaRivincita() {
1168
- const dati = this.richiediDati(), solo = this.configurazione.players.max === 1;
1169
- const keepSetup = dati.rivincita?.keepSetup === true && !solo;
1170
- dati.status = solo ? "playing" : keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
1186
+ const dati = this.richiediDati();
1187
+ const keepSetup = dati.rivincita?.keepSetup === true;
1188
+ dati.status = keepSetup ? "countdown" : this.configurazione.lobby ? "lobby" : "playing";
1171
1189
  dati.countdownRivincita = keepSetup;
1172
1190
  dati.countdownAt = keepSetup ? this.adattatore.ora() + COUNTDOWN_MS : null;
1173
1191
  dati.rivincitaFinoA = null;
@@ -1181,7 +1199,6 @@ var NucleoStanza = class _NucleoStanza {
1181
1199
  await this.applicaAzioni();
1182
1200
  if (dati.status === "playing") {
1183
1201
  await this.chiama(this.definizione.onStart, this.room);
1184
- this.iniziaReplay();
1185
1202
  }
1186
1203
  await this.concludiEvento();
1187
1204
  if (dati.status === "lobby" || dati.status === "playing" || dati.status === "countdown") {
@@ -1191,29 +1208,25 @@ var NucleoStanza = class _NucleoStanza {
1191
1208
  }
1192
1209
  await this.persistiEProgramma();
1193
1210
  }
1194
- async avviaCountdown(player) {
1211
+ /**
1212
+ * Nessuno ospita e nessuno preme "inizia": appena tutti i connessi sono pronti e i
1213
+ * minimi di giocatori, ruoli e squadre sono rispettati parte il countdown; se la
1214
+ * condizione cade durante il countdown si torna in lobby.
1215
+ */
1216
+ rivalutaAvvio() {
1195
1217
  const dati = this.richiediDati();
1196
- if (dati.hostId !== player.id) {
1197
- this.inviaErrore(player, "not_host", "Only the host can start the game.");
1198
- return;
1199
- }
1200
- const errore = this.erroreMinimi();
1201
- if (errore !== null) {
1202
- this.inviaErrore(player, errore.code, errore.message);
1218
+ if (dati.status === "countdown") {
1219
+ if (this.erroreMinimi(dati.countdownRivincita) === null) return;
1220
+ dati.status = "lobby";
1221
+ dati.countdownAt = null;
1222
+ this.inviaStatus(this.adattatore.ora());
1203
1223
  return;
1204
1224
  }
1225
+ if (dati.status !== "lobby" || this.erroreMinimi() !== null) return;
1205
1226
  dati.status = "countdown";
1206
1227
  dati.countdownRivincita = false;
1207
1228
  dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
1208
1229
  this.inviaStatus(dati.countdownAt);
1209
- await this.persistiEProgramma();
1210
- }
1211
- verificaCountdown() {
1212
- const dati = this.richiediDati();
1213
- if (dati.status !== "countdown" || this.erroreMinimi(dati.countdownRivincita) === null) return;
1214
- dati.status = "lobby";
1215
- dati.countdownAt = null;
1216
- this.inviaStatus(this.adattatore.ora());
1217
1230
  }
1218
1231
  async messaggioErrato(player) {
1219
1232
  await this.chiudiConnessione(player, 4009, "bad_message");
@@ -1231,7 +1244,6 @@ var NucleoStanza = class _NucleoStanza {
1231
1244
  if (player.connessione !== null) this.frequenza.delete(player.connessione);
1232
1245
  this.rivediVoce();
1233
1246
  this.pulisciGuadagni(player.id);
1234
- if (dati.hostId === player.id) this.assegnaHost();
1235
1247
  if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
1236
1248
  await this.chiama(
1237
1249
  this.definizione.onLeave,
@@ -1239,12 +1251,7 @@ var NucleoStanza = class _NucleoStanza {
1239
1251
  copiaGiocatore({ ...player, connected: false, connessione: null }),
1240
1252
  reason
1241
1253
  );
1242
- this.verificaCountdown();
1243
- }
1244
- assegnaHost() {
1245
- const dati = this.richiediDati();
1246
- const host = dati.giocatori.filter((player) => player.connected).sort((a, b) => a.entratoAt - b.entratoAt)[0];
1247
- dati.hostId = host?.id ?? null;
1254
+ this.rivalutaAvvio();
1248
1255
  }
1249
1256
  async eseguiTimer(timer) {
1250
1257
  const value = this.definizione[timer.handler];
@@ -1283,45 +1290,6 @@ var NucleoStanza = class _NucleoStanza {
1283
1290
  const day = this.giornata(ora);
1284
1291
  return { day, seed: seedGiornata(this.manifest.id, day), expiresAt: prossimaMezzanotteUtc(ora) };
1285
1292
  }
1286
- accodaPunteggio(playerId, board, score, options) {
1287
- if (!this.richiediDati().giocatori.some((player2) => player2.id === playerId)) {
1288
- throw new Error("Player not found.");
1289
- }
1290
- if (!CHIAVE.test(board)) {
1291
- throw new TypeError("Board names must use lowercase letters, numbers, underscores, or hyphens.");
1292
- }
1293
- if (!Number.isSafeInteger(score) || score < 0) {
1294
- throw new TypeError("Score must be a non-negative safe integer.");
1295
- }
1296
- const submittedAt = this.adattatore.ora();
1297
- const daily = options.daily === true || options.day !== void 0;
1298
- let day = daily ? this.giornata(submittedAt) : null;
1299
- const start = this.manifest.boards?.[board]?.day === "start";
1300
- if (options.day !== void 0 && (!start || options.daily === false)) {
1301
- throw erroreConCodice("board_day_policy", "An explicit day requires a start-day board and a daily score.");
1302
- }
1303
- if (daily && start) {
1304
- const run = this.richiediDati().daily;
1305
- if (options.day === void 0) throw erroreConCodice("board_day_required", "Submit the daily score with room.daily.day.");
1306
- if (options.day !== run.day) throw erroreConCodice("board_day_mismatch", "The score day must match room.daily.day.");
1307
- if (submittedAt > run.expiresAt + GRAZIA_GIORNALIERA_MS) throw erroreConCodice("board_day_expired", "The starting day grace period has expired.");
1308
- day = run.day;
1309
- }
1310
- this.richiediDati().punteggi.push({
1311
- playerId,
1312
- board,
1313
- score,
1314
- daily,
1315
- submittedAt,
1316
- day
1317
- });
1318
- const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
1319
- if (player.connected && player.connessione !== null) this.adattatore.invia(player.connessione, {
1320
- t: "score-queued",
1321
- score: { player: playerId, board, score, day, submittedAt }
1322
- });
1323
- this.broadcast({ t: "flush" });
1324
- }
1325
1293
  richiediFine(result, rematch = false) {
1326
1294
  const json = analizzaJson(result);
1327
1295
  if (!json.ok) throw new TypeError("Game result must be valid JSON.");
@@ -1349,91 +1317,6 @@ var NucleoStanza = class _NucleoStanza {
1349
1317
  if (!json.ok) throw new Error("The saved value is invalid.");
1350
1318
  return json.valore;
1351
1319
  }
1352
- verificaChiaveDeposito(key) {
1353
- if (typeof key !== "string" || !CHIAVE.test(key)) {
1354
- throw erroreConCodice(
1355
- "store_invalid_key",
1356
- "Shared store keys must use lowercase letters, numbers, underscores, or hyphens."
1357
- );
1358
- }
1359
- }
1360
- verificaPrefissoDeposito(prefix) {
1361
- if (prefix !== void 0 && (typeof prefix !== "string" || !PREFISSO_CHIAVE.test(prefix))) {
1362
- throw erroreConCodice(
1363
- "store_invalid_key",
1364
- "Shared store prefixes may contain lowercase letters, numbers, underscores, or hyphens."
1365
- );
1366
- }
1367
- }
1368
- contaOperazioneDeposito() {
1369
- const ora = this.adattatore.ora();
1370
- this.frequenzaDeposito = this.frequenzaDeposito.filter((at) => ora - at < 6e4);
1371
- if (this.frequenzaDeposito.length >= LIMITE_OPERAZIONI_DEPOSITO) {
1372
- throw erroreConCodice(
1373
- "store_rate_limited",
1374
- "The shared store allows at most 120 operations per minute for each room."
1375
- );
1376
- }
1377
- this.frequenzaDeposito.push(ora);
1378
- }
1379
- async usaDeposito(operazione) {
1380
- this.contaOperazioneDeposito();
1381
- const deposito = this.adattatore.deposito;
1382
- if (deposito === null) {
1383
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1384
- }
1385
- try {
1386
- return await operazione(deposito);
1387
- } catch (cause) {
1388
- const code = cause instanceof Error ? cause.code : void 0;
1389
- if (typeof code === "string" && CODICI_DEPOSITO.has(code)) throw cause;
1390
- throw erroreConCodice("store_unavailable", "The shared store is unavailable.");
1391
- }
1392
- }
1393
- async leggiDeposito(key) {
1394
- this.verificaChiaveDeposito(key);
1395
- const value = await this.usaDeposito((deposito) => deposito.get(key));
1396
- if (value === null) return null;
1397
- try {
1398
- return JSON.parse(JSON.stringify(value));
1399
- } catch {
1400
- throw erroreConCodice("store_unavailable", "The shared store returned invalid data.");
1401
- }
1402
- }
1403
- async scriviDeposito(key, value) {
1404
- this.verificaChiaveDeposito(key);
1405
- const json = analizzaJson(value);
1406
- if (!json.ok || json.bytes > LIMITE_DEPOSITO) {
1407
- throw erroreConCodice(
1408
- "store_too_large",
1409
- "Shared store values must be valid JSON of at most 262144 bytes."
1410
- );
1411
- }
1412
- await this.usaDeposito((deposito) => deposito.set(key, json.valore));
1413
- }
1414
- async eliminaDeposito(key) {
1415
- this.verificaChiaveDeposito(key);
1416
- await this.usaDeposito((deposito) => deposito.delete(key));
1417
- }
1418
- async elencaDeposito(prefix) {
1419
- this.verificaPrefissoDeposito(prefix);
1420
- const keys = await this.usaDeposito((deposito) => deposito.list(prefix));
1421
- if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string" || !CHIAVE.test(key))) {
1422
- throw erroreConCodice("store_unavailable", "The shared store returned invalid keys.");
1423
- }
1424
- return [...keys].sort().slice(0, 4096);
1425
- }
1426
- async incrementaDeposito(key, amount) {
1427
- this.verificaChiaveDeposito(key);
1428
- if (!Number.isSafeInteger(amount)) {
1429
- throw erroreConCodice("store_not_integer", "Shared store increments must be safe integers.");
1430
- }
1431
- const value = await this.usaDeposito((deposito) => deposito.increment(key, amount));
1432
- if (!Number.isSafeInteger(value)) {
1433
- throw erroreConCodice("store_unavailable", "The shared store returned an invalid integer.");
1434
- }
1435
- return value;
1436
- }
1437
1320
  messaggioCreatore(message) {
1438
1321
  const json = analizzaJson(message);
1439
1322
  if (!json.ok) throw new TypeError("Messages must be valid JSON.");
@@ -1460,7 +1343,6 @@ var NucleoStanza = class _NucleoStanza {
1460
1343
  this.adattatore.invia(player.connessione, message);
1461
1344
  }
1462
1345
  }
1463
- if (message.t !== "flush") this.adattatore.pubblica(message);
1464
1346
  }
1465
1347
  inviaErrore(player, code, message) {
1466
1348
  if (player.connected && player.connessione !== null) {
@@ -1505,7 +1387,6 @@ var NucleoStanza = class _NucleoStanza {
1505
1387
  tick: dati.tick,
1506
1388
  tickRate: dati.tickRate,
1507
1389
  serverTime: this.adattatore.ora(),
1508
- host: dati.hostId,
1509
1390
  countdownAt: dati.countdownAt,
1510
1391
  configuration: {
1511
1392
  players: { ...this.configurazione.players },
@@ -1516,7 +1397,7 @@ var NucleoStanza = class _NucleoStanza {
1516
1397
  };
1517
1398
  }
1518
1399
  inviaGiocatori() {
1519
- this.broadcast({ t: "players", players: this.giocatoriProtocollo(), host: this.richiediDati().hostId });
1400
+ this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
1520
1401
  }
1521
1402
  inviaStatus(at) {
1522
1403
  const dati = this.richiediDati();
@@ -1524,7 +1405,6 @@ var NucleoStanza = class _NucleoStanza {
1524
1405
  t: "status",
1525
1406
  rematch: dati.status === "finished" ? dati.rivincita ?? null : null,
1526
1407
  status: dati.status,
1527
- host: dati.hostId,
1528
1408
  countdownAt: dati.countdownAt,
1529
1409
  at,
1530
1410
  result: dati.status === "ended" || dati.status === "finished" ? dati.result : null
@@ -1546,13 +1426,6 @@ var NucleoStanza = class _NucleoStanza {
1546
1426
  dati.statoSincronizzato = copiaJson(dati.state);
1547
1427
  dati.tickSincronizzato = dati.tick;
1548
1428
  }
1549
- iniziaReplay() {
1550
- if (!this.manifest.replays || !this.adattatore.inizioReplay) return;
1551
- const json = analizzaJson(this.richiediDati().state);
1552
- if (!json.ok || json.bytes > LIMITE_STATO) return;
1553
- this.inviaSnapshotTutti();
1554
- this.adattatore.inizioReplay(this.fotografia());
1555
- }
1556
1429
  inviaSnapshotTutti() {
1557
1430
  const dati = this.richiediDati();
1558
1431
  const stato = analizzaJson(dati.state);
@@ -1602,7 +1475,7 @@ var NucleoStanza = class _NucleoStanza {
1602
1475
  async concludiEvento() {
1603
1476
  await this.applicaAzioni();
1604
1477
  if (this.dati === null || this.dati.status === "ended") return;
1605
- if (this.dati.status === "finished" && this.dati.rivincita?.autoStart && this.prontiRivincita()) {
1478
+ if (this.dati.status === "finished" && this.dati.rivincita !== null && this.prontiRivincita()) {
1606
1479
  await this.avviaRivincita();
1607
1480
  return;
1608
1481
  }
@@ -1701,10 +1574,7 @@ var NucleoStanza = class _NucleoStanza {
1701
1574
  if (dati.status === "ended") return;
1702
1575
  const giaFinita = dati.status === "finished";
1703
1576
  dati.status = rematch ? "finished" : "ended";
1704
- dati.rivincita = rematch ? {
1705
- keepSetup: typeof rematch === "object" && rematch.keepSetup === true,
1706
- autoStart: typeof rematch === "object" && rematch.autoStart === true
1707
- } : null;
1577
+ dati.rivincita = rematch ? { keepSetup: typeof rematch === "object" && rematch.keepSetup === true } : null;
1708
1578
  dati.prontiPrecedenti = rematch ? dati.giocatori.filter((p) => p.ready).map((p) => p.id) : [];
1709
1579
  dati.rivincitaFinoA = rematch ? this.adattatore.ora() + ATTESA_RIVINCITA_MS : null;
1710
1580
  dati.timer = [];
@@ -2097,14 +1967,10 @@ var ArchivioNode = class _ArchivioNode {
2097
1967
  }
2098
1968
  };
2099
1969
  var AdattatoreNode = class {
2100
- constructor(storage, deposito, ritardoSpettatori, dailyDay) {
1970
+ constructor(storage, dailyDay) {
2101
1971
  this.storage = storage;
2102
- this.deposito = deposito;
2103
- this.ritardoSpettatori = ritardoSpettatori;
2104
1972
  this.dailyDay = dailyDay;
2105
1973
  this.connessioni = /* @__PURE__ */ new Map();
2106
- this.spettatori = /* @__PURE__ */ new Map();
2107
- this.timerSpettatori = /* @__PURE__ */ new Set();
2108
1974
  this.tickTimer = null;
2109
1975
  this.tickIntervallo = null;
2110
1976
  this.tickGenerazione = 0;
@@ -2112,6 +1978,8 @@ var AdattatoreNode = class {
2112
1978
  this.svegliaAt = null;
2113
1979
  this.eseguiTick = async () => void 0;
2114
1980
  this.eseguiSveglia = async () => void 0;
1981
+ this.network = new NetworkMeter();
1982
+ this.networkWarning = "ok";
2115
1983
  }
2116
1984
  collega(input) {
2117
1985
  this.eseguiTick = input.tick;
@@ -2123,65 +1991,21 @@ var AdattatoreNode = class {
2123
1991
  rimuovi(id) {
2124
1992
  this.connessioni.delete(id);
2125
1993
  }
2126
- aggiungiSpettatore(id, socket) {
2127
- this.spettatori.set(id, socket);
2128
- }
2129
- rimuoviSpettatore(id) {
2130
- this.spettatori.delete(id);
2131
- }
2132
- numeroSpettatori() {
2133
- return this.spettatori.size;
2134
- }
2135
- elencoSpettatori() {
2136
- return [...this.spettatori];
2137
- }
2138
1994
  elencoConnessioni() {
2139
1995
  return [...this.connessioni];
2140
1996
  }
2141
- invia(connessione, messaggio) {
2142
- this.connessioni.get(connessione)?.send(JSON.stringify(messaggio));
2143
- }
2144
- pubblica(messaggio) {
2145
- const testo = JSON.stringify(messaggio);
2146
- for (const [connessione] of this.spettatori) {
2147
- this.inviaSpettatore(connessione, testo);
2148
- if (messaggio.t === "status" && messaggio.status === "ended") {
2149
- this.chiudiSpettatoreRitardato(connessione);
2150
- }
2151
- }
2152
- }
2153
- inviaSpettatore(connessione, testo) {
2154
- this.accodaSpettatore(connessione, (socket) => {
2155
- socket.send(testo);
2156
- });
1997
+ sendMeasured(socket, connection, text) {
1998
+ if (!socket) return;
1999
+ socket.send(text);
2000
+ this.network.record(connection, text);
2001
+ const report = this.network.sample();
2002
+ const warning = networkLevel(report.current);
2003
+ if (warning !== "ok" && warning !== this.networkWarning) process.stderr.write(`${networkMessage(report.current)}
2004
+ `);
2005
+ this.networkWarning = warning;
2157
2006
  }
2158
- inviaSpettatoreSubito(connessione, testo) {
2159
- this.spettatori.get(connessione)?.send(testo);
2160
- }
2161
- chiudiSpettatore(connessione, codice, motivo) {
2162
- const socket = this.spettatori.get(connessione);
2163
- this.spettatori.delete(connessione);
2164
- socket?.close(codice, motivo);
2165
- }
2166
- chiudiSpettatoreRitardato(connessione) {
2167
- this.accodaSpettatore(connessione, (socket) => {
2168
- this.spettatori.delete(connessione);
2169
- socket.close(4004, "room_ended");
2170
- });
2171
- }
2172
- accodaSpettatore(connessione, azione) {
2173
- if (this.ritardoSpettatori === 0) {
2174
- const socket = this.spettatori.get(connessione);
2175
- if (socket !== void 0) azione(socket);
2176
- return;
2177
- }
2178
- const timer = setTimeout(() => {
2179
- this.timerSpettatori.delete(timer);
2180
- const socket = this.spettatori.get(connessione);
2181
- if (socket !== void 0) azione(socket);
2182
- }, this.ritardoSpettatori ?? RITARDO_SPETTATORI_MS);
2183
- this.timerSpettatori.add(timer);
2184
- timer.unref();
2007
+ invia(connessione, messaggio) {
2008
+ this.sendMeasured(this.connessioni.get(connessione), connessione, JSON.stringify(messaggio));
2185
2009
  }
2186
2010
  chiudi(connessione, codice, motivo) {
2187
2011
  this.connessioni.get(connessione)?.close(codice, motivo);
@@ -2221,8 +2045,6 @@ var AdattatoreNode = class {
2221
2045
  this.tickGenerazione += 1;
2222
2046
  if (this.tickTimer !== null) clearTimeout(this.tickTimer);
2223
2047
  if (this.svegliaTimer !== null) clearTimeout(this.svegliaTimer);
2224
- for (const timer of this.timerSpettatori) clearTimeout(timer);
2225
- this.timerSpettatori.clear();
2226
2048
  this.tickTimer = null;
2227
2049
  this.svegliaTimer = null;
2228
2050
  }
@@ -2272,8 +2094,11 @@ var StanzaNode = class {
2272
2094
  sveglia: () => this.serializza(() => nucleo.sveglia())
2273
2095
  });
2274
2096
  }
2275
- create(roomId, mode, creator) {
2276
- return this.serializza(() => this.nucleo.crea(roomId, mode, creator));
2097
+ network() {
2098
+ return this.adattatore.network.sample();
2099
+ }
2100
+ create(roomId, mode, creator, origin = "player") {
2101
+ return this.serializza(() => this.nucleo.crea(roomId, mode, creator, origin));
2277
2102
  }
2278
2103
  info() {
2279
2104
  return this.serializza(() => Promise.resolve(this.nucleo.info()));
@@ -2281,9 +2106,6 @@ var StanzaNode = class {
2281
2106
  canJoin(identity) {
2282
2107
  return this.serializza(() => Promise.resolve(this.nucleo.puoEntrare(identity)));
2283
2108
  }
2284
- canWatch() {
2285
- return this.serializza(() => Promise.resolve(this.permessoSpettatore()));
2286
- }
2287
2109
  async connect(socket, identity) {
2288
2110
  const connessione = randomUUID();
2289
2111
  this.adattatore.aggiungi(connessione, socket);
@@ -2314,28 +2136,6 @@ var StanzaNode = class {
2314
2136
  throw cause;
2315
2137
  }
2316
2138
  }
2317
- watch(socket, _identity) {
2318
- return this.serializza(async () => {
2319
- const permesso = this.permessoSpettatore();
2320
- if (!permesso.ok) return permesso;
2321
- const connessione = randomUUID();
2322
- this.adattatore.aggiungiSpettatore(connessione, socket);
2323
- socket.on("message", (message) => {
2324
- void this.serializza(() => this.riceviSpettatore(connessione, message));
2325
- });
2326
- socket.on("close", () => {
2327
- this.adattatore.rimuoviSpettatore(connessione);
2328
- this.frameFrequenza.delete(connessione);
2329
- });
2330
- const fotografia = this.nucleo.fotografia();
2331
- if (fotografia === null) {
2332
- this.adattatore.rimuoviSpettatore(connessione);
2333
- return { ok: false, code: "room_not_found" };
2334
- }
2335
- this.inviaWatching(connessione, fotografia);
2336
- return { ok: true };
2337
- });
2338
- }
2339
2139
  flush() {
2340
2140
  return this.serializza(() => this.nucleo.flush());
2341
2141
  }
@@ -2350,11 +2150,6 @@ var StanzaNode = class {
2350
2150
  socket.close(1001, "server_shutdown");
2351
2151
  await this.serializza(() => this.nucleo.disconnetti(connessione));
2352
2152
  }
2353
- for (const [connessione, socket] of this.adattatore.elencoSpettatori()) {
2354
- this.adattatore.rimuoviSpettatore(connessione);
2355
- this.frameFrequenza.delete(connessione);
2356
- socket.close(1001, "server_shutdown");
2357
- }
2358
2153
  }
2359
2154
  serializza(operazione) {
2360
2155
  const risultato = this.coda.then(operazione);
@@ -2398,74 +2193,9 @@ var StanzaNode = class {
2398
2193
  this.riconciliaRoster();
2399
2194
  return;
2400
2195
  }
2401
- await this.riceviVoce(connessione, player.id, player.role, message);
2402
- }
2403
- permessoSpettatore() {
2404
- const info = this.nucleo.info();
2405
- if (info === null) return { ok: false, code: "room_not_found" };
2406
- if (info.status === "ended") return { ok: false, code: "room_ended" };
2407
- if (this.manifest.spectators === null) {
2408
- return { ok: false, code: "spectators_disabled" };
2409
- }
2410
- if (this.adattatore.numeroSpettatori() >= MASSIMO_SPETTATORI) {
2411
- return { ok: false, code: "spectators_full" };
2412
- }
2413
- return { ok: true };
2196
+ await this.riceviVoce(connessione, player.id, message);
2414
2197
  }
2415
- inviaWatching(connessione, fotografia) {
2416
- this.adattatore.inviaSpettatore(connessione, JSON.stringify({
2417
- t: "watching",
2418
- ...fotografia,
2419
- delayMs: this.manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS
2420
- }));
2421
- }
2422
- async riceviSpettatore(connessione, frame) {
2423
- if (Buffer.byteLength(frame, "utf8") > MASSIMO_BYTE_FRAME_STANZA) {
2424
- this.adattatore.chiudiSpettatore(connessione, 4009, "message_too_large");
2425
- this.frameFrequenza.delete(connessione);
2426
- return;
2427
- }
2428
- const ora = Date.now();
2429
- const limite = this.frameFrequenza.controlla(connessione, false, ora);
2430
- if (!limite.accetta) {
2431
- if (limite.avvisa) this.adattatore.inviaSpettatoreSubito(connessione, JSON.stringify({
2432
- t: "error",
2433
- code: "rate_limited",
2434
- message: "Too many room messages. Excess messages are dropped."
2435
- }));
2436
- if (limite.chiudi) {
2437
- this.adattatore.chiudiSpettatore(connessione, 4008, "rate_limited");
2438
- this.frameFrequenza.delete(connessione);
2439
- }
2440
- return;
2441
- }
2442
- let message = null;
2443
- try {
2444
- const value = JSON.parse(frame);
2445
- message = typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2446
- } catch {
2447
- }
2448
- if (message?.t === "ping" && typeof message.c === "number" && Number.isFinite(message.c)) {
2449
- this.adattatore.inviaSpettatoreSubito(
2450
- connessione,
2451
- JSON.stringify({ t: "pong", c: message.c, s: ora })
2452
- );
2453
- return;
2454
- }
2455
- if (message?.t === "resync") {
2456
- const fotografia = this.nucleo.fotografia();
2457
- if (fotografia !== null) this.inviaWatching(connessione, fotografia);
2458
- return;
2459
- }
2460
- if (message?.t === "leave") {
2461
- this.adattatore.chiudiSpettatore(connessione, 1e3, "left");
2462
- this.frameFrequenza.delete(connessione);
2463
- return;
2464
- }
2465
- this.adattatore.chiudiSpettatore(connessione, 4009, "bad_message");
2466
- this.frameFrequenza.delete(connessione);
2467
- }
2468
- async riceviVoce(connessione, playerId, role, value) {
2198
+ async riceviVoce(connessione, playerId, value) {
2469
2199
  const richiesta = this.richiestaVoce(value);
2470
2200
  if (richiesta === null) {
2471
2201
  this.inviaErroreVoce(connessione, value, "invalid_request", "The voice request is invalid.");
@@ -2513,10 +2243,6 @@ var StanzaNode = class {
2513
2243
  }
2514
2244
  if (richiesta.op === "publish") {
2515
2245
  const mic = richiesta.mic !== false;
2516
- if (role === "spectator" && mic) {
2517
- this.inviaErroreVoce(connessione, richiesta, "spectator", "Spectators cannot join voice.");
2518
- return;
2519
- }
2520
2246
  if (mic) {
2521
2247
  this.voceListeners.delete(playerId);
2522
2248
  this.voceRoster.set(playerId, {
@@ -2631,7 +2357,7 @@ var StanzaNode = class {
2631
2357
  let cambiato = false;
2632
2358
  for (const [playerId, peer] of this.voceRoster) {
2633
2359
  const player = this.nucleo.giocatoreConnesso(peer.connessione);
2634
- if (player?.id === playerId && player.role !== "spectator") continue;
2360
+ if (player?.id === playerId) continue;
2635
2361
  this.voceRoster.delete(playerId);
2636
2362
  cambiato = true;
2637
2363
  }
@@ -2667,10 +2393,9 @@ var StanzaNode = class {
2667
2393
  }
2668
2394
  };
2669
2395
  async function createNodeRoom(definition, manifest, options = {}) {
2670
- if (options.dailyDay !== void 0 && !validBoardDay(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
2396
+ if (options.dailyDay !== void 0 && !validDay(options.dailyDay)) throw new TypeError("dailyDay must be a real UTC date in YYYY-MM-DD format.");
2671
2397
  const storage = await ArchivioNode.apri(options.storageFile ?? null);
2672
- const ritardoSpettatori = manifest.spectators === null ? null : manifest.spectators?.delayMs ?? RITARDO_SPETTATORI_MS;
2673
- const adattatore = new AdattatoreNode(storage, options.deposito ?? null, ritardoSpettatori, options.dailyDay);
2398
+ const adattatore = new AdattatoreNode(storage, options.dailyDay);
2674
2399
  const nucleo = await NucleoStanza.apri(definition, manifest, adattatore);
2675
2400
  return new StanzaNode(nucleo, adattatore, manifest);
2676
2401
  }