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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): preview web/playable exports over loopback http
yhh1c723d1fab27
diff --git a/desktop/electron/exportPreview.ts b/desktop/electron/exportPreview.tsnew file mode 100644index 000000000..307883824--- /dev/null+++ b/desktop/electron/exportPreview.ts@@ -0,0 +1,71 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file exportPreview.ts — preview an http-servable export (web / playable) over a+ * loopback http server, the way it actually deploys.+ *+ * A single-file playable or a web build opened via `file://` hits the browser's+ * opaque-origin rules — every `file:` URL is a unique origin, so subresource+ * loads are treated cross-origin (the "unsafe attempt to load URL … unique+ * security origin" notice) and wasm can't stream-compile. Served over `http`+ * (a real origin — exactly the ad-network iframe / static host the build ships+ * to) both concerns vanish. So the correct preview is http, not the OS opening+ * the file.+ *+ * One server per served root, reused across re-previews (files are read per+ * request with no-store, so a re-export serves fresh bytes on the same URL).+ * All are closed on app quit. Pure Node (http/fs) — IPC wiring is in main.ts.+ */+import http from 'node:http';+import { readFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { httpContentType } from './mimeTypes';++/** Served root (absolute) → its running loopback server + URL. */+const servers = new Map<string, { server: http.Server; url: string }>();++/**+ * Start (or reuse) a loopback http server rooted at `rootDir` and return its base URL.+ * Throws if the directory has no `index.html` (nothing to preview) — a clear failure+ * beats silently serving 404s.+ */+export async function previewServer(rootDir: string): Promise<string> {+ const root = path.resolve(rootDir);+ if (!existsSync(path.join(root, 'index.html'))) {+ throw new Error(`no index.html in ${root} — nothing to preview`);+ }+ const existing = servers.get(root);+ if (existing) return existing.url;++ const server = http.createServer(async (req, res) => {+ try {+ const rel = decodeURIComponent(new URL(req.url ?? '/', 'http://x').pathname).replace(/^\/+/, '') || 'index.html';+ const abs = path.join(root, rel);+ // Contain within the served root (no traversal out of the build).+ if (abs !== root && !abs.startsWith(root + path.sep)) {+ res.writeHead(403).end('forbidden');+ return;+ }+ const bytes = await readFile(abs);+ res.writeHead(200, { 'content-type': httpContentType(abs), 'cache-control': 'no-store' });+ res.end(bytes);+ } catch {+ res.writeHead(404).end('not found');+ }+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const addr = server.address();+ const port = typeof addr === 'object' && addr ? addr.port : 0;+ const url = `http://127.0.0.1:${port}/`;+ servers.set(root, { server, url });+ return url;+}++/** Close every preview server (on app quit). */+export function closeAllPreviewServers(): void {+ for (const { server } of servers.values()) {+ try { server.close(); } catch { /* already closing */ }+ }+ servers.clear();+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 89bf09bbe..c3c053cc6 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -28,6 +28,8 @@ import { cookAssets } from './cookAssets';import { startProjectWatch, stopProjectWatch } from './projectWatcher';import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';import { exportGame } from './exportGame';+import { previewServer, closeAllPreviewServers } from './exportPreview';+import { httpContentType } from './mimeTypes';import { buildPlayRealm } from './buildPlayRealm';import { syncSdkTypes } from './syncSdkTypes';import { installCrashCapture, logsDir } from './resilience';@@ -67,44 +69,6 @@ protocol.registerSchemesAsPrivileged([// The app:// renderer origin (host is arbitrary; `local` keeps URLs readable).const APP_ORIGIN = 'app://local';-const ASSET_MIME: Record<string, string> = {- png: 'image/png',- jpg: 'image/jpeg',- jpeg: 'image/jpeg',- webp: 'image/webp',- ktx2: 'image/ktx2',- json: 'application/json',- esscene: 'application/json',- fnt: 'text/plain',- // The play realm is served from estella:// too (host page + SDK + bundle + wasm),- // so estella must hand back script/document/wasm types, not just asset types.- html: 'text/html',- js: 'text/javascript',- mjs: 'text/javascript',- wasm: 'application/wasm',- css: 'text/css',-};--// MIME for serving the built renderer over app:// (wasm MUST be application/wasm-// for streaming compile; js/mjs must be a script type).-const APP_MIME: Record<string, string> = {- html: 'text/html',- js: 'text/javascript',- mjs: 'text/javascript',- css: 'text/css',- json: 'application/json',- wasm: 'application/wasm',- png: 'image/png',- jpg: 'image/jpeg',- jpeg: 'image/jpeg',- webp: 'image/webp',- svg: 'image/svg+xml',- woff: 'font/woff',- woff2: 'font/woff2',- ttf: 'font/ttf',- ktx2: 'image/ktx2',-};-// The engine's Emscripten/embind glue requires 'unsafe-eval' in the renderer// CSP (it JIT-compiles call bridges via new Function). That's a deliberate,// accepted trade-off for this local dev tool, so silence the dev-only warning.@@ -572,6 +536,16 @@ ipcMain.handle(},);+// Preview an http-servable export (web / playable) over a loopback http server, then+// open it in the default browser. That is the build's real deployment surface — an+// http origin (static host / ad-network iframe) — so the file:// opaque-origin rules+// (blocked subresource loads, no wasm streaming) never apply. Returns the URL.+ipcMain.handle('export:preview', async (_e, absDir: string) => {+ const url = await previewServer(absDir);+ await shell.openExternal(url);+ return url;+});+// Stage the isolated play realm under the project's .esengine/play/ (host + SDK +// wasm + import map) and build the project's script bundle, so the editor can run// it from estella://project/.esengine/play/play.html with custom components/systems.@@ -637,10 +611,9 @@ async function handleEstella(request: Request): Promise<Response> {const rel = decodeURIComponent(new URL(request.url).pathname).replace(/^\/+/, '');const abs = resolveInRoot(projectRoot, rel); // throws if it escapes the rootconst bytes = await readFile(abs);- const ext = path.extname(abs).slice(1).toLowerCase();return new Response(new Uint8Array(bytes), {headers: {- 'content-type': ASSET_MIME[ext] ?? 'application/octet-stream',+ 'content-type': httpContentType(abs),// The play realm (app:// origin) loads project assets cross-scheme via// <img crossorigin> + fetch; allow it. estella:// is only reachable inside// the Electron app, so there is no untrusted-web exposure.@@ -669,9 +642,8 @@ async function handleApp(request: Request): Promise<Response> {if (!projectRoot) return new Response('no project open', { status: 503 });const abs = resolveInRoot(projectRoot, rel.slice(PROJECT_PREFIX.length));const bytes = await readFile(abs);- const ext = path.extname(abs).slice(1).toLowerCase();return new Response(new Uint8Array(bytes), {- headers: { 'content-type': ASSET_MIME[ext] ?? 'application/octet-stream', 'access-control-allow-origin': '*', 'cache-control': 'no-store' },+ headers: { 'content-type': httpContentType(abs), 'access-control-allow-origin': '*', 'cache-control': 'no-store' },});}const abs = path.join(RENDERER_DIST, rel);@@ -679,9 +651,8 @@ async function handleApp(request: Request): Promise<Response> {return new Response('forbidden', { status: 403 });}const bytes = await readFile(abs);- const ext = path.extname(abs).slice(1).toLowerCase();return new Response(new Uint8Array(bytes), {- headers: { 'content-type': APP_MIME[ext] ?? 'application/octet-stream', 'access-control-allow-origin': '*' },+ headers: { 'content-type': httpContentType(abs), 'access-control-allow-origin': '*' },});} catch (err) {return new Response(String(err), { status: 404 });@@ -717,3 +688,6 @@ app.on('window-all-closed', () => {stopProjectWatch();if (process.platform !== 'darwin') app.quit();});++// Tear down any loopback export-preview servers on quit.+app.on('before-quit', () => closeAllPreviewServers());diff --git a/desktop/electron/mimeTypes.ts b/desktop/electron/mimeTypes.tsnew file mode 100644index 000000000..76e8e4c5e--- /dev/null+++ b/desktop/electron/mimeTypes.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file mimeTypes.ts — one content-type table for every place the editor SERVES+ * bytes over an http-like response: the `estella://` project scheme, the+ * `app://` renderer scheme, and the loopback preview server ({@link+ * ./exportPreview}). It is a superset of documents/scripts/wasm/images/+ * audio/fonts so a build's index.html, its wasm glue, and its assets all+ * get the right type from a single source (they used to drift across three+ * hand-kept maps). Not the same concern as exportPlayable's data-URL MIME+ * (which inlines assets) — that stays local to that path.+ */+import path from 'node:path';++const HTTP_MIME: Record<string, string> = {+ html: 'text/html', htm: 'text/html',+ js: 'text/javascript', mjs: 'text/javascript', cjs: 'text/javascript',+ css: 'text/css', json: 'application/json', map: 'application/json',+ wasm: 'application/wasm', txt: 'text/plain', fnt: 'text/plain',+ esscene: 'application/json',+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',+ webp: 'image/webp', svg: 'image/svg+xml', ktx2: 'image/ktx2', ico: 'image/x-icon',+ ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', aac: 'audio/aac',+ ttf: 'font/ttf', woff: 'font/woff', woff2: 'font/woff2',+};++/** Content-type for a file path (or bare extension); octet-stream when unknown. */+export function httpContentType(pathOrExt: string): string {+ const ext = (path.extname(pathOrExt).slice(1) || pathOrExt).toLowerCase();+ return HTTP_MIME[ext] ?? 'application/octet-stream';+}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex dbeaf520e..3dbe9d19c 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -89,6 +89,10 @@ const api = {/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' | 'playable'; compressTextures?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>ipcRenderer.invoke('project:exportGame', opts),+ /** Serve a built export dir (web / playable) over loopback http and open it in the+ * default browser — the build's real deployment surface, so no file:// origin+ * restrictions apply. Returns the previewed URL. */+ previewExport: (absDir: string): Promise<string> => ipcRenderer.invoke('export:preview', absDir),/** Subscribe to export build-log phases while a package runs. Returns unsubscribe. */onExportProgress: (cb: (p: { phase: string; detail?: string }) => void): (() => void) => {const listener = (_e: unknown, p: { phase: string; detail?: string }) => cb(p);diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 5746da4de..78309fa8d 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -11,7 +11,7 @@* / Playable) are live.*/import { useState, useSyncExternalStore } from 'react';-import { Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy } from 'lucide-react';+import { Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy, ExternalLink } from 'lucide-react';import { Modal } from '@/components/Modal';import { ProjectStore } from '@/project/ProjectStore';import { useEditorStore } from '@/store/editorStore';@@ -42,6 +42,9 @@ interface PlatformDef {sourceMaps: boolean;/** A build prerequisite to surface BEFORE packaging (missing toolchain/runtime). */prereq?: string;+ /** http-servable target → offer a loopback-http Preview (opening the build via+ * file:// hits the browser's opaque-origin rules; http is its real surface). */+ httpPreview?: boolean;/** Post-build guidance (where the package is / how to run it). */next: (outDir: string) => string;}@@ -50,8 +53,8 @@ const PLATFORMS: PlatformDef[] = [{id: 'web', label: 'Web', ready: true,blurb: 'Static, self-contained web build — host it anywhere.',- defaultOut: 'dist-web', sourceMaps: true,- next: (o) => `Open ${o}/index.html, or upload ${o}/ to any static host.`,+ defaultOut: 'dist-web', sourceMaps: true, httpPreview: true,+ next: (o) => `Preview over http below, or upload ${o}/ to any static host. (A web build needs an http origin — opening index.html directly won't stream the wasm.)`,},{id: 'desktop', label: 'Desktop', ready: true,@@ -69,9 +72,9 @@ const PLATFORMS: PlatformDef[] = [{id: 'playable', label: 'Playable', ready: true,blurb: 'Single-file HTML playable ad — everything inlined, no requests.',- defaultOut: 'dist-playable', sourceMaps: false,+ defaultOut: 'dist-playable', sourceMaps: false, httpPreview: true,prereq: 'Requires the single-file runtime — run: node build-tools/cli.js build -t playable',- next: (o) => `Open ${o}/index.html. Note: a full engine usually exceeds ad-network size limits.`,+ next: () => `Preview over http below (its real surface is an ad-network iframe). Note: a full engine usually exceeds ad-network size limits.`,},];@@ -156,6 +159,17 @@ export function BuildDialog() {void navigator.clipboard?.writeText(lines.join('\n'));};+ // Serve the finished build over loopback http and open it in the default browser —+ // its real deployment surface, so none of the file:// opaque-origin limits apply.+ const preview = async () => {+ if (!result?.ok) return;+ try {+ await window.estella.project?.previewExport?.(result.outDir);+ } catch (err) {+ setLog((l) => [...l, `preview failed: ${err instanceof Error ? err.message : String(err)}`]);+ }+ };+const footer = (<><button type="button" className="btn-soft" onClick={close} disabled={running}>@@ -278,6 +292,18 @@ export function BuildDialog() {<CheckCircle2 size={14} /> Packaged {result.included} assets{result.bytes ? ` · ${mb(result.bytes)}` : ''} → {result.outDir}</span><div className="build__next selectable">{def.next(result.outDir)}</div>+ {result.ok && (+ <div className="build__actions">+ {def.httpPreview && (+ <button type="button" className="btn-soft is-primary" onClick={() => void preview()}>+ <ExternalLink size={13} /> Preview over http+ </button>+ )}+ <button type="button" className="btn-soft" onClick={() => void window.estella.shell?.openPath?.(result.outDir)}>+ <FolderOpen size={13} /> Open folder+ </button>+ </div>+ )}</>)}{phase === 'error' && result && (diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.cssindex ad2cf87e0..7b3efe315 100644--- a/desktop/src/theme/menus.css+++ b/desktop/src/theme/menus.css@@ -174,6 +174,7 @@.build__prereq { display: flex; align-items: flex-start; gap: 7px; padding: 8px 10px; border-radius: var(--r-sm); font-size: var(--fs-xs); color: var(--text-dim); background: var(--srf-3); border: 1px solid var(--border-line); }.build__prereq svg { flex-shrink: 0; margin-top: 1px; color: var(--text-mute); }.build__next { font-size: var(--fs-xs); color: var(--text-mute); font-family: var(--mono); }+.build__actions { display: flex; gap: 8px; margin-top: 2px; }.build__log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 116px; overflow-y: auto; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }.build__log li::before { content: '\203A '; color: var(--text-dim); }.build__log li:last-child { color: var(--text-dim); }diff --git a/desktop/tests/export-preview.test.ts b/desktop/tests/export-preview.test.tsnew file mode 100644index 000000000..e4be3ea0e--- /dev/null+++ b/desktop/tests/export-preview.test.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The loopback export-preview server: serves a build dir over http (its real+ * deployment surface) so web/playable previews never hit file:// opaque-origin+ * rules. Asserts it serves index.html + assets with correct content-types,+ * contains within the root (no traversal), and fails fast without an index.html.+ */+import { describe, it, expect, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { previewServer, closeAllPreviewServers } from '../electron/exportPreview';++afterAll(() => closeAllPreviewServers());++function buildDir(): string {+ const dir = mkdtempSync(path.join(tmpdir(), 'estella-preview-'));+ writeFileSync(path.join(dir, 'index.html'), '<!doctype html><title>P</title><canvas id="canvas"></canvas>');+ writeFileSync(path.join(dir, 'esengine.wasm'), 'WASMBYTES');+ return dir;+}++describe('exportPreview loopback server', () => {+ it('serves index.html and the wasm with correct content-types over http', async () => {+ const dir = buildDir();+ try {+ const url = await previewServer(dir);+ expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/$/);++ const index = await fetch(url);+ expect(index.status).toBe(200);+ expect(index.headers.get('content-type')).toBe('text/html');+ expect(await index.text()).toContain('<canvas id="canvas">');++ // wasm MUST be application/wasm (streaming compile) — the whole reason http beats file://.+ const wasm = await fetch(`${url}esengine.wasm`);+ expect(wasm.status).toBe(200);+ expect(wasm.headers.get('content-type')).toBe('application/wasm');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('reuses one server per root (same URL on re-preview)', async () => {+ const dir = buildDir();+ try {+ expect(await previewServer(dir)).toBe(await previewServer(dir));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('contains within the served root (no path traversal)', async () => {+ const dir = buildDir();+ try {+ const url = await previewServer(dir);+ const res = await fetch(`${url}../../etc/hosts`);+ expect([403, 404]).toContain(res.status);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it('fails fast when the dir has no index.html', async () => {+ const empty = mkdtempSync(path.join(tmpdir(), 'estella-preview-empty-'));+ mkdirSync(path.join(empty, 'sub'), { recursive: true });+ try {+ await expect(previewServer(empty)).rejects.toThrow(/index\.html/);+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });+});diff --git a/examples/particle-demo/project.esproject b/examples/particle-demo/project.esprojectindex 95b6592c5..aadaff836 100644--- a/examples/particle-demo/project.esproject+++ b/examples/particle-demo/project.esproject@@ -9,5 +9,16 @@"width": 1280,"height": 720},- "spineVersion": "none"+ "spineVersion": "none",+ "packaging": {+ "platform": "playable",+ "config": "shipping",+ "sourceMaps": true,+ "openFolder": true,+ "outDir": {+ "playable": "dist-playable"+ },+ "compressTextures": true,+ "atlasTextures": true+ }}diff --git a/examples/spine-demo/project.esproject b/examples/spine-demo/project.esprojectindex efc0be655..d266a8e3d 100644--- a/examples/spine-demo/project.esproject+++ b/examples/spine-demo/project.esproject@@ -9,5 +9,16 @@"width": 800,"height": 600},- "spineVersion": "4.2"+ "spineVersion": "4.2",+ "packaging": {+ "platform": "playable",+ "config": "shipping",+ "sourceMaps": false,+ "openFolder": true,+ "outDir": {+ "playable": "dist-playable"+ },+ "compressTextures": true,+ "atlasTextures": true+ }}