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.

feat(examples): the arena serves itself, and a leaver takes its pawn

yhh90c4b54e62bc
diff --git a/docs/astro/src/content/docs/scripting/networking.mdx b/docs/astro/src/content/docs/scripting/networking.mdx
index 6eafd7044..81c1e1d77 100644
--- a/docs/astro/src/content/docs/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/scripting/networking.mdx
@@ -112,8 +112,15 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplin
server plus client views run side by side, zero networking setup.
- **Dedicated servers**: the same gameplay code runs headless under Node —
`import { loadEsengineModule, createHeadlessApp, runHeadless } from 'esengine/node'`.
-
-See the **Multiplayer Arena** example for the full pattern — replication, per-tick input, and client prediction — in ~130 lines.
+ Install what the project registered at module scope with
+ `flushPendingRegistrations(app)`, the same door the shipped web runtime uses,
+ and the authority runs the project's own systems rather than a copy of them.
+- **Reconnect is yours for now**: `Replicated.owner` is a *connection* id, and a
+ player who reconnects gets a new one. Nothing in the SDK carries an identity
+ across a dropped socket, so a stable player id, a session token and a grace
+ window belong to your game.
+
+See the **Multiplayer Arena** example for the full pattern — replication, per-tick input, and client prediction — in ~130 lines. Its `server/` directory is the dedicated-server half: the same project, headless, behind a real WebSocket.
### Interest management — who sees what
diff --git a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
index 435d6e590..454236bd2 100644
--- a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx
@@ -109,8 +109,12 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上
客户端视图并排运行,零联网配置。
- **专用服务器**:同一份玩法代码可在 Node 下无头运行——
`import { loadEsengineModule, createHeadlessApp, runHeadless } from 'esengine/node'`。
+ 再用 `flushPendingRegistrations(app)` 装上项目在模块作用域注册的东西(与正式 Web
+ 运行时同一道门),权威端跑的就是项目自己的系统,而不是它的副本。
+- **重连目前由你负责**:`Replicated.owner` 是*连接* id,玩家重连会拿到新的一个。
+ SDK 没有任何身份能跨越断开的 socket,所以稳定玩家 id、会话令牌和宽限期都归你的游戏。
-完整范式(复制、每 tick 输入、客户端预测)见 **Multiplayer Arena** 示例(约 130 行)。
+完整范式(复制、每 tick 输入、客户端预测)见 **Multiplayer Arena** 示例(约 130 行)。它的 `server/` 目录就是专用服务器那一半:同一个项目,无头运行,后面是一条真实的 WebSocket。
### 兴趣管理——谁看见什么
diff --git a/examples/README.md b/examples/README.md
index c011e99eb..284cfce57 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -49,7 +49,7 @@ for your own game.
| **rich-text** | UI | A live rich-text playground — type markup (and 中文 via IME) into a TextInput and watch a `Text` render bold/italic/color/font-size runs. |
| **enemy-ai** | AI | A state machine drives enemies to patrol, sense the player, and chase via A* navigation. |
| **camera-follow** | Gameplay | The camera director — `FollowTarget` damping + dead zone, `shakeCamera` impacts, `setViewTarget` blends to an overview camera. |
-| **multiplayer-arena** | Networking | Server-authoritative multiplayer with client prediction: each player steers a replicated pawn, own-pawn input applies instantly ('2 Players' in the Play dropdown runs listen server + client). |
+| **multiplayer-arena** | Networking | Server-authoritative multiplayer with client prediction: each player steers a replicated pawn, own-pawn input applies instantly ('2 Players' in the Play dropdown runs listen server + client). `server/` runs the same project headless behind a real WebSocket. |
| **platformer** | Game | A tiny platformer — run, jump and collect coins. |
| **video-puzzle** | Game | A tile-swap puzzle whose tiles are live regions of ONE playing video — texture-handle sharing + per-piece `uvOffset`/`uvScale`. |
| **space-shooter** | Game | A vertical shmup with prefabs, a HUD and a difficulty ramp. |
diff --git a/examples/multiplayer-arena/README.md b/examples/multiplayer-arena/README.md
index b3a33c4a6..245209440 100644
--- a/examples/multiplayer-arena/README.md
+++ b/examples/multiplayer-arena/README.md
@@ -33,3 +33,60 @@ Plain **Single Player** Play works too: the same systems run offline.
authoritative state every tick.
- The same gameplay code ships unchanged against a real WebSocket server
(`esengine/node` + `createHeadlessApp`).
+
+## Dedicated server
+
+The Play-mode preview runs the authority inside player 1's own process. That is
+the right shape for developing and the wrong one for shipping — it needs
+somebody's game to be running, and a connection there never drops.
+
+`server/` is the shipping shape: the same project, headless, behind a real
+WebSocket.
+
+```sh
+cd server
+npm install # ws, and esbuild to bundle with
+npm start # → [arena] listening on ws://127.0.0.1:8080 (60 Hz)
+```
+
+`run.mjs` bundles `server/main.ts` with `esengine` aliased at the SDK's headless
+build (`index.node.js`), then runs it. The SDK and the engine wasm are taken as
+a pair from what the editor staged in `.esengine/` — open the project in the
+editor once, or pass `--sdk` / `--wasm` yourself. `--port`, `--host` and `--fps`
+do what they look like.
+
+**Nothing under `src/` is server-specific.** The server imports the project's
+own `src/main.ts`, so the authority runs the very systems the browser runs, and
+`flushPendingRegistrations` installs them through the same door the shipped web
+runtime uses. The one thing this process says about itself is:
+
+```ts
+arena.hostPlays = false; // nobody is at a keyboard here
+```
+
+A listen server hosts player 0 itself; a dedicated server owns no pawn. That
+single flag is the whole difference, and `ProvisionPawnsSystem` reads it.
+
+### What only a real server exercises
+
+Two things the preview structurally cannot show, both handled here:
+
+- **A connection that leaves.** The preview's players are MessagePorts that live
+ as long as the session. A real socket closes, `detachConnection` drops the id,
+ and `ProvisionPawnsSystem` retires that pawn on its next fixed tick — without
+ it a long-running server fills with pawns nobody is steering.
+- **An authority with no local player.** Everything in `src/` gates on
+ `arena.hostPlays` or on `Net.role`, so the same file serves all three
+ deployments: offline, listen server, dedicated.
+
+`node tools/check-arena-server.mjs` in the engine repo asserts exactly that —
+two real clients over a socket, input that moves and clamps, movement witnessed
+by a third party, and a leaver whose pawn goes with them.
+
+### What it does not do yet
+
+A player who reconnects arrives as a **new connection id**, so they get a new
+pawn rather than their old one back. Ownership is keyed on the connection
+(`Replicated.owner`), and the SDK has no notion of a player identity that
+outlives a socket — a stable id, a session token, and a reconnect window all
+belong to the game for now. Worth knowing before you build a match around it.
diff --git a/examples/multiplayer-arena/server/main.ts b/examples/multiplayer-arena/server/main.ts
new file mode 100644
index 000000000..b6df39ed4
--- /dev/null
+++ b/examples/multiplayer-arena/server/main.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The dedicated server for this arena — the same game, no window.
+ *
+ * The editor's "2 Players (Listen Server)" preview runs the authority inside a
+ * player's own process over in-memory ports. That is the right shape for
+ * developing, and the wrong shape for shipping: it needs somebody's game to be
+ * running, and it never exercises a connection that DROPS.
+ *
+ * This entry is the shipping shape. It boots the same engine wasm with no
+ * renderer (`createHeadlessApp`), installs the project's own systems through
+ * the same door the shipped web runtime uses (`flushPendingRegistrations`), and
+ * accepts real WebSocket clients. Not one line of `src/` is server-specific —
+ * the only thing this process says about itself is `arena.hostPlays = false`,
+ * because there is nobody at a keyboard here.
+ *
+ * node server/run.mjs --port 8080
+ *
+ * A browser client then connects to `ws://<host>:8080` instead of being handed
+ * a MessagePort. See the README's "Dedicated server" section.
+ */
+import { WebSocketServer, type WebSocket } from 'ws';
+import {
+ loadEsengineModule, createHeadlessApp, runHeadless,
+ flushPendingRegistrations, Net, type NetTransport,
+} from 'esengine/node';
+import { arena } from '../src/net';
+// Side-effect import: `src/main.ts` registers the arena's systems at module
+// scope, exactly as it does in the browser. The server runs the project's real
+// entry point rather than a reimplementation of it.
+import '../src/main';
+
+interface ServerOptions {
+ port: number;
+ host: string;
+ /** Directory holding the web engine build (esengine.js + esengine.wasm). */
+ wasm: string;
+ /** Simulation rate. The replication cadence follows the fixed timestep. */
+ fps: number;
+}
+
+/**
+ * One accepted `ws` connection as a {@link NetTransport}. The replication layer
+ * asks a transport for exactly two things — send a frame, subscribe to frames —
+ * so any ordered, reliable link can carry a session; `ws` is simply the one a
+ * browser can dial.
+ */
+function wsTransport(socket: WebSocket): NetTransport {
+ const handlers = new Set<(data: string | ArrayBuffer) => void>();
+ socket.on('message', (data: Buffer | ArrayBuffer | Buffer[], isBinary: boolean) => {
+ // Binary frames are the delta stream and must reach the channel as an
+ // ArrayBuffer; `ws` hands over a Buffer that is usually a VIEW into a
+ // larger pooled allocation, so the byte range has to be sliced out.
+ const frame = isBinary ? toArrayBuffer(data) : String(data);
+ for (const handler of [...handlers]) handler(frame);
+ });
+ return {
+ send: (data) => socket.send(data),
+ on: (_event, handler) => {
+ handlers.add(handler);
+ return () => handlers.delete(handler);
+ },
+ };
+}
+
+function toArrayBuffer(data: Buffer | ArrayBuffer | Buffer[]): ArrayBuffer {
+ if (data instanceof ArrayBuffer) return data;
+ const buf = Array.isArray(data) ? Buffer.concat(data) : data;
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+}
+
+export async function startArenaServer(options: ServerOptions): Promise<() => Promise<void>> {
+ // No keyboard on this machine, so no pawn for player 0 — the one line that
+ // separates a dedicated server from the editor's listen server.
+ arena.hostPlays = false;
+
+ const engineModule = await loadEsengineModule(options.wasm);
+ const app = createHeadlessApp(engineModule);
+ // Install what `src/main.ts` registered at import time. Before the loop
+ // starts, so the authority's first tick already runs the arena's systems.
+ flushPendingRegistrations(app);
+
+ const server = app.getResource(Net).startServer();
+
+ const wss = new WebSocketServer({ port: options.port, host: options.host });
+ await new Promise<void>((resolve, reject) => {
+ wss.once('listening', resolve);
+ wss.once('error', reject);
+ });
+
+ wss.on('connection', (socket: WebSocket) => {
+ const id = server.attachConnection(wsTransport(socket));
+ console.log(`[arena] connection ${id} attached`);
+ // Detaching is what makes the roster shrink: `clientIds` drops this id,
+ // and ProvisionPawnsSystem retires the pawn on its next fixed tick.
+ // Without it the arena fills up with pawns nobody is steering.
+ const drop = () => {
+ server.detachConnection(id);
+ console.log(`[arena] connection ${id} dropped`);
+ };
+ socket.on('close', drop);
+ socket.on('error', drop);
+ });
+
+ const stopLoop = runHeadless(app, { fps: options.fps });
+ const address = wss.address();
+ const port = typeof address === 'object' && address ? address.port : options.port;
+ console.log(`[arena] listening on ws://${options.host}:${port} (${options.fps} Hz)`);
+
+ return async () => {
+ stopLoop();
+ await new Promise<void>((resolve) => wss.close(() => resolve()));
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Command line. `--port 0` asks the OS for a free port and prints the one it
+// got, which is how the repo's gate runs this without picking a fixed number.
+// ---------------------------------------------------------------------------
+
+function arg(name: string, fallback: string): string {
+ const i = process.argv.indexOf(`--${name}`);
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
+}
+
+const stop = await startArenaServer({
+ port: Number(arg('port', '8080')),
+ host: arg('host', '127.0.0.1'),
+ wasm: arg('wasm', 'wasm'),
+ fps: Number(arg('fps', '60')),
+});
+
+for (const signal of ['SIGINT', 'SIGTERM'] as const) {
+ process.on(signal, () => { void stop().then(() => process.exit(0)); });
+}
diff --git a/examples/multiplayer-arena/server/package.json b/examples/multiplayer-arena/server/package.json
new file mode 100644
index 000000000..161ca15b9
--- /dev/null
+++ b/examples/multiplayer-arena/server/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "multiplayer-arena-server",
+ "private": true,
+ "type": "module",
+ "description": "Dedicated server for the Multiplayer Arena example — the same project, headless.",
+ "scripts": {
+ "start": "node run.mjs",
+ "build": "node run.mjs --build-only"
+ },
+ "dependencies": {
+ "ws": "^8.21.0"
+ },
+ "devDependencies": {
+ "esbuild": "^0.27.0"
+ }
+}
diff --git a/examples/multiplayer-arena/server/run.mjs b/examples/multiplayer-arena/server/run.mjs
new file mode 100644
index 000000000..de3df6aa4
--- /dev/null
+++ b/examples/multiplayer-arena/server/run.mjs
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Build-and-run for the arena's dedicated server.
+ *
+ * The gameplay under `src/` is TypeScript that imports the bare specifier
+ * `esengine`, exactly like the code the browser runs. A server is the same
+ * project pointed at a different SDK build, so this does what every other
+ * Estella export already does: bundle the entry with esbuild and alias
+ * `esengine` at the SDK flavour this platform needs — here `index.node.js`,
+ * the headless one.
+ *
+ * Aliasing BOTH `esengine` and `esengine/node` to the same file is not a
+ * detail: two SDK copies would mean two component registries, and the
+ * handshake's schema check would reject the server's own clients.
+ *
+ * node server/run.mjs [--port 8080] [--host 127.0.0.1] [--fps 60]
+ * [--sdk <dir>] [--wasm <dir>] [--build-only]
+ *
+ * `--sdk` and `--wasm` default to what the editor stages inside the project
+ * (`.esengine/sdk`, `.esengine/play/wasm`), falling back to the engine repo's
+ * own build outputs when this example is run from a checkout.
+ */
+import { spawn } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = path.resolve(HERE, '..');
+const REPO = path.resolve(PROJECT, '..', '..');
+
+const argv = process.argv.slice(2);
+function flag(name, fallback) {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : fallback;
+}
+/**
+ * SDK and wasm are resolved as a PAIR, never independently: they carry a shared
+ * ABI layout hash and the engine refuses a module built from another component
+ * schema. A fresh SDK beside a wasm an old editor session staged is the easy
+ * mistake, and it dies at boot with a hash mismatch, not anywhere useful.
+ */
+const PAIRS = [
+ // What the editor stages inside a project when it opens it.
+ { sdk: path.join(PROJECT, '.esengine', 'sdk'), wasm: path.join(PROJECT, '.esengine', 'play', 'wasm') },
+ // Running this example from an engine checkout.
+ { sdk: path.join(REPO, 'sdk', 'dist'), wasm: path.join(REPO, 'build', 'wasm', 'web') },
+];
+const pair = PAIRS.find((c) => existsSync(path.join(c.sdk, 'index.node.js')) && existsSync(path.join(c.wasm, 'esengine.wasm')))
+ ?? PAIRS[PAIRS.length - 1];
+
+const sdkDir = path.resolve(flag('sdk', pair.sdk));
+const wasmDir = path.resolve(flag('wasm', pair.wasm));
+
+for (const [what, dir, needs] of [
+ ['SDK', sdkDir, 'index.node.js'],
+ ['engine wasm', wasmDir, 'esengine.wasm'],
+]) {
+ if (existsSync(path.join(dir, needs))) continue;
+ console.error(`arena server: no ${what} at ${dir} (looked for ${needs}).`);
+ console.error(` Open the project in the editor once, or pass --${what === 'SDK' ? 'sdk' : 'wasm'} <dir>.`);
+ process.exit(2);
+}
+
+const sdkEntry = path.join(sdkDir, 'index.node.js');
+const outfile = path.join(PROJECT, '.esengine', 'cache', 'server.mjs');
+
+const { build } = await import('esbuild');
+await build({
+ entryPoints: [path.join(HERE, 'main.ts')],
+ outfile,
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ target: 'node20',
+ sourcemap: true,
+ logLevel: 'info',
+ // `ws` is CommonJS: the bundle calls `require('events')` and an ESM output has
+ // no `require`. Building one from this module's URL is the esbuild recipe —
+ // only node builtins reach it, everything else is already inlined.
+ banner: {
+ js: "import { createRequire as __estellaCreateRequire } from 'node:module';\n"
+ + 'const require = __estellaCreateRequire(import.meta.url);',
+ },
+ // One SDK instance, whichever specifier reached it.
+ alias: { esengine: sdkEntry, 'esengine/node': sdkEntry },
+ // `ws` is a real dependency of the server (and only of the server): resolve it
+ // from the server's own install first, then from the engine checkout.
+ nodePaths: [
+ path.join(HERE, 'node_modules'),
+ path.join(REPO, 'node_modules'),
+ path.join(REPO, 'sdk', 'node_modules'),
+ ].filter((p) => existsSync(p)),
+});
+
+if (argv.includes('--build-only')) {
+ console.log(`arena server: built ${outfile}`);
+ process.exit(0);
+}
+
+// The wasm directory is resolved against the server process's cwd, so pass it
+// absolute and let the child run wherever it likes.
+const passthrough = ['port', 'host', 'fps'].flatMap((name) => {
+ const value = flag(name, null);
+ return value === null ? [] : [`--${name}`, value];
+});
+const child = spawn(process.execPath, [outfile, '--wasm', wasmDir, ...passthrough], { stdio: 'inherit' });
+child.on('exit', (code, signal) => process.exit(signal ? 1 : (code ?? 0)));
diff --git a/examples/multiplayer-arena/server/tsconfig.json b/examples/multiplayer-arena/server/tsconfig.json
new file mode 100644
index 000000000..631d37db6
--- /dev/null
+++ b/examples/multiplayer-arena/server/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "//": "The server is a separate program from the game: Node built-ins, its own deps, and the headless SDK entry. The project's root tsconfig covers src/ only, so this one holds the server half. It only ever checks — run.mjs builds with esbuild.",
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "types": ["node"],
+ "noEmit": true,
+ "paths": {
+ "esengine": ["../.esengine/sdk/index.d.ts"],
+ "esengine/node": ["../.esengine/sdk/index.node.d.ts"],
+ "esengine/wasm": ["../.esengine/sdk/wasm.d.ts"]
+ }
+ },
+ "include": ["**/*.ts", "../src/**/*.ts"]
+}
diff --git a/examples/multiplayer-arena/src/net.ts b/examples/multiplayer-arena/src/net.ts
index 81b01a4a4..a02a9d981 100644
--- a/examples/multiplayer-arena/src/net.ts
+++ b/examples/multiplayer-arena/src/net.ts
@@ -9,6 +9,20 @@ import { Pawn } from './components';
const BOUND_X = 420;
const BOUND_Y = 278;
+/** The player id of whoever sits at THIS machine's keyboard. Connection ids the
+ * server hands out start at 1, so 0 is never a remote player. */
+const HOST_PLAYER = 0;
+
+/**
+ * The one thing a listen server and a dedicated server disagree about. The
+ * editor preview (and offline Play) hosts player 0 on the local keyboard; a
+ * dedicated server has none, sets `hostPlays = false` at startup, and owns no
+ * pawn. Nothing else in this file can tell the deployments apart.
+ */
+export const arena = {
+ hostPlays: true,
+};
+
const PLAYER_COLORS = [
{ r: 0.35, g: 0.85, b: 1.0, a: 1 }, // host — cyan
{ r: 1.0, g: 0.55, b: 0.35, a: 1 }, // player 2 — orange
@@ -61,23 +75,34 @@ function spawnPawn(world: World, player: number): void {
}
/**
- * Authority-side player provisioning: the host pawn always exists (so plain
- * single-player Play works too), and each handshaken client connection gets a
- * pawn. Stateless — derives what exists from the World each tick.
+ * Authority-side provisioning, both directions: a player owed a pawn gets one,
+ * a pawn whose player left is retired. Stateless — the roster is derived from
+ * the World and the connection list each tick. Retirement only ever fires on a
+ * real server; the preview's MessagePorts never drop, so it never ran there.
*/
export const provisionPawnsSystem = defineSystem(
[GetWorld(), Res(Net)],
(world, net) => {
if (net.role === 'client') return;
+ // Who is entitled to a pawn this tick.
+ const live = new Set<number>();
+ if (arena.hostPlays) live.add(HOST_PLAYER);
+ for (const id of net.server?.clientIds ?? []) live.add(id);
+
const have = new Set<number>();
for (const e of world.getEntitiesWithComponents([Pawn])) {
- have.add((world.tryGet(e, Pawn) as { player: number }).player);
- }
- if (!have.has(0)) spawnPawn(world, 0);
- if (net.server) {
- for (const id of net.server.clientIds) {
- if (!have.has(id)) spawnPawn(world, id);
+ const player = (world.tryGet(e, Pawn) as { player: number }).player;
+ if (!live.has(player)) {
+ // Despawning the authority's entity is the whole retirement:
+ // replication turns it into a despawn on every client that can
+ // see it, and the ghost goes with it.
+ world.despawn(e as Entity);
+ continue;
}
+ have.add(player);
+ }
+ for (const player of live) {
+ if (!have.has(player)) spawnPawn(world, player);
}
},
{ name: 'ProvisionPawnsSystem' },
@@ -95,7 +120,7 @@ export const movePawnsSystem = defineSystem(
if (net.role === 'client') return;
for (const e of world.getEntitiesWithComponents([Pawn, Replicated])) {
const repl = world.tryGet(e, Replicated)!;
- const actions = repl.owner === 0
+ const actions = repl.owner === HOST_PLAYER
? { move: readMove(input) }
: (net.server?.tickInputOf(repl.owner)?.actions ?? {});
applyMove(world as World, e as Entity, actions, time.fixedDelta);
diff --git a/tools/check-arena-server.mjs b/tools/check-arena-server.mjs
new file mode 100644
index 000000000..6603572d3
--- /dev/null
+++ b/tools/check-arena-server.mjs
@@ -0,0 +1,256 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file check-arena-server.mjs — a multiplayer game runs without the editor.
+ *
+ * `check-headless-export` proves a project PACKAGES from the command line. This
+ * proves the other half of shipping a multiplayer one: that the authority runs
+ * as an ordinary Node process, over a real socket, driving the project's own
+ * gameplay code — and that the parts the editor's preview structurally cannot
+ * reach still work.
+ *
+ * The preview wires its players over MessagePorts inside one process. Those
+ * never drop, so nothing there ever exercised a connection LEAVING; and the
+ * host is always a player, so nothing exercised an authority with no pawn of
+ * its own. Both are ordinary facts of a dedicated server, and both are checked
+ * here against `examples/multiplayer-arena`:
+ *
+ * 1. the server boots headless (no renderer, no editor) and accepts sockets
+ * 2. no phantom host pawn — a keyboard-less authority owns nothing
+ * 3. a client's input moves ITS pawn, and the arena wall clamps it
+ * 4. that movement reaches a THIRD party as replicated state
+ * 5. a client that leaves takes its pawn with it
+ *
+ * node tools/check-arena-server.mjs
+ */
+import { spawn, spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const PROJECT = path.join(ROOT, 'examples', 'multiplayer-arena');
+const SDK = path.join(ROOT, 'sdk', 'dist', 'index.node.js');
+const WASM = path.join(ROOT, 'build', 'wasm', 'web');
+
+/** Arena bounds, from the example's own movement rule. */
+const BOUND_X = 420;
+const STEP = 1 / 60;
+
+const work = mkdtempSync(path.join(tmpdir(), 'estella-arena-'));
+let server = null;
+
+function fail(message, detail) {
+ console.error(`check-arena-server: ${message}`);
+ if (detail) console.error(detail);
+ cleanup();
+ process.exit(1);
+}
+
+function cleanup() {
+ if (server && server.exitCode === null) server.kill();
+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+}
+
+const delay = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/** tsc and esbuild both want a path, not a file:// URL, with forward slashes. */
+const posix = (p) => p.split(path.sep).join('/');
+
+// ---------------------------------------------------------------------------
+// Build both ends from the project's own sources.
+// ---------------------------------------------------------------------------
+
+/**
+ * Type-check the server entry first: esbuild only strips types, so drift from
+ * the SDK would surface as a runtime throw. The project's own tsconfig covers
+ * `src/` alone — a game project has no `ws` or `@types/node` — so the check
+ * runs from here, against the SDK install that does.
+ */
+const TSC = path.join(ROOT, 'sdk', 'node_modules', 'typescript', 'bin', 'tsc');
+const SDK_TYPES = path.join(ROOT, 'sdk', 'node_modules', '@types');
+const tsconfig = path.join(work, 'tsconfig.json');
+writeFileSync(tsconfig, JSON.stringify({
+ compilerOptions: {
+ target: 'ES2022', module: 'ESNext', moduleResolution: 'bundler',
+ strict: true, skipLibCheck: true, noEmit: true, esModuleInterop: true,
+ types: ['node'], typeRoots: [posix(SDK_TYPES)],
+ baseUrl: '.',
+ paths: {
+ esengine: [posix(path.join(ROOT, 'sdk', 'dist', 'index.d.ts'))],
+ 'esengine/node': [posix(path.join(ROOT, 'sdk', 'dist', 'index.node.d.ts'))],
+ ws: [posix(path.join(SDK_TYPES, 'ws', 'index.d.ts'))],
+ },
+ },
+ include: [posix(path.join(PROJECT, 'server', '**', '*.ts')), posix(path.join(PROJECT, 'src', '**', '*.ts'))],
+}, null, 2));
+
+const typed = spawnSync(process.execPath, [TSC, '-p', tsconfig], { encoding: 'utf8', cwd: ROOT });
+if (typed.status !== 0) {
+ fail('the server entry does not type-check against the SDK.', typed.stdout || typed.stderr);
+}
+
+const built = spawnSync(process.execPath, [
+ path.join(PROJECT, 'server', 'run.mjs'), '--build-only',
+], { encoding: 'utf8', cwd: ROOT });
+if (built.status !== 0) fail('the server bundle failed to build.', built.stderr || built.stdout);
+
+/**
+ * The client half, built from the project's REAL entry point: it registers the
+ * same components (the handshake compares schemas and would reject a faked
+ * probe) and runs the same input/prediction system a browser would. The second
+ * client registers nothing, which is what makes it a fair witness.
+ */
+const probeSource = `
+// 'esengine' rather than a path: the alias below points it at the same headless
+// SDK the server bundle uses, so probe and project share one module instance.
+export { loadEsengineModule, createHeadlessApp, flushPendingRegistrations, GameSocket, Net, Input, Replicated, Transform } from 'esengine';
+import ${JSON.stringify(posix(path.join(PROJECT, 'src', 'main.ts')))};
+`;
+writeFileSync(path.join(work, 'probe.entry.ts'), probeSource);
+
+const probeOut = path.join(work, 'probe.mjs');
+const { build } = await import('esbuild');
+await build({
+ entryPoints: [path.join(work, 'probe.entry.ts')],
+ outfile: probeOut,
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ target: 'node20',
+ logLevel: 'silent',
+ // The project's `import ... from 'esengine'` resolves to the same headless SDK
+ // the server bundle uses — one build on both ends, which is what the
+ // handshake's ABI/schema check insists on.
+ alias: { esengine: SDK, 'esengine/node': SDK },
+});
+
+const probe = await import(pathToFileURL(probeOut).href);
+
+// ---------------------------------------------------------------------------
+// Boot the server and learn the port it got.
+// ---------------------------------------------------------------------------
+
+server = spawn(process.execPath, [
+ path.join(PROJECT, '.esengine', 'cache', 'server.mjs'),
+ '--port', '0', '--wasm', WASM,
+], { cwd: ROOT });
+
+let serverLog = '';
+server.stdout.on('data', (d) => { serverLog += d.toString(); });
+server.stderr.on('data', (d) => { serverLog += d.toString(); });
+server.on('exit', (code) => {
+ if (code !== 0 && code !== null) fail(`the server exited ${code}.`, serverLog);
+});
+
+const url = await (async () => {
+ for (let i = 0; i < 100; i++) {
+ const match = serverLog.match(/listening on (ws:\/\/\S+)/);
+ if (match) return match[1];
+ await delay(100);
+ }
+ return null;
+})();
+if (!url) fail('the server never reported a listening address.', serverLog);
+
+// ---------------------------------------------------------------------------
+// Two clients.
+// ---------------------------------------------------------------------------
+
+/** A client App on a real socket, ticking on the fixed step like a game does. */
+async function connectClient({ withGameplay }) {
+ const app = probe.createHeadlessApp(await probe.loadEsengineModule(WASM));
+ // Only the first client installs the project's systems; the spectator runs
+ // the replication plugin alone, so what it sees it was SENT.
+ if (withGameplay) probe.flushPendingRegistrations(app);
+ const socket = new probe.GameSocket({ url });
+ socket.connect();
+ const client = await app.getResource(probe.Net).connect(socket, { interpolationDelayTicks: 0 });
+ return { app, client, socket };
+}
+
+/** Every replicated entity this client can see, with its position. */
+function ghosts(app) {
+ return app.world.getEntitiesWithComponents([probe.Replicated]).map((e) => ({
+ entity: e,
+ x: app.world.tryGet(e, probe.Transform)?.position.x ?? NaN,
+ }));
+}
+
+/** Tick both apps for `seconds` of simulated time, letting the socket breathe. */
+async function run(apps, seconds) {
+ for (let i = 0; i < Math.round(seconds / STEP); i++) {
+ for (const app of apps) await app.tick(STEP);
+ await delay(4);
+ }
+}
+
+let player, spectator;
+try {
+ player = await connectClient({ withGameplay: true });
+ spectator = await connectClient({ withGameplay: false });
+} catch (err) {
+ fail(`a client could not complete the handshake: ${err?.message ?? err}`, serverLog);
+}
+
+// Let the roster settle: the authority provisions a pawn per connection on its
+// next fixed tick, and the spawns come back over the socket.
+await run([player.app, spectator.app], 0.5);
+
+// 2 — the authority has no keyboard, so it owns no pawn. Two connections, two
+// pawns; a third would be the host phantom this deployment must not have.
+const seen = ghosts(spectator.app);
+if (seen.length !== 2) {
+ fail(`the spectator sees ${seen.length} replicated pawn(s), expected 2 (one per connection).`
+ + ' A third would mean the dedicated server spawned a host pawn it cannot steer.', serverLog);
+}
+
+// 3 — hold a direction. This is the project's own input system reading the
+// project's own key bindings; nothing here reaches past it to move anything.
+const input = player.app.getResource(probe.Input);
+input.keysDown.add('KeyD');
+
+const own = () => ghosts(player.app).find((g) => player.client.ownsEntity(g.entity));
+const startX = own()?.x;
+if (startX === undefined) fail('the connected client owns no pawn.', serverLog);
+
+await run([player.app, spectator.app], 0.4);
+const movedX = own().x;
+if (!(movedX > startX + 20)) {
+ fail(`holding right moved the owned pawn from ${startX} to ${movedX} — expected it to advance.`, serverLog);
+}
+
+// Long enough to cross the arena and pin against the wall. The clamp is part of
+// the shared movement rule, so server and prediction must agree on it exactly.
+await run([player.app, spectator.app], 3.0);
+input.keysDown.delete('KeyD');
+const wallX = own().x;
+if (Math.abs(wallX - BOUND_X) > 0.5) {
+ fail(`the owned pawn settled at x=${wallX}, expected the arena wall at ${BOUND_X}.`, serverLog);
+}
+
+// 4 — a third party saw it happen. The spectator runs no gameplay code at all,
+// so this position can only have arrived as replicated state.
+await run([player.app, spectator.app], 0.3);
+const witnessed = ghosts(spectator.app).map((g) => g.x);
+if (!witnessed.some((x) => Math.abs(x - BOUND_X) < 40)) {
+ fail(`the spectator never saw the moving pawn reach the wall (saw x=${witnessed.join(', ')}).`, serverLog);
+}
+
+// 5 — leaving takes the pawn with it. This is the assertion the editor's
+// preview cannot make: its MessagePorts never close.
+player.client.disconnect();
+player.socket.close();
+await run([spectator.app], 0.6);
+const after = ghosts(spectator.app);
+if (after.length !== 1) {
+ fail(`after a client left the spectator still sees ${after.length} pawn(s), expected 1.`
+ + ' The authority is not retiring pawns for departed connections.', serverLog);
+}
+
+spectator.client.disconnect();
+spectator.socket.close();
+cleanup();
+console.log('check-arena-server: multiplayer-arena served headless over a real socket —'
+ + ' no host phantom, input moved and clamped, replicated to a third party, and a leaver was retired.');
diff --git a/tools/check-golden.mjs b/tools/check-golden.mjs
index d698eccd2..269d29e88 100644
--- a/tools/check-golden.mjs
+++ b/tools/check-golden.mjs
@@ -55,6 +55,10 @@ const NEEDS_RUN = {
'pause-resume': 'suspend',
'hot-update': 'runBy',
rollback: 'runBy',
+ // A frame of two coloured squares is what a working session and a broken one
+ // both look like. Nothing about replication is visible in a screenshot, so the
+ // claim needs the run that opens a socket.
+ networking: 'runBy',
};
/** Commands a release is defined as running — what makes `runBy` more than a string. */
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 1ee0b4422..6290946c5 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -113,6 +113,10 @@ export const GATES = [
// And the boundary holds in practice: a real project packages from the command
// line with no editor built.
{ id: 'headless-export', run: 'node tools/check-headless-export.mjs' },
+ // The multiplayer half of that claim: an authority runs as a plain Node
+ // process over a real socket. Also the only check of two facts the editor's
+ // preview has no way to reach — no local player, and a connection that LEAVES.
+ { id: 'arena-server', run: 'node tools/check-arena-server.mjs' },
{ id: 'cycles', run: 'node tools/check-cycles.mjs' },
{ id: 'layers', run: 'node tools/check-layers.mjs' },
// A system's parameters are what the schedule knows about it; the World
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index 627f92927..8c89d8b62 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -277,6 +277,10 @@ export const GOLDEN = [
targets: ['web', 'desktop'],
tier: 'nightly',
interactGap: 'needs a listen server up before input means anything',
+ // A packaged frame cannot tell a live session from a dead one, so a run
+ // settles this instead: check-arena-server serves the project headless over
+ // a real socket and drives two clients through it, under static-gates.
+ runBy: 'node tools/run-gates.mjs --scope local --complete',
},
{
id: 'video-puzzle',