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
fix(editor): SDK types staging is a stamped, loud, fallback-aware contract (#49)
yhha1dc4eaa2411
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex bb7831ece..8ce04df5f 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -31,7 +31,7 @@ import { exportGame } from './exportGame';import { previewServer, closeAllPreviewServers } from './exportPreview';import { httpContentType } from './mimeTypes';import { buildPlayRealm } from './buildPlayRealm';-import { syncSdkTypes } from './syncSdkTypes';+import { ensureSdkTypes } from './syncSdkTypes';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint } from './mcpEndpoint';import { checkForUpdate } from './updateCheck';@@ -110,6 +110,13 @@ const unpacked = (p: string): string => p.replace(/app\.asar(?=[\\/])/, 'app.asaconst HOSTS_DIR = unpacked(path.join(__dirname, 'hosts'));/** The esengine SDK dist: staged into realms/exports, aliased into inlined bundles. */const SDK_DIST = unpacked(path.join(process.env.APP_ROOT, 'node_modules', 'esengine', 'dist'));+/** Where the types mirror may READ the SDK dist from, in preference order. The+ * mirror is plain Node fs, which reads app.asar fine — so the in-archive path+ * is a valid fallback when the unpacked copy is missing (v0.22.0 shipped+ * without asarUnpack for the sdk; the mirror silently skipped and projects+ * lost their `esengine` types — issue #49). Native consumers (esbuild) must+ * keep using SDK_DIST only. */+const SDK_TYPES_CANDIDATES = [SDK_DIST, path.join(process.env.APP_ROOT, 'node_modules', 'esengine', 'dist')];/** The web engine runtime (glue + wasm + side modules) staged into play realms and* exports by recursive directory copy — which cannot source from inside app.asar. */const WEB_WASM_DIR = unpacked(@@ -430,15 +437,20 @@ const requireRoot = (): string => {};// Adopt a freshly opened project as the active root + (re)start the fs watcher-// so on-disk changes push to the renderer, and mirror the SDK types into+// so on-disk changes push to the renderer, and stage the SDK types into// .esengine/sdk so the project's tsconfig resolves `esengine` in the IDE.-async function adoptRoot(root: string): Promise<void> {+// Staging failure does NOT block the open — but it is returned so the renderer+// can say it loudly (Output Log + toast), never swallowed into a console.warn.+async function adoptRoot(root: string): Promise<string | undefined> {projectRoot = root;if (win) startProjectWatch(root, win.webContents);try {- await syncSdkTypes(root, SDK_DIST);+ await ensureSdkTypes(root, SDK_TYPES_CANDIDATES, app.getVersion());+ return undefined;} catch (err) {- console.warn('[sdk-types] mirror failed:', err);+ const msg = err instanceof Error ? err.message : String(err);+ console.error('[sdk-types]', msg);+ return msg;}}@@ -450,14 +462,12 @@ ipcMain.handle('project:openDialog', async () => {});if (res.canceled || res.filePaths.length === 0) return null;const opened = await openProject(res.filePaths[0]);- await adoptRoot(opened.root);- return opened;+ return { ...opened, stagingError: await adoptRoot(opened.root) };});ipcMain.handle('project:open', async (_e, root: string) => {const opened = await openProject(root);- await adoptRoot(opened.root);- return opened;+ return { ...opened, stagingError: await adoptRoot(opened.root) };});// Import: OS file picker → copy the chosen files into `destDir` + write `.meta`.diff --git a/desktop/electron/syncSdkTypes.ts b/desktop/electron/syncSdkTypes.tsindex 3a6449a32..00e7c9441 100644--- a/desktop/electron/syncSdkTypes.ts+++ b/desktop/electron/syncSdkTypes.ts@@ -1,22 +1,59 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file Mirror the SDK's type declarations into a project's `.esengine/sdk` so+ * @file Stage the SDK's type declarations into a project's `.esengine/sdk` so* its tsconfig (`esengine` → ./.esengine/sdk/index.d.ts) resolves in the* IDE the moment the project is opened — before it is ever played. Types* only; the play runtime (js + wasm) is staged separately under* `.esengine/play` by buildPlayRealm.+ *+ * Same contract as the play staging: STAMPED (re-mirror only when the+ * editor/SDK changed, not on every open) and LOUD (no reachable SDK dist+ * is an error the caller must surface — a silently skipped mirror is how+ * "cannot find module 'esengine'" shipped in v0.22.0 with zero trace).*/-import { cp, mkdir, readdir } from 'node:fs/promises';+import { cp, mkdir, readdir, readFile, writeFile, stat } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';-/** Copy every `*.d.ts` under `sdkDistDir` into `<root>/.esengine/sdk`, preserving- * the directory layout so index.d.ts's chunk imports (shared/, physics/, spine/)- * resolve. Overwrites, so a newer SDK refreshes the mirror on the next open. */-export async function syncSdkTypes(root: string, sdkDistDir: string): Promise<void> {- if (!existsSync(sdkDistDir)) return;- await copyDeclarations(sdkDistDir, path.join(root, '.esengine', 'sdk'));+const STAMP_FILE = '.stamp';++/**+ * Ensure `<root>/.esengine/sdk` mirrors the SDK's `*.d.ts` tree (layout+ * preserved so index.d.ts's chunk imports — shared/, physics/, spine/ —+ * resolve). `candidates` are SDK dist locations in preference order: the+ * packaged app lists the asar-unpacked path first and the in-asar path as the+ * fallback (Node's patched fs reads the archive fine — only NATIVE consumers+ * like esbuild need the unpacked copy). Throws when none exists.+ *+ * Returns whether the mirror was (re)written — a matching stamp skips the walk.+ */+export async function ensureSdkTypes(+ root: string,+ candidates: readonly string[],+ appVersion: string,+): Promise<{ staged: boolean }> {+ const src = candidates.find((c) => existsSync(path.join(c, 'index.d.ts')));+ if (!src) {+ throw new Error(+ `SDK dist not found (looked in: ${candidates.join(' | ')}) — ` ++ `the project's .esengine/sdk types mirror cannot be staged, so the IDE ` ++ `cannot resolve the 'esengine' module.`,+ );+ }++ // Stamp = editor version + the dist's own freshness (its index.d.ts mtime):+ // releases restage on update, dev restages after every SDK rebuild.+ const stamp = `${appVersion}:${(await stat(path.join(src, 'index.d.ts'))).mtimeMs}`;+ const dst = path.join(root, '.esengine', 'sdk');+ const stampPath = path.join(dst, STAMP_FILE);+ const current = await readFile(stampPath, 'utf8').catch(() => null);+ if (current === stamp && existsSync(path.join(dst, 'index.d.ts'))) return { staged: false };++ await copyDeclarations(src, dst);+ await mkdir(dst, { recursive: true }); // a dist with zero .d.ts never creates dst+ await writeFile(stampPath, stamp, 'utf8');+ return { staged: true };}async function copyDeclarations(src: string, dst: string): Promise<void> {diff --git a/desktop/scripts/editor-mcp-editor-e2e.mjs b/desktop/scripts/editor-mcp-editor-e2e.mjsindex 6fb9f2274..f58b2f4ea 100644--- a/desktop/scripts/editor-mcp-editor-e2e.mjs+++ b/desktop/scripts/editor-mcp-editor-e2e.mjs@@ -101,6 +101,13 @@ try {await call('open_project', { root: project }, 120_000);console.log('open_project OK');+ // Opening a project stages the SDK types mirror — the project tsconfig's+ // `esengine` path must resolve for the IDE from the very first open (a+ // silently skipped mirror shipped "cannot find module 'esengine'" in 0.22).+ const sdkTypes = await stat(path.join(project, '.esengine', 'sdk', 'index.d.ts')).catch(() => null);+ if (!sdkTypes) await fail('.esengine/sdk/index.d.ts missing after open_project — SDK types staging broken');+ console.log('sdk types staged OK — .esengine/sdk/index.d.ts present');+// No polling: open_scene's contract is "resolved = adopted", so the very next// tree read must already be populated (this line is the contract's regression// guard — do not add a retry loop here).diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex b53436123..9a81b4356 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -99,6 +99,7 @@ export const projectMessages = defineMessages({// — Project-level feedback toasts (ProjectStore) —'proj.openFailed': { en: 'Could not open project: {message}', zh: '无法打开项目:{message}' },+ 'proj.sdkTypesFailed': { en: 'SDK types staging failed — the IDE cannot resolve "esengine": {message}', zh: 'SDK 类型入驻失败——IDE 将无法解析 "esengine":{message}' },'proj.prefabLoadFailed': { en: 'Could not load prefab: {name}', zh: '无法加载预制体:{name}' },'proj.noOverrides': { en: 'No overrides to apply', zh: '没有可应用的覆盖' },'proj.applyWriteFailed': { en: 'Apply failed: could not write {name}', zh: '应用失败:无法写入 {name}' },diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex dcb653a8d..f8aeb2df0 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -254,6 +254,13 @@ class ProjectStoreImpl {* running (re-opening from the editor), load immediately.*/private async adopted(opened: OpenedProject): Promise<void> {+ // Staging problems (the .esengine/sdk types mirror) don't block the open,+ // but they must be LOUD — a silent skip is how projects lost their+ // `esengine` IDE types in v0.22.0 with nothing in any log (issue #49).+ if (opened.stagingError) {+ console.error('[project] SDK types staging failed:', opened.stagingError);+ Toasts.push(t('proj.sdkTypesFailed', { message: opened.stagingError }), 'error');+ }this.adopt(opened);await window.estella.recents.add(opened.root, opened.manifest.name);await this.refreshUserSchemas();diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 4340412ab..e9ac5ce1e 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -189,6 +189,11 @@ export interface OpenedProject {root: string;manifest: ProjectManifest;workspace: WorkspaceState;+ /** Staging that failed while adopting the project (e.g. the `.esengine/sdk`+ * types mirror couldn't find the SDK dist). The project still opens — but+ * the renderer must say so LOUDLY: a silently skipped mirror is exactly how+ * "cannot find module 'esengine'" shipped without a trace (issue #49). */+ stagingError?: string;}/** A directory entry from a sandboxed readdir. */diff --git a/desktop/templates/blank/src/main.ts b/desktop/templates/blank/src/main.tsindex 1b5e32a78..411b121ad 100644--- a/desktop/templates/blank/src/main.ts+++ b/desktop/templates/blank/src/main.ts@@ -1,3 +1,8 @@// Game entry — runs when the scene plays. Register systems here, e.g.// addSystemToSchedule(Schedule.Update, mySystem).+//+// IDE says "cannot find module 'esengine'"? Open this project in the Estella+// editor once — it stages the SDK types under .esengine/sdk (which tsconfig's+// `paths` points at). The folder is editor-managed and gitignored, so a fresh+// clone needs one editor open to regenerate it.import './components';diff --git a/desktop/tests/sync-sdk-types.test.ts b/desktop/tests/sync-sdk-types.test.tsnew file mode 100644index 000000000..7a6c7d83d--- /dev/null+++ b/desktop/tests/sync-sdk-types.test.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The `.esengine/sdk` types staging contract: stamped (re-mirror only+ * when the editor/SDK changed), candidate-fallback (the in-asar dist is+ * readable by Node when the unpacked copy is missing), and LOUD when no+ * source exists — the v0.22.0 silent skip shipped projects whose IDE+ * could not resolve `esengine` with zero trace (issue #49).+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync, statSync, utimesSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { ensureSdkTypes } from '../electron/syncSdkTypes';++let root: string;+let dist: string;++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-proj-'));+ dist = mkdtempSync(path.join(tmpdir(), 'estella-dist-'));+ writeFileSync(path.join(dist, 'index.d.ts'), 'export declare const x: 1;');+ mkdirSync(path.join(dist, 'physics'));+ writeFileSync(path.join(dist, 'physics', 'index.d.ts'), 'export {};');+ writeFileSync(path.join(dist, 'index.js'), 'js body, never mirrored');+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ rmSync(dist, { recursive: true, force: true });+});++const mirrored = (rel: string): string => path.join(root, '.esengine', 'sdk', rel);++describe('ensureSdkTypes', () => {+ it('mirrors the d.ts tree (layout preserved, js excluded) and stamps it', async () => {+ const res = await ensureSdkTypes(root, [dist], '1.0.0');+ expect(res.staged).toBe(true);+ expect(readFileSync(mirrored('index.d.ts'), 'utf8')).toContain('x: 1');+ expect(existsSync(mirrored('physics/index.d.ts'))).toBe(true);+ expect(existsSync(mirrored('index.js'))).toBe(false);+ expect(existsSync(mirrored('.stamp'))).toBe(true);+ });++ it('a matching stamp skips the re-mirror; a changed SDK restages', async () => {+ await ensureSdkTypes(root, [dist], '1.0.0');+ const mtime = statSync(mirrored('index.d.ts')).mtimeMs;+ expect((await ensureSdkTypes(root, [dist], '1.0.0')).staged).toBe(false);+ expect(statSync(mirrored('index.d.ts')).mtimeMs).toBe(mtime);+ // SDK rebuild (source index.d.ts mtime moves) → stamp differs → restage.+ utimesSync(path.join(dist, 'index.d.ts'), new Date(), new Date(Date.now() + 5000));+ expect((await ensureSdkTypes(root, [dist], '1.0.0')).staged).toBe(true);+ // Editor upgrade restages too.+ expect((await ensureSdkTypes(root, [dist], '2.0.0')).staged).toBe(true);+ });++ it('falls back through the candidate list to the first dist that exists', async () => {+ const missing = path.join(tmpdir(), 'estella-does-not-exist');+ const res = await ensureSdkTypes(root, [missing, dist], '1.0.0');+ expect(res.staged).toBe(true);+ expect(existsSync(mirrored('index.d.ts'))).toBe(true);+ });++ it('NO reachable dist is an error, not a silent skip', async () => {+ const missing = path.join(tmpdir(), 'estella-does-not-exist');+ await expect(ensureSdkTypes(root, [missing], '1.0.0')).rejects.toThrow(/SDK dist not found/);+ expect(existsSync(mirrored('index.d.ts'))).toBe(false);+ });+});