Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(launchers): the engine opens the packages it judges

esengine38dcb3f9f0e8
diff --git a/desktop b/desktop
index c5c313193..dc4c8e208 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit c5c3131937448fc8fd4718492d584ca5b9208880
+Subproject commit dc4c8e20815b894755fa6b4dac8006b761fed93f
diff --git a/pipeline/vitest.config.ts b/pipeline/vitest.config.ts
new file mode 100644
index 000000000..012c50c43
--- /dev/null
+++ b/pipeline/vitest.config.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineConfig } from 'vitest/config';
+
+/**
+ * Stated rather than inferred. Vitest walks UP from its cwd for a config, so a
+ * package without one runs on whatever it finds above — a root config once
+ * pointed these at the engine's include list and left them with no test files,
+ * passing by having nothing to run.
+ */
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ // Cook and export shell out and touch temp directories.
+ testTimeout: 30_000,
+ hookTimeout: 30_000,
+ },
+});
diff --git a/plugins/audio-mixer/vitest.config.ts b/plugins/audio-mixer/vitest.config.ts
new file mode 100644
index 000000000..f00e2d184
--- /dev/null
+++ b/plugins/audio-mixer/vitest.config.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineConfig } from 'vitest/config';
+
+/**
+ * Stated rather than inferred. Vitest walks UP from its cwd for a config, so a
+ * package without one runs on whatever it finds above — a root config once
+ * pointed these at the engine's include list and left them with no test files,
+ * passing by having nothing to run.
+ */
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ },
+});
diff --git a/plugins/ldtk/vitest.config.ts b/plugins/ldtk/vitest.config.ts
new file mode 100644
index 000000000..f00e2d184
--- /dev/null
+++ b/plugins/ldtk/vitest.config.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineConfig } from 'vitest/config';
+
+/**
+ * Stated rather than inferred. Vitest walks UP from its cwd for a config, so a
+ * package without one runs on whatever it finds above — a root config once
+ * pointed these at the engine's include list and left them with no test files,
+ * passing by having nothing to run.
+ */
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ },
+});
diff --git a/plugins/minigame-services/vitest.config.ts b/plugins/minigame-services/vitest.config.ts
new file mode 100644
index 000000000..f00e2d184
--- /dev/null
+++ b/plugins/minigame-services/vitest.config.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineConfig } from 'vitest/config';
+
+/**
+ * Stated rather than inferred. Vitest walks UP from its cwd for a config, so a
+ * package without one runs on whatever it finds above — a root config once
+ * pointed these at the engine's include list and left them with no test files,
+ * passing by having nothing to run.
+ */
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.ts'],
+ environment: 'node',
+ },
+});
diff --git a/tools/check-minigame-host.mjs b/tools/check-minigame-host.mjs
index 92c4f42b9..9ff38d804 100644
--- a/tools/check-minigame-host.mjs
+++ b/tools/check-minigame-host.mjs
@@ -16,7 +16,7 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { SHIM_MEMBERS } from '../desktop/scripts/minigameHost.mjs';
+import { SHIM_MEMBERS } from './launchers/minigameHost.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const API = 'sdk/src/platform/minigame/api.ts';
@@ -54,7 +54,7 @@ if (missing.length || stale.length) {
console.error('check-minigame-host: the stand-in host no longer matches the engine.\n');
for (const n of missing) console.error(` the engine requires "${n}" and the shim does not provide it`);
for (const n of stale) console.error(` the shim provides "${n}", which MiniGameGlobal does not declare`);
- console.error('\n Both live in desktop/scripts/minigameHost.mjs (SHIM_MEMBERS beside the page).');
+ console.error('\n Both live in tools/launchers/minigameHost.mjs (SHIM_MEMBERS beside the page).');
process.exit(1);
}
diff --git a/tools/gates.mjs b/tools/gates.mjs
index d3f8adf1f..c457283ad 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -122,7 +122,7 @@ export const GATES = [
why: 'it runs the built 3D physics wasm; CI builds that module in its own wasm job',
},
{ id: 'engine-gaps', run: 'node tools/check-engine-gaps.mjs' },
- { id: 'minigame-host', run: 'node tools/check-minigame-host.mjs', needs: 'editor' },
+ { id: 'minigame-host', run: 'node tools/check-minigame-host.mjs' },
{ id: 'release-gate', run: 'node tools/check-release-gate.mjs' },
{ id: 'component-reference', run: 'node tools/component-reference.mjs --check' },
{ id: 'api-stability-page', run: 'node tools/api-stability.mjs --check' },
diff --git a/tools/launchers/inputScript.mjs b/tools/launchers/inputScript.mjs
new file mode 100644
index 000000000..d48b0e5b1
--- /dev/null
+++ b/tools/launchers/inputScript.mjs
@@ -0,0 +1,218 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file inputScript.mjs — the gesture a launcher plays into a packaged game.
+ *
+ * Shared by launch-export and launch-minigame so a golden project's declared
+ * input means one thing whichever package it is driving. Events are real DOM
+ * events on the page the build owns: a package has no automation hook, and the
+ * point is the path a player's hardware takes, not a way around it.
+ *
+ * Pointer positions are FRACTIONS of the surface, because the surface size is
+ * chosen per project (it follows the editor's play panel) and a pixel target
+ * would land somewhere else on every game.
+ */
+
+/**
+ * JS source that plays `spec` and then lets the game run on.
+ * `{ keys?, pointer?, frames?, taps?: [{key, at}], holds?: [{key, from, to}],
+ * touches?: [{ from, to, x, y, toX?, toY? }] }`
+ *
+ * `keys` hold for the whole run, `taps` press at a frame index, `holds` hold over
+ * a frame range. A playthrough is a sequence, not a posture: "walk there, turn
+ * round, hit it" cannot be said by keys all pressed at frame zero.
+ *
+ * `hidden` is a frame range the page spends in the background: document.hidden
+ * plus a visibilitychange, which is the pair the engine's lifecycle listens to.
+ *
+ * `pad` is a gamepad the harness holds: the engine polls navigator.getGamepads,
+ * so standing one up there drives its real polling path rather than poking its
+ * state. Each entry sets axes/buttons over a frame range.
+ *
+ * `touches` are real TouchEvents — what a phone sends and what the web platform
+ * binds; a mouse pointer proves nothing about playing with a thumb. Each presses
+ * at (x, y) and optionally drags to (toX, toY) over its frame range, in
+ * fractions of the surface.
+ */
+export function inputScript(spec) {
+ const keys = JSON.stringify(spec.keys ?? []);
+ const pointer = JSON.stringify(spec.pointer ?? null);
+ const frames = Number(spec.frames ?? 40);
+ const taps = JSON.stringify(
+ (spec.taps ?? []).map((t) => ({ key: String(t.key), at: Number(t.at) || 0 })),
+ );
+ const hidden = JSON.stringify(
+ (spec.hidden ?? []).map((h) => ({ from: Number(h.from) || 0, to: Number(h.to ?? frames) })),
+ );
+ const pad = JSON.stringify(
+ (spec.pad ?? []).map((p) => ({
+ from: Number(p.from) || 0,
+ to: Number(p.to ?? frames),
+ axes: p.axes ?? {},
+ buttons: p.buttons ?? {},
+ })),
+ );
+ const touches = JSON.stringify(
+ (spec.touches ?? []).map((t, i) => ({
+ id: i + 1,
+ from: Number(t.from) || 0,
+ to: Number(t.to ?? frames),
+ x: Number(t.x) || 0,
+ y: Number(t.y) || 0,
+ toX: t.toX === undefined ? Number(t.x) || 0 : Number(t.toX),
+ toY: t.toY === undefined ? Number(t.y) || 0 : Number(t.toY),
+ })),
+ );
+ const holds = JSON.stringify(
+ (spec.holds ?? []).map((h) => ({
+ key: String(h.key), from: Number(h.from) || 0, to: Number(h.to ?? frames),
+ })),
+ );
+ return `
+ (async () => {
+ const raf = () => new Promise((r) => requestAnimationFrame(r));
+ const keys = ${keys};
+ const pointer = ${pointer};
+ const fireKey = (type, code) => {
+ const e = new KeyboardEvent(type, { key: code, code, bubbles: true, cancelable: true });
+ window.dispatchEvent(e);
+ document.dispatchEvent(e);
+ };
+ const canvas = document.querySelector('canvas');
+ // Pointer AND mouse: engines bind one or the other depending on what the
+ // host advertises, and a package driven through only half of that pair
+ // looks unresponsive for a reason that is the harness's fault.
+ const firePointer = (type, x, y) => {
+ if (!canvas) return;
+ const r = canvas.getBoundingClientRect();
+ const clientX = r.left + r.width * x;
+ const clientY = r.top + r.height * y;
+ const init = { clientX, clientY, bubbles: true, cancelable: true, button: 0, buttons: type === 'up' ? 0 : 1, pointerId: 1, isPrimary: true, pointerType: 'mouse' };
+ const names = { down: ['pointerdown', 'mousedown'], move: ['pointermove', 'mousemove'], up: ['pointerup', 'mouseup'] };
+ for (const n of names[type]) {
+ canvas.dispatchEvent(n.startsWith('pointer') ? new PointerEvent(n, init) : new MouseEvent(n, init));
+ }
+ if (type === 'up') canvas.dispatchEvent(new MouseEvent('click', init));
+ };
+
+ for (const k of keys) fireKey('keydown', k);
+ if (pointer) {
+ firePointer('move', pointer.x, pointer.y);
+ await raf();
+ firePointer('down', pointer.x, pointer.y);
+ // Held across a few frames: a press sampled once per frame can land
+ // between two of them and never be seen as a press at all.
+ for (let i = 0; i < 4; i++) await raf();
+ firePointer('up', pointer.x, pointer.y);
+ }
+ let touchBroken = null;
+ const fireTouch = (type, id, x, y, live) => {
+ if (!canvas || touchBroken) return;
+ try {
+ const r = canvas.getBoundingClientRect();
+ // Real Touch instances: TouchEvent's lists reject plain objects, and a
+ // constructor that throws leaves the driver's promise unresolved — the
+ // harness hangs rather than failing.
+ const make = (t) => new Touch({
+ identifier: t.id, target: canvas,
+ clientX: r.left + r.width * t.x, clientY: r.top + r.height * t.y,
+ pageX: r.left + r.width * t.x, pageY: r.top + r.height * t.y,
+ screenX: r.left + r.width * t.x, screenY: r.top + r.height * t.y,
+ });
+ const changed = [make({ id, x, y })];
+ // The full list is every finger still down; the changed list only the
+ // ones this event is about. A handler reading the wrong one loses a
+ // second finger, so the harness fills both.
+ const all = live.map((t) => make(t));
+ canvas.dispatchEvent(new TouchEvent(type, {
+ bubbles: true, cancelable: true,
+ touches: all, targetTouches: all, changedTouches: changed,
+ }));
+ } catch (e) {
+ touchBroken = String(e);
+ console.log('[engine] touch events unavailable: ' + touchBroken);
+ }
+ };
+
+ const taps = ${taps};
+ const holds = ${holds};
+ const touches = ${touches};
+ const hiddenSpec = ${hidden};
+ const setHidden = (h) => {
+ Object.defineProperty(document, 'hidden', { value: h, configurable: true });
+ Object.defineProperty(document, 'visibilityState', {
+ value: h ? 'hidden' : 'visible', configurable: true,
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ };
+ const padSpec = ${pad};
+ let padState = null;
+ if (padSpec.length) {
+ padState = {
+ index: 0, id: 'harness pad', connected: true, mapping: 'standard', timestamp: 0,
+ buttons: Array.from({ length: 17 }, () => ({ pressed: false, touched: false, value: 0 })),
+ axes: [0, 0, 0, 0],
+ };
+ Object.defineProperty(navigator, 'getGamepads', {
+ value: () => [padState], configurable: true, writable: true,
+ });
+ }
+ const live = [];
+ const down = new Set();
+ for (let i = 0; i < ${frames}; i++) {
+ for (const h of holds) {
+ if (h.from === i) { fireKey('keydown', h.key); down.add(h.key); }
+ if (h.to === i && down.has(h.key)) { fireKey('keyup', h.key); down.delete(h.key); }
+ }
+ for (const h of hiddenSpec) {
+ if (i === h.from) setHidden(true);
+ else if (i === h.to) setHidden(false);
+ }
+ if (padState) {
+ for (const p of padSpec) {
+ const on = i >= p.from && i < p.to;
+ for (const k of Object.keys(p.axes)) padState.axes[+k] = on ? p.axes[k] : 0;
+ for (const k of Object.keys(p.buttons)) {
+ const v = on ? p.buttons[k] : 0;
+ padState.buttons[+k] = { pressed: v > 0.5, touched: v > 0, value: v };
+ }
+ }
+ padState.timestamp = i;
+ }
+ for (const t of touches) {
+ if (i === t.from) {
+ live.push({ id: t.id, x: t.x, y: t.y });
+ fireTouch('touchstart', t.id, t.x, t.y, live);
+ } else if (i > t.from && i < t.to) {
+ const k = (i - t.from) / Math.max(1, t.to - t.from);
+ const at = live.find((l) => l.id === t.id);
+ if (at) {
+ at.x = t.x + (t.toX - t.x) * k;
+ at.y = t.y + (t.toY - t.y) * k;
+ fireTouch('touchmove', t.id, at.x, at.y, live);
+ }
+ } else if (i === t.to) {
+ const at = live.find((l) => l.id === t.id);
+ const idx = live.indexOf(at);
+ if (idx >= 0) live.splice(idx, 1);
+ fireTouch('touchend', t.id, at ? at.x : t.toX, at ? at.y : t.toY, live);
+ }
+ }
+ for (const t of taps) {
+ if (t.at !== i) continue;
+ fireKey('keydown', t.key);
+ // Held a couple of frames for the same reason a pointer press is:
+ // a key sampled once per frame can land between two of them.
+ for (let j = 0; j < 2; j++) await raf();
+ fireKey('keyup', t.key);
+ }
+ await raf();
+ }
+ for (const k of down) fireKey('keyup', k);
+ for (const k of keys) fireKey('keyup', k);
+ await raf();
+ return keys.length + taps.length + holds.length + touches.length + padSpec.length
+ + hiddenSpec.length + (pointer ? 1 : 0);
+ })()
+ `;
+}
diff --git a/tools/launchers/launch-export.mjs b/tools/launchers/launch-export.mjs
new file mode 100644
index 000000000..b67443982
--- /dev/null
+++ b/tools/launchers/launch-export.mjs
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file launch-export.mjs — a packaged web build actually starts, and draws.
+ *
+ * Exporting is checked (the pipeline reports errors, warnings and size) and
+ * the ENGINE is checked (verify:render). Between them sits the thing nobody ran
+ * in CI: the package itself, opened the way a player opens it. That gap is
+ * where a wrong export default, a missing runtime config or a path that only
+ * resolves in the editor survives every green check and ships.
+ *
+ * Serves the export over http (a build fetches its manifest and assets; file://
+ * refuses those) and asks the same two questions verify-native-boot asks of a
+ * native package: did it reach ready, and is the frame more than one flat
+ * colour — because a build that boots to black passes every other check.
+ *
+ * electron desktop/scripts/launch-export.mjs --dir <exportDir> [options]
+ * --out <file.png> write the captured frame
+ * --w / --h surface size (default 640x360)
+ * --settle <n> frames to let run before capturing (default 30)
+ * --timeout <ms> how long to wait for the first frame (default 30000)
+ * --allow-flat accept a single-colour frame (a deliberately blank scene)
+ * --input <json> drive it: {"keys":["ArrowRight"]} or {"pointer":{"x":.5,"y":.5}}
+ * --touch present as a touch device (maxTouchPoints > 0), so a
+ * build that puts its on-screen controls up for one can
+ * be driven the way a phone would drive it
+ * --safe-area t,r,b,l a screen with insets (a notch, a home bar), via the
+ * CSS variables the web platform reads
+ * --probe a,b,c after settling, print where those named entities are
+ * (opens the package with ?headless)
+ * --log <regex> also print console lines matching this (the engine's own
+ * warnings say why a subsystem sat out; only `[engine]`
+ * lines are forwarded otherwise, which means diagnosing
+ * one costs a probe planted in the game)
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { onRendererConsole } from '../lib/rendererConsole.mjs';
+import { inputScript } from './inputScript.mjs';
+
+// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.
+// Without it Chromium refuses the context outright and the package boots to
+// "WebGL2 is not available" — which is a runner without a GPU, not a broken game.
+app.commandLine.appendSwitch('enable-unsafe-swiftshader');
+// capturePage pixels go through the OS display profile; pin sRGB so a colour
+// judgement reads the same on a wide-gamut machine as on a CI runner.
+app.commandLine.appendSwitch('force-color-profile', 'srgb');
+// And pin the scale, for the same reason the editor's own driver does: a capture
+// is in DEVICE pixels, so a scaled display returns a bigger frame than the editor
+// it is compared against and parity refuses the pair for differing in size.
+app.commandLine.appendSwitch('force-device-scale-factor', '1');
+// A desktop Chromium reports no touch hardware, so a game that only shows its
+// on-screen controls to a touch device shows them to nobody here. This is the
+// emulation a phone would make true.
+if (process.argv.includes('--touch')) {
+ app.commandLine.appendSwitch('touch-events', 'enabled');
+ app.commandLine.appendSwitch('enable-features', 'TouchpadAndWheelScrollLatching');
+}
+
+const argv = process.argv.slice(2);
+const flag = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;
+};
+const has = (name) => argv.includes(`--${name}`);
+
+const DIR = path.resolve(flag('dir', ''));
+const OUT = flag('out', '');
+const W = Number(flag('w', '640'));
+const H = Number(flag('h', '360'));
+const SETTLE = Number(flag('settle', '30'));
+const INPUT = flag('input', '');
+const TIMEOUT = Number(flag('timeout', '30000'));
+const LOG = flag('log', '');
+const logRe = LOG ? new RegExp(LOG, 'i') : null;
+
+const MIME = {
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
+ '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png',
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ktx2': 'image/ktx2',
+ '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4',
+ '.mp4': 'video/mp4', '.esv': 'video/mp4', '.css': 'text/css', '.svg': 'image/svg+xml',
+ '.atlas': 'text/plain', '.skel': 'application/octet-stream', '.txt': 'text/plain',
+};
+
+/** Serve the export directory. Range requests are not implemented: a build that
+ * needs them (video seek) would read as a broken asset here, not a broken server. */
+function serve(root, safeArea) {
+ const server = http.createServer(async (req, res) => {
+ try {
+ let rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');
+ if (rel === '') rel = 'index.html';
+ const abs = path.join(root, rel);
+ if (!abs.startsWith(root)) { res.writeHead(403).end(); return; }
+ let bytes = await readFile(abs);
+ // Insets have to exist before the first script runs: the engine reads
+ // them once when its UI plugins build, and a variable set from the
+ // outside after that is a variable nobody ever asks about again.
+ if (safeArea && rel === 'index.html') {
+ const [t = 0, r = 0, b = 0, l = 0] = safeArea.split(',').map(Number);
+ const html = String(bytes);
+ const injected = html.replace(
+ '<head>',
+ `<head><style>:root{--sat:${t}px;--sar:${r}px;--sab:${b}px;--sal:${l}px}</style>`,
+ );
+ if (injected === html) console.log(' safe-area: no <head> to inject into');
+ bytes = Buffer.from(injected);
+ }
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' })
+ .end(bytes);
+ } catch {
+ res.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+/** Is more than one colour on screen? The question a boot-to-black build fails. */
+function frameIsLive(image) {
+ const { width, height } = image.getSize();
+ const buf = image.toBitmap(); // BGRA
+ const first = [buf[0], buf[1], buf[2]];
+ const step = Math.max(1, Math.floor((width * height) / 4000));
+ for (let p = 0; p < width * height; p += step) {
+ const i = p * 4;
+ if (Math.abs(buf[i] - first[0]) > 8 || Math.abs(buf[i + 1] - first[1]) > 8 || Math.abs(buf[i + 2] - first[2]) > 8) {
+ return true;
+ }
+ }
+ return false;
+}
+
+async function main() {
+ if (!DIR || !existsSync(path.join(DIR, 'index.html'))) {
+ console.error(`✗ no index.html under ${DIR || '(--dir not given)'}`);
+ app.exit(2);
+ return;
+ }
+ const PROBE = flag('probe', '');
+ const server = await serve(DIR, flag('safe-area', ''));
+ const base = `http://127.0.0.1:${server.address().port}/${PROBE ? '?headless' : ''}`;
+
+ const win = new BrowserWindow({
+ // Content size, not window size: with the frame counted in, the surface came
+ // out shorter than asked for, and a capture compared against another surface
+ // is only meaningful when the size requested is the size rendered.
+ width: W, height: H, useContentSize: true, show: false,
+ webPreferences: { offscreen: false, backgroundThrottling: false },
+ });
+ await win.webContents.session.clearCache();
+
+ const errors = [];
+ // Every line, not just the angry ones: when a package never draws, what it got
+ // through before stopping is the whole diagnosis, and none of it says "error".
+ const recent = [];
+ const stop = onRendererConsole(win.webContents, (msg) => {
+ recent.push(msg.slice(0, 200));
+ if (recent.length > 12) recent.shift();
+ if (/error|uncaught|failed/i.test(msg)) errors.push(msg.slice(0, 300));
+ if (msg.startsWith('[engine]') || logRe?.test(msg)) console.log(` ${msg}`);
+ });
+ win.webContents.on('render-process-gone', (_e, d) => errors.push(`render process gone: ${d.reason}`));
+
+ await win.loadURL(base);
+
+ // Wait for a real frame rather than a wall-clock guess: the engine paints when
+ // its wasm and assets are in, which is exactly the part a package can get wrong.
+ const paint = await win.webContents.executeJavaScript(`
+ new Promise((resolve) => {
+ const deadline = Date.now() + ${TIMEOUT};
+ let frames = 0;
+ const tick = () => {
+ const c = document.querySelector('canvas');
+ if (c && c.width > 0 && c.height > 0) frames++;
+ if (frames >= ${SETTLE}) return resolve({ ok: true, frames });
+ if (Date.now() > deadline) return resolve({ ok: false, frames });
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ })
+ `).catch((e) => { errors.push(String(e)); return { ok: false, frames: -1 }; });
+ const painted = paint.ok;
+
+ // Drive the game, then let it run on.
+ if (painted && INPUT) {
+ const spec = JSON.parse(INPUT);
+ const ran = await win.webContents.executeJavaScript(inputScript(spec))
+ .catch((e) => { errors.push(`input: ${e}`); return -1; });
+ console.log(` input: ${ran} source(s) over ${Number(spec.frames ?? 40)} frames`);
+ }
+
+ if (PROBE) {
+ const names = PROBE.split(',').map((n) => n.trim()).filter(Boolean);
+ const seen = await win.webContents.executeJavaScript(
+ `window.__estellaCooked?.probe(${JSON.stringify(names)}) ?? null`,
+ ).catch((e) => ({ error: String(e) }));
+ console.log(` probe: ${JSON.stringify(seen)}`);
+ }
+
+ const image = await win.webContents.capturePage();
+ if (OUT) await writeFile(OUT, image.toPNG());
+ stop();
+ server.close();
+
+ const live = frameIsLive(image);
+ const ok = painted && live && errors.length === 0;
+ console.log(`${ok ? '✓' : '✗'} ${path.basename(DIR)} — painted=${painted} live=${live} errors=${errors.length}`);
+ for (const e of errors.slice(0, 5)) console.log(` ${e}`);
+ if (!painted) {
+ // How far it got, rather than "it did not start": a package drawing one slow
+ // frame a second on a software rasteriser reaches neither, and only one of
+ // those two sentences sends you looking in the right place.
+ console.log(` ${paint.frames} of ${SETTLE} settled frames within ${TIMEOUT}ms`);
+ const diag = await win.webContents.executeJavaScript(`(() => {
+ const c = document.querySelector('canvas');
+ return JSON.stringify({ ready: document.readyState, canvas: !!c, w: c ? c.width : 0, h: c ? c.height : 0 });
+ })()`).catch((e) => `unreadable: ${e}`);
+ console.log(` ${diag}`);
+ for (const l of recent) console.log(` · ${l}`);
+ }
+ if (painted && !live && !has('allow-flat')) console.log(' one flat colour — it started and drew nothing');
+ app.exit(ok || (live === false && has('allow-flat') && painted && !errors.length) ? 0 : 1);
+}
+
+app.whenReady().then(main).catch((e) => {
+ console.error('✗ launch-export failed:', e);
+ app.exit(2);
+});
diff --git a/tools/launchers/launch-minigame.mjs b/tools/launchers/launch-minigame.mjs
new file mode 100644
index 000000000..7a3440b9b
--- /dev/null
+++ b/tools/launchers/launch-minigame.mjs
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file launch-minigame.mjs — a packaged mini-game starts, and draws.
+ *
+ * The WeChat/Douyin counterpart of launch-export: same two questions (did it
+ * reach a frame, is that frame more than one flat colour), asked of a package
+ * no browser can open on its own. minigameHost supplies the CommonJS loader and
+ * the `wx` global; this serves the export and judges the result.
+ *
+ * It stands in for the vendor, it does not impersonate it — see minigameHost.
+ *
+ * electron desktop/scripts/launch-minigame.mjs --dir <exportDir> [options]
+ * --out <file.png> write the captured frame
+ * --w / --h surface size (default 640x360)
+ * --settle <n> frames to let run before capturing (default 30)
+ * --timeout <ms> how long to wait for the first frame (default 30000)
+ * --input <json> drive it, same spec as launch-export
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile, writeFile } from 'node:fs/promises';
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { onRendererConsole } from '../lib/rendererConsole.mjs';
+import { HOST_PAGE } from './minigameHost.mjs';
+import { inputScript } from './inputScript.mjs';
+
+// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.
+app.commandLine.appendSwitch('enable-unsafe-swiftshader');
+app.commandLine.appendSwitch('force-color-profile', 'srgb');
+// Both of the above pin a machine's answer to the code's; so does this. A capture
+// is in DEVICE pixels, so a scaled display returns a frame the editor's own
+// capture cannot be compared against. Its twin launcher pins it for the same reason.
+app.commandLine.appendSwitch('force-device-scale-factor', '1');
+
+const argv = process.argv.slice(2);
+const flag = (n, d) => {
+ const i = argv.indexOf(`--${n}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d;
+};
+const DIR = path.resolve(flag('dir', ''));
+const OUT = flag('out', '');
+const W = Number(flag('w', '640'));
+const H = Number(flag('h', '360'));
+const SETTLE = Number(flag('settle', '30'));
+const TIMEOUT = Number(flag('timeout', '30000'));
+const INPUT = flag('input', '');
+
+const MIME = {
+ '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm',
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.ktx2': 'image/ktx2',
+ '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4',
+ '.atlas': 'text/plain', '.skel': 'application/octet-stream', '.txt': 'text/plain',
+};
+
+function serve(root, page) {
+ const server = http.createServer(async (req, res) => {
+ try {
+ let rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');
+ if (rel === '' || rel === 'index.html') {
+ res.writeHead(200, { 'content-type': 'text/html' }).end(page);
+ return;
+ }
+ const abs = path.join(root, rel);
+ if (!abs.startsWith(root)) { res.writeHead(403).end(); return; }
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' })
+ .end(await readFile(abs));
+ } catch {
+ res.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+function frameIsLive(image) {
+ const { width, height } = image.getSize();
+ const buf = image.toBitmap();
+ const first = [buf[0], buf[1], buf[2]];
+ const step = Math.max(1, Math.floor((width * height) / 4000));
+ for (let p = 0; p < width * height; p += step) {
+ const i = p * 4;
+ if (Math.abs(buf[i] - first[0]) > 8 || Math.abs(buf[i + 1] - first[1]) > 8 || Math.abs(buf[i + 2] - first[2]) > 8) {
+ return true;
+ }
+ }
+ return false;
+}
+
+async function main() {
+ const manifest = path.join(DIR, 'game.json');
+ if (!existsSync(manifest)) {
+ console.error(`✗ no game.json under ${DIR || '(--dir not given)'} — not a mini-game package`);
+ app.exit(2);
+ return;
+ }
+ // The vendor reads the entry from game.json's convention (game.js); assert it
+ // is there rather than letting the loader 404 into a confusing stack.
+ const entry = 'game.js';
+ if (!existsSync(path.join(DIR, entry))) {
+ console.error(`✗ ${entry} is missing — the package has a manifest and no entry`);
+ app.exit(1);
+ return;
+ }
+ JSON.parse(readFileSync(manifest, 'utf8')); // a manifest the vendor cannot parse is a dead package
+
+ const server = await serve(DIR, HOST_PAGE(entry));
+ const base = `http://127.0.0.1:${server.address().port}/`;
+
+ const win = new BrowserWindow({
+ width: W, height: H, useContentSize: true, show: false,
+ webPreferences: { backgroundThrottling: false },
+ });
+
+ const errors = [];
+ const stop = onRendererConsole(win.webContents, (msg) => {
+ if (/\[minigame\] boot failed|uncaught|is not a function|no such file/i.test(msg)) errors.push(msg.slice(0, 400));
+ if (msg.startsWith('[minigame]') || msg.startsWith('[engine]')) console.log(` ${msg}`);
+ });
+ win.webContents.on('render-process-gone', (_e, d) => errors.push(`render process gone: ${d.reason}`));
+
+ await win.loadURL(base);
+ const painted = await win.webContents.executeJavaScript(`
+ new Promise((resolve) => {
+ const deadline = Date.now() + ${TIMEOUT};
+ let frames = 0;
+ const tick = () => {
+ const c = document.querySelector('canvas');
+ if (c && c.width > 0 && c.height > 0) frames++;
+ if (frames >= ${SETTLE}) return resolve(true);
+ if (Date.now() > deadline) return resolve(false);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ })
+ `).catch((e) => { errors.push(String(e)); return false; });
+
+ if (painted && INPUT) {
+ const spec = JSON.parse(INPUT);
+ const ran = await win.webContents.executeJavaScript(inputScript(spec))
+ .catch((e) => { errors.push(`input: ${e}`); return -1; });
+ console.log(` input: ${ran} source(s) over ${Number(spec.frames ?? 40)} frames`);
+ }
+
+ const image = await win.webContents.capturePage();
+ if (OUT) await writeFile(OUT, image.toPNG());
+ stop();
+ server.close();
+
+ const live = frameIsLive(image);
+ const ok = painted && live && errors.length === 0;
+ console.log(`${ok ? '✓' : '✗'} ${path.basename(DIR)} (mini-game) — painted=${painted} live=${live} errors=${errors.length}`);
+ for (const e of errors.slice(0, 5)) console.log(` ${e}`);
+ if (painted && !live) console.log(' one flat colour — it started and drew nothing');
+ app.exit(ok ? 0 : 1);
+}
+
+app.whenReady().then(main).catch((e) => {
+ console.error('✗ launch-minigame failed:', e);
+ app.exit(2);
+});
diff --git a/tools/launchers/minigameHost.mjs b/tools/launchers/minigameHost.mjs
new file mode 100644
index 000000000..2fe878f5c
--- /dev/null
+++ b/tools/launchers/minigameHost.mjs
@@ -0,0 +1,217 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file minigameHost.mjs — the page that boots a mini-game package outside its vendor.
+ *
+ * A WeChat/Douyin package is CommonJS plus a `wx`/`tt` global, so no browser
+ * opens one and CI never launched a mini-game build at all. This supplies both,
+ * over http, from the export directory as it shipped.
+ *
+ * What it is NOT: WeChat. It cannot answer how the real base library behaves.
+ * What it does answer is everything between "the exporter returned ok" and "the
+ * game runs" — a file the entry requires and the package does not carry, a wasm
+ * the loader cannot locate, an entry wired to the wrong boot call.
+ *
+ * The shim implements `MiniGameGlobal` (sdk/src/platform/minigame/api.ts), which
+ * the engine documents as "only the subset the engine actually uses" — so it is
+ * written against a declared contract rather than guessed, and check-minigame-host
+ * fails when the contract grows a member the shim has not got.
+ */
+
+/** The page source; `BASE` is substituted with the served root. */
+export const HOST_PAGE = (entry) => `<!doctype html>
+<html><head><meta charset="utf-8"><style>
+ html,body{margin:0;height:100%;background:#000;overflow:hidden}
+ canvas{display:block}
+</style></head><body>
+<script>
+(() => {
+ const log = (m) => console.log('[minigame] ' + m);
+ // Vendor contract: the FIRST createCanvas() hands back the on-screen canvas and
+ // every call after it is offscreen scratch. Hand the engine a fresh offscreen
+ // one instead and the game runs perfectly, drawing where nobody can see.
+ const screenCanvas = document.createElement('canvas');
+ screenCanvas.width = window.innerWidth;
+ screenCanvas.height = window.innerHeight;
+ document.body.appendChild(screenCanvas);
+ let screenTaken = false;
+ const makeCanvas = () => {
+ if (!screenTaken) { screenTaken = true; return screenCanvas; }
+ return document.createElement('canvas');
+ };
+
+ const readAsArrayBuffer = (p) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', p, false); // sync: readFileSync is synchronous by contract
+ xhr.overrideMimeType('text/plain; charset=x-user-defined');
+ xhr.send(null);
+ if (xhr.status !== 200 && xhr.status !== 0) throw new Error('no such file: ' + p);
+ const s = xhr.responseText;
+ const b = new Uint8Array(s.length);
+ for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i) & 0xff;
+ return b.buffer;
+ };
+ const readAsText = (p) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', p, false);
+ xhr.send(null);
+ if (xhr.status !== 200 && xhr.status !== 0) throw new Error('no such file: ' + p);
+ return xhr.responseText;
+ };
+
+ const fs = {
+ readFileSync: (p, enc) => (enc === 'utf8' || enc === 'utf-8' ? readAsText(p) : readAsArrayBuffer(p)),
+ readFile: (o) => {
+ try { o.success && o.success({ data: fs.readFileSync(o.filePath, o.encoding) }); }
+ catch (e) { o.fail && o.fail({ errMsg: String(e) }); }
+ finally { o.complete && o.complete(); }
+ },
+ accessSync: (p) => { readAsArrayBuffer(p); },
+ access: (o) => {
+ try { fs.accessSync(o.path); o.success && o.success(); }
+ catch (e) { o.fail && o.fail({ errMsg: String(e) }); }
+ finally { o.complete && o.complete(); }
+ },
+ writeFile: (o) => { o.fail && o.fail({ errMsg: 'read-only host' }); o.complete && o.complete(); },
+ writeFileSync: () => { throw new Error('read-only host'); },
+ mkdirSync: () => {},
+ unlinkSync: () => {},
+ rmdirSync: () => {},
+ readdirSync: () => [],
+ statSync: () => ({ size: 0, isDirectory: () => false }),
+ };
+
+ const noop = () => {};
+ const wx = {
+ createCanvas: makeCanvas,
+ createImage: () => new Image(),
+ getFileSystemManager: () => fs,
+ getSystemInfoSync: () => ({
+ pixelRatio: window.devicePixelRatio || 1,
+ language: 'en',
+ windowWidth: window.innerWidth,
+ windowHeight: window.innerHeight,
+ platform: 'devtools',
+ safeArea: { top: 0, bottom: window.innerHeight, left: 0, right: window.innerWidth,
+ width: window.innerWidth, height: window.innerHeight },
+ }),
+ request: (o) => {
+ fetch(o.url).then(async (r) => {
+ const data = o.responseType === 'arraybuffer' ? await r.arrayBuffer() : await r.text();
+ o.success && o.success({ data, statusCode: r.status });
+ }).catch((e) => o.fail && o.fail({ errMsg: String(e) })).finally(() => o.complete && o.complete());
+ },
+ // Audio and sockets are stubs on purpose: a launch smoke asks whether the
+ // package starts and draws, and a silent stub cannot fake either answer.
+ createInnerAudioContext: () => ({
+ play: noop, pause: noop, stop: noop, destroy: noop, seek: noop,
+ onPlay: noop, onPause: noop, onStop: noop, onEnded: noop, onError: noop, onCanplay: noop,
+ offPlay: noop, offPause: noop, offStop: noop, offEnded: noop, offError: noop, offCanplay: noop,
+ src: '', loop: false, volume: 1, autoplay: false, currentTime: 0, duration: 0, paused: true,
+ }),
+ connectSocket: () => ({
+ send: noop, close: noop,
+ onOpen: noop, onClose: noop, onError: noop, onMessage: noop,
+ offOpen: noop, offClose: noop, offError: noop, offMessage: noop,
+ }),
+ onTouchStart: noop, onTouchMove: noop, onTouchEnd: noop,
+ offTouchStart: noop, offTouchMove: noop, offTouchEnd: noop,
+ onTouchCancel: noop, offTouchCancel: noop,
+ // Keyboard: forwarded from the real DOM so a driven run can reach the game.
+ onKeyDown: (cb) => window.addEventListener('keydown', (e) => cb({ code: e.code, key: e.key })),
+ onKeyUp: (cb) => window.addEventListener('keyup', (e) => cb({ code: e.code, key: e.key })),
+ offKeyDown: noop, offKeyUp: noop,
+ onMemoryWarning: noop, offMemoryWarning: noop,
+ onError: noop, offError: noop,
+ onUnhandledRejection: noop, offUnhandledRejection: noop,
+ onShow: noop, onHide: noop, offShow: noop, offHide: noop,
+ onWindowResize: noop, offWindowResize: noop,
+ loadSubpackage: (o) => { o.success && o.success(); o.complete && o.complete(); },
+ // Storage is real (localStorage), not a stub: a game that saves on boot and
+ // reads it back would otherwise take the silent path and look fine.
+ getStorageSync: (k) => { const v = localStorage.getItem(k); return v === null ? '' : JSON.parse(v); },
+ setStorageSync: (k, v) => localStorage.setItem(k, JSON.stringify(v)),
+ removeStorageSync: (k) => localStorage.removeItem(k),
+ getStorageInfoSync: () => ({ keys: Object.keys(localStorage), currentSize: 0, limitSize: 10240 }),
+ setPreferredFramesPerSecond: noop,
+ triggerGC: noop,
+ exitMiniProgram: noop,
+ getLaunchOptionsSync: () => ({ scene: 1001, query: {} }),
+ };
+ // WeChat instantiates wasm from a PACKAGE-RELATIVE PATH, not bytes — the one
+ // place the vendors genuinely diverge (sdk/src/platform/wechat/wasm.ts), and
+ // the reason a browser cannot open one of these packages unaided.
+ const asUrl = (p) => '/' + (String(p)[0] === '/' ? String(p).slice(1) : String(p));
+ globalThis.WXWebAssembly = {
+ instantiate: (pathOrBytes, imports) => (typeof pathOrBytes === 'string'
+ ? fetch(asUrl(pathOrBytes)).then((r) => r.arrayBuffer())
+ .then((b) => WebAssembly.instantiate(b, imports))
+ : WebAssembly.instantiate(pathOrBytes, imports)),
+ compile: (p) => fetch(asUrl(p)).then((r) => r.arrayBuffer()).then((b) => WebAssembly.compile(b)),
+ Memory: WebAssembly.Memory,
+ Table: WebAssembly.Table,
+ Module: WebAssembly.Module,
+ Instance: WebAssembly.Instance,
+ };
+
+ globalThis.wx = wx;
+ globalThis.GameGlobal = globalThis;
+ globalThis.canvas = screenCanvas;
+
+ // The package is CommonJS. A mini-game host resolves relative requires against
+ // the requiring file, so the loader has to carry that directory with it.
+ const modules = new Map();
+ const dirOf = (p) => p.slice(0, p.lastIndexOf('/') + 1);
+ const normalize = (p) => {
+ const out = [];
+ for (const part of p.split('/')) {
+ if (part === '.' || part === '') continue;
+ if (part === '..') out.pop();
+ else out.push(part);
+ }
+ return out.join('/');
+ };
+ function requireFrom(dir, spec) {
+ let file = spec.startsWith('.') ? normalize(dir + spec) : normalize(spec);
+ if (!/\\.(js|json)$/.test(file)) file += '.js';
+ if (modules.has(file)) return modules.get(file).exports;
+ const src = readAsText('/' + file);
+ if (file.endsWith('.json')) {
+ const m = { exports: JSON.parse(src) };
+ modules.set(file, m);
+ return m.exports;
+ }
+ const mod = { exports: {} };
+ modules.set(file, mod);
+ const fn = new Function('module', 'exports', 'require', '__filename', '__dirname', 'wx', 'GameGlobal',
+ src + '\\n//# sourceURL=' + file);
+ fn(mod, mod.exports, (s) => requireFrom(dirOf(file), s), file, dirOf(file), wx, globalThis);
+ return mod.exports;
+ }
+
+ try {
+ log('booting ${entry}');
+ requireFrom('', './${entry}');
+ log('entry returned');
+ } catch (e) {
+ console.error('[minigame] boot failed: ' + (e && e.stack ? e.stack : e));
+ }
+})();
+</script></body></html>`;
+
+/**
+ * Members of `MiniGameGlobal` the shim above provides. Kept beside it so
+ * check-minigame-host can hold the two against the SDK's declaration.
+ */
+export const SHIM_MEMBERS = [
+ 'createCanvas', 'createImage', 'getFileSystemManager', 'request',
+ 'createInnerAudioContext', 'connectSocket', 'getSystemInfoSync',
+ 'onTouchStart', 'onTouchMove', 'onTouchEnd',
+ 'offTouchStart', 'offTouchMove', 'offTouchEnd',
+ 'onTouchCancel', 'offTouchCancel',
+ 'onKeyDown', 'onKeyUp', 'offKeyDown', 'offKeyUp',
+ 'loadSubpackage', 'onMemoryWarning', 'offMemoryWarning',
+ 'onError', 'offError', 'onUnhandledRejection', 'offUnhandledRejection',
+ 'onShow', 'onHide',
+ 'getStorageSync', 'setStorageSync', 'removeStorageSync', 'getStorageInfoSync',
+];
diff --git a/tools/launchers/play-through.mjs b/tools/launchers/play-through.mjs
new file mode 100644
index 000000000..3f7d010ec
--- /dev/null
+++ b/tools/launchers/play-through.mjs
@@ -0,0 +1,334 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file play-through.mjs — can the shipped game be played from start to finish?
+ *
+ * launch-export proves a package boots and answers input. It cannot prove a
+ * playthrough: its input is a list of "hold this key from frame A to frame B",
+ * which is open-loop. Any enemy standing in the way silently turns the rest of
+ * the script into someone walking into a wall, and the run still reports green
+ * because the frame is still lively. A route written that way is a route that
+ * has to be re-timed by hand every time the level changes.
+ *
+ * So this one plays: it asks the running game where things are (`?headless` →
+ * `__estellaCooked.probe`), steers toward the next waypoint, swings on the way,
+ * and moves on when it arrives. What it asserts is the game's own progression —
+ * the areas reached, in order — not a pixel.
+ *
+ * electron desktop/scripts/play-through.mjs --dir <exportDir> --route <file.json>
+ * --out <file.png> write the final frame
+ * --w / --h surface size (default 960x540)
+ * --budget <n> give up after this many frames (default 6000)
+ * --log <regex> also print console lines matching this
+ * --trace print what the driver decided, periodically
+ *
+ * A route is a list of legs: `{ area, goal, arriveWithin?, swing?, timeout? }`.
+ * `goal` is an entity name the probe can find, so a leg survives the level being
+ * re-authored — the door moves, the route does not.
+ *
+ * Runs of one package agree to the frame, which took three rules: read on a
+ * frame boundary, never read a world mid-transition, and credit an arrival
+ * only from arm's reach with Lyra present.
+ *
+ * Answers `flagship-plays-through` via tools/verify-playthrough.mjs.
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { onRendererConsole } from '../lib/rendererConsole.mjs';
+
+app.commandLine.appendSwitch('force-color-profile', 'srgb');
+
+const argv = process.argv.slice(2);
+const flag = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;
+};
+
+const DIR = path.resolve(flag('dir', ''));
+const ROUTE = flag('route', '');
+const OUT = flag('out', '');
+const W = Number(flag('w', '960'));
+const H = Number(flag('h', '540'));
+const BUDGET = Number(flag('budget', '6000'));
+const LOG = flag('log', '');
+const logRe = LOG ? new RegExp(LOG, 'i') : null;
+const TRACE = argv.includes('--trace');
+
+const MIME = {
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
+ '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png',
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ktx2': 'image/ktx2',
+ '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav', '.m4a': 'audio/mp4',
+ '.mp4': 'video/mp4', '.esv': 'video/mp4', '.css': 'text/css', '.svg': 'image/svg+xml',
+ '.atlas': 'text/plain', '.skel': 'application/octet-stream', '.txt': 'text/plain',
+};
+
+function serve(root) {
+ const server = http.createServer(async (req, res) => {
+ try {
+ let rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');
+ if (rel === '') rel = 'index.html';
+ const abs = path.join(root, rel);
+ if (!abs.startsWith(root)) { res.writeHead(403).end(); return; }
+ const bytes = await readFile(abs);
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' })
+ .end(bytes);
+ } catch {
+ res.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+/**
+ * The page-side half: hold a set of keys for `frames` frames, then release.
+ * Keys go in as real DOM events, which is what the engine's input actually
+ * listens to — a driver that pokes state instead would be testing itself.
+ */
+const stepScript = (keys, frames, tapKey) => `
+(() => {
+ const target = document.querySelector('canvas') ?? window;
+ const send = (type, code) => {
+ const e = new KeyboardEvent(type, { code, key: code, bubbles: true, cancelable: true });
+ target.dispatchEvent(e);
+ if (target !== window) window.dispatchEvent(new KeyboardEvent(type, { code, key: code, bubbles: true }));
+ };
+ const held = ${JSON.stringify(keys)};
+ for (const k of held) send('keydown', k);
+ ${tapKey ? `send('keydown', ${JSON.stringify(tapKey)});` : ''}
+ return new Promise((resolve) => {
+ let n = 0;
+ const tick = () => {
+ n++;
+ ${tapKey ? `if (n === 2) send('keyup', ${JSON.stringify(tapKey)});` : ''}
+ if (n >= ${frames}) {
+ for (const k of held) send('keyup', k);
+ return resolve(true);
+ }
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ });
+})()
+`;
+
+/**
+ * Which keys walk from `from` toward `to`. The dead band stops a stutter
+ * between opposite keys; shrinking it is how a driver gets off a wall. Feet
+ * collide where navigation planned from the origin, so a plan can be walkable
+ * for the middle and a wall for the feet.
+ */
+function keysToward(from, to, deadband = 40) {
+ const dx = to.x - from.x;
+ const dy = to.y - from.y;
+ const keys = [];
+ if (Math.abs(dx) > deadband) keys.push(dx > 0 ? 'KeyD' : 'KeyA');
+ if (Math.abs(dy) > deadband) keys.push(dy > 0 ? 'KeyW' : 'KeyS');
+ return keys;
+}
+
+async function main() {
+ if (!DIR || !existsSync(path.join(DIR, 'index.html'))) {
+ console.error(`✗ no index.html under ${DIR || '(--dir not given)'}`);
+ app.exit(2);
+ return;
+ }
+ if (!ROUTE || !existsSync(ROUTE)) {
+ console.error(`✗ no route file at ${ROUTE || '(--route not given)'}`);
+ app.exit(2);
+ return;
+ }
+ const route = JSON.parse(await readFile(ROUTE, 'utf8'));
+ const server = await serve(DIR);
+ const base = `http://127.0.0.1:${server.address().port}/?headless`;
+
+ const win = new BrowserWindow({
+ width: W, height: H, useContentSize: true, show: false,
+ webPreferences: { offscreen: false, backgroundThrottling: false },
+ });
+ await win.webContents.session.clearCache();
+
+ const errors = [];
+ const stop = onRendererConsole(win.webContents, (msg) => {
+ if (/error|uncaught|failed/i.test(msg)) errors.push(msg.slice(0, 300));
+ if (msg.startsWith('[engine]') || logRe?.test(msg)) console.log(` ${msg}`);
+ });
+
+ await win.loadURL(base);
+ const exec = (js) => win.webContents.executeJavaScript(js);
+
+ // The handle appears as soon as the host builds it, which is before the first
+ // scene has spawned anything — asking then is asking an empty world.
+ let ready = false;
+ for (let i = 0; i < 300 && !ready; i++) {
+ ready = await exec(`(() => {
+ const c = window.__estellaCooked;
+ if (!c || !c.probe) return false;
+ const s = c.probe(['Lyra_Player']);
+ return !!(s.scene && s.at.Lyra_Player);
+ })()`).catch(() => false);
+ if (!ready) await new Promise((r) => setTimeout(r, 100));
+ }
+ if (!ready) {
+ console.log('✗ the package never exposed a probe — is this a cooked build served with ?headless');
+ stop(); server.close(); app.exit(1);
+ return;
+ }
+
+ // Read on a frame boundary. Poked from outside the loop, a read can land
+ // between the systems that despawn something and the ones that replace it,
+ // and every such read is a world nobody was ever in.
+ const probe = (names) => exec(
+ `new Promise((r) => requestAnimationFrame(() => r(window.__estellaCooked.probe(${JSON.stringify(names)}))))`,
+ );
+ const pathTo = (goal) => exec(`window.__estellaCooked.pathBetween("Lyra_Player", ${JSON.stringify(goal)})`);
+ // Every goal the route names, before a step is taken: a leg whose goal never
+ // existed would otherwise report as "already done" and the run would fail
+ // later, somewhere else, for a reason that is not the reason.
+ const goals = [...new Set(route.legs.map((l) => l.goal))];
+ const opening = await probe(goals);
+ const missing = goals.filter((g) => !(g in opening.at));
+ console.log(` route names ${goals.length} goal(s); ${goals.length - missing.length} are in ${opening.scene}`
+ + (missing.length ? `, not yet: ${missing.join(', ')}` : ''));
+
+ const STEP = 8;
+ // Nothing vanishes into a pack from across the room: a goal that goes while
+ // Lyra is nowhere near it went for some other reason, and crediting that is
+ // how a run reports legs it never walked.
+ const REACH = 220;
+ let frames = 0;
+ const done = [];
+ let failure = null;
+
+ for (const leg of route.legs) {
+ const label = `${leg.area}:${leg.goal}`;
+ const timeout = Number(leg.timeout ?? 1800);
+ const arriveWithin = Number(leg.arriveWithin ?? 90);
+ let spent = 0;
+ let arrived = false;
+ let sawArea = false;
+ let sawGoal = false;
+ let lastGap = Infinity;
+ let stuckFor = 0;
+ let was = null;
+ let deaths = 0;
+ let plan = [];
+ let replan = 0;
+ let last = null;
+
+ // Something picked up on the way to somewhere else is still picked up. A
+ // leg whose goal is already gone before it starts is a leg already walked —
+ // and a goal that is merely misspelled fails the legs that depend on it.
+ const opening = await probe([leg.goal, 'Lyra_Player']);
+ if (opening.at.Lyra_Player && !opening.at[leg.goal] && !leg.throughDoor) {
+ console.log(` ${label} was already done (probe saw ${JSON.stringify(Object.keys(opening.at))} in ${opening.scene})`);
+ done.push(label);
+ continue;
+ }
+
+ while (spent < timeout && frames < BUDGET) {
+ const state = await probe([leg.goal, 'Lyra_Player']);
+ // Nothing is true about a world that is halfway through being replaced.
+ if (state.transitioning) { await exec(stepScript([], STEP, null)); spent += STEP; frames += STEP; continue; }
+ if (state.scene === leg.area) sawArea = true;
+ // The leg is over when the area it was aiming for has been left behind:
+ // walking into a door IS the arrival, and the door is gone by the time
+ // anyone could measure standing next to it.
+ if (sawArea && state.scene !== leg.area) { arrived = true; break; }
+
+ const goal = state.at[leg.goal];
+ const me = state.at.Lyra_Player;
+ // A goal that was there and now is not was reached — taken, or killed —
+ // but only while Lyra is beside it: an area rebuilding after a death
+ // empties the world for a moment, and that is not an arrival.
+ if (sawGoal && !goal && me && lastGap < REACH && !leg.throughDoor) {
+ // One read is not evidence. Something that is really gone stays gone;
+ // something that blinked was a world caught mid-change, and crediting
+ // it costs the run a pickup it never took.
+ let gone = true;
+ for (let i = 0; i < 3 && gone; i++) {
+ await exec(stepScript([], 4, null));
+ spent += 4;
+ frames += 4;
+ gone = !(await probe([leg.goal])).at[leg.goal];
+ }
+ if (gone) { arrived = true; break; }
+ console.log(` ${label}: goal blinked out and came back — not counting it`);
+ }
+ if (goal) sawGoal = true;
+ if (me && goal) {
+ const gap = Math.hypot(goal.x - me.x, goal.y - me.y);
+ last = { me, goal, gap };
+ lastGap = gap;
+ if (gap <= arriveWithin && !leg.throughDoor) { arrived = true; break; }
+ // Re-planned every few steps rather than followed to the end: the route
+ // is walked with enemies pushing back, so a plan is a heading, not a rail.
+ if (!plan.length || replan <= 0) {
+ plan = (await pathTo(leg.goal)) ?? [];
+ replan = 40;
+ }
+ replan -= STEP;
+ while (plan.length && Math.hypot(plan[0].x - me.x, plan[0].y - me.y) < 70) plan.shift();
+ const aim = plan[0] ?? goal;
+ // Pressed and did not move: back off the dead band so the other axis
+ // comes into play, and re-plan sooner.
+ const moved = was ? Math.hypot(me.x - was.x, me.y - was.y) : Infinity;
+ // Nobody walks 600 units in eight frames: that is a death putting her
+ // back at the area's entrance, and the leg deserves its time again.
+ if (moved > 600 && was) { deaths++; spent = 0; plan = []; }
+ stuckFor = moved < 6 ? stuckFor + STEP : 0;
+ was = me;
+ if (stuckFor > 64) { replan = 0; }
+ const keys = keysToward(me, aim, stuckFor > 32 ? 4 : 40);
+ if (stuckFor > 32) {
+ // Slide along whatever is in the way: press the axis the heading does
+ // not need, flipping which way every so often until something gives.
+ const alongX = Math.abs(aim.x - me.x) >= Math.abs(aim.y - me.y);
+ const up = Math.floor(stuckFor / 96) % 2 === 0;
+ const side = alongX ? (up ? 'KeyW' : 'KeyS') : (up ? 'KeyD' : 'KeyA');
+ if (!keys.includes(side)) keys.push(side);
+ }
+ if (TRACE && spent % 160 === 0) {
+ console.log(` ${label} @${spent}: at ${Math.round(me.x)},${Math.round(me.y)} `
+ + `aim ${Math.round(aim.x)},${Math.round(aim.y)} (${plan.length} waypoints) keys ${keys.join('+') || 'none'} gap ${Math.round(gap)}`);
+ }
+ await exec(stepScript(keys, STEP, leg.swing ? 'Space' : null));
+ } else {
+ // Between areas: the next scene has not handed out its entities yet.
+ await exec(stepScript([], STEP, null));
+ }
+ spent += STEP;
+ frames += STEP;
+ }
+
+ if (!arrived) {
+ failure = `${label} — ${spent >= timeout ? 'ran out of leg budget' : 'ran out of run budget'} after ${spent} frames`
+ + (last ? `; last seen ${Math.round(last.me.x)},${Math.round(last.me.y)} with the goal at `
+ + `${Math.round(last.goal.x)},${Math.round(last.goal.y)} (${Math.round(last.gap)} away)` : '; never saw both')
+ + (deaths ? `; died ${deaths}x on this leg` : '');
+ break;
+ }
+ done.push(label);
+ console.log(` reached ${label} (${frames} frames in)`);
+ }
+
+ if (OUT) await writeFile(OUT, (await win.webContents.capturePage()).toPNG());
+ const final = await probe([]).catch(() => ({ scene: null }));
+ stop();
+ server.close();
+
+ const ok = !failure && errors.length === 0;
+ console.log(`${ok ? '✓' : '✗'} ${path.basename(DIR)} — ${done.length}/${route.legs.length} legs, `
+ + `${frames} frames, ended in ${final.scene ?? '(nothing)'}, errors=${errors.length}`);
+ if (failure) console.log(` ${failure}`);
+ for (const e of errors.slice(0, 5)) console.log(` ${e}`);
+ app.exit(ok ? 0 : 1);
+}
+
+app.whenReady().then(main).catch((e) => {
+ console.error('✗ play-through failed:', e);
+ app.exit(2);
+});
diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjs
index 16992e1c1..158916b63 100644
--- a/tools/releaseGate.mjs
+++ b/tools/releaseGate.mjs
@@ -38,7 +38,7 @@ export const CRITERIA = [
id: 'package-answers-input',
says: 'a packaged game visibly answers the input its project declares',
answeredBy: 'node tools/verify-golden.mjs --tier release',
- needs: ['desktop/scripts/inputScript.mjs'],
+ needs: ['tools/launchers/inputScript.mjs'],
},
{
id: 'launch-smoke-every-platform',
@@ -47,8 +47,8 @@ export const CRITERIA = [
+ ' && node tools/verify-desktop-render.mjs --tier pr'
+ ' && node tools/verify-native-boot.mjs --platform android --examples all',
needs: [
- 'desktop/scripts/launch-export.mjs',
- 'desktop/scripts/launch-minigame.mjs',
+ 'tools/launchers/launch-export.mjs',
+ 'tools/launchers/launch-minigame.mjs',
'tools/verify-desktop-render.mjs',
'tools/verify-native-boot.mjs',
],
@@ -142,7 +142,7 @@ export const CRITERIA = [
answeredBy: 'node tools/verify-playthrough.mjs',
needs: [
'tools/verify-playthrough.mjs',
- 'desktop/scripts/play-through.mjs',
+ 'tools/launchers/play-through.mjs',
'examples/celestial-heights/playthrough.json',
],
},
diff --git a/tools/verify-golden.mjs b/tools/verify-golden.mjs
index b6b40682f..3c1c5c068 100644
--- a/tools/verify-golden.mjs
+++ b/tools/verify-golden.mjs
@@ -39,7 +39,8 @@ const NO_PARITY = argv.includes('--no-parity');
/** Targets this runner owns; the rest belong to the native/desktop verifiers.
* A mini-game needs its vendor's globals, so it goes through its own launcher. */
const OWNED = new Set(['web', 'playable', 'wechat']);
-const LAUNCHER = (target) => (target === 'wechat' ? 'launch-minigame.mjs' : 'launch-export.mjs');
+const LAUNCHER = (target) => path.join(ROOT, 'tools', 'launchers',
+ target === 'wechat' ? 'launch-minigame.mjs' : 'launch-export.mjs');
/** Targets whose surface this runner can size to the editor's, which is what
* makes a frame comparable at all. Measured on one project: web 0.0009,
* playable 0.0027, wechat 0.0027 — the packaging wrapper is not what differs. */
@@ -179,8 +180,10 @@ function probePositions(target, dir, w, h, names, extra = []) {
function launchPackage(id, target, args) {
const run = retryOnDeadGpu(
() => {
- const r = runTool('npx', ['electron', path.join('scripts', LAUNCHER(target)), ...args],
- { encoding: 'utf8', cwd: DESKTOP });
+ // Opening a PACKAGE needs no editor — the launchers are engine-side, so a
+ // checkout without one can still judge what it shipped.
+ const r = runTool('pnpm', ['exec', 'electron', LAUNCHER(target), ...args],
+ { encoding: 'utf8', cwd: ROOT });
// The launcher prints a ✓/✗ line once it has looked at the frame; that
// line existing is what says a measurement happened.
const verdictLine = (r.stdout || '').split('\n').find((l) => l.startsWith('✓') || l.startsWith('✗'));
diff --git a/tools/verify-playthrough.mjs b/tools/verify-playthrough.mjs
index 696700073..70646161b 100644
--- a/tools/verify-playthrough.mjs
+++ b/tools/verify-playthrough.mjs
@@ -59,12 +59,12 @@ if (exported.status !== 0) {
process.exit(1);
}
-const played = runTool('npx', [
- 'electron', path.join('scripts', 'play-through.mjs'),
+const played = runTool('pnpm', [
+ 'exec', 'electron', path.join(ROOT, 'tools', 'launchers', 'play-through.mjs'),
'--dir', out, '--route', ROUTE,
'--out', path.join(WORK, `${PROJECT}.png`),
'--budget', '26000',
-], { encoding: 'utf8', cwd: DESKTOP });
+], { encoding: 'utf8', cwd: ROOT });
for (const line of (played.stdout || '').split('\n')) if (line.trim()) console.log(line);
if (!argv.includes('--keep')) rmSync(WORK, { recursive: true, force: true });