@gameslate/sdk 0.3.6 → 0.3.8

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/README.md CHANGED
@@ -17,6 +17,11 @@ runs the plugin in a QuickJS sandbox, validates everything it returns, and owns
17
17
  | `gameslate-plugin init` | Scaffolds a new plugin repository: an example plugin, a test in the core's sandbox, CI |
18
18
  | `gameslate-plugin build` | Builds a plugin folder into what the core loads |
19
19
  | `gameslate-plugin validate` | Checks a built plugin exactly as the core does: manifest, contract, hashes, and its code loaded in the sandbox |
20
+ | `gameslate-plugin verify` | Runs the game to a known moment (an emulator save state) and checks what a local GameSlate daemon reports, plus the emulator's own memory reads, against a `verify.json` |
21
+ | `gameslate-plugin addresses` | A game's address table from its decompilation: globals from its symbol maps (less a revision delta when it builds another revision), struct offsets, sizes and constants from a clang probe of its headers |
22
+
23
+ New plugin repos also get two agent skills in `.claude/skills/`: `build-gameslate-plugin` (from
24
+ choosing a state source to release) and `verify-gameslate-plugin`.
20
25
 
21
26
  ## Start a plugin
22
27
 
@@ -56,4 +61,36 @@ validates it and writes every file.
56
61
 
57
62
  `0.3.x` speaks plugin contract (`sdkApi`) 3: new 0.3 versions add tools, never change the contract. The core refuses a plugin built for another contract.
58
63
 
64
+ - **0.3.8:** `verify.json` `steps` drive an emulator to its moment through GameSlate's
65
+ `gameslate drive`, with any `emulator` command:
66
+ - `press` once, until a check matches, or taking turns between keys;
67
+ - `waitFor` a check;
68
+ - `waitMs`;
69
+ - `frame`.
70
+
71
+ A check is a peeked value or the plugin's own state, and `times` requires that many matching
72
+ reads in a row.
73
+
74
+ Also in 0.3.8:
75
+ - `gameslate-plugin addresses <spec.json>`: a decomp's addresses, offsets and sizes as a
76
+ TypeScript table that names its sources;
77
+ - `verify.json`'s `ui` screenshots each of the app's tabs (Map, Inventory, Missions, Ref) at a
78
+ phone's width, or the tabs you list;
79
+ - a live plugin that broke a sandbox limit gets a fresh runtime for its next session (at most
80
+ 3 times an hour);
81
+ - `new PluginSandbox(quickJs, code, name, { log })` now takes its log in an options object.
82
+ The plugin contract is unchanged.
83
+ - **0.3.7:**
84
+ - image outputs carry a `purpose` (atlas, map, icon, actor) and an `encoding` (PNG or WebP);
85
+ - asset extractors can be up to 10 minutes per asset, and run across builder threads;
86
+ - manifest games take `aliases`, and inputs take `subfolders` (a port's `mods/`), named
87
+ relative to the picked folder;
88
+ - offered folders can't be hidden folders except where games live (`~/.var/app`,
89
+ `~/.local/share`, `~/.steam`);
90
+ - `afterAssets` steps replace `pythonExtract` (deprecated);
91
+ - `raToGuest` / `guestToRa` translate RetroAchievements' N64 addresses;
92
+ - `gameslate-plugin verify`, and the two agent skills in the template;
93
+ - a plugin's sandbox refuses a build none of its sources verified, instead of using the first
94
+ source.
95
+
59
96
  MIT licensed.
@@ -13,6 +13,12 @@ import { initPlugin } from '../build/init-plugin.mjs';
13
13
  * gameslate-plugin validate <builtDir> [--core-version <version>]
14
14
  * Checks a built plugin exactly as the core does before running it: manifest, contract,
15
15
  * hashes, then its live and asset code loaded in the core's own sandbox.
16
+ * gameslate-plugin verify <verify.json>
17
+ * Runs the game to a known moment (RetroArch on a save state) and checks what a local
18
+ * GameSlate daemon reports, and the emulator's own memory reads, against the file.
19
+ * gameslate-plugin addresses <spec.json> [--out <file.ts>]
20
+ * A game's address table from its decompilation: symbols from its maps, struct offsets,
21
+ * sizes and constants from a clang probe against its headers (src/host/addresses.ts).
16
22
  */
17
23
  const { values, positionals } = parseArgs({
18
24
  options: {
@@ -29,6 +35,8 @@ const USAGE = [
29
35
  'usage: gameslate-plugin init <dir> --id <id> [--name <name>]',
30
36
  ' gameslate-plugin build <pluginDir> --out <dir> [--tested-with <version>]',
31
37
  ' gameslate-plugin validate <builtDir> [--core-version <version>]',
38
+ ' gameslate-plugin verify <verify.json>',
39
+ ' gameslate-plugin addresses <spec.json> [--out <file.ts>]',
32
40
  ].join('\n');
33
41
 
34
42
  async function validate(builtDir) {
@@ -76,6 +84,73 @@ if (command === 'build' && dir && values.out) {
76
84
  const problems = await validate(path.resolve(dir));
77
85
  for (const p of problems) console.error(`refused: ${p}`);
78
86
  process.exit(problems.length ? 1 : 0);
87
+ } else if (command === 'verify' && dir) {
88
+ const { expandEnv, runVerify, VerifySpecSchema } = await import('../lib/host/index.js');
89
+ const { verifyEffects } = await import('../build/verify-effects.mjs');
90
+ const file = path.resolve(dir);
91
+ const spec = VerifySpecSchema.parse(
92
+ expandEnv(JSON.parse(fs.readFileSync(file, 'utf8')), process.env),
93
+ );
94
+ const result = await runVerify(spec, verifyEffects(path.dirname(file)));
95
+ console.log(result.ok ? `${spec.game}: verified` : `${spec.game}: NOT verified`);
96
+ for (const p of result.problems) console.log(` ${p}`);
97
+ for (const s of result.screenshots) console.log(` screenshot: ${s}`);
98
+ process.exit(result.ok ? 0 : 1);
99
+ } else if (command === 'addresses' && dir) {
100
+ const { addressModule, AddressSpecSchema, buildAddressTable, expandEnv } =
101
+ await import('../lib/host/index.js');
102
+ const { execFileSync } = await import('node:child_process');
103
+ const os = await import('node:os');
104
+ const specFile = path.resolve(dir);
105
+ const spec = AddressSpecSchema.parse(
106
+ expandEnv(JSON.parse(fs.readFileSync(specFile, 'utf8')), process.env),
107
+ );
108
+ const decomp = path.resolve(path.dirname(specFile), spec.decomp);
109
+ const table = buildAddressTable(spec, {
110
+ read: file => fs.readFileSync(path.join(decomp, file), 'utf8'),
111
+ compile: source => {
112
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gs-probe-'));
113
+ const probe = path.join(dir, 'probe.c');
114
+ fs.writeFileSync(probe, source);
115
+ const stubs = path.join(dir, 'stubs');
116
+ for (const h of spec.stubHeaders) {
117
+ fs.mkdirSync(path.dirname(path.join(stubs, h)), { recursive: true });
118
+ fs.writeFileSync(
119
+ path.join(stubs, h),
120
+ '/* stub: generated by the decomp build */\n',
121
+ );
122
+ }
123
+ /* after the decomp's own include paths: a real header wins over a stub */
124
+ const args = [
125
+ ...spec.clang.args,
126
+ ...(spec.stubHeaders.length ? ['-idirafter', stubs] : []),
127
+ ];
128
+ return execFileSync(spec.clang.binary, [...args, '-S', '-o', '-', probe], {
129
+ cwd: decomp,
130
+ encoding: 'utf8',
131
+ maxBuffer: 64 * 1024 * 1024,
132
+ });
133
+ },
134
+ });
135
+ const commit = (() => {
136
+ try {
137
+ return execFileSync('git', ['-C', decomp, 'rev-parse', '--short', 'HEAD'], {
138
+ encoding: 'utf8',
139
+ }).trim();
140
+ } catch {
141
+ return 'not a git checkout';
142
+ }
143
+ })();
144
+ const provenance = [
145
+ `Addresses from the ${path.basename(decomp)} decompilation (commit ${commit}), by`,
146
+ `gameslate-plugin addresses ${path.basename(specFile)}:`,
147
+ `- symbols from ${spec.symbolFiles.join(', ')}${spec.subtract ? `, less 0x${spec.subtract.toString(16)} (another revision)` : ''};`,
148
+ `- offsets, sizes and constants from a probe of ${spec.includes.join(', ') || 'no headers'},`,
149
+ ` compiled by ${spec.clang.binary} ${spec.clang.args.filter(a => !a.startsWith('-I')).join(' ')}.`,
150
+ ].join('\n');
151
+ const text = addressModule(table, provenance);
152
+ if (values.out) fs.writeFileSync(path.resolve(values.out), text);
153
+ else process.stdout.write(text);
79
154
  } else {
80
155
  console.error(USAGE);
81
156
  process.exit(1);
@@ -13,6 +13,8 @@ const ID = /^[a-z0-9][a-z0-9-]*$/;
13
13
  const DOTFILES = new Map([
14
14
  ['gitignore', '.gitignore'],
15
15
  ['github', '.github'],
16
+ /* the agent skills for building and verifying the plugin */
17
+ ['claude', '.claude'],
16
18
  ]);
17
19
 
18
20
  function copy(from, to, fill) {
@@ -0,0 +1,188 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import dgram from 'node:dgram';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ /*
7
+ * The real effects of `gameslate-plugin verify` (src/host/verify.ts has the steps and their
8
+ * tests): RetroArch started on a save state, its network commands over UDP, the daemon's state
9
+ * over its WebSocket, and screenshots (RetroArch's own; the GameSlate page through Playwright
10
+ * when it's installed).
11
+ */
12
+
13
+ const STARTUP_MS = 3000;
14
+ const COMMAND_TIMEOUT_MS = 2000;
15
+
16
+ /** @param {string} specDir paths in the spec are relative to it */
17
+ export function verifyEffects(specDir, log = line => console.error(line)) {
18
+ const at = p => path.resolve(specDir, p);
19
+ return {
20
+ launch: spec =>
21
+ spec.emulator ? launchEmulator(spec, at, log) : launchRetroArch(spec, at, log),
22
+ drive: (spec, args) => drive(spec, at, args),
23
+ wait: ms => new Promise(resolve => setTimeout(resolve, ms)),
24
+ state: spec => nextState(spec),
25
+ command: (spec, line) => retroArchCommand(spec.retroarch?.port ?? 55355, line),
26
+ screenshots: spec => screenshots(spec, at, log),
27
+ };
28
+ }
29
+
30
+ /* a started process, once it has run STARTUP_MS without exiting */
31
+ function started(child, stop) {
32
+ return new Promise((resolve, reject) => {
33
+ child.once('error', reject);
34
+ child.once('exit', code =>
35
+ reject(new Error(`the emulator exited (${code}) while starting`)),
36
+ );
37
+ setTimeout(() => {
38
+ child.removeAllListeners('exit');
39
+ resolve(stop);
40
+ }, STARTUP_MS);
41
+ });
42
+ }
43
+
44
+ /* The emulator's own pid: the child, or the launch wrapper's child when there's a prefix. */
45
+ function emulatorPid(child, wrapped) {
46
+ if (!wrapped) return child.pid;
47
+ const children = `/proc/${child.pid}/task/${child.pid}/children`;
48
+ const pid = Number(fs.readFileSync(children, 'utf8').trim().split(/\s+/)[0]);
49
+ if (!pid) throw new Error('the launch wrapper started no emulator');
50
+ return pid;
51
+ }
52
+
53
+ async function launchEmulator(spec, at, log) {
54
+ const { command, launchPrefix } = spec.emulator;
55
+ const [first, ...rest] = [...launchPrefix, ...command];
56
+ const child = spawn(first, rest, { stdio: 'ignore', cwd: at('.') });
57
+ log(`started ${path.basename(command[0])} (pid ${child.pid})`);
58
+ await started(child, null);
59
+ return { pid: emulatorPid(child, launchPrefix.length > 0), stop: () => child.kill('SIGTERM') };
60
+ }
61
+
62
+ /* a `gameslate drive` command; a frame's file goes beside the spec */
63
+ function drive(spec, at, args) {
64
+ if (!spec.gameslate) throw new Error('steps need "gameslate": the path to dist/gameslate.mjs');
65
+ const resolved = args[0] === 'frame' ? [args[0], args[1], at(args[2])] : args;
66
+ return new Promise((resolve, reject) => {
67
+ execFile(
68
+ process.execPath,
69
+ [at(spec.gameslate), 'drive', ...resolved],
70
+ (err, stdout, stderr) =>
71
+ err
72
+ ? reject(
73
+ new Error(`gameslate drive ${args[0]}: ${stderr.trim() || err.message}`),
74
+ )
75
+ : resolve(stdout),
76
+ );
77
+ });
78
+ }
79
+
80
+ function launchRetroArch(spec, at, log) {
81
+ const ra = spec.retroarch;
82
+ if (!ra) return Promise.resolve({ stop: () => undefined });
83
+ const args = ['-L', at(ra.core), at(ra.rom), '-e', String(ra.stateSlot)];
84
+ if (ra.config) args.push('--appendconfig', at(ra.config));
85
+ const [first, ...rest] = [...ra.launchPrefix, at(ra.binary), ...args];
86
+ const child = spawn(first, rest, { stdio: 'ignore' });
87
+ log(`started RetroArch (pid ${child.pid}) on state slot ${ra.stateSlot}`);
88
+ return new Promise((resolve, reject) => {
89
+ child.once('error', reject);
90
+ child.once('exit', code => reject(new Error(`RetroArch exited (${code}) while starting`)));
91
+ setTimeout(() => {
92
+ child.removeAllListeners('exit');
93
+ resolve({ stop: () => child.kill('SIGTERM') });
94
+ }, STARTUP_MS);
95
+ });
96
+ }
97
+
98
+ /* the daemon's next full state for the spec's game */
99
+ function nextState(spec) {
100
+ return new Promise((resolve, reject) => {
101
+ const ws = new globalThis.WebSocket(spec.daemon.url);
102
+ const timer = setTimeout(() => {
103
+ ws.close();
104
+ reject(
105
+ new Error(
106
+ `no state for ${spec.game} from ${spec.daemon.url} in ${spec.timeoutMs} ms`,
107
+ ),
108
+ );
109
+ }, spec.timeoutMs);
110
+ ws.addEventListener('error', () => {
111
+ clearTimeout(timer);
112
+ reject(new Error(`can't reach the daemon at ${spec.daemon.url}`));
113
+ });
114
+ ws.addEventListener('message', event => {
115
+ const m = JSON.parse(String(event.data));
116
+ if (m.type !== 'state:full' || m.gameId !== spec.game || !m.state) return;
117
+ clearTimeout(timer);
118
+ ws.close();
119
+ resolve(m.state);
120
+ });
121
+ });
122
+ }
123
+
124
+ /* one RetroArch network command and its reply */
125
+ function retroArchCommand(port, line) {
126
+ return new Promise((resolve, reject) => {
127
+ const socket = dgram.createSocket('udp4');
128
+ const timer = setTimeout(() => {
129
+ socket.close();
130
+ reject(
131
+ new Error(`RetroArch didn't answer "${line}" (network commands on, port ${port}?)`),
132
+ );
133
+ }, COMMAND_TIMEOUT_MS);
134
+ socket.once('message', reply => {
135
+ clearTimeout(timer);
136
+ socket.close();
137
+ resolve(String(reply));
138
+ });
139
+ socket.send(line, port, '127.0.0.1');
140
+ });
141
+ }
142
+
143
+ async function screenshots(spec, at, log) {
144
+ const files = [];
145
+ if (spec.retroarch) {
146
+ /* no reply: the file goes to RetroArch's screenshot_directory */
147
+ const socket = dgram.createSocket('udp4');
148
+ await new Promise(resolve =>
149
+ socket.send('SCREENSHOT', spec.retroarch.port, '127.0.0.1', resolve),
150
+ );
151
+ socket.close();
152
+ files.push("(RetroArch's screenshot directory)");
153
+ }
154
+ if (spec.ui) {
155
+ const playwright = await import('playwright').catch(() => null);
156
+ if (!playwright) {
157
+ log('Playwright is not installed: no screenshot of the GameSlate page');
158
+ return files;
159
+ }
160
+ const browser = await playwright.chromium.launch();
161
+ try {
162
+ /* a phone's viewport: the app is laid out for one */
163
+ const page = await browser.newPage({ viewport: { width: 430, height: 900 } });
164
+ await page.goto(spec.ui.url);
165
+ await page.waitForTimeout(2000);
166
+ if (spec.ui.tabs.length === 0) {
167
+ const file = at(`verify-${spec.game}-ui.png`);
168
+ await page.screenshot({ path: file });
169
+ files.push(file);
170
+ }
171
+ for (const tab of spec.ui.tabs) {
172
+ const button = page.locator(`.fm-tab:has-text(${JSON.stringify(tab)})`);
173
+ if ((await button.count()) === 0) {
174
+ log(`the GameSlate page has no "${tab}" tab for ${spec.game}`);
175
+ continue;
176
+ }
177
+ await button.first().click();
178
+ await page.waitForTimeout(2500);
179
+ const file = at(`verify-${spec.game}-${tab.toLowerCase()}.png`);
180
+ await page.screenshot({ path: file });
181
+ files.push(file);
182
+ }
183
+ } finally {
184
+ await browser.close();
185
+ }
186
+ }
187
+ return files;
188
+ }
package/lib/assets.d.ts CHANGED
@@ -127,11 +127,42 @@ export declare const FloorplanDrawingSchema: z.ZodObject<{
127
127
  export type FloorplanDrawing = z.infer<typeof FloorplanDrawingSchema>;
128
128
  /** The SVG for a drawing. Every value in it has passed the schema, so it's safe to serve. */
129
129
  export declare function floorplanToSvg(drawing: FloorplanDrawing): string;
130
+ export declare const ImagePurposeSchema: z.ZodEnum<["atlas", "map", "icon", "actor"]>;
131
+ export type ImagePurpose = z.infer<typeof ImagePurposeSchema>;
132
+ /** PNG, lossless WebP, or lossy WebP at a quality from 1 to 100. */
133
+ export declare const ImageEncodingSchema: z.ZodUnion<[z.ZodObject<{
134
+ format: z.ZodLiteral<"png">;
135
+ }, "strict", z.ZodTypeAny, {
136
+ format: "png";
137
+ }, {
138
+ format: "png";
139
+ }>, z.ZodObject<{
140
+ format: z.ZodLiteral<"webp">;
141
+ lossless: z.ZodLiteral<true>;
142
+ }, "strict", z.ZodTypeAny, {
143
+ format: "webp";
144
+ lossless: true;
145
+ }, {
146
+ format: "webp";
147
+ lossless: true;
148
+ }>, z.ZodObject<{
149
+ format: z.ZodLiteral<"webp">;
150
+ quality: z.ZodNumber;
151
+ }, "strict", z.ZodTypeAny, {
152
+ format: "webp";
153
+ quality: number;
154
+ }, {
155
+ format: "webp";
156
+ quality: number;
157
+ }>]>;
158
+ export type ImageEncoding = z.infer<typeof ImageEncodingSchema>;
130
159
  /**
131
160
  * One file-shaped result of building an asset; the core decides where each goes:
132
161
  * floorplan → maps/<id>.svg location → manifest.json (locations[id])
133
- * nav → navs/<id>.json mesh → meshes/<id>.bin (+ its atlas as meshes/<id>.png)
134
- * image → atlases/<id>.png
162
+ * nav → navs/<id>.json mesh → meshes/<id>.bin (+ its atlas beside it)
163
+ * image → by purpose: atlases/ (default), maps/, icons/ or actors/<id>.png | .webp
164
+ * The core encodes images from the pixels; every image of a game uses one format (the web app
165
+ * reads one extension per game).
135
166
  */
136
167
  export declare const AssetOutputSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
137
168
  kind: z.ZodLiteral<"floorplan">;
@@ -817,13 +848,13 @@ export declare const AssetOutputSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodOb
817
848
  }, "strip", z.ZodTypeAny, {
818
849
  id: string;
819
850
  kind: "mesh";
820
- data: number;
821
851
  atlas: string;
852
+ data: number;
822
853
  }, {
823
854
  id: string;
824
855
  kind: "mesh";
825
- data: number;
826
856
  atlas: string;
857
+ data: number;
827
858
  }>, z.ZodObject<{
828
859
  kind: z.ZodLiteral<"image">;
829
860
  id: z.ZodEffects<z.ZodString, string, string>;
@@ -831,18 +862,66 @@ export declare const AssetOutputSchema: z.ZodDiscriminatedUnion<"kind", [z.ZodOb
831
862
  height: z.ZodNumber;
832
863
  /** RGBA, width × height × 4 bytes */
833
864
  pixels: z.ZodNumber;
865
+ /** what the image is for, which picks its folder (default atlas: a mesh's texture) */
866
+ purpose: z.ZodOptional<z.ZodEnum<["atlas", "map", "icon", "actor"]>>;
867
+ /** how the core encodes it (default PNG) */
868
+ encoding: z.ZodOptional<z.ZodUnion<[z.ZodObject<{
869
+ format: z.ZodLiteral<"png">;
870
+ }, "strict", z.ZodTypeAny, {
871
+ format: "png";
872
+ }, {
873
+ format: "png";
874
+ }>, z.ZodObject<{
875
+ format: z.ZodLiteral<"webp">;
876
+ lossless: z.ZodLiteral<true>;
877
+ }, "strict", z.ZodTypeAny, {
878
+ format: "webp";
879
+ lossless: true;
880
+ }, {
881
+ format: "webp";
882
+ lossless: true;
883
+ }>, z.ZodObject<{
884
+ format: z.ZodLiteral<"webp">;
885
+ quality: z.ZodNumber;
886
+ }, "strict", z.ZodTypeAny, {
887
+ format: "webp";
888
+ quality: number;
889
+ }, {
890
+ format: "webp";
891
+ quality: number;
892
+ }>]>>;
834
893
  }, "strip", z.ZodTypeAny, {
835
894
  id: string;
836
895
  kind: "image";
837
896
  width: number;
838
897
  height: number;
839
898
  pixels: number;
899
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
900
+ encoding?: {
901
+ format: "png";
902
+ } | {
903
+ format: "webp";
904
+ lossless: true;
905
+ } | {
906
+ format: "webp";
907
+ quality: number;
908
+ } | undefined;
840
909
  }, {
841
910
  id: string;
842
911
  kind: "image";
843
912
  width: number;
844
913
  height: number;
845
914
  pixels: number;
915
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
916
+ encoding?: {
917
+ format: "png";
918
+ } | {
919
+ format: "webp";
920
+ lossless: true;
921
+ } | {
922
+ format: "webp";
923
+ quality: number;
924
+ } | undefined;
846
925
  }>]>;
847
926
  export type AssetOutputWire = z.infer<typeof AssetOutputSchema>;
848
927
  export declare const AssetResultSchema: z.ZodObject<{
@@ -1530,13 +1609,13 @@ export declare const AssetResultSchema: z.ZodObject<{
1530
1609
  }, "strip", z.ZodTypeAny, {
1531
1610
  id: string;
1532
1611
  kind: "mesh";
1533
- data: number;
1534
1612
  atlas: string;
1613
+ data: number;
1535
1614
  }, {
1536
1615
  id: string;
1537
1616
  kind: "mesh";
1538
- data: number;
1539
1617
  atlas: string;
1618
+ data: number;
1540
1619
  }>, z.ZodObject<{
1541
1620
  kind: z.ZodLiteral<"image">;
1542
1621
  id: z.ZodEffects<z.ZodString, string, string>;
@@ -1544,18 +1623,66 @@ export declare const AssetResultSchema: z.ZodObject<{
1544
1623
  height: z.ZodNumber;
1545
1624
  /** RGBA, width × height × 4 bytes */
1546
1625
  pixels: z.ZodNumber;
1626
+ /** what the image is for, which picks its folder (default atlas: a mesh's texture) */
1627
+ purpose: z.ZodOptional<z.ZodEnum<["atlas", "map", "icon", "actor"]>>;
1628
+ /** how the core encodes it (default PNG) */
1629
+ encoding: z.ZodOptional<z.ZodUnion<[z.ZodObject<{
1630
+ format: z.ZodLiteral<"png">;
1631
+ }, "strict", z.ZodTypeAny, {
1632
+ format: "png";
1633
+ }, {
1634
+ format: "png";
1635
+ }>, z.ZodObject<{
1636
+ format: z.ZodLiteral<"webp">;
1637
+ lossless: z.ZodLiteral<true>;
1638
+ }, "strict", z.ZodTypeAny, {
1639
+ format: "webp";
1640
+ lossless: true;
1641
+ }, {
1642
+ format: "webp";
1643
+ lossless: true;
1644
+ }>, z.ZodObject<{
1645
+ format: z.ZodLiteral<"webp">;
1646
+ quality: z.ZodNumber;
1647
+ }, "strict", z.ZodTypeAny, {
1648
+ format: "webp";
1649
+ quality: number;
1650
+ }, {
1651
+ format: "webp";
1652
+ quality: number;
1653
+ }>]>>;
1547
1654
  }, "strip", z.ZodTypeAny, {
1548
1655
  id: string;
1549
1656
  kind: "image";
1550
1657
  width: number;
1551
1658
  height: number;
1552
1659
  pixels: number;
1660
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
1661
+ encoding?: {
1662
+ format: "png";
1663
+ } | {
1664
+ format: "webp";
1665
+ lossless: true;
1666
+ } | {
1667
+ format: "webp";
1668
+ quality: number;
1669
+ } | undefined;
1553
1670
  }, {
1554
1671
  id: string;
1555
1672
  kind: "image";
1556
1673
  width: number;
1557
1674
  height: number;
1558
1675
  pixels: number;
1676
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
1677
+ encoding?: {
1678
+ format: "png";
1679
+ } | {
1680
+ format: "webp";
1681
+ lossless: true;
1682
+ } | {
1683
+ format: "webp";
1684
+ quality: number;
1685
+ } | undefined;
1559
1686
  }>]>, "many">;
1560
1687
  }, "strip", z.ZodTypeAny, {
1561
1688
  outputs: ({
@@ -1651,14 +1778,24 @@ export declare const AssetResultSchema: z.ZodObject<{
1651
1778
  } | {
1652
1779
  id: string;
1653
1780
  kind: "mesh";
1654
- data: number;
1655
1781
  atlas: string;
1782
+ data: number;
1656
1783
  } | {
1657
1784
  id: string;
1658
1785
  kind: "image";
1659
1786
  width: number;
1660
1787
  height: number;
1661
1788
  pixels: number;
1789
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
1790
+ encoding?: {
1791
+ format: "png";
1792
+ } | {
1793
+ format: "webp";
1794
+ lossless: true;
1795
+ } | {
1796
+ format: "webp";
1797
+ quality: number;
1798
+ } | undefined;
1662
1799
  })[];
1663
1800
  }, {
1664
1801
  outputs: ({
@@ -1754,14 +1891,24 @@ export declare const AssetResultSchema: z.ZodObject<{
1754
1891
  } | {
1755
1892
  id: string;
1756
1893
  kind: "mesh";
1757
- data: number;
1758
1894
  atlas: string;
1895
+ data: number;
1759
1896
  } | {
1760
1897
  id: string;
1761
1898
  kind: "image";
1762
1899
  width: number;
1763
1900
  height: number;
1764
1901
  pixels: number;
1902
+ purpose?: "icon" | "map" | "atlas" | "actor" | undefined;
1903
+ encoding?: {
1904
+ format: "png";
1905
+ } | {
1906
+ format: "webp";
1907
+ lossless: true;
1908
+ } | {
1909
+ format: "webp";
1910
+ quality: number;
1911
+ } | undefined;
1765
1912
  })[];
1766
1913
  }>;
1767
1914
  /** An output as plugin code builds it: binary data as bytes. */
package/lib/assets.js CHANGED
@@ -77,11 +77,20 @@ export function floorplanToSvg(drawing) {
77
77
  /** Binary data in an output: in plugin code a Uint8Array; across the sandbox boundary, an index
78
78
  * into the chunks the guest handed the core during that call. */
79
79
  const BinaryRef = z.number().int().nonnegative();
80
+ export const ImagePurposeSchema = z.enum(['atlas', 'map', 'icon', 'actor']);
81
+ /** PNG, lossless WebP, or lossy WebP at a quality from 1 to 100. */
82
+ export const ImageEncodingSchema = z.union([
83
+ z.object({ format: z.literal('png') }).strict(),
84
+ z.object({ format: z.literal('webp'), lossless: z.literal(true) }).strict(),
85
+ z.object({ format: z.literal('webp'), quality: z.number().int().min(1).max(100) }).strict(),
86
+ ]);
80
87
  /**
81
88
  * One file-shaped result of building an asset; the core decides where each goes:
82
89
  * floorplan → maps/<id>.svg location → manifest.json (locations[id])
83
- * nav → navs/<id>.json mesh → meshes/<id>.bin (+ its atlas as meshes/<id>.png)
84
- * image → atlases/<id>.png
90
+ * nav → navs/<id>.json mesh → meshes/<id>.bin (+ its atlas beside it)
91
+ * image → by purpose: atlases/ (default), maps/, icons/ or actors/<id>.png | .webp
92
+ * The core encodes images from the pixels; every image of a game uses one format (the web app
93
+ * reads one extension per game).
85
94
  */
86
95
  export const AssetOutputSchema = z.discriminatedUnion('kind', [
87
96
  z.object({ kind: z.literal('floorplan'), id: AssetIdSchema, drawing: FloorplanDrawingSchema }),
@@ -102,6 +111,10 @@ export const AssetOutputSchema = z.discriminatedUnion('kind', [
102
111
  height: z.number().int().positive().max(16_384),
103
112
  /** RGBA, width × height × 4 bytes */
104
113
  pixels: BinaryRef,
114
+ /** what the image is for, which picks its folder (default atlas: a mesh's texture) */
115
+ purpose: ImagePurposeSchema.optional(),
116
+ /** how the core encodes it (default PNG) */
117
+ encoding: ImageEncodingSchema.optional(),
105
118
  }),
106
119
  ]);
107
120
  export const AssetResultSchema = z.object({ outputs: z.array(AssetOutputSchema).max(1000) });