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.

fix(export): a WeChat 分包 root is a directory the package carries

esengineaa19548aa6b3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 649c76102..fec24cd9e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,17 @@ published separately; it ships inside the editor.
### Fixed
+- **A WeChat 分包 is a directory the package carries.** A folder marked *subpackage*
+ in the editor staged its assets where they were authored (`assets/level2/`), while
+ `game.json` declared the root `subpackages/level2` — a directory that was never
+ written. WeChat refuses the whole game for it: `["subPackages"][0]["root"] 不存在` (#58).
+
+ Delivery now decides the layout, so a lazy group's files land under its root whether
+ or not the build content-addresses names; and the `subPackages` list is read off the
+ STAGED paths, so a root the package lacks can no longer be declared. A member that
+ cannot travel in a subpackage — a scene, which every exporter addresses by its
+ logical path — is named in the build warnings instead of silently breaking the load.
+
- **A cooked mini-game plays its sound effects.** The cook re-encodes `tap.wav` to
`assets/<hash>.mp3`, and a mini-game player is handed a URL rather than bytes — but
the asset loader handed it the AUTHORED path, which is the cache key, not a file the
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index a5e86b257..5a5ee2698 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -129,12 +129,31 @@ export async function loadAssetGroups(root: string): Promise<AssetGroupsConfig |
}
}
+/**
+ * The directory a non-local group's files live under — `subpackages/<name>` for a
+ * lazy group, `remote/<name>` for a CDN one; null for the main package. A vendor
+ * MOUNTS this root (a WeChat 分包 names it in game.json), so delivery fixes it
+ * rather than the layout: a root the package lacks is refused with "root 不存在".
+ */
+export function groupRoot(name: string, delivery: GroupDelivery): string | null {
+ if (delivery === 'lazy') return `subpackages/${name}`;
+ if (delivery === 'remote') return `remote/${name}`;
+ return null;
+}
+
/** Content-addressed base dir for a group's delivery: main → `assets`,
* lazy → `subpackages/<name>/assets`, remote → `remote/<name>/assets`. */
function caBaseFor(name: string, delivery: GroupDelivery): string {
- if (delivery === 'lazy') return `subpackages/${name}/assets`;
- if (delivery === 'remote') return `remote/${name}/assets`;
- return 'assets';
+ const root = groupRoot(name, delivery);
+ return root ? `${root}/assets` : 'assets';
+}
+
+/** `rel` moved under its group's root when names are kept. A path already there —
+ * the `subpackages/<name>/` folder convention — is its own root and stays put. */
+function underGroupRoot(rel: string, name: string, delivery: GroupDelivery): string {
+ const root = groupRoot(name, delivery);
+ if (!root || rel === root || rel.startsWith(`${root}/`)) return rel;
+ return `${root}/${rel}`;
}
/** Targets the KTX2 the cook emits can transcode to at runtime (UASTC + ETC1S). */
@@ -540,7 +559,7 @@ export async function cookAssets(
const caBase = caBaseFor(group, delivery);
const pageOutRel = contentAddressed
? `${caBase}/${pageHash}${pageExt}`
- : `${dir}.page${n}${pageExt}`;
+ : underGroupRoot(`${dir}.page${n}${pageExt}`, group, delivery);
const dst = path.join(absOut, pageOutRel);
if (!staged.has(pageOutRel)) {
await mkdir(path.dirname(dst), { recursive: true });
@@ -751,9 +770,19 @@ export async function cookAssets(
// subpackage root (subpackages/<name>/…) so the root maps to a WeChat
// subPackage — including the content-addressed layout (root/assets/<hash>).
const { name: group, delivery } = resolveAssetGroup(entry.path, groupsConfig);
+ // Scenes keep their logical path in every layout — they are loaded by name
+ // and the exporters transform them in place, addressed by it — so a scene
+ // cannot travel inside a group root, and says so instead.
const useCA = contentAddressed && entry.type !== 'scene';
const caBase = caBaseFor(group, delivery);
- const outRel = useCA ? `${caBase}/${hash}${ext}` : swapExt(entry.path, ext);
+ const outRel = entry.type === 'scene'
+ ? swapExt(entry.path, ext)
+ : useCA
+ ? `${caBase}/${hash}${ext}`
+ : underGroupRoot(swapExt(entry.path, ext), group, delivery);
+ if (entry.type === 'scene' && groupRoot(group, delivery)) {
+ warnings.push(`${entry.path}: a scene ships in the main package — group '${group}' cannot carry it`);
+ }
const dst = path.join(absOut, outRel);
if (!staged.has(outRel)) {
await mkdir(path.dirname(dst), { recursive: true });
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index 307f051be..93c1d9456 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -335,8 +335,12 @@ export interface ExportGameOptions {
sdkDistDir: string;
wasmDir: string;
outDir: string;
- /** Content-addressed asset filenames (<hash><ext>) — dedup + immutable/CDN caching.
- * Default ON (the modern-bundler standard); set false to keep logical paths. */
+ /**
+ * Content-addressed asset filenames (<hash><ext>) — dedup + immutable/CDN caching.
+ * Default ON for web / desktop / native; the mini-game route keeps logical paths,
+ * where there is no CDN cache to earn an immutable name and the vendor's packer
+ * whitelists by suffix. Explicit `false`/`true` overrides either.
+ */
contentAddressed?: boolean;
/** Encode raster textures to GPU-compressed KTX2 at cook time. Default off
* (lossy + encode-time cost — opt in per project). */
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index 4bf699168..e83f68c3c 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -80,13 +80,28 @@ function stripUuidRefs(v: unknown): unknown {
return v;
}
-/** Distinct lazy subpackage groups present in the cook, as vendor subPackage roots. */
-function subPackagesOf(entries: CookManifest['entries'], subpackageDir: string): Array<{ name: string; root: string }> {
- const names = new Set<string>();
- // Remote (CDN / hot-update) groups are NOT WeChat 分包 — they're fetched from a
- // remote origin, not packed as a subPackage root.
- for (const e of entries) if (e.group && e.group !== 'main' && e.groupMode !== 'remote') names.add(e.group);
- return [...names].map((name) => ({ name, root: `${subpackageDir}/${name}` }));
+/**
+ * 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 不存在"),
+ * so the declaration comes from the files rather than from the group names beside
+ * them. Remote (CDN / hot-update) groups are not 分包 and are skipped.
+ */
+function subPackagesOf(
+ entries: CookManifest['entries'],
+ subpackageDir: string,
+): { subPackages: Array<{ name: string; root: string }>; strays: string[] } {
+ const carried = new Set<string>();
+ const strays: string[] = [];
+ for (const e of entries) {
+ if (!e.group || e.group === 'main' || e.groupMode === 'remote') continue;
+ const root = `${subpackageDir}/${e.group}`;
+ if (e.path === root || e.path.startsWith(`${root}/`)) carried.add(e.group);
+ else strays.push(`${e.sourcePath} is in 分包 '${e.group}' but ships at ${e.path}, outside ${root}/`);
+ }
+ return {
+ subPackages: [...carried].map((name) => ({ name, root: `${subpackageDir}/${name}` })),
+ strays,
+ };
}
/** packOptions.include suffix rules for every custom extension the cook staged.
@@ -413,12 +428,14 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
}
// 5. Entry + config (vendor-specific emission).
+ const subPackages = subPackagesOf(cookEntries, profile.subpackageDir);
+ warnings.push(...subPackages.strays);
await writeFile(path.join(absOut, 'game.js'), profile.emitEntry({ sideModules, engineGlueFile }));
const configFiles = profile.emitConfigFiles({
title,
appid: opts.appid ?? '',
orientation: opts.orientation ?? 'portrait',
- subPackages: subPackagesOf(cookEntries, profile.subpackageDir),
+ subPackages: subPackages.subPackages,
includeSuffixes: packIncludeSuffixes(cookEntries, profile.nativeSuffixes),
// Only a bundle that was actually written counts: an entry that failed to
// build must not leave the config pointing at a directory with no index.js.
diff --git a/pipeline/tests/export-wechat-subpackage.test.ts b/pipeline/tests/export-wechat-subpackage.test.ts
new file mode 100644
index 000000000..8c6febfd7
--- /dev/null
+++ b/pipeline/tests/export-wechat-subpackage.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file WeChat 分包 — a `subPackages` root the package does not carry is a hard
+ * devtools failure ("root 不存在"), so the declaration and the staging
+ * must come from one decision. The group here is authored through
+ * `.esengine/asset-groups.json` on an ordinary `assets/` folder, which is
+ * how the editor's Delivery menu writes it — the legacy
+ * `subpackages/<name>/` folder convention hides the bug by naming the
+ * staged path after the root it needs.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { runtimeConfigOf } from '../src/project/runtimeConfig';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, readdirSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { exportGame } from '../src/export/exportGame';
+
+let root: string;
+let out: string;
+const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const LAZY = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-wechat-subpkg-'));
+ 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'));
+ // The user's folder: made in assets/, then marked 分包 in the editor.
+ mkdirSync(path.join(root, 'assets', 'level2'), { recursive: true });
+ writeFileSync(path.join(root, 'assets', 'level2', 'extra.png'), 'PNG2DATA');
+ writeFileSync(path.join(root, 'assets', 'level2', 'extra.png.meta'), meta(LAZY, 'texture'));
+ mkdirSync(path.join(root, '.esengine'), { recursive: true });
+ writeFileSync(
+ path.join(root, '.esengine', 'asset-groups.json'),
+ JSON.stringify({ version: '1.0', groups: { level2: { folder: 'assets/level2', mode: 'subpackage' } } }),
+ );
+ 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`);
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.wechat.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, maxRetries: 10, retryDelay: 50 }));
+
+describe('WeChat 分包 declared through asset-groups.json', () => {
+ it('stages every declared subPackage root', async () => {
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: out,
+ title: 'My Game',
+ platform: 'wechat',
+ wechatAppid: 'wxTEST0123456789',
+ orientation: 'landscape',
+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
+ });
+ expect(res.ok).toBe(true);
+
+ const gjson = JSON.parse(readFileSync(path.join(out, 'game.json'), 'utf8'));
+ expect(gjson.subPackages).toContainEqual({ name: 'level2', root: 'subpackages/level2' });
+
+ // WeChat rejects a root the package does not carry, and an EMPTY directory
+ // does not survive packing — the root must hold the group's files.
+ for (const sp of gjson.subPackages as Array<{ root: string }>) {
+ const dir = path.join(out, sp.root);
+ expect(existsSync(dir), `${sp.root} missing from the package`).toBe(true);
+ expect(readdirSync(dir, { recursive: true }).length, `${sp.root} is empty`).toBeGreaterThan(0);
+ }
+ }, 120_000);
+
+ it('never declares a root nothing was staged under', async () => {
+ // A scene keeps its logical path in every layout, so a group made of one
+ // cannot be delivered — the declaration must follow the files, not the group.
+ const root2 = mkdtempSync(path.join(tmpdir(), 'estella-wechat-subpkg-scene-'));
+ try {
+ mkdirSync(path.join(root2, 'scenes', 'levels'), { recursive: true });
+ writeFileSync(
+ path.join(root2, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [] }),
+ );
+ writeFileSync(path.join(root2, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ writeFileSync(
+ path.join(root2, 'scenes', 'levels', 'two.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Two', entities: [] }),
+ );
+ writeFileSync(path.join(root2, 'scenes', 'levels', 'two.esscene.meta'), meta(LAZY, 'scene'));
+ mkdirSync(path.join(root2, '.esengine'), { recursive: true });
+ writeFileSync(
+ path.join(root2, '.esengine', 'asset-groups.json'),
+ JSON.stringify({
+ version: '1.0',
+ groups: { levels: { folder: 'scenes/levels', mode: 'subpackage', alwaysInclude: true } },
+ }),
+ );
+ mkdirSync(path.join(root2, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root2, '_sdk', 'index.wechat.js'), 'export function initWeChatRuntime(){return Promise.resolve();}\n');
+ mkdirSync(path.join(root2, '_wxwasm'), { recursive: true });
+ writeFileSync(path.join(root2, '_wxwasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(root2, '_wxwasm', 'esengine.wasm'), 'wasmbytes');
+ const out2 = path.join(root2, 'dist-wechat');
+
+ const res = await exportGame({
+ root: root2,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ sdkDistDir: path.join(root2, '_sdk'),
+ wasmDir: path.join(root2, '_wxwasm'),
+ outDir: out2,
+ title: 'Scene Group',
+ platform: 'wechat',
+ wechatAppid: 'wxTEST0123456789',
+ orientation: 'landscape',
+ runtime: runtimeConfigOf({ designResolution: { width: 1280, height: 720 } }),
+ });
+ expect(res.ok).toBe(true);
+
+ const gjson = JSON.parse(readFileSync(path.join(out2, 'game.json'), 'utf8'));
+ expect(gjson.subPackages ?? []).toEqual([]);
+ expect(res.warnings.join('\n')).toMatch(/levels/);
+ } finally {
+ rmSync(root2, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ }
+ }, 120_000);
+});