@zaisma/cli 0.22.0 → 0.24.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/zaisma.mjs +93 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/cli",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "description": "Upload and publish browser games on Zaisma from the command line.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
package/zaisma.mjs CHANGED
@@ -136,6 +136,13 @@ const COMMANDS = {
136
136
  secrets: { about: "A game's secrets, which its game server reads as server.secrets and room.secrets: their names and when each was set, never the values", arguments: [{ name: "slug" }], flags: {} },
137
137
  "secrets set": { about: "Set a secret for a game's server, replacing one of the same name: the value piped in, or typed without showing; it's never shown again", arguments: [{ name: "slug" }, { name: "secret_name" }], flags: {} },
138
138
  "secrets delete": { about: "Delete one of a game's secrets", arguments: [{ name: "slug" }, { name: "secret_name" }], flags: {} },
139
+ items: { about: "What a game sells or grants: each item's name, kind, category and price, and the game's refund policy", arguments: [{ name: "slug" }], flags: {} },
140
+ "items set": {
141
+ about: "Make a game's items match a JSON file (or piped in) of the whole list, as list_items answers its items: each changed item is set, and each one missing from the file removed, unless players own it",
142
+ arguments: [{ name: "slug" }, { name: "file", isOptional: true }],
143
+ flags: {},
144
+ },
145
+ "items remove": { about: "Remove an item nobody bought or was granted", arguments: [{ name: "slug" }, { name: "item_name" }], flags: {} },
139
146
  "kept-rooms": { about: "A game's kept rooms (room.setKept), worlds that sleep with nobody in them: each one's code, name, size and when it was last played, and the game's storage", arguments: [{ name: "slug" }], flags: {} },
140
147
  "kept-rooms delete": { about: "Delete a kept room's world for good; players in it are sent out", arguments: [{ name: "slug" }, { name: "room_code" }], flags: {} },
141
148
  logs: {
@@ -239,7 +246,7 @@ const COMMANDS = {
239
246
  help: { about: "This help; with --json, every command, flag, exit code and error code", arguments: [], flags: {} },
240
247
  };
241
248
  /** Commands with a second word, like zaisma forum post. */
242
- const SUBCOMMANDS = { links: ["set", "remove"], forum: ["post", "message", "reply"], database: ["query", "batch", "export", "import", "restore", "undo-restore"], saves: ["get", "change", "replace", "reset", "copies", "copy", "restore"], secrets: ["set", "delete"], "kept-rooms": ["delete"] };
249
+ const SUBCOMMANDS = { links: ["set", "remove"], forum: ["post", "message", "reply"], database: ["query", "batch", "export", "import", "restore", "undo-restore"], saves: ["get", "change", "replace", "reset", "copies", "copy", "restore"], secrets: ["set", "delete"], items: ["set", "remove"], "kept-rooms": ["delete"] };
243
250
  /** Flags every command takes. */
244
251
  const GLOBAL_FLAGS = {
245
252
  json: { hasValue: false, about: "Print the API's answer as JSON, as-is (on failure its { error }), and nothing else" },
@@ -1001,11 +1008,10 @@ async function database(command, values, flags) {
1001
1008
  if (!answer.tables.length) console.log("No tables yet. Make one from your game server, or with: zaisma database query <slug> \"CREATE TABLE …\"");
1002
1009
  for (const table of answer.tables) console.log(`${table.sql};`);
1003
1010
  for (const index of answer.indexes) console.log(`${index.sql};`);
1004
- const percent = (used, free) => `${Math.floor((used / free) * 100)}%`;
1011
+ const hosting = answer.hosting_use_this_month;
1005
1012
  console.log(
1006
- `\nThis month: ${use.read_row_count.toLocaleString("en-US")} rows read (${percent(use.read_row_count, use.free_read_row_count)} of the free ${use.free_read_row_count.toLocaleString("en-US")}), ` +
1007
- `${use.written_row_count.toLocaleString("en-US")} written (${percent(use.written_row_count, use.free_written_row_count)} of ${use.free_written_row_count.toLocaleString("en-US")}), ` +
1008
- `${(use.storage_size_bytes / 1024 / 1024).toFixed(1)} MB stored (${percent(use.storage_size_bytes, use.free_storage_size_bytes)} of ${use.free_storage_size_bytes / 1024 / 1024} MB). Resets ${use.reset_date}.`,
1013
+ `\nThis month: ${use.read_row_count.toLocaleString("en-US")} rows read, ${use.written_row_count.toLocaleString("en-US")} written, ${sizeText(use.storage_size_bytes)} stored (a game keeps up to ${sizeText(use.maximum_storage_size_bytes)}). ` +
1014
+ `Free hosting this month: ${hosting.free_used_pct}% used${hosting.is_paused ? ", paused" : ""}. Resets ${hosting.resets_on_date}.`,
1009
1015
  );
1010
1016
  if (answer.restores.length) {
1011
1017
  console.log("\nRestores (newest first; undo with zaisma database undo-restore <slug> <id>):");
@@ -1457,6 +1463,85 @@ async function secrets(command, values) {
1457
1463
  if (answer.next_steps.some((step) => step.tool === "update_game")) console.log(`It calls no other servers yet: list the hosts it uses this with, like zaisma allowed-hosts ${values.slug} discord.com`);
1458
1464
  }
1459
1465
 
1466
+ /** The fields of an item the file gives and set_item takes. */
1467
+ const ITEM_FILE_FIELDS = ["item_name", "title", "description", "item_kind", "item_category", "price_minor_units", "currency_code", "local_prices"];
1468
+
1469
+ /** A price as people read it, from minor units, for the list. */
1470
+ function itemPriceText(gameItem) {
1471
+ if (gameItem.price_minor_units === null) return "not sold";
1472
+ const isWhole = ["jpy", "krw"].includes(gameItem.currency_code);
1473
+ return `${(gameItem.price_minor_units / (isWhole ? 1 : 100)).toFixed(isWhole ? 0 : 2)} ${gameItem.currency_code.toUpperCase()}${gameItem.local_prices.length ? ` (+${gameItem.local_prices.length} local)` : ""}`;
1474
+ }
1475
+
1476
+ /**
1477
+ * A game's items (…/games/<slug>/items…), as the MCP's list_items, set_item and remove_item. items set takes
1478
+ * the whole list from a file kept beside the game, so prices live in git: one call per changed item, and one
1479
+ * per item gone from the file, which the API refuses for an item players own.
1480
+ */
1481
+ async function items(command, values) {
1482
+ const path = `/games/${values.slug}/items`;
1483
+ if (command === "items remove") {
1484
+ const answer = await api("DELETE", `${path}/${encodeURIComponent(values.item_name)}`);
1485
+ if (isJson) return printJson(answer);
1486
+ return console.log(`Removed ${values.item_name} from ${values.slug}.`);
1487
+ }
1488
+ if (command === "items set") {
1489
+ const text = values.file ? await readFile(values.file, "utf8").catch(() => refuse("not_a_file", { message: `Couldn't read ${values.file}.`, field: "file", fix: "Give the path of a JSON file of the game's items, or pipe it in." })) : await readInput();
1490
+ let wanted;
1491
+ try {
1492
+ wanted = JSON.parse(text);
1493
+ } catch {
1494
+ wanted = null;
1495
+ }
1496
+ const fileFix = 'Give a JSON list of whole items, like [{ "item_name": "revive", "title": "Revive", "description": "", "item_kind": "consumable", "item_category": "gameplay", "price_minor_units": 199, "currency_code": "usd", "local_prices": [] }].';
1497
+ if (!Array.isArray(wanted) || wanted.some((gameItem) => !gameItem || typeof gameItem !== "object" || typeof gameItem.item_name !== "string")) refuse("bad_item", { message: `${values.file ?? "What was piped in"} isn't a JSON list of items.`, field: "file", fix: fileFix });
1498
+ for (const gameItem of wanted) {
1499
+ const unknown = Object.keys(gameItem).find((key) => !ITEM_FILE_FIELDS.includes(key) && !["card_fee_note", "created_at", "updated_at"].includes(key));
1500
+ if (unknown) refuse("unknown_field", { message: `${gameItem.item_name} has ${unknown}, which isn't an item's field.`, field: "file", fix: `An item takes ${ITEM_FILE_FIELDS.join(", ")}.` });
1501
+ }
1502
+ const names = wanted.map((gameItem) => gameItem.item_name);
1503
+ const repeated = names.find((name, i) => names.indexOf(name) !== i);
1504
+ if (repeated) refuse("bad_item", { message: `${repeated} is in the file twice.`, field: "file", fix: "Give each item once." });
1505
+ const current = (await api("GET", path)).items;
1506
+ const same = (gameItem, existing) => ITEM_FILE_FIELDS.every((field) => JSON.stringify(gameItem[field] ?? null) === JSON.stringify(existing[field] ?? null));
1507
+ const changed = wanted.filter((gameItem) => { const existing = current.find((other) => other.item_name === gameItem.item_name); return !existing || !same(gameItem, existing); });
1508
+ const gone = current.filter((existing) => !names.includes(existing.item_name));
1509
+ const setNames = [];
1510
+ for (const gameItem of changed) {
1511
+ const { item_name: itemName, ...fields } = gameItem;
1512
+ for (const field of ITEM_FILE_FIELDS.slice(1)) if (!(field in fields)) fields[field] = field === "local_prices" ? [] : field === "description" ? "" : null;
1513
+ for (const key of ["card_fee_note", "created_at", "updated_at"]) delete fields[key];
1514
+ await api("PUT", `${path}/${encodeURIComponent(itemName)}`, fields);
1515
+ setNames.push(itemName);
1516
+ say(`Set ${itemName}.`);
1517
+ }
1518
+ const removedNames = [];
1519
+ const keptNames = [];
1520
+ for (const existing of gone) {
1521
+ try {
1522
+ await api("DELETE", `${path}/${encodeURIComponent(existing.item_name)}`);
1523
+ removedNames.push(existing.item_name);
1524
+ say(`Removed ${existing.item_name}.`);
1525
+ } catch (error) {
1526
+ if (!(error instanceof CommandError) || error.error.code !== "item_has_owners") throw error;
1527
+ keptNames.push(existing.item_name);
1528
+ }
1529
+ }
1530
+ const answer = await api("GET", path);
1531
+ if (keptNames.length) {
1532
+ refuse("item_has_owners", { message: `Players own ${keptNames.join(", ")}, so ${keptNames.length === 1 ? "it stays" : "they stay"}; everything else matches the file.`, field: "file", fix: "Keep them in the file with price_minor_units and currency_code null to stop selling them." }, EXIT_CODES.failed);
1533
+ }
1534
+ if (isJson) return printJson({ ...answer, set_item_names: setNames, removed_item_names: removedNames });
1535
+ if (!setNames.length && !removedNames.length) console.log(`${values.slug}'s items already match the file.`);
1536
+ return;
1537
+ }
1538
+ const answer = await api("GET", path);
1539
+ if (isJson) return printJson(answer);
1540
+ if (!answer.items.length) console.log(`${values.slug} sells nothing yet. Set its items with: zaisma items set ${values.slug} items.json`);
1541
+ for (const gameItem of answer.items) console.log(`${gameItem.item_name.padEnd(24)} ${gameItem.item_kind.padEnd(11)} ${gameItem.item_category.padEnd(9)} ${itemPriceText(gameItem)}`);
1542
+ console.log(`Refund policy: ${answer.refund_policy === "own_words" ? answer.refund_policy_text : (answer.refund_policy ?? "none yet (set_purchase_settings), needed before anything goes on sale")}`);
1543
+ }
1544
+
1460
1545
  /** A game's kept rooms (…/games/<slug>/kept-rooms…), as the MCP's list_kept_rooms and delete_kept_room. */
1461
1546
  async function keptRooms(command, values) {
1462
1547
  if (command === "kept-rooms") {
@@ -1464,7 +1549,7 @@ async function keptRooms(command, values) {
1464
1549
  if (isJson) return printJson(answer);
1465
1550
  if (!answer.kept_rooms.length) console.log(`No kept rooms. A game server keeps one with room.setKept(true).`);
1466
1551
  for (const keptRoom of answer.kept_rooms) console.log(`${keptRoom.room_code} ${(keptRoom.name ?? "").padEnd(24)} ${sizeText(keptRoom.saved_size_bytes).padStart(9)} played ${keptRoom.last_played_at ? when(keptRoom.last_played_at) : "never"}`);
1467
- console.log(`Storage: ${sizeText(answer.storage_size_bytes)} of ${sizeText(answer.free_storage_size_bytes)} free (database and kept rooms).`);
1552
+ console.log(`Storage: ${sizeText(answer.storage_size_bytes)} of the ${sizeText(answer.maximum_storage_size_bytes)} a game can keep (database and kept rooms).`);
1468
1553
  return;
1469
1554
  }
1470
1555
  const answer = await api("DELETE", `/games/${values.slug}/kept-rooms/${encodeURIComponent(values.room_code)}`);
@@ -1602,7 +1687,7 @@ function readKeys(given) {
1602
1687
  return keys;
1603
1688
  }
1604
1689
 
1605
- const sizeText = (sizeBytes) => (sizeBytes < 1024 ? `${sizeBytes} B` : sizeBytes < 1048576 ? `${(sizeBytes / 1024).toFixed(1)} KB` : `${(sizeBytes / 1048576).toFixed(1)} MB`);
1690
+ const sizeText = (sizeBytes) => (sizeBytes < 1024 ? `${sizeBytes} B` : sizeBytes < 1048576 ? `${(sizeBytes / 1024).toFixed(1)} KB` : sizeBytes < 1024 ** 3 ? `${(sizeBytes / 1048576).toFixed(1)} MB` : `${(sizeBytes / 1024 ** 3).toFixed(1)} GB`);
1606
1691
 
1607
1692
  /** A statement's rows as a table, then what it read and wrote. Blobs show their size. */
1608
1693
  function printRows({ rows, read_row_count: readRowCount, written_row_count: writtenRowCount }) {
@@ -1690,6 +1775,7 @@ async function run({ command, values, flags, globalFlags, rest }) {
1690
1775
  else if (command === "own-servers") await ownServers(values, flags);
1691
1776
  else if (command === "links" || command.startsWith("links ")) await links(command, values, flags);
1692
1777
  else if (command === "secrets" || command.startsWith("secrets ")) await secrets(command, values);
1778
+ else if (command === "items" || command.startsWith("items ")) await items(command, values);
1693
1779
  else if (command === "kept-rooms" || command.startsWith("kept-rooms ")) await keptRooms(command, values);
1694
1780
  else if (command === "logs") await logs(values, flags);
1695
1781
  else if (command === "database" || command.startsWith("database ")) await database(command, values, flags);