@gameslate/sdk 0.3.0 → 0.3.2
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 +4 -1
- package/bin/gameslate-plugin.mjs +49 -12
- package/build/build-plugin.mjs +24 -0
- package/lib/host/asset-sandbox.d.ts +45 -0
- package/lib/host/asset-sandbox.js +131 -0
- package/lib/host/index.d.ts +4 -0
- package/lib/host/index.js +8 -0
- package/lib/host/inspect.d.ts +28 -0
- package/lib/host/inspect.js +97 -0
- package/lib/host/live-sandbox.d.ts +36 -0
- package/lib/host/live-sandbox.js +198 -0
- package/lib/host/quickjs-guest.d.ts +37 -0
- package/lib/host/quickjs-guest.js +132 -0
- package/package.json +13 -3
package/README.md
CHANGED
|
@@ -13,7 +13,9 @@ runs the plugin in a QuickJS sandbox, validates everything it returns, and owns
|
|
|
13
13
|
|---|---|
|
|
14
14
|
| `@gameslate/sdk` | Game state, catalogue (items, missions, collectibles, pins), conditions, map and asset schemas, `Bytes` |
|
|
15
15
|
| `@gameslate/sdk/plugin` | The plugin contract (`GamePlugin`, `GameMemory`, `AssetExtractor`, `PluginModule`), `seqlockSample`, and the sandbox adapters |
|
|
16
|
+
| `@gameslate/sdk/host` | (Node) the core's own sandbox and checks, for testing a built plugin the way the core runs it |
|
|
16
17
|
| `gameslate-plugin build` | Builds a plugin folder into what the core loads |
|
|
18
|
+
| `gameslate-plugin validate` | Checks a built plugin exactly as the core does: manifest, contract, hashes, and its code loaded in the sandbox |
|
|
17
19
|
|
|
18
20
|
## A plugin folder
|
|
19
21
|
|
|
@@ -25,6 +27,7 @@ assets.ts optional, default export: { id, extractors }: maps and meshes fr
|
|
|
25
27
|
|
|
26
28
|
```bash
|
|
27
29
|
gameslate-plugin build ./my-plugin --out ./dist/my-plugin --tested-with 2.3.0
|
|
30
|
+
gameslate-plugin validate ./dist/my-plugin
|
|
28
31
|
```
|
|
29
32
|
|
|
30
33
|
`live.js` and `assets.js` run in the core's sandbox, built for a neutral platform: no Node APIs,
|
|
@@ -34,6 +37,6 @@ validates it and writes every file.
|
|
|
34
37
|
|
|
35
38
|
## Versions
|
|
36
39
|
|
|
37
|
-
`0.3.x` speaks plugin contract (`sdkApi`) 3. The core refuses a plugin built for another contract.
|
|
40
|
+
`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.
|
|
38
41
|
|
|
39
42
|
MIT licensed.
|
package/bin/gameslate-plugin.mjs
CHANGED
|
@@ -4,23 +4,60 @@ import { parseArgs } from 'node:util';
|
|
|
4
4
|
import { buildPlugin } from '../build/build-plugin.mjs';
|
|
5
5
|
|
|
6
6
|
/*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
7
|
+
* gameslate-plugin build <pluginDir> --out <dir> [--tested-with <coreVersion> ...]
|
|
8
|
+
* Builds a plugin folder into what the GameSlate core loads (see build/build-plugin.mjs).
|
|
9
|
+
* gameslate-plugin validate <builtDir> [--core-version <version>]
|
|
10
|
+
* Checks a built plugin exactly as the core does before running it: manifest, contract,
|
|
11
|
+
* hashes, then its live and asset code loaded in the core's own sandbox.
|
|
9
12
|
*/
|
|
10
13
|
const { values, positionals } = parseArgs({
|
|
11
|
-
options: {
|
|
14
|
+
options: {
|
|
15
|
+
out: { type: 'string' },
|
|
16
|
+
'tested-with': { type: 'string', multiple: true },
|
|
17
|
+
'core-version': { type: 'string' },
|
|
18
|
+
},
|
|
12
19
|
allowPositionals: true,
|
|
13
20
|
});
|
|
14
21
|
const [command, dir] = positionals;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
22
|
+
const USAGE = [
|
|
23
|
+
'usage: gameslate-plugin build <pluginDir> --out <dir> [--tested-with <version>]',
|
|
24
|
+
' gameslate-plugin validate <builtDir> [--core-version <version>]',
|
|
25
|
+
].join('\n');
|
|
26
|
+
|
|
27
|
+
async function validate(builtDir) {
|
|
28
|
+
const { inspectPlugin, loadQuickJs, readPluginManifest } = await import('../lib/host/index.js');
|
|
29
|
+
const read = readPluginManifest(builtDir);
|
|
30
|
+
if ('problem' in read) return [read.problem];
|
|
31
|
+
const { manifest } = read;
|
|
32
|
+
const coreVersion = values['core-version'] ?? manifest.testedWith[0] ?? '0.0.0';
|
|
33
|
+
const result = inspectPlugin(await loadQuickJs(), builtDir, manifest, {
|
|
34
|
+
coreVersion,
|
|
35
|
+
log: line => console.error(line),
|
|
36
|
+
});
|
|
37
|
+
if (typeof result === 'string') return [result];
|
|
38
|
+
const { live, assets, warnings } = result;
|
|
39
|
+
console.log(`${manifest.id} ${manifest.version} (contract ${manifest.sdkApi}): OK`);
|
|
40
|
+
console.log(` packs: ${live.packs.map(p => p.id).join(', ') || 'none'}`);
|
|
41
|
+
console.log(
|
|
42
|
+
` sources: ${live.sources.map(s => `${s.gameId} (${s.supportedBuildIds.size} builds)`).join(', ') || 'none'}`,
|
|
18
43
|
);
|
|
44
|
+
console.log(` assets: ${assets?.games.join(', ') || 'none'}`);
|
|
45
|
+
for (const w of warnings) console.log(` warning: ${w}`);
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (command === 'build' && dir && values.out) {
|
|
50
|
+
const built = await buildPlugin({
|
|
51
|
+
srcDir: path.resolve(dir),
|
|
52
|
+
outDir: path.resolve(values.out),
|
|
53
|
+
testedWith: values['tested-with'] ?? [],
|
|
54
|
+
});
|
|
55
|
+
console.log(`built ${built.id} ${built.version} -> ${values.out}`);
|
|
56
|
+
} else if (command === 'validate' && dir) {
|
|
57
|
+
const problems = await validate(path.resolve(dir));
|
|
58
|
+
for (const p of problems) console.error(`refused: ${p}`);
|
|
59
|
+
process.exit(problems.length ? 1 : 0);
|
|
60
|
+
} else {
|
|
61
|
+
console.error(USAGE);
|
|
19
62
|
process.exit(1);
|
|
20
63
|
}
|
|
21
|
-
const built = await buildPlugin({
|
|
22
|
-
srcDir: path.resolve(dir),
|
|
23
|
-
outDir: path.resolve(values.out),
|
|
24
|
-
testedWith: values['tested-with'] ?? [],
|
|
25
|
-
});
|
|
26
|
-
console.log(`built ${built.id} ${built.version} -> ${values.out}`);
|
package/build/build-plugin.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as esbuild from 'esbuild';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
|
|
6
7
|
/*
|
|
@@ -16,6 +17,27 @@ const LIVE_FILE = 'live.js';
|
|
|
16
17
|
const ASSETS_FILE = 'assets.js';
|
|
17
18
|
const EXTRACT_FILE = 'extract.mjs';
|
|
18
19
|
|
|
20
|
+
/*
|
|
21
|
+
* Resolves bare imports (`@gameslate/sdk`, `earcut`) the way Node does, from the importing file's
|
|
22
|
+
* folder. esbuild otherwise obeys any Yarn Plug'n'Play manifest it finds in a parent directory,
|
|
23
|
+
* even one that has nothing to do with the plugin, and then refuses the plugin's own packages.
|
|
24
|
+
*/
|
|
25
|
+
const nodeResolution = {
|
|
26
|
+
name: 'gameslate-node-resolution',
|
|
27
|
+
setup(build) {
|
|
28
|
+
build.onResolve({ filter: /^[^./]/ }, args => {
|
|
29
|
+
if (args.path.startsWith('node:') || !args.resolveDir) return undefined;
|
|
30
|
+
try {
|
|
31
|
+
const resolve = createRequire(path.join(args.resolveDir, 'noop.js')).resolve;
|
|
32
|
+
return { path: resolve(args.path) };
|
|
33
|
+
} catch {
|
|
34
|
+
/* not resolvable this way (an alias, or an import-only package): esbuild decides */
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
|
|
19
41
|
const hashOf = file => createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
20
42
|
|
|
21
43
|
/* a sandbox script: `entry`'s default export handed to the sdk's `expose` function */
|
|
@@ -40,6 +62,7 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
|
|
|
40
62
|
format: 'iife',
|
|
41
63
|
target: 'es2022',
|
|
42
64
|
alias,
|
|
65
|
+
plugins: Object.keys(alias).length ? [] : [nodeResolution],
|
|
43
66
|
logLevel: 'warning',
|
|
44
67
|
});
|
|
45
68
|
}
|
|
@@ -54,6 +77,7 @@ async function buildNode(srcDir, entry, outfile, alias) {
|
|
|
54
77
|
target: 'node20',
|
|
55
78
|
format: 'esm',
|
|
56
79
|
alias,
|
|
80
|
+
plugins: Object.keys(alias).length ? [] : [nodeResolution],
|
|
57
81
|
banner: {
|
|
58
82
|
js: [
|
|
59
83
|
"import { createRequire as __gsCreateRequire } from 'node:module';",
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
|
|
2
|
+
import { type AssetList, type AssetOutputWire, type InputPick, type SandboxInputFile } from '../index.js';
|
|
3
|
+
export declare const ASSET_LIMITS: {
|
|
4
|
+
readonly memoryBytes: number;
|
|
5
|
+
readonly stackBytes: number;
|
|
6
|
+
readonly loadMs: 10000;
|
|
7
|
+
/** one asset (the spike's slowest Doom map took 0.3 s) */
|
|
8
|
+
readonly callMs: 120000;
|
|
9
|
+
/** the largest single input read */
|
|
10
|
+
readonly maxReadBytes: number;
|
|
11
|
+
/** all output bytes of one asset */
|
|
12
|
+
readonly maxOutputBytes: number;
|
|
13
|
+
};
|
|
14
|
+
/** The player's files for one run, opened by the core and read by range. */
|
|
15
|
+
export declare class InputSet {
|
|
16
|
+
private readonly files;
|
|
17
|
+
constructor(paths: readonly string[]);
|
|
18
|
+
/** what the guest sees: handles, names and sizes, never paths */
|
|
19
|
+
describe(): SandboxInputFile[];
|
|
20
|
+
read(handle: number, offset: number, length: number): Uint8Array;
|
|
21
|
+
close(): void;
|
|
22
|
+
}
|
|
23
|
+
export interface BuiltAsset {
|
|
24
|
+
outputs: AssetOutputWire[];
|
|
25
|
+
/** the bytes outputs refer to by index */
|
|
26
|
+
binaries: Uint8Array[];
|
|
27
|
+
}
|
|
28
|
+
export declare class AssetSandbox {
|
|
29
|
+
private readonly guest;
|
|
30
|
+
private binaries;
|
|
31
|
+
private binaryBytes;
|
|
32
|
+
private readonly name;
|
|
33
|
+
private readonly inputs;
|
|
34
|
+
constructor(quickJs: QuickJSWASMModule, opts: {
|
|
35
|
+
name: string;
|
|
36
|
+
code: string;
|
|
37
|
+
inputs: InputSet;
|
|
38
|
+
log: (line: string) => void;
|
|
39
|
+
});
|
|
40
|
+
games(): string[];
|
|
41
|
+
list(gameId: string, pick: InputPick): AssetList;
|
|
42
|
+
build(gameId: string, id: string): BuiltAsset;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
private capabilities;
|
|
45
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AssetListSchema, AssetResultSchema, } from '../index.js';
|
|
4
|
+
import { QuickJsGuest } from './quickjs-guest.js';
|
|
5
|
+
/*
|
|
6
|
+
* A plugin's asset code in its own QuickJS runtime, for one extraction run. Its capabilities:
|
|
7
|
+
* ranged reads of the files the core opened for this run, and handing back output bytes. No
|
|
8
|
+
* paths, no writes: the job's writer validates and stores what comes back.
|
|
9
|
+
*/
|
|
10
|
+
export const ASSET_LIMITS = {
|
|
11
|
+
/* a whole campaign's levels, textures and atlas stay parsed for the run */
|
|
12
|
+
memoryBytes: 1024 * 1024 * 1024,
|
|
13
|
+
stackBytes: 1024 * 1024,
|
|
14
|
+
loadMs: 10_000,
|
|
15
|
+
/** one asset (the spike's slowest Doom map took 0.3 s) */
|
|
16
|
+
callMs: 120_000,
|
|
17
|
+
/** the largest single input read */
|
|
18
|
+
maxReadBytes: 64 * 1024 * 1024,
|
|
19
|
+
/** all output bytes of one asset */
|
|
20
|
+
maxOutputBytes: 256 * 1024 * 1024,
|
|
21
|
+
};
|
|
22
|
+
/** The player's files for one run, opened by the core and read by range. */
|
|
23
|
+
export class InputSet {
|
|
24
|
+
files = [];
|
|
25
|
+
constructor(paths) {
|
|
26
|
+
for (const p of paths) {
|
|
27
|
+
const fd = fs.openSync(p, 'r');
|
|
28
|
+
this.files.push({ fd, name: path.basename(p), size: fs.fstatSync(fd).size });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** what the guest sees: handles, names and sizes, never paths */
|
|
32
|
+
describe() {
|
|
33
|
+
return this.files.map((f, i) => ({ handle: i + 1, name: f.name, size: f.size }));
|
|
34
|
+
}
|
|
35
|
+
read(handle, offset, length) {
|
|
36
|
+
const file = this.files[handle - 1];
|
|
37
|
+
if (!file)
|
|
38
|
+
throw new Error('no such input');
|
|
39
|
+
if (!Number.isInteger(offset) || !Number.isInteger(length) || offset < 0 || length < 0) {
|
|
40
|
+
throw new Error('a read needs a whole-number offset and length');
|
|
41
|
+
}
|
|
42
|
+
if (length > ASSET_LIMITS.maxReadBytes) {
|
|
43
|
+
throw new Error(`an input read of ${length} bytes is over the limit`);
|
|
44
|
+
}
|
|
45
|
+
if (offset + length > file.size)
|
|
46
|
+
throw new Error(`a read past the end of ${file.name}`);
|
|
47
|
+
const out = new Uint8Array(length);
|
|
48
|
+
fs.readSync(file.fd, out, 0, length, offset);
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
close() {
|
|
52
|
+
for (const f of this.files)
|
|
53
|
+
fs.closeSync(f.fd);
|
|
54
|
+
this.files.length = 0;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export class AssetSandbox {
|
|
58
|
+
guest;
|
|
59
|
+
binaries = [];
|
|
60
|
+
binaryBytes = 0;
|
|
61
|
+
name;
|
|
62
|
+
inputs;
|
|
63
|
+
constructor(quickJs, opts) {
|
|
64
|
+
const { name, code, log } = opts;
|
|
65
|
+
this.name = name;
|
|
66
|
+
this.inputs = opts.inputs;
|
|
67
|
+
this.guest = new QuickJsGuest(quickJs, {
|
|
68
|
+
name,
|
|
69
|
+
code,
|
|
70
|
+
file: 'assets.js',
|
|
71
|
+
limits: ASSET_LIMITS,
|
|
72
|
+
apiGlobal: '__gsAssets',
|
|
73
|
+
host: { __gsAssetsHost: this.capabilities() },
|
|
74
|
+
log,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
games() {
|
|
78
|
+
const games = this.guest.call('games', []);
|
|
79
|
+
if (!Array.isArray(games) || !games.every(g => typeof g === 'string')) {
|
|
80
|
+
throw new Error(`${this.name}: games() returned no list of ids`);
|
|
81
|
+
}
|
|
82
|
+
return games;
|
|
83
|
+
}
|
|
84
|
+
list(gameId, pick) {
|
|
85
|
+
const raw = this.guest.call('listAssets', [
|
|
86
|
+
gameId,
|
|
87
|
+
JSON.stringify(this.inputs.describe()),
|
|
88
|
+
pick,
|
|
89
|
+
]);
|
|
90
|
+
if (typeof raw !== 'string')
|
|
91
|
+
throw new Error(`${this.name}: listAssets returned no text`);
|
|
92
|
+
return AssetListSchema.parse(JSON.parse(raw));
|
|
93
|
+
}
|
|
94
|
+
build(gameId, id) {
|
|
95
|
+
this.binaries = [];
|
|
96
|
+
this.binaryBytes = 0;
|
|
97
|
+
const raw = this.guest.call('buildAsset', [
|
|
98
|
+
gameId,
|
|
99
|
+
id,
|
|
100
|
+
JSON.stringify(this.inputs.describe()),
|
|
101
|
+
]);
|
|
102
|
+
if (typeof raw !== 'string')
|
|
103
|
+
throw new Error(`${this.name}: buildAsset returned no text`);
|
|
104
|
+
const parsed = JSON.parse(raw);
|
|
105
|
+
const { outputs } = AssetResultSchema.parse({ outputs: parsed });
|
|
106
|
+
return { outputs, binaries: this.binaries };
|
|
107
|
+
}
|
|
108
|
+
dispose() {
|
|
109
|
+
this.guest.dispose();
|
|
110
|
+
}
|
|
111
|
+
capabilities() {
|
|
112
|
+
const vm = () => this.guest.vm;
|
|
113
|
+
return {
|
|
114
|
+
inputRead: (handle, offset, length) => {
|
|
115
|
+
const bytes = this.inputs.read(vm().getNumber(handle), vm().getNumber(offset), vm().getNumber(length));
|
|
116
|
+
return vm().newArrayBuffer(bytes.buffer);
|
|
117
|
+
},
|
|
118
|
+
emitBinary: data => {
|
|
119
|
+
const lifetime = vm().getArrayBuffer(data);
|
|
120
|
+
const bytes = lifetime.value.slice();
|
|
121
|
+
lifetime.dispose();
|
|
122
|
+
this.binaryBytes += bytes.length;
|
|
123
|
+
if (this.binaryBytes > ASSET_LIMITS.maxOutputBytes) {
|
|
124
|
+
throw new Error('this asset is over its output quota');
|
|
125
|
+
}
|
|
126
|
+
this.binaries.push(bytes);
|
|
127
|
+
return vm().newNumber(this.binaries.length - 1);
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* `@gameslate/sdk/host` (Node only): the plugin sandbox exactly as the GameSlate core runs it. The
|
|
3
|
+
* core loads plugins through it; plugin repos use it to test their bundles the way the core will.
|
|
4
|
+
*/
|
|
5
|
+
export * from './quickjs-guest.js';
|
|
6
|
+
export * from './live-sandbox.js';
|
|
7
|
+
export * from './asset-sandbox.js';
|
|
8
|
+
export * from './inspect.js';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
|
|
2
|
+
import { type PluginManifest } from '../plugin-manifest.js';
|
|
3
|
+
import type { PluginModule } from '../plugin/index.js';
|
|
4
|
+
export type ManifestResult = {
|
|
5
|
+
manifest: PluginManifest;
|
|
6
|
+
} | {
|
|
7
|
+
problem: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function readPluginManifest(dir: string): ManifestResult;
|
|
10
|
+
export interface InspectedPlugin {
|
|
11
|
+
manifest: PluginManifest;
|
|
12
|
+
/** the live code running in its sandbox, as the core uses it */
|
|
13
|
+
live: PluginModule;
|
|
14
|
+
/** the asset code and the games it extracts for (jobs load it again per run) */
|
|
15
|
+
assets: {
|
|
16
|
+
code: string;
|
|
17
|
+
games: string[];
|
|
18
|
+
} | null;
|
|
19
|
+
/** things that don't stop it loading (built for other core versions) */
|
|
20
|
+
warnings: string[];
|
|
21
|
+
}
|
|
22
|
+
export interface InspectOptions {
|
|
23
|
+
/** the core version it will run in; others it was tested with become a warning */
|
|
24
|
+
coreVersion: string;
|
|
25
|
+
log: (line: string) => void;
|
|
26
|
+
}
|
|
27
|
+
/** Everything the core checks before running a plugin; the reason it can't, as a string. */
|
|
28
|
+
export declare function inspectPlugin(quickJs: QuickJSWASMModule, dir: string, manifest: PluginManifest, opts: InspectOptions): InspectedPlugin | string;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { PluginManifestSchema, SDK_API } from '../plugin-manifest.js';
|
|
5
|
+
import { AssetSandbox, InputSet } from './asset-sandbox.js';
|
|
6
|
+
import { PluginSandbox } from './live-sandbox.js';
|
|
7
|
+
export function readPluginManifest(dir) {
|
|
8
|
+
let raw;
|
|
9
|
+
try {
|
|
10
|
+
raw = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
|
|
11
|
+
}
|
|
12
|
+
catch (e) {
|
|
13
|
+
return {
|
|
14
|
+
problem: `unreadable manifest.json (${e instanceof Error ? e.message : String(e)})`,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const parsed = PluginManifestSchema.safeParse(raw);
|
|
18
|
+
if (parsed.success)
|
|
19
|
+
return { manifest: parsed.data };
|
|
20
|
+
const issues = parsed.error.issues.map(i => `${i.path.join('.')} ${i.message}`).join('; ');
|
|
21
|
+
return { problem: `invalid manifest: ${issues}` };
|
|
22
|
+
}
|
|
23
|
+
/** Why a code file can't be trusted (missing, or not the file the manifest hashed), or null. */
|
|
24
|
+
function codeProblem(dir, code) {
|
|
25
|
+
const file = path.join(dir, code.file);
|
|
26
|
+
if (!fs.existsSync(file))
|
|
27
|
+
return `code file ${code.file} is missing`;
|
|
28
|
+
const sha = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
29
|
+
return sha === code.sha256 ? null : `${code.file} doesn't match its hash`;
|
|
30
|
+
}
|
|
31
|
+
function describedProblem(manifest, d) {
|
|
32
|
+
if (d.id !== manifest.id)
|
|
33
|
+
return `its code says it is ${d.id}`;
|
|
34
|
+
const games = new Set(manifest.games.map(g => g.id));
|
|
35
|
+
const stray = [...d.sources.map(s => s.gameId), ...d.packs.map(p => p.id)].filter(id => !games.has(id));
|
|
36
|
+
return stray.length
|
|
37
|
+
? `its code covers games its manifest doesn't list (${stray.join(', ')})`
|
|
38
|
+
: null;
|
|
39
|
+
}
|
|
40
|
+
function loadLive(quickJs, dir, manifest, log) {
|
|
41
|
+
const code = fs.readFileSync(path.join(dir, manifest.code.file), 'utf8');
|
|
42
|
+
const sandbox = new PluginSandbox(quickJs, code, manifest.id, log);
|
|
43
|
+
try {
|
|
44
|
+
const description = sandbox.describe();
|
|
45
|
+
const problem = describedProblem(manifest, description);
|
|
46
|
+
if (!problem)
|
|
47
|
+
return sandbox.module(description);
|
|
48
|
+
sandbox.dispose();
|
|
49
|
+
return problem;
|
|
50
|
+
}
|
|
51
|
+
catch (e) {
|
|
52
|
+
sandbox.dispose();
|
|
53
|
+
throw e;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function loadAssets(quickJs, dir, manifest, log) {
|
|
57
|
+
if (!manifest.assets)
|
|
58
|
+
return null;
|
|
59
|
+
const code = fs.readFileSync(path.join(dir, manifest.assets.file), 'utf8');
|
|
60
|
+
const inputs = new InputSet([]);
|
|
61
|
+
const sandbox = new AssetSandbox(quickJs, { name: manifest.id, code, inputs, log });
|
|
62
|
+
try {
|
|
63
|
+
const games = sandbox.games();
|
|
64
|
+
const listed = new Set(manifest.games.map(g => g.id));
|
|
65
|
+
const stray = games.filter(g => !listed.has(g));
|
|
66
|
+
return stray.length
|
|
67
|
+
? `its asset code covers games its manifest doesn't list (${stray.join(', ')})`
|
|
68
|
+
: { code, games };
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
sandbox.dispose();
|
|
72
|
+
inputs.close();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Everything the core checks before running a plugin; the reason it can't, as a string. */
|
|
76
|
+
export function inspectPlugin(quickJs, dir, manifest, opts) {
|
|
77
|
+
if (manifest.sdkApi !== SDK_API) {
|
|
78
|
+
return `built for plugin contract ${manifest.sdkApi}, this core speaks ${SDK_API}`;
|
|
79
|
+
}
|
|
80
|
+
const bad = [manifest.code, manifest.assets, manifest.extract]
|
|
81
|
+
.flatMap(code => (code ? [codeProblem(dir, code)] : []))
|
|
82
|
+
.find(reason => reason !== null);
|
|
83
|
+
if (bad)
|
|
84
|
+
return bad;
|
|
85
|
+
const warnings = manifest.testedWith.includes(opts.coreVersion)
|
|
86
|
+
? []
|
|
87
|
+
: [
|
|
88
|
+
`${manifest.id} ${manifest.version} wasn't tested with core ${opts.coreVersion} (tested: ${manifest.testedWith.join(', ') || 'none'}); it may not work`,
|
|
89
|
+
];
|
|
90
|
+
const live = loadLive(quickJs, dir, manifest, opts.log);
|
|
91
|
+
if (typeof live === 'string')
|
|
92
|
+
return live;
|
|
93
|
+
const assets = loadAssets(quickJs, dir, manifest, opts.log);
|
|
94
|
+
if (typeof assets === 'string')
|
|
95
|
+
return assets;
|
|
96
|
+
return { manifest, live, assets, warnings };
|
|
97
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
|
|
2
|
+
import { type SandboxDescription } from '../index.js';
|
|
3
|
+
import type { PluginModule } from '../plugin/index.js';
|
|
4
|
+
export { loadQuickJs } from './quickjs-guest.js';
|
|
5
|
+
export declare const SANDBOX_LIMITS: {
|
|
6
|
+
readonly memoryBytes: number;
|
|
7
|
+
readonly stackBytes: number;
|
|
8
|
+
readonly loadMs: 3000;
|
|
9
|
+
readonly callMs: 250;
|
|
10
|
+
/** the largest single memory read a plugin may ask for */
|
|
11
|
+
readonly maxReadBytes: number;
|
|
12
|
+
};
|
|
13
|
+
/** One plugin's live code in its own runtime. */
|
|
14
|
+
export declare class PluginSandbox {
|
|
15
|
+
private readonly name;
|
|
16
|
+
private readonly log;
|
|
17
|
+
private readonly guest;
|
|
18
|
+
private readonly memories;
|
|
19
|
+
private nextHandle;
|
|
20
|
+
private readonly viewsCache;
|
|
21
|
+
constructor(quickJs: QuickJSWASMModule, code: string, name: string, log: (line: string) => void);
|
|
22
|
+
describe(): SandboxDescription;
|
|
23
|
+
/** The plugin as the core uses it: sources and packs whose code runs in here. */
|
|
24
|
+
module(description: SandboxDescription): PluginModule;
|
|
25
|
+
dispose(): void;
|
|
26
|
+
private call;
|
|
27
|
+
private source;
|
|
28
|
+
private pack;
|
|
29
|
+
private createSession;
|
|
30
|
+
/** One poll's state, checked against the schema (a plugin can't hand the UI anything else). */
|
|
31
|
+
private poll;
|
|
32
|
+
private views;
|
|
33
|
+
private memory;
|
|
34
|
+
/** `__gsHost`: the plugin's only capabilities, memory reads on the games it was given. */
|
|
35
|
+
private memoryCapabilities;
|
|
36
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { GameStateSchema, PackViewsSchema, SandboxDescriptionSchema, } from '../index.js';
|
|
2
|
+
import { errorText, QuickJsGuest } from './quickjs-guest.js';
|
|
3
|
+
export { loadQuickJs } from './quickjs-guest.js';
|
|
4
|
+
/*
|
|
5
|
+
* The live sandbox (docs/plugin-architecture.md § The sandbox): each plugin's live code (packs and
|
|
6
|
+
* memory sources) in its own QuickJS runtime. Its only capabilities are memory reads, for games
|
|
7
|
+
* the core has already attached to, and whatever comes back (states, views, its description) is
|
|
8
|
+
* validated before the core uses it.
|
|
9
|
+
*
|
|
10
|
+
* Calls run on the daemon's thread: a poll costs well under a millisecond (the spike measured
|
|
11
|
+
* 0.26 ms) and the budget bounds the worst case. A plugin that breaks a limit is switched off, so
|
|
12
|
+
* a stall happens at most once per plugin.
|
|
13
|
+
*/
|
|
14
|
+
export const SANDBOX_LIMITS = {
|
|
15
|
+
/* the real plugins use about 3.5 MB after loading */
|
|
16
|
+
memoryBytes: 32 * 1024 * 1024,
|
|
17
|
+
stackBytes: 1024 * 1024,
|
|
18
|
+
loadMs: 3000,
|
|
19
|
+
callMs: 250,
|
|
20
|
+
/** the largest single memory read a plugin may ask for */
|
|
21
|
+
maxReadBytes: 16 * 1024 * 1024,
|
|
22
|
+
};
|
|
23
|
+
/** One plugin's live code in its own runtime. */
|
|
24
|
+
export class PluginSandbox {
|
|
25
|
+
name;
|
|
26
|
+
log;
|
|
27
|
+
guest;
|
|
28
|
+
memories = new Map();
|
|
29
|
+
nextHandle = 1;
|
|
30
|
+
/* each state's views, so a pack's three view accessors cost one call */
|
|
31
|
+
viewsCache = new WeakMap();
|
|
32
|
+
constructor(quickJs, code, name, log) {
|
|
33
|
+
this.name = name;
|
|
34
|
+
this.log = log;
|
|
35
|
+
this.guest = new QuickJsGuest(quickJs, {
|
|
36
|
+
name,
|
|
37
|
+
code,
|
|
38
|
+
file: 'live.js',
|
|
39
|
+
limits: SANDBOX_LIMITS,
|
|
40
|
+
apiGlobal: '__gs',
|
|
41
|
+
host: { __gsHost: this.memoryCapabilities() },
|
|
42
|
+
log,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
describe() {
|
|
46
|
+
const raw = this.call('describe', []);
|
|
47
|
+
if (typeof raw !== 'string')
|
|
48
|
+
throw new Error(`${this.name}: describe() returned no text`);
|
|
49
|
+
return SandboxDescriptionSchema.parse(JSON.parse(raw));
|
|
50
|
+
}
|
|
51
|
+
/** The plugin as the core uses it: sources and packs whose code runs in here. */
|
|
52
|
+
module(description) {
|
|
53
|
+
return {
|
|
54
|
+
id: description.id,
|
|
55
|
+
sources: description.sources.map(s => this.source(s)),
|
|
56
|
+
packs: description.packs.map(data => this.pack(data)),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
dispose() {
|
|
60
|
+
this.guest.dispose();
|
|
61
|
+
}
|
|
62
|
+
call(fn, args) {
|
|
63
|
+
return this.guest.call(fn, args);
|
|
64
|
+
}
|
|
65
|
+
source(s) {
|
|
66
|
+
return {
|
|
67
|
+
gameId: s.gameId,
|
|
68
|
+
stateSchemaVersion: s.stateSchemaVersion,
|
|
69
|
+
capabilities: s.capabilities,
|
|
70
|
+
supportedBuildIds: new Map(s.supportedBuildIds),
|
|
71
|
+
executableHints: s.executableHints,
|
|
72
|
+
...(s.wrapperMayOmitStats ? { wrapperMayOmitStats: s.wrapperMayOmitStats } : {}),
|
|
73
|
+
...(s.unsupportedExecutables
|
|
74
|
+
? { unsupportedExecutables: s.unsupportedExecutables }
|
|
75
|
+
: {}),
|
|
76
|
+
createSession: memory => this.createSession(s.gameId, memory),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
pack(data) {
|
|
80
|
+
const views = (state) => this.views(data.id, state);
|
|
81
|
+
return {
|
|
82
|
+
...data,
|
|
83
|
+
describeState: state => views(state).facts,
|
|
84
|
+
ui: {
|
|
85
|
+
statusStrip: state => views(state).statusStrip,
|
|
86
|
+
timelines: state => views(state).timelines,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
createSession(gameId, memory) {
|
|
91
|
+
const handle = this.nextHandle++;
|
|
92
|
+
this.memories.set(handle, memory);
|
|
93
|
+
const info = {
|
|
94
|
+
buildId: memory.buildId,
|
|
95
|
+
commandLine: [...memory.commandLine],
|
|
96
|
+
moduleBase: memory.moduleBase.toString(),
|
|
97
|
+
};
|
|
98
|
+
let started = false;
|
|
99
|
+
try {
|
|
100
|
+
started = this.call('createSession', [gameId, handle, JSON.stringify(info)]) === true;
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
this.log(`[plugins] ${this.name}: ${gameId} session failed to start: ${errorText(e)}`);
|
|
104
|
+
}
|
|
105
|
+
if (!started) {
|
|
106
|
+
this.memories.delete(handle);
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
let lastProblem = null;
|
|
110
|
+
const report = (problem) => {
|
|
111
|
+
if (problem !== lastProblem)
|
|
112
|
+
this.log(`[plugins] ${this.name}: ${gameId}: ${problem}`);
|
|
113
|
+
lastProblem = problem;
|
|
114
|
+
};
|
|
115
|
+
return {
|
|
116
|
+
poll: () => {
|
|
117
|
+
try {
|
|
118
|
+
const state = this.poll(handle);
|
|
119
|
+
lastProblem = null;
|
|
120
|
+
return state;
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
report(errorText(e));
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
close: () => {
|
|
128
|
+
try {
|
|
129
|
+
this.call('closeSession', [handle]);
|
|
130
|
+
}
|
|
131
|
+
catch (e) {
|
|
132
|
+
report(`close failed: ${errorText(e)}`);
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
this.memories.delete(handle);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/** One poll's state, checked against the schema (a plugin can't hand the UI anything else). */
|
|
141
|
+
poll(handle) {
|
|
142
|
+
const raw = this.call('poll', [handle]);
|
|
143
|
+
if (raw === null)
|
|
144
|
+
return null;
|
|
145
|
+
if (typeof raw !== 'string')
|
|
146
|
+
throw new Error('poll returned no state text');
|
|
147
|
+
const parsed = GameStateSchema.safeParse(JSON.parse(raw));
|
|
148
|
+
if (!parsed.success) {
|
|
149
|
+
const issue = parsed.error.issues[0];
|
|
150
|
+
throw new Error(`invalid state (${issue?.path.join('.')}: ${issue?.message})`);
|
|
151
|
+
}
|
|
152
|
+
return parsed.data;
|
|
153
|
+
}
|
|
154
|
+
views(gameId, state) {
|
|
155
|
+
const cached = this.viewsCache.get(state);
|
|
156
|
+
if (cached)
|
|
157
|
+
return cached;
|
|
158
|
+
const raw = this.call('views', [gameId, JSON.stringify(state)]);
|
|
159
|
+
if (typeof raw !== 'string')
|
|
160
|
+
throw new Error(`${this.name}: views returned no text`);
|
|
161
|
+
const views = PackViewsSchema.parse(JSON.parse(raw));
|
|
162
|
+
this.viewsCache.set(state, views);
|
|
163
|
+
return views;
|
|
164
|
+
}
|
|
165
|
+
memory(handle) {
|
|
166
|
+
const memory = this.memories.get(this.guest.vm.getNumber(handle));
|
|
167
|
+
if (!memory)
|
|
168
|
+
throw new Error('no such memory handle');
|
|
169
|
+
return memory;
|
|
170
|
+
}
|
|
171
|
+
/** `__gsHost`: the plugin's only capabilities, memory reads on the games it was given. */
|
|
172
|
+
memoryCapabilities() {
|
|
173
|
+
const vm = () => this.guest.vm;
|
|
174
|
+
return {
|
|
175
|
+
read: (handle, address, length) => {
|
|
176
|
+
const memory = this.memory(handle);
|
|
177
|
+
const byteLength = vm().getNumber(length);
|
|
178
|
+
if (!Number.isInteger(byteLength) || byteLength <= 0)
|
|
179
|
+
return vm().undefined;
|
|
180
|
+
if (byteLength > SANDBOX_LIMITS.maxReadBytes) {
|
|
181
|
+
throw new Error(`a read of ${byteLength} bytes is over the limit`);
|
|
182
|
+
}
|
|
183
|
+
const bytes = memory.read(BigInt(vm().getString(address)), byteLength);
|
|
184
|
+
return bytes ? vm().newArrayBuffer(bytes.data.slice().buffer) : vm().undefined;
|
|
185
|
+
},
|
|
186
|
+
isValidRange: (handle, address, length) => this.memory(handle).isValidRange(BigInt(vm().getString(address)), vm().getNumber(length))
|
|
187
|
+
? vm().true
|
|
188
|
+
: vm().false,
|
|
189
|
+
resolveSymbol: (handle, name) => {
|
|
190
|
+
const at = this.memory(handle).resolveSymbol(vm().getString(name));
|
|
191
|
+
return at === null ? vm().null : vm().newString(at.toString());
|
|
192
|
+
},
|
|
193
|
+
refreshMappings: handle => {
|
|
194
|
+
this.memory(handle).refreshMappings();
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type QuickJSContext, type QuickJSHandle, type QuickJSWASMModule } from 'quickjs-emscripten-core';
|
|
2
|
+
/** The QuickJS engine: the copy next to the daemon's bundle, else the installed package's. */
|
|
3
|
+
export declare function loadQuickJs(): Promise<QuickJSWASMModule>;
|
|
4
|
+
export interface GuestLimits {
|
|
5
|
+
memoryBytes: number;
|
|
6
|
+
stackBytes: number;
|
|
7
|
+
loadMs: number;
|
|
8
|
+
callMs: number;
|
|
9
|
+
}
|
|
10
|
+
export type HostFunction = (...args: QuickJSHandle[]) => QuickJSHandle | void;
|
|
11
|
+
export declare const errorText: (e: unknown) => string;
|
|
12
|
+
export declare class QuickJsGuest {
|
|
13
|
+
private readonly opts;
|
|
14
|
+
readonly vm: QuickJSContext;
|
|
15
|
+
private readonly runtime;
|
|
16
|
+
private readonly api;
|
|
17
|
+
private disabled;
|
|
18
|
+
constructor(quickJs: QuickJSWASMModule, opts: {
|
|
19
|
+
name: string;
|
|
20
|
+
code: string;
|
|
21
|
+
file: string;
|
|
22
|
+
limits: GuestLimits;
|
|
23
|
+
/** the global the guest's entry sets (`exposeToHost` → `__gs`) */
|
|
24
|
+
apiGlobal: string;
|
|
25
|
+
/** host functions, by global object name (the guest's only capabilities) */
|
|
26
|
+
host: Record<string, Record<string, HostFunction>>;
|
|
27
|
+
log: (line: string) => void;
|
|
28
|
+
});
|
|
29
|
+
/** Calls a guest function within the budget; its JSON-able result, dumped to the host. */
|
|
30
|
+
call(fn: string, args: ReadonlyArray<string | number>): unknown;
|
|
31
|
+
dispose(): void;
|
|
32
|
+
private disable;
|
|
33
|
+
private callGuest;
|
|
34
|
+
private withBudget;
|
|
35
|
+
private guestError;
|
|
36
|
+
private install;
|
|
37
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import releaseSync from '@jitl/quickjs-wasmfile-release-sync';
|
|
6
|
+
import { newQuickJSWASMModuleFromVariant, newVariant, shouldInterruptAfterDeadline, } from 'quickjs-emscripten-core';
|
|
7
|
+
/*
|
|
8
|
+
* One piece of plugin code in its own QuickJS runtime (WebAssembly): no file system, network,
|
|
9
|
+
* process or module loader, only the host functions the caller installs. Every call has a time
|
|
10
|
+
* budget and the runtime a memory cap. A guest that runs out of memory, is interrupted or overruns
|
|
11
|
+
* its budget is switched off for good: its next call fails at once.
|
|
12
|
+
*/
|
|
13
|
+
const WASM_FILE = 'quickjs.wasm';
|
|
14
|
+
/** The QuickJS engine: the copy next to the daemon's bundle, else the installed package's. */
|
|
15
|
+
export async function loadQuickJs() {
|
|
16
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
17
|
+
const bundled = path.join(here, WASM_FILE);
|
|
18
|
+
const file = fs.existsSync(bundled)
|
|
19
|
+
? bundled
|
|
20
|
+
: path.join(path.dirname(createRequire(import.meta.url).resolve('@jitl/quickjs-wasmfile-release-sync/package.json')), 'dist/emscripten-module.wasm');
|
|
21
|
+
const bytes = fs.readFileSync(file);
|
|
22
|
+
const wasmBinary = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
23
|
+
return newQuickJSWASMModuleFromVariant(newVariant(releaseSync, { wasmBinary }));
|
|
24
|
+
}
|
|
25
|
+
export const errorText = (e) => (e instanceof Error ? e.message : String(e));
|
|
26
|
+
export class QuickJsGuest {
|
|
27
|
+
opts;
|
|
28
|
+
vm;
|
|
29
|
+
runtime;
|
|
30
|
+
api;
|
|
31
|
+
disabled = null;
|
|
32
|
+
constructor(quickJs, opts) {
|
|
33
|
+
this.opts = opts;
|
|
34
|
+
this.runtime = quickJs.newRuntime();
|
|
35
|
+
this.runtime.setMemoryLimit(opts.limits.memoryBytes);
|
|
36
|
+
this.runtime.setMaxStackSize(opts.limits.stackBytes);
|
|
37
|
+
this.vm = this.runtime.newContext();
|
|
38
|
+
try {
|
|
39
|
+
for (const [global, fns] of Object.entries(opts.host))
|
|
40
|
+
this.install(global, fns);
|
|
41
|
+
this.withBudget(opts.limits.loadMs, () => {
|
|
42
|
+
const loaded = this.vm.evalCode(opts.code, `${opts.name}/${opts.file}`);
|
|
43
|
+
if (loaded.error)
|
|
44
|
+
throw this.guestError('loading', loaded.error);
|
|
45
|
+
loaded.value.dispose();
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
this.vm.dispose();
|
|
50
|
+
this.runtime.dispose();
|
|
51
|
+
throw e;
|
|
52
|
+
}
|
|
53
|
+
this.api = this.vm.getProp(this.vm.global, opts.apiGlobal);
|
|
54
|
+
if (this.vm.typeof(this.api) !== 'object') {
|
|
55
|
+
this.dispose();
|
|
56
|
+
throw new Error(`${opts.name}: its ${opts.file} didn't expose itself to the core`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Calls a guest function within the budget; its JSON-able result, dumped to the host. */
|
|
60
|
+
call(fn, args) {
|
|
61
|
+
if (this.disabled)
|
|
62
|
+
throw new Error(`${this.opts.name} is switched off: ${this.disabled}`);
|
|
63
|
+
const started = Date.now();
|
|
64
|
+
try {
|
|
65
|
+
return this.withBudget(this.opts.limits.callMs, () => this.callGuest(fn, args));
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
const message = errorText(e);
|
|
69
|
+
if (/interrupted|out of memory|stack overflow/i.test(message))
|
|
70
|
+
this.disable(message);
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
const ms = Date.now() - started;
|
|
75
|
+
const budget = this.opts.limits.callMs;
|
|
76
|
+
if (!this.disabled && ms > budget * 2) {
|
|
77
|
+
this.disable(`${fn} took ${ms} ms (budget ${budget} ms)`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
dispose() {
|
|
82
|
+
if (this.api.alive)
|
|
83
|
+
this.api.dispose();
|
|
84
|
+
this.vm.dispose();
|
|
85
|
+
this.runtime.dispose();
|
|
86
|
+
}
|
|
87
|
+
disable(reason) {
|
|
88
|
+
this.disabled = reason;
|
|
89
|
+
this.opts.log(`[plugins] ${this.opts.name} broke a sandbox limit and is off until restart: ${reason}`);
|
|
90
|
+
}
|
|
91
|
+
callGuest(fn, args) {
|
|
92
|
+
const vm = this.vm;
|
|
93
|
+
const fnHandle = vm.getProp(this.api, fn);
|
|
94
|
+
const argHandles = args.map(a => typeof a === 'string' ? vm.newString(a) : vm.newNumber(a));
|
|
95
|
+
const result = vm.callFunction(fnHandle, this.api, ...argHandles);
|
|
96
|
+
fnHandle.dispose();
|
|
97
|
+
argHandles.forEach(h => h.dispose());
|
|
98
|
+
if (result.error)
|
|
99
|
+
throw this.guestError(fn, result.error);
|
|
100
|
+
const value = vm.dump(result.value);
|
|
101
|
+
result.value.dispose();
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
withBudget(ms, run) {
|
|
105
|
+
this.runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + ms));
|
|
106
|
+
try {
|
|
107
|
+
return run();
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
this.runtime.removeInterruptHandler();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
guestError(what, error) {
|
|
114
|
+
const dumped = this.vm.dump(error);
|
|
115
|
+
error.dispose();
|
|
116
|
+
const message = typeof dumped === 'object' && dumped !== null && 'message' in dumped
|
|
117
|
+
? String(dumped.message)
|
|
118
|
+
: String(dumped);
|
|
119
|
+
return new Error(`${this.opts.name}: ${what}: ${message}`);
|
|
120
|
+
}
|
|
121
|
+
install(global, fns) {
|
|
122
|
+
const vm = this.vm;
|
|
123
|
+
const host = vm.newObject();
|
|
124
|
+
for (const [name, impl] of Object.entries(fns)) {
|
|
125
|
+
const fn = vm.newFunction(name, impl);
|
|
126
|
+
vm.setProp(host, name, fn);
|
|
127
|
+
fn.dispose();
|
|
128
|
+
}
|
|
129
|
+
vm.setProp(vm.global, global, host);
|
|
130
|
+
host.dispose();
|
|
131
|
+
}
|
|
132
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gameslate/sdk",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
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",
|
|
@@ -20,7 +20,11 @@
|
|
|
20
20
|
"types": "./lib/plugin/index.d.ts",
|
|
21
21
|
"default": "./lib/plugin/index.js"
|
|
22
22
|
},
|
|
23
|
-
"./build": "./build/build-plugin.mjs"
|
|
23
|
+
"./build": "./build/build-plugin.mjs",
|
|
24
|
+
"./host": {
|
|
25
|
+
"types": "./lib/host/index.d.ts",
|
|
26
|
+
"default": "./lib/host/index.js"
|
|
27
|
+
}
|
|
24
28
|
},
|
|
25
29
|
"bin": {
|
|
26
30
|
"gameslate-plugin": "./bin/gameslate-plugin.mjs"
|
|
@@ -43,14 +47,20 @@
|
|
|
43
47
|
"types": "./lib/plugin/index.d.ts",
|
|
44
48
|
"default": "./lib/plugin/index.js"
|
|
45
49
|
},
|
|
46
|
-
"./build": "./build/build-plugin.mjs"
|
|
50
|
+
"./build": "./build/build-plugin.mjs",
|
|
51
|
+
"./host": {
|
|
52
|
+
"types": "./lib/host/index.d.ts",
|
|
53
|
+
"default": "./lib/host/index.js"
|
|
54
|
+
}
|
|
47
55
|
}
|
|
48
56
|
},
|
|
49
57
|
"scripts": {
|
|
50
58
|
"prepack": "yarn run -T tsc -p tsconfig.publish.json"
|
|
51
59
|
},
|
|
52
60
|
"dependencies": {
|
|
61
|
+
"@jitl/quickjs-wasmfile-release-sync": "0.31.0",
|
|
53
62
|
"esbuild": "^0.24.0",
|
|
63
|
+
"quickjs-emscripten-core": "0.31.0",
|
|
54
64
|
"zod": "^3.24.1"
|
|
55
65
|
}
|
|
56
66
|
}
|