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): the engine binary can ship as .wasm.br to a host that takes one

esenginee6b2b704e4f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf3f11fd4..3b963362f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,18 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **A WeChat mini-game can ship its engine compressed, freeing a third of the main
+ package.** The engine binary is the largest single file such a package carries — 1.74MB
+ against WeChat's 4MB main-package limit, 43.6% of it spent before any of your content.
+ WeChat's loader accepts a brotli-compressed `.wasm.br` path, so turning on *Compress
+ engine binary* on the WeChat page of Package Project ships 0.35MB instead: 8.7% of the
+ limit, with 1.40MB handed back to the game. The package carries one file, not both, and
+ the host decompresses it on load. Off by default, since it costs about two seconds of
+ build time and only pays where a main-package limit is being fought. Needs WeChat base
+ library 2.14.0.
+
## [0.69.0] - 2026-09-18
### Added
diff --git a/desktop b/desktop
index be2aadb3a..4342add95 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit be2aadb3aea2319726a553bc68c7611fc4aba708
+Subproject commit 4342add952fd8f971be7c54c0620c7a5417f5156
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index 6f5c6582d..7231380f5 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -357,6 +357,9 @@ export interface ExportGameOptions {
compressAudio?: boolean;
/** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. Default off. */
atlasTextures?: boolean;
+ /** Compress the engine binary to `.wasm.br`, where the target's loader takes
+ * one. Default off; ignored by targets that cannot load it. */
+ compressWasm?: boolean;
title?: string;
platform?: ExportPlatform;
/** The ad network a playable targets (`packaging.platforms.playable.network`),
@@ -586,6 +589,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
compressTextures: opts.compressTextures,
compressAudio: opts.compressAudio,
atlasTextures: opts.atlasTextures,
+ compressWasm: opts.compressWasm,
onProgress: opts.onProgress,
});
}
@@ -612,6 +616,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
compressTextures: opts.compressTextures,
compressAudio: opts.compressAudio,
atlasTextures: opts.atlasTextures,
+ compressWasm: opts.compressWasm,
onProgress: opts.onProgress,
});
}
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index 2f9838fa6..d7580d293 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -33,6 +33,8 @@ import {
DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,
} from '../project/runtimeConfig';
import { writeFile, mkdir, cp, readFile, rename, rm } from 'node:fs/promises';
+import { brotliCompress as brotliCompressCb, constants as zlibConstants } from 'node:zlib';
+import { promisify } from 'node:util';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets, type Inclusion } from '../assets/cookAssets';
@@ -67,6 +69,8 @@ interface CookManifest {
}[];
}
+const brotliPack = promisify(brotliCompressCb);
+
const UUID_PREFIX = '@uuid:';
/** Strip @uuid: asset refs to the bare (lowercased) uuid the resolver keys by.
@@ -82,6 +86,42 @@ function stripUuidRefs(v: unknown): unknown {
return v;
}
+/** What this export stages into `wasm/`, and the engine path the loader is told. */
+interface RuntimeLayout {
+ /** Package-relative path the boot config hands the loader. */
+ readonly enginePath: string;
+ /** Engine artifacts to stage, as the name in `wasmDir` → the name in the package. */
+ readonly files: ReadonlyArray<{ readonly src: string; readonly staged: string; readonly brotli?: true }>;
+}
+
+/**
+ * Decided ONCE, read by the boot config and the copy loop: what lands is what
+ * the loader is told. Only the ENGINE binary compresses — a side module's is
+ * found at `wasm/<file>.wasm` by three hosts that spell that suffix themselves,
+ * so renaming one here would leave all three naming a file that is not there.
+ */
+function planRuntimeLayout(
+ engineGlueFile: string,
+ sideModules: ReadonlyArray<{ file: string }>,
+ brotli: boolean,
+): RuntimeLayout {
+ const engineBinary = engineGlueFile.replace(/\.js$/, '.wasm');
+ const engineStaged = brotli ? `${engineBinary}.br` : engineBinary;
+ return {
+ enginePath: `wasm/${engineStaged}`,
+ files: [
+ { src: engineGlueFile, staged: engineGlueFile },
+ ...(brotli
+ ? [{ src: engineBinary, staged: engineStaged, brotli: true as const }]
+ : [{ src: engineBinary, staged: engineStaged }]),
+ ...sideModules.flatMap((m) => [
+ { src: `${m.file}.js`, staged: `${m.file}.js` },
+ { src: `${m.file}.wasm`, staged: `${m.file}.wasm` },
+ ]),
+ ],
+ };
+}
+
/**
* The vendor subPackage roots this package actually carries, read off the STAGED
* paths: a root the package lacks fails the whole game at load ("root 不存在").
@@ -190,6 +230,9 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
compressAudio?: boolean;
/** Pack `<name>.atlas/` folder PNGs into atlas pages at cook time. */
atlasTextures?: boolean;
+ /** The project's `packaging.compressWasm`; honoured only where the vendor can
+ * load a `.wasm.br` (profile.wasmBrotli) — policy meeting capability. */
+ compressWasm?: boolean;
onProgress?: OnExportProgress;
}): Promise<ExportMiniGameResult> {
const title = opts.title ?? 'Game';
@@ -308,10 +351,11 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// 4. game-bundle.js — vendor 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;
- // The engine wasm path rides into the boot config: only the exporter knows
- // which glue it staged (esengine.wxgame vs the web-aligned esengine), and the
- // runtime must instantiate the staged glue's .wasm twin, not guess a name.
- const engineWasmPath = `wasm/${engineGlueFile.replace(/\.js$/, '.wasm')}`;
+ // Compressing needs both halves: a vendor whose loader takes `.wasm.br`, and a
+ // project that asked for it. Either alone leaves the binary as built.
+ const brotli = profile.wasmBrotli && (opts.compressWasm ?? false);
+ const runtimeLayout = planRuntimeLayout(engineGlueFile, engineSideModules, brotli);
+ const engineWasmPath = runtimeLayout.enginePath;
// The packaged slice of the project's settings, GENERATED rather than listed:
// a setting added to packagedRuntimeFields reaches this boot without anyone
// having to remember that this template exists. Theme colours are the one that
@@ -478,24 +522,34 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
await mkdir(wasmOut, { recursive: true });
// Engine artifacts only — the project's own come from `.esengine/modules/`,
// not from the engine runtime dir, and are staged below.
- const runtimeFiles = [
- engineGlueFile,
- engineGlueFile.replace(/\.js$/, '.wasm'),
- ...engineSideModules.flatMap((m) => [`${m.file}.js`, `${m.file}.wasm`]),
- ];
const { transform } = await loadEsbuild();
- for (const f of runtimeFiles) {
- const src = path.join(opts.wasmDir, f);
+ for (const f of runtimeLayout.files) {
+ const src = path.join(opts.wasmDir, f.src);
if (!existsSync(src)) {
- errors.push(`${profile.id} runtime file missing: ${f} (in ${opts.wasmDir}) — rebuild with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\``);
+ errors.push(`${profile.id} runtime file missing: ${f.src} (in ${opts.wasmDir}) — rebuild with \`node build-tools/cli.js build -t ${profile.wasmBuildHint}\``);
continue;
}
- const dest = path.join(wasmOut, f);
- if (f.endsWith('.js')) {
+ const dest = path.join(wasmOut, f.staged);
+ if (f.src.endsWith('.js')) {
// Emscripten glue can carry es2020 syntax (`?.`, `??`) that real-device
// WeChat rejects — down-level it like the game bundle.
const out = await transform(await readFile(src, 'utf8'), { target: profile.esTarget, loader: 'js' });
await writeFile(dest, out.code);
+ } else if (f.brotli) {
+ // Quality 11: it runs once per build, and the bytes it saves are spent
+ // against a main-package limit for the life of the package.
+ const raw = await readFile(src);
+ const packed = await brotliPack(raw, {
+ params: {
+ [zlibConstants.BROTLI_PARAM_QUALITY]: zlibConstants.BROTLI_MAX_QUALITY,
+ [zlibConstants.BROTLI_PARAM_SIZE_HINT]: raw.byteLength,
+ },
+ });
+ await writeFile(dest, packed);
+ progress({
+ phase: 'Copying runtime',
+ detail: `${f.staged} ${(raw.byteLength / 1048576).toFixed(2)}MB → ${(packed.byteLength / 1048576).toFixed(2)}MB`,
+ });
} else {
await cp(src, dest);
}
diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.ts
index 804bf882a..032c9eca9 100644
--- a/pipeline/src/export/miniGameExportProfile.ts
+++ b/pipeline/src/export/miniGameExportProfile.ts
@@ -103,6 +103,13 @@ export interface MiniGameExportProfile {
readonly nativeSuffixes: ReadonlySet<string>;
/** Custom extensions the packer denies unless restaged to `<ext>.bin`. */
readonly binRestageExts: readonly string[];
+ /**
+ * Whether this vendor's loader takes a `.wasm.br` path — a CAPABILITY;
+ * spending the build time is `packaging.compressWasm`. WeChat's
+ * `WXWebAssembly.instantiate` accepts one from base library 2.14.0, a floor
+ * documented rather than probed: the loader cannot be asked.
+ */
+ readonly wasmBrotli: boolean;
/** Subpackage root prefix (files stage under `<subpackageDir>/<name>/`). */
readonly subpackageDir: string;
/**
@@ -168,6 +175,7 @@ export const wechatExportProfile: MiniGameExportProfile = {
nativeSuffixes: new Set(['.js', '.json']),
// WeChat's code-package suffix whitelist has no ktx2/esv; restage to *.bin.
binRestageExts: ['ktx2', 'esv'],
+ wasmBrotli: true,
subpackageDir: 'subpackages',
subpackageEntry: 'game.js',
diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.ts
index 2a46f4856..f0d2d8efc 100644
--- a/pipeline/src/project/format.ts
+++ b/pipeline/src/project/format.ts
@@ -291,6 +291,12 @@ export interface ProjectPackaging {
compressAudio?: boolean;
/** @deprecated see {@link assetCompression}. */
atlasTextures?: boolean;
+ /**
+ * Compress the engine binary to `.wasm.br` where the host can load one — the
+ * POLICY half of `profile.wasmBrotli`, ignored by hosts that cannot. Off by
+ * default: it costs build time, and only pays where a main-package limit is.
+ */
+ compressWasm?: boolean;
/** Project-relative scene paths NOT shipped as switchable scenes (dev/test
* scenes). Everything else under the scenes dir exports; the startup scene
* always ships regardless. */
diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.ts
index f8f1ea472..119fbb213 100644
--- a/pipeline/tests/export-wechat.test.ts
+++ b/pipeline/tests/export-wechat.test.ts
@@ -511,6 +511,62 @@ describe('exportGame (wechat)', () => {
const pcfg = JSON.parse(readFileSync(path.join(outMulti, 'project.config.json'), 'utf8'));
expect(pcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.esscene' });
}, 60_000);
+ // The engine binary is the largest single file in a mini-game package and the
+ // main-package limit is 4MB, so compressing it is worth a build-time cost —
+ // but only where the host can load the result, and only when the project asked.
+ it('compresses the engine binary to .wasm.br, and tells the loader THAT name', async () => {
+ const o = path.join(root, 'dist-wx-br');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ hostsDir: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: o,
+ platform: 'wechat',
+ wechatAppid: 'wxTEST0123456789',
+ compressWasm: true,
+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
+ });
+ expect(res.ok).toBe(true);
+
+ // What landed is the compressed one, under the .br name, and the raw twin
+ // is NOT also shipped — two copies would cost more than the compression saves.
+ expect(existsSync(path.join(o, 'wasm', 'esengine.wasm.br'))).toBe(true);
+ expect(existsSync(path.join(o, 'wasm', 'esengine.wasm'))).toBe(false);
+
+ // And the boot config names the file that is actually there. This is the
+ // half that a second derivation of the name would get wrong in silence.
+ const bundle = readFileSync(path.join(o, 'game-bundle.js'), 'utf8');
+ expect(bundle).toContain('wasm/esengine.wasm.br');
+
+ // The glue is untouched: only the binary compresses, and the packer still
+ // has JS it can compile.
+ expect(existsSync(path.join(o, 'wasm', 'esengine.js'))).toBe(true);
+ }, 60_000);
+
+ // Policy without capability changes nothing, and neither does the reverse:
+ // the default export still ships the binary as it was built.
+ it('leaves the binary alone when the project did not ask', async () => {
+ const o = path.join(root, 'dist-wx-nobr');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ hostsDir: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: o,
+ platform: 'wechat',
+ wechatAppid: 'wxTEST0123456789',
+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
+ });
+ expect(res.ok).toBe(true);
+ expect(existsSync(path.join(o, 'wasm', 'esengine.wasm'))).toBe(true);
+ expect(existsSync(path.join(o, 'wasm', 'esengine.wasm.br'))).toBe(false);
+ expect(readFileSync(path.join(o, 'game-bundle.js'), 'utf8')).toContain('wasm/esengine.wasm');
+ }, 60_000);
});
/**
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index d980f2ca2..4ff461859 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,12 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'feat(export): the engine binary can ship as .wasm.br to a host that takes one':
+ { note: 'A WeChat mini-game can ship its engine compressed, freeing a third of the main' },
+
+ 'feat(build): a mini-game can ship its engine binary compressed':
+ { note: 'A WeChat mini-game can ship its engine compressed, freeing a third of the main' },
+
'fix(gates): project-health tests a warning with a field that still is one':
{ internal: "The preflight check's own fixture; it follows the sprite-texture change and no creator runs it." },