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): WeChat MiniGame target (exportWeChat)

esenginebcf82c5bcc5b
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index d41068ec1..115826eb6 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -25,8 +25,9 @@ import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets } from './cookAssets';
import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';
+import { exportWeChat } from './exportWeChat';
-export type ExportPlatform = 'web' | 'desktop';
+export type ExportPlatform = 'web' | 'desktop' | 'wechat';
export interface ExportGameResult {
ok: boolean;
@@ -201,12 +202,29 @@ export async function exportGame(opts: {
outDir: string;
title?: string;
platform?: ExportPlatform;
+ /** Built wechat SDK (dist/index.wechat.js) the WeChat bundle aliases `esengine` to. */
+ wechatSdkEntry?: string;
/** 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';
+
+ // WeChat has no import maps + a different module/asset model → its own pipeline.
+ if (platform === 'wechat') {
+ return exportWeChat({
+ root: opts.root,
+ entryScene: opts.entryScene,
+ scriptsEntry: opts.scriptsEntry,
+ wechatSdkEntry: opts.wechatSdkEntry ?? path.join(opts.sdkDistDir, 'index.wechat.js'),
+ wasmDir: opts.wasmDir,
+ outDir: opts.outDir,
+ title,
+ minify: opts.minify,
+ });
+ }
+
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;
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
new file mode 100644
index 000000000..2b230fc3c
--- /dev/null
+++ b/desktop/electron/exportWeChat.ts
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WeChat MiniGame export (REARCH_EXPORT E2). Assembles a project into the
+ * exact shape the SHIPPED runtime `initWeChatRuntime` consumes — it's
+ * correct-by-construction against that contract (this sandbox has no WeChat
+ * devtools, so runtime correctness is validated by the user in devtools):
+ *
+ * asset-manifest.json AddressableManifest (groups.<g>.assets[uuid] = {path,…});
+ * the WeChat path resolver keys by uuid → path.
+ * scenes/<name>.json the entry scene with @uuid: refs STRIPPED to bare
+ * uuids (the resolver looks up bare uuids, not @uuid:).
+ * game-bundle.js esbuild CJS of [wechat SDK (esengine aliased to the
+ * wechat build) + project scripts + a boot()] — one
+ * esengine instance so custom components/systems run.
+ * game.js the MiniGame entry: require the wasm factory + boot.
+ * wasm/ the -t wechat engine runtime (WXWebAssembly glue).
+ * game.json / project.config.json MiniGame config.
+ *
+ * Unlike web/desktop (which share the import-map web payload), WeChat has no
+ * import maps and a different module/asset model, so this is its own path.
+ * Pure Node (esbuild + fs) — IPC wiring is in main.ts.
+ */
+import { build } from 'esbuild';
+import { writeFile, mkdir, cp, readFile, stat, rm } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+import { cookAssets } from './cookAssets';
+
+export interface ExportWeChatResult {
+ ok: boolean;
+ platform: 'wechat';
+ outDir: string;
+ included: number;
+ warnings: string[];
+ errors: string[];
+}
+
+interface CookManifest {
+ entries: { uuid: string; path: string; type: string }[];
+}
+
+// Editor asset type → AddressableAssetType (sdk/src/assetTypes.ts). The WeChat
+// path resolver ignores type (keys by uuid → path); this only feeds the Catalog,
+// so an unmapped type degrading to 'binary' is harmless.
+const ADDRESSABLE_TYPE: Record<string, string> = {
+ texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',
+ prefab: 'prefab', 'spine-atlas': 'spine', 'spine-skeleton': 'spine',
+ scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', shader: 'text',
+};
+const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';
+
+const UUID_PREFIX = '@uuid:';
+
+/** Strip @uuid: asset refs to the bare (lowercased) uuid the WeChat resolver keys
+ * by. Deep, value-only — any string starting with @uuid: is a ref. */
+function stripUuidRefs(v: unknown): unknown {
+ if (typeof v === 'string') return v.startsWith(UUID_PREFIX) ? v.slice(UUID_PREFIX.length).toLowerCase() : v;
+ if (Array.isArray(v)) return v.map(stripUuidRefs);
+ if (v && typeof v === 'object') {
+ const o: Record<string, unknown> = {};
+ for (const k of Object.keys(v as Record<string, unknown>)) o[k] = stripUuidRefs((v as Record<string, unknown>)[k]);
+ return o;
+ }
+ return v;
+}
+
+function gameJson(): string {
+ return JSON.stringify({ deviceOrientation: 'portrait', showStatusBar: false }, null, 2) + '\n';
+}
+
+function projectConfigJson(title: string): string {
+ return JSON.stringify({
+ miniprogramRoot: './',
+ projectname: title,
+ appid: '', // fill in your WeChat MiniGame appid in devtools
+ setting: { es6: false, minified: false },
+ compileType: 'game',
+ }, null, 2) + '\n';
+}
+
+/** The MiniGame entry WeChat runs: hand the wasm factory to the bundle's boot(). */
+function gameEntryJs(): string {
+ return `'use strict';
+// Generated by Estella exportGame (WeChat MiniGame entry).
+const factory = require('./wasm/esengine.js');
+const bundle = require('./game-bundle.js');
+bundle.boot(typeof factory === 'function' ? factory : (factory && factory.default) || factory);
+`;
+}
+
+/** Read the web cook's flat manifest → AddressableManifest the WeChat runtime reads. */
+async function buildAddressableManifest(absOut: string): Promise<string> {
+ const cook = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest;
+ const assets: Record<string, { path: string; type: string; size: number; labels: string[] }> = {};
+ for (const e of cook.entries) {
+ let size = 0;
+ try { size = (await stat(path.join(absOut, e.path))).size; } catch { /* missing file → 0 */ }
+ assets[e.uuid.toLowerCase()] = { path: e.path, type: addrType(e.type), size, labels: [] };
+ }
+ return JSON.stringify({ version: '2.0', groups: { main: { bundleMode: 'local', labels: [], assets } } }, null, 2) + '\n';
+}
+
+/**
+ * Export the open project as a WeChat MiniGame into `outDir`. `wechatSdkEntry` is
+ * the built wechat SDK (dist/index.wechat.js) the bundle aliases `esengine` to;
+ * `wasmDir` the -t wechat engine runtime to copy.
+ */
+export async function exportWeChat(opts: {
+ root: string;
+ entryScene: string;
+ scriptsEntry?: string;
+ wechatSdkEntry: string;
+ wasmDir: string;
+ outDir: string;
+ title?: string;
+ minify?: boolean;
+}): Promise<ExportWeChatResult> {
+ const title = opts.title ?? 'Game';
+ const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(opts.root, opts.outDir);
+ const warnings: string[] = [];
+ const errors: string[] = [];
+ await mkdir(absOut, { recursive: true });
+
+ // 1. Cook reachable assets (paths preserved) + the flat manifest.
+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut });
+ warnings.push(...cook.warnings);
+
+ // 2. Flat manifest → AddressableManifest (asset-manifest.json); drop the web one.
+ try {
+ await writeFile(path.join(absOut, 'asset-manifest.json'), await buildAddressableManifest(absOut));
+ await rm(path.join(absOut, 'assets.manifest.json'), { force: true });
+ } catch (err) {
+ errors.push(`manifest: ${err instanceof Error ? err.message : String(err)}`);
+ }
+
+ // 3. Entry scene → scenes/<name>.json with @uuid: refs stripped to bare uuids.
+ const sceneName = path.basename(opts.entryScene).replace(/\.[^.]+$/, '');
+ try {
+ const raw = JSON.parse(await readFile(path.join(absOut, opts.entryScene), 'utf8'));
+ await mkdir(path.join(absOut, 'scenes'), { recursive: true });
+ await writeFile(path.join(absOut, 'scenes', `${sceneName}.json`), JSON.stringify(stripUuidRefs(raw)) + '\n');
+ } catch (err) {
+ errors.push(`scene transform: ${err instanceof Error ? err.message : String(err)}`);
+ }
+
+ // 4. game-bundle.js — wechat SDK (esengine aliased) + project scripts + boot(),
+ // one esengine instance so the project's defineComponent/defineSystem run.
+ const scriptsAbs = opts.scriptsEntry ? path.join(opts.root, opts.scriptsEntry) : null;
+ const entrySrc =
+ `import { initWeChatRuntime } from 'esengine';\n` +
+ (scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
+ `export function boot(engineFactory) {\n` +
+ ` return initWeChatRuntime({ engineFactory, sceneNames: ${JSON.stringify([sceneName])}, firstScene: ${JSON.stringify(sceneName)} });\n` +
+ `}\n`;
+ try {
+ const res = await build({
+ stdin: { contents: entrySrc, resolveDir: opts.root, loader: 'js', sourcefile: 'wechat-entry.js' },
+ bundle: true,
+ format: 'cjs',
+ platform: 'browser',
+ target: 'es2020',
+ alias: { esengine: opts.wechatSdkEntry },
+ minify: opts.minify ?? false,
+ sourcemap: false,
+ outfile: path.join(absOut, 'game-bundle.js'),
+ logLevel: 'silent',
+ write: true,
+ });
+ errors.push(...res.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)]));
+ }
+
+ // 5. Entry + config.
+ await writeFile(path.join(absOut, 'game.js'), gameEntryJs());
+ await writeFile(path.join(absOut, 'game.json'), gameJson());
+ await writeFile(path.join(absOut, 'project.config.json'), projectConfigJson(title));
+
+ // 6. The -t wechat engine runtime (WXWebAssembly glue + binary + side modules).
+ if (existsSync(opts.wasmDir)) await cp(opts.wasmDir, path.join(absOut, 'wasm'), { recursive: true });
+ else warnings.push(`wechat wasm runtime dir not found: ${opts.wasmDir}`);
+
+ return { ok: errors.length === 0, platform: 'wechat', outDir: absOut, included: cook.included.length, warnings, errors };
+}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index f6a475baa..fbfd3c09a 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -275,19 +275,26 @@ 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; platform?: 'web' | 'desktop' }) => {
+ async (_e, opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' }) => {
const root = requireRoot();
const manifest = await readManifest(root);
const entryScene = manifest.defaultScene;
if (!entryScene) throw new Error('project has no defaultScene to export');
+ const sdkDistDir = path.join(process.env.APP_ROOT!, 'node_modules', 'esengine', 'dist');
const publicWasm = path.join(VITE_PUBLIC, 'wasm');
+ const webWasm = existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm');
+ // WeChat needs the -t wechat runtime (WXWebAssembly glue); build it with
+ // `node build-tools/cli.js build -t wechat`. Absent → exportWeChat warns.
+ const wechatWasm = [path.join(VITE_PUBLIC, 'wasm-wechat'), path.join(process.env.APP_ROOT!, '..', 'build', 'wasm', 'wechat')]
+ .find(existsSync) ?? path.join(VITE_PUBLIC, 'wasm-wechat');
return exportGame({
root,
entryScene,
gameHostEntry: path.join(process.env.APP_ROOT!, 'src', 'gameHost.ts'),
scriptsEntry: resolveScripts(manifest).main,
- sdkDistDir: path.join(process.env.APP_ROOT!, 'node_modules', 'esengine', 'dist'),
- wasmDir: existsSync(publicWasm) ? publicWasm : path.join(RENDERER_DIST, 'wasm'),
+ sdkDistDir,
+ wasmDir: opts?.platform === 'wechat' ? wechatWasm : webWasm,
+ wechatSdkEntry: path.join(sdkDistDir, 'index.wechat.js'),
outDir: opts?.outDir || 'dist-game',
title: manifest.name,
platform: opts?.platform,
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 358e7a0db..0bc365ef7 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; platform?: 'web' | 'desktop' }): Promise<ExportGameResult> =>
+ exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' }): 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 8b617da98..a47c73dff 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -26,11 +26,11 @@ interface Result {
const PLATFORMS = [
{ id: 'web', label: 'Web', ready: true },
{ id: 'desktop', label: 'Desktop', ready: true },
- { id: 'wechat', label: 'WeChat', ready: false },
+ { id: 'wechat', label: 'WeChat', ready: true },
{ id: 'playable', label: 'Playable', ready: false },
] as const;
-type Platform = 'web' | 'desktop';
+type Platform = 'web' | 'desktop' | 'wechat';
export function BuildDialog() {
const close = () => useEditorStore.getState().setBuildOpen(false);
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index ce3300d2d..83368cb9b 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; platform?: 'web' | 'desktop' }) {
+ async exportGame(opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: 'web' | 'desktop' | 'wechat' }) {
if (!this.state) return null;
return window.estella.project.exportGame(opts);
}
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
new file mode 100644
index 000000000..c9259a5d0
--- /dev/null
+++ b/desktop/tests/export-wechat.test.ts
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WeChat MiniGame export — structure / contract alignment. Asserts the
+ * output matches what initWeChatRuntime consumes: AddressableManifest
+ * (asset-manifest.json), @uuid:-stripped scenes/<name>.json, the single
+ * CJS game-bundle (esengine aliased so project scripts share one instance),
+ * the game.js entry, the wasm copy, and game.json/project.config.json.
+ * (Runtime correctness is validated by the user in WeChat devtools — no
+ * simulator here.)
+ */
+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 { exportGame } from '../electron/exportGame';
+
+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(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-wechat-'));
+ 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`);
+ // Stub wechat SDK (the bundle aliases `esengine` to this) + stub -t wechat runtime.
+ writeFileSync(path.join(root, '_wechat-sdk.js'), `export function initWeChatRuntime(){return Promise.resolve();}\nexport function defineComponent(){}\n`);
+ mkdirSync(path.join(root, '_wxwasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(root, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
+
+ out = path.join(root, 'dist-wechat');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('exportGame (wechat)', () => {
+ it('assembles a MiniGame matching the initWeChatRuntime contract', async () => {
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wechatSdkEntry: path.join(root, '_wechat-sdk.js'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: out,
+ title: 'My Game',
+ platform: 'wechat',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('wechat');
+
+ // AddressableManifest (asset-manifest.json), web flat manifest removed.
+ expect(existsSync(path.join(out, 'assets.manifest.json'))).toBe(false);
+ const manifest = JSON.parse(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8'));
+ expect(manifest.version).toBe('2.0');
+ expect(manifest.groups.main.assets[TEX].path).toBe('assets/hero.png');
+ expect(manifest.groups.main.assets[TEX].type).toBe('texture');
+
+ // Scene at scenes/<name>.json with @uuid: stripped to the bare uuid.
+ const scene = JSON.parse(readFileSync(path.join(out, 'scenes', 'main.json'), 'utf8'));
+ expect(scene.entities[0].components[0].data.texture).toBe(TEX); // no @uuid: prefix
+
+ // One CJS bundle (SDK aliased + project scripts) exposing boot(), + the entry.
+ const bundle = readFileSync(path.join(out, 'game-bundle.js'), 'utf8');
+ expect(bundle).toContain('boot');
+ expect(bundle).toContain('SpawnMarker'); // project script inlined into the one bundle
+ const entry = readFileSync(path.join(out, 'game.js'), 'utf8');
+ expect(entry).toContain("require('./game-bundle.js')");
+ expect(entry).toContain("require('./wasm/esengine.js')");
+
+ // Config + runtime copy.
+ const pcfg = JSON.parse(readFileSync(path.join(out, 'project.config.json'), 'utf8'));
+ expect(pcfg.compileType).toBe('game');
+ expect(pcfg.projectname).toBe('My Game');
+ expect(existsSync(path.join(out, 'game.json'))).toBe(true);
+ expect(existsSync(path.join(out, 'wasm', 'esengine.js'))).toBe(true);
+ expect(existsSync(path.join(out, 'wasm', 'esengine.wasm'))).toBe(true);
+ }, 60_000);
+});