@zaisma/cli 0.24.0 → 0.26.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/zaisma.mjs CHANGED
@@ -6,11 +6,13 @@ import { createHash } from "node:crypto";
6
6
  import { createReadStream, createWriteStream, readFileSync } from "node:fs";
7
7
  import { mkdir, mkdtemp, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
- import { dirname, extname, join, posix, relative, sep } from "node:path";
9
+ import { dirname, extname, join, posix, relative, resolve, sep } from "node:path";
10
10
  import { pipeline } from "node:stream/promises";
11
11
  import { createBrotliDecompress, createGunzip } from "node:zlib";
12
12
  import { CHECKED_TEXT_EXTENSIONS, GAME_FILE_EXTENSIONS, PRECOMPRESSED_EXTENSIONS, checkGameFiles, extensionOf, findOutsideReferences } from "./check.mjs";
13
13
  import { assetHeadSizes } from "./performance.mjs";
14
+ import { findChrome, openChrome } from "./chrome.mjs";
15
+ import { SHADER_CHECK_PAGE, SHADER_LIMITS, isShaderCheckPassing, shaderCheckPageExpressions, shaderDraftAnswer, shaderRenderFromPage, shaderRenderInputOf } from "./shader-check.mjs";
14
16
 
15
17
  const API = (process.env.ZAISMA_API || "https://zaisma.com").replace(/\/+$/, "");
16
18
  const KEY = process.env.ZAISMA_KEY || "";
@@ -38,8 +40,30 @@ const OUTSIDE_FOLDER = "zaisma-outside";
38
40
  /** Files database export and import read and write as SQLite databases; any other name is SQL text. */
39
41
  const SQLITE_EXTENSIONS = [".sqlite", ".sqlite3", ".db"];
40
42
 
43
+ /**
44
+ * A shader's folder (zaisma shader, and zaisma check on a folder with image.glsl): its passes, by file name (null is the image pass,
45
+ * otherwise the buffer's name), channels.json wiring each pass's iChannel0 to iChannel3, and the textures channels.json names. Nothing else.
46
+ */
47
+ const SHADER_PASS_FILES = { "image.glsl": null, "buffer-a.glsl": "a", "buffer-b.glsl": "b", "buffer-c.glsl": "c", "buffer-d.glsl": "d" };
48
+ const CHANNELS_FILE = "channels.json";
49
+ const TEXTURE_EXTENSIONS = ["png", "jpg", "jpeg", "webp"];
50
+ /** A channel in channels.json: the API's channel, with the texture named by its file in the folder (texture_file) instead of an image_id. */
51
+ const CHANNEL_FIELDS = ["channel_index", "input_kind", "buffer_name", "texture_file", "filter", "wrap"];
52
+ const CHANNELS_FILE_EXAMPLE = {
53
+ image: [
54
+ { channel_index: 0, input_kind: "buffer", buffer_name: "a" },
55
+ { channel_index: 1, input_kind: "texture", texture_file: "noise.png", filter: "linear", wrap: "repeat" },
56
+ ],
57
+ "buffer-a": [{ channel_index: 0, input_kind: "buffer", buffer_name: "a" }],
58
+ };
59
+ const CHANNELS_FIX = `Give channels.json as an object of passes ("image", "buffer-a" to "buffer-d"), each a list of up to 4 channels, like ${JSON.stringify(CHANNELS_FILE_EXAMPLE)}; filter linear or nearest, wrap clamp or repeat. zaisma help shows it.`;
60
+ /** How long shader and check wait for a texture image a person has to approve (image matching couldn't answer): 20 checks, 3 seconds apart; ZAISMA_SCAN_CHECK_INTERVAL_MS speeds it up in tests. */
61
+ const TEXTURE_CHECK_INTERVAL_MS = Number(process.env.ZAISMA_SCAN_CHECK_INTERVAL_MS) || 3000;
62
+ const TEXTURE_CHECK_COUNT = 20;
63
+
41
64
  /** The choices the API takes, checked before anything is sent (test/node/cli.test.ts holds them to the API's lists). */
42
65
  const VISIBILITIES = ["listed", "unlisted", "private", "draft"];
66
+ const SCREENS = ["wide", "phone"];
43
67
  const TOPIC_KINDS = ["bug", "gap", "feature", "question", "talk"];
44
68
  const MESSAGE_KINDS = ["bug", "gap", "feature", "question"];
45
69
  const FORUM_CATEGORIES = ["publishing", "scans", "pages", "rooms", "servers", "passes", "sdk", "saves", "stats", "mcp", "api", "cli", "accounts", "dashboard", "reports", "rules", "docs", "other"];
@@ -52,7 +76,7 @@ const EXIT_CODES = {
52
76
  held: { exitCode: 3, meaning: "upload: the version is held for a person at Zaisma to look at, usually within a day." },
53
77
  rejected: { exitCode: 4, meaning: "upload: the version was rejected. Its review_reason and findings say why and how to fix it." },
54
78
  still_scanning: { exitCode: 5, meaning: "upload: the version was still being scanned after 10 minutes. Check it later with zaisma versions <slug>." },
55
- problems_found: { exitCode: 6, meaning: "check: something in the game won't work on Zaisma as it is, and the upload command doesn't fix it. The problems say what and how to fix it." },
79
+ problems_found: { exitCode: 6, meaning: "check: something in the game won't work on Zaisma as it is, and the upload command doesn't fix it; or the shader doesn't compile, is too slow or flashes. The problems say what and how to fix it." },
56
80
  };
57
81
 
58
82
  /** The errors only the command itself answers with; every other code is the API's (ERROR_CODES in packages/core/src/errors.ts). */
@@ -68,12 +92,18 @@ const COMMAND_ERROR_CODES = {
68
92
  not_a_file: "The file given (of statements, a dump to import, or a save) can't be read.",
69
93
  file_exists: "database export won't write over a file that's already there.",
70
94
  folder_not_empty: "export saves only into a new or empty folder.",
71
- needs_newer_node: "Reading or writing a .sqlite file needs Node 22.13 or newer.",
95
+ needs_newer_node: "Reading or writing a .sqlite file needs Node 22.13 or newer, and drawing a shader in a local Chrome Node 22.",
72
96
  not_a_database: "The .sqlite file to import isn't a SQLite database.",
73
97
  unknown_link: "links remove: the game has no link by that name.",
74
98
  outside_file_unreachable: "upload: a file the game loads from an outside site couldn't be downloaded, so nothing was sent.",
75
99
  too_many_outside_files: "upload: the game loads more than 500 files from outside sites, so nothing was sent.",
76
100
  unpack_failed: "upload: a pre-compressed file couldn't be unpacked, so nothing was sent.",
101
+ no_image_pass: "shader: the folder has no image.glsl, the shader's image pass.",
102
+ unknown_shader_file: "A file in a shader's folder isn't one the command reads, or no channel in channels.json names it.",
103
+ bad_channels_file: "A shader's channels.json isn't JSON, or isn't an object of the folder's passes, each a list of channels.",
104
+ shader_texture_not_approved: "shader, check: a texture sent for the shader was rejected, or still waits for a person, so the shader wasn't sent.",
105
+ no_chrome: "check: there's no Chrome on this computer to draw the shader in, and no --game with ZAISMA_KEY to draw it on Zaisma.",
106
+ local_chrome_failed: "check: the Chrome on this computer couldn't draw the shader.",
77
107
  server_unreachable: "Zaisma couldn't be reached: no connection, or a wrong ZAISMA_API.",
78
108
  unexpected_answer: "Zaisma answered without JSON, like a page from a network in between.",
79
109
  };
@@ -91,9 +121,16 @@ const COMMANDS = {
91
121
  games: { about: "List your games", arguments: [], flags: {} },
92
122
  new: { about: "Make a game (it starts as a draft)", arguments: [{ name: "title", isRest: true }], flags: { slug: { hasValue: true, placeholder: "<slug>", about: "Its link name, as in zaisma.com/g/<slug>; made from the title if left out" } } },
93
123
  check: {
94
- about: "Check a game's folder for anything Zaisma refuses or that won't work on Zaisma, with how to fix each, before anything is sent; needs no key",
124
+ about:
125
+ "Check a game's folder for anything Zaisma refuses or that won't work on Zaisma, with how to fix each, before anything is sent; needs no key. " +
126
+ "On a shader's folder (one with image.glsl, below), draw it as Zaisma's check does, in the Chrome on this computer (CHROME_PATH, the system's, or one Playwright or @puppeteer/browsers downloaded), " +
127
+ "saving its sheet picture beside the folder; with no Chrome, on Zaisma with --game and ZAISMA_KEY (up to 100 a day)",
95
128
  arguments: [{ name: "folder" }],
96
- flags: { game: { hasValue: true, placeholder: "<slug>", about: "The game it's for, so the fixes name it (and, with ZAISMA_KEY set, so its own servers count)" } },
129
+ flags: {
130
+ game: { hasValue: true, placeholder: "<slug>", about: "The game it's for, so the fixes name it (and, with ZAISMA_KEY set, so its own servers count); for a shader's folder with no Chrome here, the game to draw it on Zaisma for" },
131
+ screen: { hasValue: true, choices: SCREENS, about: "A shader's folder only: the screen to draw it for, wide (desktops and tablets; the default) or phone" },
132
+ "draw-on-zaisma": { hasValue: false, about: "A shader's folder only: draw it on Zaisma's own renderer, with --game and ZAISMA_KEY, even when there's a Chrome here" },
133
+ },
97
134
  },
98
135
  upload: {
99
136
  about: "Upload a version; only changed files are sent. It runs the check first, and downloads files the game loads from outside sites and unpacks pre-compressed builds in what it sends, never in the folder",
@@ -105,6 +142,16 @@ const COMMANDS = {
105
142
  "match-update-mode": { hasValue: true, placeholder: "<next_match|now>", about: "With --publish-when-approved: when running matches get it: next_match (they finish on the version they started; the default) or now (every live match switches within seconds, in the same room)" },
106
143
  },
107
144
  },
145
+ shader: {
146
+ about:
147
+ "Send a shader for a game's background from its folder (below): each texture goes as an image of kind shader_texture (one the game has already, byte for byte, is used again) and is waited for, " +
148
+ "then the shader; Zaisma checks it in a minute or two, then set_background or the dashboard shows it",
149
+ arguments: [{ name: "folder" }],
150
+ flags: {
151
+ game: { hasValue: true, isRequired: true, placeholder: "<slug>", about: "The game it's for" },
152
+ screen: { hasValue: true, isRequired: true, choices: SCREENS, about: "wide (desktops and tablets) or phone (composed for a tall screen)" },
153
+ },
154
+ },
108
155
  versions: { about: "List a game's versions and preview links", arguments: [{ name: "slug" }], flags: {} },
109
156
  publish: {
110
157
  about: "Publish a version that passed, or roll back to an older one",
@@ -380,6 +427,20 @@ function parseCommandLine(argv) {
380
427
  return { command, values, flags, globalFlags, rest };
381
428
  }
382
429
 
430
+ /** A shader's folder, as zaisma shader and zaisma check read it. */
431
+ const SHADER_FOLDER_HELP = [
432
+ "A shader's folder (zaisma shader, zaisma check):",
433
+ " image.glsl The image pass, Shadertoy's form in WebGL2's GLSL: void mainImage(out vec4 fragColor, in vec2 fragCoord) { … }.",
434
+ " buffer-a.glsl … buffer-d.glsl Buffers, if any: each drawn to a picture kept between frames, a to d, before the image pass.",
435
+ " channels.json If any pass reads a channel: what each pass's iChannel0 to iChannel3 read, by pass (image, buffer-a … buffer-d).",
436
+ " Each channel is the API's, with the texture named by its file in the folder (texture_file) instead of an image_id:",
437
+ ` ${JSON.stringify(CHANNELS_FILE_EXAMPLE)}`,
438
+ " channel_index 0 to 3, each once in a pass; input_kind buffer (with buffer_name a to d, a buffer file in the folder) or texture (with texture_file);",
439
+ " filter linear (the default; a texture's with mipmaps) or nearest; wrap clamp (a buffer's default) or repeat (a texture's).",
440
+ ` *.png, *.jpg, *.webp The textures channels.json names: up to ${SHADER_LIMITS.maximumShaderTextureCount}, each up to ${SHADER_LIMITS.maximumTextureSizeBytes / 1048576} MB and ${SHADER_LIMITS.maximumTextureSidePx} px a side.`,
441
+ " Any other file, a texture no channel names, or a field channels.json doesn't take is refused before anything is sent; hidden files are left out.",
442
+ ];
443
+
383
444
  function helpText() {
384
445
  const lines = ["Usage:"];
385
446
  for (const command of Object.keys(COMMANDS)) {
@@ -392,6 +453,8 @@ function helpText() {
392
453
  "Every command takes --json: it prints the API's answer as-is (on failure, its { error }) and nothing else.",
393
454
  "Categories: " + FORUM_CATEGORIES.join(", ") + ".",
394
455
  "",
456
+ ...SHADER_FOLDER_HELP,
457
+ "",
395
458
  "Exit codes:",
396
459
  ...Object.values(EXIT_CODES).map((exit) => ` ${exit.exitCode} ${exit.meaning}`),
397
460
  "",
@@ -413,6 +476,13 @@ function helpAnswer() {
413
476
  flags: Object.entries(spec.flags).map(flagAnswer),
414
477
  })),
415
478
  global_flags: Object.entries(GLOBAL_FLAGS).map(flagAnswer),
479
+ shader_folder: {
480
+ pass_files: Object.keys(SHADER_PASS_FILES),
481
+ channels_file: CHANNELS_FILE,
482
+ channel_fields: CHANNEL_FIELDS,
483
+ channels_file_example: CHANNELS_FILE_EXAMPLE,
484
+ texture_extensions: TEXTURE_EXTENSIONS,
485
+ },
416
486
  exit_codes: Object.entries(EXIT_CODES).map(([name, exit]) => ({ exit_code: exit.exitCode, name, meaning: exit.meaning })),
417
487
  error_codes: Object.entries(COMMAND_ERROR_CODES).map(([code, meaning]) => ({ code, meaning })),
418
488
  };
@@ -525,6 +595,10 @@ function printSmallerNotes(notes) {
525
595
 
526
596
  /** zaisma check: the problems, or the answer with --json. Ends with problems_found when one isn't fixed by the upload command. */
527
597
  async function checkFolder({ folder }, flags) {
598
+ if ((await stat(join(folder, "image.glsl")).catch(() => null))?.isFile()) return checkShaderFolder(folder, flags);
599
+ for (const name of ["screen", "draw-on-zaisma"]) {
600
+ if (flags[name]) refuse("unknown_field", { message: `--${name} is only for a shader's folder, and ${folder} has no image.glsl.`, field: `--${name}`, fix: `Leave --${name} out to check a game's folder, or give a shader's folder (zaisma help shows one).` });
601
+ }
528
602
  const answer = await checkGame(await readGameFolder(folder), flags.game ?? null);
529
603
  const hasProblems = answer.problems.some((problem) => !problem.is_fixed_by_upload_command);
530
604
  if (isJson) printJson(answer);
@@ -541,6 +615,297 @@ async function checkFolder({ folder }, flags) {
541
615
  return hasProblems ? EXIT_CODES.problems_found : EXIT_CODES.done;
542
616
  }
543
617
 
618
+ // --- Shaders ------------------------------------------------------------------------------------------------------------------
619
+
620
+ const isPlainObject = (given) => typeof given === "object" && given !== null && !Array.isArray(given);
621
+ /** A texture's kind by its first bytes: PNG, JPEG or WebP, or null. */
622
+ const textureTypeOf = (bytes) =>
623
+ bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
624
+ ? "png"
625
+ : bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
626
+ ? "jpeg"
627
+ : String.fromCharCode(...bytes.subarray(0, 4)) === "RIFF" && String.fromCharCode(...bytes.subarray(8, 12)) === "WEBP"
628
+ ? "webp"
629
+ : null;
630
+
631
+ /**
632
+ * A shader's folder, read and checked closed before anything is sent or drawn: { manifest, textures }. The manifest is the API's shape
633
+ * with each texture channel naming its file (texture_file); textures are the files channels.json names, each { textureFile, bytes }.
634
+ */
635
+ async function readShaderFolder(folder) {
636
+ if (!(await stat(folder).catch(() => null))?.isDirectory()) refuse("not_a_folder", { message: `${folder} isn't a folder.`, field: "folder", fix: "Give the shader's folder, with its image.glsl at the top." });
637
+ const fileFix = (name) => `A shader's folder holds ${Object.keys(SHADER_PASS_FILES).join(", ")}, ${CHANNELS_FILE} and the textures it names (${TEXTURE_EXTENSIONS.map((extension) => `.${extension}`).join(", ")}); move ${name} out of it. zaisma help shows the folder.`;
638
+ const passSources = new Map();
639
+ const textureFiles = new Map();
640
+ let channelsText = null;
641
+ for (const entry of (await readdir(folder, { withFileTypes: true })).sort((first, second) => first.name.localeCompare(second.name))) {
642
+ if (JUNK.has(entry.name) || entry.name.startsWith(".")) continue;
643
+ const full = join(folder, entry.name);
644
+ if (!entry.isFile()) refuse("unknown_shader_file", { message: `${entry.name} is a folder; a shader's folder holds only its files.`, field: entry.name, fix: fileFix(entry.name) });
645
+ if (entry.name in SHADER_PASS_FILES) passSources.set(entry.name, await readFile(full, "utf8"));
646
+ else if (entry.name === CHANNELS_FILE) channelsText = await readFile(full, "utf8");
647
+ else if (TEXTURE_EXTENSIONS.includes(extensionOf(entry.name))) textureFiles.set(entry.name, full);
648
+ else refuse("unknown_shader_file", { message: `${entry.name} isn't a file a shader's folder holds.`, field: entry.name, fix: fileFix(entry.name) });
649
+ }
650
+ if (!passSources.has("image.glsl")) refuse("no_image_pass", { message: `${folder} has no image.glsl, the shader's image pass.`, field: "folder", fix: "Put the image pass in image.glsl: void mainImage(out vec4 fragColor, in vec2 fragCoord) { … }, Shadertoy's form in WebGL2's GLSL." });
651
+ for (const [fileName, source] of passSources) {
652
+ if (Buffer.byteLength(source) > SHADER_LIMITS.maximumPassSizeBytes) refuse("shader_too_big", { message: `${fileName} is over ${SHADER_LIMITS.maximumPassSizeBytes / 1024} KB.`, field: fileName, fix: "Take out unused functions and long comments, or move work into a buffer of its own (each pass gets 64 KB)." });
653
+ }
654
+
655
+ const bufferNames = Object.entries(SHADER_PASS_FILES).filter(([fileName, bufferName]) => bufferName && passSources.has(fileName)).map(([, bufferName]) => bufferName);
656
+ const passNames = ["image", ...bufferNames.map((bufferName) => `buffer-${bufferName}`)];
657
+ const channelsByPass = Object.fromEntries(passNames.map((passName) => [passName, []]));
658
+ if (channelsText !== null) {
659
+ let given;
660
+ try {
661
+ given = JSON.parse(channelsText);
662
+ } catch (error) {
663
+ refuse("bad_channels_file", { message: `${CHANNELS_FILE} isn't JSON: ${error.message}.`, field: CHANNELS_FILE, fix: CHANNELS_FIX });
664
+ }
665
+ if (!isPlainObject(given)) refuse("bad_channels_file", { message: `${CHANNELS_FILE} isn't a JSON object of passes.`, field: CHANNELS_FILE, fix: CHANNELS_FIX });
666
+ for (const [passName, givenChannels] of Object.entries(given)) {
667
+ const place = `${CHANNELS_FILE}: ${passName}`;
668
+ if (!passNames.includes(passName)) {
669
+ const isBufferName = /^buffer-[a-d]$/.test(passName);
670
+ refuse(isBufferName ? "bad_channels_file" : "unknown_field", {
671
+ message: isBufferName ? `${CHANNELS_FILE} wires ${passName}, and ${folder} has no ${passName}.glsl.` : `${JSON.stringify(passName)} in ${CHANNELS_FILE} isn't a pass.`,
672
+ field: place,
673
+ fix: `${CHANNELS_FILE} takes the folder's passes: ${passNames.join(", ")}.${isBufferName ? ` Add ${passName}.glsl, or take ${passName} out of ${CHANNELS_FILE}.` : ""}`,
674
+ });
675
+ }
676
+ if (!Array.isArray(givenChannels) || givenChannels.length > SHADER_LIMITS.maximumChannelCount) refuse("bad_channels_file", { message: `${place} isn't a list of up to ${SHADER_LIMITS.maximumChannelCount} channels.`, field: place, fix: CHANNELS_FIX });
677
+ for (const [channelIndex, givenChannel] of givenChannels.entries()) channelsByPass[passName].push(readChannel(givenChannel, `${place}[${channelIndex}]`, channelsByPass[passName], bufferNames, textureFiles));
678
+ }
679
+ }
680
+
681
+ const namedFiles = [...new Set(Object.values(channelsByPass).flatMap((channels) => channels.map((channel) => channel.texture_file).filter(Boolean)))];
682
+ const unnamedFile = [...textureFiles.keys()].find((name) => !namedFiles.includes(name));
683
+ if (unnamedFile) refuse("unknown_shader_file", { message: `No channel in ${CHANNELS_FILE} reads ${unnamedFile}.`, field: unnamedFile, fix: `Name it as a channel's texture_file in ${CHANNELS_FILE}, or move it out of the folder.` });
684
+ if (namedFiles.length > SHADER_LIMITS.maximumShaderTextureCount) {
685
+ refuse("too_many_shader_textures", { message: `${CHANNELS_FILE} names ${namedFiles.length} textures; a shader reads up to ${SHADER_LIMITS.maximumShaderTextureCount}.`, field: CHANNELS_FILE, fix: "Name at most 4 different textures across the image pass and its buffers; several channels can read the same one." });
686
+ }
687
+ const textures = [];
688
+ for (const textureFile of namedFiles) {
689
+ const bytes = new Uint8Array(await readFile(textureFiles.get(textureFile)));
690
+ if (bytes.length > SHADER_LIMITS.maximumTextureSizeBytes) refuse("shader_texture_too_big", { message: `${textureFile} is over ${SHADER_LIMITS.maximumTextureSizeBytes / 1048576} MB.`, field: textureFile, fix: "Save it smaller (a JPEG or WebP, or fewer pixels; a shader samples it with mipmaps)." });
691
+ if (!textureTypeOf(bytes)) refuse("not_an_image", { message: `${textureFile} isn't a PNG, JPEG or WebP image.`, field: textureFile, fix: "Save it as a PNG, JPEG or WebP file." });
692
+ textures.push({ textureFile, bytes });
693
+ }
694
+ const passOf = (passName, fileName) => ({ source: passSources.get(fileName), channels: channelsByPass[passName] });
695
+ return {
696
+ manifest: { image: passOf("image", "image.glsl"), buffers: bufferNames.map((bufferName) => ({ buffer_name: bufferName, ...passOf(`buffer-${bufferName}`, `buffer-${bufferName}.glsl`) })) },
697
+ textures,
698
+ };
699
+ }
700
+
701
+ /** One channel of channels.json, checked closed, with the API's defaults filled in: filter linear, wrap repeat for a texture and clamp for a buffer. */
702
+ function readChannel(given, place, earlier, bufferNames, textureFiles) {
703
+ const bad = (field, message) => refuse("bad_shader_channel", { message, field, fix: CHANNELS_FIX });
704
+ if (!isPlainObject(given)) bad(place, `${place} isn't an object.`);
705
+ const unknown = Object.keys(given).find((key) => !CHANNEL_FIELDS.includes(key));
706
+ if (unknown !== undefined) {
707
+ refuse("unknown_field", { message: `${unknown} isn't a field of a channel in ${CHANNELS_FILE}.`, field: `${place}.${unknown}`, fix: `${unknown === "image_id" ? "In a folder, a texture channel names its file: texture_file. " : ""}Leave it out. A channel takes: ${CHANNEL_FIELDS.join(", ")}.` });
708
+ }
709
+ const { channel_index: channelIndex, input_kind: inputKind } = given;
710
+ if (!Number.isInteger(channelIndex) || channelIndex < 0 || channelIndex >= SHADER_LIMITS.maximumChannelCount) bad(`${place}.channel_index`, `${place}.channel_index isn't 0, 1, 2 or 3.`);
711
+ if (earlier.some((channel) => channel.channel_index === channelIndex)) bad(`${place}.channel_index`, `${place.replace(/\[\d+\]$/, "")} has channel_index ${channelIndex} twice.`);
712
+ if (inputKind !== "buffer" && inputKind !== "texture") bad(`${place}.input_kind`, `${place}.input_kind ${JSON.stringify(inputKind ?? null)} isn't buffer or texture.`);
713
+ const bufferName = given.buffer_name ?? null;
714
+ const textureFile = given.texture_file ?? null;
715
+ if (inputKind === "buffer") {
716
+ if (!bufferNames.includes(bufferName)) {
717
+ bad(`${place}.buffer_name`, bufferName === null ? `${place} reads a buffer but names none.` : `${place} reads buffer ${JSON.stringify(bufferName)}, and the folder has no buffer-${bufferName}.glsl${bufferNames.length ? ` (it has ${bufferNames.map((name) => `buffer-${name}.glsl`).join(", ")})` : ""}.`);
718
+ }
719
+ if (textureFile !== null) bad(`${place}.texture_file`, `${place} reads a buffer, so it takes no texture_file.`);
720
+ } else {
721
+ if (typeof textureFile !== "string" || !textureFiles.has(textureFile)) bad(`${place}.texture_file`, textureFile === null ? `${place} reads a texture but names no texture_file.` : `${place} reads ${JSON.stringify(textureFile)}, which isn't a texture in the folder.`);
722
+ if (bufferName !== null) bad(`${place}.buffer_name`, `${place} reads a texture, so it takes no buffer_name.`);
723
+ }
724
+ const filter = given.filter ?? "linear";
725
+ if (filter !== "linear" && filter !== "nearest") bad(`${place}.filter`, `${place}.filter ${JSON.stringify(filter)} isn't linear or nearest.`);
726
+ const wrap = given.wrap ?? (inputKind === "texture" ? "repeat" : "clamp");
727
+ if (wrap !== "clamp" && wrap !== "repeat") bad(`${place}.wrap`, `${place}.wrap ${JSON.stringify(wrap)} isn't clamp or repeat.`);
728
+ return { channel_index: channelIndex, input_kind: inputKind, buffer_name: inputKind === "buffer" ? bufferName : null, texture_file: inputKind === "texture" ? textureFile : null, filter, wrap };
729
+ }
730
+
731
+ /** The folder's manifest as the API takes it: each texture channel naming its image (imageIdOf its file) instead of its file. */
732
+ function manifestWithImageIds(manifest, imageIdOf) {
733
+ const passWith = (pass) => ({ ...pass, channels: pass.channels.map(({ texture_file: textureFile, ...channel }) => ({ ...channel, image_id: textureFile === null ? null : imageIdOf(textureFile) })) });
734
+ return { image: passWith(manifest.image), buffers: manifest.buffers.map(passWith) };
735
+ }
736
+
737
+ /**
738
+ * Sends each texture as an image of kind shader_texture, or uses an approved one the game has with the same bytes, and waits until each
739
+ * is approved (at once, unless image matching couldn't check it and a person looks). Answers each { texture_file, image_id, added_image },
740
+ * added_image being the API's answer as-is, or null for one used again.
741
+ */
742
+ async function sendTextures(slug, textures) {
743
+ if (!textures.length) return [];
744
+ const { images } = await api("GET", `/games/${slug}`);
745
+ const textureImages = [];
746
+ for (const texture of textures) {
747
+ const textureHash = sha256Of(texture.bytes);
748
+ let imageId = null;
749
+ for (const image of images.filter((candidate) => candidate.kind === "shader_texture" && candidate.review_status === "approved" && candidate.size_bytes === texture.bytes.length)) {
750
+ const stored = await fetch(image.image_url).then((response) => (response.ok ? response.arrayBuffer() : null)).catch(() => null);
751
+ if (stored && sha256Of(new Uint8Array(stored)) === textureHash) {
752
+ imageId = image.id;
753
+ break;
754
+ }
755
+ }
756
+ if (imageId) {
757
+ say(`Using ${texture.textureFile}: the game has it already (${imageId}).`);
758
+ textureImages.push({ texture_file: texture.textureFile, image_id: imageId, added_image: null });
759
+ continue;
760
+ }
761
+ say(`Sending ${texture.textureFile} (${readableSize(texture.bytes.length)})…`);
762
+ const added = await api("POST", `/games/${slug}/images?kind=shader_texture`, texture.bytes);
763
+ textureImages.push({ texture_file: texture.textureFile, image_id: added.image.id, added_image: added });
764
+ }
765
+ let waiting = textureImages.filter((textureImage) => textureImage.added_image && textureImage.added_image.image.review_status !== "approved");
766
+ if (waiting.length) say("Image matching couldn't check a texture just now, so a person at Zaisma looks; waiting a minute…");
767
+ for (let i = 0; i < TEXTURE_CHECK_COUNT && waiting.length; i++) {
768
+ await sleep(TEXTURE_CHECK_INTERVAL_MS);
769
+ const { images: checked } = await api("GET", `/games/${slug}`);
770
+ const statusOf = (textureImage) => checked.find((image) => image.id === textureImage.image_id)?.review_status ?? "rejected";
771
+ const rejected = waiting.find((textureImage) => statusOf(textureImage) === "rejected");
772
+ if (rejected) refuse("shader_texture_not_approved", { message: `${rejected.texture_file} (${rejected.image_id}) was rejected, so the shader wasn't sent.`, field: rejected.texture_file, fix: "The game's images (get_game) give its review_reason; use another texture." }, EXIT_CODES.failed);
773
+ waiting = waiting.filter((textureImage) => statusOf(textureImage) !== "approved");
774
+ }
775
+ if (waiting.length) {
776
+ refuse(
777
+ "shader_texture_not_approved",
778
+ { message: `${waiting[0].texture_file} (${waiting[0].image_id}) waits for a person at Zaisma, usually within a day, so the shader wasn't sent.`, field: waiting[0].texture_file, fix: "Run the same command again once the game's images (get_game) show it approved: it's used then, not sent again." },
779
+ EXIT_CODES.failed,
780
+ );
781
+ }
782
+ return textureImages;
783
+ }
784
+
785
+ /** zaisma shader: sends the folder's textures, then the shader. With --json, { texture_images, added_shader }: the API's answers as-is. */
786
+ async function sendShader({ folder }, flags) {
787
+ const { manifest, textures } = await readShaderFolder(folder);
788
+ const textureImages = await sendTextures(flags.game, textures);
789
+ const imageIds = new Map(textureImages.map((textureImage) => [textureImage.texture_file, textureImage.image_id]));
790
+ const answer = await api("POST", `/games/${flags.game}/shaders`, { screen: flags.screen, ...manifestWithImageIds(manifest, (textureFile) => imageIds.get(textureFile)) });
791
+ if (isJson) return printAnswer({ texture_images: textureImages, added_shader: answer });
792
+ console.log(`Sent ${answer.shader.id} for ${answer.shader.screen}: ${answer.shader.review_status}.`);
793
+ if (answer.review_message) console.log(answer.review_message);
794
+ return EXIT_CODES.done;
795
+ }
796
+
797
+ /** Draws the shader as Zaisma's check does, in a headless Chrome on this computer, from the check's own page (shader-check.mjs). */
798
+ async function drawInChrome(chromePath, manifest, textures, screen) {
799
+ const input = shaderRenderInputOf(manifestWithImageIds(manifest, (textureFile) => textureFile), screen, textures.map((texture) => ({ imageId: texture.textureFile, bytes: texture.bytes })), true);
800
+ const { textureExpressions, checkExpression } = shaderCheckPageExpressions(input);
801
+ const failed = (error) => refuse("local_chrome_failed", { message: `Chrome on this computer couldn't draw the shader: ${error.message}`, field: process.env.CHROME_PATH ? "CHROME_PATH" : null, fix: "Set CHROME_PATH to another Chrome or Chromium; or give --game <slug> with ZAISMA_KEY set, and it's drawn on Zaisma instead." }, EXIT_CODES.failed);
802
+ say(`Drawing it for ${screen} as Zaisma's check does, in Chrome on this computer; this takes a minute or two…`);
803
+ let chrome;
804
+ try {
805
+ chrome = await openChrome(chromePath, "zaisma-shader-check-");
806
+ } catch (error) {
807
+ failed(error);
808
+ }
809
+ let timer;
810
+ try {
811
+ const { targetId } = await chrome.send("Target.createTarget", { url: "about:blank" });
812
+ const { sessionId } = await chrome.send("Target.attachToTarget", { targetId, flatten: true });
813
+ const send = (method, parameters) => chrome.send(method, parameters, sessionId);
814
+ // Nothing the check page asks for leaves it.
815
+ chrome.listen(sessionId, (method, parameters) => method === "Fetch.requestPaused" && send("Fetch.failRequest", { requestId: parameters.requestId, errorReason: "BlockedByClient" }).catch(() => {}));
816
+ await send("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
817
+ const { frameTree } = await send("Page.getFrameTree");
818
+ await send("Page.setDocumentContent", { frameId: frameTree.frame.id, html: SHADER_CHECK_PAGE });
819
+ const evaluate = async (expression) => {
820
+ const { result: evaluated, exceptionDetails } = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
821
+ if (exceptionDetails) throw new Error(exceptionDetails.exception?.description?.split("\n")[0] ?? exceptionDetails.text);
822
+ return evaluated.value;
823
+ };
824
+ for (const expression of textureExpressions) await evaluate(expression);
825
+ const outOfTime = new Promise((resolve) => (timer = setTimeout(() => resolve(null), SHADER_LIMITS.checkTimeoutSec * 1000)));
826
+ const render = shaderRenderFromPage(await Promise.race([evaluate(checkExpression), outOfTime]), input);
827
+ return { rendererKind: "local_chrome", shaderCheck: await shaderDraftAnswer(render, screen), remainingShaderCheckCount: null, sheetPng: render.sheetPng, textureImages: [] };
828
+ } catch (error) {
829
+ if (error instanceof CommandError) throw error;
830
+ failed(error);
831
+ } finally {
832
+ clearTimeout(timer);
833
+ await chrome.close();
834
+ }
835
+ }
836
+
837
+ /** Draws the shader on Zaisma, as a check before sending (POST /games/:slug/shader-checks), after sending its textures; downloads its sheet. */
838
+ async function drawOnZaisma(slug, manifest, textures, screen) {
839
+ const textureImages = await sendTextures(slug, textures);
840
+ const imageIds = new Map(textureImages.map((textureImage) => [textureImage.texture_file, textureImage.image_id]));
841
+ say(`Drawing it for ${screen} on Zaisma; this takes a minute or two…`);
842
+ const answer = await api("POST", `/games/${slug}/shader-checks`, { screen, ...manifestWithImageIds(manifest, (textureFile) => imageIds.get(textureFile)) });
843
+ let sheetPng = null;
844
+ if (answer.shader_check.sheet_url) {
845
+ const response = await fetch(answer.shader_check.sheet_url).catch(() => null);
846
+ if (response?.ok) sheetPng = new Uint8Array(await response.arrayBuffer());
847
+ }
848
+ return { rendererKind: "zaisma", shaderCheck: answer.shader_check, remainingShaderCheckCount: answer.remaining_shader_check_count, sheetPng, textureImages };
849
+ }
850
+
851
+ /**
852
+ * zaisma check on a shader's folder: drawn in Chrome on this computer when there is one, otherwise on Zaisma (--game and ZAISMA_KEY),
853
+ * with its sheet saved beside the folder. Ends with problems_found when it doesn't compile, is too slow at a level or flashes; its notes
854
+ * never change the exit code. --json prints { renderer_kind, shader_check, remaining_shader_check_count, sheet_file, texture_images }.
855
+ */
856
+ async function checkShaderFolder(folder, flags) {
857
+ if (flags["draw-on-zaisma"] && !flags.game) refuse("missing_field", { message: "--draw-on-zaisma needs --game: the game to draw it for.", field: "--game", fix: `Run it as: zaisma check ${folder} --game <slug> --draw-on-zaisma, with ZAISMA_KEY set.` });
858
+ const { manifest, textures } = await readShaderFolder(folder);
859
+ const screen = flags.screen ?? "wide";
860
+ const canDrawOnZaisma = Boolean(flags.game && KEY);
861
+ const hasWebSocket = typeof globalThis.WebSocket === "function";
862
+ const chromePath = flags["draw-on-zaisma"] ? null : findChrome([join(process.cwd(), ".wrangler/chrome"), join(process.cwd(), "chrome")]);
863
+ let drawn = null;
864
+ if (chromePath && hasWebSocket) {
865
+ try {
866
+ drawn = await drawInChrome(chromePath, manifest, textures, screen);
867
+ } catch (error) {
868
+ if (!(error instanceof CommandError && error.error.code === "local_chrome_failed" && canDrawOnZaisma)) throw error;
869
+ say(`${error.error.message} Drawing it on Zaisma instead.`);
870
+ }
871
+ } else if (!canDrawOnZaisma && !flags["draw-on-zaisma"]) {
872
+ if (chromePath) refuse("needs_newer_node", { message: `Drawing a shader in Chrome on this computer needs Node 22 or newer; this is ${process.version}.`, field: null, fix: "Run it with Node 22 or newer; or give --game <slug> with ZAISMA_KEY set to draw it on Zaisma." }, EXIT_CODES.failed);
873
+ refuse("no_chrome", { message: "There's no Chrome on this computer to draw the shader in.", field: "--game", fix: "Install Chrome, or set CHROME_PATH to a Chrome or Chromium; or give --game <slug> with ZAISMA_KEY set to draw it on Zaisma (up to 100 checks a day)." }, EXIT_CODES.failed);
874
+ }
875
+ drawn ??= await drawOnZaisma(flags.game, manifest, textures, screen);
876
+ const sheetPath = drawn.sheetPng ? `${resolve(folder)}-${screen}-check.png` : null;
877
+ if (sheetPath) await writeFile(sheetPath, drawn.sheetPng);
878
+ const sheetFile = sheetPath ? relative(process.cwd(), sheetPath) || sheetPath : null;
879
+ const isPassing = isShaderCheckPassing(drawn.shaderCheck);
880
+ if (isJson) printJson({ renderer_kind: drawn.rendererKind, shader_check: drawn.shaderCheck, remaining_shader_check_count: drawn.remainingShaderCheckCount, sheet_file: sheetFile, texture_images: drawn.textureImages });
881
+ else printShaderCheck(drawn, { folder, screen, sheetFile, slug: flags.game ?? null, isPassing });
882
+ return isPassing ? EXIT_CODES.done : EXIT_CODES.problems_found;
883
+ }
884
+
885
+ /** A shader check for people: what it measured against each limit, the glass, the notes and where its sheet is. */
886
+ function printShaderCheck({ rendererKind, shaderCheck, remainingShaderCheckCount }, { folder, screen, sheetFile, slug, isPassing }) {
887
+ console.log(rendererKind === "local_chrome" ? `Drawn for ${screen} in Chrome on this computer, in software, as Zaisma's check draws it.` : `Drawn for ${screen} on Zaisma (${remainingShaderCheckCount} checks left today).`);
888
+ if (shaderCheck.compile_error) {
889
+ console.log(` ${shaderCheck.compile_error} [shader_does_not_compile]\n Line numbers are the pass's own.`);
890
+ } else {
891
+ const levelCount = shaderCheck.quality_checks.length;
892
+ for (const qualityCheck of shaderCheck.quality_checks) {
893
+ const isTooSlow = qualityCheck.check_frame_ms > qualityCheck.maximum_check_frame_ms;
894
+ console.log(` ${levelCount > 1 ? `Quality ${qualityCheck.quality_level}` : "A frame"}: ${qualityCheck.check_frame_ms} ms in the check; the most is ${qualityCheck.maximum_check_frame_ms}${isTooSlow ? ". Too slow [shader_too_slow]" : "."}`);
895
+ }
896
+ if (shaderCheck.quality_checks.some((qualityCheck) => qualityCheck.check_frame_ms > qualityCheck.maximum_check_frame_ms)) console.log(" Fix: draw less (fewer steps, octaves or lights), or less where iQuality is lower.");
897
+ if (shaderCheck.flash_count !== null) {
898
+ const isFlashing = shaderCheck.flash_count > SHADER_LIMITS.maximumFlashCountPerSec;
899
+ console.log(` Flashes: at most ${shaderCheck.flash_count} in a second; the most is ${SHADER_LIMITS.maximumFlashCountPerSec}${isFlashing ? ". Too many [shader_flashes]: flashing can cause seizures; change brightness slowly." : "."}`);
900
+ }
901
+ if (shaderCheck.is_glass_smoked !== null) console.log(` The glass over it: ${shaderCheck.is_glass_smoked ? "smoked" : "light"}, tinted ${shaderCheck.glass_tint_pct}%.`);
902
+ }
903
+ for (const note of shaderCheck.notes) console.log(` · ${note.message} Fix: ${note.fix} [${note.code}]`);
904
+ if (sheetFile) console.log(`The sheet (wide and phone under Zaisma's glass, small, what changes between frames, and its pixels close up): ${sheetFile}`);
905
+ else if (shaderCheck.sheet_url) console.log(`The sheet, for a day: ${shaderCheck.sheet_url}`);
906
+ console.log(isPassing ? `Ready to send: zaisma shader ${folder} --game ${slug ?? "<slug>"} --screen ${screen}` : "Fix what's above, then check again.");
907
+ }
908
+
544
909
  const sha256Of = (text) => createHash("sha256").update(text).digest("hex");
545
910
  const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
546
911
  /** A path's file kind for findOutsideReferences, or null when its text isn't read. */
@@ -758,12 +1123,15 @@ async function upload({ folder }, flags) {
758
1123
  const slug = flags.game;
759
1124
  const gameFolder = await readGameFolder(folder);
760
1125
  const { problems } = await checkGame(gameFolder, slug);
761
- const refused = problems.find((problem) => problem.problem_kind === "refused" && !problem.is_fixed_by_upload_command);
1126
+ // The size limit depends on the developer's plan (Zaisma Pro allows more), which only the server knows: it answers game_too_big itself.
1127
+ const refused = problems.find((problem) => problem.problem_kind === "refused" && !problem.is_fixed_by_upload_command && problem.code !== "game_too_big");
762
1128
  if (refused) {
763
1129
  printProblems(problems, PROBLEM_GROUPS.slice(0, 2));
764
1130
  throw new CommandError({ code: refused.code, message: refused.message, field: "folder", fix: refused.fix, retry_after_sec: null }, EXIT_CODES.failed.exitCode);
765
1131
  }
766
1132
  printProblems(problems, PROBLEM_GROUPS.slice(1, 2));
1133
+ const tooBig = problems.find((problem) => problem.code === "game_too_big");
1134
+ if (tooBig) say(`${tooBig.message} Uploading anyway: Zaisma checks it against your plan.`);
767
1135
  if (gameFolder.hiddenPaths.length) say(`Leaving out hidden files: ${gameFolder.hiddenPaths.slice(0, 5).join(", ")}${gameFolder.hiddenPaths.length > 5 ? "…" : ""}`);
768
1136
 
769
1137
  const fixed = await fixUpload(gameFolder.files);
@@ -1734,6 +2102,7 @@ async function run({ command, values, flags, globalFlags, rest }) {
1734
2102
  if (command === "check") return checkFolder(values, flags);
1735
2103
  if (command === "export") return exportGame(values, flags);
1736
2104
  if (command === "upload") return upload(values, flags);
2105
+ if (command === "shader") return sendShader(values, flags);
1737
2106
  if (command === "versions") {
1738
2107
  const answer = await api("GET", `/games/${values.slug}`);
1739
2108
  if (isJson) return printAnswer(answer);