@caisual/kit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kit.js CHANGED
@@ -1,4 +1,169 @@
1
- // Caisual game kit v0.3.0
1
+ // Caisual game kit v0.4.0
2
+
3
+ // ../contracts/src/slug.ts
4
+ var NOMI_RISERVATI = [
5
+ "www",
6
+ "api",
7
+ "app",
8
+ "play",
9
+ "live",
10
+ "multi",
11
+ "cdn",
12
+ "assets",
13
+ "static",
14
+ "mail",
15
+ "mx",
16
+ "ns1",
17
+ "ns2",
18
+ "autodiscover",
19
+ "_dmarc",
20
+ "admin",
21
+ "login",
22
+ "account",
23
+ "auth",
24
+ "pay",
25
+ "secure",
26
+ "support",
27
+ "help",
28
+ "blog",
29
+ "status",
30
+ "dev",
31
+ "staging",
32
+ "test",
33
+ "caisual",
34
+ "shipz"
35
+ ];
36
+ var RISERVATI = new Set(NOMI_RISERVATI);
37
+
38
+ // ../contracts/src/device.ts
39
+ function deviceTier(report) {
40
+ if (report.gpu !== "hardware" || report.memoryMb !== null && report.memoryMb <= 2048) return "low";
41
+ if (report.mobile || report.memoryMb !== null && report.memoryMb <= 4096 || report.cores !== null && report.cores <= 4) return "mid";
42
+ return "high";
43
+ }
44
+ function perdiContesto(context) {
45
+ try {
46
+ context?.getExtension("WEBGL_lose_context")?.loseContext();
47
+ } catch {
48
+ }
49
+ }
50
+ function valoriSincroni(ambiente) {
51
+ let navigator2;
52
+ try {
53
+ navigator2 = ambiente.navigator;
54
+ } catch {
55
+ navigator2 = void 0;
56
+ }
57
+ let memoryMb = null;
58
+ try {
59
+ const memory = navigator2?.deviceMemory;
60
+ const converted = typeof memory === "number" ? memory * 1024 : NaN;
61
+ if (Number.isFinite(converted)) memoryMb = converted;
62
+ } catch {
63
+ memoryMb = null;
64
+ }
65
+ let cores = null;
66
+ try {
67
+ const value = navigator2?.hardwareConcurrency;
68
+ if (typeof value === "number" && Number.isFinite(value)) cores = value;
69
+ } catch {
70
+ cores = null;
71
+ }
72
+ let mobile = false;
73
+ try {
74
+ mobile = typeof navigator2?.userAgentData?.mobile === "boolean" ? navigator2.userAgentData.mobile : /Android|iPhone|iPad|iPod|Mobile/i.test(navigator2?.userAgent ?? "");
75
+ } catch {
76
+ mobile = false;
77
+ }
78
+ let isolated = false;
79
+ try {
80
+ isolated = ambiente.crossOriginIsolated === true;
81
+ } catch {
82
+ isolated = false;
83
+ }
84
+ return {
85
+ webgl2: false,
86
+ webgpu: false,
87
+ wasm: false,
88
+ threads: false,
89
+ isolated,
90
+ gpu: "none",
91
+ memoryMb,
92
+ cores,
93
+ mobile
94
+ };
95
+ }
96
+ async function probeDevice(globals, timeoutMs = 1500) {
97
+ const ambiente = globals ?? globalThis;
98
+ const report = valoriSincroni(ambiente);
99
+ const webgl = Promise.resolve().then(() => {
100
+ try {
101
+ const canvas = ambiente.document?.createElement("canvas");
102
+ if (canvas === void 0) return;
103
+ const hardware = canvas.getContext("webgl2", { failIfMajorPerformanceCaveat: true });
104
+ if (hardware !== null) {
105
+ report.webgl2 = true;
106
+ report.gpu = "hardware";
107
+ perdiContesto(hardware);
108
+ return;
109
+ }
110
+ const software = canvas.getContext("webgl2");
111
+ if (software !== null) {
112
+ report.webgl2 = true;
113
+ report.gpu = "software";
114
+ perdiContesto(software);
115
+ }
116
+ } catch {
117
+ report.webgl2 = false;
118
+ report.gpu = "none";
119
+ }
120
+ });
121
+ const webgpu = Promise.resolve().then(async () => {
122
+ let device;
123
+ try {
124
+ const gpu = ambiente.navigator?.gpu;
125
+ if (gpu === void 0) return;
126
+ const adapter = await gpu.requestAdapter();
127
+ if (adapter === null) return;
128
+ device = await adapter.requestDevice();
129
+ report.webgpu = true;
130
+ } catch {
131
+ report.webgpu = false;
132
+ } finally {
133
+ try {
134
+ device?.destroy?.();
135
+ } catch {
136
+ }
137
+ }
138
+ });
139
+ const wasm = Promise.resolve().then(() => {
140
+ try {
141
+ report.wasm = ambiente.WebAssembly?.validate(
142
+ new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
143
+ ) === true;
144
+ } catch {
145
+ report.wasm = false;
146
+ }
147
+ });
148
+ const threads = Promise.resolve().then(() => {
149
+ try {
150
+ if (ambiente.WebAssembly === void 0) return;
151
+ new ambiente.WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
152
+ report.threads = true;
153
+ } catch {
154
+ report.threads = false;
155
+ }
156
+ });
157
+ let timer;
158
+ await Promise.race([
159
+ Promise.all([webgl, webgpu, wasm, threads]),
160
+ new Promise((resolve) => {
161
+ timer = setTimeout(resolve, Math.max(0, timeoutMs));
162
+ })
163
+ ]);
164
+ if (timer !== void 0) clearTimeout(timer);
165
+ return { ...report, tier: deviceTier(report) };
166
+ }
2
167
 
3
168
  // src/errors.ts
4
169
  function creaErrore(code, message) {
@@ -294,11 +459,12 @@ var VoceClient = class {
294
459
  this.midGiocatori = /* @__PURE__ */ new Map();
295
460
  this.mesh = /* @__PURE__ */ new Map();
296
461
  this.stream = null;
297
- this.mic = null;
462
+ this.tracciaMic = null;
298
463
  this.audioContext = null;
299
464
  this.analyser = null;
300
465
  this.peerSfu = null;
301
466
  this.sessioneSfu = null;
467
+ this.connessioneSfuAttesa = false;
302
468
  this.trasporto = null;
303
469
  this.intervalloAudio = null;
304
470
  this.timerConnessione = null;
@@ -309,6 +475,7 @@ var VoceClient = class {
309
475
  this.generazione = 0;
310
476
  this.tentativoRiconnessione = 0;
311
477
  this.desiderata = false;
478
+ this.micDesiderato = true;
312
479
  this.promessaIngresso = null;
313
480
  this.negoziazione = Promise.resolve();
314
481
  this.dipendenze = dipendenze ?? dipendenzeReali(timer);
@@ -319,6 +486,9 @@ var VoceClient = class {
319
486
  get state() {
320
487
  return this.stateCorrente;
321
488
  }
489
+ get mic() {
490
+ return this.stateCorrente === "on" && this.tracciaMic !== null;
491
+ }
322
492
  get muted() {
323
493
  return this.mutedCorrente;
324
494
  }
@@ -328,14 +498,16 @@ var VoceClient = class {
328
498
  get peers() {
329
499
  return this.copiaPeers();
330
500
  }
331
- async join() {
501
+ async join(options = {}) {
332
502
  if (this.stateCorrente === "on") return;
333
503
  if (this.stateCorrente === "joining") {
334
504
  if (this.promessaIngresso !== null) await this.promessaIngresso;
335
505
  return;
336
506
  }
337
507
  if (this.stateCorrente === "reconnecting" && this.desiderata) return;
338
- this.verificaIngresso();
508
+ const mic = this.scegliMic(options);
509
+ this.verificaIngresso(mic);
510
+ this.micDesiderato = mic;
339
511
  this.desiderata = true;
340
512
  this.tentativoRiconnessione = 0;
341
513
  this.aggiornaState("joining");
@@ -372,11 +544,11 @@ var VoceClient = class {
372
544
  this.aggiornaState("off");
373
545
  }
374
546
  mute(muted = true) {
375
- if (this.stateCorrente !== "on" || this.mic === null) {
547
+ if (this.stateCorrente !== "on" || this.tracciaMic === null) {
376
548
  throw creaErrore("not_publishing", "Join voice before changing mute.");
377
549
  }
378
550
  this.mutedCorrente = muted;
379
- this.mic.enabled = !muted;
551
+ this.tracciaMic.enabled = !muted;
380
552
  void this.richiedi({ t: "voice", op: "mute", muted }).catch(() => void 0);
381
553
  }
382
554
  setVolume(playerId, volume) {
@@ -410,7 +582,11 @@ var VoceClient = class {
410
582
  }
411
583
  if (message.op === "roster") {
412
584
  this.modeCorrente = message.mode;
413
- this.roster = message.peers.map((peer) => ({ ...peer }));
585
+ const publisher = new Set(message.peers.map((peer) => peer.id));
586
+ this.roster = [
587
+ ...message.peers.map((peer) => ({ ...peer, mic: true })),
588
+ ...message.listeners.flatMap((id) => publisher.has(id) ? [] : [{ id, mic: false, muted: true }])
589
+ ];
414
590
  for (const peer of this.roster) {
415
591
  if (peer.muted) this.speakingPeers.set(peer.id, false);
416
592
  }
@@ -467,14 +643,19 @@ var VoceClient = class {
467
643
  this.chiudiRisorse();
468
644
  this.aggiornaState("off");
469
645
  }
470
- verificaIngresso() {
646
+ scegliMic(options) {
647
+ if (options.mic !== void 0) return options.mic;
648
+ const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
649
+ return you?.role !== "spectator";
650
+ }
651
+ verificaIngresso(mic = this.micDesiderato) {
471
652
  if (!this.contesto.connessa()) throw creaErrore("offline", "The room is not connected.");
472
653
  if (this.modeCorrente === "none") {
473
654
  throw creaErrore("voice_disabled", "Voice is disabled for this room.");
474
655
  }
475
656
  const you = this.contesto.giocatori().find((player) => player.id === this.contesto.you());
476
- if (you?.role === "spectator") {
477
- throw creaErrore("spectator", "Spectators cannot join voice.");
657
+ if (you?.role === "spectator" && mic) {
658
+ throw creaErrore("spectator", "Spectators cannot publish voice.");
478
659
  }
479
660
  if (this.dipendenze === null) {
480
661
  throw creaErrore("unsupported", "Voice is not supported in this browser.");
@@ -489,27 +670,29 @@ var VoceClient = class {
489
670
  await audioContext.resume();
490
671
  } catch {
491
672
  }
492
- let stream;
493
- try {
494
- stream = await dipendenze.getUserMedia({ audio: true });
495
- } catch (cause) {
496
- if (this.permessoNegato(cause)) {
497
- throw creaErrore("permission_denied", "Microphone permission was denied.");
673
+ if (this.micDesiderato) {
674
+ let stream;
675
+ try {
676
+ stream = await dipendenze.getUserMedia({ audio: true });
677
+ } catch (cause) {
678
+ if (this.permessoNegato(cause)) {
679
+ throw creaErrore("permission_denied", "Microphone permission was denied.");
680
+ }
681
+ throw creaErrore("voice_error", "The microphone could not be opened.");
682
+ }
683
+ try {
684
+ this.controllaGenerazione(generazione);
685
+ } catch (cause) {
686
+ for (const track of stream.getTracks()) track.stop();
687
+ throw cause;
498
688
  }
499
- throw creaErrore("voice_error", "The microphone could not be opened.");
689
+ const mic = stream.getAudioTracks()[0];
690
+ if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");
691
+ this.stream = stream;
692
+ this.tracciaMic = mic;
693
+ mic.enabled = !this.mutedCorrente;
694
+ this.preparaAnalizzatore(stream);
500
695
  }
501
- try {
502
- this.controllaGenerazione(generazione);
503
- } catch (cause) {
504
- for (const track of stream.getTracks()) track.stop();
505
- throw cause;
506
- }
507
- const mic = stream.getAudioTracks()[0];
508
- if (mic === void 0) throw creaErrore("voice_error", "The microphone has no audio track.");
509
- this.stream = stream;
510
- this.mic = mic;
511
- mic.enabled = !this.mutedCorrente;
512
- this.preparaAnalizzatore(stream);
513
696
  const risposta = await this.richiedi({ t: "voice", op: "ice" });
514
697
  this.controllaGenerazione(generazione);
515
698
  if (risposta.op !== "ice") throw creaErrore("voice_error", "The voice service returned an invalid response.");
@@ -519,9 +702,11 @@ var VoceClient = class {
519
702
  if (risposta.transport === "sfu") {
520
703
  await this.entraSfu(risposta.iceServers, generazione);
521
704
  } else {
522
- await this.richiedi({ t: "voice", op: "publish" });
705
+ await this.richiedi({ t: "voice", op: "publish", mic: this.micDesiderato });
706
+ }
707
+ if (this.micDesiderato && this.mutedCorrente) {
708
+ await this.richiedi({ t: "voice", op: "mute", muted: true });
523
709
  }
524
- if (this.mutedCorrente) await this.richiedi({ t: "voice", op: "mute", muted: true });
525
710
  this.controllaGenerazione(generazione);
526
711
  this.tentativoRiconnessione = 0;
527
712
  this.aggiornaState("on");
@@ -536,27 +721,45 @@ var VoceClient = class {
536
721
  });
537
722
  this.peerSfu = pc;
538
723
  pc.ontrack = (event) => {
539
- const mid2 = event.transceiver.mid;
540
- const playerId = mid2 === null ? void 0 : this.midGiocatori.get(mid2);
724
+ const mid = event.transceiver.mid;
725
+ const playerId = mid === null ? void 0 : this.midGiocatori.get(mid);
541
726
  if (playerId !== void 0) this.collegaTraccia(playerId, event.track, event.receiver);
542
727
  };
543
728
  this.osservaCaduta(pc);
544
- const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });
545
- const offer = await pc.createOffer();
546
- await pc.setLocalDescription(offer);
547
- this.controllaGenerazione(generazione);
548
- const mid = transceiver.mid;
549
- const sdp = pc.localDescription?.sdp;
550
- if (mid === null || sdp === void 0) {
551
- throw creaErrore("voice_error", "The voice connection could not create an offer.");
729
+ let risposta;
730
+ if (this.micDesiderato) {
731
+ const transceiver = pc.addTransceiver(this.richiediMic(), { direction: "sendonly" });
732
+ const offer = await pc.createOffer();
733
+ await pc.setLocalDescription(offer);
734
+ this.controllaGenerazione(generazione);
735
+ const mid = transceiver.mid;
736
+ const sdp = pc.localDescription?.sdp;
737
+ if (mid === null || sdp === void 0) {
738
+ throw creaErrore("voice_error", "The voice connection could not create an offer.");
739
+ }
740
+ risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });
741
+ } else {
742
+ risposta = await this.richiedi({ t: "voice", op: "session" });
552
743
  }
553
- const risposta = await this.richiedi({ t: "voice", op: "session", sdp, mid });
554
744
  if (risposta.op !== "session") {
555
745
  throw creaErrore("voice_error", "The voice service returned an invalid response.");
556
746
  }
557
747
  this.sessioneSfu = risposta.session;
558
- await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });
559
- await this.attendiConnessione(pc, generazione);
748
+ if (this.micDesiderato) {
749
+ if (risposta.sdp === null) {
750
+ throw creaErrore("voice_error", "The voice service returned an invalid response.");
751
+ }
752
+ await pc.setRemoteDescription({ type: "answer", sdp: risposta.sdp });
753
+ await this.attendiConnessione(pc, generazione);
754
+ this.connessioneSfuAttesa = true;
755
+ return;
756
+ }
757
+ if (risposta.sdp !== null) {
758
+ throw creaErrore("voice_error", "The voice service returned an invalid response.");
759
+ }
760
+ if (this.publisherDesiderati().length > 0) {
761
+ await this.riconciliaSfu();
762
+ }
560
763
  }
561
764
  attendiConnessione(pc, generazione) {
562
765
  if (pc.connectionState === "connected") return Promise.resolve();
@@ -603,7 +806,7 @@ var VoceClient = class {
603
806
  const sessione = this.sessioneSfu;
604
807
  const pc = this.peerSfu;
605
808
  if (sessione === null || pc === null) return;
606
- const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
809
+ const desiderati = new Map(this.publisherDesiderati().map((peer) => [peer.id, peer]));
607
810
  const daChiudere = [];
608
811
  for (const [playerId, attiva] of this.sfuAttive) {
609
812
  const peer = desiderati.get(playerId);
@@ -652,6 +855,10 @@ var VoceClient = class {
652
855
  const sdp = pc.localDescription?.sdp;
653
856
  if (sdp === void 0) throw creaErrore("voice_error", "The voice answer is missing.");
654
857
  await this.richiedi({ t: "voice", op: "answer", session: sessione, sdp });
858
+ if (!this.connessioneSfuAttesa) {
859
+ await this.attendiConnessione(pc, this.generazione);
860
+ this.connessioneSfuAttesa = true;
861
+ }
655
862
  }
656
863
  riconciliaMesh() {
657
864
  const desiderati = new Map(this.peerDesiderati().map((peer) => [peer.id, peer]));
@@ -662,10 +869,11 @@ var VoceClient = class {
662
869
  this.scollegaTraccia(playerId);
663
870
  }
664
871
  for (const peer of desiderati.values()) {
665
- if (!this.mesh.has(peer.id)) this.creaMesh(peer.id);
872
+ if (!this.mesh.has(peer.id)) this.creaMesh(peer);
666
873
  }
667
874
  }
668
- creaMesh(playerId) {
875
+ creaMesh(peer) {
876
+ const playerId = peer.id;
669
877
  const pc = this.richiediDipendenze().creaPeerConnection();
670
878
  const item = {
671
879
  pc,
@@ -688,7 +896,13 @@ var VoceClient = class {
688
896
  this.collegaTraccia(playerId, event.track, event.receiver);
689
897
  };
690
898
  this.osservaCaduta(pc);
691
- pc.addTrack(this.richiediMic(), this.richiediStream());
899
+ if (this.micDesiderato) {
900
+ pc.addTransceiver(this.richiediMic(), {
901
+ direction: peer.mic ? "sendrecv" : "sendonly"
902
+ });
903
+ } else {
904
+ pc.addTransceiver("audio", { direction: "recvonly" });
905
+ }
692
906
  }
693
907
  async offriMesh(playerId, item) {
694
908
  try {
@@ -703,8 +917,9 @@ var VoceClient = class {
703
917
  }
704
918
  async riceviSegnale(from, data) {
705
919
  if (this.trasporto !== "mesh" || this.stateCorrente !== "on") return;
706
- if (!this.peerDesiderati().some((peer) => peer.id === from)) return;
707
- if (!this.mesh.has(from)) this.creaMesh(from);
920
+ const peer = this.peerDesiderati().find((item2) => item2.id === from);
921
+ if (peer === void 0) return;
922
+ if (!this.mesh.has(from)) this.creaMesh(peer);
708
923
  const item = this.mesh.get(from);
709
924
  if (item === void 0 || typeof data !== "object" || data === null || Array.isArray(data)) return;
710
925
  const segnale = data;
@@ -740,14 +955,23 @@ var VoceClient = class {
740
955
  const player = giocatori.find((item) => item.id === you);
741
956
  return this.roster.filter((peer) => {
742
957
  if (peer.id === you) return false;
958
+ if (!this.micDesiderato && !peer.mic) return false;
743
959
  if (this.modeCorrente === "team") {
744
960
  const altro = giocatori.find((item) => item.id === peer.id);
745
961
  if (player?.role !== "spectator" && altro?.team !== player?.team) return false;
746
962
  }
747
- const zeroAt = this.zeroDa.get(peer.id);
748
- return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;
963
+ return true;
749
964
  });
750
965
  }
966
+ publisherDesiderati() {
967
+ return this.peerDesiderati().filter(
968
+ (peer) => {
969
+ if (!peer.mic) return false;
970
+ const zeroAt = this.zeroDa.get(peer.id);
971
+ return zeroAt === void 0 || this.richiediDipendenze().ora() - zeroAt < DURATA_ZERO;
972
+ }
973
+ );
974
+ }
751
975
  aggiornaZero(playerId) {
752
976
  const dipendenze = this.dipendenze;
753
977
  if (dipendenze === null) return;
@@ -872,8 +1096,9 @@ var VoceClient = class {
872
1096
  }
873
1097
  return [{
874
1098
  id: peer.id,
1099
+ mic: peer.mic,
875
1100
  muted: peer.muted,
876
- speaking: !peer.muted && (this.speakingPeers.get(peer.id) ?? false),
1101
+ speaking: peer.mic && !peer.muted && (this.speakingPeers.get(peer.id) ?? false),
877
1102
  volume: this.volumi.get(peer.id) ?? 1,
878
1103
  gain: this.gains.get(peer.id) ?? 1
879
1104
  }];
@@ -952,11 +1177,12 @@ var VoceClient = class {
952
1177
  this.midGiocatori.clear();
953
1178
  for (const track of this.stream?.getTracks() ?? []) track.stop();
954
1179
  this.stream = null;
955
- this.mic = null;
1180
+ this.tracciaMic = null;
956
1181
  this.analyser = null;
957
1182
  void this.audioContext?.close().catch(() => void 0);
958
1183
  this.audioContext = null;
959
1184
  this.sessioneSfu = null;
1185
+ this.connessioneSfuAttesa = false;
960
1186
  this.trasporto = null;
961
1187
  this.speakingCorrente = false;
962
1188
  this.ultimoAudioMic = Number.NEGATIVE_INFINITY;
@@ -1010,12 +1236,8 @@ var VoceClient = class {
1010
1236
  return this.dipendenze;
1011
1237
  }
1012
1238
  richiediMic() {
1013
- if (this.mic === null) throw creaErrore("voice_error", "The microphone is not ready.");
1014
- return this.mic;
1015
- }
1016
- richiediStream() {
1017
- if (this.stream === null) throw creaErrore("voice_error", "The microphone is not ready.");
1018
- return this.stream;
1239
+ if (this.tracciaMic === null) throw creaErrore("voice_error", "The microphone is not ready.");
1240
+ return this.tracciaMic;
1019
1241
  }
1020
1242
  richiediAudioContext() {
1021
1243
  if (this.audioContext === null) throw creaErrore("voice_error", "Audio is not ready.");
@@ -1045,6 +1267,15 @@ var CHIUSURE_DEFINITIVE = /* @__PURE__ */ new Set([4003, 4004, 4005, 4006]);
1045
1267
  function record2(value) {
1046
1268
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1047
1269
  }
1270
+ function ingressoValido(value) {
1271
+ const dati = record2(value);
1272
+ return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
1273
+ }
1274
+ function rispostaMatchValida(value) {
1275
+ const dati = record2(value);
1276
+ const players = record2(dati?.players);
1277
+ return dati !== null && typeof dati.url === "string" && Number.isInteger(dati.timeoutMs) && dati.timeoutMs >= 1e3 && dati.timeoutMs <= 3e5 && players !== null && Number.isInteger(players.min) && Number.isInteger(players.max) && players.min >= 1 && players.max >= players.min;
1278
+ }
1048
1279
  function copiaJson(value) {
1049
1280
  return JSON.parse(JSON.stringify(value));
1050
1281
  }
@@ -1095,10 +1326,6 @@ function applicaPatch(state, value) {
1095
1326
  }
1096
1327
  function creaApiLive(input) {
1097
1328
  const richiesta = creaRichiedente(input.liveOrigin, "", input.fetcher, input.biglietto);
1098
- function ingressoValido(value) {
1099
- const dati = record2(value);
1100
- return dati !== null && typeof dati.roomId === "string" && typeof dati.code === "string" && typeof dati.join === "string" && typeof dati.url === "string";
1101
- }
1102
1329
  async function ingresso(path, body, rinnova = false) {
1103
1330
  const value = await richiesta(path, "POST", body, rinnova);
1104
1331
  if (!ingressoValido(value)) {
@@ -1106,10 +1333,21 @@ function creaApiLive(input) {
1106
1333
  }
1107
1334
  return value;
1108
1335
  }
1336
+ async function match(options) {
1337
+ const value = await richiesta("/match", "POST", {
1338
+ mode: options.mode,
1339
+ key: options.key
1340
+ });
1341
+ if (!rispostaMatchValida(value)) {
1342
+ throw creaErrore("internal_error", "The matchmaking service returned an invalid response.");
1343
+ }
1344
+ return value;
1345
+ }
1109
1346
  return {
1110
1347
  create: (mode) => ingresso("/rooms", { mode }),
1111
1348
  joinCode: (code) => ingresso("/rooms/join", { code }),
1112
1349
  joinRoom: (roomId) => ingresso("/rooms/join", { roomId }, true),
1350
+ match,
1113
1351
  flush: (roomId) => richiesta(
1114
1352
  `/rooms/${encodeURIComponent(roomId)}/flush`,
1115
1353
  "POST"
@@ -1117,14 +1355,16 @@ function creaApiLive(input) {
1117
1355
  };
1118
1356
  }
1119
1357
  var StanzaClient = class {
1120
- constructor(roomId, codice, url, input, api) {
1358
+ constructor(roomId, codice, url, input, api, segnalaStanza) {
1121
1359
  this.roomId = roomId;
1122
1360
  this.codice = codice;
1123
1361
  this.input = input;
1124
1362
  this.api = api;
1363
+ this.segnalaStanza = segnalaStanza;
1125
1364
  this.statoPubblico = null;
1126
1365
  this.statoSincronizzato = null;
1127
1366
  this.tickCorrente = 0;
1367
+ this.seedCorrente = 0;
1128
1368
  this.statusCorrente = "lobby";
1129
1369
  this.giocatoriCorrenti = [];
1130
1370
  this.youCorrente = "";
@@ -1175,6 +1415,9 @@ var StanzaClient = class {
1175
1415
  get tick() {
1176
1416
  return this.tickCorrente;
1177
1417
  }
1418
+ get seed() {
1419
+ return this.seedCorrente;
1420
+ }
1178
1421
  get status() {
1179
1422
  return this.statusCorrente;
1180
1423
  }
@@ -1244,6 +1487,7 @@ var StanzaClient = class {
1244
1487
  if (this.lasciata) return;
1245
1488
  this.voice.leave();
1246
1489
  this.lasciata = true;
1490
+ this.segnalaStanza(null);
1247
1491
  if (this.socket?.readyState === APERTO) this.invia({ t: "leave" });
1248
1492
  this.termina(1e3);
1249
1493
  }
@@ -1335,6 +1579,7 @@ var StanzaClient = class {
1335
1579
  const room = dati.room;
1336
1580
  if (room.id !== this.roomId) return;
1337
1581
  this.youCorrente = dati.you;
1582
+ this.seedCorrente = room.seed;
1338
1583
  this.hostCorrente = room.host;
1339
1584
  this.statusCorrente = room.status;
1340
1585
  this.giocatoriCorrenti = dati.players.map((player) => ({ ...player }));
@@ -1377,6 +1622,7 @@ var StanzaClient = class {
1377
1622
  this.resultCorrente = copiaJson(dati.result);
1378
1623
  if (dati.status === "ended") {
1379
1624
  this.terminata = true;
1625
+ this.segnalaStanza(null);
1380
1626
  this.voice.termina();
1381
1627
  this.fermaPing();
1382
1628
  this.fermaRiconnessione();
@@ -1450,7 +1696,11 @@ var StanzaClient = class {
1450
1696
  if (this.terminata || this.lasciata) return;
1451
1697
  try {
1452
1698
  const ingresso = await this.api.joinRoom(this.roomId);
1699
+ const codiceCambiato = this.codice !== ingresso.code;
1453
1700
  this.codice = ingresso.code;
1701
+ if (codiceCambiato && this.prontaRisolta && !this.terminata && !this.lasciata) {
1702
+ this.segnalaStanza({ code: this.codice });
1703
+ }
1454
1704
  this.apri(ingresso.url);
1455
1705
  } catch {
1456
1706
  this.programmaRiconnessione();
@@ -1465,6 +1715,7 @@ var StanzaClient = class {
1465
1715
  const risultato = { closed: code };
1466
1716
  const cambiato = this.statusCorrente !== "ended" || JSON.stringify(this.resultCorrente) !== JSON.stringify(risultato);
1467
1717
  this.terminata = true;
1718
+ this.segnalaStanza(null);
1468
1719
  this.statusCorrente = "ended";
1469
1720
  this.resultCorrente = risultato;
1470
1721
  this.voice.termina();
@@ -1490,6 +1741,7 @@ var StanzaClient = class {
1490
1741
  this.timerRoster = null;
1491
1742
  }
1492
1743
  this.prontaRisolta = true;
1744
+ if (!this.terminata && !this.lasciata) this.segnalaStanza({ code: this.codice });
1493
1745
  this.risolviPronta();
1494
1746
  }
1495
1747
  richiediFlush() {
@@ -1521,16 +1773,132 @@ function creaStanzeOffline(invited = null) {
1521
1773
  },
1522
1774
  async join() {
1523
1775
  throw erroreOffline();
1776
+ },
1777
+ async match() {
1778
+ throw erroreOffline();
1524
1779
  }
1525
1780
  };
1526
1781
  }
1527
1782
  function creaGestoreStanze(input, invited) {
1528
1783
  const api = creaApiLive(input);
1784
+ let haSegnalato = false;
1785
+ let ultimoCodice = null;
1786
+ const segnalaStanza = (room) => {
1787
+ const codice = room?.code ?? null;
1788
+ if (haSegnalato && codice === ultimoCodice) return;
1789
+ haSegnalato = true;
1790
+ ultimoCodice = codice;
1791
+ input.segnalaStanza?.(room);
1792
+ };
1529
1793
  const collega = async (ingresso) => {
1530
- const stanza = new StanzaClient(ingresso.roomId, ingresso.code, ingresso.url, input, api);
1794
+ const stanza = new StanzaClient(
1795
+ ingresso.roomId,
1796
+ ingresso.code,
1797
+ ingresso.url,
1798
+ input,
1799
+ api,
1800
+ segnalaStanza
1801
+ );
1531
1802
  await stanza.pronta();
1532
1803
  return stanza;
1533
1804
  };
1805
+ const attendiMatch = (url, options) => new Promise((resolve, reject) => {
1806
+ let socket;
1807
+ let conclusa = false;
1808
+ const pulisci = () => {
1809
+ socket.removeEventListener("message", ricevi);
1810
+ socket.removeEventListener("close", chiuso);
1811
+ socket.removeEventListener("error", caduto);
1812
+ options.signal?.removeEventListener("abort", annulla);
1813
+ };
1814
+ const chiudi = () => {
1815
+ try {
1816
+ socket.close(1e3);
1817
+ } catch {
1818
+ }
1819
+ };
1820
+ const fallisci = (errore, chiudiSocket) => {
1821
+ if (conclusa) return;
1822
+ conclusa = true;
1823
+ pulisci();
1824
+ if (chiudiSocket) chiudi();
1825
+ reject(errore);
1826
+ };
1827
+ function annulla() {
1828
+ fallisci(
1829
+ creaErrore("cancelled", "The matchmaking search was cancelled."),
1830
+ true
1831
+ );
1832
+ }
1833
+ function chiuso() {
1834
+ fallisci(erroreOffline(), false);
1835
+ }
1836
+ function caduto() {
1837
+ fallisci(erroreOffline(), true);
1838
+ }
1839
+ function ricevi(evento) {
1840
+ let dati = null;
1841
+ try {
1842
+ dati = typeof evento.data === "string" ? record2(JSON.parse(evento.data)) : null;
1843
+ } catch {
1844
+ }
1845
+ if (dati === null || typeof dati.t !== "string") {
1846
+ fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
1847
+ return;
1848
+ }
1849
+ if (dati.t === "waiting") {
1850
+ if (!Number.isInteger(dati.players) || !Number.isInteger(dati.min) || !Number.isInteger(dati.max)) {
1851
+ fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
1852
+ return;
1853
+ }
1854
+ try {
1855
+ options.onWaiting?.({
1856
+ players: dati.players,
1857
+ min: dati.min,
1858
+ max: dati.max
1859
+ });
1860
+ } catch {
1861
+ }
1862
+ return;
1863
+ }
1864
+ if (dati.t === "matched") {
1865
+ if (!ingressoValido(dati)) {
1866
+ fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
1867
+ return;
1868
+ }
1869
+ conclusa = true;
1870
+ pulisci();
1871
+ chiudi();
1872
+ resolve(dati);
1873
+ return;
1874
+ }
1875
+ if (dati.t === "no_match") {
1876
+ fallisci(creaErrore("no_match", "No match was found before the timeout."), true);
1877
+ return;
1878
+ }
1879
+ if (dati.t === "error") {
1880
+ fallisci(creaErrore(
1881
+ typeof dati.code === "string" ? dati.code : "internal_error",
1882
+ typeof dati.message === "string" ? dati.message : "The matchmaking service could not complete the search."
1883
+ ), true);
1884
+ return;
1885
+ }
1886
+ if (dati.t !== "pong") {
1887
+ fallisci(creaErrore("internal_error", "The matchmaking service sent an invalid message."), true);
1888
+ }
1889
+ }
1890
+ try {
1891
+ socket = input.apriSocket(url);
1892
+ } catch {
1893
+ reject(erroreOffline());
1894
+ return;
1895
+ }
1896
+ socket.addEventListener("message", ricevi);
1897
+ socket.addEventListener("close", chiuso);
1898
+ socket.addEventListener("error", caduto);
1899
+ options.signal?.addEventListener("abort", annulla, { once: true });
1900
+ if (options.signal?.aborted === true) annulla();
1901
+ });
1534
1902
  return {
1535
1903
  invited,
1536
1904
  async create(options) {
@@ -1542,6 +1910,17 @@ function creaGestoreStanze(input, invited) {
1542
1910
  throw creaErrore("invalid_request", "A room invitation code is required.");
1543
1911
  }
1544
1912
  return collega(await api.joinCode(scelto));
1913
+ },
1914
+ async match(options) {
1915
+ const annullata = () => options.signal?.aborted === true;
1916
+ if (annullata()) {
1917
+ throw creaErrore("cancelled", "The matchmaking search was cancelled.");
1918
+ }
1919
+ const risposta = await api.match(options);
1920
+ if (annullata()) {
1921
+ throw creaErrore("cancelled", "The matchmaking search was cancelled.");
1922
+ }
1923
+ return collega(await attendiMatch(risposta.url, options));
1545
1924
  }
1546
1925
  };
1547
1926
  }
@@ -1655,7 +2034,8 @@ function dipendenzeReali2() {
1655
2034
  archivio: archivioReale(),
1656
2035
  hostname: typeof location === "undefined" ? "" : location.hostname,
1657
2036
  subtle: globalThis.crypto.subtle,
1658
- ora: Date.now
2037
+ ora: Date.now,
2038
+ sonda: () => probeDevice()
1659
2039
  };
1660
2040
  }
1661
2041
  async function connetti(input) {
@@ -1710,7 +2090,13 @@ async function connetti(input) {
1710
2090
  clearTimeout: (id) => globalThis.clearTimeout(id),
1711
2091
  setInterval: (handler, timeout) => globalThis.setInterval(handler, timeout),
1712
2092
  clearInterval: (id) => globalThis.clearInterval(id),
1713
- voce: input.voce
2093
+ voce: input.voce,
2094
+ segnalaStanza(room2) {
2095
+ try {
2096
+ handshake.porta.postMessage({ type: "caisual:room", room: room2 });
2097
+ } catch {
2098
+ }
2099
+ }
1714
2100
  }, handshake.invite);
1715
2101
  return {
1716
2102
  connected: true,
@@ -1737,11 +2123,38 @@ async function connetti(input) {
1737
2123
  room
1738
2124
  };
1739
2125
  }
2126
+ function dispositivoSconosciuto() {
2127
+ return {
2128
+ webgl2: false,
2129
+ webgpu: false,
2130
+ wasm: false,
2131
+ threads: false,
2132
+ isolated: false,
2133
+ gpu: "none",
2134
+ memoryMb: null,
2135
+ cores: null,
2136
+ mobile: false,
2137
+ tier: "low"
2138
+ };
2139
+ }
2140
+ async function attendiSonda(sonda) {
2141
+ let timer;
2142
+ try {
2143
+ return await Promise.race([
2144
+ Promise.resolve().then(sonda).catch(() => dispositivoSconosciuto()),
2145
+ new Promise((resolve) => {
2146
+ timer = globalThis.setTimeout(() => resolve(dispositivoSconosciuto()), 1500);
2147
+ })
2148
+ ]);
2149
+ } finally {
2150
+ if (timer !== void 0) globalThis.clearTimeout(timer);
2151
+ }
2152
+ }
1740
2153
  function creaKit(input = dipendenzeReali2()) {
1741
2154
  let promessa = null;
1742
2155
  return {
1743
2156
  connect() {
1744
- promessa ?? (promessa = connetti(input));
2157
+ promessa ?? (promessa = Promise.all([connetti(input), attendiSonda(input.sonda)]).then(([connessione, device]) => ({ ...connessione, device })));
1745
2158
  return promessa;
1746
2159
  }
1747
2160
  };