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(export): parameterize export by platform + desktop (Electron) target

esenginec7b748e96e87
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index fb8a804e1..d41068ec1 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -1,14 +1,21 @@
// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file Game export (REARCH_EDITOR_REALM Phase S — play == ship). Produces a
- * self-contained, static-servable web build of the open project:
- * - cookAssets → reachable assets (paths preserved) + assets.manifest.json
- * - esbuild the game host (gameHost.ts, esengine INLINED) → game.js
- * - copy the /wasm runtime
- * - emit index.html + game.config.json (the entry scene)
- * The host boots the SAME runtime the editor's play realm uses
- * (initPlayRealmRuntime), so the shipped game is what was played.
+ * @file Game export (REARCH_EDITOR_REALM Phase S / REARCH_EXPORT). Produces a
+ * self-contained build of the open project, parameterized by platform:
+ *
+ * web → a static-servable web build (cooked assets + manifest, the
+ * esbuild'd game host, the SDK + wasm runtime, index.html).
+ * desktop → the SAME web build under `app/`, wrapped in a runnable
+ * Electron app (main.cjs serving it over a custom `game://`
+ * scheme — file:// blocks the runtime's asset/wasm fetches),
+ * plus a package.json wired for `electron-builder`.
+ *
+ * The web payload is identical across targets and boots the SAME runtime
+ * the editor's play realm uses (gameHost → initPlayRealmRuntime), so the
+ * shipped game is what was played (play == ship). The host is origin-
+ * agnostic (relative fetch + import.meta.url), so the desktop scheme needs
+ * no host changes.
*
* Pure Node (esbuild + fs) — IPC wiring is in main.ts.
*/
@@ -19,8 +26,11 @@ import path from 'node:path';
import { cookAssets } from './cookAssets';
import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
+export type ExportPlatform = 'web' | 'desktop';
+
export interface ExportGameResult {
ok: boolean;
+ platform: ExportPlatform;
outDir: string;
/** Count of assets included (reachable from the entry scene). */
included: number;
@@ -54,10 +64,131 @@ function indexHtml(title: string): string {
`;
}
+/** A filesystem-safe slug for the app id / package name. */
+function slugify(title: string): string {
+ return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'game';
+}
+
+/** The Electron main process for an exported desktop game: serve the bundled web
+ * payload (./app) over a stable, fetch-enabled `game://` scheme and show it in a
+ * window. Mirrors the editor's estella:// scheme (file:// blocks fetch of sibling
+ * assets + wasm streaming, which the runtime needs). */
+function desktopMain(title: string): string {
+ return `'use strict';
+// Generated by Estella exportGame — the desktop shell for this game.
+const { app, protocol, BrowserWindow, net } = require('electron');
+const path = require('node:path');
+const { pathToFileURL } = require('node:url');
+
+const SCHEME = 'game';
+const ROOT = path.join(__dirname, 'app');
+const MIME = {
+ html: 'text/html', js: 'text/javascript', mjs: 'text/javascript', css: 'text/css',
+ json: 'application/json', wasm: 'application/wasm', map: 'application/json',
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
+ svg: 'image/svg+xml', ktx2: 'image/ktx2',
+ ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', aac: 'audio/aac',
+ fnt: 'text/plain', ttf: 'font/ttf', woff: 'font/woff', woff2: 'font/woff2',
+};
+
+// Emscripten/embind glue JIT-compiles call bridges (new Function) → needs unsafe-eval.
+process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
+
+protocol.registerSchemesAsPrivileged([
+ { scheme: SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true } },
+]);
+
+function createWindow() {
+ const win = new BrowserWindow({
+ width: 1280,
+ height: 720,
+ backgroundColor: '#0e121b',
+ title: ${JSON.stringify(title)},
+ webPreferences: { contextIsolation: true, sandbox: true },
+ });
+ win.removeMenu();
+ win.loadURL(SCHEME + '://app/index.html');
+}
+
+app.whenReady().then(() => {
+ protocol.handle(SCHEME, async (req) => {
+ let rel = decodeURIComponent(new URL(req.url).pathname).replace(/^\\/+/, '') || 'index.html';
+ const filePath = path.join(ROOT, rel);
+ // Contain within ROOT (no path traversal out of the bundled payload).
+ if (filePath !== ROOT && !filePath.startsWith(ROOT + path.sep)) {
+ return new Response('forbidden', { status: 403 });
+ }
+ try {
+ const res = await net.fetch(pathToFileURL(filePath).toString());
+ const ext = path.extname(filePath).slice(1).toLowerCase();
+ const headers = new Headers(res.headers);
+ headers.set('content-type', MIME[ext] || 'application/octet-stream');
+ return new Response(res.body, { status: res.status, headers });
+ } catch {
+ return new Response('not found', { status: 404 });
+ }
+ });
+ createWindow();
+ app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
+});
+
+app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
+`;
+}
+
+function desktopPackageJson(title: string): string {
+ const slug = slugify(title);
+ return JSON.stringify({
+ name: slug,
+ version: '1.0.0',
+ private: true,
+ main: 'main.cjs',
+ scripts: { start: 'electron .', dist: 'electron-builder' },
+ devDependencies: { electron: '^42.0.0', 'electron-builder': '^25.0.0' },
+ build: {
+ appId: `com.estella.${slug}`,
+ productName: title,
+ files: ['main.cjs', 'app/**/*'],
+ directories: { output: 'installer' },
+ mac: { target: 'dmg' },
+ win: { target: 'nsis' },
+ linux: { target: 'AppImage' },
+ },
+ }, null, 2) + '\n';
+}
+
+function desktopReadme(title: string): string {
+ return `# ${title}
+
+A desktop build exported from Estella. The game (\`app/\`) is the same play==ship
+runtime served over a \`game://\` scheme by the Electron shell (\`main.cjs\`).
+
+## Run it
+
+ npm install
+ npm start
+
+## Package a native installer (.dmg / .exe / AppImage)
+
+ npm install
+ npm run dist
+
+The installer is written to \`installer/\`. Build each OS's installer on that OS
+(electron-builder doesn't cross-compile reliably).
+`;
+}
+
+/** Stage the Electron shell around the web payload already built under `<absOut>/app`. */
+async function stageDesktopApp(absOut: string, title: string): Promise<void> {
+ await writeFile(path.join(absOut, 'main.cjs'), desktopMain(title));
+ await writeFile(path.join(absOut, 'package.json'), desktopPackageJson(title));
+ await writeFile(path.join(absOut, 'README.md'), desktopReadme(title));
+}
+
/**
- * Export the open project to a runnable web build in `outDir`. `entryScene` is
- * the project-relative scene to boot; `gameHostEntry` the gameHost.ts source;
- * `wasmDir` the engine runtime to copy.
+ * Export the open project. `entryScene` is the project-relative scene to boot;
+ * `gameHostEntry` the gameHost.ts source; `wasmDir` the engine runtime to copy.
+ * `platform` selects the target (default web).
*/
export async function exportGame(opts: {
root: string;
@@ -69,14 +200,19 @@ export async function exportGame(opts: {
wasmDir: string;
outDir: string;
title?: string;
+ platform?: ExportPlatform;
/** Shipping config: minify the bundles, no sourcemap. Default off (dev). */
minify?: boolean;
sourcemap?: boolean;
}): Promise<ExportGameResult> {
+ const platform = opts.platform ?? 'web';
+ const title = opts.title ?? 'Game';
const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(opts.root, opts.outDir);
+ // Desktop nests the web build under app/; the Electron shell sits beside it.
+ const payloadDir = platform === 'desktop' ? path.join(absOut, 'app') : absOut;
const warnings: string[] = [];
const errors: string[] = [];
- await mkdir(absOut, { recursive: true });
+ await mkdir(payloadDir, { recursive: true });
const common: BuildOptions = {
bundle: true,
format: 'esm',
@@ -90,39 +226,42 @@ export async function exportGame(opts: {
};
// 1. Cook reachable assets + manifest (the entry scene file is staged too).
- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut });
+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: payloadDir });
warnings.push(...cook.warnings);
try {
// 2. Game host — esengine EXTERNAL (resolved by the index.html import map),
// so the shipped game shares one SDK with the project bundle and runs
// custom systems (same shape as the play realm).
- const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(absOut, 'game.js') });
+ const host = await build({ ...common, entryPoints: [opts.gameHostEntry], outfile: path.join(payloadDir, 'game.js') });
errors.push(...host.errors.map((e) => e.text));
// 3. Project bundle (defineComponent/defineSystem) → scripts.mjs, esengine external.
const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
if (scriptsAbs && existsSync(scriptsAbs)) {
- const proj = await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(absOut, 'scripts.mjs') });
+ const proj = await build({ ...common, entryPoints: [scriptsAbs], outfile: path.join(payloadDir, 'scripts.mjs') });
errors.push(...proj.errors.map((e) => e.text));
}
} catch (err) {
const e = err as { errors?: { text: string }[]; message?: string };
errors.push(...(e.errors?.map((x) => x.text) ?? [String(e.message ?? err)]));
- return { ok: false, outDir: absOut, included: cook.included.length, warnings, errors };
+ return { ok: false, platform, outDir: absOut, included: cook.included.length, warnings, errors };
}
// 4. SDK (import-map target) + wasm runtime.
- if (existsSync(opts.sdkDistDir)) await cp(opts.sdkDistDir, path.join(absOut, 'sdk'), { recursive: true });
+ if (existsSync(opts.sdkDistDir)) await cp(opts.sdkDistDir, path.join(payloadDir, 'sdk'), { recursive: true });
else warnings.push(`sdk dist not found: ${opts.sdkDistDir}`);
- if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(absOut, 'wasm'), { recursive: true });
+ if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(payloadDir, 'wasm'), { recursive: true });
else warnings.push(`wasm runtime dir not found: ${opts.wasmDir}`);
// 5. Host page + entry-scene config.
- await writeFile(path.join(absOut, 'index.html'), indexHtml(opts.title ?? 'Game'));
+ await writeFile(path.join(payloadDir, 'index.html'), indexHtml(title));
await writeFile(
- path.join(absOut, 'game.config.json'),
+ path.join(payloadDir, 'game.config.json'),
JSON.stringify({ entryScene: opts.entryScene }, null, 2) + '\n',
);
- return { ok: errors.length === 0, outDir: absOut, included: cook.included.length, warnings, errors };
+ // 6. Desktop: wrap the payload in a runnable Electron app.
+ if (platform === 'desktop') await stageDesktopApp(absOut, title);
+
+ return { ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length, warnings, errors };
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index ef4722afd..f6a475baa 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -275,7 +275,7 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {
// Export a runnable web build (play == ship): cook + game host + wasm + index.html.
ipcMain.handle(
'project:exportGame',
- async (_e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean }) => {
+ async (_e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' }) => {
const root = requireRoot();
const manifest = await readManifest(root);
const entryScene = manifest.defaultScene;
@@ -290,6 +290,7 @@ ipcMain.handle(
wasmDir: existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm'),
outDir: opts?.outDir || 'dist-game',
title: manifest.name,
+ platform: opts?.platform,
minify: opts?.minify,
sourcemap: opts?.sourcemap,
});
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 07e453a5e..358e7a0db 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -41,7 +41,7 @@ const api = {
/** Cook reachable assets for shipping → staged files + runtime manifest in `outDir`. */
cookAssets: (outDir?: string): Promise<CookResult> => ipcRenderer.invoke('project:cookAssets', outDir),
/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */
- exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean }): Promise<ExportGameResult> =>
+ exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' }): Promise<ExportGameResult> =>
ipcRenderer.invoke('project:exportGame', opts),
/** Stage the isolated play realm (host + SDK + wasm + project bundle) under
* `.esengine/play/`; returns the project-relative host page path. */
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index a5b9c0a62..8b617da98 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -25,15 +25,18 @@ interface Result {
const PLATFORMS = [
{ id: 'web', label: 'Web', ready: true },
+ { id: 'desktop', label: 'Desktop', ready: true },
{ id: 'wechat', label: 'WeChat', ready: false },
{ id: 'playable', label: 'Playable', ready: false },
- { id: 'native', label: 'Native', ready: false },
] as const;
+type Platform = 'web' | 'desktop';
+
export function BuildDialog() {
const close = () => useEditorStore.getState().setBuildOpen(false);
const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);
+ const [platform, setPlatform] = useState<Platform>('web');
const [config, setConfig] = useState<Config>('shipping');
const [outDir, setOutDir] = useState('dist-game');
const [openFolder, setOpenFolder] = useState(true);
@@ -53,6 +56,7 @@ export function BuildDialog() {
setResult(null);
try {
const res = (await ProjectStore.exportGame({
+ platform,
outDir,
minify: config === 'shipping',
sourcemap: sourceMaps,
@@ -99,9 +103,11 @@ export function BuildDialog() {
<button
key={p.id}
type="button"
- className={`build__plat${p.ready ? ' on' : ''}`}
+ className={`build__plat${platform === p.id ? ' on' : ''}`}
disabled={!p.ready}
+ aria-pressed={platform === p.id}
title={p.ready ? p.label : 'Coming soon'}
+ onClick={() => p.ready && setPlatform(p.id as Platform)}
>
{p.label}
{!p.ready && <span className="soon">soon</span>}
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 901cd328f..ce3300d2d 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -695,7 +695,7 @@ class ProjectStoreImpl {
* (default `dist-game/`). Returns the bridge result so the Build dialog can
* render status/log; null if no project is open.
*/
- async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean }) {
+ async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' }) {
if (!this.state) return null;
return window.estella.project.exportGame(opts);
}
diff --git a/desktop/tests/export-desktop.test.ts b/desktop/tests/export-desktop.test.ts
new file mode 100644
index 000000000..3bf21b3a2
--- /dev/null
+++ b/desktop/tests/export-desktop.test.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Desktop (Electron) export. Asserts the web payload lands under app/ and a
+ * runnable Electron shell (main.cjs registering the game:// scheme +
+ * electron-builder-wired package.json) is staged beside it.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../electron/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', 'src', 'gameHost.ts');
+
+let root: string;
+let out: string;
+const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+beforeAll(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-desktop-'));
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
+ writeFileSync(path.join(root, 'assets', 'hero.png'), 'PNGDATA');
+ writeFileSync(path.join(root, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
+ mkdirSync(path.join(root, 'scenes'), { recursive: true });
+ writeFileSync(
+ path.join(root, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
+ );
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
+
+ out = path.join(root, 'dist-desktop');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('exportGame (desktop)', () => {
+ it('stages an Electron shell around the web payload', async () => {
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: out,
+ title: 'My Cool Game',
+ platform: 'desktop',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('desktop');
+
+ // Web payload nested under app/.
+ const app = path.join(out, 'app');
+ for (const f of ['index.html', 'game.js', 'scripts.mjs', 'game.config.json', 'assets.manifest.json']) {
+ expect(existsSync(path.join(app, f))).toBe(true);
+ }
+ expect(existsSync(path.join(app, 'wasm', 'esengine.js'))).toBe(true);
+ expect(existsSync(path.join(app, 'sdk', 'index.js'))).toBe(true);
+ expect(existsSync(path.join(app, 'assets', 'hero.png'))).toBe(true);
+
+ // Electron shell beside it.
+ const main = readFileSync(path.join(out, 'main.cjs'), 'utf8');
+ expect(main).toContain('registerSchemesAsPrivileged');
+ expect(main).toContain("SCHEME = 'game'");
+ expect(main).toContain('://app/index.html'); // window loads the payload over the scheme
+
+ const pkg = JSON.parse(readFileSync(path.join(out, 'package.json'), 'utf8'));
+ expect(pkg.main).toBe('main.cjs');
+ expect(pkg.scripts.start).toBe('electron .');
+ expect(pkg.scripts.dist).toBe('electron-builder');
+ expect(pkg.build.productName).toBe('My Cool Game');
+ expect(pkg.name).toBe('my-cool-game'); // slugified
+ expect(pkg.build.files).toContain('app/**/*');
+
+ expect(existsSync(path.join(out, 'README.md'))).toBe(true);
+ }, 60_000);
+
+ it('leaves the web target unnested (no app/ wrapper)', async () => {
+ const webOut = path.join(root, 'dist-web');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: webOut,
+ platform: 'web',
+ });
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('web');
+ expect(existsSync(path.join(webOut, 'index.html'))).toBe(true); // top-level, not under app/
+ expect(existsSync(path.join(webOut, 'app'))).toBe(false);
+ expect(existsSync(path.join(webOut, 'main.cjs'))).toBe(false);
+ }, 60_000);
+});