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): project-script bundler with esengine external (editor-realm P1 / E8-1)
esengine6145301bdb79
diff --git a/desktop/electron/buildScripts.ts b/desktop/electron/buildScripts.tsnew file mode 100644index 000000000..0e6a8d365--- /dev/null+++ b/desktop/electron/buildScripts.ts@@ -0,0 +1,74 @@+/**+ * @file Project-script bundler (REARCH_EDITOR_REALM.md Phase P1 / RC12 §E8-1).+ *+ * Bundles a project's `src/main.ts` into a single ESM with `esengine` left+ * EXTERNAL, written to `.esengine/cache/`. The bundle's bare `import ... from+ * "esengine"` is resolved by an import map in the isolated play realm to that+ * realm's own SDK instance — so the engine is never duplicated into each project+ * bundle, and the realm runs the project's real (shipped) code (play==ship).+ *+ * Pure Node (esbuild + fs/path), no Electron imports, so it is unit-testable and+ * reusable; the IPC wiring lives in main.ts.+ */+import { build, type BuildResult } from 'esbuild';+import { existsSync } from 'node:fs';+import path from 'node:path';++/** esengine and any subpath import are left for the realm's import map to resolve. */+const EXTERNAL = ['esengine', 'esengine/*'];+const DEFAULT_SRC_DIR = 'src';+const DEFAULT_ENTRY = 'main.ts';+/** Local, gitignored build cache inside the project (next to workspace.json). */+const CACHE_DIR = '.esengine/cache';+const OUTPUT = 'scripts.mjs';++export interface BuildScriptsResult {+ ok: boolean;+ /** Absolute path to the bundled ESM, or null if the build failed. */+ outputPath: string | null;+ errors: string[];+ warnings: string[];+}++/**+ * Bundle `<root>/<srcDir>/<entry>` → `<root>/.esengine/cache/scripts.mjs`,+ * esengine external. Never throws — failures come back as `{ ok:false, errors }`.+ */+export async function buildProjectScripts(+ root: string,+ opts?: { srcDir?: string; entry?: string },+): Promise<BuildScriptsResult> {+ const entryPath = path.join(root, opts?.srcDir ?? DEFAULT_SRC_DIR, opts?.entry ?? DEFAULT_ENTRY);+ if (!existsSync(entryPath)) {+ return { ok: false, outputPath: null, errors: [`script entry not found: ${entryPath}`], warnings: [] };+ }+ const outputPath = path.join(root, CACHE_DIR, OUTPUT);+ try {+ const result: BuildResult = await build({+ entryPoints: [entryPath],+ bundle: true,+ format: 'esm',+ platform: 'browser',+ target: 'es2020',+ external: EXTERNAL,+ outfile: outputPath,+ sourcemap: true,+ write: true,+ logLevel: 'silent',+ });+ return {+ ok: true,+ outputPath,+ errors: result.errors.map((e) => e.text),+ warnings: result.warnings.map((w) => w.text),+ };+ } catch (err) {+ const e = err as { errors?: { text: string }[]; warnings?: { text: string }[]; message?: string };+ return {+ ok: false,+ outputPath: null,+ errors: e.errors?.map((x) => x.text) ?? [String(e.message ?? err)],+ warnings: e.warnings?.map((x) => x.text) ?? [],+ };+ }+}diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex f7351d4fe..e9bbfa9e1 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -11,6 +11,7 @@ import {resolveInRoot,} from './projectFs';import { listRecents, addRecent, listTemplates, createFromTemplate } from './launcher';+import { buildProjectScripts } from './buildScripts';import type { WorkspaceState } from '../src/project/format';// Custom scheme that serves files from the open project root (sandboxed). Lets@@ -131,6 +132,10 @@ ipcMain.handle('fs:write', (_e, relPath: string, contents: string) =>ipcMain.handle('fs:readdir', (_e, relPath: string) => readDirInRoot(requireRoot(), relPath));ipcMain.handle('workspace:save', (_e, ws: WorkspaceState) => saveWorkspace(requireRoot(), ws));+// Bundle the open project's scripts (src/main.ts → .esengine/cache, esengine+// external) for the isolated play realm (REARCH_EDITOR_REALM P1 / RC12 §E8-1).+ipcMain.handle('project:buildScripts', () => buildProjectScripts(requireRoot()));+ipcMain.handle('recents:list', () => listRecents());ipcMain.handle('recents:add', (_e, root: string, name: string) => addRecent(root, name));diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 69d99264c..7ba094ba7 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -1,5 +1,6 @@import { contextBridge, ipcRenderer } from 'electron';import type { OpenedProject, WorkspaceState, DirEntry, RecentEntry, TemplateEntry } from '../src/project/format';+import type { BuildScriptsResult } from './buildScripts';// The privileged bridge the renderer is allowed to touch. Keep this surface small// and explicit — anything the editor needs from the OS or Node goes through here.@@ -24,6 +25,8 @@ const api = {ipcRenderer.invoke('project:createFromTemplate', templateDir, location, name),/** Pick a folder (for the new-project location); returns an absolute path or null. */chooseDirectory: (): Promise<string | null> => ipcRenderer.invoke('project:chooseDirectory'),+ /** Bundle the open project's scripts (src/main.ts) for the isolated play realm. */+ buildScripts: (): Promise<BuildScriptsResult> => ipcRenderer.invoke('project:buildScripts'),},// New-project templates (launcher New tab).templates: {diff --git a/desktop/package.json b/desktop/package.jsonindex be66d831b..2ac10a35a 100644--- a/desktop/package.json+++ b/desktop/package.json@@ -15,6 +15,7 @@},"dependencies": {"esengine": "workspace:*",+ "esbuild": "^0.27.0","dockview": "^6.6.1","lucide-react": "^1.21.0","react": "^19.2.0",diff --git a/desktop/tests/build-scripts.test.ts b/desktop/tests/build-scripts.test.tsnew file mode 100644index 000000000..bffe1d482--- /dev/null+++ b/desktop/tests/build-scripts.test.ts@@ -0,0 +1,67 @@+/**+ * @file Project-script bundler (REARCH_EDITOR_REALM Phase P1 / RC12 §E8-1).+ * Asserts esengine is left EXTERNAL (resolved by the play realm's import+ * map, not duplicated into every bundle) while the project's own modules+ * are bundled in.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { buildProjectScripts } from '../electron/buildScripts';++let root: string;++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-proj-'));+ mkdirSync(path.join(root, 'src'), { recursive: true });+ // A project's own module — must be bundled IN.+ writeFileSync(+ path.join(root, 'src', 'components.ts'),+ `import { defineComponent } from 'esengine';\n` ++ `export const Wave = defineComponent('Wave', { amplitude: 1 });\n`,+ );+ // Entry — imports esengine (external) + a local module (bundled).+ writeFileSync(+ path.join(root, 'src', 'main.ts'),+ `import { addSystemToSchedule, Schedule } from 'esengine';\n` ++ `import { Wave } from './components';\n` ++ `addSystemToSchedule(Schedule.Update, () => { void Wave; });\n`,+ );+});++afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true });+});++describe('buildProjectScripts (E8-1)', () => {+ it('bundles src/main.ts with esengine external and local modules inlined', async () => {+ const res = await buildProjectScripts(root);+ expect(res.ok).toBe(true);+ expect(res.errors).toEqual([]);+ expect(res.outputPath).toBe(path.join(root, '.esengine/cache/scripts.mjs'));+ expect(existsSync(res.outputPath!)).toBe(true);++ const out = readFileSync(res.outputPath!, 'utf8');+ // esengine is kept external — the bare import survives in the bundle:+ expect(out).toMatch(/from\s*["']esengine["']/);+ // …and esengine is NOT inlined (the build would have errored trying to+ // resolve it from this fixture's node_modules if it weren't external).+ // The project's own module IS bundled (its local import is gone, its code present):+ expect(out).not.toMatch(/from\s*["']\.\/components["']/);+ expect(out).toContain('Wave');+ expect(out).toContain('amplitude');+ });++ it('reports a clean failure when the entry is missing', async () => {+ const empty = mkdtempSync(path.join(tmpdir(), 'estella-empty-'));+ try {+ const res = await buildProjectScripts(empty);+ expect(res.ok).toBe(false);+ expect(res.outputPath).toBeNull();+ expect(res.errors.join(' ')).toMatch(/entry not found/);+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });+});