@zaisma/game-server 1.33.0 → 1.35.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/bench/brand/README.md +2 -1
- package/bench/brand/share-card-letters.png +0 -0
- package/bench/brand/share-card-person-light.png +0 -0
- package/bench/glass.js +4662 -4530
- package/bin/local-play-runner.js +2 -0
- package/bin/local-play.d.ts +9 -0
- package/bin/local-play.js +47 -12
- package/bin/node-parts.js +36 -2
- package/bin/node.d.ts +2 -0
- package/bin/node.js +16 -10
- package/package.json +1 -1
- package/src/index.d.ts +1 -1
- package/src/index.js +1 -1
- package/src/requests.d.ts +2 -0
- package/src/room-calls.d.ts +5 -0
- package/src/room-calls.js +12 -1
- package/src/room.d.ts +36 -1
- package/src/room.js +25 -0
package/bin/local-play-runner.js
CHANGED
|
@@ -27,6 +27,8 @@ try {
|
|
|
27
27
|
issuerUrl: config.issuerUrl,
|
|
28
28
|
database: localDatabase(config.databaseFile),
|
|
29
29
|
roomStateFile: config.roomStateFile,
|
|
30
|
+
// room.readDataFile reads the game server's data files from its folder, as on Zaisma's rooms.
|
|
31
|
+
dataFolder: config.dataFolder,
|
|
30
32
|
// onPurchase and onRefund hear purchases through the stand-in developer API on the bench's rooms.
|
|
31
33
|
zaismaKey: config.zaismaKey,
|
|
32
34
|
developerApiUrl: config.developerApiUrl,
|
package/bin/local-play.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface LocalPlayOptions {
|
|
|
8
8
|
isOnNetwork?: boolean;
|
|
9
9
|
/** Your game's Zaisma slug. Default: the folder's name. */
|
|
10
10
|
gameSlug?: string | null;
|
|
11
|
+
/** Where the bench keeps its keys, players, saves and the game's database. Default: ~/.zaisma/play-locally/<folder's name>-<hash of the game folder's real path>, outside the game's folder, so a build that empties it leaves them be. */
|
|
12
|
+
benchFolder?: string | null;
|
|
11
13
|
/** An API key; with gameSlug, each start brings in the game's items from Zaisma. Default: the ZAISMA_KEY environment variable. */
|
|
12
14
|
zaismaKey?: string;
|
|
13
15
|
/** Zaisma's developer API, where that copy is read from. Default: https://zaisma.com/api/dev. */
|
|
@@ -23,6 +25,12 @@ export interface LocalPlay {
|
|
|
23
25
|
roomsUrl: string;
|
|
24
26
|
/** The bench's address for a phone on the same Wi-Fi; null without isOnNetwork. */
|
|
25
27
|
networkUrl: string | null;
|
|
28
|
+
/** The slug the bench plays the game as: gameSlug, or the folder's name. */
|
|
29
|
+
gameSlug: string;
|
|
30
|
+
/** Whether gameSlug came from the folder's name, since none was given. */
|
|
31
|
+
isGameSlugFromFolder: boolean;
|
|
32
|
+
/** The folder holding what the bench keeps. */
|
|
33
|
+
benchFolder: string;
|
|
26
34
|
/** How many times the game server has been started: more than one after a change to its files. */
|
|
27
35
|
readonly runnerStartCount: number;
|
|
28
36
|
/** Saves every room, then stops everything. */
|
|
@@ -35,6 +43,7 @@ export const LOCAL_FOLDER: string;
|
|
|
35
43
|
export const SERVED_ZAISMA_PATHS: string[];
|
|
36
44
|
export const ONLY_ON_ZAISMA_PATHS: string[];
|
|
37
45
|
export function startLocalPlay(options: LocalPlayOptions): Promise<LocalPlay>;
|
|
46
|
+
export function benchFolderOf(gameFolder: string): string;
|
|
38
47
|
export function serverEntryOf(gameFolder: string): string | null;
|
|
39
48
|
export function withScripts(page: string, scriptUrls: string[]): string;
|
|
40
49
|
export function localGameHeaders(contentType: string, benchOrigin: string, connectOrigins: string[]): Record<string, string>;
|
package/bin/local-play.js
CHANGED
|
@@ -9,15 +9,16 @@
|
|
|
9
9
|
// page; the stand-in rooms (4802), which answers the calls the SDK makes to Zaisma's rooms and signs real player passes
|
|
10
10
|
// and receipts with keys made on the first run; and your game server (4803), the Node runner, as its own process.
|
|
11
11
|
// Different ports are different origins, so the game is on another origin from its page, as on Zaisma.
|
|
12
|
-
// Everything it keeps is in
|
|
12
|
+
// Everything it keeps is in ~/.zaisma/play-locally/<folder's name>-<hash of the folder>/, outside the game's folder, so a build that empties
|
|
13
|
+
// its output folder (Vite's emptyOutDir) never takes the keys, players, saves or database with it. Nothing here changes the game server: it checks the
|
|
13
14
|
// stand-in passes the way it checks Zaisma's, against the keys the stand-in rooms publishes.
|
|
14
15
|
import { createServer, request as httpRequest } from "node:http";
|
|
15
16
|
import { createServer as createSecureServer } from "node:https";
|
|
16
17
|
import { createServer as createSocketServer } from "node:net";
|
|
17
|
-
import { hostname as computerName } from "node:os";
|
|
18
|
+
import { homedir, hostname as computerName } from "node:os";
|
|
18
19
|
import { spawn } from "node:child_process";
|
|
19
20
|
import { createHash } from "node:crypto";
|
|
20
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
|
|
21
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
|
|
21
22
|
import { pathToFileURL } from "node:url";
|
|
22
23
|
import { networkInterfaces } from "node:os";
|
|
23
24
|
import { basename, extname, isAbsolute, join, relative as relativePath, resolve, sep } from "node:path";
|
|
@@ -32,12 +33,12 @@ import { isCertificateGood, makeCertificate } from "./local-play-certificate.js"
|
|
|
32
33
|
export const DEFAULT_PORT_NUMBER = 4800;
|
|
33
34
|
/** The version the SDK's setup names. */
|
|
34
35
|
export const LOCAL_VERSION_ID = "version_local";
|
|
35
|
-
/** The folder in the game's folder that
|
|
36
|
+
/** The folder in the game's folder that held what the bench keeps, before it moved out (benchFolderOf): still never served, watched or uploaded, and moved out on the next start. */
|
|
36
37
|
export const LOCAL_FOLDER = ".zaisma-local";
|
|
37
38
|
/** Every _zaisma/ file the games Worker serves, split by whether it works here or only loads and does nothing (test/node/local-play-parity.test.ts holds this to apps/games/src/index.ts). */
|
|
38
39
|
export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/saves.js", "_zaisma/restore"];
|
|
39
40
|
export const ONLY_ON_ZAISMA_PATHS = ["_zaisma/performance.js", "_zaisma/warm", "_zaisma/warm.json", "_zaisma/warm-redirects.json", "_zaisma/warm.js"];
|
|
40
|
-
const OPTION_NAMES = ["gameFolder", "port", "isOnNetwork", "gameSlug", "zaismaKey", "developerApiUrl", "log"];
|
|
41
|
+
const OPTION_NAMES = ["gameFolder", "port", "isOnNetwork", "gameSlug", "benchFolder", "zaismaKey", "developerApiUrl", "log"];
|
|
41
42
|
const SAVE_LIMIT_BYTES = 5 * 1024 * 1024;
|
|
42
43
|
const PASS_DURATION_SEC = 24 * 3600;
|
|
43
44
|
const SCRIPTS_VERSION_NUMBER = 7;
|
|
@@ -193,7 +194,8 @@ function sourceOf(gameFolder) {
|
|
|
193
194
|
const folder = join(gameFolder, "zaisma-server");
|
|
194
195
|
if (existsSync(folder)) walk(folder);
|
|
195
196
|
if (existsSync(join(gameFolder, "zaisma-server.js"))) found.push(join(gameFolder, "zaisma-server.js"));
|
|
196
|
-
|
|
197
|
+
// Code by its text; a data file by its size and time, so a big one isn't read again on every change (any change restarts the runner).
|
|
198
|
+
return found.map((path) => (/\.(js|json|wasm)$/.test(path) ? readFileSync(path, "utf8") : `${path} ${statSync(path).size} ${statSync(path).mtimeMs}`)).join("\n");
|
|
197
199
|
}
|
|
198
200
|
|
|
199
201
|
/** The first non-internal IPv4 addresses of this computer, for a phone on the same Wi-Fi. */
|
|
@@ -207,13 +209,32 @@ function checkedOptions(options) {
|
|
|
207
209
|
const fail = (code, field, message, fix) => new GameServerError(code, field, message, fix);
|
|
208
210
|
if (options === null || typeof options !== "object" || Array.isArray(options)) throw fail("bad_option", "options", "startLocalPlay takes one object of options.", `Call startLocalPlay({ gameFolder }), with any of: ${OPTION_NAMES.join(", ")}.`);
|
|
209
211
|
for (const field of Object.keys(options)) if (!OPTION_NAMES.includes(field)) throw fail("unknown_option", field, `${field} isn't a startLocalPlay option.`, `startLocalPlay takes: ${OPTION_NAMES.join(", ")}.`);
|
|
210
|
-
const { gameFolder, port = DEFAULT_PORT_NUMBER, isOnNetwork = false, gameSlug = null, zaismaKey = process.env.ZAISMA_KEY ?? "", developerApiUrl = (process.env.ZAISMA_API || "https://zaisma.com").replace(/\/+$/, "") + "/api/dev", log = (line) => console.log(line) } = options;
|
|
212
|
+
const { gameFolder, port = DEFAULT_PORT_NUMBER, isOnNetwork = false, gameSlug = null, benchFolder = null, zaismaKey = process.env.ZAISMA_KEY ?? "", developerApiUrl = (process.env.ZAISMA_API || "https://zaisma.com").replace(/\/+$/, "") + "/api/dev", log = (line) => console.log(line) } = options;
|
|
211
213
|
if (typeof gameFolder !== "string" || !gameFolder) throw fail("bad_option", "gameFolder", "gameFolder is missing.", "Give the folder of your game, the one with index.html at the top.");
|
|
212
214
|
if (!Number.isInteger(port) || port < 1 || port > 65532) throw fail("bad_option", "port", "port isn't a whole number from 1 to 65532.", "Give the first of four ports, like 4800: the bench, the game's site, the stand-in rooms and your game server take it and the next three.");
|
|
213
215
|
if (typeof isOnNetwork !== "boolean") throw fail("bad_option", "isOnNetwork", "isOnNetwork isn't true or false.", "Give true to let a phone on the same Wi-Fi in, or leave it out.");
|
|
214
216
|
if (gameSlug !== null && !(typeof gameSlug === "string" && /^[a-z0-9-]{1,40}$/.test(gameSlug))) throw fail("bad_option", "gameSlug", "gameSlug isn't a game's slug.", "A slug is 1 to 40 lowercase letters, digits or hyphens, like sky-hopper.");
|
|
217
|
+
if (benchFolder !== null && !(typeof benchFolder === "string" && benchFolder)) throw fail("bad_option", "benchFolder", "benchFolder isn't a folder's path.", "Give the folder for what the bench keeps, outside the game's folder, or leave it out for ~/.zaisma/play-locally/.");
|
|
215
218
|
if (typeof log !== "function") throw fail("bad_option", "log", "log isn't a function.", "Give a function that takes one line of text, or leave it out to print to the terminal.");
|
|
216
|
-
return { gameFolder: resolve(gameFolder), port, isOnNetwork, gameSlug, zaismaKey, developerApiUrl, log };
|
|
219
|
+
return { gameFolder: resolve(gameFolder), port, isOnNetwork, gameSlug, benchFolder: benchFolder === null ? null : resolve(benchFolder), zaismaKey, developerApiUrl, log };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Where the bench keeps its keys, players, saves and the game's database for a game folder: outside it, in
|
|
224
|
+
* ~/.zaisma/play-locally/<folder's name>-<hash of the folder's real path>/, so a build that empties the folder leaves
|
|
225
|
+
* them be, two dist/ folders keep theirs apart, and the folder alone decides it: the same with --game or without,
|
|
226
|
+
* and through a symlink or another case of its path.
|
|
227
|
+
*/
|
|
228
|
+
export function benchFolderOf(gameFolder) {
|
|
229
|
+
let realPath = resolve(gameFolder);
|
|
230
|
+
try {
|
|
231
|
+
realPath = realpathSync.native(realPath);
|
|
232
|
+
} catch {
|
|
233
|
+
// Not there yet: its path as given.
|
|
234
|
+
}
|
|
235
|
+
const folderHash = createHash("sha256").update(realPath).digest("hex").slice(0, 12);
|
|
236
|
+
const label = basename(realPath).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "game";
|
|
237
|
+
return join(homedir(), ".zaisma", "play-locally", `${label}-${folderHash}`);
|
|
217
238
|
}
|
|
218
239
|
|
|
219
240
|
/**
|
|
@@ -225,7 +246,7 @@ function checkedOptions(options) {
|
|
|
225
246
|
* close() }: close() saves every room first and finishes once everything has stopped.
|
|
226
247
|
*/
|
|
227
248
|
export async function startLocalPlay(givenOptions) {
|
|
228
|
-
const { gameFolder, port, isOnNetwork, gameSlug: givenSlug, zaismaKey, developerApiUrl, log: printLine } = checkedOptions(givenOptions);
|
|
249
|
+
const { gameFolder, port, isOnNetwork, gameSlug: givenSlug, benchFolder: givenBenchFolder, zaismaKey, developerApiUrl, log: printLine } = checkedOptions(givenOptions);
|
|
229
250
|
// Everything the bench says goes to the terminal, and the last of it to the dev page's Log.
|
|
230
251
|
const logLines = [];
|
|
231
252
|
const log = (line) => {
|
|
@@ -244,7 +265,18 @@ export async function startLocalPlay(givenOptions) {
|
|
|
244
265
|
}
|
|
245
266
|
const ports = { bench: port, game: port + 1, rooms: port + 2, runner: port + 3 };
|
|
246
267
|
const host = isOnNetwork ? undefined : "127.0.0.1";
|
|
247
|
-
const localFolder =
|
|
268
|
+
const localFolder = givenBenchFolder ?? benchFolderOf(gameFolder);
|
|
269
|
+
// What an older bench kept in the game's folder moves out once, keys, players and saves with it: copied beside its
|
|
270
|
+
// new place and renamed into it, so a copy cut short is never taken for the whole.
|
|
271
|
+
const oldFolder = join(gameFolder, LOCAL_FOLDER);
|
|
272
|
+
if (existsSync(oldFolder) && !existsSync(localFolder)) {
|
|
273
|
+
const copyFolder = `${localFolder}.moving`;
|
|
274
|
+
rmSync(copyFolder, { recursive: true, force: true });
|
|
275
|
+
cpSync(oldFolder, copyFolder, { recursive: true });
|
|
276
|
+
renameSync(copyFolder, localFolder);
|
|
277
|
+
rmSync(oldFolder, { recursive: true, force: true });
|
|
278
|
+
log(`Moved what the bench keeps out of the game's folder, to ${localFolder}.`);
|
|
279
|
+
}
|
|
248
280
|
mkdirSync(join(localFolder, "saves"), { recursive: true });
|
|
249
281
|
|
|
250
282
|
// --- The keys: one pair for passes, one for receipts, made on the first run ---
|
|
@@ -821,7 +853,7 @@ export async function startLocalPlay(givenOptions) {
|
|
|
821
853
|
return fail(404, "not_local", `${request.method} ${path} is a part of Zaisma's buy sheet the bench has no stand-in for.`);
|
|
822
854
|
}
|
|
823
855
|
|
|
824
|
-
// Cloud saves (apps/site/src/saves.ts), stood in for: one save per account, kept in
|
|
856
|
+
// Cloud saves (apps/site/src/saves.ts), stood in for: one save per account, kept in the bench's folder's saves/, with its version number.
|
|
825
857
|
const saveFileOf = (accountId) => join(localFolder, "saves", `${accountId}.json`);
|
|
826
858
|
const savedRowOf = (accountId) => {
|
|
827
859
|
try {
|
|
@@ -1484,7 +1516,7 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1484
1516
|
saveState();
|
|
1485
1517
|
tell("reload");
|
|
1486
1518
|
}
|
|
1487
|
-
const config = { entry: entry(), gameSlug, port: ports.runner, origin: localhostOrigin(ports.game), issuerUrl: roomsAddress(), databaseFile: join(localFolder, "database.sqlite"), roomStateFile: join(localFolder, "room-states.sqlite"), developerApiUrl: `${roomsAddress()}/api/dev`, zaismaKey: LOCAL_RUNNER_KEY };
|
|
1519
|
+
const config = { entry: entry(), gameSlug, port: ports.runner, origin: localhostOrigin(ports.game), issuerUrl: roomsAddress(), databaseFile: join(localFolder, "database.sqlite"), roomStateFile: join(localFolder, "room-states.sqlite"), dataFolder: join(gameFolder, "zaisma-server"), developerApiUrl: `${roomsAddress()}/api/dev`, zaismaKey: LOCAL_RUNNER_KEY };
|
|
1488
1520
|
const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", runnerFile, JSON.stringify(config)], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env } });
|
|
1489
1521
|
let isReady = false;
|
|
1490
1522
|
const timeout = setTimeout(() => {
|
|
@@ -1624,6 +1656,9 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1624
1656
|
gameSiteUrl: localhostOrigin(ports.game),
|
|
1625
1657
|
roomsUrl: issuerUrl,
|
|
1626
1658
|
networkUrl,
|
|
1659
|
+
gameSlug,
|
|
1660
|
+
isGameSlugFromFolder: givenSlug === null,
|
|
1661
|
+
benchFolder: localFolder,
|
|
1627
1662
|
get runnerStartCount() {
|
|
1628
1663
|
return runnerStartCount;
|
|
1629
1664
|
},
|
package/bin/node-parts.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// profiles, its local SQLite files, and the checks on its options. Nothing here is part of the
|
|
3
3
|
// public package: tests reach it by path.
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { existsSync } from "node:fs";
|
|
5
|
+
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
+
import { resolve, sep } from "node:path";
|
|
6
7
|
import { DATABASE_LIMITS, GameServerError, answerDatabase, checkBatch, checkPlayerId, checkStatement, checkedRow, eraseRefused, eraseStatements, readDatabaseAnswer, tablesFromColumns, tooManyRows, TABLE_COLUMNS_SQL } from "../src/internal.js";
|
|
7
8
|
|
|
8
9
|
/** How long the pass keys and the profiles of accounts are kept before they're fetched again. */
|
|
@@ -366,7 +367,7 @@ export function secretsFromEnvironment() {
|
|
|
366
367
|
const WORLD_COPIES_DURATION_MS = 30 * 86_400_000;
|
|
367
368
|
const WORLD_COPY_MINUTES_DURATION_MS = 86_400_000;
|
|
368
369
|
|
|
369
|
-
const OPTION_NAMES = ["gameServer", "gameSlug", "port", "origins", "issuerUrl", "loadPassKeys", "loadReceiptKeys", "loadProfile", "database", "secrets", "webhookSigningSecret", "roomStateFile", "zaismaKey", "developerApiUrl", "webtransportPort", "certificatePath", "certificateKeyPath", "identifyPlayer", "outsideGuestsEnabled"];
|
|
370
|
+
const OPTION_NAMES = ["gameServer", "gameSlug", "port", "origins", "issuerUrl", "loadPassKeys", "loadReceiptKeys", "loadProfile", "database", "secrets", "webhookSigningSecret", "roomStateFile", "zaismaKey", "developerApiUrl", "webtransportPort", "certificatePath", "certificateKeyPath", "identifyPlayer", "outsideGuestsEnabled", "dataFolder"];
|
|
370
371
|
|
|
371
372
|
/**
|
|
372
373
|
* Check what startServer was given: unknown options and options of the wrong kind are a GameServerError,
|
|
@@ -404,6 +405,8 @@ export function checkedStartServerOptions(given, issuerUrlDefault) {
|
|
|
404
405
|
if (options.developerApiUrl !== undefined && (!isText(options.developerApiUrl) || !URL.canParse(options.developerApiUrl))) throw bad("developerApiUrl", "a URL", 'Give the address of Zaisma\'s developer API, like "https://zaisma.com/api/dev".');
|
|
405
406
|
// Players from outside Zaisma (games played off their Zaisma page): who a playerToken is, and whether players with none come in as guests.
|
|
406
407
|
if (options.identifyPlayer !== undefined && !isFunction(options.identifyPlayer)) throw bad("identifyPlayer", "a function", "Give async (playerToken, { origin }) => ({ id, name }) or null, like signInWithZaismaPlayers({ signInAppIds }) makes.");
|
|
408
|
+
options.dataFolder ??= "zaisma-server";
|
|
409
|
+
if (!isText(options.dataFolder)) throw bad("dataFolder", "a folder path", 'Give the folder room.readDataFile reads from, like "zaisma-server": the game server\'s own folder.');
|
|
407
410
|
options.outsideGuestsEnabled ??= false;
|
|
408
411
|
if (typeof options.outsideGuestsEnabled !== "boolean") throw bad("outsideGuestsEnabled", "true or false", "Give true to let players with no playerToken in as guests, or false (the default).");
|
|
409
412
|
// The fast lane (WebTransport): its UDP port and the certificate it holds itself, all three or none.
|
|
@@ -416,3 +419,34 @@ export function checkedStartServerOptions(given, issuerUrlDefault) {
|
|
|
416
419
|
}
|
|
417
420
|
return options;
|
|
418
421
|
}
|
|
422
|
+
|
|
423
|
+
/** Files in the game server's folder that are code, imported rather than read: the same kinds as on Zaisma's rooms. */
|
|
424
|
+
const CODE_FILE = /\.(js|json|wasm)$/;
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* room.readDataFile and server.readDataFile on your own server: a data file from the folder by its path there (each
|
|
428
|
+
* read once, then the same ArrayBuffer), or null for no such file, a code file, or a path outside the folder.
|
|
429
|
+
*/
|
|
430
|
+
export function dataFilesFrom(dataFolder) {
|
|
431
|
+
const folder = resolve(dataFolder);
|
|
432
|
+
const read = new Map();
|
|
433
|
+
return (dataFilePath) => {
|
|
434
|
+
if (read.has(dataFilePath)) return read.get(dataFilePath);
|
|
435
|
+
const path = resolve(folder, dataFilePath);
|
|
436
|
+
let found = null;
|
|
437
|
+
if (path.startsWith(folder + sep) && !CODE_FILE.test(path)) {
|
|
438
|
+
try {
|
|
439
|
+
// A link that leads out of the folder isn't one of its files.
|
|
440
|
+
if (realpathSync(path).startsWith(realpathSync(folder) + sep) && statSync(path).isFile()) {
|
|
441
|
+
const bytes = readFileSync(path);
|
|
442
|
+
found = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
443
|
+
}
|
|
444
|
+
} catch {
|
|
445
|
+
found = null;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// Found files are kept; a missing one is looked for again, so a file added while the server runs is read.
|
|
449
|
+
if (found !== null) read.set(dataFilePath, found);
|
|
450
|
+
return found;
|
|
451
|
+
};
|
|
452
|
+
}
|
package/bin/node.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface StartServerOptions {
|
|
|
27
27
|
webhookSigningSecret?: string;
|
|
28
28
|
/** Where rooms save their states, so a restart brings matches back. Default zaisma-room-states.sqlite; null keeps none. */
|
|
29
29
|
roomStateFile?: string | null;
|
|
30
|
+
/** Where room.readDataFile and server.readDataFile read data files from. Default: zaisma-server, the game server's own folder. */
|
|
31
|
+
dataFolder?: string;
|
|
30
32
|
/** An API key with purchase_access write for this game, which onPurchase and onRefund need. Default: the ZAISMA_KEY environment variable. */
|
|
31
33
|
zaismaKey?: string;
|
|
32
34
|
/** Zaisma's developer API, which marks purchases handled. Default: https://zaisma.com/api/dev. */
|
package/bin/node.js
CHANGED
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
import { WebSocketServer } from "ws";
|
|
25
25
|
import { createServer } from "node:http";
|
|
26
26
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
27
|
-
import { resolve } from "node:path";
|
|
27
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
28
28
|
import { readFileSync, realpathSync } from "node:fs";
|
|
29
29
|
import { roomMessageProblem, BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, ERROR_TEXT, NO_ANSWER_CLOSE_CODE, PASS_ISSUER_URL, OUTSIDE_ZAISMA_CHAT_SETTINGS, PassError, ReceiptError, REMOVED_CLOSE_CODE, REQUEST_ERROR_HTTP_STATUS, REQUEST_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_TUNING, WEBHOOK_LIMITS, GameServerError, RoomCore, chatSettingsOf, checkChat, readChatMessage, restoreInfoOf, passesAreFriends, passesHaveBlockBetween, answerRequest, startSchedules, checkRoomData, checkedOutsidePlayer, clientIdle, defineGameServer, errorMessage, guestPlayer, newServer, isPlayerToken, isRoomCode, readRequestBody, relay, requestError, runWebhook, tidyRoomInfo, verifyPass, verifyReceipt, verifyWebhook } from "../src/internal.js";
|
|
30
30
|
import { OutsideCallError } from "../src/outside-calls.js";
|
|
31
31
|
import { startFastLane } from "./fast-lane.js";
|
|
32
|
-
import { checkedStartServerOptions, localDatabase, localRoomStates, passKeysFrom, profilesFrom, receiptKeysFrom, secretsFromEnvironment } from "./node-parts.js";
|
|
32
|
+
import { checkedStartServerOptions, dataFilesFrom, localDatabase, localRoomStates, passKeysFrom, profilesFrom, receiptKeysFrom, secretsFromEnvironment } from "./node-parts.js";
|
|
33
33
|
|
|
34
34
|
// Code that names OutsideCallError, as Zaisma's sandbox lets it, moves unchanged: nothing here refuses a call, so instanceof is simply false.
|
|
35
35
|
globalThis.OutsideCallError ??= OutsideCallError;
|
|
@@ -79,12 +79,14 @@ const CATCH_UP_MS = 50;
|
|
|
79
79
|
* identifyPlayer (async (playerToken, { origin }) => ({ id, name }) or null; none by default) says who a player from
|
|
80
80
|
* outside Zaisma is by the playerToken their game sent (signInWithZaismaPlayers makes one for Sign in with Zaisma),
|
|
81
81
|
* and outsideGuestsEnabled (false by default) lets players with no token (playerToken: null) in as guests (guestPlayer).
|
|
82
|
-
* Both join with kind "outside_zaisma".
|
|
82
|
+
* Both join with kind "outside_zaisma". dataFolder (by default zaisma-server, as uploads lay it out) is where
|
|
83
|
+
* room.readDataFile and server.readDataFile read data files from.
|
|
83
84
|
* Answers { close(), httpServer, fastLaneReady }: close() saves every room first and finishes once the server
|
|
84
85
|
* has stopped; fastLaneReady settles once the fast lane listens (at once without one), or rejects saying why it can't.
|
|
85
86
|
*/
|
|
86
87
|
export function startServer(options) {
|
|
87
|
-
const { gameServer, gameSlug, port: portNumber, origins, issuerUrl, loadPassKeys = passKeysFrom(`${issuerUrl}/v1/pass-keys/${gameSlug}`), loadReceiptKeys = receiptKeysFrom(`${issuerUrl}/.well-known/receipt-jwks.json`), loadProfile = profilesFrom(issuerUrl), database = localDatabase("zaisma-database.sqlite"), secrets = secretsFromEnvironment(), webhookSigningSecret = process.env.ZAISMA_WEBHOOK_SIGNING_SECRET, roomStateFile = "zaisma-room-states.sqlite", zaismaKey = process.env.ZAISMA_KEY, developerApiUrl = "https://zaisma.com/api/dev", webtransportPort, certificatePath, certificateKeyPath, identifyPlayer, outsideGuestsEnabled } = checkedStartServerOptions(options, PASS_ISSUER_URL);
|
|
88
|
+
const { gameServer, gameSlug, port: portNumber, origins, issuerUrl, loadPassKeys = passKeysFrom(`${issuerUrl}/v1/pass-keys/${gameSlug}`), loadReceiptKeys = receiptKeysFrom(`${issuerUrl}/.well-known/receipt-jwks.json`), loadProfile = profilesFrom(issuerUrl), database = localDatabase("zaisma-database.sqlite"), secrets = secretsFromEnvironment(), webhookSigningSecret = process.env.ZAISMA_WEBHOOK_SIGNING_SECRET, roomStateFile = "zaisma-room-states.sqlite", zaismaKey = process.env.ZAISMA_KEY, developerApiUrl = "https://zaisma.com/api/dev", webtransportPort, certificatePath, certificateKeyPath, identifyPlayer, outsideGuestsEnabled, dataFolder } = checkedStartServerOptions(options, PASS_ISSUER_URL);
|
|
89
|
+
const findDataFile = dataFilesFrom(dataFolder);
|
|
88
90
|
const definition = defineGameServer(gameServer);
|
|
89
91
|
// Exactly once needs Zaisma's record of what's handled: without a key, purchases would come twice, so it doesn't start.
|
|
90
92
|
if ((definition.onPurchase || definition.onRefund) && !zaismaKey) {
|
|
@@ -105,7 +107,7 @@ export function startServer(options) {
|
|
|
105
107
|
const stateSaveIntervalMs = (definition.stateSaveIntervalSec ?? ROOM_LIMITS.defaultStateSaveIntervalSec) * 1000;
|
|
106
108
|
// Schedules run while this server is up; one that's down when a run is due misses that run.
|
|
107
109
|
// What onRequest, onSchedule and onWebhook get: the game's database, secrets, receipt checks and this server's rooms.
|
|
108
|
-
const server = newServer({ database, secrets, verifyReceipt: receiptClaims }, roomReachFrom(null));
|
|
110
|
+
const server = newServer({ database, secrets, verifyReceipt: receiptClaims, findDataFile }, roomReachFrom(null));
|
|
109
111
|
const schedules = startSchedules(definition, server, (run, failure) => console.error(`Game server error in onSchedule ("${run.name}", due ${run.scheduledAt}):`, failure));
|
|
110
112
|
const rooms = new Map(); // code -> { core, sockets: Map<playerId, ws>, timer }
|
|
111
113
|
// When the game last sent to every room, within the last minute (ROOM_MESSAGE_LIMITS.maximumEveryRoomSendsPerMin).
|
|
@@ -312,6 +314,7 @@ export function startServer(options) {
|
|
|
312
314
|
roomCode: code,
|
|
313
315
|
database,
|
|
314
316
|
secrets,
|
|
317
|
+
findDataFile,
|
|
315
318
|
verifyReceipt: receiptClaims,
|
|
316
319
|
purchaseHandling,
|
|
317
320
|
roomReach: roomReachFrom(code),
|
|
@@ -903,8 +906,8 @@ function binaryBytes(received) {
|
|
|
903
906
|
return new Uint8Array(received.buffer.slice(received.byteOffset, received.byteOffset + received.byteLength));
|
|
904
907
|
}
|
|
905
908
|
|
|
906
|
-
const USAGE = "Usage: zaisma-game-server <server.ts | relay> --game <slug> [--port 8080] [--origin <url>,<url>] [--issuer-url https://rooms.zaisma.com] [--database-file zaisma-database.sqlite] [--room-state-file zaisma-room-states.sqlite] [--webtransport-port 443 --certificate-path fullchain.pem --certificate-key-path privkey.pem]\n or: zaisma-game-server play-locally [folder] [--port 4800] [--game <slug>] [--on-network] [--no-open] [--json]";
|
|
907
|
-
const FLAGS = ["game", "port", "origin", "issuer-url", "database-file", "room-state-file", "webtransport-port", "certificate-path", "certificate-key-path"];
|
|
909
|
+
const USAGE = "Usage: zaisma-game-server <server.ts | relay> --game <slug> [--port 8080] [--origin <url>,<url>] [--issuer-url https://rooms.zaisma.com] [--database-file zaisma-database.sqlite] [--room-state-file zaisma-room-states.sqlite] [--data-folder <folder>] [--webtransport-port 443 --certificate-path fullchain.pem --certificate-key-path privkey.pem]\n or: zaisma-game-server play-locally [folder] [--port 4800] [--game <slug>] [--on-network] [--no-open] [--json]";
|
|
910
|
+
const FLAGS = ["game", "port", "origin", "issuer-url", "database-file", "room-state-file", "data-folder", "webtransport-port", "certificate-path", "certificate-key-path"];
|
|
908
911
|
/** The fast lane's flags: all three or none. */
|
|
909
912
|
const FAST_LANE_FLAGS = ["webtransport-port", "certificate-path", "certificate-key-path"];
|
|
910
913
|
|
|
@@ -967,10 +970,10 @@ async function playLocally(argumentList) {
|
|
|
967
970
|
process.exit(1);
|
|
968
971
|
}
|
|
969
972
|
for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => running.close().then(() => process.exit(0)));
|
|
970
|
-
if (given.isJson) console.log(JSON.stringify({ bench_url: running.benchUrl, game_site_url: running.gameSiteUrl, rooms_url: running.roomsUrl, network_url: running.networkUrl }));
|
|
971
|
-
say(`Playing ${
|
|
973
|
+
if (given.isJson) console.log(JSON.stringify({ bench_url: running.benchUrl, game_site_url: running.gameSiteUrl, rooms_url: running.roomsUrl, network_url: running.networkUrl, game_slug: running.gameSlug, is_game_slug_from_folder: running.isGameSlugFromFolder, bench_folder: running.benchFolder }));
|
|
974
|
+
say(`Playing ${running.gameSlug} on this computer${running.isGameSlugFromFolder ? ` (the slug from the folder's name: give --game <slug> to play it as your game's own slug)` : ""}. The test bench is at ${running.benchUrl}`);
|
|
972
975
|
say("Each player plays on Zaisma's own game page. Add a player in the dev bar to play with yourself in another tab. A change to a game file reloads the game, and a change to the game server starts it again with its rooms kept.");
|
|
973
|
-
say(
|
|
976
|
+
say(`Nothing here talks to Zaisma. What the bench keeps (its keys, players, saves and the game's database) is in ${running.benchFolder}, outside the game's folder. Press Ctrl-C to stop.`);
|
|
974
977
|
if (running.networkUrl) {
|
|
975
978
|
say(`On a phone on the same Wi-Fi: ${running.networkUrl}`);
|
|
976
979
|
say(terminalQr(running.networkUrl));
|
|
@@ -1009,6 +1012,9 @@ async function runCommand() {
|
|
|
1009
1012
|
...(flags["issuer-url"] !== undefined ? { issuerUrl: flags["issuer-url"] } : {}),
|
|
1010
1013
|
...(flags["database-file"] !== undefined ? { database: localDatabase(resolve(flags["database-file"])) } : {}),
|
|
1011
1014
|
roomStateFile: resolve(flags["room-state-file"] ?? "zaisma-room-states.sqlite"),
|
|
1015
|
+
// Data files sit beside the game server's code: zaisma-server/index.js reads zaisma-server/maps/docks.bin.
|
|
1016
|
+
// The game server's own folder, never the project's: a lone server file reads from zaisma-server/ beside it.
|
|
1017
|
+
dataFolder: resolve(flags["data-folder"] ?? (file === "relay" ? "zaisma-server" : basename(dirname(resolve(file))) === "zaisma-server" ? dirname(resolve(file)) : join(dirname(resolve(file)), "zaisma-server"))),
|
|
1012
1018
|
...(flags["webtransport-port"] !== undefined ? { webtransportPort: Number(flags["webtransport-port"]), certificatePath: resolve(flags["certificate-path"]), certificateKeyPath: resolve(flags["certificate-key-path"]) } : {}),
|
|
1013
1019
|
});
|
|
1014
1020
|
} catch (error) {
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, type Audience, type AwayInfo, type AwayMode, type AwayReason, type BroadcastOptions, type Delivery, type GameServer, type GameServerErrorCode, type HandlerResult, type IdleCheck, type JoinAnswer, type ChatAnswer, type ChatInfo, type JoinInfo, type KickOptions, type LiveRoom, type LeaveInfo, type LeaveReason, type MoveOptions, type MoveResult, type Player, type Purchase, type Refusal, type ReserveOptions, type KeptRoomRestoreInfo, type RestoreInfo, type Room, type RoomErrorCode, type RoomInfo, type RoomMessage, type RoomMessageSenderKind, type RoomPlayer, type RoomSelection, type SendOptions, type VersionUpdate, } from "./room.ts";
|
|
1
|
+
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, GAME_SERVER_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, type Audience, type AwayInfo, type AwayMode, type AwayReason, type BroadcastOptions, type Delivery, type GameServer, type GameServerErrorCode, type HandlerResult, type IdleCheck, type JoinAnswer, type ChatAnswer, type ChatInfo, type JoinInfo, type KickOptions, type LiveRoom, type LeaveInfo, type LeaveReason, type MoveOptions, type MoveResult, type Player, type Purchase, type Refusal, type ReserveOptions, type KeptRoomRestoreInfo, type RestoreInfo, type Room, type RoomErrorCode, type RoomInfo, type RoomMessage, type RoomMessageSenderKind, type RoomPlayer, type RoomSelection, type SendOptions, type VersionUpdate, } from "./room.ts";
|
|
2
2
|
export { REQUEST_LIMITS, type RequestErrorCode, type Server } from "./requests.ts";
|
|
3
3
|
export { SCHEDULE_LIMITS, type Schedule, type ScheduledRun } from "./schedules.ts";
|
|
4
4
|
export { WEBHOOK_LIMITS, verifyWebhook, type WebhookError, type WebhookErrorCode, type WebhookEvent, type WebhookEventKind, type WebhookHeaders } from "./webhooks.ts";
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// What @zaisma/game-server gives developers, named one by one: from v1 it only grows (test/contracts).
|
|
2
2
|
// Zaisma's own parts of the package, never locked, are in ./internal.
|
|
3
|
-
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, } from "./room.js";
|
|
3
|
+
export { BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, GAME_SERVER_OPTIONS, GameServerError, NO_ANSWER_CLOSE_CODE, REMOVED_CLOSE_CODE, GAME_SERVER_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_MESSAGE_SENDER_KINDS, SEAT_GONE_CLOSE_CODE, VERSION_UPDATE_CLOSE_CODE, defineGameServer, } from "./room.js";
|
|
4
4
|
export { REQUEST_LIMITS } from "./requests.js";
|
|
5
5
|
export { SCHEDULE_LIMITS } from "./schedules.js";
|
|
6
6
|
export { WEBHOOK_LIMITS, verifyWebhook } from "./webhooks.js";
|
package/src/requests.d.ts
CHANGED
|
@@ -25,6 +25,8 @@ export interface Server {
|
|
|
25
25
|
* (set_secret) and never shown again, or the environment variables on your own server.
|
|
26
26
|
*/
|
|
27
27
|
secrets: Readonly<Record<string, string>>;
|
|
28
|
+
/** A data file the game server ships beside its code, by its path from the zaisma-server/ folder, as room.readDataFile reads it. */
|
|
29
|
+
readDataFile(path: string): ArrayBuffer;
|
|
28
30
|
/** Check a purchase's receipt, as room.verifyReceipt does: the runtime fills in Zaisma's keys and this game. */
|
|
29
31
|
verifyReceipt(receipt: string): Promise<ReceiptClaims>;
|
|
30
32
|
/** Send a message to one of the game's live rooms by its code, as room.sendToRoom does. isDelivered is false when no such room is running or it's busy. */
|
package/src/room-calls.d.ts
CHANGED
|
@@ -132,6 +132,11 @@ export interface RoomCallChecks {
|
|
|
132
132
|
} | {
|
|
133
133
|
isValid: false;
|
|
134
134
|
};
|
|
135
|
+
/**
|
|
136
|
+
* room.readDataFile and server.readDataFile: a data file of the game server's folder, by its path from zaisma-server/ (like
|
|
137
|
+
* "maps/docks.bin"), as find answers it, or a bad_room_call naming the path when find has none.
|
|
138
|
+
*/
|
|
139
|
+
readDataFile(path: unknown, find: (dataFilePath: string) => ArrayBuffer | null, call: string): ArrayBuffer;
|
|
135
140
|
}
|
|
136
141
|
/** The checks for a runtime: pass its GameServerError class and the room limits. */
|
|
137
142
|
export declare function roomCallChecks(ErrorClass: RoomCallErrorClass, limits: RoomCallLimits): RoomCallChecks;
|
package/src/room-calls.js
CHANGED
|
@@ -241,7 +241,18 @@ function roomCallChecksParts() {
|
|
|
241
241
|
return { toRoomCode, message: readRoomMessage(message, call) };
|
|
242
242
|
};
|
|
243
243
|
const checkSendToEveryRoom = (message, roomSelection, call) => ({ message: readRoomMessage(message, call), ...checkRoomSelection(roomSelection, call) });
|
|
244
|
-
|
|
244
|
+
const readDataFile = (path, find, call) => {
|
|
245
|
+
const example = 'Give its path from the zaisma-server/ folder, like "maps/docks.bin".';
|
|
246
|
+
if (typeof path !== "string" || !path)
|
|
247
|
+
throw mistake(call, `${call} needs a data file's path.`, example);
|
|
248
|
+
// "./maps/docks.bin" and "maps/docks.bin" are the same file; nothing outside the folder is one.
|
|
249
|
+
const dataFilePath = path.replace(/^(\.\/)+/, "");
|
|
250
|
+
const found = dataFilePath.split("/").some((part) => part === "" || part === "." || part === "..") ? null : find(dataFilePath);
|
|
251
|
+
if (found === null)
|
|
252
|
+
throw mistake(call, `${call} found no data file at ${JSON.stringify(path.slice(0, 200))}.`, `Put the file in the upload's zaisma-server/ folder. ${example} .js, .json and .wasm files there are code: import them instead.`);
|
|
253
|
+
return found;
|
|
254
|
+
};
|
|
255
|
+
return { checkBroadcast, checkSend, checkBroadcastBytes, checkSendBytes, checkKick, checkReserve, checkMoveTo, checkSetInfo, checkEnd, checkRestoreToAt, checkKeptRoomRestoreId, keptRoomRestoreOf, keptRoomRestoreListOf, checkSendToRoom, checkSendToEveryRoom, checkRoomSelection, tidy, tidyRoomInfo, checkRoomData, readDataFile };
|
|
245
256
|
}
|
|
246
257
|
return { checksFor };
|
|
247
258
|
}
|
package/src/room.d.ts
CHANGED
|
@@ -191,6 +191,16 @@ export interface Room {
|
|
|
191
191
|
* game_server_allowed_hosts, and anything else throws an OutsideCallError.
|
|
192
192
|
*/
|
|
193
193
|
readonly secrets: Readonly<Record<string, string>>;
|
|
194
|
+
/**
|
|
195
|
+
* A data file the game server ships beside its code, by its path from the zaisma-server/ folder, like
|
|
196
|
+
* room.readDataFile("maps/docks.bin"): every file there that isn't .js, .json or .wasm, at any size the game
|
|
197
|
+
* server's limit allows (GAME_SERVER_LIMITS). The same ArrayBuffer every time, shared by every room of the
|
|
198
|
+
* version that runs in the same place, so read it, never change it. Reading costs nothing: the file comes with
|
|
199
|
+
* the code. A real-time room's first tick has a start's CPU (GAME_SERVER_LIMITS.maximumStartCpuDurationMs) to
|
|
200
|
+
* build from it once. On your own server it's read from dataFolder (startServer). A path with no data file
|
|
201
|
+
* throws a bad_room_call.
|
|
202
|
+
*/
|
|
203
|
+
readDataFile(path: string): ArrayBuffer;
|
|
194
204
|
/**
|
|
195
205
|
* Check a purchase's receipt, as the game sent it, before delivering: its claims, or an error named
|
|
196
206
|
* ReceiptError with a code (wrong_game, bad_signature, ...); check error.name, not instanceof, since in
|
|
@@ -786,6 +796,27 @@ export declare function readJoinAnswer(answer: unknown): {
|
|
|
786
796
|
};
|
|
787
797
|
/** Everything a game server object may have, in the order the docs give them. Anything else is refused. */
|
|
788
798
|
export declare const GAME_SERVER_OPTIONS: readonly ["maximumPlayerCount", "maximumSpectatorCount", "ticksPerSec", "hostControlsEnabled", "idleCheck", "idleTimeoutSec", "awayMode", "seatHoldDurationSec", "stateSyncEnabled", "adultChatFilterEnabled", "reconnectTimeoutSec", "maximumRoomCountPerPlayer", "stateSaveIntervalSec", "setup", "onJoin", "canJoin", "onChat", "onMoved", "onLeave", "onSpectatorJoin", "onSpectatorLeave", "onAway", "onBack", "onMessage", "onBytes", "onPurchase", "onRefund", "onTick", "onEnding", "onEndingCancelled", "onRestored", "stateView", "onVersionUpdate", "onRoomMessage", "onRequest", "schedules", "onSchedule", "onWebhook"];
|
|
799
|
+
/**
|
|
800
|
+
* What a game server on Zaisma's rooms can be and use. Each is Cloudflare's own limit or what keeps a room responsive,
|
|
801
|
+
* never a judgement of the game: a call's CPU is the work between two ticks, a start's is the one-time work before a match.
|
|
802
|
+
*/
|
|
803
|
+
export declare const GAME_SERVER_LIMITS: {
|
|
804
|
+
/**
|
|
805
|
+
* Every file of the game server together, code and data files. Cloudflare takes a Worker of 64 MB, but a room holds the
|
|
806
|
+
* files in memory (128 MB, shared) while it hands them to the sandbox, so half of that is what a room can carry safely.
|
|
807
|
+
*/
|
|
808
|
+
readonly maximumSizeBytes: number;
|
|
809
|
+
/** Files in the zaisma-server/ folder: each is read once whenever a copy of the game server loads. */
|
|
810
|
+
readonly maximumFileCount: 500;
|
|
811
|
+
/** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
|
|
812
|
+
readonly maximumCallCpuDurationMs: 50;
|
|
813
|
+
/** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after either. */
|
|
814
|
+
readonly maximumStartCpuDurationMs: 5000;
|
|
815
|
+
/** CPU for the game server's top-level code (outside its handlers) as it loads: Cloudflare's own limit. Heavy work goes in the first tick. */
|
|
816
|
+
readonly maximumLoadCpuDurationMs: 1000;
|
|
817
|
+
/** Memory of one copy of the game server, which every room of the version running in the same place shares: Cloudflare's own limit. */
|
|
818
|
+
readonly maximumMemorySizeBytes: number;
|
|
819
|
+
};
|
|
789
820
|
export declare const ROOM_LIMITS: {
|
|
790
821
|
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
791
822
|
readonly maximumPlayerCount: 100;
|
|
@@ -1230,6 +1261,8 @@ export interface Transport {
|
|
|
1230
1261
|
database?: GameDatabase;
|
|
1231
1262
|
/** The game's secrets, as room.secrets. Without them, there are none. */
|
|
1232
1263
|
secrets?: Readonly<Record<string, string>>;
|
|
1264
|
+
/** A data file by its path from the game server's folder, as room.readDataFile answers it, or null. Without it, there are none. */
|
|
1265
|
+
findDataFile?(dataFilePath: string): ArrayBuffer | null;
|
|
1233
1266
|
/** room.verifyReceipt, with Zaisma's keys and this game filled in. Without it, it throws, saying so. */
|
|
1234
1267
|
verifyReceipt?(receipt: string): Promise<ReceiptClaims>;
|
|
1235
1268
|
/** room.applyVersionUpdate(): switch to the version coming now. Without it (your own server), it does nothing. */
|
|
@@ -1245,9 +1278,11 @@ export interface Transport {
|
|
|
1245
1278
|
* The game server's server (onRequest, onSchedule, onWebhook) from what the runtime gives it: its calls to the game's
|
|
1246
1279
|
* rooms checked as a room's are, then made through roomReach, or throwing room_call_unavailable without one.
|
|
1247
1280
|
*/
|
|
1248
|
-
export declare function newServer(serverParts: Pick<Server, "database" | "secrets" | "verifyReceipt">, roomReach?: ServerRoomReach): Server;
|
|
1281
|
+
export declare function newServer(serverParts: Pick<Server, "database" | "secrets" | "verifyReceipt"> & Pick<Transport, "findDataFile">, roomReach?: ServerRoomReach): Server;
|
|
1249
1282
|
/** room.secrets and server.secrets where a game has none. */
|
|
1250
1283
|
export declare const NO_SECRETS: Readonly<Record<string, string>>;
|
|
1284
|
+
/** No data files: room.readDataFile and server.readDataFile find none. */
|
|
1285
|
+
export declare const NO_DATA_FILES: () => ArrayBuffer | null;
|
|
1251
1286
|
/** room.verifyReceipt and server.verifyReceipt where the runtime has no receipt keys. */
|
|
1252
1287
|
export declare const NO_RECEIPT_CHECK: () => Promise<ReceiptClaims>;
|
|
1253
1288
|
/**
|
package/src/room.js
CHANGED
|
@@ -135,6 +135,27 @@ export const GAME_SERVER_OPTIONS = [
|
|
|
135
135
|
"onSchedule",
|
|
136
136
|
"onWebhook",
|
|
137
137
|
];
|
|
138
|
+
/**
|
|
139
|
+
* What a game server on Zaisma's rooms can be and use. Each is Cloudflare's own limit or what keeps a room responsive,
|
|
140
|
+
* never a judgement of the game: a call's CPU is the work between two ticks, a start's is the one-time work before a match.
|
|
141
|
+
*/
|
|
142
|
+
export const GAME_SERVER_LIMITS = {
|
|
143
|
+
/**
|
|
144
|
+
* Every file of the game server together, code and data files. Cloudflare takes a Worker of 64 MB, but a room holds the
|
|
145
|
+
* files in memory (128 MB, shared) while it hands them to the sandbox, so half of that is what a room can carry safely.
|
|
146
|
+
*/
|
|
147
|
+
maximumSizeBytes: 32 * 1024 * 1024,
|
|
148
|
+
/** Files in the zaisma-server/ folder: each is read once whenever a copy of the game server loads. */
|
|
149
|
+
maximumFileCount: 500,
|
|
150
|
+
/** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
|
|
151
|
+
maximumCallCpuDurationMs: 50,
|
|
152
|
+
/** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after either. */
|
|
153
|
+
maximumStartCpuDurationMs: 5000,
|
|
154
|
+
/** CPU for the game server's top-level code (outside its handlers) as it loads: Cloudflare's own limit. Heavy work goes in the first tick. */
|
|
155
|
+
maximumLoadCpuDurationMs: 1000,
|
|
156
|
+
/** Memory of one copy of the game server, which every room of the version running in the same place shares: Cloudflare's own limit. */
|
|
157
|
+
maximumMemorySizeBytes: 128 * 1024 * 1024,
|
|
158
|
+
};
|
|
138
159
|
export const ROOM_LIMITS = {
|
|
139
160
|
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
140
161
|
maximumPlayerCount: 100,
|
|
@@ -376,6 +397,7 @@ export function newServer(serverParts, roomReach) {
|
|
|
376
397
|
return {
|
|
377
398
|
database: serverParts.database,
|
|
378
399
|
secrets: serverParts.secrets,
|
|
400
|
+
readDataFile: (path) => checks.readDataFile(path, serverParts.findDataFile ?? NO_DATA_FILES, "server.readDataFile"),
|
|
379
401
|
verifyReceipt: serverParts.verifyReceipt,
|
|
380
402
|
sendToRoom: (roomCode, message) => {
|
|
381
403
|
const reach = reachFor("server.sendToRoom");
|
|
@@ -418,6 +440,8 @@ export function newServer(serverParts, roomReach) {
|
|
|
418
440
|
}
|
|
419
441
|
/** room.secrets and server.secrets where a game has none. */
|
|
420
442
|
export const NO_SECRETS = Object.freeze({});
|
|
443
|
+
/** No data files: room.readDataFile and server.readDataFile find none. */
|
|
444
|
+
export const NO_DATA_FILES = () => null;
|
|
421
445
|
/** room.verifyReceipt and server.verifyReceipt where the runtime has no receipt keys. */
|
|
422
446
|
export const NO_RECEIPT_CHECK = () => Promise.reject(new Error("Receipts can't be checked here: run the game server in Zaisma rooms or with the Node runner (npx @zaisma/game-server), or call verifyReceipt with the keys from https://rooms.zaisma.com/.well-known/receipt-jwks.json and issuer https://rooms.zaisma.com/receipts."));
|
|
423
447
|
/** room.database where the room has no database: every call fails, saying so. */
|
|
@@ -1040,6 +1064,7 @@ export class RoomCore {
|
|
|
1040
1064
|
listRooms: (roomSelection) => this.roomReachFor("room.listRooms").listRooms(checks.checkRoomSelection(roomSelection, "room.listRooms").labels),
|
|
1041
1065
|
database: transport.database ?? NO_DATABASE,
|
|
1042
1066
|
secrets: transport.secrets ?? NO_SECRETS,
|
|
1067
|
+
readDataFile: (path) => checks.readDataFile(path, transport.findDataFile ?? NO_DATA_FILES, "room.readDataFile"),
|
|
1043
1068
|
verifyReceipt: transport.verifyReceipt ?? NO_RECEIPT_CHECK,
|
|
1044
1069
|
hasBlockBetween: (firstPlayerId, secondPlayerId) => this.hasBlockBetween(firstPlayerId, secondPlayerId),
|
|
1045
1070
|
areFriends: (firstPlayerId, secondPlayerId) => this.areFriends(firstPlayerId, secondPlayerId),
|