@caisual/kit 0.1.0 → 0.3.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.d.ts +67 -0
- package/dist/kit.js +1374 -31
- package/dist/node.d.ts +75 -0
- package/dist/node.js +1930 -0
- package/dist/runtime.d.ts +106 -0
- package/dist/runtime.js +1458 -0
- package/dist/server.d.ts +57 -0
- package/dist/server.js +38 -0
- package/package.json +33 -6
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,1458 @@
|
|
|
1
|
+
// src/stanza/json.ts
|
|
2
|
+
function isPlainObject(value) {
|
|
3
|
+
const prototype = Object.getPrototypeOf(value);
|
|
4
|
+
return prototype === Object.prototype || prototype === null;
|
|
5
|
+
}
|
|
6
|
+
function verificaValore(value, visitati) {
|
|
7
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
8
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
9
|
+
if (typeof value !== "object") return false;
|
|
10
|
+
if (visitati.has(value)) return false;
|
|
11
|
+
visitati.add(value);
|
|
12
|
+
let valido = true;
|
|
13
|
+
if (Array.isArray(value)) {
|
|
14
|
+
const chiavi = Reflect.ownKeys(value);
|
|
15
|
+
if (chiavi.some((key) => {
|
|
16
|
+
if (key === "length") return false;
|
|
17
|
+
if (typeof key !== "string" || !/^(0|[1-9][0-9]*)$/.test(key)) return true;
|
|
18
|
+
const indice = Number(key);
|
|
19
|
+
return !Number.isSafeInteger(indice) || indice >= value.length;
|
|
20
|
+
})) valido = false;
|
|
21
|
+
for (let indice = 0; indice < value.length; indice++) {
|
|
22
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(indice));
|
|
23
|
+
if (!valido || descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor) || !verificaValore(descriptor.value, visitati)) {
|
|
24
|
+
valido = false;
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
} else if (isPlainObject(value)) {
|
|
29
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
30
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
31
|
+
if (typeof key !== "string" || descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor) || !verificaValore(descriptor.value, visitati)) {
|
|
32
|
+
valido = false;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
} else {
|
|
37
|
+
valido = false;
|
|
38
|
+
}
|
|
39
|
+
visitati.delete(value);
|
|
40
|
+
return valido;
|
|
41
|
+
}
|
|
42
|
+
function analizzaJson(value) {
|
|
43
|
+
if (!verificaValore(value, /* @__PURE__ */ new Set())) return { ok: false, code: "state_invalid" };
|
|
44
|
+
const testo = JSON.stringify(value);
|
|
45
|
+
return {
|
|
46
|
+
ok: true,
|
|
47
|
+
testo,
|
|
48
|
+
valore: JSON.parse(testo),
|
|
49
|
+
bytes: new TextEncoder().encode(testo).byteLength
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function isObject(value) {
|
|
53
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
54
|
+
}
|
|
55
|
+
function visitaDiff(prima, dopo, path, patch) {
|
|
56
|
+
if (Array.isArray(prima) && Array.isArray(dopo)) {
|
|
57
|
+
if (prima.length !== dopo.length) {
|
|
58
|
+
patch.push({ op: "set", path, value: dopo });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
for (let indice = 0; indice < dopo.length; indice++) {
|
|
62
|
+
visitaDiff(prima[indice], dopo[indice], [...path, indice], patch);
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (isObject(prima) && isObject(dopo)) {
|
|
67
|
+
for (const key of Object.keys(prima)) {
|
|
68
|
+
if (!(key in dopo)) patch.push({ op: "del", path: [...path, key] });
|
|
69
|
+
}
|
|
70
|
+
for (const [key, value] of Object.entries(dopo)) {
|
|
71
|
+
if (!(key in prima)) patch.push({ op: "set", path: [...path, key], value });
|
|
72
|
+
else visitaDiff(prima[key], value, [...path, key], patch);
|
|
73
|
+
}
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (!Object.is(prima, dopo)) patch.push({ op: "set", path, value: dopo });
|
|
77
|
+
}
|
|
78
|
+
function creaDiff(prima, dopo) {
|
|
79
|
+
const patch = [];
|
|
80
|
+
visitaDiff(prima, dopo, [], patch);
|
|
81
|
+
return patch;
|
|
82
|
+
}
|
|
83
|
+
function giornoUtc(ora) {
|
|
84
|
+
return new Date(ora).toISOString().slice(0, 10);
|
|
85
|
+
}
|
|
86
|
+
var COSTANTI_SHA256 = [
|
|
87
|
+
1116352408,
|
|
88
|
+
1899447441,
|
|
89
|
+
3049323471,
|
|
90
|
+
3921009573,
|
|
91
|
+
961987163,
|
|
92
|
+
1508970993,
|
|
93
|
+
2453635748,
|
|
94
|
+
2870763221,
|
|
95
|
+
3624381080,
|
|
96
|
+
310598401,
|
|
97
|
+
607225278,
|
|
98
|
+
1426881987,
|
|
99
|
+
1925078388,
|
|
100
|
+
2162078206,
|
|
101
|
+
2614888103,
|
|
102
|
+
3248222580,
|
|
103
|
+
3835390401,
|
|
104
|
+
4022224774,
|
|
105
|
+
264347078,
|
|
106
|
+
604807628,
|
|
107
|
+
770255983,
|
|
108
|
+
1249150122,
|
|
109
|
+
1555081692,
|
|
110
|
+
1996064986,
|
|
111
|
+
2554220882,
|
|
112
|
+
2821834349,
|
|
113
|
+
2952996808,
|
|
114
|
+
3210313671,
|
|
115
|
+
3336571891,
|
|
116
|
+
3584528711,
|
|
117
|
+
113926993,
|
|
118
|
+
338241895,
|
|
119
|
+
666307205,
|
|
120
|
+
773529912,
|
|
121
|
+
1294757372,
|
|
122
|
+
1396182291,
|
|
123
|
+
1695183700,
|
|
124
|
+
1986661051,
|
|
125
|
+
2177026350,
|
|
126
|
+
2456956037,
|
|
127
|
+
2730485921,
|
|
128
|
+
2820302411,
|
|
129
|
+
3259730800,
|
|
130
|
+
3345764771,
|
|
131
|
+
3516065817,
|
|
132
|
+
3600352804,
|
|
133
|
+
4094571909,
|
|
134
|
+
275423344,
|
|
135
|
+
430227734,
|
|
136
|
+
506948616,
|
|
137
|
+
659060556,
|
|
138
|
+
883997877,
|
|
139
|
+
958139571,
|
|
140
|
+
1322822218,
|
|
141
|
+
1537002063,
|
|
142
|
+
1747873779,
|
|
143
|
+
1955562222,
|
|
144
|
+
2024104815,
|
|
145
|
+
2227730452,
|
|
146
|
+
2361852424,
|
|
147
|
+
2428436474,
|
|
148
|
+
2756734187,
|
|
149
|
+
3204031479,
|
|
150
|
+
3329325298
|
|
151
|
+
];
|
|
152
|
+
function ruotaDestra(value, bits) {
|
|
153
|
+
return value >>> bits | value << 32 - bits;
|
|
154
|
+
}
|
|
155
|
+
function seedGiornata(slug, day) {
|
|
156
|
+
const testo = `caisual:${slug}:${day}`;
|
|
157
|
+
const bytes = Array.from(testo, (carattere) => carattere.charCodeAt(0));
|
|
158
|
+
const bitLength = bytes.length * 8;
|
|
159
|
+
bytes.push(128);
|
|
160
|
+
while (bytes.length % 64 !== 56) bytes.push(0);
|
|
161
|
+
for (let indice = 7; indice >= 0; indice--) {
|
|
162
|
+
bytes.push(indice < 4 ? bitLength >>> indice * 8 & 255 : 0);
|
|
163
|
+
}
|
|
164
|
+
let h0 = 1779033703;
|
|
165
|
+
let h1 = 3144134277;
|
|
166
|
+
let h2 = 1013904242;
|
|
167
|
+
let h3 = 2773480762;
|
|
168
|
+
let h4 = 1359893119;
|
|
169
|
+
let h5 = 2600822924;
|
|
170
|
+
let h6 = 528734635;
|
|
171
|
+
let h7 = 1541459225;
|
|
172
|
+
const parole = new Uint32Array(64);
|
|
173
|
+
for (let blocco = 0; blocco < bytes.length; blocco += 64) {
|
|
174
|
+
for (let indice = 0; indice < 16; indice++) {
|
|
175
|
+
const offset = blocco + indice * 4;
|
|
176
|
+
parole[indice] = ((bytes[offset] ?? 0) << 24 | (bytes[offset + 1] ?? 0) << 16 | (bytes[offset + 2] ?? 0) << 8 | (bytes[offset + 3] ?? 0)) >>> 0;
|
|
177
|
+
}
|
|
178
|
+
for (let indice = 16; indice < 64; indice++) {
|
|
179
|
+
const x = parole[indice - 15] ?? 0;
|
|
180
|
+
const y = parole[indice - 2] ?? 0;
|
|
181
|
+
const s0 = ruotaDestra(x, 7) ^ ruotaDestra(x, 18) ^ x >>> 3;
|
|
182
|
+
const s1 = ruotaDestra(y, 17) ^ ruotaDestra(y, 19) ^ y >>> 10;
|
|
183
|
+
parole[indice] = (parole[indice - 16] ?? 0) + s0 + (parole[indice - 7] ?? 0) + s1 >>> 0;
|
|
184
|
+
}
|
|
185
|
+
let a = h0;
|
|
186
|
+
let b = h1;
|
|
187
|
+
let c = h2;
|
|
188
|
+
let d = h3;
|
|
189
|
+
let e = h4;
|
|
190
|
+
let f = h5;
|
|
191
|
+
let g = h6;
|
|
192
|
+
let h = h7;
|
|
193
|
+
for (let indice = 0; indice < 64; indice++) {
|
|
194
|
+
const s1 = ruotaDestra(e, 6) ^ ruotaDestra(e, 11) ^ ruotaDestra(e, 25);
|
|
195
|
+
const scelta = e & f ^ ~e & g;
|
|
196
|
+
const temp1 = h + s1 + scelta + (COSTANTI_SHA256[indice] ?? 0) + (parole[indice] ?? 0) >>> 0;
|
|
197
|
+
const s0 = ruotaDestra(a, 2) ^ ruotaDestra(a, 13) ^ ruotaDestra(a, 22);
|
|
198
|
+
const maggioranza = a & b ^ a & c ^ b & c;
|
|
199
|
+
const temp2 = s0 + maggioranza >>> 0;
|
|
200
|
+
h = g;
|
|
201
|
+
g = f;
|
|
202
|
+
f = e;
|
|
203
|
+
e = d + temp1 >>> 0;
|
|
204
|
+
d = c;
|
|
205
|
+
c = b;
|
|
206
|
+
b = a;
|
|
207
|
+
a = temp1 + temp2 >>> 0;
|
|
208
|
+
}
|
|
209
|
+
h0 = h0 + a >>> 0;
|
|
210
|
+
h1 = h1 + b >>> 0;
|
|
211
|
+
h2 = h2 + c >>> 0;
|
|
212
|
+
h3 = h3 + d >>> 0;
|
|
213
|
+
h4 = h4 + e >>> 0;
|
|
214
|
+
h5 = h5 + f >>> 0;
|
|
215
|
+
h6 = h6 + g >>> 0;
|
|
216
|
+
h7 = h7 + h >>> 0;
|
|
217
|
+
}
|
|
218
|
+
return h0 >>> 0;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/stanza/nucleo.ts
|
|
222
|
+
var CHIAVE_NUCLEO = "nucleo";
|
|
223
|
+
var PREFISSO_SAVE = "save:";
|
|
224
|
+
var LIMITE_FRAME = 16 * 1024;
|
|
225
|
+
var LIMITE_STATO = 256 * 1024;
|
|
226
|
+
var LIMITE_SAVE = 128 * 1024;
|
|
227
|
+
var GRAZIA_MS = 6e4;
|
|
228
|
+
var STANZA_VUOTA_MS = 5 * 6e4;
|
|
229
|
+
var COUNTDOWN_MS = 3e3;
|
|
230
|
+
var RIPOSO_TICK_MS = 3e4;
|
|
231
|
+
var INATTIVITA_MS = 10 * 6e4;
|
|
232
|
+
var CHIAVE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
233
|
+
var GAME_DEFINITION = /* @__PURE__ */ Symbol.for("@caisual/kit/game-definition");
|
|
234
|
+
function record(value) {
|
|
235
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
236
|
+
}
|
|
237
|
+
function definizioneValida(value) {
|
|
238
|
+
return record(value)?.[GAME_DEFINITION] === true;
|
|
239
|
+
}
|
|
240
|
+
function idGiocatore(player) {
|
|
241
|
+
return typeof player === "string" ? player : player.id;
|
|
242
|
+
}
|
|
243
|
+
function copiaGiocatore(player) {
|
|
244
|
+
return {
|
|
245
|
+
id: player.id,
|
|
246
|
+
name: player.name,
|
|
247
|
+
guest: player.guest,
|
|
248
|
+
role: player.role,
|
|
249
|
+
team: player.team,
|
|
250
|
+
connected: player.connected
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function copiaJson(value) {
|
|
254
|
+
return JSON.parse(JSON.stringify(value));
|
|
255
|
+
}
|
|
256
|
+
function codiceIngresso(code) {
|
|
257
|
+
if (code === "room_not_found") return 4001;
|
|
258
|
+
if (code === "room_full") return 4e3;
|
|
259
|
+
return 4004;
|
|
260
|
+
}
|
|
261
|
+
var NucleoStanza = class _NucleoStanza {
|
|
262
|
+
constructor(definizione, manifest, adattatore) {
|
|
263
|
+
this.definizione = definizione;
|
|
264
|
+
this.manifest = manifest;
|
|
265
|
+
this.adattatore = adattatore;
|
|
266
|
+
this.dati = null;
|
|
267
|
+
this.frequenza = /* @__PURE__ */ new Map();
|
|
268
|
+
this.kickRichiesti = /* @__PURE__ */ new Set();
|
|
269
|
+
this.voceGuadagniCambiati = /* @__PURE__ */ new Map();
|
|
270
|
+
this.fineRichiesta = null;
|
|
271
|
+
this.applicandoAzioni = false;
|
|
272
|
+
this.ultimoStatoOsservato = "";
|
|
273
|
+
this.voceDaPersistire = false;
|
|
274
|
+
const nucleo = this;
|
|
275
|
+
const daily = {
|
|
276
|
+
get day() {
|
|
277
|
+
return giornoUtc(nucleo.adattatore.ora());
|
|
278
|
+
},
|
|
279
|
+
get seed() {
|
|
280
|
+
return seedGiornata(nucleo.manifest.id, giornoUtc(nucleo.adattatore.ora()));
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
this.room = {
|
|
284
|
+
get id() {
|
|
285
|
+
return nucleo.richiediDati().id;
|
|
286
|
+
},
|
|
287
|
+
get mode() {
|
|
288
|
+
return nucleo.richiediDati().mode;
|
|
289
|
+
},
|
|
290
|
+
get status() {
|
|
291
|
+
return nucleo.richiediDati().status;
|
|
292
|
+
},
|
|
293
|
+
get tick() {
|
|
294
|
+
return nucleo.richiediDati().tick;
|
|
295
|
+
},
|
|
296
|
+
get state() {
|
|
297
|
+
return nucleo.richiediDati().state;
|
|
298
|
+
},
|
|
299
|
+
set state(value) {
|
|
300
|
+
nucleo.richiediDati().state = value;
|
|
301
|
+
},
|
|
302
|
+
get players() {
|
|
303
|
+
return nucleo.richiediDati().giocatori.map(copiaGiocatore);
|
|
304
|
+
},
|
|
305
|
+
get host() {
|
|
306
|
+
const dati = nucleo.richiediDati();
|
|
307
|
+
const host = dati.giocatori.find((player) => player.id === dati.hostId);
|
|
308
|
+
return host === void 0 ? null : copiaGiocatore(host);
|
|
309
|
+
},
|
|
310
|
+
broadcast(message) {
|
|
311
|
+
nucleo.broadcastCreatore(message);
|
|
312
|
+
},
|
|
313
|
+
send(player, message) {
|
|
314
|
+
nucleo.inviaCreatore(idGiocatore(player), message);
|
|
315
|
+
},
|
|
316
|
+
kick(player) {
|
|
317
|
+
nucleo.kickRichiesti.add(idGiocatore(player));
|
|
318
|
+
},
|
|
319
|
+
end(result) {
|
|
320
|
+
nucleo.richiediFine(result);
|
|
321
|
+
},
|
|
322
|
+
save(key, value) {
|
|
323
|
+
return nucleo.salva(key, value);
|
|
324
|
+
},
|
|
325
|
+
load(key) {
|
|
326
|
+
return nucleo.caricaSave(key);
|
|
327
|
+
},
|
|
328
|
+
schedule(milliseconds, handler, payload) {
|
|
329
|
+
nucleo.pianifica(milliseconds, handler, payload);
|
|
330
|
+
},
|
|
331
|
+
board: {
|
|
332
|
+
submit(player, board, score, options = {}) {
|
|
333
|
+
nucleo.accodaPunteggio(idGiocatore(player), board, score, options.daily === true);
|
|
334
|
+
}
|
|
335
|
+
},
|
|
336
|
+
daily,
|
|
337
|
+
time: { now: () => nucleo.adattatore.ora() },
|
|
338
|
+
voice: {
|
|
339
|
+
get mode() {
|
|
340
|
+
return nucleo.manifest.voice ?? "none";
|
|
341
|
+
},
|
|
342
|
+
setProximity(a, b, gain) {
|
|
343
|
+
nucleo.impostaProssimita(idGiocatore(a), idGiocatore(b), gain);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
static async apri(definizione, manifest, adattatore) {
|
|
349
|
+
if (!definizioneValida(definizione)) {
|
|
350
|
+
throw new TypeError("The game server must export a definition created with defineGame.");
|
|
351
|
+
}
|
|
352
|
+
_NucleoStanza.verificaManifest(manifest);
|
|
353
|
+
const nucleo = new _NucleoStanza(definizione, manifest, adattatore);
|
|
354
|
+
const salvato = await adattatore.storage.get(CHIAVE_NUCLEO);
|
|
355
|
+
if (salvato !== void 0) {
|
|
356
|
+
nucleo.dati = salvato;
|
|
357
|
+
const daAggiornare = salvato.ultimoInputAt === void 0 || salvato.ultimoCambioStatoAt === void 0;
|
|
358
|
+
salvato.ultimoInputAt ??= adattatore.ora();
|
|
359
|
+
salvato.ultimoCambioStatoAt ??= salvato.ultimoInputAt;
|
|
360
|
+
nucleo.ultimoStatoOsservato = JSON.stringify(salvato.state);
|
|
361
|
+
await nucleo.riconciliaConnessioni();
|
|
362
|
+
if (daAggiornare) await nucleo.persisti();
|
|
363
|
+
}
|
|
364
|
+
await nucleo.aggiornaProgrammazione();
|
|
365
|
+
return nucleo;
|
|
366
|
+
}
|
|
367
|
+
static verificaManifest(manifest) {
|
|
368
|
+
if (typeof manifest?.id !== "string" || !Number.isInteger(manifest.players?.min) || !Number.isInteger(manifest.players?.max) || manifest.players.min < 1 || manifest.players.max < manifest.players.min || typeof manifest.lobby !== "boolean" || !Array.isArray(manifest.roles) || !Array.isArray(manifest.modes) || manifest.voice !== void 0 && !["none", "room", "team", "proximity"].includes(manifest.voice)) {
|
|
369
|
+
throw new TypeError("The room manifest is invalid.");
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
richiediDati() {
|
|
373
|
+
if (this.dati === null) throw new Error("The room has not been created.");
|
|
374
|
+
return this.dati;
|
|
375
|
+
}
|
|
376
|
+
stanzaTerminata() {
|
|
377
|
+
return this.dati?.status === "ended";
|
|
378
|
+
}
|
|
379
|
+
get esiste() {
|
|
380
|
+
return this.dati !== null;
|
|
381
|
+
}
|
|
382
|
+
async crea(id, mode, _creator) {
|
|
383
|
+
if (this.dati !== null) return false;
|
|
384
|
+
if (mode !== null && !this.manifest.modes.some((item) => item.id === mode)) {
|
|
385
|
+
throw new Error("The selected game mode does not exist.");
|
|
386
|
+
}
|
|
387
|
+
const ora = this.adattatore.ora();
|
|
388
|
+
this.dati = {
|
|
389
|
+
versione: 1,
|
|
390
|
+
id,
|
|
391
|
+
mode,
|
|
392
|
+
status: "lobby",
|
|
393
|
+
tick: 0,
|
|
394
|
+
tickRate: this.definizione.tickRate,
|
|
395
|
+
ultimoInputAt: ora,
|
|
396
|
+
ultimoCambioStatoAt: ora,
|
|
397
|
+
state: {},
|
|
398
|
+
giocatori: [],
|
|
399
|
+
hostId: null,
|
|
400
|
+
result: null,
|
|
401
|
+
resultAt: null,
|
|
402
|
+
countdownAt: null,
|
|
403
|
+
timer: [],
|
|
404
|
+
prossimoTimerId: 1,
|
|
405
|
+
punteggi: [],
|
|
406
|
+
fineInCoda: null,
|
|
407
|
+
vuotaDa: ora,
|
|
408
|
+
cancellaDopoFlush: false,
|
|
409
|
+
tickSincronizzato: 0,
|
|
410
|
+
statoSincronizzato: {},
|
|
411
|
+
durateCpu: [],
|
|
412
|
+
cpuOltreCento: 0,
|
|
413
|
+
voceGuadagni: {}
|
|
414
|
+
};
|
|
415
|
+
await this.chiama(this.definizione.onCreate, this.room);
|
|
416
|
+
await this.applicaAzioni();
|
|
417
|
+
this.inviaGuadagniCambiati();
|
|
418
|
+
if (this.dati.status !== "ended") {
|
|
419
|
+
const stato = analizzaJson(this.dati.state);
|
|
420
|
+
if (!stato.ok || stato.bytes > LIMITE_STATO) {
|
|
421
|
+
await this.terminaPerStato(stato.ok ? "state_too_large" : "state_invalid");
|
|
422
|
+
} else {
|
|
423
|
+
this.dati.state = stato.valore;
|
|
424
|
+
this.dati.statoSincronizzato = copiaJson(stato.valore);
|
|
425
|
+
this.ultimoStatoOsservato = stato.testo;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
await this.persistiEProgramma();
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
info() {
|
|
432
|
+
if (this.dati === null) return null;
|
|
433
|
+
return {
|
|
434
|
+
roomId: this.dati.id,
|
|
435
|
+
status: this.dati.status,
|
|
436
|
+
players: this.dati.giocatori.filter(
|
|
437
|
+
(player) => player.connected || player.graziaFinoA !== null
|
|
438
|
+
).length,
|
|
439
|
+
max: this.manifest.players.max,
|
|
440
|
+
mode: this.dati.mode
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
giocatoreConnesso(connessione) {
|
|
444
|
+
const player = this.dati?.giocatori.find(
|
|
445
|
+
(item) => item.connected && item.connessione === connessione
|
|
446
|
+
);
|
|
447
|
+
return player === void 0 ? null : copiaGiocatore(player);
|
|
448
|
+
}
|
|
449
|
+
puoEntrare(identity) {
|
|
450
|
+
if (this.dati === null) return { ok: false, code: "room_not_found" };
|
|
451
|
+
if (this.dati.status === "ended") return { ok: false, code: "room_ended" };
|
|
452
|
+
const esistente = this.dati.giocatori.find((player) => player.id === identity.id);
|
|
453
|
+
if (esistente !== void 0) return { ok: true };
|
|
454
|
+
if (this.manifest.lobby && this.dati.status !== "lobby") {
|
|
455
|
+
return { ok: false, code: "room_playing" };
|
|
456
|
+
}
|
|
457
|
+
if (this.dati.giocatori.length >= this.manifest.players.max) {
|
|
458
|
+
return { ok: false, code: "room_full" };
|
|
459
|
+
}
|
|
460
|
+
return { ok: true };
|
|
461
|
+
}
|
|
462
|
+
async entra(identity, connessione) {
|
|
463
|
+
await this.terminaSeInattiva();
|
|
464
|
+
const permesso = this.puoEntrare(identity);
|
|
465
|
+
if (!permesso.ok) {
|
|
466
|
+
this.adattatore.chiudi(connessione, codiceIngresso(permesso.code), permesso.code);
|
|
467
|
+
return permesso;
|
|
468
|
+
}
|
|
469
|
+
const dati = this.richiediDati();
|
|
470
|
+
const ora = this.adattatore.ora();
|
|
471
|
+
let player = dati.giocatori.find((item) => item.id === identity.id);
|
|
472
|
+
const nuovo = player === void 0;
|
|
473
|
+
if (player === void 0) {
|
|
474
|
+
player = {
|
|
475
|
+
...identity,
|
|
476
|
+
role: this.ruoloAutomatico(),
|
|
477
|
+
team: this.squadraAutomatica(),
|
|
478
|
+
ready: false,
|
|
479
|
+
connected: true,
|
|
480
|
+
entratoAt: ora,
|
|
481
|
+
graziaFinoA: null,
|
|
482
|
+
connessione,
|
|
483
|
+
seq: 0
|
|
484
|
+
};
|
|
485
|
+
dati.giocatori.push(player);
|
|
486
|
+
dati.hostId ??= player.id;
|
|
487
|
+
} else {
|
|
488
|
+
if (player.connected && player.connessione !== null && player.connessione !== connessione) {
|
|
489
|
+
this.adattatore.chiudi(player.connessione, 4006, "replaced");
|
|
490
|
+
}
|
|
491
|
+
player.name = identity.name;
|
|
492
|
+
player.guest = identity.guest;
|
|
493
|
+
player.connected = true;
|
|
494
|
+
player.graziaFinoA = null;
|
|
495
|
+
player.connessione = connessione;
|
|
496
|
+
player.seq = 0;
|
|
497
|
+
}
|
|
498
|
+
dati.vuotaDa = null;
|
|
499
|
+
dati.ultimoInputAt = ora;
|
|
500
|
+
const primaConnessione = !this.manifest.lobby && dati.status === "lobby";
|
|
501
|
+
if (primaConnessione) dati.status = "playing";
|
|
502
|
+
if (nuovo) {
|
|
503
|
+
await this.chiama(
|
|
504
|
+
this.definizione.onJoin,
|
|
505
|
+
this.room,
|
|
506
|
+
copiaGiocatore(player)
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
if (primaConnessione) {
|
|
510
|
+
await this.chiama(this.definizione.onStart, this.room);
|
|
511
|
+
this.inviaStatus(ora);
|
|
512
|
+
}
|
|
513
|
+
await this.concludiEvento();
|
|
514
|
+
if (dati.status !== "ended") {
|
|
515
|
+
this.inviaWelcome(player);
|
|
516
|
+
this.inviaSnapshotTutti();
|
|
517
|
+
this.inviaGiocatori();
|
|
518
|
+
}
|
|
519
|
+
await this.persistiEProgramma();
|
|
520
|
+
return { ok: true };
|
|
521
|
+
}
|
|
522
|
+
async disconnetti(connessione) {
|
|
523
|
+
if (this.dati === null || this.dati.status === "ended") return;
|
|
524
|
+
const player = this.dati.giocatori.find(
|
|
525
|
+
(item) => item.connected && item.connessione === connessione
|
|
526
|
+
);
|
|
527
|
+
if (player === void 0) return;
|
|
528
|
+
player.connected = false;
|
|
529
|
+
player.connessione = null;
|
|
530
|
+
player.graziaFinoA = this.adattatore.ora() + GRAZIA_MS;
|
|
531
|
+
this.frequenza.delete(connessione);
|
|
532
|
+
if (this.dati.hostId === player.id) this.assegnaHost();
|
|
533
|
+
this.verificaCountdown();
|
|
534
|
+
this.inviaGiocatori();
|
|
535
|
+
await this.persistiEProgramma();
|
|
536
|
+
}
|
|
537
|
+
async ricevi(connessione, frame) {
|
|
538
|
+
if (this.dati === null || this.dati.status === "ended") return;
|
|
539
|
+
if (await this.terminaSeInattiva()) return;
|
|
540
|
+
const player = this.dati.giocatori.find(
|
|
541
|
+
(item) => item.connected && item.connessione === connessione
|
|
542
|
+
);
|
|
543
|
+
if (player === void 0) return;
|
|
544
|
+
if (new TextEncoder().encode(frame).byteLength > LIMITE_FRAME) {
|
|
545
|
+
await this.chiudiConnessione(player, 4009, "bad_message");
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
const ora = this.adattatore.ora();
|
|
549
|
+
const recenti = (this.frequenza.get(connessione) ?? []).filter((at) => ora - at < 1e3);
|
|
550
|
+
if (recenti.length >= 20) {
|
|
551
|
+
await this.chiudiConnessione(player, 4008, "rate_limited");
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
recenti.push(ora);
|
|
555
|
+
this.frequenza.set(connessione, recenti);
|
|
556
|
+
let message = null;
|
|
557
|
+
try {
|
|
558
|
+
message = record(JSON.parse(frame));
|
|
559
|
+
} catch {
|
|
560
|
+
}
|
|
561
|
+
if (message === null || typeof message.t !== "string") {
|
|
562
|
+
await this.chiudiConnessione(player, 4009, "bad_message");
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (message.t === "ping") {
|
|
566
|
+
if (typeof message.c !== "number" || !Number.isFinite(message.c)) {
|
|
567
|
+
await this.chiudiConnessione(player, 4009, "bad_message");
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
this.adattatore.invia(connessione, { t: "pong", c: message.c, s: ora });
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (message.t === "resync") {
|
|
574
|
+
this.inviaSnapshotTutti();
|
|
575
|
+
await this.persistiEProgramma();
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
if (message.t === "leave") {
|
|
579
|
+
this.dati.ultimoInputAt = ora;
|
|
580
|
+
await this.rimuoviGiocatore(player, "left");
|
|
581
|
+
this.adattatore.chiudi(connessione, 1e3, "left");
|
|
582
|
+
await this.concludiEvento();
|
|
583
|
+
this.inviaGiocatori();
|
|
584
|
+
await this.persistiEProgramma();
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
if (message.t === "ready") {
|
|
588
|
+
if (typeof message.ready !== "boolean") return this.messaggioErrato(player);
|
|
589
|
+
if (!this.inLobby(player)) return;
|
|
590
|
+
this.dati.ultimoInputAt = ora;
|
|
591
|
+
player.ready = message.ready;
|
|
592
|
+
this.inviaGiocatori();
|
|
593
|
+
await this.persistiEProgramma();
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (message.t === "role") {
|
|
597
|
+
if (typeof message.role !== "string") return this.messaggioErrato(player);
|
|
598
|
+
if (!this.inLobby(player)) return;
|
|
599
|
+
this.dati.ultimoInputAt = ora;
|
|
600
|
+
this.scegliRuolo(player, message.role);
|
|
601
|
+
await this.persistiEProgramma();
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
if (message.t === "team") {
|
|
605
|
+
if (!Number.isInteger(message.team)) return this.messaggioErrato(player);
|
|
606
|
+
if (!this.inLobby(player)) return;
|
|
607
|
+
this.dati.ultimoInputAt = ora;
|
|
608
|
+
this.scegliSquadra(player, message.team);
|
|
609
|
+
await this.persistiEProgramma();
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
if (message.t === "start") {
|
|
613
|
+
if (!this.inLobby(player)) return;
|
|
614
|
+
this.dati.ultimoInputAt = ora;
|
|
615
|
+
await this.avviaCountdown(player);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (message.t === "msg") {
|
|
619
|
+
if (!Number.isSafeInteger(message.seq) || message.seq < 1) {
|
|
620
|
+
await this.messaggioErrato(player);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const seq = message.seq;
|
|
624
|
+
if (seq <= player.seq) return;
|
|
625
|
+
const contenuto = analizzaJson(message.m);
|
|
626
|
+
if (!contenuto.ok) {
|
|
627
|
+
await this.messaggioErrato(player);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
player.seq = seq;
|
|
631
|
+
if (player.role === "spectator") {
|
|
632
|
+
this.inviaErrore(player, "spectator", "Spectators cannot send game input.");
|
|
633
|
+
await this.persistiEProgramma();
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
this.dati.ultimoInputAt = ora;
|
|
637
|
+
await this.chiama(
|
|
638
|
+
this.definizione.onMessage,
|
|
639
|
+
this.room,
|
|
640
|
+
copiaGiocatore(player),
|
|
641
|
+
contenuto.valore
|
|
642
|
+
);
|
|
643
|
+
await this.concludiEvento();
|
|
644
|
+
await this.persistiEProgramma();
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
await this.messaggioErrato(player);
|
|
648
|
+
}
|
|
649
|
+
async eseguiTick() {
|
|
650
|
+
if (this.dati === null || this.dati.status !== "playing" || this.dati.tickRate === 0) return;
|
|
651
|
+
if (await this.terminaSeInattiva()) return;
|
|
652
|
+
if (!this.serveTick()) {
|
|
653
|
+
await this.persistiEProgramma();
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
const dati = this.dati;
|
|
657
|
+
dati.tick++;
|
|
658
|
+
const inizio = this.adattatore.misuraCpu();
|
|
659
|
+
await this.chiama(
|
|
660
|
+
this.definizione.onTick,
|
|
661
|
+
this.room,
|
|
662
|
+
1 / dati.tickRate
|
|
663
|
+
);
|
|
664
|
+
const durata = Math.max(0, this.adattatore.misuraCpu() - inizio);
|
|
665
|
+
this.registraCpu(durata);
|
|
666
|
+
await this.applicaAzioni();
|
|
667
|
+
if (dati.status === "ended") return;
|
|
668
|
+
this.inviaGuadagniCambiati();
|
|
669
|
+
const stato = await this.verificaStato();
|
|
670
|
+
if (stato === null || this.stanzaTerminata()) return;
|
|
671
|
+
const cambiato = stato.testo !== JSON.stringify(dati.statoSincronizzato);
|
|
672
|
+
if (dati.tick % 100 === 0) {
|
|
673
|
+
dati.state = stato.valore;
|
|
674
|
+
this.inviaSnapshotTutti();
|
|
675
|
+
} else if (cambiato) {
|
|
676
|
+
const base = dati.tickSincronizzato;
|
|
677
|
+
this.broadcast({
|
|
678
|
+
t: "state",
|
|
679
|
+
tick: dati.tick,
|
|
680
|
+
serverTime: this.adattatore.ora(),
|
|
681
|
+
base,
|
|
682
|
+
patch: creaDiff(dati.statoSincronizzato, stato.valore)
|
|
683
|
+
});
|
|
684
|
+
dati.state = stato.valore;
|
|
685
|
+
dati.statoSincronizzato = copiaJson(stato.valore);
|
|
686
|
+
dati.tickSincronizzato = dati.tick;
|
|
687
|
+
}
|
|
688
|
+
if (dati.tick % 100 === 0 || this.voceDaPersistire) await this.persisti();
|
|
689
|
+
await this.aggiornaProgrammazione();
|
|
690
|
+
}
|
|
691
|
+
async sveglia() {
|
|
692
|
+
if (this.dati === null || this.dati.status === "ended") return;
|
|
693
|
+
if (await this.terminaSeInattiva()) return;
|
|
694
|
+
const ora = this.adattatore.ora();
|
|
695
|
+
const scaduti = this.dati.giocatori.filter(
|
|
696
|
+
(player) => !player.connected && player.graziaFinoA !== null && player.graziaFinoA <= ora
|
|
697
|
+
);
|
|
698
|
+
for (const player of scaduti) await this.rimuoviGiocatore(player, "timeout");
|
|
699
|
+
if (this.dati.status === "countdown" && this.dati.countdownAt !== null && this.dati.countdownAt <= ora) {
|
|
700
|
+
const errore = this.erroreMinimi();
|
|
701
|
+
if (errore !== null) {
|
|
702
|
+
this.dati.status = "lobby";
|
|
703
|
+
this.dati.countdownAt = null;
|
|
704
|
+
this.broadcast({ t: "error", code: errore.code, message: errore.message });
|
|
705
|
+
this.inviaStatus(ora);
|
|
706
|
+
} else {
|
|
707
|
+
this.dati.status = "playing";
|
|
708
|
+
this.dati.ultimoInputAt = ora;
|
|
709
|
+
this.dati.countdownAt = null;
|
|
710
|
+
await this.chiama(this.definizione.onStart, this.room);
|
|
711
|
+
this.inviaStatus(ora);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
const dovuti = this.dati.timer.filter((timer) => timer.at <= ora).sort((a, b) => a.at - b.at || a.id - b.id);
|
|
715
|
+
if (dovuti.length > 0) {
|
|
716
|
+
const ids = new Set(dovuti.map((timer) => timer.id));
|
|
717
|
+
this.dati.timer = this.dati.timer.filter((timer) => !ids.has(timer.id));
|
|
718
|
+
for (const timer of dovuti) await this.eseguiTimer(timer);
|
|
719
|
+
}
|
|
720
|
+
await this.concludiEvento();
|
|
721
|
+
if (!this.stanzaTerminata() && this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null && this.dati.vuotaDa + STANZA_VUOTA_MS <= ora) {
|
|
722
|
+
this.dati.cancellaDopoFlush = true;
|
|
723
|
+
await this.terminaInterna(null);
|
|
724
|
+
}
|
|
725
|
+
if (scaduti.length > 0) this.inviaGiocatori();
|
|
726
|
+
await this.concludiEvento();
|
|
727
|
+
await this.persistiEProgramma();
|
|
728
|
+
}
|
|
729
|
+
async flush() {
|
|
730
|
+
const dati = this.richiediDati();
|
|
731
|
+
const esito = {
|
|
732
|
+
scores: dati.punteggi.map((score) => ({ ...score })),
|
|
733
|
+
ended: dati.fineInCoda === null ? null : { result: dati.fineInCoda.result, at: dati.fineInCoda.at }
|
|
734
|
+
};
|
|
735
|
+
dati.punteggi = [];
|
|
736
|
+
dati.fineInCoda = null;
|
|
737
|
+
if (dati.cancellaDopoFlush && dati.status === "ended") {
|
|
738
|
+
const chiavi = await this.adattatore.storage.list();
|
|
739
|
+
for (const key of chiavi.keys()) await this.adattatore.storage.delete(key);
|
|
740
|
+
this.dati = null;
|
|
741
|
+
this.adattatore.programmaTick(null);
|
|
742
|
+
await this.adattatore.programmaSveglia(null);
|
|
743
|
+
} else {
|
|
744
|
+
await this.persistiEProgramma();
|
|
745
|
+
}
|
|
746
|
+
return esito;
|
|
747
|
+
}
|
|
748
|
+
async riconciliaConnessioni() {
|
|
749
|
+
const dati = this.richiediDati();
|
|
750
|
+
const attive = new Set(this.adattatore.connessioniAttive());
|
|
751
|
+
const ora = this.adattatore.ora();
|
|
752
|
+
let cambiato = false;
|
|
753
|
+
for (const player of dati.giocatori) {
|
|
754
|
+
if (player.connected && (player.connessione === null || !attive.has(player.connessione))) {
|
|
755
|
+
player.connected = false;
|
|
756
|
+
player.connessione = null;
|
|
757
|
+
player.graziaFinoA = ora + GRAZIA_MS;
|
|
758
|
+
cambiato = true;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (cambiato) {
|
|
762
|
+
this.assegnaHost();
|
|
763
|
+
await this.persisti();
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
ruoloAutomatico() {
|
|
767
|
+
if (this.manifest.roles.length === 0) return null;
|
|
768
|
+
const dati = this.richiediDati();
|
|
769
|
+
const candidati = this.manifest.roles.filter((role) => {
|
|
770
|
+
const count = dati.giocatori.filter((player) => player.role === role.id).length;
|
|
771
|
+
return role.max === void 0 || count < role.max;
|
|
772
|
+
});
|
|
773
|
+
candidati.sort((a, b) => {
|
|
774
|
+
const countA = dati.giocatori.filter((player) => player.role === a.id).length;
|
|
775
|
+
const countB = dati.giocatori.filter((player) => player.role === b.id).length;
|
|
776
|
+
const mancaA = countA < a.min ? 0 : 1;
|
|
777
|
+
const mancaB = countB < b.min ? 0 : 1;
|
|
778
|
+
return mancaA - mancaB || countA - countB;
|
|
779
|
+
});
|
|
780
|
+
return candidati[0]?.id ?? "spectator";
|
|
781
|
+
}
|
|
782
|
+
squadraAutomatica() {
|
|
783
|
+
if (this.manifest.teams === null) return null;
|
|
784
|
+
const dati = this.richiediDati();
|
|
785
|
+
let scelta = 1;
|
|
786
|
+
let minimo = Number.POSITIVE_INFINITY;
|
|
787
|
+
for (let team = 1; team <= this.manifest.teams.min; team++) {
|
|
788
|
+
const count = dati.giocatori.filter((player) => player.team === team).length;
|
|
789
|
+
if (count < minimo) {
|
|
790
|
+
minimo = count;
|
|
791
|
+
scelta = team;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
return scelta;
|
|
795
|
+
}
|
|
796
|
+
inLobby(player) {
|
|
797
|
+
if (this.richiediDati().status === "lobby") return true;
|
|
798
|
+
this.inviaErrore(player, "not_in_lobby", "This action is only available in the lobby.");
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
scegliRuolo(player, roleId) {
|
|
802
|
+
const ruolo = this.manifest.roles.find((item) => item.id === roleId);
|
|
803
|
+
if (ruolo === void 0 && roleId !== "spectator") {
|
|
804
|
+
this.inviaErrore(player, "invalid_role", "This role does not exist.");
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const occupati = this.richiediDati().giocatori.filter(
|
|
808
|
+
(item) => item.id !== player.id && item.role === roleId
|
|
809
|
+
).length;
|
|
810
|
+
if (ruolo?.max !== void 0 && occupati >= ruolo.max) {
|
|
811
|
+
this.inviaErrore(player, "role_full", "This role is full.");
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
player.role = roleId;
|
|
815
|
+
if (roleId === "spectator") player.team = null;
|
|
816
|
+
else if (player.team === null) player.team = this.squadraAutomatica();
|
|
817
|
+
player.ready = false;
|
|
818
|
+
this.inviaGiocatori();
|
|
819
|
+
}
|
|
820
|
+
scegliSquadra(player, team) {
|
|
821
|
+
if (this.manifest.teams === null || team < 1 || team > this.manifest.teams.max) {
|
|
822
|
+
this.inviaErrore(player, "invalid_team", "This team does not exist.");
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
if (player.role === "spectator") {
|
|
826
|
+
this.inviaErrore(player, "spectator", "Spectators cannot join a team.");
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
player.team = team;
|
|
830
|
+
player.ready = false;
|
|
831
|
+
this.inviaGiocatori();
|
|
832
|
+
}
|
|
833
|
+
erroreMinimi() {
|
|
834
|
+
const connessi = this.richiediDati().giocatori.filter((player) => player.connected);
|
|
835
|
+
const attivi = connessi.filter((player) => player.role !== "spectator");
|
|
836
|
+
if (attivi.length < this.manifest.players.min) {
|
|
837
|
+
return { code: "not_enough_players", message: "The room does not have enough players." };
|
|
838
|
+
}
|
|
839
|
+
if (connessi.some((player) => !player.ready)) {
|
|
840
|
+
return { code: "players_not_ready", message: "Every connected player must be ready." };
|
|
841
|
+
}
|
|
842
|
+
for (const role of this.manifest.roles) {
|
|
843
|
+
if (attivi.filter((player) => player.role === role.id).length < role.min) {
|
|
844
|
+
return { code: "role_minimum", message: `Role ${role.id} does not meet its minimum.` };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (this.manifest.teams !== null) {
|
|
848
|
+
const squadre = new Set(attivi.map((player) => player.team).filter((team) => team !== null));
|
|
849
|
+
if (attivi.some((player) => player.team === null) || squadre.size < this.manifest.teams.min) {
|
|
850
|
+
return { code: "team_minimum", message: "The room does not have enough teams." };
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
async avviaCountdown(player) {
|
|
856
|
+
const dati = this.richiediDati();
|
|
857
|
+
if (dati.hostId !== player.id) {
|
|
858
|
+
this.inviaErrore(player, "not_host", "Only the host can start the game.");
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const errore = this.erroreMinimi();
|
|
862
|
+
if (errore !== null) {
|
|
863
|
+
this.inviaErrore(player, errore.code, errore.message);
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
dati.status = "countdown";
|
|
867
|
+
dati.countdownAt = this.adattatore.ora() + COUNTDOWN_MS;
|
|
868
|
+
this.inviaStatus(dati.countdownAt);
|
|
869
|
+
await this.persistiEProgramma();
|
|
870
|
+
}
|
|
871
|
+
verificaCountdown() {
|
|
872
|
+
const dati = this.richiediDati();
|
|
873
|
+
if (dati.status !== "countdown" || this.erroreMinimi() === null) return;
|
|
874
|
+
dati.status = "lobby";
|
|
875
|
+
dati.countdownAt = null;
|
|
876
|
+
this.inviaStatus(this.adattatore.ora());
|
|
877
|
+
}
|
|
878
|
+
async messaggioErrato(player) {
|
|
879
|
+
await this.chiudiConnessione(player, 4009, "bad_message");
|
|
880
|
+
}
|
|
881
|
+
async chiudiConnessione(player, codice, motivo) {
|
|
882
|
+
const connessione = player.connessione;
|
|
883
|
+
if (connessione !== null) this.adattatore.chiudi(connessione, codice, motivo);
|
|
884
|
+
await this.disconnetti(connessione ?? "");
|
|
885
|
+
}
|
|
886
|
+
async rimuoviGiocatore(player, reason) {
|
|
887
|
+
const dati = this.richiediDati();
|
|
888
|
+
const indice = dati.giocatori.findIndex((item) => item.id === player.id);
|
|
889
|
+
if (indice < 0) return;
|
|
890
|
+
dati.giocatori.splice(indice, 1);
|
|
891
|
+
this.pulisciGuadagni(player.id);
|
|
892
|
+
if (dati.hostId === player.id) this.assegnaHost();
|
|
893
|
+
if (dati.giocatori.length === 0) dati.vuotaDa = this.adattatore.ora();
|
|
894
|
+
await this.chiama(
|
|
895
|
+
this.definizione.onLeave,
|
|
896
|
+
this.room,
|
|
897
|
+
copiaGiocatore({ ...player, connected: false, connessione: null }),
|
|
898
|
+
reason
|
|
899
|
+
);
|
|
900
|
+
this.verificaCountdown();
|
|
901
|
+
}
|
|
902
|
+
assegnaHost() {
|
|
903
|
+
const dati = this.richiediDati();
|
|
904
|
+
const host = dati.giocatori.filter((player) => player.connected).sort((a, b) => a.entratoAt - b.entratoAt)[0];
|
|
905
|
+
dati.hostId = host?.id ?? null;
|
|
906
|
+
}
|
|
907
|
+
async eseguiTimer(timer) {
|
|
908
|
+
const value = this.definizione[timer.handler];
|
|
909
|
+
await this.chiama(
|
|
910
|
+
typeof value === "function" ? value : void 0,
|
|
911
|
+
this.room,
|
|
912
|
+
timer.payload
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
pianifica(milliseconds, handler, payload) {
|
|
916
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) {
|
|
917
|
+
throw new TypeError("Schedule delay must be a non-negative integer.");
|
|
918
|
+
}
|
|
919
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(handler)) {
|
|
920
|
+
throw new TypeError("Schedule handler must be a method name.");
|
|
921
|
+
}
|
|
922
|
+
const callback = this.definizione[handler];
|
|
923
|
+
if (typeof callback !== "function") {
|
|
924
|
+
throw new TypeError(`Schedule handler ${handler} is not defined.`);
|
|
925
|
+
}
|
|
926
|
+
const json = analizzaJson(payload);
|
|
927
|
+
if (!json.ok) throw new TypeError("Schedule payload must be valid JSON.");
|
|
928
|
+
const dati = this.richiediDati();
|
|
929
|
+
dati.timer.push({
|
|
930
|
+
id: dati.prossimoTimerId++,
|
|
931
|
+
at: this.adattatore.ora() + milliseconds,
|
|
932
|
+
handler,
|
|
933
|
+
payload: json.valore
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
accodaPunteggio(playerId, board, score, daily) {
|
|
937
|
+
if (!this.richiediDati().giocatori.some((player) => player.id === playerId)) {
|
|
938
|
+
throw new Error("Player not found.");
|
|
939
|
+
}
|
|
940
|
+
if (!CHIAVE.test(board)) {
|
|
941
|
+
throw new TypeError("Board names must use lowercase letters, numbers, underscores, or hyphens.");
|
|
942
|
+
}
|
|
943
|
+
if (!Number.isSafeInteger(score) || score < 0) {
|
|
944
|
+
throw new TypeError("Score must be a non-negative safe integer.");
|
|
945
|
+
}
|
|
946
|
+
this.richiediDati().punteggi.push({ playerId, board, score, daily });
|
|
947
|
+
this.broadcast({ t: "flush" });
|
|
948
|
+
}
|
|
949
|
+
richiediFine(result) {
|
|
950
|
+
const json = analizzaJson(result);
|
|
951
|
+
if (!json.ok) throw new TypeError("Game result must be valid JSON.");
|
|
952
|
+
this.fineRichiesta = json.valore;
|
|
953
|
+
}
|
|
954
|
+
async salva(key, value) {
|
|
955
|
+
if (!CHIAVE.test(key)) {
|
|
956
|
+
throw new TypeError("Save keys must use lowercase letters, numbers, underscores, or hyphens.");
|
|
957
|
+
}
|
|
958
|
+
const json = analizzaJson(value);
|
|
959
|
+
if (!json.ok) throw new TypeError("Saved values must be valid JSON.");
|
|
960
|
+
if (json.bytes > LIMITE_SAVE) {
|
|
961
|
+
throw new RangeError("Saved values must be at most 131072 bytes.");
|
|
962
|
+
}
|
|
963
|
+
await this.adattatore.storage.put(PREFISSO_SAVE + key, json.valore);
|
|
964
|
+
}
|
|
965
|
+
async caricaSave(key) {
|
|
966
|
+
if (!CHIAVE.test(key)) {
|
|
967
|
+
throw new TypeError("Save keys must use lowercase letters, numbers, underscores, or hyphens.");
|
|
968
|
+
}
|
|
969
|
+
const value = await this.adattatore.storage.get(PREFISSO_SAVE + key);
|
|
970
|
+
if (value === void 0) return null;
|
|
971
|
+
const json = analizzaJson(value);
|
|
972
|
+
if (!json.ok) throw new Error("The saved value is invalid.");
|
|
973
|
+
return json.valore;
|
|
974
|
+
}
|
|
975
|
+
broadcastCreatore(message) {
|
|
976
|
+
const json = analizzaJson(message);
|
|
977
|
+
if (!json.ok) throw new TypeError("Messages must be valid JSON.");
|
|
978
|
+
this.broadcast({ t: "msg", m: json.valore });
|
|
979
|
+
}
|
|
980
|
+
inviaCreatore(playerId, message) {
|
|
981
|
+
const json = analizzaJson(message);
|
|
982
|
+
if (!json.ok) throw new TypeError("Messages must be valid JSON.");
|
|
983
|
+
const player = this.richiediDati().giocatori.find((item) => item.id === playerId);
|
|
984
|
+
if (player === void 0) throw new Error("Player not found.");
|
|
985
|
+
if (player.connected && player.connessione !== null) {
|
|
986
|
+
this.adattatore.invia(player.connessione, { t: "msg", m: json.valore });
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
broadcast(message) {
|
|
990
|
+
for (const player of this.richiediDati().giocatori) {
|
|
991
|
+
if (player.connected && player.connessione !== null) {
|
|
992
|
+
this.adattatore.invia(player.connessione, message);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
inviaErrore(player, code, message) {
|
|
997
|
+
if (player.connected && player.connessione !== null) {
|
|
998
|
+
this.adattatore.invia(player.connessione, { t: "error", code, message });
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
giocatoriProtocollo() {
|
|
1002
|
+
return this.richiediDati().giocatori.map((player) => ({
|
|
1003
|
+
id: player.id,
|
|
1004
|
+
name: player.name,
|
|
1005
|
+
guest: player.guest,
|
|
1006
|
+
role: player.role,
|
|
1007
|
+
team: player.team,
|
|
1008
|
+
ready: player.ready,
|
|
1009
|
+
connected: player.connected
|
|
1010
|
+
}));
|
|
1011
|
+
}
|
|
1012
|
+
inviaWelcome(player) {
|
|
1013
|
+
if (!player.connected || player.connessione === null) return;
|
|
1014
|
+
const dati = this.richiediDati();
|
|
1015
|
+
this.adattatore.invia(player.connessione, {
|
|
1016
|
+
t: "welcome",
|
|
1017
|
+
you: player.id,
|
|
1018
|
+
room: {
|
|
1019
|
+
id: dati.id,
|
|
1020
|
+
status: dati.status,
|
|
1021
|
+
mode: dati.mode,
|
|
1022
|
+
tick: dati.tick,
|
|
1023
|
+
tickRate: dati.tickRate,
|
|
1024
|
+
serverTime: this.adattatore.ora(),
|
|
1025
|
+
host: dati.hostId
|
|
1026
|
+
},
|
|
1027
|
+
players: this.giocatoriProtocollo(),
|
|
1028
|
+
state: dati.state
|
|
1029
|
+
});
|
|
1030
|
+
const gains = dati.voceGuadagni?.[player.id];
|
|
1031
|
+
if (gains !== void 0 && Object.keys(gains).length > 0) {
|
|
1032
|
+
this.adattatore.invia(player.connessione, { t: "voice", op: "gain", gains: { ...gains } });
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
inviaGiocatori() {
|
|
1036
|
+
this.broadcast({ t: "players", players: this.giocatoriProtocollo() });
|
|
1037
|
+
}
|
|
1038
|
+
inviaStatus(at) {
|
|
1039
|
+
const dati = this.richiediDati();
|
|
1040
|
+
this.broadcast({
|
|
1041
|
+
t: "status",
|
|
1042
|
+
status: dati.status,
|
|
1043
|
+
at,
|
|
1044
|
+
result: dati.status === "ended" ? dati.result : null
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
inviaSnapshotTutti() {
|
|
1048
|
+
const dati = this.richiediDati();
|
|
1049
|
+
const stato = analizzaJson(dati.state);
|
|
1050
|
+
if (!stato.ok || stato.bytes > LIMITE_STATO) return;
|
|
1051
|
+
dati.state = stato.valore;
|
|
1052
|
+
dati.statoSincronizzato = copiaJson(stato.valore);
|
|
1053
|
+
dati.tickSincronizzato = dati.tick;
|
|
1054
|
+
this.broadcast({
|
|
1055
|
+
t: "snapshot",
|
|
1056
|
+
tick: dati.tick,
|
|
1057
|
+
serverTime: this.adattatore.ora(),
|
|
1058
|
+
state: stato.valore
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
async chiama(callback, ...args) {
|
|
1062
|
+
if (callback === void 0 || this.dati?.status === "ended") return;
|
|
1063
|
+
try {
|
|
1064
|
+
await callback(...args);
|
|
1065
|
+
} catch {
|
|
1066
|
+
this.fineRichiesta = { error: "callback_error" };
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
async applicaAzioni() {
|
|
1070
|
+
if (this.applicandoAzioni || this.dati === null) return;
|
|
1071
|
+
this.applicandoAzioni = true;
|
|
1072
|
+
try {
|
|
1073
|
+
while (this.kickRichiesti.size > 0 && this.dati.status !== "ended") {
|
|
1074
|
+
const playerId = this.kickRichiesti.values().next().value;
|
|
1075
|
+
if (playerId === void 0) break;
|
|
1076
|
+
this.kickRichiesti.delete(playerId);
|
|
1077
|
+
const player = this.dati.giocatori.find((item) => item.id === playerId);
|
|
1078
|
+
if (player === void 0) continue;
|
|
1079
|
+
if (player.connessione !== null) this.adattatore.chiudi(player.connessione, 4003, "kicked");
|
|
1080
|
+
await this.rimuoviGiocatore(player, "kicked");
|
|
1081
|
+
}
|
|
1082
|
+
if (this.fineRichiesta !== null && this.dati.status !== "ended") {
|
|
1083
|
+
const result = this.fineRichiesta;
|
|
1084
|
+
this.fineRichiesta = null;
|
|
1085
|
+
await this.terminaInterna(result);
|
|
1086
|
+
}
|
|
1087
|
+
} finally {
|
|
1088
|
+
this.applicandoAzioni = false;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
async concludiEvento() {
|
|
1092
|
+
await this.applicaAzioni();
|
|
1093
|
+
if (this.dati === null || this.dati.status === "ended") return;
|
|
1094
|
+
this.inviaGuadagniCambiati();
|
|
1095
|
+
const stato = await this.verificaStato();
|
|
1096
|
+
if (stato === null || this.stanzaTerminata()) return;
|
|
1097
|
+
const precedente = JSON.stringify(this.dati.statoSincronizzato);
|
|
1098
|
+
this.dati.state = stato.valore;
|
|
1099
|
+
if ((this.dati.tickRate === 0 || this.dati.status !== "playing") && stato.testo !== precedente) {
|
|
1100
|
+
this.dati.tick++;
|
|
1101
|
+
this.inviaSnapshotTutti();
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
async verificaStato() {
|
|
1105
|
+
const stato = analizzaJson(this.richiediDati().state);
|
|
1106
|
+
if (!stato.ok) {
|
|
1107
|
+
await this.terminaPerStato("state_invalid");
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
if (stato.bytes > LIMITE_STATO) {
|
|
1111
|
+
await this.terminaPerStato("state_too_large");
|
|
1112
|
+
return null;
|
|
1113
|
+
}
|
|
1114
|
+
if (stato.testo !== this.ultimoStatoOsservato) {
|
|
1115
|
+
this.richiediDati().ultimoCambioStatoAt = this.adattatore.ora();
|
|
1116
|
+
this.ultimoStatoOsservato = stato.testo;
|
|
1117
|
+
}
|
|
1118
|
+
return stato;
|
|
1119
|
+
}
|
|
1120
|
+
impostaProssimita(a, b, gain) {
|
|
1121
|
+
if ((this.manifest.voice ?? "none") !== "proximity") return;
|
|
1122
|
+
const dati = this.richiediDati();
|
|
1123
|
+
if (!dati.giocatori.some((player) => player.id === a) || !dati.giocatori.some((player) => player.id === b)) throw new Error("Player not found.");
|
|
1124
|
+
if (Number.isNaN(gain)) throw new TypeError("Voice gain must be a number.");
|
|
1125
|
+
if (a === b) return;
|
|
1126
|
+
const valore = Math.round(Math.min(1, Math.max(0, gain)) * 100) / 100;
|
|
1127
|
+
dati.voceGuadagni ??= {};
|
|
1128
|
+
this.salvaGuadagno(a, b, valore);
|
|
1129
|
+
this.salvaGuadagno(b, a, valore);
|
|
1130
|
+
}
|
|
1131
|
+
salvaGuadagno(playerId, altroId, valore) {
|
|
1132
|
+
const dati = this.richiediDati();
|
|
1133
|
+
dati.voceGuadagni ??= {};
|
|
1134
|
+
const precedente = dati.voceGuadagni[playerId]?.[altroId] ?? 1;
|
|
1135
|
+
if (precedente === valore) return;
|
|
1136
|
+
this.voceDaPersistire = true;
|
|
1137
|
+
if (valore === 1) {
|
|
1138
|
+
const riga = dati.voceGuadagni[playerId];
|
|
1139
|
+
if (riga !== void 0) {
|
|
1140
|
+
delete riga[altroId];
|
|
1141
|
+
if (Object.keys(riga).length === 0) delete dati.voceGuadagni[playerId];
|
|
1142
|
+
}
|
|
1143
|
+
} else {
|
|
1144
|
+
(dati.voceGuadagni[playerId] ??= {})[altroId] = valore;
|
|
1145
|
+
}
|
|
1146
|
+
(this.voceGuadagniCambiati.get(playerId) ?? this.creaCambiVoce(playerId))[altroId] = valore;
|
|
1147
|
+
}
|
|
1148
|
+
creaCambiVoce(playerId) {
|
|
1149
|
+
const cambi = {};
|
|
1150
|
+
this.voceGuadagniCambiati.set(playerId, cambi);
|
|
1151
|
+
return cambi;
|
|
1152
|
+
}
|
|
1153
|
+
inviaGuadagniCambiati() {
|
|
1154
|
+
if (this.dati === null || this.voceGuadagniCambiati.size === 0) return;
|
|
1155
|
+
for (const [playerId, gains] of this.voceGuadagniCambiati) {
|
|
1156
|
+
const player = this.dati.giocatori.find((item) => item.id === playerId);
|
|
1157
|
+
if (player?.connected && player.connessione !== null) {
|
|
1158
|
+
this.adattatore.invia(player.connessione, { t: "voice", op: "gain", gains: { ...gains } });
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
this.voceGuadagniCambiati.clear();
|
|
1162
|
+
}
|
|
1163
|
+
pulisciGuadagni(playerId) {
|
|
1164
|
+
const guadagni = this.richiediDati().voceGuadagni;
|
|
1165
|
+
if (guadagni === void 0) return;
|
|
1166
|
+
let cambiato = Object.hasOwn(guadagni, playerId);
|
|
1167
|
+
delete guadagni[playerId];
|
|
1168
|
+
this.voceGuadagniCambiati.delete(playerId);
|
|
1169
|
+
for (const [altroId, riga] of Object.entries(guadagni)) {
|
|
1170
|
+
cambiato = Object.hasOwn(riga, playerId) || cambiato;
|
|
1171
|
+
delete riga[playerId];
|
|
1172
|
+
if (Object.keys(riga).length === 0) delete guadagni[altroId];
|
|
1173
|
+
}
|
|
1174
|
+
if (cambiato) this.voceDaPersistire = true;
|
|
1175
|
+
}
|
|
1176
|
+
async terminaPerStato(code) {
|
|
1177
|
+
const dati = this.richiediDati();
|
|
1178
|
+
dati.state = dati.statoSincronizzato;
|
|
1179
|
+
await this.terminaInterna({ error: code });
|
|
1180
|
+
}
|
|
1181
|
+
async terminaInterna(result) {
|
|
1182
|
+
const dati = this.richiediDati();
|
|
1183
|
+
if (dati.status === "ended") return;
|
|
1184
|
+
dati.status = "ended";
|
|
1185
|
+
dati.countdownAt = null;
|
|
1186
|
+
dati.result = result;
|
|
1187
|
+
dati.resultAt = this.adattatore.ora();
|
|
1188
|
+
try {
|
|
1189
|
+
await this.definizione.onEnd?.(this.room);
|
|
1190
|
+
} catch {
|
|
1191
|
+
if (record(result)?.error === void 0) dati.result = { error: "callback_error" };
|
|
1192
|
+
}
|
|
1193
|
+
const stato = analizzaJson(dati.state);
|
|
1194
|
+
if (!stato.ok || stato.bytes > LIMITE_STATO) {
|
|
1195
|
+
dati.state = dati.statoSincronizzato;
|
|
1196
|
+
dati.result = { error: stato.ok ? "state_too_large" : "state_invalid" };
|
|
1197
|
+
} else if (stato.testo !== JSON.stringify(dati.statoSincronizzato)) {
|
|
1198
|
+
dati.tick++;
|
|
1199
|
+
dati.state = stato.valore;
|
|
1200
|
+
this.inviaSnapshotTutti();
|
|
1201
|
+
}
|
|
1202
|
+
const fine = { result: dati.result, at: dati.resultAt };
|
|
1203
|
+
dati.fineInCoda = fine;
|
|
1204
|
+
this.inviaStatus(dati.resultAt);
|
|
1205
|
+
this.broadcast({ t: "flush" });
|
|
1206
|
+
for (const player of dati.giocatori) {
|
|
1207
|
+
if (player.connected && player.connessione !== null) {
|
|
1208
|
+
this.adattatore.chiudi(player.connessione, 4004, "room_ended");
|
|
1209
|
+
player.connected = false;
|
|
1210
|
+
player.connessione = null;
|
|
1211
|
+
player.graziaFinoA = null;
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
await this.persistiEProgramma();
|
|
1215
|
+
}
|
|
1216
|
+
registraCpu(durata) {
|
|
1217
|
+
const dati = this.richiediDati();
|
|
1218
|
+
dati.durateCpu.push(durata);
|
|
1219
|
+
if (dati.durateCpu.length > 50) dati.durateCpu.shift();
|
|
1220
|
+
dati.cpuOltreCento = durata > 100 ? dati.cpuOltreCento + 1 : 0;
|
|
1221
|
+
if (dati.cpuOltreCento >= 20) {
|
|
1222
|
+
this.fineRichiesta = { error: "cpu_budget" };
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
if (dati.durateCpu.length === 50) {
|
|
1226
|
+
const media = dati.durateCpu.reduce((somma, value) => somma + value, 0) / 50;
|
|
1227
|
+
if (media > 20 && dati.tickRate > 5) {
|
|
1228
|
+
dati.tickRate = Math.max(5, Math.floor(dati.tickRate / 2));
|
|
1229
|
+
dati.durateCpu = [];
|
|
1230
|
+
this.broadcast({
|
|
1231
|
+
t: "error",
|
|
1232
|
+
code: "tick_rate_reduced",
|
|
1233
|
+
message: `Tick rate reduced to ${dati.tickRate} because the game exceeded its CPU budget.`
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
async persisti() {
|
|
1239
|
+
if (this.dati !== null) {
|
|
1240
|
+
await this.adattatore.storage.put(CHIAVE_NUCLEO, this.dati);
|
|
1241
|
+
this.voceDaPersistire = false;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
async persistiEProgramma() {
|
|
1245
|
+
await this.persisti();
|
|
1246
|
+
await this.aggiornaProgrammazione();
|
|
1247
|
+
}
|
|
1248
|
+
serveTick() {
|
|
1249
|
+
const dati = this.dati;
|
|
1250
|
+
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;
|
|
1251
|
+
}
|
|
1252
|
+
async terminaSeInattiva() {
|
|
1253
|
+
if (this.dati?.status !== "playing" || this.adattatore.ora() < this.dati.ultimoInputAt + INATTIVITA_MS) return false;
|
|
1254
|
+
await this.terminaInterna({ error: "idle" });
|
|
1255
|
+
return true;
|
|
1256
|
+
}
|
|
1257
|
+
async aggiornaProgrammazione() {
|
|
1258
|
+
if (this.dati === null || this.dati.status === "ended") {
|
|
1259
|
+
this.adattatore.programmaTick(null);
|
|
1260
|
+
await this.adattatore.programmaSveglia(null);
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
this.adattatore.programmaTick(
|
|
1264
|
+
this.serveTick() ? 1e3 / this.dati.tickRate : null
|
|
1265
|
+
);
|
|
1266
|
+
const prossime = [];
|
|
1267
|
+
if (this.dati.status === "playing") prossime.push(this.dati.ultimoInputAt + INATTIVITA_MS);
|
|
1268
|
+
if (this.dati.countdownAt !== null) prossime.push(this.dati.countdownAt);
|
|
1269
|
+
for (const player of this.dati.giocatori) {
|
|
1270
|
+
if (!player.connected && player.graziaFinoA !== null) prossime.push(player.graziaFinoA);
|
|
1271
|
+
}
|
|
1272
|
+
for (const timer of this.dati.timer) prossime.push(timer.at);
|
|
1273
|
+
if (this.dati.giocatori.length === 0 && this.dati.vuotaDa !== null) {
|
|
1274
|
+
prossime.push(this.dati.vuotaDa + STANZA_VUOTA_MS);
|
|
1275
|
+
}
|
|
1276
|
+
await this.adattatore.programmaSveglia(prossime.length === 0 ? null : Math.min(...prossime));
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
// src/runtime/index.ts
|
|
1281
|
+
var CHIAVE_ADATTATORE = "adattatore";
|
|
1282
|
+
var ArchivioFacet = class {
|
|
1283
|
+
constructor(archivio) {
|
|
1284
|
+
this.archivio = archivio;
|
|
1285
|
+
}
|
|
1286
|
+
get(chiave) {
|
|
1287
|
+
return this.archivio.get(chiave);
|
|
1288
|
+
}
|
|
1289
|
+
put(chiave, valore) {
|
|
1290
|
+
return this.archivio.put(chiave, valore);
|
|
1291
|
+
}
|
|
1292
|
+
async delete(chiave) {
|
|
1293
|
+
await this.archivio.delete(chiave);
|
|
1294
|
+
}
|
|
1295
|
+
list(prefix) {
|
|
1296
|
+
return this.archivio.list(prefix === void 0 ? void 0 : { prefix });
|
|
1297
|
+
}
|
|
1298
|
+
};
|
|
1299
|
+
var AdattatoreFacet = class {
|
|
1300
|
+
constructor(archivio, tickRate) {
|
|
1301
|
+
this.connessioni = /* @__PURE__ */ new Set();
|
|
1302
|
+
this.cpuMessaggiOltreCento = 0;
|
|
1303
|
+
this.frames = [];
|
|
1304
|
+
this.chiusure = [];
|
|
1305
|
+
this.sveglia = null;
|
|
1306
|
+
this.tick = false;
|
|
1307
|
+
this.salvato = "";
|
|
1308
|
+
this.storage = new ArchivioFacet(archivio);
|
|
1309
|
+
this.tickRate = tickRate;
|
|
1310
|
+
}
|
|
1311
|
+
async ripristina() {
|
|
1312
|
+
const dati = await this.storage.get(CHIAVE_ADATTATORE);
|
|
1313
|
+
if (dati === void 0) return;
|
|
1314
|
+
for (const connessione of dati.connessioni) this.connessioni.add(connessione);
|
|
1315
|
+
this.tickRate = dati.tickRate;
|
|
1316
|
+
this.cpuMessaggiOltreCento = dati.cpuMessaggiOltreCento;
|
|
1317
|
+
this.salvato = JSON.stringify(dati);
|
|
1318
|
+
}
|
|
1319
|
+
async persisti() {
|
|
1320
|
+
const dati = {
|
|
1321
|
+
connessioni: [...this.connessioni],
|
|
1322
|
+
tickRate: this.tickRate,
|
|
1323
|
+
cpuMessaggiOltreCento: this.cpuMessaggiOltreCento
|
|
1324
|
+
};
|
|
1325
|
+
const testo = JSON.stringify(dati);
|
|
1326
|
+
if (testo === this.salvato) return;
|
|
1327
|
+
await this.storage.put(CHIAVE_ADATTATORE, dati);
|
|
1328
|
+
this.salvato = testo;
|
|
1329
|
+
}
|
|
1330
|
+
invia(connessione, messaggio) {
|
|
1331
|
+
this.frames.push({ connessione, testo: JSON.stringify(messaggio) });
|
|
1332
|
+
}
|
|
1333
|
+
chiudi(connessione, codice, motivo) {
|
|
1334
|
+
this.chiusure.push({ connessione, codice, motivo });
|
|
1335
|
+
this.connessioni.delete(connessione);
|
|
1336
|
+
}
|
|
1337
|
+
connessioniAttive() {
|
|
1338
|
+
return [...this.connessioni];
|
|
1339
|
+
}
|
|
1340
|
+
ora() {
|
|
1341
|
+
return Date.now();
|
|
1342
|
+
}
|
|
1343
|
+
misuraCpu() {
|
|
1344
|
+
return performance.now();
|
|
1345
|
+
}
|
|
1346
|
+
programmaTick(intervalloMs) {
|
|
1347
|
+
this.tick = intervalloMs !== null;
|
|
1348
|
+
if (intervalloMs !== null) this.tickRate = 1e3 / intervalloMs;
|
|
1349
|
+
}
|
|
1350
|
+
async programmaSveglia(ora) {
|
|
1351
|
+
this.sveglia = ora;
|
|
1352
|
+
}
|
|
1353
|
+
esito() {
|
|
1354
|
+
const risultato = {
|
|
1355
|
+
frames: this.frames,
|
|
1356
|
+
chiusure: this.chiusure,
|
|
1357
|
+
sveglia: this.sveglia,
|
|
1358
|
+
tick: this.tick,
|
|
1359
|
+
tickRate: this.tickRate
|
|
1360
|
+
};
|
|
1361
|
+
this.frames = [];
|
|
1362
|
+
this.chiusure = [];
|
|
1363
|
+
return risultato;
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
function creaFacetStanza(DurableObject, definizione, manifest) {
|
|
1367
|
+
return class Room extends DurableObject {
|
|
1368
|
+
#adattatore;
|
|
1369
|
+
#pronto;
|
|
1370
|
+
#coda = Promise.resolve();
|
|
1371
|
+
#roomId;
|
|
1372
|
+
constructor(stato, ambiente) {
|
|
1373
|
+
super(stato, ambiente);
|
|
1374
|
+
this.#roomId = typeof stato.id === "string" ? stato.id : stato.id.name ?? stato.id.toString();
|
|
1375
|
+
const adattatore = new AdattatoreFacet(stato.storage, definizione.tickRate);
|
|
1376
|
+
this.#adattatore = adattatore;
|
|
1377
|
+
const misurata = Object.create(definizione);
|
|
1378
|
+
if (definizione.onMessage !== void 0) {
|
|
1379
|
+
misurata.onMessage = async (room, player, messaggio) => {
|
|
1380
|
+
const inizio = adattatore.misuraCpu();
|
|
1381
|
+
try {
|
|
1382
|
+
await definizione.onMessage?.(room, player, messaggio);
|
|
1383
|
+
} finally {
|
|
1384
|
+
const durata = Math.max(0, adattatore.misuraCpu() - inizio);
|
|
1385
|
+
adattatore.cpuMessaggiOltreCento = durata > 100 ? adattatore.cpuMessaggiOltreCento + 1 : 0;
|
|
1386
|
+
if (adattatore.cpuMessaggiOltreCento >= 20) room.end({ error: "cpu_budget" });
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
this.#pronto = stato.blockConcurrencyWhile(async () => {
|
|
1391
|
+
await adattatore.ripristina();
|
|
1392
|
+
return NucleoStanza.apri(misurata, manifest, adattatore);
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
// Le RPC possono intercalarsi durante un await del creatore: ogni Esito deve restare del suo evento.
|
|
1396
|
+
#serializza(operazione) {
|
|
1397
|
+
const risultato = this.#coda.then(async () => operazione(await this.#pronto));
|
|
1398
|
+
this.#coda = risultato.then(() => void 0, () => void 0);
|
|
1399
|
+
return risultato;
|
|
1400
|
+
}
|
|
1401
|
+
#esegui(operazione) {
|
|
1402
|
+
return this.#serializza(async (nucleo) => {
|
|
1403
|
+
await operazione(nucleo);
|
|
1404
|
+
await this.#adattatore.persisti();
|
|
1405
|
+
return this.#adattatore.esito();
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
crea(input) {
|
|
1409
|
+
return this.#serializza(async (nucleo) => {
|
|
1410
|
+
const ok = await nucleo.crea(this.#roomId, input.mode, input.creator);
|
|
1411
|
+
await this.#adattatore.persisti();
|
|
1412
|
+
return {
|
|
1413
|
+
...this.#adattatore.esito(),
|
|
1414
|
+
ok,
|
|
1415
|
+
status: nucleo.info()?.status === "playing" ? "playing" : "lobby"
|
|
1416
|
+
};
|
|
1417
|
+
});
|
|
1418
|
+
}
|
|
1419
|
+
info() {
|
|
1420
|
+
return this.#serializza((nucleo) => nucleo.info());
|
|
1421
|
+
}
|
|
1422
|
+
puoEntrare(identita) {
|
|
1423
|
+
return this.#serializza((nucleo) => nucleo.puoEntrare(identita));
|
|
1424
|
+
}
|
|
1425
|
+
entra(identita, connessione) {
|
|
1426
|
+
return this.#esegui(async (nucleo) => {
|
|
1427
|
+
this.#adattatore.connessioni.add(connessione);
|
|
1428
|
+
await nucleo.entra(identita, connessione);
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
ricevi(connessione, testo) {
|
|
1432
|
+
return this.#esegui(async (nucleo) => {
|
|
1433
|
+
if (new TextEncoder().encode(testo).byteLength > 16 * 1024) {
|
|
1434
|
+
this.#adattatore.chiudi(connessione, 4008, "rate_limited");
|
|
1435
|
+
await nucleo.disconnetti(connessione);
|
|
1436
|
+
} else await nucleo.ricevi(connessione, testo);
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
disconnetti(connessione) {
|
|
1440
|
+
return this.#esegui(async (nucleo) => {
|
|
1441
|
+
this.#adattatore.connessioni.delete(connessione);
|
|
1442
|
+
await nucleo.disconnetti(connessione);
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
tick() {
|
|
1446
|
+
return this.#esegui((nucleo) => nucleo.eseguiTick());
|
|
1447
|
+
}
|
|
1448
|
+
sveglia() {
|
|
1449
|
+
return this.#esegui((nucleo) => nucleo.sveglia());
|
|
1450
|
+
}
|
|
1451
|
+
flush() {
|
|
1452
|
+
return this.#serializza((nucleo) => nucleo.flush());
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
export {
|
|
1457
|
+
creaFacetStanza
|
|
1458
|
+
};
|