@zaisma/game-server 1.50.0 → 1.51.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/bin/local-play.js CHANGED
@@ -38,7 +38,7 @@ export const LOCAL_VERSION_ID = "version_local";
38
38
  /** 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. */
39
39
  export const LOCAL_FOLDER = ".zaisma-local";
40
40
  /** 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). */
41
- export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/saves.js", "_zaisma/restore"];
41
+ export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/sound.js", "_zaisma/saves.js", "_zaisma/restore"];
42
42
  /** The _zaisma/ files only the bench serves, which Zaisma's games Worker never does: the bench's clip recorder. */
43
43
  export const ONLY_ON_BENCH_PATHS = ["_zaisma/clip.js"];
44
44
  export const ONLY_ON_ZAISMA_PATHS = ["_zaisma/performance.js", "_zaisma/pressure.js", "_zaisma/warm", "_zaisma/warm.json", "_zaisma/warm-redirects.json", "_zaisma/warm.js"];
@@ -1053,10 +1053,23 @@ export async function startLocalPlay(givenOptions) {
1053
1053
 
1054
1054
  // Friends: who's playing, the Friend marks in the players sheet, and blocks.
1055
1055
  if (request.method === "GET" && path === `${game}/friends`) return fragment(account ? glass.friendsHereHtml(gameSlug, friendsPlaying(account.id)) : "");
1056
- if (request.method === "GET" && path === `${game}/players/friends`) {
1057
- if (!account) return reply(401, { error: { code: "not_signed_in", message: "Sign in to see your friends." } });
1058
- const room = (url.searchParams.get("room") ?? "").toUpperCase();
1059
- return fragment(glass.friendRowsHtml(gameSlug, friendsPlaying(account.id).filter((friend) => friend.roomCode !== room)));
1056
+ // The guide's places, from the bench's own players (glass.guidePlaceHtml); its sound and invites are kept nowhere here.
1057
+ const guideMatch = /^\/guide\/([a-z]+)$/.exec(path);
1058
+ if (guideMatch && request.method === "GET") {
1059
+ const friendIds = new Set(account ? friendIdsOf(account.id) : []);
1060
+ const markup = glass.guidePlaceHtml(guideMatch[1], url.searchParams, {
1061
+ gameSlug,
1062
+ account: account ? { username: account.username, playerId: account.playerId } : null,
1063
+ friends: account ? friendsPlaying(account.id) : [],
1064
+ others: state.accounts.map((other) => ({ username: other.username, playerId: other.playerId, isFriend: friendIds.has(other.id) })),
1065
+ });
1066
+ return markup === null ? reply(404, { error: { code: "not_found", message: "Nothing here." } }) : fragment(markup);
1067
+ }
1068
+ if (guideMatch && isPost) {
1069
+ const body = await readJson(request);
1070
+ if (!account) return reply(401, { error: { code: "not_signed_in", message: "Sign in first.", field: null, fix: "Sign in, then try again." } });
1071
+ if (guideMatch[1] === "sound") return reply(200, { sound: body });
1072
+ if (guideMatch[1] === "invite") return reply(200, { invite_status: "sent" });
1060
1073
  }
1061
1074
  if (request.method === "GET" && path === "/friends/among") {
1062
1075
  const given = (url.searchParams.get("player_ids") ?? "").split(",").filter(Boolean);
@@ -1334,6 +1347,7 @@ export async function startLocalPlay(givenOptions) {
1334
1347
  if (path === "_zaisma/clip.js") return send(200, js, clipScriptSource(benchOrigin));
1335
1348
  if (path === "_zaisma/relay.js") return send(200, js, withSetup("__ZAISMA_RELAY__", { rooms: originFor(request, ports.rooms), game: gameSlug, site: benchOrigin, ownRelayHosts: [], fetchEarly: false }, sdkText("relay.js")));
1336
1349
  if (path === "_zaisma/picture.js") return send(200, js, withSetup("__ZAISMA_PICTURE__", { site: benchOrigin }, sdkText("picture.js")));
1350
+ if (path === "_zaisma/sound.js") return send(200, js, withSetup("__ZAISMA_SOUND__", { site: benchOrigin }, sdkText("sound.js")));
1337
1351
  if (path === "_zaisma/saves.js") {
1338
1352
  const versionId = url.searchParams.get("version_id");
1339
1353
  return send(200, js, withSetup("__ZAISMA_SAVES__", { site: benchOrigin, saveLimitBytes: SAVE_LIMIT_BYTES, versionId: versionId === LOCAL_VERSION_ID ? versionId : null }, sdkText("saves.js")));
@@ -1358,7 +1372,7 @@ export async function startLocalPlay(givenOptions) {
1358
1372
  const contentType = TYPES[extname(target).toLowerCase()] ?? "application/octet-stream";
1359
1373
  const bytes = readFileSync(target);
1360
1374
  if (contentType.startsWith("text/html")) {
1361
- const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`, `/_zaisma/clip.js?v=${SCRIPTS_VERSION_NUMBER}`]);
1375
+ const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/sound.js?v=${SCRIPTS_VERSION_NUMBER}`, `/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`, `/_zaisma/clip.js?v=${SCRIPTS_VERSION_NUMBER}`]);
1362
1376
  return send(200, contentType, injected);
1363
1377
  }
1364
1378
  const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/game-server",
3
- "version": "1.50.0",
3
+ "version": "1.51.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/sdk/sound.js ADDED
@@ -0,0 +1,84 @@
1
+ /*
2
+ * Zaisma's own sound for every game. Zaisma adds this to every game page, first, before any of the game's own scripts: one volume and one mute
3
+ * over all of the game's audio, whatever the game does with its own settings, and voices (the SDK's room.voice) at a volume of their own. The
4
+ * player sets them in the guide's Settings, beside the game, and the Zaisma game page hands them over (zaisma:sound); nothing leaves the frame.
5
+ * Web Audio: whatever the game connects to a context's speakers goes through one gain of Zaisma's on its way. Audio and video elements: the volume
6
+ * a game sets is kept as its own, and the element plays at that times Zaisma's. Plain JavaScript, no dependencies, MIT licensed.
7
+ */
8
+ (function () {
9
+ "use strict";
10
+ var site = typeof __ZAISMA_SOUND__ === "object" && __ZAISMA_SOUND__ ? __ZAISMA_SOUND__.site : "";
11
+ if (!site || window.parent === window || window.__zaismaSoundSet) return;
12
+ window.__zaismaSoundSet = true;
13
+ var sound = { gameVolumePct: 100, isGameSoundOn: true, voiceVolumePct: 100 };
14
+ var levelOf = function (isVoice) { return isVoice ? sound.voiceVolumePct / 100 : sound.isGameSoundOn ? sound.gameVolumePct / 100 : 0; };
15
+
16
+ /* ---- Web Audio ---- */
17
+
18
+ var Node = window.AudioNode, Destination = window.AudioDestinationNode;
19
+ var gains = [];
20
+ if (Node && Destination) {
21
+ var connect = Node.prototype.connect, disconnect = Node.prototype.disconnect;
22
+ // Each context's own gain in front of its speakers, made the first time something is connected to them.
23
+ var gainOf = function (audioContext) {
24
+ if (audioContext.__zaismaGain) return audioContext.__zaismaGain;
25
+ var gain = audioContext.createGain();
26
+ connect.call(gain, audioContext.destination);
27
+ gain.gain.value = levelOf(audioContext.__zaismaVoice === true);
28
+ audioContext.__zaismaGain = gain;
29
+ gains.push({ audioContext: audioContext, gain: gain });
30
+ return gain;
31
+ };
32
+ Node.prototype.connect = function (target) {
33
+ if (target instanceof Destination && this !== target.context.__zaismaGain) {
34
+ var rest = Array.prototype.slice.call(arguments, 1);
35
+ return connect.apply(this, [gainOf(target.context)].concat(rest));
36
+ }
37
+ return connect.apply(this, arguments);
38
+ };
39
+ Node.prototype.disconnect = function (target) {
40
+ if (target instanceof Destination && target.context.__zaismaGain && this !== target.context.__zaismaGain) {
41
+ var rest = Array.prototype.slice.call(arguments, 1);
42
+ return disconnect.apply(this, [target.context.__zaismaGain].concat(rest));
43
+ }
44
+ return disconnect.apply(this, arguments);
45
+ };
46
+ }
47
+
48
+ /* ---- Audio and video elements ---- */
49
+
50
+ var Media = window.HTMLMediaElement;
51
+ var elements = [];
52
+ var volume = Media && Object.getOwnPropertyDescriptor(Media.prototype, "volume");
53
+ if (volume && volume.get && volume.set) {
54
+ var own = function (element) { return typeof element.__zaismaVolume === "number" ? element.__zaismaVolume : 1; };
55
+ var apply = function (element) { volume.set.call(element, Math.max(0, Math.min(1, own(element) * levelOf(element.__zaismaVoice === true)))); };
56
+ var keep = function (element) { if (element.__zaismaKept) return; element.__zaismaKept = true; elements.push(new WeakRef(element)); };
57
+ Object.defineProperty(Media.prototype, "volume", {
58
+ configurable: true,
59
+ enumerable: volume.enumerable,
60
+ get: function () { return own(this); },
61
+ set: function (volumeLevel) { this.__zaismaVolume = Math.max(0, Math.min(1, Number(volumeLevel))); keep(this); apply(this); },
62
+ });
63
+ var play = Media.prototype.play;
64
+ Media.prototype.play = function () { keep(this); apply(this); return play.apply(this, arguments); };
65
+ document.addEventListener("play", function (event) { if (event.target instanceof Media) { keep(event.target); apply(event.target); } }, true);
66
+ }
67
+
68
+ function applyAll() {
69
+ gains.forEach(function (each) {
70
+ var level = levelOf(each.audioContext.__zaismaVoice === true);
71
+ try { each.gain.gain.setTargetAtTime(level, each.audioContext.currentTime, 0.02); } catch (error) { each.gain.gain.value = level; }
72
+ });
73
+ elements = elements.filter(function (held) { var element = held.deref(); if (element) apply(element); return Boolean(element); });
74
+ }
75
+ var pct = function (given, fallback) { return typeof given === "number" && given >= 0 && given <= 100 ? Math.round(given) : fallback; };
76
+ window.addEventListener("message", function (event) {
77
+ var told = event.data;
78
+ if (event.origin !== site || event.source !== window.parent || !told || told.type !== "zaisma:sound") return;
79
+ sound = { gameVolumePct: pct(told.gameVolumePct, 100), isGameSoundOn: told.isGameSoundOn !== false, voiceVolumePct: pct(told.voiceVolumePct, 100) };
80
+ applyAll();
81
+ });
82
+ // Asked for as the game starts, so a game that plays at once plays at the player's volume.
83
+ window.parent.postMessage({ type: "zaisma:sound-request" }, site);
84
+ })();
package/sdk/zaisma.d.ts CHANGED
@@ -209,7 +209,7 @@ declare namespace Zaisma {
209
209
  const server: Server;
210
210
 
211
211
  /**
212
- * Invite friends. On Zaisma it opens Zaisma's invite sheet, the same as the Zaisma overlay's Share: the
212
+ * Invite friends. On Zaisma it opens Zaisma's invite sheet, the same as the guide's Share: the
213
213
  * room's QR code, link and code, Copy and the share sheet ("opened", or "failed" when the page couldn't
214
214
  * open it). On your own site it opens the share sheet on phones, otherwise copies the room's invite link
215
215
  * (the game's page without a room). Call it from a button in your game, like on a "waiting for players"
@@ -606,7 +606,7 @@ declare namespace Zaisma {
606
606
 
607
607
  /**
608
608
  * Whether Zaisma's page covers the game right now, so a game can pause or hold the player's input while it does.
609
- * coveredBy is "sheet" while one of Zaisma's sheets is open over the game (buying, the Zaisma overlay, Report: the player is
609
+ * coveredBy is "sheet" while one of Zaisma's sheets is open over the game (buying, the guide, Report: the player is
610
610
  * busy with it), "card" while one of its cards is over the game's corner (Still there?, Keep your progress; the
611
611
  * game stays in view and playable), and null otherwise. Always null outside Zaisma's page (your own site, a
612
612
  * local test). Listen for "coveredBy" to hear each change.
@@ -618,10 +618,26 @@ declare namespace Zaisma {
618
618
  */
619
619
  const page: Page;
620
620
 
621
- /** Whether Zaisma's page covers the game ({@link page}). */
621
+ /** Whether Zaisma's page covers the game ({@link page}), and the game's two calls on it. */
622
622
  interface Page {
623
623
  /** "sheet", "card" or null: what of Zaisma's is over the game now. Read-only. */
624
624
  readonly coveredBy: CoveredBy;
625
+ /**
626
+ * Opens Zaisma's player card for a player in the game's room, on that player's press in your game (a Card button on a scoreboard): who they are, how
627
+ * the player knows them, Add friend, Mute, Block and Report. Only a player in the room the game is in; the guide beside the game shows it. It opens
628
+ * only right after the player's own press, as Zaisma.invite does: called at any other time, nothing opens.
629
+ * Fails with error.code "bad_player_id" for something that isn't a player's id, and "not_on_zaisma" off Zaisma's page.
630
+ * @example
631
+ * cardButton.onclick = () => Zaisma.page.openPlayerCard(player.id);
632
+ */
633
+ openPlayerCard(playerId: string): Promise<void>;
634
+ /**
635
+ * Ends play from the game's own menu, after its own confirm: the player lands on the game's page, where the guide's Leave lands. Fails with
636
+ * error.code "not_on_zaisma" off Zaisma's page, where the game ends play its own way.
637
+ * @example
638
+ * quitConfirm.onclick = () => Zaisma.page.leave();
639
+ */
640
+ leave(): Promise<void>;
625
641
  /** Listen for "coveredBy": called with the new value each time it changes. A wrong name fails with error.code "unknown_event". */
626
642
  on(event: "coveredBy", listener: (coveredBy: CoveredBy) => void): Page;
627
643
  off(event: "coveredBy", listener: (coveredBy: CoveredBy) => void): Page;
package/sdk/zaisma.js CHANGED
@@ -1982,13 +1982,15 @@
1982
1982
  this._isMicrophoneMuted = Boolean(voiceOptions && voiceOptions.isMuted);
1983
1983
  this._wantsJoin = true;
1984
1984
  // Made and woken here, inside the player's tap: made later, after the microphone's prompt, browsers keep it silent.
1985
- if (!this.audioContext) this.audioContext = new AudioContext();
1985
+ // Voices are marked as such, so Zaisma's own sound (_zaisma/sound.js) plays them at the player's voice volume, apart from the game's.
1986
+ if (!this.audioContext) { this.audioContext = new AudioContext(); this.audioContext.__zaismaVoice = true; }
1986
1987
  if (!this.outputNode) {
1987
1988
  // Voices reach the speakers through a media element, not the context's own output: echo cancellation hears what
1988
1989
  // media elements play (on phones, only that), so the microphone doesn't send the voices back. The game's own sound
1989
1990
  // can come this way too (outputNode).
1990
1991
  var output = this.audioContext.createMediaStreamDestination();
1991
1992
  this._outputElement = new Audio();
1993
+ this._outputElement.__zaismaVoice = true;
1992
1994
  this._outputElement.srcObject = output.stream;
1993
1995
  this.outputNode = output;
1994
1996
  this._unlockSoundOnTap();
@@ -2104,6 +2106,7 @@
2104
2106
  var stream = new MediaStream([transceiver.receiver.track]);
2105
2107
  // Chrome plays a remote voice into Web Audio only while a media element holds it too; the element itself stays silent.
2106
2108
  var element = new Audio();
2109
+ element.__zaismaVoice = true;
2107
2110
  element.muted = true;
2108
2111
  element.srcObject = stream;
2109
2112
  element.play().catch(function () {});
@@ -3040,7 +3043,26 @@
3040
3043
  */
3041
3044
  var pageEvents = new Emitter(PAGE_EVENTS, "Zaisma.page has");
3042
3045
  var coveredBy = null;
3046
+ /*
3047
+ * The game's two calls on Zaisma's page (zaisma.d.ts: Zaisma.page.openPlayerCard, Zaisma.page.leave). A game owns everything inside itself, so its own
3048
+ * scoreboard's Card button and its own menu's Leave are its; Zaisma only draws the card (with Block and Report always in it) and takes the player out.
3049
+ * Off Zaisma (the developer's own site, a local test without a page) there's no page to answer: each says so, and the game does what it does there.
3050
+ */
3051
+ var MAXIMUM_PLAYER_ID_CHARACTER_COUNT = 60;
3052
+ function openPlayerCard(playerId) {
3053
+ if (typeof playerId !== "string" || !playerId || playerId.length > MAXIMUM_PLAYER_ID_CHARACTER_COUNT) return Promise.reject(codedError("bad_player_id", "openPlayerCard takes the player's id, as room.players lists it."));
3054
+ if (!config.site || window.parent === window) return Promise.reject(notOnZaisma("Zaisma's player card opens when the game is played on its zaisma.com page."));
3055
+ window.parent.postMessage({ type: "zaisma:open-player-card", playerId: playerId }, config.site);
3056
+ return Promise.resolve();
3057
+ }
3058
+ function leave() {
3059
+ if (!config.site || window.parent === window) return Promise.reject(notOnZaisma("Leaving through Zaisma works when the game is played on its zaisma.com page."));
3060
+ window.parent.postMessage({ type: "zaisma:leave" }, config.site);
3061
+ return Promise.resolve();
3062
+ }
3043
3063
  var zaismaPage = {
3064
+ openPlayerCard: openPlayerCard,
3065
+ leave: leave,
3044
3066
  on: function (event, listener) {
3045
3067
  pageEvents.on(event, listener);
3046
3068
  return zaismaPage;