devrock-gametests 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,71 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export const nodeHost = {
3
+ platform: process.platform,
4
+ arch: process.arch,
5
+ run(command, args) {
6
+ const result = spawnSync(command, args, { encoding: 'utf8', windowsHide: true });
7
+ if (result.error)
8
+ return { kind: 'spawn-failed', error: result.error };
9
+ return { kind: 'exited', status: result.status, stdout: result.stdout, stderr: result.stderr };
10
+ },
11
+ say: (message) => console.log(message),
12
+ };
13
+ const CANT = "Can't run the GameTests:";
14
+ const blocked = (reason, message) => ({ kind: 'blocked', reason, message });
15
+ /**
16
+ * Checks that Podman can run a server container, and starts a stopped Podman machine. It never creates
17
+ * a machine or installs anything.
18
+ */
19
+ export function preflight(host) {
20
+ const machine = podmanMachine(host);
21
+ return machine.kind === 'ready' ? reachable(host) : machine;
22
+ }
23
+ /** Ready once Podman answers through the connection it is set to use, which may not be the machine it lists. */
24
+ function reachable(host) {
25
+ const info = host.run('podman', ['info', '--format', '{{.Host.Arch}}']);
26
+ if (info.kind === 'exited' && info.status === 0)
27
+ return { kind: 'ready' };
28
+ const detail = info.kind === 'spawn-failed' ? info.error.message : info.stderr.trim();
29
+ return blocked('podman-unreachable', `${CANT} Podman can't reach its machine or service, so \`podman info\` failed. Fix the error below, then try again.\n${detail}`);
30
+ }
31
+ /** Checks the processor and that Podman is installed, and on Windows and macOS starts a stopped machine. */
32
+ function podmanMachine(host) {
33
+ if (host.arch !== 'x64') {
34
+ return blocked('unsupported-arch', `${CANT} the Bedrock Dedicated Server runs only on x86-64 processors, and this one is ${host.arch}.`);
35
+ }
36
+ const version = host.run('podman', ['--version']);
37
+ if (version.kind === 'spawn-failed') {
38
+ return blocked('podman-missing', `${CANT} Podman isn't installed. Install it from https://podman.io, then try again.`);
39
+ }
40
+ if (version.status !== 0)
41
+ throw new Error(`\`podman --version\` failed:\n${version.stderr.trim()}`);
42
+ if (host.platform === 'linux')
43
+ return { kind: 'ready' };
44
+ const list = host.run('podman', ['machine', 'list', '--format', 'json']);
45
+ if (list.kind === 'spawn-failed')
46
+ throw list.error;
47
+ if (list.status !== 0)
48
+ throw new Error(`\`podman machine list\` failed:\n${list.stderr.trim()}`);
49
+ const machines = JSON.parse(list.stdout);
50
+ const machine = machines.find((candidate) => candidate.Default) ?? machines[0];
51
+ if (machine === undefined) {
52
+ // Only checked here: an existing machine may use Hyper-V instead. Podman's own Windows provider treats a
53
+ // failing `wsl --status` as WSL not installed. The exit code is used because wsl.exe prints localized UTF-16.
54
+ if (host.platform === 'win32') {
55
+ const wsl = host.run('wsl', ['--status']);
56
+ if (wsl.kind === 'spawn-failed' || wsl.status !== 0) {
57
+ return blocked('wsl-missing', `${CANT} Podman needs WSL, which isn't installed. In a terminal opened as administrator, run \`wsl --install --no-distribution\`, restart the computer, then try again.`);
58
+ }
59
+ }
60
+ return blocked('no-machine', `${CANT} Podman has no machine. Run \`podman machine init\` (it downloads about 1 GB), then try again.`);
61
+ }
62
+ if (machine.Running)
63
+ return { kind: 'ready' };
64
+ host.say(`Starting the Podman machine ${machine.Name}...`);
65
+ const start = host.run('podman', ['machine', 'start', machine.Name]);
66
+ if (start.kind === 'spawn-failed' || start.status !== 0) {
67
+ const detail = start.kind === 'spawn-failed' ? start.error.message : start.stderr.trim();
68
+ return blocked('machine-start-failed', `${CANT} the Podman machine ${machine.Name} is stopped, and \`podman machine start ${machine.Name}\` failed. Fix the error below, then try again.\n${detail}`);
69
+ }
70
+ return { kind: 'ready' };
71
+ }
@@ -0,0 +1,43 @@
1
+ /** Everything a run needs to know about the project, read once from its `.devrock` folder. Paths are absolute. */
2
+ export interface Project {
3
+ readonly root: string;
4
+ readonly namespace: string;
5
+ readonly behaviorPack: string;
6
+ readonly resourcePack: string;
7
+ /** The Bedrock Dedicated Server version the tests run on, such as `1.26.66.1`. */
8
+ readonly serverVersion: string;
9
+ /** The GameTest entry, bundled into the test pack. */
10
+ readonly entry: string;
11
+ /** The argv that builds the add-on into its packs. It runs in `root`, without a shell. */
12
+ readonly build: readonly [string, ...string[]];
13
+ /** The test pack's template folder: its manifest.json and any other files the pack needs. */
14
+ readonly testPack: string;
15
+ /** The folder name the test pack gets in the world. */
16
+ readonly testPackFolder: string;
17
+ /** Passed to esbuild's `define` when the entry is bundled. */
18
+ readonly define: Readonly<Record<string, string>>;
19
+ /** The names BDS uses for our content in the content log: pack folders, `namespace:` and pack display names. */
20
+ readonly ourContent: readonly string[];
21
+ /** Downloads, the image's build context, the template world, the run folder and the logs. */
22
+ readonly workDir: string;
23
+ }
24
+ export declare const PROJECT_FILE = ".devrock/project.json";
25
+ export declare const GAMETESTS_FILE = ".devrock/gametests.json";
26
+ export declare const WORK_DIR = ".devrock-gametests";
27
+ /** Reads `.devrock/project.json` and `.devrock/gametests.json` under `root`. Throws naming the file and field. */
28
+ export declare function loadProject(projectRoot: string): Project;
29
+ /**
30
+ * The `entry` of the script module in `packDir`'s manifest, relative to the pack, or undefined if it has none. Throws
31
+ * if the entry points outside the pack, because the runner writes next to it.
32
+ */
33
+ export declare function readScriptEntry(packDir: string, root?: string): string | undefined;
34
+ /** What the runner reads from a pack manifest's header. */
35
+ export interface PackHeader {
36
+ readonly name: string;
37
+ readonly uuid: string;
38
+ /** `[major, minor, patch]`, as the world's pack lists want it. */
39
+ readonly version: readonly number[];
40
+ }
41
+ /** Reads the header of `packDir`'s manifest. Throws naming the manifest, from `root`, and the field. */
42
+ export declare function readPackHeader(packDir: string, root?: string): PackHeader;
43
+ export declare const isFile: (file: string) => boolean;
@@ -0,0 +1,204 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { transformSync } from 'esbuild';
4
+ export const PROJECT_FILE = '.devrock/project.json';
5
+ export const GAMETESTS_FILE = '.devrock/gametests.json';
6
+ export const WORK_DIR = '.devrock-gametests';
7
+ const VERSION_RE = /^\d+\.\d+\.\d+\.\d+$/;
8
+ /** Reads `.devrock/project.json` and `.devrock/gametests.json` under `root`. Throws naming the file and field. */
9
+ export function loadProject(projectRoot) {
10
+ const root = path.resolve(projectRoot);
11
+ const project = readConfig(root, PROJECT_FILE);
12
+ const gametests = readConfig(root, GAMETESTS_FILE);
13
+ // It names a folder in the world and prefixes ids, so it can't hold a path separator, a colon or a space.
14
+ const namespace = field(project, 'namespace', (value) => isString(value) && /^[A-Za-z0-9_.-]+$/.test(value), 'letters, digits, underscores, dots and hyphens, without the colon');
15
+ const behaviorPack = folder(root, project, 'behavior_pack', 'manifest.json');
16
+ const resourcePack = folder(root, project, 'resource_pack', 'manifest.json');
17
+ const serverVersion = field(gametests, 'serverVersion', (value) => isString(value) && VERSION_RE.test(value), 'a version like 1.26.66.1');
18
+ const entry = path.resolve(root, field(gametests, 'entry', isString, 'a path to the GameTest entry'));
19
+ if (!isFile(entry))
20
+ fail(gametests, 'entry', `names ${entry}, which isn't a file`);
21
+ const build = field(gametests, 'build', (value) => Array.isArray(value) && isString(value[0]) && value.every((part) => typeof part === 'string'), 'a non-empty array of strings, the command and its arguments');
22
+ const testPack = folder(root, gametests, 'testPack', 'manifest.json');
23
+ const define = field(gametests, 'define', (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).every(isString), 'an object whose values are strings');
24
+ const defines = (key, value) => {
25
+ try {
26
+ transformSync('', { define: { [key]: value } });
27
+ return true;
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ };
33
+ for (const [key, value] of Object.entries(define)) {
34
+ if (!defines(key, 'true')) {
35
+ fail(gametests, 'define', `has the key ${JSON.stringify(key)}, which isn't a JavaScript name like DEBUG or a.b`);
36
+ }
37
+ if (!defines(key, value)) {
38
+ fail(gametests, `define.${key}`, `must be a JavaScript literal or name, such as "true", not ${JSON.stringify(value)}`);
39
+ }
40
+ }
41
+ const testPackFolder = `${namespace}_test_bp`;
42
+ // Folder names compare in any letter case, because Windows and macOS file systems do.
43
+ if (path.basename(behaviorPack).toLowerCase() === testPackFolder.toLowerCase()) {
44
+ fail(project, 'behavior_pack', `names a folder called ${path.basename(behaviorPack)}, which is the name the test pack gets in the world. ` +
45
+ 'Rename the folder');
46
+ }
47
+ const packs = [behaviorPack, resourcePack, testPack];
48
+ const headers = packs.map((pack) => readPackHeader(pack, root));
49
+ if (readScriptEntry(testPack, root) !== 'scripts/main.js') {
50
+ fail(gametests, 'testPack', `names ${testPack}, whose manifest.json has no script module with the entry scripts/main.js`);
51
+ }
52
+ const dependencies = readModuleDependencies(testPack, root);
53
+ for (const module of ['@minecraft/server', '@minecraft/server-gametest']) {
54
+ const dependency = dependencies.find((each) => each.module === module);
55
+ if (dependency === undefined) {
56
+ fail(gametests, 'testPack', `names ${testPack}, whose manifest.json has no dependency on ${module}`);
57
+ }
58
+ }
59
+ for (const { module, versioned } of dependencies) {
60
+ if (!versioned) {
61
+ fail(gametests, 'testPack', `names ${testPack}, whose manifest.json depends on ${module} with no version`);
62
+ }
63
+ }
64
+ // The world lists packs by uuid, so two packs with one uuid load as one.
65
+ for (const [i, header] of headers.entries()) {
66
+ const j = headers.findIndex((other, k) => k > i && other.uuid.toLowerCase() === header.uuid.toLowerCase());
67
+ if (j !== -1) {
68
+ const shown = (pack) => path.relative(root, path.join(pack, 'manifest.json'));
69
+ throw new Error(`${shown(packs[i])} and ${shown(packs[j])} have the same header uuid, ${header.uuid}. Give each pack its own.`);
70
+ }
71
+ }
72
+ const ourContent = [
73
+ path.basename(behaviorPack),
74
+ path.basename(resourcePack),
75
+ testPackFolder,
76
+ `${namespace}:`,
77
+ ...packs.map((pack, i) => packName(pack, headers[i].name)),
78
+ ];
79
+ return {
80
+ root,
81
+ namespace,
82
+ behaviorPack,
83
+ resourcePack,
84
+ serverVersion,
85
+ entry,
86
+ build,
87
+ testPack,
88
+ testPackFolder,
89
+ define,
90
+ ourContent,
91
+ workDir: path.join(root, WORK_DIR),
92
+ };
93
+ }
94
+ function readConfig(root, file) {
95
+ const full = path.join(root, file);
96
+ if (!existsSync(full))
97
+ throw new Error(`${file} is missing from ${root}.`);
98
+ const value = readJson(full, file);
99
+ if (!isObject(value))
100
+ throw new Error(`${file} must hold a JSON object.`);
101
+ return { file, value };
102
+ }
103
+ const BYTE_ORDER_MARK = String.fromCodePoint(0xfeff);
104
+ const withoutByteOrderMark = (text) => (text.startsWith(BYTE_ORDER_MARK) ? text.slice(1) : text);
105
+ /** Parses a JSON file, after any byte order mark. Throws naming the file as `shown` if it isn't JSON. */
106
+ function readJson(file, shown) {
107
+ try {
108
+ return JSON.parse(withoutByteOrderMark(readFileSync(file, 'utf8')));
109
+ }
110
+ catch (error) {
111
+ throw new Error(`${shown} isn't valid JSON: ${error.message}`);
112
+ }
113
+ }
114
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
115
+ /** Each script module `packDir`'s manifest depends on, by `module_name`, and whether that dependency has a version. */
116
+ function readModuleDependencies(packDir, root) {
117
+ const file = path.join(packDir, 'manifest.json');
118
+ const manifest = readJson(file, path.relative(root, file));
119
+ const dependencies = isObject(manifest) && Array.isArray(manifest.dependencies) ? manifest.dependencies : [];
120
+ return dependencies.flatMap((dependency) => isObject(dependency) && isString(dependency.module_name)
121
+ ? [
122
+ {
123
+ module: dependency.module_name,
124
+ versioned: isString(dependency.version) || Array.isArray(dependency.version),
125
+ },
126
+ ]
127
+ : []);
128
+ }
129
+ /**
130
+ * The `entry` of the script module in `packDir`'s manifest, relative to the pack, or undefined if it has none. Throws
131
+ * if the entry points outside the pack, because the runner writes next to it.
132
+ */
133
+ export function readScriptEntry(packDir, root = process.cwd()) {
134
+ const file = path.join(packDir, 'manifest.json');
135
+ const shown = path.relative(root, file);
136
+ const manifest = readJson(file, shown);
137
+ const modules = isObject(manifest) && Array.isArray(manifest.modules) ? manifest.modules : [];
138
+ for (const module of modules) {
139
+ if (!isObject(module) || module.type !== 'script' || !isString(module.entry))
140
+ continue;
141
+ const inPack = path.relative(packDir, path.resolve(packDir, module.entry));
142
+ if (inPack === '' || inPack.startsWith('..') || path.isAbsolute(inPack)) {
143
+ throw new Error(`${shown} names the script entry ${module.entry}, which is outside the pack.`);
144
+ }
145
+ return module.entry;
146
+ }
147
+ return undefined;
148
+ }
149
+ /** A semantic version 2.0.0, which is what Bedrock reads a manifest's version string as. */
150
+ const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
151
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
152
+ /** Reads the header of `packDir`'s manifest. Throws naming the manifest, from `root`, and the field. */
153
+ export function readPackHeader(packDir, root = process.cwd()) {
154
+ const file = path.join(packDir, 'manifest.json');
155
+ const shown = path.relative(root, file);
156
+ const manifest = readJson(file, shown);
157
+ const header = isObject(manifest) ? manifest.header : undefined;
158
+ function wrong(name, problem) {
159
+ throw new Error(`${shown}: "${name}" ${problem}.`);
160
+ }
161
+ if (!isObject(header))
162
+ wrong('header', 'is missing. It must be an object with name, uuid and version');
163
+ const { name, uuid, version } = header;
164
+ if (!isString(name))
165
+ wrong('header.name', `must be a string, not ${JSON.stringify(name)}`);
166
+ if (!isString(uuid) || !UUID_RE.test(uuid)) {
167
+ wrong('header.uuid', `must be a UUID like "4227c987-8fb0-4a4f-a7a4-35b9bf7369af", not ${JSON.stringify(uuid)}`);
168
+ }
169
+ const parts = Array.isArray(version)
170
+ ? version
171
+ : SEMVER_RE.exec(String(version))?.slice(1, 4).map(Number);
172
+ const isPart = (part) => Number.isInteger(part) && Number(part) >= 0;
173
+ if (parts?.length !== 3 || !parts.every(isPart)) {
174
+ wrong('header.version', `must be a version like "1.0.0" or [1, 0, 0], not ${JSON.stringify(version)}`);
175
+ }
176
+ return { name, uuid, version: parts };
177
+ }
178
+ function fail(config, name, problem) {
179
+ throw new Error(`${config.file}: "${name}" ${problem}.`);
180
+ }
181
+ function field(config, name, valid, expected) {
182
+ if (!(name in config.value))
183
+ fail(config, name, `is missing. It must be ${expected}`);
184
+ const value = config.value[name];
185
+ if (!valid(value))
186
+ fail(config, name, `must be ${expected}, not ${JSON.stringify(value)}`);
187
+ return value;
188
+ }
189
+ /** A folder field, resolved from `root`, that must hold `required`. */
190
+ function folder(root, config, name, required) {
191
+ const dir = path.resolve(root, field(config, name, isString, 'a path to a folder'));
192
+ if (!isFile(path.join(dir, required)))
193
+ fail(config, name, `names ${dir}, which has no ${required}`);
194
+ return dir;
195
+ }
196
+ const isString = (value) => typeof value === 'string' && value !== '';
197
+ export const isFile = (file) => existsSync(file) && statSync(file).isFile();
198
+ /** A pack's display name, from its header's `name`. A `pack.name` key is looked up in its en_US.lang. */
199
+ function packName(packDir, name) {
200
+ const lang = path.join(packDir, 'texts', 'en_US.lang');
201
+ if (name !== 'pack.name' || !existsSync(lang))
202
+ return name;
203
+ return /^pack\.name=(.*?)\s*$/m.exec(readFileSync(lang, 'utf8'))?.[1] ?? name;
204
+ }
@@ -0,0 +1,38 @@
1
+ export interface Registration {
2
+ /** The entry that registered the test, as it was passed to `listGameTests`. */
3
+ readonly file: string;
4
+ readonly className: string;
5
+ readonly name: string;
6
+ /** The batch the test named, or undefined when it runs in the default batch. */
7
+ batch?: string;
8
+ structure?: string;
9
+ /** The tick limit the test set, or undefined when it keeps GameTest's default. */
10
+ maxTicks?: number;
11
+ readonly tags: string[];
12
+ }
13
+ export interface ListOptions {
14
+ /** Passed to esbuild's `define`, for the build flags the entries read. */
15
+ readonly define?: Record<string, string>;
16
+ /** For `listGameTestsInWorker`: how long the entries get to finish loading. 30 seconds by default. */
17
+ readonly timeoutMs?: number;
18
+ /** The folder to make the listing's temporary folder in. The system's temporary folder by default. */
19
+ readonly tempRoot?: string;
20
+ /** Where the game modules' type definitions are looked up from, in node_modules there or above. The working directory by default. */
21
+ readonly root?: string;
22
+ }
23
+ /**
24
+ * The game's native script modules, the ones stock BDS lets a pack use. They exist only in the game, so a bundle
25
+ * leaves them external, and the listing stands each one in that the project installs.
26
+ */
27
+ export declare const GAME_MODULES: string[];
28
+ /**
29
+ * Every test the entries register, in the order they register them. Each entry is bundled on its own and
30
+ * imported once per call. The stand-ins resolve only for those bundles, and only during the call.
31
+ */
32
+ export declare function listGameTests(entries: readonly string[], options?: ListOptions): Promise<Registration[]>;
33
+ /**
34
+ * `listGameTests` in a worker thread, so an entry that never finishes loading outside the game can't hang the
35
+ * caller: a loop that awaits a stand-in never yields, and an await on something only the game settles never ends.
36
+ * Rejects if the entries haven't loaded after `options.timeoutMs`, or the worker stops without an answer.
37
+ */
38
+ export declare function listGameTestsInWorker(entries: readonly string[], options?: ListOptions): Promise<Registration[]>;
@@ -0,0 +1,194 @@
1
+ // Loads GameTest entries outside the game and records what each one registers.
2
+ //
3
+ // The game's own modules ship as type definitions only, so this stands a module in for each: every export is an
4
+ // object that accepts any property read, call, or `new`. `registerAsync` and `register` record the test instead of
5
+ // registering it. Nothing from the game runs, and no test body runs either.
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
8
+ import { registerHooks } from 'node:module';
9
+ import { tmpdir } from 'node:os';
10
+ import path from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { Worker } from 'node:worker_threads';
13
+ import { build } from 'esbuild';
14
+ /**
15
+ * The game's native script modules, the ones stock BDS lets a pack use. They exist only in the game, so a bundle
16
+ * leaves them external, and the listing stands each one in that the project installs.
17
+ */
18
+ export const GAME_MODULES = [
19
+ '@minecraft/server',
20
+ '@minecraft/server-ui',
21
+ '@minecraft/server-gametest',
22
+ '@minecraft/server-admin',
23
+ '@minecraft/server-editor',
24
+ '@minecraft/debug-utilities',
25
+ ];
26
+ const STAND_INS = GAME_MODULES;
27
+ const ANYTHING = `
28
+ const handler = {
29
+ get(_target, key) {
30
+ if (key === Symbol.toPrimitive) return () => 0;
31
+ // Not a promise: \`await\` must not wait on a stand-in.
32
+ if (key === 'then') return undefined;
33
+ return anything();
34
+ },
35
+ apply: () => anything(),
36
+ construct: () => anything(),
37
+ };
38
+ function anything() {
39
+ return new Proxy(function () {}, handler);
40
+ }
41
+ `;
42
+ const recorder = (key) => `
43
+ const recording = globalThis[Symbol.for(${JSON.stringify(key)})];
44
+ function record(className, name) {
45
+ const registration = { file: recording.file, className, name, tags: [] };
46
+ recording.registrations.push(registration);
47
+ const builder = new Proxy(
48
+ {},
49
+ {
50
+ get(_target, key) {
51
+ // Not a promise: \`await\` on a builder must not wait on it.
52
+ if (key === 'then') return undefined;
53
+ return (value) => {
54
+ if (key === 'batch') registration.batch = value;
55
+ if (key === 'structureName') registration.structure = value;
56
+ if (key === 'maxTicks') registration.maxTicks = value;
57
+ if (key === 'tag') registration.tags.push(value);
58
+ return builder;
59
+ };
60
+ },
61
+ },
62
+ );
63
+ return builder;
64
+ }
65
+ export const registerAsync = record;
66
+ export const register = record;
67
+ `;
68
+ /** Every name a module's type definitions export, so an `import { name }` of any of them resolves. */
69
+ function exportedNames(types) {
70
+ const names = [
71
+ ...types.matchAll(/^export (?:declare )?(?:class|enum|const|function|interface|type|namespace) (\w+)/gm),
72
+ ];
73
+ return [...new Set(names.map((match) => match[1]))];
74
+ }
75
+ /** The module's type definitions in the nearest node_modules that has them, from `from` up. */
76
+ function typesOf(module, from) {
77
+ for (let dir = from;; dir = path.dirname(dir)) {
78
+ const file = path.join(dir, 'node_modules', module, 'index.d.ts');
79
+ if (existsSync(file))
80
+ return file;
81
+ if (path.dirname(dir) === dir)
82
+ return undefined;
83
+ }
84
+ }
85
+ /** The stand-in's source, or undefined when the project doesn't install the module, so nothing can import it. */
86
+ function standIn(module, key, from) {
87
+ const typesFile = typesOf(module, from);
88
+ if (typesFile === undefined)
89
+ return undefined;
90
+ const recorded = module === '@minecraft/server-gametest' ? ['registerAsync', 'register'] : [];
91
+ const names = exportedNames(readFileSync(typesFile, 'utf8')).filter((name) => !recorded.includes(name));
92
+ const exports = names.map((name) => `export const ${name} = anything();`).join('\n');
93
+ return `${ANYTHING}${recorded.length > 0 ? recorder(key) : ''}${exports}\n`;
94
+ }
95
+ /**
96
+ * Every test the entries register, in the order they register them. Each entry is bundled on its own and
97
+ * imported once per call. The stand-ins resolve only for those bundles, and only during the call.
98
+ */
99
+ export async function listGameTests(entries, options = {}) {
100
+ const directory = await mkdtemp(path.join(options.tempRoot ?? tmpdir(), 'devrock-gametests-'));
101
+ const key = `devrock-gametests:${directory}`;
102
+ const recording = { file: '', registrations: [] };
103
+ const globals = globalThis;
104
+ globals[Symbol.for(key)] = recording;
105
+ const standIns = new Map();
106
+ const from = options.root ?? process.cwd();
107
+ for (const module of STAND_INS) {
108
+ const source = standIn(module, key, from);
109
+ if (source === undefined)
110
+ continue;
111
+ const file = path.join(directory, `${module.replace(/[@/]/g, '_')}.mjs`);
112
+ await writeFile(file, source);
113
+ standIns.set(module, pathToFileURL(file).href);
114
+ }
115
+ const bundles = new Set();
116
+ const hooks = registerHooks({
117
+ resolve: (specifier, context, nextResolve) => {
118
+ if (!bundles.has(context.parentURL ?? ''))
119
+ return nextResolve(specifier, context);
120
+ const url = standIns.get(specifier);
121
+ if (url !== undefined)
122
+ return { url, shortCircuit: true };
123
+ if (STAND_INS.includes(specifier)) {
124
+ throw new Error(`${specifier} isn't installed in the project, and the runner reads its type definitions to list the ` +
125
+ `tests. Run \`npm install --save-dev ${specifier}\`.`);
126
+ }
127
+ return nextResolve(specifier, context);
128
+ },
129
+ });
130
+ try {
131
+ for (const [index, entry] of entries.entries()) {
132
+ const bundle = path.join(directory, 'entries', `${index}.mjs`);
133
+ await mkdir(path.dirname(bundle), { recursive: true });
134
+ await build({
135
+ entryPoints: [entry],
136
+ outfile: bundle,
137
+ bundle: true,
138
+ format: 'esm',
139
+ platform: 'node',
140
+ external: STAND_INS,
141
+ define: options.define,
142
+ logLevel: 'silent',
143
+ });
144
+ const url = pathToFileURL(bundle).href;
145
+ bundles.add(url);
146
+ recording.file = entry;
147
+ await import(url);
148
+ }
149
+ }
150
+ finally {
151
+ hooks.deregister();
152
+ delete globals[Symbol.for(key)];
153
+ await rm(directory, { recursive: true, force: true });
154
+ }
155
+ return recording.registrations;
156
+ }
157
+ /**
158
+ * `listGameTests` in a worker thread, so an entry that never finishes loading outside the game can't hang the
159
+ * caller: a loop that awaits a stand-in never yields, and an await on something only the game settles never ends.
160
+ * Rejects if the entries haven't loaded after `options.timeoutMs`, or the worker stops without an answer.
161
+ */
162
+ export async function listGameTestsInWorker(entries, options = {}) {
163
+ // The worker's own cleanup never runs when it is stopped, so its files go in a folder this thread removes.
164
+ const tempRoot = await mkdtemp(path.join(tmpdir(), 'devrock-gametests-list-'));
165
+ try {
166
+ return await listInWorker(entries, { ...options, tempRoot });
167
+ }
168
+ finally {
169
+ await rm(tempRoot, { recursive: true, force: true });
170
+ }
171
+ }
172
+ function listInWorker(entries, options) {
173
+ const { timeoutMs = 30_000, ...listOptions } = options;
174
+ // Under tsx the sources run as .ts, and once built as .js.
175
+ const script = new URL(import.meta.url.endsWith('.ts') ? './list-worker.ts' : './list-worker.js', import.meta.url);
176
+ return new Promise((resolve, reject) => {
177
+ const worker = new Worker(script, { workerData: { entries, options: listOptions } });
178
+ const neverFinished = (how) => new Error(`${entries.join(', ')} never finished loading outside the game: ${how}, for example because it awaits ` +
179
+ 'something only the game settles.');
180
+ let settled = false;
181
+ const settle = (finish) => {
182
+ if (settled)
183
+ return;
184
+ settled = true;
185
+ clearTimeout(timer);
186
+ void worker.terminate();
187
+ finish();
188
+ };
189
+ const timer = setTimeout(() => settle(() => reject(neverFinished(`it was still loading after ${timeoutMs / 1000} s`))), timeoutMs);
190
+ worker.once('message', (answer) => settle(() => answer.error === undefined ? resolve(answer.registrations ?? []) : reject(new Error(answer.error))));
191
+ worker.once('error', (error) => settle(() => reject(error)));
192
+ worker.once('exit', () => settle(() => reject(neverFinished('it stopped waiting on a promise nothing settles'))));
193
+ });
194
+ }
@@ -0,0 +1,87 @@
1
+ /** A test id as the engine prints it, `class:name`. */
2
+ export declare const TEST_ID: string;
3
+ /** The tag a named run gives the tests it names, and runs with `runset`. */
4
+ export declare const NAMED_TAG = "devrock_gametests_named";
5
+ /** The line GameTest prints as each batch starts. The batch name before the colon can be empty. */
6
+ export declare const BATCH_RE: RegExp;
7
+ /**
8
+ * What the runner's console patch puts at the start of each line after a line break in a script's console message.
9
+ * Such a line belongs to the message before it, which its level was read from.
10
+ */
11
+ export declare const CONTINUATION = " | ";
12
+ /**
13
+ * What tied a line to us, for the summary. Many real warnings name nothing, such as a block whose material
14
+ * instances mix render methods. Either way the line fails the run.
15
+ */
16
+ export type Tie = {
17
+ kind: 'ours';
18
+ name: string;
19
+ } | {
20
+ kind: 'unattributed';
21
+ };
22
+ /** Where in a transcript the chunk probe ran, as string offsets. */
23
+ export interface Probe {
24
+ readonly start: number;
25
+ readonly end: number;
26
+ }
27
+ export interface ContentLogLine {
28
+ /** `[Category] message`, or just the message when the line has no category. */
29
+ entry: string;
30
+ tie: Tie;
31
+ }
32
+ export interface TestReport {
33
+ /** How many tests the engine said it would run, or null if it never said. */
34
+ expected: number | null;
35
+ noTestsForTag: boolean;
36
+ loaded: string[];
37
+ /** One entry per passing attempt, so a test that must pass twice is here twice. */
38
+ passed: string[];
39
+ /** The last failure of each test that failed an attempt. */
40
+ failed: Map<string, string>;
41
+ /** One id per verdict line, pass or fail, in order. */
42
+ finished: string[];
43
+ /** The name of each batch the engine started, once per part, in order. */
44
+ batches: string[];
45
+ /** Unique error and warning lines from the whole run, startup included. Each one fails the run. */
46
+ contentErrors: ContentLogLine[];
47
+ }
48
+ export declare function tieLabel(tie: Tie): string;
49
+ /**
50
+ * `runOutput` is everything printed after the runset command. `fullOutput` also has startup, where
51
+ * pack load errors appear. `sent` is every command the runner sent, whose echoes pass. Every line that
52
+ * isn't at a harmless level or a known line with no bracket fails the run, except a line that continues a script's
53
+ * message. `probe` is where in `fullOutput` the chunk probe started and ended, each on a line start. Its answer passes
54
+ * only there.
55
+ */
56
+ export declare function parseReport(runOutput: string, fullOutput: string, ourContent: readonly string[], sent: readonly string[], probe?: Probe): TestReport;
57
+ /** True if the transcript runs through a clean stop, so it holds every line the server printed. */
58
+ export declare function stoppedCleanly(transcript: string): boolean;
59
+ /**
60
+ * How many passes each test needs, by id, from `requiredSuccessfulAttempts`. A test it doesn't name needs one, and
61
+ * a test passes only with that many.
62
+ */
63
+ export type RequiredPasses = ReadonlyMap<string, number>;
64
+ /**
65
+ * True once each of `given` is done, no test has an attempt or rotation open, and there are as many verdicts as
66
+ * the engine announced tests, or once the engine said there was nothing to run. The engine announces each rotation
67
+ * as a test, and loads a test's next attempt just after the last one's verdict, so a caller should see this hold for
68
+ * a moment before it stops the server.
69
+ */
70
+ export declare function isComplete(report: TestReport, given: readonly string[], required?: RequiredPasses): boolean;
71
+ /**
72
+ * True once each of `ids` failed an attempt or passed as many as it needs, and no test has an attempt or rotation
73
+ * open. A failure is final, because any failed attempt fails the test.
74
+ */
75
+ export declare function isFinished(report: TestReport, ids: readonly string[], required?: RequiredPasses): boolean;
76
+ export interface Verdict {
77
+ id: string;
78
+ passed: boolean;
79
+ error?: string;
80
+ }
81
+ /**
82
+ * One verdict for each of `ids`, from all its attempts and rotations. A test passes only if it passed as many
83
+ * attempts as it needs, no attempt or rotation failed, and none was left open.
84
+ */
85
+ export declare function verdicts(report: TestReport, ids: readonly string[], required?: RequiredPasses): Verdict[];
86
+ /** The tests that reported a verdict or loaded, in the order they first did. */
87
+ export declare const testsSeen: (report: TestReport) => string[];