@zaisma/game-server 1.34.0 → 1.36.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.
@@ -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 <folder>/.zaisma-local/. Nothing here changes the game server: it checks the
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 holds what the bench keeps. */
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;
@@ -208,13 +209,32 @@ function checkedOptions(options) {
208
209
  const fail = (code, field, message, fix) => new GameServerError(code, field, message, fix);
209
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(", ")}.`);
210
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(", ")}.`);
211
- 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;
212
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.");
213
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.");
214
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.");
215
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/.");
216
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.");
217
- 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}`);
218
238
  }
219
239
 
220
240
  /**
@@ -226,7 +246,7 @@ function checkedOptions(options) {
226
246
  * close() }: close() saves every room first and finishes once everything has stopped.
227
247
  */
228
248
  export async function startLocalPlay(givenOptions) {
229
- 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);
230
250
  // Everything the bench says goes to the terminal, and the last of it to the dev page's Log.
231
251
  const logLines = [];
232
252
  const log = (line) => {
@@ -245,7 +265,18 @@ export async function startLocalPlay(givenOptions) {
245
265
  }
246
266
  const ports = { bench: port, game: port + 1, rooms: port + 2, runner: port + 3 };
247
267
  const host = isOnNetwork ? undefined : "127.0.0.1";
248
- const localFolder = join(gameFolder, LOCAL_FOLDER);
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
+ }
249
280
  mkdirSync(join(localFolder, "saves"), { recursive: true });
250
281
 
251
282
  // --- The keys: one pair for passes, one for receipts, made on the first run ---
@@ -822,7 +853,7 @@ export async function startLocalPlay(givenOptions) {
822
853
  return fail(404, "not_local", `${request.method} ${path} is a part of Zaisma's buy sheet the bench has no stand-in for.`);
823
854
  }
824
855
 
825
- // Cloud saves (apps/site/src/saves.ts), stood in for: one save per account, kept in .zaisma-local/saves/, with its version number.
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.
826
857
  const saveFileOf = (accountId) => join(localFolder, "saves", `${accountId}.json`);
827
858
  const savedRowOf = (accountId) => {
828
859
  try {
@@ -1625,6 +1656,9 @@ export async function startLocalPlay(givenOptions) {
1625
1656
  gameSiteUrl: localhostOrigin(ports.game),
1626
1657
  roomsUrl: issuerUrl,
1627
1658
  networkUrl,
1659
+ gameSlug,
1660
+ isGameSlugFromFolder: givenSlug === null,
1661
+ benchFolder: localFolder,
1628
1662
  get runnerStartCount() {
1629
1663
  return runnerStartCount;
1630
1664
  },
package/bin/node.js CHANGED
@@ -970,10 +970,10 @@ async function playLocally(argumentList) {
970
970
  process.exit(1);
971
971
  }
972
972
  for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => running.close().then(() => process.exit(0)));
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 }));
974
- say(`Playing ${given.gameSlug ?? "your game"} on this computer. The test bench is at ${running.benchUrl}`);
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}`);
975
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.");
976
- say("Nothing here talks to Zaisma. What the bench keeps is in .zaisma-local/ in the game's folder: add it to your .gitignore. Press Ctrl-C to stop.");
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.`);
977
977
  if (running.networkUrl) {
978
978
  say(`On a phone on the same Wi-Fi: ${running.networkUrl}`);
979
979
  say(terminalQr(running.networkUrl));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/game-server",
3
- "version": "1.34.0",
3
+ "version": "1.36.0",
4
4
  "description": "Run your Zaisma game server: the same rooms on Zaisma or on your own server.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
package/src/room.d.ts CHANGED
@@ -810,7 +810,7 @@ export declare const GAME_SERVER_LIMITS: {
810
810
  readonly maximumFileCount: 500;
811
811
  /** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
812
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. */
813
+ /** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after any of them, or after its state is put back in a fresh copy of the game server, onRestored or not. */
814
814
  readonly maximumStartCpuDurationMs: 5000;
815
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
816
  readonly maximumLoadCpuDurationMs: 1000;
package/src/room.js CHANGED
@@ -149,7 +149,7 @@ export const GAME_SERVER_LIMITS = {
149
149
  maximumFileCount: 500,
150
150
  /** CPU for one call: a tick with the messages since the last one, a join, a request, a schedule's run. */
151
151
  maximumCallCpuDurationMs: 50,
152
- /** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after either. */
152
+ /** CPU for one start: loading the game server, setup, onRestored, and a real-time room's first tick after any of them, or after its state is put back in a fresh copy of the game server, onRestored or not. */
153
153
  maximumStartCpuDurationMs: 5000,
154
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
155
  maximumLoadCpuDurationMs: 1000,