@gameslate/sdk 0.3.24 → 0.3.26

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
@@ -66,6 +66,21 @@ no file system, no network. Read the game through `GameMemory`, the player's fil
66
66
  `InputFile`, and bytes with `Bytes`. Return data (states, drawings, pixels, meshes, notes); the core
67
67
  validates it and writes every file.
68
68
 
69
+ The sandbox refuses a call of more than 65535 arguments, where Node (and so vitest) takes far more:
70
+ `Math.min(...xs)`, `out.push(...items)` or `String.fromCharCode(...bytes)` over a map's worth of
71
+ data passes the tests and fails in the core. So `gameslate-plugin build` refuses a spread argument,
72
+ and `x.apply(t, list)` (also `x['apply']`, `apply.call`), `Reflect.apply(fn, t, list)` and
73
+ `Reflect.construct(C, list)` with a list that isn't an array literal, in the plugin's own code,
74
+ naming the file and line; a file it can't parse fails the build too. Fold and append by loop with
75
+ `extent(values, what)` (`{ min, max }`; throws on no values or a non-finite one) and
76
+ `append(into, items)` from `@gameslate/sdk`. A spread whose length the code fixes (four header
77
+ bytes, a triangle's corners) stays with `/* spread-ok: <why> */` on the line directly above its
78
+ statement (a function, class, `export default` or class property counts as one). The marker covers
79
+ the calls that start on that statement's first line, including those of a statement nested there
80
+ (`for (…) f(...p)`), and nothing on later lines: not a loop body, not a multi-line arrow's body. A
81
+ marker needs a reason and must mark something. Dependencies under `node_modules` aren't checked
82
+ (they can't be marked).
83
+
69
84
  A file the asset code needs from the web (a port's source at a pinned commit) is a download in the
70
85
  game's manifest entry: `downloads: [{ id, url, sha256 }]`, an exact https URL. The core fetches it
71
86
  when a build for that game starts, checks the hash, and hands it to `listAssets` / `buildAsset` as
@@ -75,6 +90,15 @@ the input `downloads/<id>`; the player sees it among the plugin's permissions.
75
90
 
76
91
  `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.
77
92
 
93
+ - **0.3.26**: `Bytes#toString` decodes 8 KiB per call and joins the pieces, since building the
94
+ string a byte at a time was quadratic in QuickJS (a 1 MB string took 147 s). `isCoreInput(name)`
95
+ and `REGISTRY_INPUT_NAME` name the inputs the core adds (the registry manifest, downloads), which
96
+ code reading every picked file must leave out.
97
+ - **0.3.25**: `extent` and `append` fold and append by loop; `gameslate-plugin build` refuses a
98
+ call whose argument count is an array's length (a spread argument, `.apply`, `Reflect.apply`,
99
+ `Reflect.construct`) unless a `/* spread-ok: <why> */` marker sits directly above its
100
+ statement: the sandbox refuses more than 65535 arguments. The sdk now depends on `typescript` (the check
101
+ parses the plugin's source).
78
102
  - **0.3.24**: `gameslate-plugin addresses` takes `sourceTypes` (`[{ file, types }]`): types a
79
103
  decomp declares only in a `.c` file, lifted into the probe at probe time so their `offsetof`
80
104
  and `sizeof` can be checked. A declaration inside an `#if` region, or holding a preprocessor
@@ -4,6 +4,7 @@ import { createHash } from 'node:crypto';
4
4
  import fs from 'node:fs';
5
5
  import { createRequire } from 'node:module';
6
6
  import path from 'node:path';
7
+ import { checkSpreadLimit } from './spread-limit.mjs';
7
8
  import { renderLicences } from './third-party-licences.mjs';
8
9
  import { zipFolder } from './zip.mjs';
9
10
 
@@ -24,7 +25,9 @@ export { zipEntries } from './zip.mjs';
24
25
  * registry/ the plugin's registry data, copied as it is (the core checks it on load:
25
26
  * src/host/plugin-registry.ts; `gameslate-plugin validate` runs the same check)
26
27
  * Sandbox scripts are built for a neutral platform, so a Node API in them fails the build. No plugin
27
- * code runs outside the sandbox: an `extract.ts` (the old unsandboxed hooks) fails the build.
28
+ * code runs outside the sandbox: an `extract.ts` (the old unsandboxed hooks) fails the build. A
29
+ * call whose argument count is an array's length (`f(...xs)`, `.apply`) fails it too, unless its
30
+ * site is marked as staying small: the sandbox refuses more than 65535 (spread-limit.mjs).
28
31
  *
29
32
  * With `release` (a folder), it also writes what a release uploads, side by side:
30
33
  * <id>-<version>.zip the built folder, under <id>/
@@ -68,11 +71,22 @@ const nodeResolution = {
68
71
 
69
72
  const hashOf = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
70
73
 
71
- /* a sandbox script: `entry`'s default export handed to the sdk's `expose` function */
74
+ const SANDBOX_ENTRY = 'sandbox-entry.ts';
75
+
72
76
  /* the absolute paths of the modules an esbuild result bundled */
73
77
  const inputsOf = (srcDir, result) =>
74
78
  Object.keys(result.metafile.inputs).map(input => path.resolve(srcDir, input));
75
79
 
80
+ /* the absolute paths of the modules that put code into the bundle (an output's inputs: a module
81
+ * only imported for what tree shaking dropped isn't one), without the generated entry */
82
+ const contributorsOf = (srcDir, result) =>
83
+ Object.values(result.metafile.outputs).flatMap(output =>
84
+ Object.keys(output.inputs)
85
+ .filter(input => input !== SANDBOX_ENTRY)
86
+ .map(input => path.resolve(srcDir, input)),
87
+ );
88
+
89
+ /* a sandbox script: `entry`'s default export handed to the sdk's `expose` function */
76
90
  async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
77
91
  const result = await esbuild.build({
78
92
  absWorkingDir: srcDir,
@@ -83,7 +97,7 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
83
97
  `${expose}(plugin);`,
84
98
  ].join('\n'),
85
99
  resolveDir: srcDir,
86
- sourcefile: 'sandbox-entry.ts',
100
+ sourcefile: SANDBOX_ENTRY,
87
101
  loader: 'ts',
88
102
  },
89
103
  outfile,
@@ -98,6 +112,7 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
98
112
  metafile: true,
99
113
  logLevel: 'warning',
100
114
  });
115
+ checkSpreadLimit(contributorsOf(srcDir, result), path.dirname(srcDir));
101
116
  return inputsOf(srcDir, result);
102
117
  }
103
118
 
@@ -0,0 +1,6 @@
1
+ /** One source file's problems, each `<file>:<line>: <what>` (see spread-limit.mjs). */
2
+ export function spreadProblems(file: string, text: string): string[];
3
+
4
+ /** Throws, listing every problem, when the plugin code in `modules` calls with an unbounded
5
+ * argument count; files are named relative to `baseDir`. */
6
+ export function checkSpreadLimit(modules: readonly string[], baseDir: string): void;
@@ -0,0 +1,202 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import ts from 'typescript';
4
+
5
+ /*
6
+ * The core's QuickJS sandbox refuses a call of more than 65535 arguments; Node takes far more, so
7
+ * `Math.min(...xs)` over a big map passes vitest and fails in the sandbox (DK64's Frantic Factory,
8
+ * 2026-12-06). The build refuses every call whose argument count is the length of an array:
9
+ * a spread argument, and `.apply` (also as `['apply']` and `apply.call`), `Reflect.apply` and
10
+ * `Reflect.construct` with a list that isn't an array literal.
11
+ *
12
+ * A site whose length the code fixes (a triangle's corners) stays only with a block comment
13
+ * `spread-ok: <why>` on the line directly above its statement. A statement here is also a function,
14
+ * class, `export default` or class property declaration. The marker covers the calls that start on
15
+ * that statement's first line, its own and those of statements nested on the same line
16
+ * (`for (…) f(...xs)`), and nothing on later lines: not a loop body, not an arrow's body. A marker
17
+ * needs a reason, and one that marks nothing is refused.
18
+ *
19
+ * The plugin's own source is read, not the bundle: esbuild drops plain comments, so the marker
20
+ * wouldn't reach the bundle. Only the modules that put code into the bundle are read (esbuild's
21
+ * metafile), and not those under node_modules: a dependency can't be marked.
22
+ */
23
+
24
+ const MARKER = /^\/\*\s*spread-ok\b:?\s*(.*?)\s*\*\/$/s;
25
+ const LIMIT =
26
+ "the sandbox refuses a call of more than 65535 arguments: fold or append by loop (extent, append from '@gameslate/sdk'), or mark a statement whose spread stays small with /* spread-ok: <why> */ on the line directly above";
27
+
28
+ const lineAt = (source, pos) => source.getLineAndCharacterOfPosition(pos).line + 1;
29
+ const lineOf = (source, node) => lineAt(source, node.getStart(source));
30
+
31
+ /* what a marker can lead */
32
+ const isStatement = node =>
33
+ (node.kind >= ts.SyntaxKind.FirstStatement && node.kind <= ts.SyntaxKind.LastStatement) ||
34
+ ts.isFunctionDeclaration(node) ||
35
+ ts.isClassDeclaration(node) ||
36
+ ts.isExportAssignment(node) ||
37
+ ts.isPropertyDeclaration(node);
38
+
39
+ /* the statement `node` is in, and any enclosing one that starts on the same line */
40
+ function statementsOf(source, node) {
41
+ const found = [];
42
+ for (let n = node.parent; n !== undefined && !ts.isSourceFile(n); n = n.parent) {
43
+ if (!isStatement(n)) continue;
44
+ const first = found[0];
45
+ if (first !== undefined && lineOf(source, n) !== lineOf(source, first)) break;
46
+ found.push(n);
47
+ }
48
+ return found;
49
+ }
50
+
51
+ /* a list whose length is fixed in the source: an array literal without spreads */
52
+ const isFixedList = node =>
53
+ ts.isArrayLiteralExpression(node) && !node.elements.some(e => ts.isSpreadElement(e));
54
+
55
+ /* `object.name` or `object['name']`, parentheses skipped: `{ object, name }`, or undefined */
56
+ function memberOf(expression) {
57
+ const e = ts.skipParentheses(expression);
58
+ if (ts.isPropertyAccessExpression(e)) return { object: e.expression, name: e.name.text };
59
+ if (ts.isElementAccessExpression(e) && ts.isStringLiteralLike(e.argumentExpression))
60
+ return { object: e.expression, name: e.argumentExpression.text };
61
+ return undefined;
62
+ }
63
+
64
+ /* the list `call` spreads into a call through apply or Reflect: `{ rule, list }`, or undefined */
65
+ function appliedList(call) {
66
+ const member = memberOf(call.expression);
67
+ if (!member) return undefined;
68
+ const object = ts.skipParentheses(member.object);
69
+ const onReflect = ts.isIdentifier(object) && object.text === 'Reflect';
70
+ const args = call.arguments;
71
+ if (onReflect && member.name === 'apply') return { rule: 'Reflect.apply', list: args[2] };
72
+ if (onReflect && member.name === 'construct')
73
+ return { rule: 'Reflect.construct', list: args[1] };
74
+ if (member.name === 'apply') return { rule: '.apply with an argument list', list: args[1] };
75
+ if (member.name === 'call' && memberOf(object)?.name === 'apply')
76
+ return { rule: '.apply.call with an argument list', list: args[2] };
77
+ return undefined;
78
+ }
79
+
80
+ /** Sites in `source` that pass an array's length of arguments: `{ node, call, rule }`. */
81
+ function unboundedSites(source) {
82
+ const found = [];
83
+ const visit = node => {
84
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
85
+ for (const arg of node.arguments ?? [])
86
+ if (ts.isSpreadElement(arg))
87
+ found.push({ node: arg, call: node, rule: 'a spread argument' });
88
+ }
89
+ if (ts.isCallExpression(node)) {
90
+ const applied = appliedList(node);
91
+ if (applied?.list && !isFixedList(applied.list))
92
+ found.push({ node: applied.list, call: node, rule: applied.rule });
93
+ }
94
+ ts.forEachChild(node, visit);
95
+ };
96
+ visit(source);
97
+ return found;
98
+ }
99
+
100
+ /* the spread-ok marker on the line directly above one of the statements whose first line `site`'s
101
+ * call starts on: `{ pos, reason }`, or undefined */
102
+ function markerOf(source, site) {
103
+ const statements = statementsOf(source, site.node);
104
+ const first = statements[0];
105
+ if (first === undefined || lineOf(source, site.call) !== lineOf(source, first))
106
+ return undefined;
107
+ for (const statement of statements) {
108
+ const ranges = ts.getLeadingCommentRanges(source.text, statement.getFullStart()) ?? [];
109
+ for (const range of ranges) {
110
+ if (lineAt(source, range.end) !== lineOf(source, statement) - 1) continue;
111
+ const match = MARKER.exec(source.text.slice(range.pos, range.end));
112
+ if (match) return { pos: range.pos, reason: match[1] ?? '' };
113
+ }
114
+ }
115
+ return undefined;
116
+ }
117
+
118
+ /* the positions of every spread-ok comment in `source`; every token is visited (getChildren,
119
+ * not forEachChild), since a comment after `(` is trivia of the parenthesis, not of a node */
120
+ function markerPositions(source) {
121
+ const found = new Set();
122
+ const collect = ranges => {
123
+ for (const range of ranges ?? [])
124
+ if (MARKER.test(source.text.slice(range.pos, range.end))) found.add(range.pos);
125
+ };
126
+ const visit = node => {
127
+ collect(ts.getLeadingCommentRanges(source.text, node.pos));
128
+ collect(ts.getTrailingCommentRanges(source.text, node.end));
129
+ for (const child of node.getChildren(source)) visit(child);
130
+ };
131
+ visit(source);
132
+ return found;
133
+ }
134
+
135
+ function scriptKindOf(file) {
136
+ if (/\.tsx$/.test(file)) return ts.ScriptKind.TSX;
137
+ if (/\.[cm]?ts$/.test(file)) return ts.ScriptKind.TS;
138
+ if (/\.jsx$/.test(file)) return ts.ScriptKind.JSX;
139
+ if (/\.[cm]?js$/.test(file)) return ts.ScriptKind.JS;
140
+ throw new Error(`${file}: not a script the spread check can read`);
141
+ }
142
+
143
+ /**
144
+ * The problems in one source file, each `<file>:<line>: <what>`: unmarked sites, markers without
145
+ * a reason and markers that mark nothing. `file` names it in the messages. Throws on a file that
146
+ * doesn't parse: a misparse can hide a spread.
147
+ */
148
+ export function spreadProblems(file, text) {
149
+ const source = ts.createSourceFile(
150
+ file,
151
+ text,
152
+ ts.ScriptTarget.Latest,
153
+ true,
154
+ scriptKindOf(file),
155
+ );
156
+ const [syntax] = source.parseDiagnostics;
157
+ if (syntax)
158
+ throw new Error(
159
+ `${file}:${lineAt(source, syntax.start)}: the spread check can't parse it: ${ts.flattenDiagnosticMessageText(syntax.messageText, ' ')}`,
160
+ );
161
+ const problems = [];
162
+ const used = new Set();
163
+ for (const site of unboundedSites(source)) {
164
+ const marker = markerOf(source, site);
165
+ if (!marker) {
166
+ problems.push({ line: lineOf(source, site.node), text: `${site.rule}: ${LIMIT}` });
167
+ continue;
168
+ }
169
+ if (used.has(marker.pos)) continue;
170
+ used.add(marker.pos);
171
+ if (!marker.reason)
172
+ problems.push({
173
+ line: lineAt(source, marker.pos),
174
+ text: 'a spread-ok marker needs a reason: /* spread-ok: <why it stays small> */',
175
+ });
176
+ }
177
+ for (const pos of markerPositions(source))
178
+ if (!used.has(pos))
179
+ problems.push({
180
+ line: lineAt(source, pos),
181
+ text: 'a spread-ok marker that marks no spread, .apply or Reflect call: it goes on the line directly above the statement',
182
+ });
183
+ return problems.sort((a, b) => a.line - b.line).map(p => `${file}:${p.line}: ${p.text}`);
184
+ }
185
+
186
+ /* modules read as code, not data an esbuild loader bundles (JSON, text) */
187
+ const CODE = /\.([cm]?[jt]sx?)$/;
188
+
189
+ /**
190
+ * Throws, listing every problem, when the plugin code in `modules` (absolute paths) calls with an
191
+ * unbounded argument count. Files are named relative to `baseDir`.
192
+ */
193
+ export function checkSpreadLimit(modules, baseDir) {
194
+ const own = modules.filter(m => CODE.test(m) && !m.split(path.sep).includes('node_modules'));
195
+ const problems = own.flatMap(m =>
196
+ spreadProblems(path.relative(baseDir, m), fs.readFileSync(m, 'utf8')),
197
+ );
198
+ if (problems.length)
199
+ throw new Error(
200
+ `plugin code calls with an unbounded argument count:\n${problems.map(p => ` ${p}`).join('\n')}`,
201
+ );
202
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The least and greatest of `values`. Throws on none, or on one that isn't a finite number: either
3
+ * would frame or band a drawing on NaN or infinite pixels. `what` names the values in the error.
4
+ */
5
+ export declare function extent(values: Iterable<number>, what: string): {
6
+ min: number;
7
+ max: number;
8
+ };
9
+ /** Appends `items` to `into`, in order. */
10
+ export declare function append<T>(into: T[], items: Iterable<T>): void;
package/lib/arrays.js ADDED
@@ -0,0 +1,31 @@
1
+ /*
2
+ * Folds and appends by loop, never by spreading an array into a call: the core's QuickJS sandbox
3
+ * refuses a call of more than 65535 arguments where Node takes far more, so `Math.min(...xs)` over
4
+ * a big map passes vitest and fails in the sandbox (`gameslate-plugin build` refuses the spread).
5
+ */
6
+ /**
7
+ * The least and greatest of `values`. Throws on none, or on one that isn't a finite number: either
8
+ * would frame or band a drawing on NaN or infinite pixels. `what` names the values in the error.
9
+ */
10
+ export function extent(values, what) {
11
+ let min = Infinity;
12
+ let max = -Infinity;
13
+ let seen = false;
14
+ for (const v of values) {
15
+ if (!Number.isFinite(v))
16
+ throw new Error(`${what} include ${v}`);
17
+ seen = true;
18
+ if (v < min)
19
+ min = v;
20
+ if (v > max)
21
+ max = v;
22
+ }
23
+ if (!seen)
24
+ throw new Error(`no ${what}`);
25
+ return { min, max };
26
+ }
27
+ /** Appends `items` to `into`, in order. */
28
+ export function append(into, items) {
29
+ for (const item of items)
30
+ into.push(item);
31
+ }
package/lib/bytes.js CHANGED
@@ -4,6 +4,10 @@
4
4
  * match Buffer's so decoders read the same either way. Reads past the end throw a RangeError,
5
5
  * as Buffer's do.
6
6
  */
7
+ /* Text is decoded this many bytes per call and the pieces joined: QuickJS copies the whole string
8
+ * on every `+=`, so a byte at a time is quadratic (a 1 MB string took 147 s in the sandbox), and
9
+ * one call per string would pass the sandbox's 65535-argument limit. */
10
+ const TEXT_CHUNK_BYTES = 8192;
7
11
  export class Bytes {
8
12
  data;
9
13
  view;
@@ -79,11 +83,14 @@ export class Bytes {
79
83
  * clears the high bit first, as Buffer does.
80
84
  */
81
85
  toString(encoding, start = 0, end = this.data.length) {
82
- const mask = encoding === 'ascii' ? 0x7f : 0xff;
83
- let out = '';
84
- for (let i = Math.max(0, start); i < Math.min(end, this.data.length); i++) {
85
- out += String.fromCharCode((this.data[i] ?? 0) & mask);
86
+ const to = Math.min(end, this.data.length);
87
+ const parts = [];
88
+ for (let i = Math.max(0, start); i < to; i += TEXT_CHUNK_BYTES) {
89
+ const raw = this.data.subarray(i, Math.min(to, i + TEXT_CHUNK_BYTES));
90
+ const chunk = encoding === 'ascii' ? raw.map(b => b & 0x7f) : raw;
91
+ /* spread-ok: at most TEXT_CHUNK_BYTES bytes */
92
+ parts.push(String.fromCharCode(...chunk));
86
93
  }
87
- return out;
94
+ return parts.join('');
88
95
  }
89
96
  }
package/lib/index.d.ts CHANGED
@@ -8,6 +8,7 @@ export * from './pins.js';
8
8
  export * from './chips.js';
9
9
  export * from './pack.js';
10
10
  export * from './views.js';
11
+ export * from './arrays.js';
11
12
  export * from './bytes.js';
12
13
  export * from './navigation.js';
13
14
  export * from './plugin-manifest.js';
package/lib/index.js CHANGED
@@ -8,6 +8,7 @@ export * from './pins.js';
8
8
  export * from './chips.js';
9
9
  export * from './pack.js';
10
10
  export * from './views.js';
11
+ export * from './arrays.js';
11
12
  export * from './bytes.js';
12
13
  export * from './navigation.js';
13
14
  export * from './plugin-manifest.js';
@@ -7,8 +7,10 @@ export function wasmModule(file) {
7
7
  throw new Error('the core gave no WebAssembly capability');
8
8
  return bridge;
9
9
  };
10
+ /* spread-ok: a WebAssembly export's parameters, a handful of numbers */
11
+ const call = (fn, ...args) => host().call(file, fn, ...args);
10
12
  return {
11
- call: (fn, ...args) => host().call(file, fn, ...args),
13
+ call,
12
14
  read: (ptr, length) => new Uint8Array(host().read(file, ptr, length)),
13
15
  /* an exact-size copy, so only these bytes cross */
14
16
  write: (ptr, bytes) => host().write(file, ptr, bytes.slice().buffer),
@@ -35,6 +35,11 @@ export declare const PluginDownloadSchema: z.ZodObject<{
35
35
  export type PluginDownload = z.infer<typeof PluginDownloadSchema>;
36
36
  /** The input name a download reaches the asset code under. */
37
37
  export declare const downloadInputName: (id: string) => string;
38
+ /** The input name the game's registry manifest reaches the asset code under. */
39
+ export declare const REGISTRY_INPUT_NAME = "registry/manifest.json";
40
+ /** Whether an input is one the core adds (a download, the registry manifest), not the player's
41
+ * own file: code reading every picked file must leave these out. */
42
+ export declare const isCoreInput: (name: string) => boolean;
38
43
  /**
39
44
  * A build of a game that the plugin's live code reads memory from: the id its source matches
40
45
  * (an ELF or PE build id, or an N64 ROM's code and version such as `CZLE.2`) and what the player
@@ -97,8 +97,14 @@ export const PluginDownloadSchema = z
97
97
  sha256: Sha256,
98
98
  })
99
99
  .strict();
100
+ const DOWNLOADS_FOLDER = 'downloads/';
100
101
  /** The input name a download reaches the asset code under. */
101
- export const downloadInputName = (id) => `downloads/${id}`;
102
+ export const downloadInputName = (id) => `${DOWNLOADS_FOLDER}${id}`;
103
+ /** The input name the game's registry manifest reaches the asset code under. */
104
+ export const REGISTRY_INPUT_NAME = 'registry/manifest.json';
105
+ /** Whether an input is one the core adds (a download, the registry manifest), not the player's
106
+ * own file: code reading every picked file must leave these out. */
107
+ export const isCoreInput = (name) => name === REGISTRY_INPUT_NAME || name.startsWith(DOWNLOADS_FOLDER);
102
108
  /**
103
109
  * A build of a game that the plugin's live code reads memory from: the id its source matches
104
110
  * (an ELF or PE build id, or an N64 ROM's code and version such as `CZLE.2`) and what the player
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gameslate/sdk",
3
- "version": "0.3.24",
3
+ "version": "0.3.26",
4
4
  "description": "Build plugins for GameSlate, the second-screen companion for PC games: the plugin contract, game-state and catalogue schemas, and the plugin builder.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -76,6 +76,7 @@
76
76
  "@jitl/quickjs-wasmfile-release-sync": "0.31.0",
77
77
  "esbuild": "^0.24.0",
78
78
  "quickjs-emscripten-core": "0.31.0",
79
+ "typescript": "^5.7.2",
79
80
  "zod": "^3.24.1"
80
81
  },
81
82
  "gameslate": {
@@ -355,13 +355,16 @@ Images have a `purpose` (`atlas`, `map`, `icon`, `actor`, which picks the folder
355
355
 
356
356
  Every image of a game uses one format. In the sandbox:
357
357
 
358
- - **No `TextDecoder`, `TextEncoder` or `Buffer`.** Decode UTF-8 by hand, and decode files in
359
- chunks (`String.fromCharCode(...bytes)` has an argument limit).
358
+ - **No `TextDecoder`, `TextEncoder` or `Buffer`.** Decode Latin-1 and ASCII with `new
359
+ Bytes(data).toString('latin1', start, end)` (sdk >= 0.3.26 is fast at any length), and UTF-8 by
360
+ hand.
360
361
  - **One asset per unit of work** (per map, per actor): each gets its own time budget (10 minutes)
361
362
  and its own up-to-date stamp, and jobs build assets across several threads.
362
363
  - Inputs are named relative to the folder the player picked (`mods/pack.o2r`). The core also hands
363
364
  in the game's registry manifest as `registry/manifest.json` when there is one, so renders line up
364
- with the registry's maps.
365
+ with the registry's maps, and each download as `downloads/<id>`. Code that reads every picked
366
+ file leaves those out with `isCoreInput(name)` (sdk 0.3.26): idtech1 read the registry manifest
367
+ as a WAD, so every build from picked WADs failed until 2026-12-06.
365
368
  - **Data from the web is a download, never a fetch.** Plugin code has no network and nothing
366
369
  runs outside the sandbox (`extract.ts` fails the build). Declare the file in the game's
367
370
  manifest entry, `downloads: [{ id, url, sha256 }]` with an exact https URL (a release asset, a
@@ -812,6 +815,65 @@ the plugin repos) in the same change as the fix. The next game should not have t
812
815
  - **A place that covers several maps can't get a drawing.** DK64's live reader groups 95
813
816
  unnamed maps as a world's "elsewhere"; plan for one place per map when a game has unnamed
814
817
  maps.
818
+ - **A place name is a stated fact: two written sources, or the id.** Name a map only as far as
819
+ two written sources agree (decomp code or tables, a survey note, a recorded live run), cite both
820
+ beside the name, and otherwise name it by id ("map 0x38") while the live read supplies context.
821
+ Uncited player knowledge isn't a source: 33 of 44 names in DK64's first pass didn't survive
822
+ this. Slug unnamed places by id alone (`map-0c`), so a later name or ruling never changes a
823
+ slug; and a decomp's `.data` tables copied from the ROM (DK64's map → world table) are the
824
+ publisher's data, read live, not committed (DK64 review, 2026-12-05).
825
+ - **A counter declared only for `describeState` also reaches the AI.** Shared code puts every
826
+ declared counter the state carries into LIVE_STATE (`readableCountersFor`): DK64's world counter
827
+ told the model the main menu was "a shop". Send such a counter only where its value means
828
+ something to the model, and throw in `describeState` where it must be present.
829
+ - **The 65535-argument limit.** The core's QuickJS sandbox refuses a call of more than 65535
830
+ arguments; Node allows far more, so `Math.min(...xs)`, `out.push(...items)` and
831
+ `String.fromCharCode(...bytes)` over map-sized data pass vitest and throw in the sandbox (DK64's
832
+ Frantic Factory, 2026-12-06). `gameslate-plugin build` (sdk >= 0.3.25) reads your own code (what
833
+ `live.ts` and `assets.ts` bundle, not `node_modules`) and refuses, naming file:line, a spread
834
+ argument to any call or `new`, and `x.apply(t, list)`, `x['apply'](t, list)`,
835
+ `Function.prototype.apply.call(f, t, list)`, `Reflect.apply` and `Reflect.construct` unless the
836
+ list is an array literal without spreads; a file it can't parse fails too. Fold with
837
+ `extent(values, 'corner xs')` (it throws on no values or a non-finite one, so a bad frame fails
838
+ loud) and append with `append(into, items)`, both from `@gameslate/sdk`. When the length is fixed,
839
+ prefer plain arguments (`f(p[0], p[1], p[2])`). Otherwise put `/* spread-ok: <why it stays small>
840
+ */` on the line directly above the statement (a function, class, `export default` or class
841
+ property counts); it covers only calls that start on that statement's first line, never a loop
842
+ body or a multi-line arrow's body below, and the build refuses an empty reason or a marker that
843
+ marks nothing. Decode text with `Bytes#toString`. Before marking a spread "small", find what
844
+ bounds it (a 4-byte field, a 3-vertex triangle, a format's u8 count): a string that only looks
845
+ short (a name, a path) is bounded by nothing. Test a fix with at least 300k items (Node starts
846
+ throwing at about 150k); a test that size also catches a loop that went quadratic. Name
847
+ `extent`'s `what` as a plural (`'vertex xs'`): its errors read "no vertex xs". Dependencies
848
+ aren't checked: if one handles map-sized arrays, test a big input in the sandbox
849
+ (`@gameslate/sdk/host`). After a change that grows the geometry, run `gameslate extract-assets
850
+ <game> --input <rom> --out-dir <scratch>` (the core's `dist/gameslate.mjs` with
851
+ `GAMESLATE_PLUGINS_DIR=<plugin>/dist`).
852
+ - **Never build a long string with `+=` a piece at a time.** QuickJS copies the whole string on
853
+ every `+=`, so it is quadratic where Node is linear: a 1 MB string a byte at a time took 147 s
854
+ in the sandbox (the sdk's own `Bytes#toString` did this until 0.3.26). Push the pieces into an
855
+ array and `join('')`, and run a multi-MB input through the sandbox
856
+ (`@gameslate/sdk/host`'s `loadQuickJs`), not only vitest.
857
+ - **Follow every source the floor or water query asks.** DK64's floor query merges the map mesh,
858
+ placed models and actor boxes; Conker's water height comes from water props, trigger-zone
859
+ volumes and surface type 8 at once. Port the game's query, not one of its sources, and say in
860
+ Known Gaps which sources are built at run time (animated bones, actor floors, scripted water)
861
+ and so aren't drawn.
862
+ - **A trigger volume isn't a surface.** Port its contains-test exactly (Conker's
863
+ `zone_isOutside`: thresholds, integer truncation, rotation order), draw the floors it holds as
864
+ water rather than its outline, check whether overlaps resolve last-wins or highest-wins, and
865
+ check any pre-filter the caller applies (a bounds box that rotates when the test doesn't).
866
+ Recolour floors under water as water, so a band painter can't hide a pond under ground of the
867
+ same band.
868
+ - **Prove a rotation's sign at a non-90° angle, axes combined.** A 90° turn or one axis lets a
869
+ sign error through, and a ROM check over mostly unrotated objects can't see it: derive order and
870
+ sign from the game's matrix chain (row vectors, `guMtxCatF` is a × b), pin per-axis goldens,
871
+ order goldens and an independent matrix oracle. Use the SDK's documented conventions, not the
872
+ decomp's copy of libultra, which is Nintendo's code.
873
+ - **Read the spawn function before blaming a spawn with no floor.** DK64's "nothing under"
874
+ spawns were doorway walk-ins (the kong walks 50 units along its yaw): test the walk's end over
875
+ a floor instead of raising a cap.
876
+ - **Padded record files:** accept a zero tail shorter than one record, refuse anything else.
815
877
  - **Keep exploration tests out of a shared tree.** A `*.scratch.test.ts` broke another agent's
816
878
  check: explore from the scratchpad.
817
879
  - **Mirror modes: draw the course as built.** `roomId` means a room to shared code (layer