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
// SPDX-License-Identifier: Apache-2.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), 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 { runtimeConfigOf } from '../src/project/runtimeConfig';
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, readdirSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { exportGame } from '../src/export/exportGame';
import { miniGameSdkStub } from './fixtures/miniGameSdkStub';
import { wechatExportProfile } from '../src/export/miniGameExportProfile';
import { OFFICIAL_PACKAGES } from './officialPackagesDir';
let root: string;
let out: string;
const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
const SUBTEX = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
const LOC = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
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'));
// An authored format whose suffix is NOT on WeChat's upload whitelist. Without
// one here, a gate about that whitelist has nothing to be wrong about — which
// is how a package full of them built clean for as long as it did.
mkdirSync(path.join(root, 'assets', 'i18n'), { recursive: true });
writeFileSync(path.join(root, 'assets', 'i18n', 'en.eslocale'), JSON.stringify({ hello: 'hi' }));
writeFileSync(path.join(root, 'assets', 'i18n', 'en.eslocale.meta'), meta(LOC, 'locale'));
// A lazy-subpackage asset (folder convention): NOT referenced by the entry
// scene, so it exercises force-include + grouping.
mkdirSync(path.join(root, 'subpackages', 'level2'), { recursive: true });
writeFileSync(path.join(root, 'subpackages', 'level2', 'extra.png'), 'PNG2DATA');
writeFileSync(path.join(root, 'subpackages', 'level2', 'extra.png.meta'), meta(SUBTEX, 'texture'));
mkdirSync(path.join(root, 'src'), { recursive: true });
writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
// Stub SDK dist (the bundle aliases `esengine` → <sdkDir>/index.wechat.js) + stub -t wechat runtime.
mkdirSync(path.join(root, '_sdk'), { recursive: true });
writeFileSync(path.join(root, '_sdk', 'index.wechat.js'), miniGameSdkStub(wechatExportProfile, ['defineComponent']));
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, maxRetries: 10, retryDelay: 50 }));
describe('exportGame (wechat)', () => {
it('fails instead of shipping a video the WASM decoder cannot play', async () => {
const video = '99999999-9999-4999-8999-999999999999';
writeFileSync(path.join(root, 'assets/broken.mp4'), 'NOT A VIDEO');
writeFileSync(path.join(root, 'assets/broken.mp4.meta'), meta(video, 'video'));
const entry = 'scenes/broken-video.esscene';
writeFileSync(path.join(root, entry), JSON.stringify({ version: '1.0', entities: [
{ id: 0, components: [{ type: 'Video', data: { source: `@uuid:${video}` } }] },
] }));
writeFileSync(path.join(root, `${entry}.meta`), meta('88888888-8888-4888-8888-888888888888', 'scene'));
const dir = path.join(root, 'dist-wechat-broken-video');
try {
const result = await exportGame({ minifyScripts: false, root, entryScene: entry,
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wxwasm'), outDir: dir, platform: 'wechat' });
expect(result.ok).toBe(false);
expect(result.errors.join('\n')).toMatch(/asset not packaged.*broken\.mp4/);
const manifest = JSON.parse(readFileSync(path.join(dir, 'asset-manifest.json'), 'utf8'));
expect(manifest.groups.main.assets[video]).toBeUndefined();
} finally {
for (const file of ['assets/broken.mp4', 'assets/broken.mp4.meta', entry, `${entry}.meta`]) {
rmSync(path.join(root, file), { force: true });
}
}
}, 60_000);
it('removes the old texture file when re-exporting changed art', async () => {
const dir = path.join(root, 'dist-wechat-recook');
const source = path.join(root, 'assets/hero.png');
const original = readFileSync(source);
const run = () => exportGame({ minifyScripts: false, root, entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wxwasm'), outDir: dir, platform: 'wechat' });
try {
expect((await run()).ok).toBe(true);
const old = JSON.parse(readFileSync(path.join(dir, 'asset-manifest.json'), 'utf8')).groups.main.assets[TEX].path as string;
writeFileSync(path.join(dir, 'project.private.config.json'), 'KEEP');
writeFileSync(source, 'CHANGEDPNGDATA');
expect((await run()).ok).toBe(true);
const current = JSON.parse(readFileSync(path.join(dir, 'asset-manifest.json'), 'utf8')).groups.main.assets[TEX].path as string;
expect(current).not.toBe(old);
expect(existsSync(path.join(dir, old))).toBe(false);
expect(existsSync(path.join(dir, current))).toBe(true);
expect(readFileSync(path.join(dir, 'project.private.config.json'), 'utf8')).toBe('KEEP');
} finally { writeFileSync(source, original); }
}, 60_000);
it('assembles a MiniGame matching the initWeChatRuntime contract', async () => {
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: out,
title: 'My Game',
platform: 'wechat',
miniGameAppid: 'wxTEST0123456789',
orientation: 'landscape',
runtime: runtimeConfigOf({
designResolution: { width: 1280, height: 720 },
features: { rendering: { cameraScaleMode: 'expand', depthLayers: [1] } },
}),
});
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).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
expect(manifest.groups.main.assets[TEX].type).toBe('texture');
// Scene at scenes/<name>.json, its refs as authored — the web package's form.
// Stripping them to bare uuids lost every atlas frame, which is keyed `@uuid:`.
const scene = JSON.parse(readFileSync(path.join(out, 'scenes', 'main.json'), 'utf8'));
expect(scene.entities[0].components[0].data.texture).toBe(`@uuid:${TEX}`);
// 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')");
// The boot config names the staged glue's .wasm twin — WXWebAssembly
// instantiates by package-relative path, so the runtime must not guess.
expect(bundle).toContain('wasm/esengine.wasm');
// The project camera fit rides the boot config into initWeChatRuntime.
expect(bundle).toContain('screenFit');
// The platform is INSTALLED by a call the entry makes, not by an SDK module's
// top-level statement: when the install sat in a shared chunk that
// `sideEffects` did not name, the bundler dropped it and every package threw
// "Platform not initialized" on its first frame.
const { platformInit } = wechatExportProfile;
expect(platformInit, 'the profile must name how the platform is installed').toBeTruthy();
expect(bundle).toContain(`${platformInit}()`);
expect(bundle).toMatch(/"scaleMode":\s*2/);
// Same generated boot carries the 2.5D opt-in — one packaged slice, so a
// setting cannot reach one target and not another.
expect(bundle).toMatch(/depthLayers:\s*2/);
// 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(pcfg.appid).toBe('wxTEST0123456789'); // from Project Settings → Packaging
const gjson = JSON.parse(readFileSync(path.join(out, 'game.json'), 'utf8'));
expect(gjson.deviceOrientation).toBe('landscape');
expect(existsSync(path.join(out, 'wasm', 'esengine.js'))).toBe(true);
expect(existsSync(path.join(out, 'wasm', 'esengine.wasm'))).toBe(true);
// 分包: the subpackages/level2 asset forms a lazy group, registered as a
// WeChat subPackage, with its file staged under the subpackage root.
expect(manifest.groups.level2.bundleMode).toBe('lazy');
expect(manifest.groups.main.bundleMode).toBe('local');
expect(manifest.groups.level2.assets[SUBTEX].path).toMatch(/^subpackages\/level2\/assets\/[0-9a-f]{16}\.png$/);
expect(gjson.subPackages).toContainEqual({ name: 'level2', root: 'subpackages/level2' });
expect(existsSync(path.join(out, manifest.groups.level2.assets[SUBTEX].path))).toBe(true);
}, 60_000);
it('requires the glue by its actual -t wechat name; unneeded side modules stay out (4MB budget)', async () => {
const wxDir = path.join(root, '_wxwasm-wxgame');
mkdirSync(wxDir, { recursive: true });
writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(wxDir, 'esengine.wxgame.wasm'), 'wasmbytes');
// Present in the runtime dir but not needed by the scene — must not ship.
writeFileSync(path.join(wxDir, 'physics.js'), 'module.exports = () => {};');
writeFileSync(path.join(wxDir, 'physics.wasm'), 'wasmbytes');
const outWx = path.join(root, 'dist-wechat-wxgame');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: wxDir,
outDir: outWx,
platform: 'wechat',
});
expect(res.ok).toBe(true);
expect(readFileSync(path.join(outWx, 'game.js'), 'utf8')).toContain("require('./wasm/esengine.wxgame.js')");
expect(readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8')).toContain('wasm/esengine.wxgame.wasm');
expect(existsSync(path.join(outWx, 'wasm', 'esengine.wxgame.wasm'))).toBe(true);
expect(existsSync(path.join(outWx, 'wasm', 'physics.js'))).toBe(false);
expect(existsSync(path.join(outWx, 'wasm', 'physics.wasm'))).toBe(false);
// …and the budget in that title is now MEASURED, not just a motive. WeChat's
// two limits ride the mini-game path the same way they ride every other one,
// and the main-package figure counts the engine and the bundle — the bytes a
// player downloads before anything runs, which is what the 4MB applies to.
const initial = res.size?.verdicts.find((v) => v.budget.scope === 'initial');
const total = res.size?.verdicts.find((v) => v.budget.scope === 'total');
expect(initial?.budget.maxBytes).toBe(4 * 1024 * 1024);
expect(total?.budget.maxBytes).toBe(30 * 1024 * 1024);
expect(initial?.status).toBe('ok');
expect(res.size?.byKind.find((k) => k.kind === 'engine')?.bytes).toBeGreaterThan(0);
// Everything under a subpackage root is off the main package: the asset
// (8 bytes) AND the entry `game.js` WeChat demands in every root (169).
const lazy = 8 + 169;
expect(res.size?.lazyBytes).toBe(lazy);
expect(res.size?.packageBytes).toBe(res.size!.initialBytes + lazy);
expect(initial?.measuredBytes).toBe(res.size?.initialBytes);
}, 60_000);
// The project's own ceiling, all the way through: packaging.sizeBudget →
// exportGame → the verdict a CI gate and the build dialog both read. The
// headless exporter reads that field through `parseManifest`, so this covers
// the half of the path that is not the parser's.
it("judges against the project's own ceiling when it declares one", async () => {
const outWx = path.join(root, 'dist-wechat-budget');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outWx,
platform: 'wechat',
sizeBudgetBytes: 1024, // this fixture is a few KB — deliberately over
});
expect(res.ok).toBe(true);
const initial = res.size?.verdicts.find((v) => v.budget.scope === 'initial');
expect(initial?.status).toBe('over');
expect(initial?.budget.maxBytes).toBe(1024);
// Attributed to the project, not quoted as a WeChat rule that never said this.
expect(initial?.budget.note).toBe('project budget');
// Replacing the main-package limit is not a waiver of the other one.
expect(res.size?.verdicts.find((v) => v.budget.scope === 'total')?.budget.maxBytes)
.toBe(30 * 1024 * 1024);
}, 60_000);
// The platform this matters most on: a mini-game has no `fetch`, so a
// third-party runtime cannot be loaded by hand at all — the binary has to be
// in the package and the glue has to be require()d by the generated entry.
it("packages a project's own native module and requires it from game.js", async () => {
const modDir = path.join(root, '.esengine', 'modules', 'rive');
rmSync(path.join(root, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
mkdirSync(path.join(modDir, 'wechat'), { recursive: true });
writeFileSync(path.join(modDir, 'module.json'), JSON.stringify({ file: 'rive', globalName: 'RiveModule' }));
// `?.` is exactly what a real-device host rejects — it must not survive.
writeFileSync(path.join(modDir, 'wechat', 'rive.js'), 'var RiveModule = (o) => Promise.resolve(o?.x);');
writeFileSync(path.join(modDir, 'wechat', 'rive.wasm'), 'wasmbytes');
const outWx = path.join(root, 'dist-wechat-module');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outWx,
platform: 'wechat',
});
expect(res.ok).toBe(true);
// Staged beside the engine's runtime, in the dir game.js require()s from.
expect(existsSync(path.join(outWx, 'wasm', 'rive.js'))).toBe(true);
expect(existsSync(path.join(outWx, 'wasm', 'rive.wasm'))).toBe(true);
// The generated entry hands its factory in by id, like a built-in module.
const gameJs = readFileSync(path.join(outWx, 'game.js'), 'utf8');
expect(gameJs).toContain(`"rive": asFactory(require('./wasm/rive.js'))`);
// A mini-game does not read game.config.json — its config IS the boot call,
// so the artifact name rides there or the runtime cannot find the binary.
// Matched loosely: the bundler re-prints the object literal.
const bundle = readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8');
const declaration = bundle.match(/sideModules:\s*\[[^\]]*\]/)?.[0] ?? '(no sideModules in the boot call)';
expect(declaration).toContain('"rive"');
expect(declaration).toContain('RiveModule');
// Down-levelled like the engine's own glue.
expect(readFileSync(path.join(outWx, 'wasm', 'rive.js'), 'utf8')).not.toContain('?.');
rmSync(path.join(root, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
}, 60_000);
it('carries the same hot-update delivery the web road does into the boot call', async () => {
const outWx = path.join(root, 'dist-wechat-hotupdate');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outWx,
platform: 'wechat',
hotUpdate: { remoteRoot: 'https://cdn.example/v3', persistUpdateKey: 'game:updates' },
});
expect(res.ok).toBe(true);
// Without it a mini-game neither resolved remote groups against its CDN nor
// started on an update it had applied: the next launch was the shipped build.
const bundle = readFileSync(path.join(outWx, 'game-bundle.js'), 'utf8');
const declaration = bundle.match(/hotUpdate:\s*\{[^}]*\}/)?.[0] ?? '(no hotUpdate in the boot call)';
expect(declaration).toContain('https://cdn.example/v3');
expect(declaration).toContain('game:updates');
}, 60_000);
it('a development build that dials the editor turns off DevTools\' domain check, and only that build', async () => {
const cfg = async (debugChannel?: { url: string }) => {
const out = path.join(root, debugChannel ? 'dist-wechat-dbg' : 'dist-wechat-nodbg');
const res = await exportGame({
minifyScripts: false,
root, entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES, scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wxwasm'), outDir: out,
platform: 'wechat', ...(debugChannel ? { debugChannel } : {}),
});
expect(res.ok).toBe(true);
return JSON.parse(readFileSync(path.join(out, 'project.config.json'), 'utf8')).setting;
};
// Measured in DevTools: without it the socket is refused, "url not in domain list".
expect((await cfg({ url: 'ws://192.168.1.5:37420/?token=t' })).urlCheck).toBe(false);
expect((await cfg()).urlCheck).toBeUndefined();
}, 60_000);
it('refuses to substitute a web build for a mini-game one', async () => {
// Serving the web glue would produce a package that builds clean and dies on
// a device — the failure this whole per-platform layout exists to prevent.
const modDir = path.join(root, '.esengine', 'modules', 'rive');
rmSync(path.join(root, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
mkdirSync(path.join(modDir, 'web'), { recursive: true });
writeFileSync(path.join(modDir, 'web', 'rive.js'), 'export default () => Promise.resolve({});');
const outWx = path.join(root, 'dist-wechat-module-webonly');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outWx,
platform: 'wechat',
});
expect(res.ok).toBe(true);
expect(res.warnings.join('\n')).toContain('wechat/rive.js');
expect(existsSync(path.join(outWx, 'wasm', 'rive.js'))).toBe(false);
expect(readFileSync(path.join(outWx, 'game.js'), 'utf8')).not.toContain('rive');
rmSync(path.join(root, '.esengine'), { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
}, 60_000);
it('fails fast when the -t wechat engine runtime is missing', async () => {
const outMissing = path.join(root, 'dist-wechat-missing');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_no-such-wasm'),
outDir: outMissing,
platform: 'wechat',
});
expect(res.ok).toBe(false);
expect(res.errors[0]).toContain('build -t wechat');
// Failed before cooking — no half-assembled package left behind.
expect(existsSync(outMissing)).toBe(false);
}, 60_000);
it('detects a spine skeleton (authored meta type "spine") and ships exactly its module', async () => {
const SPINE = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
const SPINESCN = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';
writeFileSync(path.join(root, 'assets', 'boy.json'), JSON.stringify({ skeleton: { spine: '4.2.22' } }));
writeFileSync(path.join(root, 'assets', 'boy.json.meta'), meta(SPINE, 'spine'));
// Own scenes dir: scene discovery walks the entry's dir, and this test's
// scene must not leak into the other exports (nor theirs into this one).
mkdirSync(path.join(root, 'scenes-spine'), { recursive: true });
writeFileSync(
path.join(root, 'scenes-spine', 'spine.esscene'),
JSON.stringify({ version: '1.0', name: 'Spine', entities: [{ id: 0, components: [{ type: 'SpineSkeleton', data: { skeleton: `@uuid:${SPINE}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes-spine', 'spine.esscene.meta'), meta(SPINESCN, 'scene'));
const wxDir = path.join(root, '_wxwasm-spine');
mkdirSync(wxDir, { recursive: true });
writeFileSync(path.join(wxDir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(wxDir, 'esengine.wasm'), 'wasmbytes');
writeFileSync(path.join(wxDir, 'spine42.js'), 'module.exports = () => {};');
writeFileSync(path.join(wxDir, 'spine42.wasm'), 'wasmbytes');
const outSpine = path.join(root, 'dist-wechat-spine');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-spine/spine.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: wxDir,
outDir: outSpine,
platform: 'wechat',
});
expect(res.ok).toBe(true);
const entry = readFileSync(path.join(outSpine, 'game.js'), 'utf8');
expect(entry).toContain("\"spine:4.2\": asFactory(require('./wasm/spine42.js'))");
expect(existsSync(path.join(outSpine, 'wasm', 'spine42.wasm'))).toBe(true);
// Scenes restage as scenes/<name>.json, so no .esscene ships — and native
// types stay out of the include list; it exists for the custom ones.
const spcfg = JSON.parse(readFileSync(path.join(outSpine, 'project.config.json'), 'utf8'));
expect(spcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.esscene' });
expect(spcfg.packOptions?.include ?? []).not.toContainEqual({ type: 'suffix', value: '.json' });
// The manifest keeps the real addressable type, not a 'binary' downgrade.
const manifest = JSON.parse(readFileSync(path.join(outSpine, 'asset-manifest.json'), 'utf8'));
expect(manifest.groups.main.assets[SPINE].type).toBe('spine');
}, 60_000);
it('a needed spine module missing from the runtime dir fails the export', async () => {
const outBroken = path.join(root, 'dist-wechat-spine-missing');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-spine/spine.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'), // engine only — no spine42
outDir: outBroken,
platform: 'wechat',
});
expect(res.ok).toBe(false);
expect(res.errors.some((e) => e.includes('spine-wechat'))).toBe(true);
}, 60_000);
it('a staged .ktx2 texture ships the Basis transcoder module', async () => {
const KTX = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
const KTXSCN = 'abababab-abab-abab-abab-abababababab';
writeFileSync(path.join(root, 'assets', 'pre.ktx2'), 'KTX2BYTES');
writeFileSync(path.join(root, 'assets', 'pre.ktx2.meta'), meta(KTX, 'texture'));
mkdirSync(path.join(root, 'scenes-ktx2'), { recursive: true });
writeFileSync(
path.join(root, 'scenes-ktx2', 'ktx2.esscene'),
JSON.stringify({ version: '1.0', name: 'Ktx', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${KTX}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes-ktx2', 'ktx2.esscene.meta'), meta(KTXSCN, 'scene'));
const wxDir = path.join(root, '_wxwasm-basis');
mkdirSync(wxDir, { recursive: true });
writeFileSync(path.join(wxDir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(wxDir, 'esengine.wasm'), 'wasmbytes');
writeFileSync(path.join(wxDir, 'basis.js'), 'module.exports = () => {};');
writeFileSync(path.join(wxDir, 'basis.wasm'), 'wasmbytes');
const outKtx = path.join(root, 'dist-wechat-ktx2');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-ktx2/ktx2.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: wxDir,
outDir: outKtx,
platform: 'wechat',
});
expect(res.ok).toBe(true);
expect(readFileSync(path.join(outKtx, 'game.js'), 'utf8')).toContain("\"basis\": asFactory(require('./wasm/basis.js'))");
expect(existsSync(path.join(outKtx, 'wasm', 'basis.wasm'))).toBe(true);
// WeChat's code-package suffix whitelist has no `ktx2` — the container is
// re-staged as .ktx2.bin (whitelisted), and the manifest tracks the rename
// while the logical identity stays on the source path.
const manifest = JSON.parse(readFileSync(path.join(outKtx, 'asset-manifest.json'), 'utf8'));
const ktxAsset = manifest.groups.main.assets['ffffffff-ffff-ffff-ffff-ffffffffffff'];
expect(ktxAsset.path).toMatch(/^assets\/[0-9a-f]{16}\.ktx2\.bin$/);
expect(existsSync(path.join(outKtx, ktxAsset.path))).toBe(true);
expect(readdirSync(path.join(outKtx, 'assets')).some((f) => f.endsWith('.ktx2'))).toBe(false);
const pcfg = JSON.parse(readFileSync(path.join(outKtx, 'project.config.json'), 'utf8'));
expect(pcfg.packOptions.include).toContainEqual({ type: 'suffix', value: '.bin' });
expect(pcfg.packOptions.include).not.toContainEqual({ type: 'suffix', value: '.ktx2' });
}, 60_000);
it('a .ktx2 texture without a wechat basis build fails the export', async () => {
const outNoBasis = path.join(root, 'dist-wechat-ktx2-missing');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-ktx2/ktx2.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'), // engine only — no basis
outDir: outNoBasis,
platform: 'wechat',
});
expect(res.ok).toBe(false);
expect(res.errors.some((e) => e.includes('basis-wechat'))).toBe(true);
}, 60_000);
it('re-exporting into a populated dir rematerializes wasm/, dropping a stale side module', async () => {
// A prior export shipped the Basis transcoder (KTX2 was on then), including
// a glue file an older pipeline emitted with un-down-leveled es2020 syntax —
// the mini-game packer compiles EVERY .js in the package, so a leftover
// `wasm/basis.js` with `?.` fails real-device compile. This project needs no
// basis (plain texture scene); the re-export must wipe wasm/ and repopulate
// it with exactly the engine glue, so the stale module cannot ride along.
const outStale = path.join(root, 'dist-wechat-stale');
mkdirSync(path.join(outStale, 'wasm'), { recursive: true });
writeFileSync(path.join(outStale, 'wasm', 'basis.js'), 'var s = globalThis.document?.currentScript?.src;');
writeFileSync(path.join(outStale, 'wasm', 'basis.wasm'), 'stalebytes');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outStale,
platform: 'wechat',
});
expect(res.ok).toBe(true);
expect(existsSync(path.join(outStale, 'wasm', 'esengine.js'))).toBe(true);
expect(existsSync(path.join(outStale, 'wasm', 'basis.js'))).toBe(false);
expect(existsSync(path.join(outStale, 'wasm', 'basis.wasm'))).toBe(false);
}, 60_000);
it('content-addressed export carries the logical path as the asset address', async () => {
const outCa = path.join(root, 'dist-wechat-ca');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outCa,
title: 'My Game',
platform: 'wechat',
contentAddressed: true,
});
expect(res.ok).toBe(true);
const manifest = JSON.parse(readFileSync(path.join(outCa, 'asset-manifest.json'), 'utf8'));
const tex = manifest.groups.main.assets[TEX];
// Physical file renamed; the logical identity rides as the address —
// the runtime's ManifestModel + catalog resolve path refs through it.
expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
expect(tex.address).toBe('assets/hero.png');
// The scene restaged to scenes/<name>.json keeps its logical path as the
// address, so scene refs resolve to the WeChat-readable file.
expect(manifest.groups.main.assets[SCN].path).toBe('scenes/main.json');
expect(manifest.groups.main.assets[SCN].address).toBe('scenes/main.esscene');
}, 60_000);
it('ships every scene in the scenes dir as a switchable SceneManager target', async () => {
const LV2TEX = '99999999-9999-9999-9999-999999999999';
const LV2SCN = '88888888-8888-8888-8888-888888888888';
mkdirSync(path.join(root, 'scenes-multi'), { recursive: true });
writeFileSync(
path.join(root, 'scenes-multi', 'main.esscene'),
JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes-multi', 'main.esscene.meta'), meta('12121212-1212-1212-1212-121212121212', 'scene'));
writeFileSync(path.join(root, 'assets', 'lv2.png'), 'PNG3DATA');
writeFileSync(path.join(root, 'assets', 'lv2.png.meta'), meta(LV2TEX, 'texture'));
writeFileSync(
path.join(root, 'scenes-multi', 'level2.esscene'),
JSON.stringify({ version: '1.0', name: 'Level2', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${LV2TEX}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes-multi', 'level2.esscene.meta'), meta(LV2SCN, 'scene'));
const outMulti = path.join(root, 'dist-wechat-multi');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-multi/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: outMulti,
platform: 'wechat',
});
expect(res.ok).toBe(true);
// Both scenes transformed; the staged .esscene sources (not in WeChat's
// suffix whitelist) are gone, their manifest entries following the move.
expect(existsSync(path.join(outMulti, 'scenes', 'main.json'))).toBe(true);
expect(existsSync(path.join(outMulti, 'scenes', 'level2.json'))).toBe(true);
expect(existsSync(path.join(outMulti, 'scenes-multi', 'main.esscene'))).toBe(false);
expect(existsSync(path.join(outMulti, 'scenes-multi', 'level2.esscene'))).toBe(false);
const manifest = JSON.parse(readFileSync(path.join(outMulti, 'asset-manifest.json'), 'utf8'));
expect(manifest.groups.main.assets[LV2SCN].path).toBe('scenes/level2.json');
// The second scene is a cook root: its assets ship even though the entry
// scene never references them.
expect(manifest.groups.main.assets[LV2TEX].path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
// Boot registers every scene, booting into the entry.
const bundle = readFileSync(path.join(outMulti, 'game-bundle.js'), 'utf8');
expect(bundle).toContain('"main"');
expect(bundle).toContain('"level2"');
expect(bundle).toContain('firstScene: "main"');
// No .esscene rides in packOptions — nothing ships under that suffix.
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({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: o,
platform: 'wechat',
miniGameAppid: '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);
// The side modules are the other half of the main package: basis alone is
// 1.1MB raw, 27% of the 4MB cap. They compress on the same switch, and the
// loader is TOLD the suffix rather than spelling `.wasm` itself.
it('compresses a side module too, and declares the suffix the loader must use', async () => {
const wxDir = path.join(root, '_wxwasm-spine');
const o = path.join(root, 'dist-wx-br-side');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes-spine/spine.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: wxDir,
outDir: o,
platform: 'wechat',
compressWasm: true,
runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
});
expect(res.ok, res.errors.join('\n')).toBe(true);
expect(existsSync(path.join(o, 'wasm', 'spine42.wasm.br'))).toBe(true);
expect(existsSync(path.join(o, 'wasm', 'spine42.wasm'))).toBe(false);
// The glue stays raw — a vendor's brotli path takes wasm, not `.js` — and
// the entry still requires it by that name.
expect(existsSync(path.join(o, 'wasm', 'spine42.js'))).toBe(true);
expect(readFileSync(path.join(o, 'game.js'), 'utf8')).toContain("require('./wasm/spine42.js')");
// The half a second derivation would get wrong in silence: nothing in the
// runtime knows the suffix unless the package says so.
expect(readFileSync(path.join(o, 'game-bundle.js'), 'utf8')).toContain('sideModuleSuffix');
}, 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({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: o,
platform: 'wechat',
miniGameAppid: '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);
// The GLX engine is a separate build beside the plain one; a project that asks
// for it must ship THAT binary, and one that has not built it must hear how.
it('ships the EmscriptenGLX engine from the -glx runtime when the project asks for it', async () => {
const base = path.join(root, '_wxwasm-g');
for (const [dir, bytes] of [[base, 'plainbytes'], [`${base}-glx`, 'glxbytes']] as const) {
mkdirSync(dir, { recursive: true });
writeFileSync(path.join(dir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(dir, 'esengine.wasm'), bytes);
}
const o = path.join(root, 'dist-wx-glx');
const exportWith = (wasmDir: string) => exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir,
outDir: o,
platform: 'wechat',
miniGameAppid: 'wxTEST0123456789',
miniGameGlx: true,
runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
});
const res = await exportWith(base);
expect(res.ok).toBe(true);
expect(readFileSync(path.join(o, 'wasm', 'esengine.wasm'), 'utf8')).toBe('glxbytes');
const missing = await exportWith(path.join(root, '_wxwasm'));
expect(missing.ok).toBe(false);
expect(missing.errors.join('\n')).toContain('build -t wechat-glx');
}, 60_000);
// The lite engine is the plain one without particles, post-processing and tilemaps, and it is only right for content
// that reaches none of them — by a component in a scene or by a word in a script.
it('ships the lite engine only when nothing in the content or the scripts reaches what it leaves out', async () => {
const base = path.join(root, '_wxwasm-l');
for (const [dir, bytes] of [[base, 'plainbytes'], [`${base}-lite`, 'litebytes']] as const) {
mkdirSync(dir, { recursive: true });
writeFileSync(path.join(dir, 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(dir, 'esengine.wasm'), bytes);
}
const scene = path.join(root, 'scenes', 'main.esscene');
const script = path.join(root, 'src', 'main.ts');
const sceneText = readFileSync(scene, 'utf8');
const scriptText = readFileSync(script, 'utf8');
const shipped = async (name: string): Promise<string> => {
const o = path.join(root, name);
const res = await exportGame({
minifyScripts: false,
root, entryScene: 'scenes/main.esscene', hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts', sdkDistDir: path.join(root, '_sdk'), wasmDir: base, outDir: o,
platform: 'wechat', miniGameAppid: 'wxTEST0123456789',
runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
});
expect(res.ok).toBe(true);
return readFileSync(path.join(o, 'wasm', 'esengine.wasm'), 'utf8');
};
try {
expect(await shipped('dist-wx-lite-a')).toBe('litebytes');
const withEmitter = JSON.parse(sceneText);
withEmitter.entities.push({ id: 1, components: [{ type: 'ParticleEmitter', data: {} }] });
writeFileSync(scene, JSON.stringify(withEmitter));
expect(await shipped('dist-wx-lite-b')).toBe('plainbytes');
writeFileSync(scene, sceneText);
writeFileSync(script, `${scriptText}
// builds a PostProcessVolume at run time
`);
expect(await shipped('dist-wx-lite-c')).toBe('plainbytes');
} finally {
writeFileSync(scene, sceneText);
writeFileSync(script, scriptText);
}
}, 120_000);
// Moving the binary out of the 4MB main package means four things must agree:
// where it lands, what the loader is told, what game.json declares, and that
// the entry asks the host for the 分包 before the engine is instantiated.
it('moves the engine binary into a 分包 the entry loads before booting', async () => {
const o = path.join(root, 'dist-wx-subpkg');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: o,
platform: 'wechat',
miniGameAppid: 'wxTEST0123456789',
engineSubpackage: true,
runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
});
expect(res.ok).toBe(true);
// 1. It landed in the 分包, and NOT in the main package's wasm/.
expect(existsSync(path.join(o, 'subpackages', 'engine', 'esengine.wasm'))).toBe(true);
expect(existsSync(path.join(o, 'wasm', 'esengine.wasm'))).toBe(false);
// The glue stays put: the entry `require`s it, and a 分包 is not requirable
// until the host has loaded it.
expect(existsSync(path.join(o, 'wasm', 'esengine.js'))).toBe(true);
// 2. The loader is told where it actually is.
expect(readFileSync(path.join(o, 'game-bundle.js'), 'utf8'))
.toContain('subpackages/engine/esengine.wasm');
// 3. game.json declares it, or the host refuses the root at load.
const cfg = JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')) as
{ subPackages?: Array<{ name: string; root: string }> };
expect(cfg.subPackages ?? []).toContainEqual({ name: 'engine', root: 'subpackages/engine' });
// WeChat refuses a 分包 root with no game.js.
expect(existsSync(path.join(o, 'subpackages', 'engine', 'game.js'))).toBe(true);
// 4. The entry asks for it BEFORE it boots — the binary is not in the package
// until the host has loaded the 分包.
const entry = readFileSync(path.join(o, 'game.js'), 'utf8');
// The vendor's own host, bound once: `tt` answers the same shape and the
// entry is generated from the profile, not written per vendor.
expect(entry).toContain('= wx;');
expect(entry).toContain('loadSubpackage');
expect(entry.indexOf('loadSubpackage')).toBeLessThan(entry.indexOf('bundle.boot'));
// And a failure says so rather than leaving a blank canvas.
expect(entry).toContain('did not load');
// 5. The player is told something is happening. This fetch runs BEFORE the
// bundle is parsed, so the runtime's own indicator cannot cover it, and
// it is the one part of a cold start with real byte progress.
expect(entry.indexOf('showLoading')).toBeLessThan(entry.indexOf('loadSubpackage'));
expect(entry).toContain('onProgressUpdate');
// 6. …and the notice is never what kills the boot. MiniGameGlobal declares
// showLoading OPTIONAL, and this is the entry's FIRST line: an unguarded
// call is a package that dies for the sake of a progress message.
for (const call of ['showLoading', 'hideLoading']) {
for (const at of [...entry.matchAll(new RegExp(`\\.${call}\\(`, 'g'))].map((m) => m.index!)) {
const before = entry.slice(Math.max(0, at - 90), at);
expect(before, `${call}() at ${at} is called without checking the host has it`)
.toMatch(new RegExp(`${call}\\s*&&`));
}
}
}, 60_000);
it('leaves the engine in the main package when the project did not ask', async () => {
const o = path.join(root, 'dist-wx-nosubpkg');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: o,
platform: 'wechat',
miniGameAppid: '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, 'subpackages', 'engine'))).toBe(false);
expect(readFileSync(path.join(o, 'game.js'), 'utf8')).not.toContain('loadSubpackage');
}, 60_000);
// WeChat publishes the suffixes its packer will UPLOAD. A file outside that
// list is readable in devtools and refused at upload — so a package can build
// clean, run in the simulator and fail at the one step nobody automates.
it('stages nothing the packer would refuse to upload', async () => {
const o = path.join(root, 'dist-wx-suffixes');
const res = await exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
scriptsEntry: 'src/main.ts',
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: o,
platform: 'wechat',
miniGameAppid: 'wxTEST0123456789',
runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
});
expect(res.ok).toBe(true);
// developers.weixin.qq.com/minigame/dev/guide/base-ability/code-package.html
const whitelist = new Set(`png jpg jpeg gif svg js json cer obj dae fbx mtl stl 3ds mp3 pvr
wav plist ttf fnt gz ccz m4a mp4 bmp atlas swf ani part proto bin sk mipmaps txt zip tt map
ogg silk dbbin dbmv etc lmat lm ls lh lani lav lsani ltc aac astc br csv cur dat dds glb
gltf ico ktx lmani lml pkm prefab scene wasm xml`.split(/\s+/).filter(Boolean));
const walk = (dir: string, out: string[] = []): string[] => {
for (const e of readdirSync(dir)) {
const p = path.join(dir, e);
if (statSync(p).isDirectory()) walk(p, out);
else out.push(p);
}
return out;
};
const refused = walk(o)
.map((f) => path.relative(o, f))
.filter((f) => {
const ext = path.extname(f).slice(1).toLowerCase();
return ext !== '' && !whitelist.has(ext);
});
expect(refused, `these would be refused at upload: ${refused.join(', ')}`).toEqual([]);
}, 60_000);
});
/**
* The open data context — a SECOND bundle for a second JS runtime, which is the
* only place a player's friends can be read. Its own project roots: the presence
* of an `open-data/` directory changes the emitted config, so a case that adds
* one must not be able to leak into a case that asserts its absence.
*/
describe('exportGame (wechat) — open data context', () => {
const roots: string[] = [];
/** A minimal exportable project: one scene, one texture, stub SDK + runtime. */
function scaffold(openDataSource?: string): { root: string; out: string } {
const dir = mkdtempSync(path.join(tmpdir(), 'estella-export-opendata-'));
roots.push(dir);
mkdirSync(path.join(dir, 'assets'), { recursive: true });
writeFileSync(path.join(dir, 'assets', 'hero.png'), 'PNGDATA');
writeFileSync(path.join(dir, 'assets', 'hero.png.meta'), meta(TEX, 'texture'));
mkdirSync(path.join(dir, 'scenes'), { recursive: true });
writeFileSync(
path.join(dir, 'scenes', 'main.esscene'),
JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
);
writeFileSync(path.join(dir, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
mkdirSync(path.join(dir, '_sdk'), { recursive: true });
writeFileSync(path.join(dir, '_sdk', 'index.wechat.js'), miniGameSdkStub(wechatExportProfile));
mkdirSync(path.join(dir, '_wxwasm'), { recursive: true });
writeFileSync(path.join(dir, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(dir, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
if (openDataSource !== undefined) {
mkdirSync(path.join(dir, 'open-data'), { recursive: true });
writeFileSync(path.join(dir, 'open-data', 'index.ts'), openDataSource);
}
return { root: dir, out: path.join(dir, 'dist-wechat') };
}
const exportIt = (root: string, out: string) => exportGame({
minifyScripts: false,
root,
entryScene: 'scenes/main.esscene',
hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
sdkDistDir: path.join(root, '_sdk'),
wasmDir: path.join(root, '_wxwasm'),
outDir: out,
platform: 'wechat',
});
afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });
it('a project without one declares no context — an absent directory would fail the host compile', async () => {
const { root: r, out: o } = scaffold();
const res = await exportIt(r, o);
expect(res.ok).toBe(true);
expect(existsSync(path.join(o, 'open-data'))).toBe(false);
expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8'))).not.toHaveProperty('openDataContext');
}, 60_000);
it('a project with one is bundled beside the game and named in game.json', async () => {
const { root: r, out: o } = scaffold(
'const draw = (n?: { rows?: string[] }) => n?.rows?.length ?? 0;\n'
+ 'wx.onMessage((m: { rows?: string[] }) => { draw(m); });\n'
+ 'declare const wx: { onMessage(cb: (m: unknown) => void): void };\n',
);
const res = await exportIt(r, o);
expect(res.ok).toBe(true);
const bundled = path.join(o, 'open-data', 'index.js');
expect(existsSync(bundled)).toBe(true);
expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')).openDataContext).toBe('open-data');
// Down-levelled to the vendor's syntax floor like every other .js in the
// package: the host compiles this file too, and real-device WeChat rejects
// the optional chaining the source is written with.
const code = readFileSync(bundled, 'utf8');
expect(code).not.toContain('?.');
}, 60_000);
it('a package can be the context, through the one line the project writes', async () => {
// Which is how a friends board ships without the engine carrying one: the
// project owns the file, a dependency owns the code, and the bundler
// resolves it like any other import.
const { root: r, out: o } = scaffold("import 'estella-plugin-fake/open-data';\n");
const pkg = path.join(r, 'node_modules', 'estella-plugin-fake');
mkdirSync(pkg, { recursive: true });
writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({
name: 'estella-plugin-fake', version: '1.0.0', exports: { './open-data': './od.js' },
}));
writeFileSync(path.join(pkg, 'od.js'), 'globalThis.__PACKAGE_BOARD__ = 1;\n');
const res = await exportIt(r, o);
expect(res.ok).toBe(true);
expect(readFileSync(path.join(o, 'open-data', 'index.js'), 'utf8')).toContain('__PACKAGE_BOARD__');
expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8')).openDataContext).toBe('open-data');
}, 60_000);
it('a context that imports the engine fails the export, not the device', async () => {
const { root: r, out: o } = scaffold("import { Assets } from 'esengine';\nAssets.toString();\n");
const res = await exportIt(r, o);
expect(res.ok).toBe(false);
expect(res.errors.join('\n')).toMatch(/esengine/);
// And a failed context leaves the config pointing at nothing.
expect(JSON.parse(readFileSync(path.join(o, 'game.json'), 'utf8'))).not.toHaveProperty('openDataContext');
}, 60_000);
});
/**
* Assets share a staged file freely: every sprite packed into an atlas names the
* same page, and content addressing hands identical bytes one name. The packer
* rename walked manifest ENTRIES, so the first moved the file and the rest died
* on a path that was no longer there — which is every atlased 2D project.
*/
describe('two assets, one staged file', () => {
const roots: string[] = [];
afterAll(() => {
for (const r of roots) rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
});
it('renames it once and points both entries at the new name', async () => {
const dir = mkdtempSync(path.join(tmpdir(), 'estella-export-shared-'));
roots.push(dir);
const A = '11111111-1111-1111-1111-111111111111';
const B = '22222222-2222-2222-2222-222222222222';
// `.eslocale` is not on WeChat's upload whitelist, and identical bytes under
// content addressing cook to one file — the shape an atlas page has.
mkdirSync(path.join(dir, 'assets', 'i18n'), { recursive: true });
for (const [name, uuid] of [['en', A], ['fr', B]] as const) {
writeFileSync(path.join(dir, 'assets', 'i18n', `${name}.eslocale`), JSON.stringify({ hello: 'hi' }));
writeFileSync(path.join(dir, 'assets', 'i18n', `${name}.eslocale.meta`), meta(uuid, 'locale'));
}
mkdirSync(path.join(dir, 'scenes'), { recursive: true });
writeFileSync(path.join(dir, 'scenes', 'main.esscene'), JSON.stringify({
version: '1.0', name: 'Main', entities: [{ id: 0, components: [] }],
}));
writeFileSync(path.join(dir, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
mkdirSync(path.join(dir, '_sdk'), { recursive: true });
writeFileSync(path.join(dir, '_sdk', 'index.wechat.js'), miniGameSdkStub(wechatExportProfile));
mkdirSync(path.join(dir, '_wxwasm'), { recursive: true });
writeFileSync(path.join(dir, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
writeFileSync(path.join(dir, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
const outDir = path.join(dir, 'dist-wechat');
const res = await exportGame({
minifyScripts: false,
root: dir, entryScene: 'scenes/main.esscene', hostsDir: 'unused-for-wechat', packagesDir: OFFICIAL_PACKAGES,
sdkDistDir: path.join(dir, '_sdk'), wasmDir: path.join(dir, '_wxwasm'),
outDir, platform: 'wechat', contentAddressed: true,
});
expect(res.errors.join('\n')).not.toMatch(/ENOENT/);
expect(res.ok).toBe(true);
const manifest = JSON.parse(readFileSync(path.join(outDir, 'asset-manifest.json'), 'utf8'));
const paths = Object.values(manifest.groups as Record<string, { assets: Record<string, { path: string }> }>)
.flatMap((g) => Object.values(g.assets).map((a) => a.path))
.filter((p) => p.includes('.eslocale'));
expect(paths.length).toBe(2);
expect(new Set(paths).size).toBe(1);
for (const p of paths) {
expect(p.endsWith('.bin')).toBe(true);
expect(existsSync(path.join(outDir, p))).toBe(true);
}
}, 60_000);
});