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(tests): the engine runs its own test suites

esengine1feb7efe69cc
diff --git a/desktop b/desktop
index 9dde2a5a4..f44e1b573 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 9dde2a5a4e99ee93835665efea6dcbea61914187
+Subproject commit f44e1b573a862a39c06f99a27aa7de18923cd4ad
diff --git a/native/README.md b/native/README.md
index 072b860d2..e29fe3c8e 100644
--- a/native/README.md
+++ b/native/README.md
@@ -377,4 +377,4 @@ plus physics / Spine / video, which ship as emscripten side modules with no nati
counterpart yet. An export names them: **Package Project → Mobile** warns about any of them
a scene uses rather than shipping a package that quietly renders half of it (the gaps are
declared in `desktop/src/project/targetSupport.ts`, checked against this CMakeLists by
-`desktop/tests/target-support.test.ts`).
+`pipeline/tests/target-support.test.ts`).
diff --git a/package.json b/package.json
index 93bf7a8f5..fffc5cccd 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,8 @@
"torture": "pnpm --filter ./sdk exec vitest run tests/torture",
"gate": "node tools/check-release-gate.mjs --report",
"render-host": "node tools/render-host/build.mjs",
- "verify:render": "node tools/verify-render.mjs"
+ "verify:render": "node tools/verify-render.mjs",
+ "test": "vitest run --config vitest.engine.config.ts"
},
"dependencies": {
"chalk": "^5.3.0",
@@ -47,6 +48,7 @@
"devDependencies": {
"electron": "^42.4.1",
"esbuild": "^0.27.0",
- "madge": "^8.0.0"
+ "madge": "^8.0.0",
+ "vitest": "^2.1.9"
}
}
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index f48c77dfa..2f02f4cb4 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -16,7 +16,7 @@
*
* Without this, an export writes a package that is quietly missing half a
* scene. This is the one declaration of that gap, so the export can name it
- * instead. `desktop/tests/target-support.test.ts` reads the native CMakeLists
+ * instead. `pipeline/tests/target-support.test.ts` reads the native CMakeLists
* and fails when the two drift: flipping a flag there is what deletes an entry
* here.
*
@@ -79,7 +79,7 @@ export interface SubsystemGap {
/** What the native app cannot render — currently nothing. ONE list: iOS and Android
* compile the same `native/CMakeLists.txt`, so a flag flipped there opens or closes
- * the gap on both. `desktop/tests/target-support.test.ts` reads that file and fails
+ * the gap on both. `pipeline/tests/target-support.test.ts` reads that file and fails
* when the two disagree. */
const NATIVE_GAPS: readonly SubsystemGap[] = [];
diff --git a/pipeline/tests/addressable-manifest.test.ts b/pipeline/tests/addressable-manifest.test.ts
new file mode 100644
index 000000000..2b4dd9b92
--- /dev/null
+++ b/pipeline/tests/addressable-manifest.test.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The ship manifest is a packaged build's ONLY channel for the `.meta`.
+ *
+ * The cook records each asset's importer block, but assembling the addressable
+ * manifest used to drop it — so a shipped game had no filter/wrap/sRGB and no
+ * 9-slice border, and a frame that sliced correctly in the editor stretched in
+ * the build. What ships is the PARSED runtime half: the renderer needs how the
+ * texture is sampled, never the cook's own knobs.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { buildAddressableManifest } from '../src/assets/addressableManifest';
+import type { AddressableManifest } from '../../sdk/src/asset/AddressableManifest';
+
+const SLICED = {
+ uuid: 'A0C281AF-F1E6-43F1-9561-834D9AFB25B5',
+ path: 'assets/ui/Button_Red.png',
+ type: 'texture',
+ size: 100,
+ importer: {
+ maxSize: 2048, compress: true, compressFormat: 'uastc',
+ filterMode: 'linear', wrapMode: 'clamp', sRGB: true,
+ sliceBorder: { left: 23, right: 24, top: 25, bottom: 29 },
+ },
+};
+const PLAIN = {
+ uuid: 'B0000000-0000-4000-8000-000000000000',
+ path: 'assets/ui/Background.png',
+ type: 'texture',
+ size: 100,
+ // Cook-only knobs plus an all-zero border: nothing the renderer acts on.
+ importer: {
+ maxSize: 2048, compress: true, compressFormat: 'uastc',
+ sliceBorder: { left: 0, right: 0, top: 0, bottom: 0 },
+ },
+};
+
+describe('buildAddressableManifest — texture import settings', () => {
+ let dir: string;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'estella-manifest-'));
+ });
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ const build = async (entries: unknown[]): Promise<AddressableManifest> => {
+ await writeFile(path.join(dir, 'assets.manifest.json'), JSON.stringify({ entries }));
+ return JSON.parse(await buildAddressableManifest(dir)) as AddressableManifest;
+ };
+
+ it('ships the parsed settings, not the raw importer block', async () => {
+ const manifest = await build([SLICED]);
+ const asset = manifest.groups.main.assets[SLICED.uuid.toLowerCase()];
+
+ expect(asset.textureImport).toEqual({
+ filter: 'linear', wrap: 'clamp', srgb: true,
+ sliceBorder: { left: 23, right: 24, top: 25, bottom: 29 },
+ });
+ // The cook's own settings stay behind — they mean nothing to a renderer.
+ expect(JSON.stringify(asset)).not.toContain('maxSize');
+ expect(JSON.stringify(asset)).not.toContain('compressFormat');
+ });
+
+ it('omits the field for an asset whose importer says nothing renderable', async () => {
+ const manifest = await build([PLAIN]);
+ const asset = manifest.groups.main.assets[PLAIN.uuid.toLowerCase()];
+
+ expect(asset.textureImport).toBeUndefined();
+ });
+
+ it('is answerable by every ref spelling once the runtime indexes it', async () => {
+ const manifest = await build([{ ...SLICED, sourcePath: 'assets/ui/Button_Red.png', path: 'ca/9f3a1b.png' }]);
+ const { ManifestModel } = await import('../../sdk/src/asset/AddressableManifest');
+ const lookup = ManifestModel.fromJson(manifest).textureImportLookup();
+
+ // The uuid, the staged path a content-addressed cook renamed it to, and the
+ // authored address a path-style ref still names it by.
+ for (const ref of [
+ SLICED.uuid.toLowerCase(), `@uuid:${SLICED.uuid.toLowerCase()}`,
+ 'ca/9f3a1b.png', 'assets/ui/Button_Red.png', '/assets/ui/Button_Red.png',
+ ]) {
+ expect(lookup(ref)?.sliceBorder, ref).toEqual({ left: 23, right: 24, top: 25, bottom: 29 });
+ }
+ });
+});
diff --git a/pipeline/tests/asset-db-incremental.test.ts b/pipeline/tests/asset-db-incremental.test.ts
new file mode 100644
index 000000000..905c48af4
--- /dev/null
+++ b/pipeline/tests/asset-db-incremental.test.ts
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Incremental asset-index update (Task 1). The watcher delivers precise
+ * changed paths, so a disk touch folds into the cached index per-path
+ * instead of re-walking the whole tree. The correctness bar: the
+ * incremental result must be IDENTICAL to a full rescan of the same on-disk
+ * state — same `entries`, same dependency graph — so Find Usages, delete
+ * warnings and the cook can't disagree with what actually changed. Plus the
+ * explicit fallback cases (overflow / bulk / directory move → full rescan).
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase, updateAssetIndex, INCREMENTAL_PATH_LIMIT } from '../src/assets/assetDb';
+
+let root: string;
+
+const TEX = '11111111-1111-4111-8111-111111111111';
+const TEX2 = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const FONT = '22222222-2222-4222-8222-222222222222';
+const MAT = '44444444-4444-4444-8444-444444444444';
+const SCENE = '33333333-3333-4333-8333-333333333333';
+
+function writeAsset(rel: string, type: string, uuid: string, body = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+function sceneBody(refs: { texture?: string; font?: string }): string {
+ return JSON.stringify({
+ version: '1.0',
+ name: 'main',
+ entities: [
+ {
+ id: 1, name: 'Hero', parent: null, children: [],
+ components: [
+ ...(refs.texture ? [{ type: 'Sprite', data: { texture: `@uuid:${refs.texture}` } }] : []),
+ ...(refs.font ? [{ type: 'BitmapText', data: { font: `@uuid:${refs.font}` } }] : []),
+ ],
+ },
+ ],
+ });
+}
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-inc-'));
+ writeAsset('assets/textures/player.png', 'texture', TEX, 'PNGDATA');
+ writeAsset('assets/fonts/ui.fnt', 'font', FONT, 'FNTDATA');
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, sceneBody({ texture: TEX, font: FONT }));
+});
+
+afterEach(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+/** Assert an incremental update equals a full rescan of the same on-disk state. */
+async function expectIncrementalEqualsFull(prev: Awaited<ReturnType<typeof scanAssetDatabase>>['index'], changed: string[]): Promise<void> {
+ const inc = await updateAssetIndex(root, prev, changed, { write: false });
+ const full = await scanAssetDatabase(root, { write: false, adopt: false });
+ expect(inc.fullRescan).toBe(false);
+ expect(inc.index.entries).toEqual(full.index.entries);
+ expect(inc.index.deps).toEqual(full.index.deps);
+}
+
+describe('updateAssetIndex — incremental == full rescan', () => {
+ it('a content edit that DROPS a scene ref removes just that dependency edge', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ expect(prev.deps[SCENE]).toEqual([FONT, TEX].sort());
+
+ writeFileSync(path.join(root, 'assets/scenes/main.esscene'), sceneBody({ texture: TEX })); // font ref gone
+ await expectIncrementalEqualsFull(prev, ['assets/scenes/main.esscene']);
+
+ // And concretely: the edge to the font is gone, the texture edge stays.
+ const inc = await updateAssetIndex(root, prev, ['assets/scenes/main.esscene'], { write: false });
+ expect(inc.index.deps[SCENE]).toEqual([TEX]);
+ });
+
+ it('a .meta-only touch (paired to its content path) refreshes the entry', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ writeFileSync(
+ path.join(root, 'assets/textures/player.png.meta'),
+ JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: { filter: 'nearest' } }),
+ );
+ await expectIncrementalEqualsFull(prev, ['assets/textures/player.png.meta']);
+ const inc = await updateAssetIndex(root, prev, ['assets/textures/player.png.meta'], { write: false });
+ expect(inc.index.entries.find((e) => e.uuid === TEX)?.importer).toEqual({ filter: 'nearest' });
+ });
+
+ it('ADDING an asset + a ref to it updates entries AND the dep graph', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ writeAsset('assets/textures/enemy.png', 'texture', TEX2, 'PNG2');
+ writeFileSync(path.join(root, 'assets/scenes/main.esscene'), sceneBody({ texture: TEX2, font: FONT }));
+ await expectIncrementalEqualsFull(prev, ['assets/textures/enemy.png', 'assets/scenes/main.esscene']);
+ });
+
+ it('a PATH-ref that only resolves once its target is added (reverse-dep) matches full', async () => {
+ // A material references a sibling texture by relative path; the texture is
+ // added AFTER the material — the edge must appear once both exist, exactly as a
+ // full rescan resolves it.
+ writeAsset('assets/materials/m.esmaterial', 'material', MAT, JSON.stringify({ texture: 'wall.png' }));
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ expect(prev.deps[MAT]).toBeUndefined(); // wall.png doesn't exist yet → no edge
+
+ writeAsset('assets/materials/wall.png', 'texture', TEX2, 'WALL');
+ await expectIncrementalEqualsFull(prev, ['assets/materials/wall.png']);
+ const inc = await updateAssetIndex(root, prev, ['assets/materials/wall.png'], { write: false });
+ expect(inc.index.deps[MAT]).toEqual([TEX2]); // the referrer's edge now resolves
+ });
+
+ it('DELETING an asset drops its entry (dep edges from @uuid: referrers persist, as in full)', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ rmSync(path.join(root, 'assets/fonts/ui.fnt'));
+ rmSync(path.join(root, 'assets/fonts/ui.fnt.meta'));
+ await expectIncrementalEqualsFull(prev, ['assets/fonts/ui.fnt', 'assets/fonts/ui.fnt.meta']);
+ const inc = await updateAssetIndex(root, prev, ['assets/fonts/ui.fnt.meta'], { write: false });
+ expect(inc.index.entries.some((e) => e.uuid === FONT)).toBe(false);
+ });
+
+ // A removal doesn't recompute the whole graph any more — only the documents that
+ // referenced what left. A PATH-ref is the case that proves the set is right: it
+ // stops resolving when its target goes, so its referrer MUST be re-read (unlike
+ // an `@uuid:` one, which a full scan keeps dangling).
+ it('DELETING a path-ref target re-resolves its referrer, matching full', async () => {
+ writeAsset('assets/materials/wall.png', 'texture', TEX2, 'WALL');
+ writeAsset('assets/materials/m.esmaterial', 'material', MAT, JSON.stringify({ texture: 'wall.png' }));
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ expect(prev.deps[MAT]).toEqual([TEX2]);
+
+ rmSync(path.join(root, 'assets/materials/wall.png'));
+ rmSync(path.join(root, 'assets/materials/wall.png.meta'));
+ await expectIncrementalEqualsFull(prev, ['assets/materials/wall.png', 'assets/materials/wall.png.meta']);
+
+ const inc = await updateAssetIndex(root, prev, ['assets/materials/wall.png'], { write: false });
+ expect(inc.index.deps[MAT]).toBeUndefined(); // the edge is gone, not left dangling
+ });
+
+ it('DELETING a .meta while the content file stays re-adopts it, like a full scan', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ rmSync(path.join(root, 'assets/textures/player.png.meta')); // orphan the png
+ const inc = await updateAssetIndex(root, prev, ['assets/textures/player.png.meta'], { write: false });
+ // Re-adopted → still an entry (a fresh uuid, so not identity-comparable to full).
+ expect(inc.adopted).toEqual(['assets/textures/player.png']);
+ expect(inc.index.entries.some((e) => e.path === 'assets/textures/player.png')).toBe(true);
+ });
+});
+
+describe('updateAssetIndex — fallbacks (never silent)', () => {
+ it('an empty change set (watcher overflow) falls back to a full rescan', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ const inc = await updateAssetIndex(root, prev, [], { write: false });
+ expect(inc.fullRescan).toBe(true);
+ expect(inc.reason).toContain('overflow');
+ });
+
+ it('a bulk change above the limit falls back to a full rescan', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ const many = Array.from({ length: INCREMENTAL_PATH_LIMIT + 1 }, (_, i) => `assets/x${i}.png`);
+ const inc = await updateAssetIndex(root, prev, many, { write: false });
+ expect(inc.fullRescan).toBe(true);
+ expect(inc.reason).toContain('bulk');
+ });
+
+ it('a directory change (create / rename / move) falls back to a full rescan', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ mkdirSync(path.join(root, 'assets/newdir'));
+ const inc = await updateAssetIndex(root, prev, ['assets/newdir'], { write: false });
+ expect(inc.fullRescan).toBe(true);
+ expect(inc.reason).toContain('directory');
+ });
+
+ it('a removed directory that held assets falls back (its child moves are invisible)', async () => {
+ const { index: prev } = await scanAssetDatabase(root, { write: false });
+ // Simulate the dir vanishing (the watcher may report only the dir path).
+ rmSync(path.join(root, 'assets/fonts'), { recursive: true });
+ const inc = await updateAssetIndex(root, prev, ['assets/fonts'], { write: false });
+ expect(inc.fullRescan).toBe(true);
+ expect(inc.reason).toContain('directory');
+ });
+});
diff --git a/pipeline/tests/asset-db.test.ts b/pipeline/tests/asset-db.test.ts
new file mode 100644
index 000000000..3cbc5f420
--- /dev/null
+++ b/pipeline/tests/asset-db.test.ts
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AssetDatabase scanner (REARCH_ASSETS.md A2). A pure-node step: walk a
+ * project's `.meta` sidecars into a uuid↔path registry + a dependency
+ * graph (which scene/prefab references which asset), written to
+ * `.esengine/cache/assets.json`. Skips code/build/vcs dirs; reads the
+ * `type` each `.meta` already declares (no extension table).
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase, type AssetIndex } from '../src/assets/assetDb';
+
+let root: string;
+
+const TEX_UUID = '11111111-1111-4111-8111-111111111111';
+const FONT_UUID = '22222222-2222-4222-8222-222222222222';
+const SCENE_UUID = '33333333-3333-4333-8333-333333333333';
+
+function writeAsset(rel: string, type: string, uuid: string, body = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-assetdb-'));
+ // Two leaf assets + a scene that references them by @uuid:.
+ writeAsset('assets/textures/player.png', 'texture', TEX_UUID, 'PNGDATA');
+ writeAsset('assets/fonts/ui.fnt', 'font', FONT_UUID, 'FNTDATA');
+ writeAsset(
+ 'assets/scenes/main.esscene',
+ 'scene',
+ SCENE_UUID,
+ JSON.stringify({
+ version: '1.0',
+ name: 'main',
+ entities: [
+ {
+ id: 1,
+ name: 'Hero',
+ parent: null,
+ children: [],
+ components: [
+ { type: 'Sprite', data: { texture: `@uuid:${TEX_UUID}` } },
+ { type: 'BitmapText', data: { font: `@uuid:${FONT_UUID}` } },
+ ],
+ },
+ ],
+ }),
+ );
+ // A code dir that must be SKIPPED even though it contains a stray .meta.
+ const nm = path.join(root, 'node_modules', 'pkg');
+ mkdirSync(nm, { recursive: true });
+ writeFileSync(path.join(nm, 'thing.png.meta'), JSON.stringify({ uuid: 'deadbeef', type: 'texture' }));
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+describe('scanAssetDatabase (A2)', () => {
+ it('indexes every .meta into uuid↔path entries and writes assets.json', async () => {
+ const res = await scanAssetDatabase(root);
+ expect(res.ok).toBe(true);
+ expect(res.outputPath).toBe(path.join(root, '.esengine/cache/assets.json'));
+ expect(existsSync(res.outputPath!)).toBe(true);
+
+ const byUuid = Object.fromEntries(res.index.entries.map((e) => [e.uuid, e]));
+ expect(byUuid[TEX_UUID].path).toBe('assets/textures/player.png');
+ expect(byUuid[TEX_UUID].type).toBe('texture');
+ expect(byUuid[FONT_UUID].path).toBe('assets/fonts/ui.fnt');
+ expect(byUuid[SCENE_UUID].type).toBe('scene');
+
+ // The written artifact matches the returned index.
+ const onDisk = JSON.parse(readFileSync(res.outputPath!, 'utf8')) as AssetIndex;
+ expect(onDisk.entries.length).toBe(res.index.entries.length);
+ });
+
+ it('builds a dependency graph: the scene depends on the assets it references', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.deps[SCENE_UUID]).toEqual([FONT_UUID, TEX_UUID].sort());
+ // Leaf assets have no deps.
+ expect(index.deps[TEX_UUID]).toBeUndefined();
+ });
+
+ it('skips node_modules / build / vcs dirs', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.entries.some((e) => e.path.includes('node_modules'))).toBe(false);
+ expect(index.entries.length).toBe(3); // texture + font + scene, nothing from node_modules
+ });
+
+ it('write-if-changed: an unchanged index does not rewrite assets.json', async () => {
+ const first = await scanAssetDatabase(root);
+ const mtime = statSync(first.outputPath!).mtimeMs;
+ const second = await scanAssetDatabase(root);
+ expect(statSync(second.outputPath!).mtimeMs).toBe(mtime); // untouched → no watcher echo
+ });
+});
+
+describe('scanAssetDatabase — orphan adoption', () => {
+ it('adopts a content file with no .meta: mints one and indexes it this scan', async () => {
+ const abs = path.join(root, 'assets/textures/orphan.png');
+ writeFileSync(abs, 'PNGDATA');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual(['assets/textures/orphan.png']);
+ expect(existsSync(`${abs}.meta`)).toBe(true);
+ const meta = JSON.parse(readFileSync(`${abs}.meta`, 'utf8'));
+ expect(meta.type).toBe('texture');
+ const entry = res.index.entries.find((e) => e.path === 'assets/textures/orphan.png');
+ expect(entry?.uuid).toBe(meta.uuid.toLowerCase());
+ // Second scan: nothing left to adopt, identity stable.
+ const again = await scanAssetDatabase(root, { write: false });
+ expect(again.adopted).toEqual([]);
+ expect(again.index.entries.find((e) => e.path === 'assets/textures/orphan.png')?.uuid)
+ .toBe(entry?.uuid);
+ rmSync(abs); rmSync(`${abs}.meta`);
+ });
+
+ it('leaves unknown extensions alone (docs and source files are not assets)', async () => {
+ const abs = path.join(root, 'assets/README.txt');
+ writeFileSync(abs, 'hello');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual([]);
+ expect(existsSync(`${abs}.meta`)).toBe(false);
+ rmSync(abs);
+ });
+
+ it('the project-root thumbnail.png (editor-managed launcher cover) is never adopted', async () => {
+ const abs = path.join(root, 'thumbnail.png');
+ writeFileSync(abs, 'PNGDATA');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual([]);
+ expect(existsSync(`${abs}.meta`)).toBe(false);
+ rmSync(abs);
+ });
+
+ it('adopt: false is a pure read (cook path) — orphans stay untouched', async () => {
+ const abs = path.join(root, 'assets/pure.png');
+ writeFileSync(abs, 'PNGDATA');
+ const res = await scanAssetDatabase(root, { write: false, adopt: false });
+ expect(res.adopted).toEqual([]);
+ expect(existsSync(`${abs}.meta`)).toBe(false);
+ rmSync(abs);
+ });
+
+ // "I dropped my spine folder into the project" — with a JSON skeleton, which is
+ // all Spine 2.1 can export. Nothing in the NAME says the `.json` is a skeleton,
+ // so a name-only adoption left it out of the registry entirely and its component
+ // slot had nothing to offer.
+ it('adopts a JSON Spine skeleton as spine and a plain one as data', async () => {
+ const skel = path.join(root, 'assets/skeleton.json');
+ const data = path.join(root, 'assets/levels.json');
+ writeFileSync(skel, '{"skeleton":{"hash":"h","spine":"2.1.27"},"bones":[{"name":"root"}]}');
+ writeFileSync(data, '{"levels":[1,2,3]}');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted.sort()).toEqual(['assets/levels.json', 'assets/skeleton.json']);
+ // The marker inside the file wins; a `.json` nobody else claims is data.
+ expect(JSON.parse(readFileSync(`${skel}.meta`, 'utf8')).type).toBe('spine');
+ expect(JSON.parse(readFileSync(`${data}.meta`, 'utf8')).type).toBe('json');
+ expect(res.index.entries.find((e) => e.path === 'assets/skeleton.json')?.type).toBe('spine');
+ expect(res.index.entries.find((e) => e.path === 'assets/levels.json')?.type).toBe('json');
+ rmSync(skel); rmSync(`${skel}.meta`); rmSync(data); rmSync(`${data}.meta`);
+ });
+
+ it("leaves the project's own config files alone", async () => {
+ // Every project has these, and a `.meta` beside them is pure noise.
+ const ts = path.join(root, 'tsconfig.json');
+ const pkg = path.join(root, 'package.json');
+ writeFileSync(ts, '{"compilerOptions":{}}');
+ writeFileSync(pkg, '{"name":"game"}');
+ const res = await scanAssetDatabase(root, { write: false });
+ expect(res.adopted).toEqual([]);
+ expect(existsSync(`${ts}.meta`)).toBe(false);
+ expect(existsSync(`${pkg}.meta`)).toBe(false);
+ rmSync(ts); rmSync(pkg);
+ });
+});
+
+describe('two files that claim the same uuid', () => {
+ // A uuid IS the asset's identity: the registry is a uuid→path map, so a shared one
+ // keeps a single winner. The other file is then in no registry at all, and every
+ // reference to that uuid resolves to whichever the scan saw last — which reaches a
+ // user as "the sprite I dropped shows a different picture than the preview".
+ it('gives each file its own identity back, on disk, and says so', async () => {
+ const shared = '44444444-4444-4444-8444-444444444444';
+ writeAsset('assets/bulk/a.png', 'texture', shared, 'A');
+ writeAsset('assets/bulk/b.png', 'texture', shared, 'B');
+ writeAsset('assets/bulk/c.png', 'texture', shared, 'C');
+
+ const res = await scanAssetDatabase(root, { write: false });
+ const bulk = res.index.entries.filter((e) => e.path.startsWith('assets/bulk/'));
+ expect(bulk.map((e) => e.path)).toEqual(['assets/bulk/a.png', 'assets/bulk/b.png', 'assets/bulk/c.png']);
+ expect(new Set(bulk.map((e) => e.uuid)).size).toBe(3);
+
+ // The FIRST in path order keeps it, so a re-scan does not shuffle identities and
+ // whatever already referenced it still resolves.
+ expect(bulk[0].uuid).toBe(shared);
+ expect(res.reminted.sort()).toEqual(['assets/bulk/b.png', 'assets/bulk/c.png']);
+ expect(res.warnings.some((w) => /shared its uuid/.test(w))).toBe(true);
+
+ // Written through, not just fixed in memory — the next scan must agree.
+ const uuidOf = (p: string) => JSON.parse(readFileSync(path.join(root, `${p}.meta`), 'utf8')).uuid;
+ expect(uuidOf('assets/bulk/b.png')).not.toBe(shared);
+ expect(uuidOf('assets/bulk/c.png')).not.toBe(uuidOf('assets/bulk/b.png'));
+
+ const again = await scanAssetDatabase(root, { write: false });
+ expect(again.reminted).toEqual([]);
+ expect(new Set(again.index.entries.filter((e) => e.path.startsWith('assets/bulk/')).map((e) => e.uuid)).size).toBe(3);
+
+ for (const f of ['a.png', 'b.png', 'c.png']) {
+ rmSync(path.join(root, `assets/bulk/${f}`));
+ rmSync(path.join(root, `assets/bulk/${f}.meta`));
+ }
+ });
+});
diff --git a/pipeline/tests/asset-meta-table.test.ts b/pipeline/tests/asset-meta-table.test.ts
new file mode 100644
index 000000000..43c9927ff
--- /dev/null
+++ b/pipeline/tests/asset-meta-table.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Guards the single source for the `.meta` type vocabulary. The CLI
+// (tools/asset-meta.js) and the editor mint door (electron/assetMeta.ts) both
+// derive from tools/assetMetaTable.js; they used to hand-mirror it and had
+// drifted (`.esanim` minted as `animation` from the CLI but `animclip` from the
+// editor; `.esanimator` had no CLI entry, so an imported animator controller
+// never got a `.meta`).
+import { describe, it, expect } from 'vitest';
+import { EXT_TO_TYPE, metaTypeFor } from '../src/assets/assetMeta';
+import {
+ EXT_TO_TYPE as SHARED, metaTypeForContent, needsContentType, isProjectPlumbing,
+} from '../../tools/assetMetaTable.js';
+
+describe('.meta type table (single source)', () => {
+ it('the editor mint door re-exports the shared table verbatim', () => {
+ expect(EXT_TO_TYPE).toBe(SHARED);
+ });
+
+ it('mints the canonical type for every engine authoring format', () => {
+ expect(metaTypeFor('x.esanim')).toBe('animclip');
+ expect(metaTypeFor('x.esanimclip')).toBe('animclip');
+ expect(metaTypeFor('x.estimeline')).toBe('animation');
+ expect(metaTypeFor('x.estileset')).toBe('tileset');
+ expect(metaTypeFor('x.estilemap')).toBe('tilemap');
+ expect(metaTypeFor('x.esfsm')).toBe('statemachine');
+ expect(metaTypeFor('x.esbt')).toBe('behaviortree');
+ expect(metaTypeFor('x.eslocale')).toBe('locale');
+ expect(metaTypeFor('x.inputmap')).toBe('inputmap');
+ });
+
+ // The graph is editor-side source that never ships — but an extension only
+ // the Content Browser knew about is one create_asset cannot name and the
+ // scan cannot adopt, so it belongs on the shared table like every other.
+ it('types a material graph (regression: only the renderer knew the extension)', () => {
+ expect(metaTypeFor('fire.esmatgraph')).toBe('materialgraph');
+ expect(metaTypeFor('fire.esshader')).toBe('shader');
+ expect(metaTypeFor('fire.esmaterial')).toBe('material');
+ });
+
+ it('mints a type for an imported .esanimator (regression: was unknown → no meta)', () => {
+ expect(metaTypeFor('player.esanimator')).toBe('animatorcontroller');
+ });
+
+ it('is case-insensitive and null for unknown extensions', () => {
+ expect(metaTypeFor('X.ESANIM')).toBe('animclip');
+ expect(metaTypeFor('notes.txt')).toBeNull();
+ expect(metaTypeFor('README.md')).toBeNull();
+ });
+
+ it('types a DragonBones pair by its name suffix (`.json` alone cannot)', () => {
+ expect(metaTypeFor('DragonBoy_ske.json')).toBe('dragonbones');
+ expect(metaTypeFor('DragonBoy_tex.json')).toBe('dragonbones');
+ expect(metaTypeFor('DragonBoy.dbbin')).toBe('dragonbones');
+ });
+});
+
+// A Spine skeleton exported as JSON is a plain `.json` under whatever name the
+// artist chose — and Spine 2.1 has NO binary export, so that is the only form
+// such a project can hand the editor. It is typed by the marker inside the file:
+// the same one the runtime's version detection reads, so the editor and the
+// runtime cannot disagree about what a given `.json` is.
+describe('content-typed assets', () => {
+ const SKELETON = '{"skeleton":{"hash":"4NGJIALC","spine":"2.1.27","width":1371.35},"bones":[]}';
+
+ it('claims only the files a name cannot type', () => {
+ expect(needsContentType('skeleton.json')).toBe(true);
+ expect(needsContentType('hero.png')).toBe(false);
+ expect(needsContentType('level.tmj')).toBe(false);
+ // A name that DOES type it is not up for content review.
+ expect(needsContentType('DragonBoy_ske.json')).toBe(false);
+ });
+
+ it('types a Spine JSON skeleton as spine', () => {
+ expect(metaTypeForContent('skeleton.json', SKELETON)).toBe('spine');
+ expect(metaTypeForContent('boy.json', '{"skeleton":{"spine":"4.2.31"},"bones":[]}')).toBe('spine');
+ // Pretty-printed exports read the same.
+ expect(metaTypeForContent('x.json', '{\n "skeleton": {\n "spine": "3.8.99"\n }\n}')).toBe('spine');
+ });
+
+ it('types a `.json` nobody else claims as data', () => {
+ // The game's own tables are assets: that is what gives them a uuid, a
+ // place in the manifest, and a seat in the build.
+ expect(metaTypeForContent('levels.json', '{"levels":[1,2,3]}')).toBe('json');
+ // "spine" outside a skeleton header is not a skeleton — it is data.
+ expect(metaTypeForContent('notes.json', '{"about":"the spine: 4.2 runtime"}')).toBe('json');
+ });
+
+ it('leaves the project\'s own plumbing alone', () => {
+ // These are read by the toolchain, not the game; a `.meta` beside them
+ // is noise in every project that has ever existed.
+ for (const name of ['package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json']) {
+ expect(needsContentType(name)).toBe(false);
+ expect(metaTypeForContent(name, '{}')).toBeNull();
+ }
+ expect(isProjectPlumbing('a/b/tsconfig.json')).toBe(true);
+ expect(isProjectPlumbing('assets/data/levels.json')).toBe(false);
+ });
+
+ it('never types a name that is not JSON at all', () => {
+ expect(metaTypeForContent('README.md', '# hi')).toBeNull();
+ expect(metaTypeForContent('main.ts', 'export {}')).toBeNull();
+ });
+
+ it('never overrides a name that already typed the file', () => {
+ expect(metaTypeForContent('DragonBoy_ske.json', '{"armature":[]}')).toBe('dragonbones');
+ expect(metaTypeForContent('hero.png', SKELETON)).toBe('texture');
+ });
+});
diff --git a/pipeline/tests/asset-symlink-escape.test.ts b/pipeline/tests/asset-symlink-escape.test.ts
new file mode 100644
index 000000000..fc85f32f8
--- /dev/null
+++ b/pipeline/tests/asset-symlink-escape.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A project is not trusted input, and the cook reads by project-relative
+ * path. Together those mean a link inside a project is an instruction to
+ * read whatever it points at — and the cook writes what it reads into the
+ * game that gets shipped. A project cloned, unzipped or handed over could
+ * therefore carry files off the machine that exported it.
+ *
+ * The IPC door (resolveInside) already refuses links out. The scanner and
+ * the cook are a separate path: they never went through that door, so a
+ * link named like content, with a sidecar beside it, was indexed and its
+ * target's bytes were staged with no warning.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, readFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase } from '../src/assets/assetDb';
+import { cookAssets } from '../src/assets/cookAssets';
+
+const SECRET = 'SECRET-BYTES-NOT-IN-THE-PROJECT';
+const LEAK_UUID = '33333333-3333-4333-8333-333333333333';
+const SCENE_UUID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+
+/** Windows refuses plain symlinks without elevation but allows directory junctions. */
+function linkDir(target: string, at: string): void {
+ symlinkSync(target, at, process.platform === 'win32' ? 'junction' : 'dir');
+}
+
+interface Fixture { base: string; root: string; outsideFile: string }
+
+function makeProject(): Fixture {
+ const base = mkdtempSync(path.join(tmpdir(), 'estella-escape-'));
+ const outside = path.join(base, 'outside');
+ mkdirSync(outside, { recursive: true });
+ const outsideFile = path.join(outside, 'secret.png');
+ writeFileSync(outsideFile, SECRET);
+
+ const root = path.join(base, 'project');
+ mkdirSync(path.join(root, 'assets', 'textures'), { recursive: true });
+ mkdirSync(path.join(root, 'assets', 'scenes'), { recursive: true });
+ writeFileSync(path.join(root, 'assets', 'textures', 'ok.png'), 'legit');
+ return { base, root, outsideFile };
+}
+
+function writeMeta(abs: string, uuid: string, type: string): void {
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+function writeScene(root: string, texUuid: string): string {
+ const rel = 'assets/scenes/main.esscene';
+ const abs = path.join(root, rel);
+ writeFileSync(abs, JSON.stringify({
+ version: 1, name: 's',
+ entities: [{
+ id: 1, name: 'S', parent: null, children: [],
+ components: [{ type: 'Sprite', data: { texture: `@uuid:${texUuid}` } }],
+ }],
+ }));
+ writeMeta(abs, SCENE_UUID, 'scene');
+ return rel;
+}
+
+describe('a link out of the project reaches neither the index nor the build', () => {
+ it('a linked content file is not indexed, with or without a sidecar', async () => {
+ const { base, root, outsideFile } = makeProject();
+ try {
+ symlinkSync(outsideFile, path.join(root, 'assets', 'textures', 'adopted.png'));
+ symlinkSync(outsideFile, path.join(root, 'assets', 'textures', 'sidecar.png'));
+ writeMeta(path.join(root, 'assets', 'textures', 'sidecar.png'), LEAK_UUID, 'texture');
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ const paths = index.entries.map((e) => e.path);
+ expect(paths).toContain('assets/textures/ok.png');
+ expect(paths).not.toContain('assets/textures/adopted.png');
+ expect(paths).not.toContain('assets/textures/sidecar.png');
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a linked directory is not walked into', async () => {
+ const { base, root } = makeProject();
+ try {
+ const outsideDir = path.join(base, 'outside', 'more');
+ mkdirSync(outsideDir, { recursive: true });
+ writeFileSync(path.join(outsideDir, 'deep.png'), SECRET);
+ linkDir(outsideDir, path.join(root, 'assets', 'linked'));
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ expect(index.entries.map((e) => e.path).some((p) => p.includes('deep'))).toBe(false);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a scene referencing a linked texture ships without its bytes', async () => {
+ const { base, root, outsideFile } = makeProject();
+ try {
+ const leak = path.join(root, 'assets', 'textures', 'leak.png');
+ symlinkSync(outsideFile, leak);
+ writeMeta(leak, LEAK_UUID, 'texture');
+ const scene = writeScene(root, LEAK_UUID);
+
+ const out = path.join(base, 'out');
+ const cooked = await cookAssets(root, { entryScenes: [scene], outDir: out, contentAddressed: false });
+
+ expect(cooked.includedPaths).not.toContain('assets/textures/leak.png');
+ const staged = path.join(out, 'assets', 'textures', 'leak.png');
+ expect(existsSync(staged)).toBe(false);
+ // Nothing anywhere in the build may carry those bytes.
+ const manifest = path.join(out, 'assets.manifest.json');
+ if (existsSync(manifest)) expect(readFileSync(manifest, 'utf8')).not.toContain(SECRET);
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+
+ it('a link that stays inside the project still works', async () => {
+ const { base, root } = makeProject();
+ try {
+ const real = path.join(root, 'assets', 'textures', 'real.png');
+ writeFileSync(real, 'inside-bytes');
+ writeMeta(real, LEAK_UUID, 'texture');
+ symlinkSync(real, path.join(root, 'assets', 'textures', 'alias.png'));
+
+ const { index } = await scanAssetDatabase(root, { write: false, adopt: true });
+ const paths = index.entries.map((e) => e.path);
+ expect(paths).toContain('assets/textures/real.png');
+ expect(paths).toContain('assets/textures/alias.png');
+ } finally {
+ rmSync(base, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/pipeline/tests/atlas-packer.test.ts b/pipeline/tests/atlas-packer.test.ts
new file mode 100644
index 000000000..4a5014ac3
--- /dev/null
+++ b/pipeline/tests/atlas-packer.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Atlas packer — deterministic shelf packing + page composition.
+ */
+import { describe, it, expect } from 'vitest';
+import { packAtlas, decodePngImage, encodePagePng, encodeRgbaPng, downscaleRgba, type AtlasInputImage } from '../src/assets/atlasPacker';
+
+function solid(key: string, width: number, height: number, rgba: [number, number, number, number]): AtlasInputImage {
+ const data = new Uint8Array(width * height * 4);
+ for (let i = 0; i < width * height; i++) data.set(rgba, i * 4);
+ return { key, width, height, rgba: data };
+}
+
+describe('packAtlas', () => {
+ it('packs everything onto the smallest power-of-two page that fits', () => {
+ const pages = packAtlas([
+ solid('a', 16, 16, [255, 0, 0, 255]),
+ solid('b', 16, 16, [0, 255, 0, 255]),
+ solid('c', 16, 16, [0, 0, 255, 255]),
+ ]);
+ expect(pages).toHaveLength(1);
+ expect(pages[0].width).toBe(64); // three 20px padded boxes need one 60px shelf
+ expect(pages[0].height).toBe(64);
+ expect(pages[0].placements).toHaveLength(3);
+ });
+
+ it('is deterministic regardless of input order', () => {
+ const images = [
+ solid('tall', 8, 32, [1, 2, 3, 255]),
+ solid('wide', 32, 8, [4, 5, 6, 255]),
+ solid('mid', 16, 16, [7, 8, 9, 255]),
+ ];
+ const a = packAtlas(images);
+ const b = packAtlas([...images].reverse());
+ expect(b).toEqual(a);
+ });
+
+ it('keeps placements padded and non-overlapping', () => {
+ const pages = packAtlas([
+ solid('a', 30, 10, [1, 0, 0, 255]),
+ solid('b', 10, 30, [0, 1, 0, 255]),
+ solid('c', 20, 20, [0, 0, 1, 255]),
+ ], { padding: 2 });
+ for (const page of pages) {
+ for (const p of page.placements) {
+ expect(p.x).toBeGreaterThanOrEqual(2);
+ expect(p.y).toBeGreaterThanOrEqual(2);
+ expect(p.x + p.width).toBeLessThanOrEqual(page.width - 2);
+ expect(p.y + p.height).toBeLessThanOrEqual(page.height - 2);
+ }
+ for (const p of page.placements) {
+ for (const q of page.placements) {
+ if (p === q) continue;
+ const overlap = p.x < q.x + q.width && q.x < p.x + p.width
+ && p.y < q.y + q.height && q.y < p.y + p.height;
+ expect(overlap).toBe(false);
+ }
+ }
+ }
+ });
+
+ it('spills onto extra pages when the cap cannot hold everything', () => {
+ const images = Array.from({ length: 5 }, (_, i) => solid(`i${i}`, 40, 40, [i, i, i, 255]));
+ const pages = packAtlas(images, { maxSize: 64 });
+ expect(pages.length).toBe(5); // one padded 44px box per 64px page
+ expect(pages.flatMap((p) => p.placements)).toHaveLength(5);
+ });
+
+ it('rejects an image larger than the page cap', () => {
+ expect(() => packAtlas([solid('huge', 3000, 8, [0, 0, 0, 255])])).toThrow(/exceeds/);
+ });
+
+ it('composes page pixels at the placements', () => {
+ const pages = packAtlas([
+ solid('red', 2, 2, [255, 0, 0, 255]),
+ solid('blue', 2, 2, [0, 0, 255, 255]),
+ ], { padding: 1 });
+ expect(pages).toHaveLength(1);
+ const page = pages[0];
+ for (const p of page.placements) {
+ const px = (p.y * page.width + p.x) * 4;
+ const want = p.key === 'red' ? [255, 0, 0, 255] : [0, 0, 255, 255];
+ expect([...page.rgba.subarray(px, px + 4)]).toEqual(want);
+ }
+ // Padding gutters stay transparent.
+ expect(page.rgba[3]).toBe(0);
+ });
+
+ it('round-trips through PNG encode/decode', () => {
+ const pages = packAtlas([solid('x', 3, 5, [10, 20, 30, 255])]);
+ const png = encodePagePng(pages[0]);
+ const back = decodePngImage('page', png);
+ expect(back.width).toBe(pages[0].width);
+ expect(back.height).toBe(pages[0].height);
+ expect([...back.rgba]).toEqual([...pages[0].rgba]);
+ });
+});
+
+describe('downscaleRgba (Max Size cook cap)', () => {
+ it('returns the input untouched when within the cap', () => {
+ const img = solid('a', 64, 64, [1, 2, 3, 255]);
+ expect(downscaleRgba(img, 2048)).toBe(img); // same reference — no work
+ expect(downscaleRgba(img, 64)).toBe(img); // exactly at cap
+ });
+
+ it('shrinks so the longest side ≤ cap, keeping aspect + solid color', () => {
+ const out = downscaleRgba(solid('a', 128, 32, [200, 100, 50, 255]), 32);
+ expect(out.width).toBe(32); // 128 → 32
+ expect(out.height).toBe(8); // 32 → 8 (aspect preserved)
+ expect(out.rgba).toHaveLength(32 * 8 * 4);
+ // A solid image downscales to the same solid color everywhere.
+ for (let i = 0; i < out.width * out.height; i++) {
+ expect([...out.rgba.subarray(i * 4, i * 4 + 4)]).toEqual([200, 100, 50, 255]);
+ }
+ });
+
+ it('averages color in premultiplied space (transparent pixels do not bleed)', () => {
+ // 2×1: opaque red + fully-transparent — the shrunk pixel keeps red's hue,
+ // with alpha averaged to half. (Naive averaging would darken toward black.)
+ const img: AtlasInputImage = { key: 'k', width: 2, height: 1, rgba: new Uint8Array([255, 0, 0, 255, 0, 0, 0, 0]) };
+ const out = downscaleRgba(img, 1);
+ expect(out.width).toBe(1);
+ expect(out.height).toBe(1);
+ expect([...out.rgba]).toEqual([255, 0, 0, 128]);
+ });
+
+ it('encodeRgbaPng round-trips raw pixels', () => {
+ const rgba = new Uint8Array([9, 8, 7, 255, 6, 5, 4, 255]);
+ const back = decodePngImage('p', encodeRgbaPng(2, 1, rgba));
+ expect(back.width).toBe(2);
+ expect([...back.rgba]).toEqual([...rgba]);
+ });
+});
diff --git a/pipeline/tests/audio-cook.test.ts b/pipeline/tests/audio-cook.test.ts
new file mode 100644
index 000000000..a0260d137
--- /dev/null
+++ b/pipeline/tests/audio-cook.test.ts
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Cook-time audio: WAV parsing (PCM16/24/float, extensible, word-aligned
+ * chunks) and the WAV→MP3 transcode through the real LAME wasm encoder.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseWav, encodeWavToMp3, audioImportSettings } from '../src/assets/audioCook';
+
+/** Build a minimal RIFF/WAVE file. */
+function makeWav(opts: {
+ formatTag?: number; channels?: number; sampleRate?: number; bits?: number;
+ frames?: number; sample?: (frame: number, ch: number) => number;
+}): Uint8Array {
+ const formatTag = opts.formatTag ?? 1;
+ const channels = opts.channels ?? 1;
+ const rate = opts.sampleRate ?? 44100;
+ const bits = opts.bits ?? 16;
+ const frames = opts.frames ?? 100;
+ const sample = opts.sample ?? ((f) => Math.sin(f / 10) * 0.5);
+ const bytesPer = bits / 8;
+ const dataSize = frames * channels * bytesPer;
+ const buf = new ArrayBuffer(44 + dataSize);
+ const v = new DataView(buf);
+ const w4 = (o: number, s: string) => { for (let i = 0; i < 4; i++) v.setUint8(o + i, s.charCodeAt(i)); };
+ w4(0, 'RIFF'); v.setUint32(4, 36 + dataSize, true); w4(8, 'WAVE');
+ w4(12, 'fmt '); v.setUint32(16, 16, true);
+ v.setUint16(20, formatTag, true); v.setUint16(22, channels, true);
+ v.setUint32(24, rate, true); v.setUint32(28, rate * channels * bytesPer, true);
+ v.setUint16(32, channels * bytesPer, true); v.setUint16(34, bits, true);
+ w4(36, 'data'); v.setUint32(40, dataSize, true);
+ for (let f = 0; f < frames; f++) {
+ for (let c = 0; c < channels; c++) {
+ const off = 44 + (f * channels + c) * bytesPer;
+ const s = sample(f, c);
+ if (formatTag === 3) v.setFloat32(off, s, true);
+ else if (bits === 16) v.setInt16(off, Math.round(s * 0x7fff), true);
+ else if (bits === 24) {
+ const u = (Math.round(s * 0x7fffff) + 0x1000000) & 0xffffff;
+ v.setUint8(off, u & 0xff); v.setUint8(off + 1, (u >> 8) & 0xff); v.setUint8(off + 2, (u >> 16) & 0xff);
+ }
+ }
+ }
+ return new Uint8Array(buf);
+}
+
+describe('parseWav', () => {
+ it('parses PCM16 stereo', () => {
+ const wav = makeWav({ channels: 2, frames: 50, sample: (_f, c) => (c === 0 ? 0.5 : -0.5) });
+ const parsed = parseWav(wav)!;
+ expect(parsed.sampleRate).toBe(44100);
+ expect(parsed.channels).toHaveLength(2);
+ expect(parsed.channels[0][10]).toBeCloseTo(0.5, 2);
+ expect(parsed.channels[1][10]).toBeCloseTo(-0.5, 2);
+ });
+
+ it('parses 32-bit float and 24-bit PCM', () => {
+ const f32 = parseWav(makeWav({ formatTag: 3, bits: 32, sample: () => 0.25 }))!;
+ expect(f32.channels[0][5]).toBeCloseTo(0.25, 5);
+ const p24 = parseWav(makeWav({ bits: 24, sample: () => 0.25 }))!;
+ expect(p24.channels[0][5]).toBeCloseTo(0.25, 3);
+ });
+
+ it('rejects non-WAV bytes', () => {
+ expect(parseWav(new Uint8Array(100))).toBeNull();
+ expect(parseWav(new TextEncoder().encode('OggS' + 'x'.repeat(60)))).toBeNull();
+ });
+});
+
+describe('encodeWavToMp3', () => {
+ it('re-encodes a WAV to a smaller MP3', async () => {
+ const wav = makeWav({ frames: 44100, sample: (f) => Math.sin((f / 44100) * 2 * Math.PI * 440) * 0.7 });
+ const mp3 = await encodeWavToMp3(wav, 128);
+ expect(mp3).not.toBeNull();
+ // MP3 frame sync at the start (0xFFEx) or an ID3/LAME header.
+ expect(mp3!.byteLength).toBeGreaterThan(1000);
+ expect(mp3!.byteLength).toBeLessThan(wav.byteLength);
+ }, 30000);
+
+ it('returns null for unparseable input', async () => {
+ expect(await encodeWavToMp3(new Uint8Array(64), 128)).toBeNull();
+ });
+});
+
+describe('audioImportSettings', () => {
+ it('defaults and validates', () => {
+ expect(audioImportSettings(undefined)).toEqual({ compress: true, bitrateKbps: 128 });
+ expect(audioImportSettings({ compress: false, bitrateKbps: 192 })).toEqual({ compress: false, bitrateKbps: 192 });
+ expect(audioImportSettings({ bitrateKbps: 999 })).toEqual({ compress: true, bitrateKbps: 128 });
+ });
+});
diff --git a/pipeline/tests/build-scripts.test.ts b/pipeline/tests/build-scripts.test.ts
new file mode 100644
index 000000000..8bbaae44c
--- /dev/null
+++ b/pipeline/tests/build-scripts.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Project-script bundler (REARCH_EDITOR_REALM Phase P1 / RC12 §E8-1).
+ * Asserts esengine is left EXTERNAL (resolved by the play realm's import
+ * map, not duplicated into every bundle) while the project's own modules
+ * are bundled in.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { buildProjectScripts } from '../src/bundle/buildScripts';
+
+let root: string;
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-proj-'));
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ // A project's own module — must be bundled IN.
+ writeFileSync(
+ path.join(root, 'src', 'components.ts'),
+ `import { defineComponent } from 'esengine';\n` +
+ `export const Wave = defineComponent('Wave', { amplitude: 1 });\n`,
+ );
+ // Entry — imports esengine (external) + a local module (bundled).
+ writeFileSync(
+ path.join(root, 'src', 'main.ts'),
+ `import { addSystemToSchedule, Schedule } from 'esengine';\n` +
+ `import { Wave } from './components';\n` +
+ `addSystemToSchedule(Schedule.Update, () => { void Wave; });\n`,
+ );
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+describe('buildProjectScripts (E8-1)', () => {
+ it('bundles src/main.ts with esengine external and local modules inlined', async () => {
+ const res = await buildProjectScripts(root);
+ expect(res.ok).toBe(true);
+ expect(res.errors).toEqual([]);
+ expect(res.outputPath).toBe(path.join(root, '.esengine/cache/scripts.mjs'));
+ expect(existsSync(res.outputPath!)).toBe(true);
+
+ const out = readFileSync(res.outputPath!, 'utf8');
+ // esengine is kept external — the bare import survives in the bundle:
+ expect(out).toMatch(/from\s*["']esengine["']/);
+ // …and esengine is NOT inlined (the build would have errored trying to
+ // resolve it from this fixture's node_modules if it weren't external).
+ // The project's own module IS bundled (its local import is gone, its code present):
+ expect(out).not.toMatch(/from\s*["']\.\/components["']/);
+ expect(out).toContain('Wave');
+ expect(out).toContain('amplitude');
+ });
+
+ it('bundles a plugin installed from npm, sharing the one engine instance', async () => {
+ // A plugin's runtime half is an ordinary dependency, but it has to reach
+ // the same engine the game runs on: a copy bundled inside the package is a
+ // second component registry, and its systems register into nothing.
+ const proj = mkdtempSync(path.join(tmpdir(), 'estella-pkgruntime-'));
+ try {
+ const pkg = path.join(proj, 'node_modules', 'estella-plugin-demo');
+ mkdirSync(path.join(pkg, 'runtime'), { recursive: true });
+ writeFileSync(
+ path.join(pkg, 'package.json'),
+ JSON.stringify({ name: 'estella-plugin-demo', version: '1.0.0', type: 'module', main: 'runtime/index.js' }),
+ );
+ writeFileSync(
+ path.join(pkg, 'runtime', 'index.js'),
+ `import { defineComponent } from 'esengine';\n`
+ + `export const DemoService = defineComponent('DemoService', { level: 1 });\n`,
+ );
+ mkdirSync(path.join(proj, 'src'), { recursive: true });
+ // The entry imports ONLY the package, so a surviving bare `esengine`
+ // import can only have come from inside it.
+ writeFileSync(
+ path.join(proj, 'src', 'main.ts'),
+ `import { DemoService } from 'estella-plugin-demo';\nvoid DemoService;\n`,
+ );
+
+ const res = await buildProjectScripts(proj);
+ expect(res.errors).toEqual([]);
+ expect(res.ok).toBe(true);
+ const out = readFileSync(res.outputPath!, 'utf8');
+ expect(out).toContain('DemoService'); // the package's code is IN the bundle
+ expect(out).toMatch(/from\s*["']esengine["']/); // …and its engine import is not
+ } finally {
+ rmSync(proj, { recursive: true, force: true });
+ }
+ });
+
+ it('reports a clean failure when the entry is missing', async () => {
+ const empty = mkdtempSync(path.join(tmpdir(), 'estella-empty-'));
+ try {
+ const res = await buildProjectScripts(empty);
+ expect(res.ok).toBe(false);
+ expect(res.outputPath).toBeNull();
+ expect(res.errors.join(' ')).toMatch(/entry not found/);
+ } finally {
+ rmSync(empty, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/pipeline/tests/bundle-diagnostics.test.ts b/pipeline/tests/bundle-diagnostics.test.ts
new file mode 100644
index 000000000..a459002f6
--- /dev/null
+++ b/pipeline/tests/bundle-diagnostics.test.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file `Could not resolve "crypto"` is true and useless.
+ *
+ * npm packages bundle into a game fine — until one reaches for a Node built-in,
+ * and then the export fails with a bundler message that names no cause, no
+ * culprit file and no fix. A developer who has just run `npm install` reads it
+ * as "this engine cannot handle npm", which is the wrong conclusion and an
+ * expensive one.
+ *
+ * The rule this file holds: explain the ONE case that can be identified with
+ * certainty, and leave everything else exactly as the bundler said it. A guess
+ * appended to a real compile error costs more than the explanation is worth.
+ */
+import { describe, it, expect } from 'vitest';
+import { explainBundleError, explainBundleErrors, isNodeBuiltin } from '../src/bundle/bundleDiagnostics';
+
+describe('recognizing a Node built-in', () => {
+ it('knows the built-ins in both spellings', () => {
+ expect(isNodeBuiltin('crypto')).toBe(true);
+ expect(isNodeBuiltin('node:crypto')).toBe(true);
+ expect(isNodeBuiltin('fs/promises')).toBe(true);
+ expect(isNodeBuiltin('node:fs/promises')).toBe(true);
+ });
+
+ it('does not mistake an npm package for one', () => {
+ expect(isNodeBuiltin('protobufjs')).toBe(false);
+ expect(isNodeBuiltin('protobufjs/minimal')).toBe(false);
+ expect(isNodeBuiltin('./local-module')).toBe(false);
+ });
+});
+
+describe('explaining', () => {
+ it('says why, and points at web APIs when the import is the developer\'s own', () => {
+ const said = explainBundleError({
+ text: 'Could not resolve "crypto"',
+ location: { file: 'src/net/sign.ts' },
+ });
+ expect(said).toContain('Could not resolve "crypto"'); // the original, kept
+ expect(said).toContain('src/net/sign.ts'); // who asked
+ expect(said).toContain('does not run in Node'); // why
+ expect(said).toContain('crypto.subtle'); // what instead
+ });
+
+ it('points at the package when a dependency is the one reaching', () => {
+ // The developer's own code is fine here — telling them to "use a web API
+ // instead" would be advice about code they did not write.
+ const said = explainBundleError({
+ text: 'Could not resolve "fs"',
+ location: { file: 'node_modules/some-lib/dist/index.js' },
+ });
+ expect(said).toContain('came from a dependency');
+ expect(said).toContain('browser'); // the "browser" field / browser entry
+ expect(said).not.toContain('crypto.subtle'); // not the own-code advice
+ });
+
+ it('recognizes a windows path under node_modules too', () => {
+ const said = explainBundleError({
+ text: 'Could not resolve "path"',
+ location: { file: 'C:\\proj\\node_modules\\some-lib\\index.js' },
+ });
+ expect(said).toContain('came from a dependency');
+ });
+
+ it('still explains when the bundler named no file', () => {
+ const said = explainBundleError({ text: 'Could not resolve "os"' });
+ expect(said).toContain('is a Node built-in');
+ expect(said).not.toContain('imported by');
+ });
+});
+
+describe('leaving well enough alone', () => {
+ it('passes through an unresolved npm package untouched', () => {
+ // A missing dependency is a different problem with a different fix
+ // (`npm install`), and this has nothing to add to it.
+ const text = 'Could not resolve "protobufjs"';
+ expect(explainBundleError({ text })).toBe(text);
+ });
+
+ it('passes through an ordinary compile error untouched', () => {
+ const text = 'Expected ";" but found "}"';
+ expect(explainBundleError({ text, location: { file: 'src/main.ts' } })).toBe(text);
+ });
+
+ it('maps a batch, explaining only what it can', () => {
+ const out = explainBundleErrors([
+ { text: 'Could not resolve "fs"' },
+ { text: 'Expected ";" but found "}"' },
+ ]);
+ expect(out[0]).toContain('Node built-in');
+ expect(out[1]).toBe('Expected ";" but found "}"');
+ });
+});
diff --git a/pipeline/tests/content-policy.test.ts b/pipeline/tests/content-policy.test.ts
new file mode 100644
index 000000000..3d66eeb94
--- /dev/null
+++ b/pipeline/tests/content-policy.test.ts
@@ -0,0 +1,85 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The single authority on what counts as project content, and the separate
+ * question of what the watcher reports. These came apart when editor plugins
+ * landed: plugin sources live under `.esengine/` (so they are NOT content —
+ * they must stay out of the Content Browser and the asset scan) but they DO
+ * need watching, because they drive plugin hot reload.
+ *
+ * The loop hazard is what makes this worth pinning: the editor writes its own
+ * caches and the generated plugin typings under `.esengine/`, and reporting
+ * those would make the editor retrigger itself forever.
+ */
+import { describe, it, expect } from 'vitest';
+import { isContentDir, isContentFile, isNonContentPath, isPluginSourcePath, isWatchedPath } from '../src/assets/contentPolicy';
+
+describe('content classification', () => {
+ it('excludes dot entries, dependency and build dirs', () => {
+ expect(isContentDir('assets')).toBe(true);
+ expect(isContentDir('.esengine')).toBe(false);
+ expect(isContentDir('node_modules')).toBe(false);
+ expect(isContentDir('dist')).toBe(false);
+ expect(isContentFile('hero.png')).toBe(true);
+ expect(isContentFile('hero.png.meta')).toBe(false);
+ expect(isContentFile('.DS_Store')).toBe(false);
+ });
+
+ it("excludes an export's output, whichever platform wrote it", () => {
+ // A build's output is made OF content, so every file in it looks like one.
+ // Adopted, the registry treats a finished build as authored assets and the
+ // next build ships the previous one's manifest inside itself.
+ for (const dir of ['dist-web', 'dist-android', 'dist-wechat', 'dist-playable', 'dist-native']) {
+ expect(isContentDir(dir)).toBe(false);
+ expect(isNonContentPath(`${dir}/assets/hero.png`)).toBe(true);
+ }
+ // Not a prefix match on "dist": a folder of distortion sprites is content.
+ expect(isContentDir('distortion')).toBe(true);
+ });
+
+ it('treats any dot or build segment in a path as leaving content space', () => {
+ expect(isNonContentPath('assets/hero.png')).toBe(false);
+ expect(isNonContentPath('.esengine/cache/assets.json')).toBe(true);
+ expect(isNonContentPath('src/node_modules/x.ts')).toBe(true);
+ expect(isNonContentPath('assets\\sub\\hero.png')).toBe(false); // windows separators
+ });
+});
+
+describe('plugin sources are watched but are not content', () => {
+ const pluginEntry = '.esengine/plugins/acme.tools/src/editor.ts';
+
+ it('recognizes a plugin source path', () => {
+ expect(isPluginSourcePath(pluginEntry)).toBe(true);
+ expect(isPluginSourcePath('.esengine/plugins/acme.tools/plugin.json')).toBe(true);
+ expect(isPluginSourcePath('.esengine/plugins')).toBe(false); // the dir itself
+ expect(isPluginSourcePath('.esengine/cache/assets.json')).toBe(false);
+ expect(isPluginSourcePath('assets/hero.png')).toBe(false);
+ });
+
+ it('keeps plugin sources OUT of content space', () => {
+ // If this flipped, plugin sources would show up in the Content Browser and be
+ // scanned as assets.
+ expect(isNonContentPath(pluginEntry)).toBe(true);
+ });
+
+ it('reports plugin sources to the watcher anyway', () => {
+ expect(isWatchedPath(pluginEntry)).toBe(true);
+ expect(isWatchedPath('assets/hero.png')).toBe(true);
+ });
+
+ it('never watches the editor`s own writes under .esengine', () => {
+ // Each of these is written BY the editor; watching one would loop.
+ expect(isWatchedPath('.esengine/cache/assets.json')).toBe(false);
+ expect(isWatchedPath('.esengine/cache/scripts.mjs')).toBe(false);
+ expect(isWatchedPath('.esengine/workspace.json')).toBe(false);
+ // The generated plugin typings sit INSIDE the plugin dir, so they need the
+ // dot-prefix rule specifically — the plugin-source allowance would otherwise
+ // let the editor's own write retrigger a plugin reload.
+ expect(isWatchedPath('.esengine/plugins/.types/editor-api.d.ts')).toBe(false);
+ expect(isPluginSourcePath('.esengine/plugins/.types/editor-api.d.ts')).toBe(false);
+ });
+
+ it('handles windows separators in plugin paths', () => {
+ expect(isPluginSourcePath('.esengine\\plugins\\acme.tools\\src\\editor.ts')).toBe(true);
+ });
+});
diff --git a/pipeline/tests/cook-assets.test.ts b/pipeline/tests/cook-assets.test.ts
new file mode 100644
index 000000000..8aa23e15d
--- /dev/null
+++ b/pipeline/tests/cook-assets.test.ts
@@ -0,0 +1,545 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Asset cook (REARCH_ASSETS.md A4). From an entry scene, walk the
+ * AssetDatabase dep graph to the reachable assets, stage them + emit the
+ * runtime manifest, and cull anything unreferenced.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { cookAssets } from '../src/assets/cookAssets';
+import { decodePngImage } from '../src/assets/atlasPacker';
+import { contentHashHex } from '../../sdk/src/asset/contentHash';
+
+interface AssetManifest {
+ version: string;
+ entries: Array<{ uuid: string; path: string; type: string; contentHash?: string; size?: number; compressedFormats?: string[] }>;
+}
+
+let root: string;
+
+const USED_TEX = '11111111-1111-4111-8111-111111111111';
+const ORPHAN_TEX = '22222222-2222-4222-8222-222222222222';
+const STRAY_TEX = '99999999-9999-4999-8999-999999999999';
+const ENTRY_SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const ORPHAN_SCENE = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const LOCALE_TABLE = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+
+function writeAsset(rel: string, type: string, uuid: string, body = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+const sprite = (texUuid: string) =>
+ JSON.stringify({
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'S', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${texUuid}` } }] },
+ ],
+ });
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-cook-'));
+ writeAsset('assets/textures/used.png', 'texture', USED_TEX, 'USED');
+ writeAsset('assets/textures/orphan.png', 'texture', ORPHAN_TEX, 'ORPHAN');
+ writeAsset('assets/textures/stray.png', 'texture', STRAY_TEX, 'STRAY'); // referenced by nobody
+ writeAsset('assets/scenes/main.esscene', 'scene', ENTRY_SCENE, sprite(USED_TEX));
+ writeAsset('assets/scenes/orphan.esscene', 'scene', ORPHAN_SCENE, sprite(ORPHAN_TEX));
+ // Referenced by nothing — but locale tables load by code (Text carries keys,
+ // not paths), so the cook force-includes them instead of culling.
+ writeAsset('assets/i18n/zh-CN.eslocale', 'locale', LOCALE_TABLE,
+ JSON.stringify({ version: 1, locale: 'zh-CN', entries: { play: '开始' } }));
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+/** A solid RGBA PNG of an exact size — block alignment is a cook decision, so a
+ * test that wants a texture compressed has to ask for whole 4x4 blocks. */
+function solidPng(width: number, height: number, rgba: [number, number, number, number]): Buffer {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { PNG } = require('pngjs') as typeof import('pngjs');
+ const png = new PNG({ width, height });
+ for (let i = 0; i < width * height; i++) png.data.set(rgba, i * 4);
+ return PNG.sync.write(png);
+}
+
+describe('cookAssets (A4)', () => {
+ it('includes assets reachable from the entry scene and culls the rest', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ expect(res.ok).toBe(true);
+
+ // Reachable: the entry scene + its texture, plus the force-included locale table.
+ expect(res.included.sort()).toEqual([ENTRY_SCENE, USED_TEX, LOCALE_TABLE].sort());
+ // Culled: the orphan scene, its texture, and the totally-unreferenced one.
+ expect(res.unused.sort()).toEqual([ORPHAN_SCENE, ORPHAN_TEX, STRAY_TEX].sort());
+ });
+
+ it('stages reachable files + writes a runtime manifest; excludes culled files', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+
+ expect(existsSync(path.join(res.outDir, 'assets/textures/used.png'))).toBe(true);
+ expect(existsSync(path.join(res.outDir, 'assets/scenes/main.esscene'))).toBe(true);
+ expect(existsSync(path.join(res.outDir, 'assets/i18n/zh-CN.eslocale'))).toBe(true);
+ // Culled assets are not staged.
+ expect(existsSync(path.join(res.outDir, 'assets/textures/orphan.png'))).toBe(false);
+ expect(existsSync(path.join(res.outDir, 'assets/textures/stray.png'))).toBe(false);
+
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ expect(manifest.version).toBe('1.0');
+ const paths = manifest.entries.map((e) => e.path).sort();
+ expect(paths).toEqual(['assets/i18n/zh-CN.eslocale', 'assets/scenes/main.esscene', 'assets/textures/used.png']);
+ });
+
+ it('warns when an entry scene is not a tracked asset', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/missing.esscene'], outDir: 'build' });
+ expect(res.warnings.some((w) => w.includes('missing.esscene'))).toBe(true);
+ // Scene-reachable set is empty; the locale table still force-includes.
+ expect(res.included).toEqual([LOCALE_TABLE]);
+ });
+
+ it('records a contentHash + size for each staged asset', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ for (const e of manifest.entries) {
+ expect(e.contentHash, e.path).toMatch(/^[0-9a-f]{16}$/);
+ expect(e.size, e.path).toBeGreaterThan(0);
+ }
+ // The hash is over the exact staged bytes; 'USED' is the used.png body.
+ const tex = manifest.entries.find((e) => e.path === 'assets/textures/used.png')!;
+ expect(tex.contentHash).toBe(contentHashHex(new TextEncoder().encode('USED')));
+ expect(tex.size).toBe(4);
+ });
+
+ it('is deterministic: re-cooking yields identical content hashes', async () => {
+ const a = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ const b = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build2' });
+ const hashes = (p: string) =>
+ JSON.parse(readFileSync(p, 'utf8')).entries
+ .map((e: { path: string; contentHash: string }) => `${e.path}=${e.contentHash}`)
+ .sort();
+ expect(hashes(a.manifestPath!)).toEqual(hashes(b.manifestPath!));
+ });
+
+ it('gives identical bytes one hash (dedup foundation), distinct bytes distinct hashes', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-dedup-'));
+ try {
+ const A = '33333333-3333-4333-8333-333333333333';
+ const B = '44444444-4444-4444-8444-444444444444';
+ const C = '55555555-5555-4555-8555-555555555555';
+ const SC = '66666666-6666-4666-8666-666666666666';
+ const wa = (rel: string, type: string, uuid: string, body: string): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ wa('t/a.png', 'texture', A, 'SAME-BYTES');
+ wa('t/b.png', 'texture', B, 'SAME-BYTES'); // byte-identical to a, different uuid+path
+ wa('t/c.png', 'texture', C, 'OTHER-BYTES');
+ wa('s/main.esscene', 'scene', SC, JSON.stringify({
+ version: '1.0', name: 's', entities: [A, B, C].map((u, i) => ({
+ id: i + 1, name: `E${i}`, parent: null, children: [],
+ components: [{ type: 'Sprite', data: { texture: `@uuid:${u}` } }],
+ })),
+ }));
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out' });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const h = (p: string) => m.entries.find((e) => e.path === p)!.contentHash;
+ expect(h('t/a.png')).toBe(h('t/b.png')); // identical content → one physical identity
+ expect(h('t/a.png')).not.toBe(h('t/c.png')); // different content → different identity
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('content-addresses leaf assets (<hash><ext>), dedups identical bytes, keeps scenes by name', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-ca-'));
+ try {
+ const A = '33333333-3333-4333-8333-333333333333';
+ const B = '44444444-4444-4444-8444-444444444444';
+ const C = '55555555-5555-4555-8555-555555555555';
+ const SC = '66666666-6666-4666-8666-666666666666';
+ const wa = (rel: string, type: string, uuid: string, body: string): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ wa('t/a.png', 'texture', A, 'SAME-BYTES');
+ wa('t/b.png', 'texture', B, 'SAME-BYTES'); // byte-identical to a
+ wa('t/c.png', 'texture', C, 'OTHER-BYTES');
+ wa('s/main.esscene', 'scene', SC, JSON.stringify({
+ version: '1.0', name: 's', entities: [A, B, C].map((u, i) => ({
+ id: i + 1, name: `E${i}`, parent: null, children: [],
+ components: [{ type: 'Sprite', data: { texture: `@uuid:${u}` } }],
+ })),
+ }));
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', contentAddressed: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const byUuid = (u: string) => m.entries.find((e) => e.uuid === u)!;
+
+ // Leaf textures are content-addressed; scene keeps its logical name.
+ expect(byUuid(A).path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
+ expect(byUuid(SC).path).toBe('s/main.esscene');
+
+ // Byte-identical leaves collapse to one path (and one staged file); distinct content does not.
+ expect(byUuid(A).path).toBe(byUuid(B).path);
+ expect(byUuid(A).path).not.toBe(byUuid(C).path);
+ expect(existsSync(path.join(res.outDir, byUuid(A).path))).toBe(true);
+ expect(existsSync(path.join(res.outDir, byUuid(C).path))).toBe(true);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('compresses raster textures to KTX2 (compressTextures) + records compressedFormats', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-ktx2-'));
+ try {
+ const TEX = '77777777-7777-4777-8777-777777777777';
+ const SC = '88888888-8888-4888-8888-888888888888';
+ // 64x64: a block-compressed texture must be whole 4x4 blocks, so a source
+ // that is not (logo.png is 70x70) is shipped raw by design — see below.
+ const png = solidPng(64, 64, [200, 60, 40, 255]);
+ const wa = (rel: string, type: string, uuid: string, body: Buffer | string): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ wa('t/logo.png', 'texture', TEX, png);
+ wa('s/main.esscene', 'scene', SC, JSON.stringify({
+ version: '1.0', name: 's', entities: [
+ { id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] },
+ ],
+ }));
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const tex = m.entries.find((e) => e.uuid === TEX)!;
+
+ // The PNG was encoded to KTX2: extension, compressedFormats, and a valid container.
+ expect(tex.path).toMatch(/\.ktx2$/);
+ expect(tex.compressedFormats).toEqual(['astc-4x4', 'etc2-rgba8', 's3tc-dxt5']);
+ const bytes = readFileSync(path.join(res.outDir, tex.path));
+ const magic = [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb, 0x0d, 0x0a, 0x1a, 0x0a];
+ expect(magic.every((b, i) => bytes[i] === b)).toBe(true);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ it('honors per-texture compress=false: ships the raw PNG even when the build compresses', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-texopt-'));
+ try {
+ const TEX = '77777777-7777-4777-8777-777777777771';
+ const SC = '88888888-8888-4888-8888-888888888881';
+ const png = readFileSync(path.resolve(__dirname, '../../examples/hello-world/assets/textures/logo.png'));
+ const abs = path.join(r, 't/logo.png');
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, png);
+ // Per-asset opt-out — the same switch audio clips already have.
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: { compress: false } }));
+ const sc = path.join(r, 's/main.esscene');
+ mkdirSync(path.dirname(sc), { recursive: true });
+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));
+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));
+
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const tex = m.entries.find((e) => e.uuid === TEX)!;
+ expect(tex.path).toMatch(/\.png$/); // NOT .ktx2 — the asset opted out
+ expect(tex.compressedFormats).toBeUndefined();
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ it('downscales a texture to its Max Size at cook (longest side capped)', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-maxsize-'));
+ try {
+ const TEX = '77777777-7777-4777-8777-777777777772';
+ const SC = '88888888-8888-4888-8888-888888888882';
+ const png = readFileSync(path.resolve(__dirname, '../../examples/hello-world/assets/textures/logo.png'));
+ const src = decodePngImage('src', png);
+ expect(Math.max(src.width, src.height)).toBeGreaterThan(64); // fixture is larger than the cap
+ const abs = path.join(r, 't/logo.png');
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, png);
+ // maxSize + compress:false → ships a SHRUNK PNG we can measure directly.
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: { compress: false, maxSize: 64 } }));
+ const sc = path.join(r, 's/main.esscene');
+ mkdirSync(path.dirname(sc), { recursive: true });
+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));
+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));
+
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const tex = m.entries.find((e) => e.uuid === TEX)!;
+ const shrunk = decodePngImage('out', readFileSync(path.join(res.outDir, tex.path)));
+ expect(Math.max(shrunk.width, shrunk.height)).toBeLessThanOrEqual(64);
+ expect(Math.max(shrunk.width, shrunk.height)).toBeGreaterThan(32); // scaled to fit, not over-shrunk
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ it('ships a texture that is not whole 4x4 blocks raw, and says why', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-block-'));
+ try {
+ const TEX = '77777777-7777-4777-8777-777777777779';
+ const SC = '88888888-8888-4888-8888-888888888889';
+ // 70x70 — what hello-world ships, and what made every desktop package draw
+ // nothing: WebGPU refuses an ASTC texture that is not whole blocks.
+ const abs = path.join(r, 't/odd.png');
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, solidPng(70, 70, [10, 200, 40, 255]));
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid: TEX, version: '2.0', type: 'texture', importer: {} }));
+ const sc = path.join(r, 's/main.esscene');
+ mkdirSync(path.dirname(sc), { recursive: true });
+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));
+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));
+
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out', compressTextures: true });
+ const m = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest;
+ const tex = m.entries.find((e) => e.uuid === TEX)!;
+ expect(tex.path).toMatch(/\.png$/);
+ expect(tex.compressedFormats).toBeUndefined();
+ expect(res.warnings.some((w) => w.includes('70x70') && w.includes('multiple of 4'))).toBe(true);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('applies a per-platform texture override: one asset, smaller raw PNG for WeChat vs KTX2 for web', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-platov-'));
+ try {
+ const TEX = '77777777-7777-4777-8777-777777777773';
+ const SC = '88888888-8888-4888-8888-888888888883';
+ const png = solidPng(64, 64, [200, 60, 40, 255]);
+ const abs = path.join(r, 't/logo.png');
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, png);
+ // Default: compress (KTX2). WeChat override: ship a small raw PNG instead.
+ writeFileSync(`${abs}.meta`, JSON.stringify({
+ uuid: TEX, version: '2.0', type: 'texture',
+ importer: { compress: true, overrides: { wechat: { enabled: true, compress: false, maxSize: 64 } } },
+ }));
+ const sc = path.join(r, 's/main.esscene');
+ mkdirSync(path.dirname(sc), { recursive: true });
+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));
+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));
+
+ const web = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out-web', compressTextures: true, platform: 'web' });
+ const wechat = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out-wx', compressTextures: true, platform: 'wechat' });
+ const texOf = (res: Awaited<ReturnType<typeof cookAssets>>) =>
+ (JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest).entries.find((e) => e.uuid === TEX)!;
+
+ expect(texOf(web).path).toMatch(/\.ktx2$/); // web: default → compressed
+ const wx = texOf(wechat);
+ expect(wx.path).toMatch(/\.png$/); // wechat override: raw PNG…
+ const shrunk = decodePngImage('wx', readFileSync(path.join(wechat.outDir, wx.path)));
+ expect(Math.max(shrunk.width, shrunk.height)).toBeLessThanOrEqual(64); // …downscaled to its cap
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 30_000);
+
+ it('follows PATH refs: scene → material (project path) → shader + texture (dir-relative)', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-pathref-'));
+ try {
+ const SC = 'aaaa1111-1111-4111-8111-111111111111';
+ const MAT = 'aaaa2222-2222-4222-8222-222222222222';
+ const SHADER = 'aaaa3333-3333-4333-8333-333333333333';
+ const TEX = 'aaaa4444-4444-4444-8444-444444444444';
+ const ORPHAN = 'aaaa5555-5555-4555-8555-555555555555';
+ const wa = (rel: string, type: string, uuid: string, body: string): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ // The real-content shape: the scene names the material by PROJECT PATH (no
+ // @uuid:), and the material names its shader + texture RELATIVE to itself.
+ wa('assets/materials/m.esmaterial', 'material', MAT, JSON.stringify({
+ version: '1.0', type: 'material', shader: 'm.esshader',
+ properties: { u_mask: 'green.png', u_mode: 'additive' },
+ }));
+ wa('assets/materials/m.esshader', 'shader', SHADER,
+ '#pragma shader "M"\n#pragma fragment\nvoid main() {}\n#pragma end\n');
+ wa('assets/materials/green.png', 'texture', TEX, 'G');
+ wa('assets/materials/orphan.png', 'texture', ORPHAN, 'O');
+ wa('s/main.esscene', 'scene', SC, JSON.stringify({
+ version: '1.0', name: 's', entities: [
+ { id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { material: 'assets/materials/m.esmaterial' } }] },
+ ],
+ }));
+
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out' });
+ expect(res.included.sort()).toEqual([SC, MAT, SHADER, TEX].sort());
+ expect(res.unused).toEqual([ORPHAN]);
+ // A twin-less shader ships GL-only: the cook says so.
+ expect(res.warnings.some((w) => w.includes('no WGSL twin'))).toBe(true);
+
+ // Content addressing renames the physical file but keeps the LOGICAL
+ // identity in sourcePath — what path refs name at runtime.
+ const ca = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out-ca', contentAddressed: true });
+ const m = JSON.parse(readFileSync(ca.manifestPath!, 'utf8')) as AssetManifest & {
+ entries: Array<{ uuid: string; path: string; sourcePath: string }>;
+ };
+ const mat = m.entries.find((e) => e.uuid === MAT)!;
+ expect((mat as { sourcePath?: string }).sourcePath).toBe('assets/materials/m.esmaterial');
+ expect(mat.path).toMatch(/^assets\/[0-9a-f]{16}\.esmaterial$/);
+
+ // The staged material's RELATIVE refs were rewritten to logical project
+ // paths (content addressing destroys the directory structure relative
+ // resolution relies on); non-asset strings pass through untouched.
+ const stagedMat = JSON.parse(readFileSync(path.join(ca.outDir, mat.path), 'utf8')) as {
+ shader: string; properties: Record<string, string>;
+ };
+ expect(stagedMat.shader).toBe('assets/materials/m.esshader');
+ expect(stagedMat.properties.u_mask).toBe('assets/materials/green.png');
+ expect(stagedMat.properties.u_mode).toBe('additive');
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('bare uuid refs (anim-frame form) create edges only when they name a real asset', async () => {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-bareuuid-'));
+ try {
+ const SC = 'bbbb1111-1111-4111-8111-111111111111';
+ const CLIP = 'bbbb2222-2222-4222-8222-222222222222';
+ const FRAME = 'bbbb3333-3333-4333-8333-333333333333';
+ const NOT_AN_ASSET = 'bbbb9999-9999-4999-8999-999999999999'; // uuid-shaped entity id
+ const wa = (rel: string, type: string, uuid: string, body: string): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ wa('a/frame.png', 'texture', FRAME, 'F');
+ wa('a/idle.esanim', 'animclip', CLIP, JSON.stringify({
+ version: '1.0', frames: [FRAME], sourceId: NOT_AN_ASSET,
+ }));
+ wa('s/main.esscene', 'scene', SC, JSON.stringify({
+ version: '1.0', name: 's', entities: [
+ { id: 1, name: 'E', parent: null, children: [], components: [{ type: 'SpriteAnimator', data: { clip: 'a/idle.esanim' } }] },
+ ],
+ }));
+ const res = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out' });
+ expect(res.included.sort()).toEqual([SC, CLIP, FRAME].sort());
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('cookAssets — auto-atlas (<name>.atlas folder convention)', () => {
+ const TEX_A = 'cccc1111-1111-4111-8111-111111111111';
+ const TEX_B = 'cccc2222-2222-4222-8222-222222222222';
+ const LOOSE = 'cccc3333-3333-4333-8333-333333333333';
+ const SCENE = 'cccc4444-4444-4444-8444-444444444444';
+
+ function makeAtlasProject(): string {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-atlas-'));
+ const wa = (rel: string, type: string, uuid: string, body: string | Buffer): void => {
+ const abs = path.join(r, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+ };
+ wa('assets/sprites/heroes.atlas/a.png', 'texture', TEX_A, solidPng(4, 4, [255, 0, 0, 255]));
+ wa('assets/sprites/heroes.atlas/b.png', 'texture', TEX_B, solidPng(4, 4, [0, 255, 0, 255]));
+ wa('assets/textures/loose.png', 'texture', LOOSE, solidPng(2, 2, [0, 0, 255, 255]));
+ wa('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({
+ version: '1.0', name: 's', entities: [
+ { id: 1, name: 'A', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX_A}` } }] },
+ { id: 2, name: 'B', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX_B}` } }] },
+ { id: 3, name: 'L', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${LOOSE}` } }] },
+ ],
+ }));
+ return r;
+ }
+
+ it('packs atlas-folder PNGs into one staged page with frame metadata', async () => {
+ const r = makeAtlasProject();
+ try {
+ const res = await cookAssets(r, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'out', atlasTextures: true });
+ expect(res.ok).toBe(true);
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string; sourcePath: string;
+ atlas?: { page: number; frame: { x: number; y: number; width: number; height: number }; pageWidth: number; pageHeight: number } }>;
+ };
+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;
+ const b = manifest.entries.find((e) => e.uuid === TEX_B)!;
+ const loose = manifest.entries.find((e) => e.uuid === LOOSE)!;
+
+ // Both frames point at the SAME page file; the loose texture stages standalone.
+ expect(a.path).toBe('assets/sprites/heroes.atlas.page0.png');
+ expect(b.path).toBe(a.path);
+ expect(a.sourcePath).toBe('assets/sprites/heroes.atlas/a.png');
+ expect(loose.path).toBe('assets/textures/loose.png');
+ expect(loose.atlas).toBeUndefined();
+ expect(existsSync(path.join(res.outDir, a.path))).toBe(true);
+ // Frame sources are not staged as standalone files.
+ expect(existsSync(path.join(res.outDir, 'assets/sprites/heroes.atlas/a.png'))).toBe(false);
+
+ // Distinct frames inside a shared page whose size both entries agree on.
+ expect(a.atlas!.pageWidth).toBe(b.atlas!.pageWidth);
+ expect(a.atlas!.frame).not.toEqual(b.atlas!.frame);
+
+ // Decode the staged page: each frame's pixels are its source's color.
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { PNG } = require('pngjs') as typeof import('pngjs');
+ const page = PNG.sync.read(readFileSync(path.join(res.outDir, a.path)));
+ expect(page.width).toBe(a.atlas!.pageWidth);
+ const at = (f: { x: number; y: number }) => [...page.data.subarray((f.y * page.width + f.x) * 4, (f.y * page.width + f.x) * 4 + 4)];
+ expect(at(a.atlas!.frame)).toEqual([255, 0, 0, 255]);
+ expect(at(b.atlas!.frame)).toEqual([0, 255, 0, 255]);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('stages atlas-folder textures standalone when atlasTextures is off', async () => {
+ const r = makeAtlasProject();
+ try {
+ const res = await cookAssets(r, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'out' });
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string; atlas?: unknown }>;
+ };
+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;
+ expect(a.path).toBe('assets/sprites/heroes.atlas/a.png');
+ expect(a.atlas).toBeUndefined();
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+
+ it('content-addressed staging names the page by its hash, shared by both frames', async () => {
+ const r = makeAtlasProject();
+ try {
+ const res = await cookAssets(r, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'out',
+ atlasTextures: true, contentAddressed: true,
+ });
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string; contentHash: string; sourcePath: string; atlas?: unknown }>;
+ };
+ const a = manifest.entries.find((e) => e.uuid === TEX_A)!;
+ const b = manifest.entries.find((e) => e.uuid === TEX_B)!;
+ expect(a.path).toBe(`assets/${a.contentHash}.png`);
+ expect(b.path).toBe(a.path);
+ expect(a.sourcePath).toBe('assets/sprites/heroes.atlas/a.png');
+ expect(existsSync(path.join(res.outDir, a.path))).toBe(true);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/pipeline/tests/cooked-verify-fixture.test.ts b/pipeline/tests/cooked-verify-fixture.test.ts
new file mode 100644
index 000000000..fa5794a23
--- /dev/null
+++ b/pipeline/tests/cooked-verify-fixture.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Produces the cooked build that headless-cooked-verify.mjs renders — a
+ * content-addressed web export of a green-KTX2 sprite scene, built with the
+ * real SDK dist + engine/basis wasm. Guarded by ESTELLA_COOK_FIXTURE so it's
+ * not part of the normal unit suite; the verify:render:cooked script sets it.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdirSync, writeFileSync, copyFileSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const OUT = path.resolve(HERE, '..', '.cooked-verify');
+const SRC = path.resolve(HERE, '..', '.cooked-src');
+const TEX = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const SCN = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const MAT = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const SHD = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+// A user material chain referenced entirely by PATH: the scene names the
+// material by project path, the material names its shader + a texture RELATIVE
+// to itself — the forms real content uses. The shader paints solid red via a
+// reflected param, so the cooked render proves the whole logical→staged
+// resolution (dep-graph inclusion, cook ref rewrite, runtime pathMap+catalog).
+const TINT_SHADER = `#pragma shader "CookTint"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_tint color default(1,1,1,1)
+#pragma param u_tex texture default(white)
+
+#pragma fragment
+precision mediump float;
+in vec4 v_color;
+in vec2 v_texCoord;
+out vec4 fragColor;
+void main() { fragColor = u_tint; }
+#pragma end
+`;
+
+describe.skipIf(!process.env.ESTELLA_COOK_FIXTURE)('cooked-verify fixture', () => {
+ it('cooks a content-addressed build: green KTX2 sprite + path-ref material chain', async () => {
+ rmSync(SRC, { recursive: true, force: true });
+ rmSync(OUT, { recursive: true, force: true });
+
+ mkdirSync(path.join(SRC, 'assets'), { recursive: true });
+ copyFileSync(path.resolve(HERE, '..', 'public', 'scenes', 'ktx2-test', 'green.ktx2'),
+ path.join(SRC, 'assets', 'green.ktx2'));
+ writeFileSync(path.join(SRC, 'assets', 'green.ktx2.meta'), meta(TEX, 'texture'));
+ writeFileSync(path.join(SRC, 'assets', 'tint.esshader'), TINT_SHADER);
+ writeFileSync(path.join(SRC, 'assets', 'tint.esshader.meta'), meta(SHD, 'shader'));
+ writeFileSync(path.join(SRC, 'assets', 'red.esmaterial'), JSON.stringify({
+ version: '1.0', type: 'material', shader: 'tint.esshader',
+ properties: { u_tint: { r: 1, g: 0, b: 0, a: 1 }, u_tex: 'green.ktx2' },
+ }));
+ writeFileSync(path.join(SRC, 'assets', 'red.esmaterial.meta'), meta(MAT, 'material'));
+
+ mkdirSync(path.join(SRC, 'scenes'), { recursive: true });
+ writeFileSync(path.join(SRC, 'scenes', 'main.esscene'), JSON.stringify({
+ version: '1.0', name: 'Main', entities: [
+ { id: 0, name: 'Camera', parent: null, children: [], visible: true, components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },
+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },
+ ] },
+ { id: 1, name: 'GreenQuad', parent: null, children: [], visible: true, components: [
+ { type: 'Transform', data: { position: { x: -150, y: 0, z: 0 } } },
+ { type: 'Sprite', data: { size: { x: 250, y: 250 }, color: { r: 1, g: 1, b: 1, a: 1 }, texture: `@uuid:${TEX}` } },
+ ] },
+ { id: 2, name: 'RedMaterialQuad', parent: null, children: [], visible: true, components: [
+ { type: 'Transform', data: { position: { x: 150, y: 0, z: 0 } } },
+ { type: 'Sprite', data: { size: { x: 250, y: 250 }, color: { r: 1, g: 1, b: 1, a: 1 }, material: 'assets/red.esmaterial' } },
+ ] },
+ ],
+ }));
+ writeFileSync(path.join(SRC, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+
+ mkdirSync(path.join(SRC, 'src'), { recursive: true });
+ writeFileSync(path.join(SRC, 'src', 'main.ts'), 'export {};\n');
+
+ const res = await exportGame({
+ root: SRC,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: path.resolve(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts'),
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.resolve(HERE, '..', '..', 'sdk', 'dist'),
+ wasmDir: path.resolve(HERE, '..', '..', 'build', 'wasm', 'web'),
+ outDir: OUT,
+ title: 'Cooked Verify',
+ contentAddressed: true,
+ });
+ expect(res.ok, res.errors.join('; ')).toBe(true);
+ }, 120_000);
+});
diff --git a/pipeline/tests/document-ref-cook-deps.test.ts b/pipeline/tests/document-ref-cook-deps.test.ts
new file mode 100644
index 000000000..ad19d8981
--- /dev/null
+++ b/pipeline/tests/document-ref-cook-deps.test.ts
@@ -0,0 +1,208 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Regression: an asset named ONLY from inside another asset's document is
+ * still cooked. A baked environment names its reflection atlas and an
+ * animator controller names the clips its states play; nothing in the scene
+ * graph mentions either, so a type left out of the dep scan ships the
+ * document and 404s what it needs — in the build only, since the editor
+ * serves the whole project.
+ *
+ * Neither asset here is referenced by the scene as well. That is the point:
+ * examples/sprite-animation happens to list its clips in the scene too, so
+ * the missing controller → clip edge was invisible for as long as it existed.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase } from '../src/assets/assetDb';
+import { cookAssets } from '../src/assets/cookAssets';
+
+let root: string;
+
+const SPECULAR = '11111111-1111-4111-8111-111111111111';
+const ESENV = '22222222-2222-4222-8222-222222222222';
+const CLIP = '33333333-3333-4333-8333-333333333333';
+const CONTROLLER = '44444444-4444-4444-8444-444444444444';
+const FRAME = '55555555-5555-4555-8555-555555555555';
+const FNT = '66666666-6666-4666-8666-666666666666';
+const FNT_PAGE = '77777777-7777-4777-8777-777777777777';
+const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+function writeAsset(rel: string, type: string, uuid: string, body: string | Uint8Array = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+// The importer writes the atlas as a SIBLING file name, resolved against the
+// document — not as a project path.
+const esenv = JSON.stringify({
+ version: 1, irradiance: new Array(27).fill(0), specular: 'sky_env.png',
+ faceSize: 8, mipCount: 1, maxRange: 8,
+});
+
+const controller = JSON.stringify({
+ parameters: [], initialState: 'Idle',
+ states: [{ name: 'Idle', clip: 'assets/anim/idle.esanim', loop: true, transitions: [] }],
+});
+
+// A bitmap font is TEXT, and names its page image the way a spine atlas does:
+// as a sibling, resolved against the .fnt's own directory at load.
+const fnt = [
+ 'info face="tiny" size=8',
+ 'common lineHeight=8 base=8 scaleW=16 scaleH=8 pages=1',
+ 'page id=0 file="tiny.png"',
+ 'chars count=1',
+ 'char id=65 x=0 y=0 width=8 height=8 xoffset=0 yoffset=0 xadvance=8 page=0 chnl=15',
+ '',
+].join('\n');
+
+const clip = JSON.stringify({
+ version: '1.2', name: 'idle', fps: 8,
+ frames: [{ texture: 'assets/anim/frame0.png', duration: 1 }],
+});
+
+// The scene names the environment and the controller, and NOTHING else.
+const scene = JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [
+ {
+ id: 1, name: 'Sky', parent: null, children: [],
+ components: [{ type: 'Light2D', data: { type: 2, environment: 'assets/env/sky.esenv' } }],
+ },
+ {
+ id: 2, name: 'Actor', parent: null, children: [],
+ components: [{ type: 'UIController', data: { controller: 'assets/anim/player.esanimator' } }],
+ },
+ {
+ id: 3, name: 'Label', parent: null, children: [],
+ components: [{ type: 'BitmapText', data: { text: 'A', font: 'assets/fonts/tiny.fnt' } }],
+ },
+ ],
+});
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-docrefs-'));
+ writeAsset('assets/env/sky_env.png', 'texture', SPECULAR, 'PNG');
+ writeAsset('assets/env/sky.esenv', 'environment', ESENV, esenv);
+ writeAsset('assets/anim/frame0.png', 'texture', FRAME, 'PNG');
+ writeAsset('assets/anim/idle.esanim', 'animclip', CLIP, clip);
+ writeAsset('assets/anim/player.esanimator', 'animatorcontroller', CONTROLLER, controller);
+ writeAsset('assets/fonts/tiny.png', 'texture', FNT_PAGE, 'PNG');
+ writeAsset('assets/fonts/tiny.fnt', 'bitmapFont', FNT, fnt);
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, scene);
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+describe('assets named only inside another document are cooked', () => {
+ it('links environment → its reflection atlas, resolved as a sibling', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.deps[ESENV]).toContain(SPECULAR);
+ });
+
+ it('links a bitmap font → the page image it names', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.deps[FNT]).toContain(FNT_PAGE);
+ });
+
+ it('links animator controller → the clip its state plays', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.deps[CONTROLLER]).toContain(CLIP);
+ });
+
+ it('ships both, and the clip\'s own frame through it', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ expect(res.ok).toBe(true);
+ expect(res.included).toEqual(expect.arrayContaining([SCENE, ESENV, SPECULAR, CONTROLLER, CLIP, FRAME, FNT, FNT_PAGE]));
+ expect(res.unused).toEqual([]);
+ });
+
+ // Shipping the atlas is only half of it: content-addressed staging moves the
+ // document away from its sibling, so a ref left as-authored resolves to nothing
+ // and the reflection is silently lost. The staged copy must name the asset.
+ it('rewrites the staged environment\'s sibling ref to a path the package has', async () => {
+ const res = await cookAssets(root, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build-ca', contentAddressed: true,
+ });
+ expect(res.ok).toBe(true);
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string; sourcePath: string }>;
+ };
+ const env = manifest.entries.find((e) => e.uuid === ESENV)!;
+ const staged = JSON.parse(readFileSync(path.join(res.outDir, env.path), 'utf8')) as { specular: string };
+ expect(staged.specular).toBe('assets/env/sky_env.png');
+ expect(manifest.entries.some((e) => e.sourcePath === staged.specular)).toBe(true);
+
+ // The bitmap font says the same thing in text rather than JSON.
+ const font = manifest.entries.find((e) => e.uuid === FNT)!;
+ const stagedFnt = readFileSync(path.join(res.outDir, font.path), 'utf8');
+ expect(stagedFnt).toContain('file="assets/fonts/tiny.png"');
+
+ // And the package is self-consistent: nothing it staged names a path it lacks.
+ expect(res.warnings.filter((w) => /does not carry/.test(w))).toEqual([]);
+ });
+
+ // The mirror image: a `builtin:` ref names code, so the package is right not to
+ // carry it. It has to reach the runtime spelled as authored — rewritten toward a
+ // path, it would resolve to a file nothing ever staged.
+ it('leaves a built-in mesh ref alone rather than calling it dangling', async () => {
+ const lone = mkdtempSync(path.join(tmpdir(), 'estella-builtin-'));
+ const prev = root;
+ root = lone;
+ try {
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [{
+ id: 1, name: 'Cube', parent: null, children: [],
+ components: [{ type: 'Mesh2D', data: { mesh: 'builtin:cube', lit: true } }],
+ }],
+ }));
+ const res = await cookAssets(lone, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build', contentAddressed: true,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.filter((w) => /does not carry/.test(w))).toEqual([]);
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string }>;
+ };
+ const staged = readFileSync(
+ path.join(res.outDir, manifest.entries.find((e) => e.uuid === SCENE)!.path), 'utf8');
+ expect(staged).toContain('builtin:cube');
+ } finally {
+ root = prev;
+ rmSync(lone, { recursive: true, force: true });
+ }
+ });
+
+ // The backstop for the type nobody has wired up yet: whatever the document is,
+ // a path it names that the package does not carry is a 404 waiting to happen.
+ it('reports a staged document that names an asset the package lacks', async () => {
+ const lone = mkdtempSync(path.join(tmpdir(), 'estella-dangling-'));
+ const prev = root;
+ root = lone;
+ try {
+ writeAsset('assets/env/gone.esenv', 'environment', ESENV, JSON.stringify({
+ version: 1, irradiance: new Array(27).fill(0), specular: 'nowhere.png',
+ faceSize: 8, mipCount: 1, maxRange: 8,
+ }));
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [{
+ id: 1, name: 'Sky', parent: null, children: [],
+ components: [{ type: 'Light2D', data: { type: 2, environment: 'assets/env/gone.esenv' } }],
+ }],
+ }));
+ const res = await cookAssets(lone, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ expect(res.warnings.some((w) => /gone\.esenv: names 'nowhere\.png'/.test(w))).toBe(true);
+ } finally {
+ root = prev;
+ rmSync(lone, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/pipeline/tests/environment-import.test.ts b/pipeline/tests/environment-import.test.ts
new file mode 100644
index 000000000..0293c5a25
--- /dev/null
+++ b/pipeline/tests/environment-import.test.ts
@@ -0,0 +1,272 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a `.hdr` panorama becomes: nine irradiance coefficients and a
+ * prefiltered octahedral atlas.
+ *
+ * These are the claims a pixel gate cannot make. A rendered sphere says the
+ * lighting changed; only arithmetic says it changed to the RIGHT value — and the
+ * one identity the whole design rests on (a constant environment reconstructs as
+ * that constant, which is what keeps existing scenes pixel-identical) is checked
+ * here rather than inferred from a screenshot.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ decodeRadianceHdr, projectIrradianceSH, evalIrradianceSH, samplePanorama,
+ octEncode, octDecode, encodeRgbm, decodeRgbm, atlasLayout, prefilterOctahedral,
+ importEnvironment, mipCountFor, ENV_MAX_RANGE,
+ type Panorama,
+} from '../src/assets/environmentImport';
+
+/** A Radiance file in the flat (uncompressed) encoding, one RGBE per pixel. */
+function flatHdr(width: number, height: number,
+ pixel: (x: number, y: number) => [number, number, number]): Uint8Array {
+ const header = Buffer.from(`#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y ${height} +X ${width}\n`);
+ const body = Buffer.alloc(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const [r, g, b] = pixel(x, y);
+ const peak = Math.max(r, g, b);
+ let e = 0;
+ let scale = 0;
+ if (peak > 1e-9) {
+ e = Math.ceil(Math.log2(peak)) + 128;
+ scale = 256 / Math.pow(2, e - 128);
+ }
+ const at = (y * width + x) * 4;
+ body[at] = Math.min(255, Math.floor(r * scale));
+ body[at + 1] = Math.min(255, Math.floor(g * scale));
+ body[at + 2] = Math.min(255, Math.floor(b * scale));
+ body[at + 3] = e;
+ }
+ }
+ return new Uint8Array(Buffer.concat([header, body]));
+}
+
+/** The same panorama without the file round trip, for the convolution tests. */
+function panorama(width: number, height: number,
+ pixel: (x: number, y: number) => [number, number, number]): Panorama {
+ const rgb = new Float32Array(width * height * 3);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const [r, g, b] = pixel(x, y);
+ const at = (y * width + x) * 3;
+ rgb[at] = r; rgb[at + 1] = g; rgb[at + 2] = b;
+ }
+ }
+ return { width, height, rgb };
+}
+
+describe('Radiance decode', () => {
+ it('reads a flat scanline back as the values it was given', () => {
+ const env = decodeRadianceHdr(flatHdr(4, 2, (x, y) => [x + 1, y + 1, 0.5]));
+ expect(env.width).toBe(4);
+ expect(env.height).toBe(2);
+ // RGBE is a shared 8-bit mantissa, so the round trip is close, not exact.
+ expect(env.rgb[0]).toBeCloseTo(1, 1);
+ expect(env.rgb[1]).toBeCloseTo(1, 1);
+ expect(env.rgb[(1 * 4 + 3) * 3]).toBeCloseTo(4, 1);
+ });
+
+ it('reads the adaptive-RLE encoding as the same picture', () => {
+ // 8 wide is the narrowest width the RLE header is legal at.
+ const width = 8;
+ const values = Array.from({ length: width }, (_, x) => 32 + x * 4);
+ const header = Buffer.from(`#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 1 +X ${width}\n`);
+ const rle: number[] = [2, 2, 0, width];
+ for (let channel = 0; channel < 4; channel++) {
+ rle.push(width);
+ for (let x = 0; x < width; x++) rle.push(channel === 3 ? 128 : values[x]!);
+ }
+ const env = decodeRadianceHdr(new Uint8Array(Buffer.concat([header, Buffer.from(rle)])));
+ expect(env.width).toBe(width);
+ // e = 128 means a scale of 2^-8, so each stored byte reads back as byte/256.
+ expect(env.rgb[0]).toBeCloseTo(32 / 256, 5);
+ expect(env.rgb[(width - 1) * 3]).toBeCloseTo((32 + 7 * 4) / 256, 5);
+ });
+
+ it('refuses a file that is not Radiance', () => {
+ expect(() => decodeRadianceHdr(new Uint8Array([1, 2, 3, 4]))).toThrow(/Radiance/);
+ });
+});
+
+describe('irradiance coefficients', () => {
+ // THE identity the design rests on: a constant environment must come back as
+ // that same constant in every direction. If this drifts, every existing lit
+ // scene changes brightness the day an environment is attached.
+ it('reconstructs a constant environment as that constant', () => {
+ const sh = projectIrradianceSH(panorama(64, 32, () => [0.25, 0.5, 0.75]));
+ for (const [x, y, z] of [[0, 1, 0], [0, -1, 0], [1, 0, 0], [0, 0, 1],
+ [0.577, 0.577, 0.577]] as const) {
+ const [r, g, b] = evalIrradianceSH(sh, x, y, z);
+ expect(r).toBeCloseTo(0.25, 2);
+ expect(g).toBeCloseTo(0.5, 2);
+ expect(b).toBeCloseTo(0.75, 2);
+ }
+ });
+
+ it('puts a lit upper hemisphere above a dark lower one', () => {
+ const sh = projectIrradianceSH(panorama(64, 32, (_x, y) => (y < 16 ? [1, 1, 1] : [0, 0, 0])));
+ const up = evalIrradianceSH(sh, 0, 1, 0)[0];
+ const down = evalIrradianceSH(sh, 0, -1, 0)[0];
+ const side = evalIrradianceSH(sh, 1, 0, 0)[0];
+ // Analytic: a white upper hemisphere gives E(up)/π = 1, E(side)/π = 0.5,
+ // E(down)/π = 0. Order-2 SH rings, so the ends land near rather than on them.
+ expect(up).toBeGreaterThan(0.9);
+ expect(side).toBeCloseTo(0.5, 1);
+ expect(down).toBeLessThan(0.1);
+ expect(up).toBeGreaterThan(side);
+ expect(side).toBeGreaterThan(down);
+ });
+
+ it('answers with the colour that lies in that direction, not the average', () => {
+ // Red on the +Z half of the sphere (the image's centre column), green behind.
+ const sh = projectIrradianceSH(panorama(64, 32,
+ (x) => (x > 16 && x < 48 ? [1, 0, 0] : [0, 1, 0])));
+ const front = evalIrradianceSH(sh, 0, 0, 1);
+ const back = evalIrradianceSH(sh, 0, 0, -1);
+ expect(front[0]).toBeGreaterThan(front[1]);
+ expect(back[1]).toBeGreaterThan(back[0]);
+ });
+});
+
+describe('octahedral mapping', () => {
+ it('round-trips every direction it is given', () => {
+ const third = 1 / Math.sqrt(3);
+ for (const d of [[0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0], [0, 0, 1], [0, 0, -1],
+ [third, third, third], [-third, -third, third]]) {
+ const [u, v] = octEncode(d[0], d[1], d[2]);
+ expect(u).toBeGreaterThanOrEqual(0);
+ expect(u).toBeLessThanOrEqual(1);
+ const back = octDecode(u, v);
+ for (let i = 0; i < 3; i++) expect(back[i]).toBeCloseTo(d[i]!, 5);
+ }
+ });
+
+ it('stays continuous just outside the square, which is what the border is for', () => {
+ // The texel one step past the edge must be the direction its neighbour across
+ // the fold sees — otherwise a bilinear tap at the seam blends in nothing.
+ const inside = octDecode(0.02, 0.5);
+ const outside = octDecode(-0.02, 0.5);
+ const dot = inside[0] * outside[0] + inside[1] * outside[1] + inside[2] * outside[2];
+ expect(dot).toBeGreaterThan(0.99);
+ });
+});
+
+describe('RGBM', () => {
+ it('round-trips values across the range within a percent of full scale', () => {
+ for (const v of [0, 0.01, 0.1, 0.5, 1, 3, 7.9]) {
+ const out = new Uint8Array(4);
+ encodeRgbm(v, v * 0.5, 0, ENV_MAX_RANGE, out, 0);
+ const [r, g, b] = decodeRgbm(out[0]!, out[1]!, out[2]!, out[3]!, ENV_MAX_RANGE);
+ expect(Math.abs(r - v)).toBeLessThan(0.08);
+ expect(Math.abs(g - v * 0.5)).toBeLessThan(0.08);
+ expect(b).toBeCloseTo(0, 3);
+ }
+ });
+
+ it('clamps rather than wrapping above the range', () => {
+ const out = new Uint8Array(4);
+ encodeRgbm(100, 100, 100, ENV_MAX_RANGE, out, 0);
+ const [r] = decodeRgbm(out[0]!, out[1]!, out[2]!, out[3]!, ENV_MAX_RANGE);
+ expect(r).toBeCloseTo(ENV_MAX_RANGE, 1);
+ });
+});
+
+describe('prefiltered atlas', () => {
+ it('stops before a face gets too small to be an environment', () => {
+ // A 4-texel octahedral face is not a blurrier sky, it is a different one.
+ expect(mipCountFor(128)).toBe(5);
+ expect(mipCountFor(32)).toBe(3);
+ expect(mipCountFor(8)).toBe(1);
+ expect(mipCountFor(128, 2)).toBe(2);
+ });
+
+ it('stacks the mips with a border between them', () => {
+ const { width, height, offsets } = atlasLayout(128, 6);
+ expect(width).toBe(130);
+ expect(height).toBe(130 + 66 + 34 + 18 + 10 + 6);
+ expect(offsets[0]).toBe(0);
+ expect(offsets[1]).toBe(130);
+ // The closed form the shader uses instead of a loop.
+ for (let mip = 0; mip < 6; mip++) {
+ expect(offsets[mip]).toBe(2 * 128 * (1 - Math.pow(2, -mip)) + 2 * mip);
+ }
+ });
+
+ it('reproduces the source in mip 0 and averages it away by the last', () => {
+ // Sky above, ground below: a mirror sees the half it faces; a fully rough
+ // surface sees the whole sphere at once.
+ const env = panorama(64, 32, (_x, y) => (y < 16 ? [0, 0, 4] : [1, 0, 0]));
+ const { width, rgba } = prefilterOctahedral(env, 16, 4, ENV_MAX_RANGE);
+ const { offsets } = atlasLayout(16, 4);
+ const read = (mip: number, dx: number, dy: number, dz: number): [number, number, number] => {
+ const size = 16 >> mip;
+ const [u, v] = octEncode(dx, dy, dz);
+ const px = Math.min(size - 1, Math.floor(u * size)) + 1;
+ const py = offsets[mip]! + Math.min(size - 1, Math.floor(v * size)) + 1;
+ const at = (py * width + px) * 4;
+ return decodeRgbm(rgba[at]!, rgba[at + 1]!, rgba[at + 2]!, rgba[at + 3]!, ENV_MAX_RANGE);
+ };
+
+ const mirrorUp = read(0, 0, 1, 0);
+ expect(mirrorUp[2]).toBeGreaterThan(3);
+ expect(mirrorUp[0]).toBeLessThan(0.2);
+ const mirrorDown = read(0, 0, -1, 0);
+ expect(mirrorDown[0]).toBeGreaterThan(0.8);
+ expect(mirrorDown[2]).toBeLessThan(0.2);
+
+ // The roughest mip has seen both halves from either side, so the two agree.
+ const roughUp = read(3, 0, 1, 0);
+ const roughDown = read(3, 0, -1, 0);
+ expect(roughUp[2]).toBeGreaterThan(0.5);
+ expect(roughDown[2]).toBeGreaterThan(0.5);
+ expect(Math.abs(roughUp[2] - roughDown[2])).toBeLessThan(1.5);
+ });
+
+ it('fills the border with the neighbour across the fold', () => {
+ const env = panorama(64, 32, (_x, y) => (y < 16 ? [0, 0, 4] : [1, 0, 0]));
+ const { width, rgba } = prefilterOctahedral(env, 8, 1, ENV_MAX_RANGE);
+ const texel = (x: number, y: number): [number, number, number] => {
+ const at = (y * width + x) * 4;
+ return decodeRgbm(rgba[at]!, rgba[at + 1]!, rgba[at + 2]!, rgba[at + 3]!, ENV_MAX_RANGE);
+ };
+ // Column 0 is the border; column 1 is the face's first real texel. Both look
+ // outward along -X near the horizon, so neither is the untouched black an
+ // unfilled border would be.
+ for (let y = 1; y <= 8; y++) {
+ const border = texel(0, y);
+ expect(border[0] + border[1] + border[2]).toBeGreaterThan(0.1);
+ }
+ });
+});
+
+describe('importEnvironment', () => {
+ it('produces a document and an atlas that describe each other', () => {
+ const hdr = flatHdr(32, 16, (_x, y) => (y < 8 ? [2, 2, 2] : [0, 0, 0]));
+ const result = importEnvironment(hdr, 'studio', { faceSize: 32, mipCount: 3 });
+ expect(result.atlasName).toBe('studio_env.png');
+ expect(result.document.irradiance).toHaveLength(27);
+ expect(result.document.faceSize).toBe(32);
+ expect(result.document.mipCount).toBe(3);
+ expect(result.document.maxRange).toBe(ENV_MAX_RANGE);
+ // A PNG, and one whose size the layout predicts.
+ expect(Array.from(result.atlasBytes.subarray(1, 4))).toEqual([0x50, 0x4e, 0x47]);
+ const up = evalIrradianceSH(result.document.irradiance, 0, 1, 0)[0];
+ const down = evalIrradianceSH(result.document.irradiance, 0, -1, 0)[0];
+ expect(up).toBeGreaterThan(down + 1);
+ });
+});
+
+describe('panorama sampling', () => {
+ it('reads the image centre as +Z and row 0 as +Y', () => {
+ const env = panorama(8, 4, (x, y) => [x, y, 0]);
+ const out = new Float32Array(3);
+ samplePanorama(env, 0, 1, 0, out);
+ expect(out[1]).toBeLessThan(0.5);
+ samplePanorama(env, 0, -1, 0, out);
+ expect(out[1]).toBeGreaterThan(2.5);
+ samplePanorama(env, 0, 0, 1, out);
+ expect(out[0]).toBeCloseTo(3.5, 1);
+ });
+});
diff --git a/pipeline/tests/export-desktop.test.ts b/pipeline/tests/export-desktop.test.ts
new file mode 100644
index 000000000..6cd68f3a1
--- /dev/null
+++ b/pipeline/tests/export-desktop.test.ts
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Desktop export. It is a NATIVE target now: the payload is app content —
+ * no HTML page, no SDK/wasm tree — and the app is assembled from a runtime
+ * template, exactly as the APK and the Xcode project are.
+ *
+ * Pinned here: no npm project, nothing for the user to install before running
+ * what the editor produced.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+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(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-desktop-'));
+ 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`);
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
+
+ out = path.join(root, 'dist-desktop');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+/** A template with the files the assembler reads. What is under test is the EXPORT
+ * reaching the assembler; the assembler itself is pinned in desktop-app.test.ts. */
+function fakeTemplate(os: 'macos' | 'windows'): string {
+ const dir = path.join(root, `_template-${os}`);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, os === 'windows' ? 'estella_desktop.exe' : 'estella_desktop'), 'runtime');
+ writeFileSync(path.join(dir, 'esengine.native.qjsbc'), 'bytecode');
+ writeFileSync(path.join(dir, 'Info.plist.in'),
+ '<plist><dict><key>N</key><string>@APP_NAME@</string></dict></plist>');
+ return dir;
+}
+
+const desktopExport = (outDir: string) => ({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir,
+ title: 'Packed Game',
+ platform: 'desktop' as const,
+});
+
+describe('exportGame (desktop)', () => {
+ it('exports app CONTENT, not a web payload in a shell', async () => {
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: out,
+ title: 'My Cool Game',
+ platform: 'desktop',
+ appId: 'com.studio.cool',
+ desktopProductName: 'Cool Override',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('desktop');
+
+ // Content only, at the top level — no app/ nesting, because there is no shell
+ // to nest under any more.
+ const present = readdirSync(out).sort();
+ for (const f of ['game.config.json', 'app.config.json', 'asset-manifest.json', 'scripts.js']) {
+ expect(present, `missing ${f}`).toContain(f);
+ }
+ // The web payload's pieces are gone: the engine, the SDK and the runtime are
+ // in the app binary, so shipping them again would be shipping two engines.
+ for (const f of ['index.html', 'game.js', 'scripts.mjs', 'app', 'sdk', 'wasm']) {
+ expect(existsSync(path.join(out, f))).toBe(false);
+ }
+
+ // The identity a packager reads, by the same rule every native target uses.
+ const app = JSON.parse(readFileSync(path.join(out, 'app.config.json'), 'utf8'));
+ expect(app.id).toBe('com.studio.cool');
+ // productName was electron-builder's; it means what CFBundleName does, so it
+ // still names the app.
+ expect(app.name).toBe('Cool Override');
+
+ // No template installed in this test's environment ⇒ content, and a warning
+ // that says so rather than a silent half-export.
+ if (!res.appBundles) {
+ expect(res.warnings.join(' ')).toMatch(/runtime template/i);
+ }
+ }, 60_000);
+
+ it('assembles one app per installed template, on whatever OS is building', async () => {
+ const packed = path.join(root, 'dist-desktop-packed');
+ const res = await exportGame({
+ ...desktopExport(packed),
+ desktopTemplates: [
+ { os: 'windows', dir: fakeTemplate('windows') },
+ { os: 'macos', dir: fakeTemplate('macos') },
+ ],
+ });
+
+ expect(res.ok).toBe(true);
+ // Both, regardless of process.platform: the assembler is pure Node, so the
+ // machine doing the building is not an input (only signing a .app is).
+ expect(res.appBundles).toEqual([
+ { os: 'windows', dir: path.join(packed, 'Packed Game') },
+ { os: 'macos', dir: path.join(packed, 'Packed Game.app') },
+ ]);
+
+ // The runtime's bytecode joins the game's files in ONE namespace, which is
+ // what the host reads — the whole reason the bundles are laid out this way.
+ for (const content of ['Packed Game/Content', 'Packed Game.app/Contents/Resources/Content']) {
+ expect(existsSync(path.join(packed, content, 'game.config.json'))).toBe(true);
+ expect(existsSync(path.join(packed, content, 'esengine.native.qjsbc'))).toBe(true);
+ }
+ if (process.platform !== 'darwin') {
+ expect(res.warnings.join(' ')).toMatch(/UNSIGNED/);
+ }
+ }, 60_000);
+
+ it('writes a depot for each app it actually assembled, not for one fixed OS', async () => {
+ const packed = path.join(root, 'dist-desktop-steam');
+ const res = await exportGame({
+ ...desktopExport(packed),
+ desktopTemplates: [{ os: 'windows', dir: fakeTemplate('windows') }],
+ desktopChannel: 'steam',
+ steam: { appId: 480 },
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.steamChecklist).toBe(path.join(packed, 'STEAM.md'));
+
+ // The Windows depot, and NOT a macOS one: a depot naming `<Name>.app/*` in a
+ // build that assembled `<Name>/` maps nothing, uploads an empty depot and
+ // reports success.
+ const scripts = readdirSync(path.join(packed, 'steam')).sort();
+ expect(scripts).toContain('depot_481_windows.vdf');
+ expect(scripts.some((f) => f.includes('macos'))).toBe(false);
+
+ const depot = readFileSync(path.join(packed, 'steam', 'depot_481_windows.vdf'), 'utf8');
+ expect(depot).toContain('"Packed Game/*"');
+ expect(depot).not.toContain('.app');
+
+ // And the checklist says what a player's Steam client will launch, plus where
+ // Auto-Cloud has to look — both per-OS, both wrong if the OS is assumed.
+ const checklist = readFileSync(res.steamChecklist!, 'utf8');
+ expect(checklist).toContain('Packed Game.exe');
+ expect(checklist).toContain('WinAppDataRoaming');
+ expect(checklist).not.toContain('MacHome');
+ }, 60_000);
+
+ it('no longer writes anything electron-builder would read', async () => {
+ for (const f of ['main.cjs', 'package.json', 'README.md']) {
+ expect(existsSync(path.join(out, f))).toBe(false);
+ }
+ });
+
+ it('leaves the web target unnested (no app/ wrapper)', async () => {
+ const webOut = path.join(root, 'dist-web');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: webOut,
+ platform: 'web',
+ });
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('web');
+ expect(existsSync(path.join(webOut, 'index.html'))).toBe(true); // top-level, not under app/
+ expect(existsSync(path.join(webOut, 'app'))).toBe(false);
+ expect(existsSync(path.join(webOut, 'main.cjs'))).toBe(false);
+ }, 60_000);
+
+});
diff --git a/pipeline/tests/export-native.test.ts b/pipeline/tests/export-native.test.ts
new file mode 100644
index 000000000..734e889f0
--- /dev/null
+++ b/pipeline/tests/export-native.test.ts
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Native export (Stage C). The native app carries the runtime in its
+ * binary — engine core, SDK bundle and game runtime all ship inside the
+ * host — so its export is CONTENT: cooked assets, both manifests, the
+ * scenes and game.config.json. Asserts exactly that, and that the web-only
+ * payload (host page, SDK/wasm trees, an ESM host bundle) stays out.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+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(async () => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-export-native-'));
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
+ copyFileSync(path.resolve(HERE, '..', '..', 'examples', 'hello-world', 'assets', 'textures', 'logo.png'),
+ path.join(root, 'assets', 'hero.png'));
+ 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`);
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+
+ out = path.join(root, 'dist-android');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('exportGame (native app content)', () => {
+ it('ships content only — cooked assets, manifests, scene, config', async () => {
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'), outDir: out,
+ platform: 'android', title: 'NativeGame',
+ });
+ expect(res.errors).toEqual([]);
+ expect(res.ok).toBe(true);
+
+ // What the native runtime reads off the device.
+ expect(existsSync(path.join(out, 'game.config.json'))).toBe(true);
+ expect(existsSync(path.join(out, 'asset-manifest.json'))).toBe(true);
+ // The flat manifest is a build-time intermediate — the addressable one is the
+ // runtime contract, and it is the only one that ships.
+ expect(existsSync(path.join(out, 'assets.manifest.json'))).toBe(false);
+ expect(JSON.parse(readFileSync(path.join(out, 'game.config.json'), 'utf8')).entryScene)
+ .toBe('scenes/main.esscene');
+
+ // The runtime lives in the app binary — none of the web payload ships.
+ expect(existsSync(path.join(out, 'index.html'))).toBe(false);
+ expect(existsSync(path.join(out, 'game.js'))).toBe(false);
+ expect(existsSync(path.join(out, 'sdk'))).toBe(false);
+ expect(existsSync(path.join(out, 'wasm'))).toBe(false);
+ }, 90_000);
+
+ it("binds the project's scripts to the host's SDK instance, not a second copy", async () => {
+ // QuickJS has no module loader: the scripts bundle is an IIFE, and its
+ // `esengine` imports must resolve to the globalThis.ESEngine the host already
+ // installed — a bundled-in second SDK would register components into a rival
+ // registry the engine never sees.
+ const scripts = path.join(out, 'scripts.js');
+ expect(existsSync(scripts)).toBe(true);
+ expect(existsSync(path.join(out, 'scripts.mjs'))).toBe(false);
+ const js = readFileSync(scripts, 'utf8');
+ expect(js).toContain('globalThis.ESEngine');
+ expect(js).toContain('SpawnMarker');
+ // An IIFE, not ESM — nothing for the host to import.
+ expect(js).not.toMatch(/^\s*(import|export)\s/m);
+ }, 90_000);
+});
diff --git a/pipeline/tests/export-playable.test.ts b/pipeline/tests/export-playable.test.ts
new file mode 100644
index 000000000..00193dc3b
--- /dev/null
+++ b/pipeline/tests/export-playable.test.ts
@@ -0,0 +1,407 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Playable-ad export — structure. Asserts ONE self-contained index.html
+ * inlines the SINGLE_FILE glue, the host+scripts IIFE bundle, and the
+ * assets (base64 data URLs keyed by @uuid:) + scenes as globals; and that
+ * the temp cook dir is cleaned (single-file output). Runtime is validated
+ * by the user in a browser / ad preview (no playable simulator here).
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { runtimeConfigOf } from '../src/project/runtimeConfig';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PLAYABLE_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'playableHost.ts');
+
+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-playable-'));
+ 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'));
+ // Project script imports 'esengine' (aliased to the stub SDK below); the REAL
+ // playableHost is bundled too — so this exercises actual esengine resolution +
+ // host bundling (the old stub host hid the resolution bug).
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', {});\n`);
+ // Stub SDK dist exporting what the real host + scripts import (bundles for real).
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'),
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function defineComponent(){}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
+ // Stub web wasm runtime (glue text + wasm) — playable inlines these, no separate build.
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), `export default function(){}/*WEB_GLUE*/\n`);
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'WASMBYTES');
+
+ out = path.join(root, 'dist-playable');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('exportGame (playable)', () => {
+ it('produces one self-contained index.html with everything inlined', async () => {
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: out,
+ title: 'Playable Demo',
+ platform: 'playable',
+ });
+
+ expect(res.ok).toBe(true);
+ expect(res.platform).toBe('playable');
+
+ // Single file: only index.html, temp cook dir removed, no staged assets dir.
+ expect(existsSync(path.join(out, 'index.html'))).toBe(true);
+ expect(existsSync(path.join(out, '.playable-cook'))).toBe(false);
+ expect(existsSync(path.join(out, 'assets'))).toBe(false);
+
+ const html = readFileSync(path.join(out, 'index.html'), 'utf8');
+ expect(html).toContain('WEB_GLUE'); // web glue text inlined
+ expect(html).toContain('__ENGINE_GLUE__'); // glue + wasm inlined as globals
+ expect(html).toContain('__ENGINE_WASM__');
+ expect(html).toContain('createObjectURL'); // real host bundled (blob loader)
+ expect(html).toContain('SpawnMarker'); // project script bundled
+ expect(html).toContain(`@uuid:${TEX}`); // asset keyed by ref
+ expect(html).toContain('data:image/png;base64,'); // asset inlined as data URL
+ // Logical path → embedded key map (path refs alias in memory at runtime;
+ // the data URL itself ships once, under the uuid key).
+ expect(html).toContain('__GAME_PATHMAP__');
+ expect(html).toMatch(new RegExp(`"assets/hero\\.png":"@uuid:${TEX}"`));
+ expect(html).toContain('__GAME_FIRST__');
+ expect(html).toContain('"main"'); // first scene name
+ expect(html).toContain('__GAME_SCENES__');
+ expect(html).toContain('<title>Playable Demo</title>');
+ // NO rotate-to-fit overlay, unlike the web export. Inside an ad SDK the media
+ // query reports the CONTAINER's aspect, which turning the phone need not change,
+ // so an overlay keyed on it hid the canvas forever — a playable nobody could play.
+ expect(html).not.toContain('rotate-hint');
+ expect(html).not.toContain('@media (orientation');
+ expect(html).not.toContain('screen.orientation');
+ }, 60_000);
+
+ // The ad network is a PROFILE, not a branch: what it contributes is head markup, a
+ // CTA bridge, and the size it accepts. A project profile and a built-in one reach
+ // the pipeline the same way, so this exercises the contract with a bespoke one.
+ it('injects the ad network profile head + CTA bridge, and warns against ITS limit', async () => {
+ const o = path.join(root, 'dist-playable-network');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, platform: 'playable',
+ playableAdProfile: {
+ id: 'acme', label: 'Acme Ads',
+ // Tiny cap so this fixture's few KB trip the warning.
+ maxBytes: 16, limitNote: 'Acme caps playables at 16 bytes',
+ emitHead: (ctx) => `<meta name="acme.orientation" content="${ctx.orientation}">`,
+ emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){AcmeSDK.openStore();}};',
+ },
+ });
+ expect(res.ok).toBe(true);
+
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('<meta name="acme.orientation" content="landscape">');
+ expect(html).toContain('AcmeSDK.openStore()');
+ // The bridge must precede the game bundle, or a CTA fired during boot finds nothing.
+ expect(html.indexOf('__ESTELLA_PLAYABLE__')).toBeLessThan(html.indexOf('__ENGINE_GLUE__'));
+ // The verdict cites THIS network's cap and where it came from — not a constant,
+ // and not an English sentence composed in the main process: the export reports
+ // the fact and the build dialog writes it in the editor's language.
+ const verdict = res.size?.verdicts.find((v) => v.budget.scope === 'deliverable');
+ expect(verdict?.status).toBe('over');
+ expect(verdict?.budget.maxBytes).toBe(16);
+ expect(verdict?.budget.note).toBe('Acme caps playables at 16 bytes');
+ // Measured against index.html itself, which is what this network takes.
+ expect(verdict?.measuredBytes).toBe(res.size?.deliverableBytes);
+ expect(res.size?.deliverableName).toBe('index.html');
+ }, 60_000);
+
+ // A zip-delivery network gets an archive with index.html at the root, and the cap
+ // then applies to the ARCHIVE — the file actually being uploaded.
+ it('writes playable.zip for a zip-delivery network and measures that', async () => {
+ const o = path.join(root, 'dist-playable-zip');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, platform: 'playable',
+ playableAdProfile: {
+ id: 'zipnet', label: 'Zip Net', maxBytes: 5 * 1024 * 1024,
+ limitNote: 'Zip Net docs', delivery: 'zip',
+ },
+ });
+ expect(res.ok).toBe(true);
+
+ const zip = path.join(o, 'playable.zip');
+ expect(existsSync(zip)).toBe(true);
+ // The HTML stays: it is what "Preview over http" serves.
+ expect(existsSync(path.join(o, 'index.html'))).toBe(true);
+ expect(execFileSync('unzip', ['-t', zip], { encoding: 'utf8' })).toContain('No errors detected');
+ expect(execFileSync('unzip', ['-Z1', zip], { encoding: 'utf8' }).trim()).toBe('index.html');
+ // What the entry unpacks to IS the exported page, byte for byte.
+ const unpacked = execFileSync('unzip', ['-p', zip, 'index.html'], { encoding: 'utf8', maxBuffer: 1 << 26 });
+ expect(unpacked).toBe(readFileSync(path.join(o, 'index.html'), 'utf8'));
+ // `bytes` is the upload, not the page — they differ, and the compressed one is smaller.
+ expect(res.zipFile).toBe(zip);
+ const sized = res as unknown as { bytes: number; htmlBytes: number };
+ expect(sized.bytes).toBeLessThan(sized.htmlBytes);
+ // The archive is what the limit is measured against, and it is NOT counted a
+ // second time as a file sitting in the output dir.
+ expect(res.size?.deliverableName).toBe('playable.zip');
+ expect(res.size?.deliverableBytes).toBe(sized.bytes);
+ }, 60_000);
+
+ it('injects nothing and keeps the default cap with no network selected', async () => {
+ const o = path.join(root, 'dist-playable-generic');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, platform: 'playable',
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).not.toContain('__ESTELLA_PLAYABLE__');
+ // A fixture this small is under every cap, so nothing to report.
+ expect(res.warnings).toEqual([]);
+ // …but it is still judged, against the same fallback the pipeline packages
+ // with: the strictest cap we know of. A build with no network selected that
+ // reported no limit at all would be the one that surprises you at upload.
+ const verdict = res.size?.verdicts.find((v) => v.budget.scope === 'deliverable');
+ expect(verdict?.status).toBe('ok');
+ expect(verdict?.budget.maxBytes).toBe(2 * 1024 * 1024);
+ }, 60_000);
+
+ it('inlines the project camera fit as __GAME_SCREENFIT__ (only when opted in)', async () => {
+ const o = path.join(root, 'dist-playable-fit');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, platform: 'playable',
+ runtime: runtimeConfigOf({
+ designResolution: { width: 750, height: 1334 },
+ features: { rendering: { cameraScaleMode: 'fixed-height', depthLayers: [2] } },
+ }),
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('__GAME_RUNTIME__');
+ expect(html).toMatch(/"scaleMode":1/);
+ expect(html).toMatch(/"designWidth":750/);
+ // The 2.5D opt-in ships too: it used to reach the play realm and no build.
+ expect(html).toMatch(/"depthLayers":4/);
+ }, 60_000);
+
+ // A portrait project must ALSO stay playable in a landscape container: the page
+ // adapts rather than demanding a rotation the SDK may not honour. The orientation
+ // reaches the network profile, which is free to declare it to the platform.
+ it('does not pin the page even when the project is portrait', async () => {
+ const o = path.join(root, 'dist-playable-portrait');
+ const res = await exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: 'unused-for-playable',
+ playableHostEntry: PLAYABLE_HOST, scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir: o, title: 'Playable Demo', platform: 'playable', orientation: 'portrait',
+ playableAdProfile: {
+ id: 'declares', label: 'Declares Orientation', maxBytes: 5 * 1024 * 1024,
+ limitNote: 'test', emitHead: (ctx) => `<meta name="ad.orientation" content="${ctx.orientation}">`,
+ },
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).not.toContain('rotate-hint');
+ expect(html).not.toContain('@media (orientation');
+ // Declared to the platform, not enforced on the player.
+ expect(html).toContain('<meta name="ad.orientation" content="portrait">');
+ }, 60_000);
+});
+
+/**
+ * The fix this whole path delivers: the exporter runs the runtime's physics/spine
+ * gating and inlines exactly those modules — so a physics scene ships with physics,
+ * and a missing module fails the export loudly instead of shipping silently broken.
+ */
+describe('exportGame (playable) — side-module embedding', () => {
+ const PSCN = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
+
+ function setupRoot(withPhysicsArtifact: boolean): { r: string; o: string } {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-playable-phys-'));
+ mkdirSync(path.join(r, 'scenes'), { recursive: true });
+ // A RigidBody makes sceneUsesPhysics() true → the runtime needs physics.
+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'RigidBody', data: { bodyType: 1 } }] }] }));
+ writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(PSCN, 'scene'));
+ mkdirSync(path.join(r, '_sdk'), { recursive: true });
+ writeFileSync(path.join(r, '_sdk', 'index.js'),
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
+ mkdirSync(path.join(r, '_wasm'), { recursive: true });
+ writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
+ writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
+ if (withPhysicsArtifact) {
+ writeFileSync(path.join(r, '_wasm', 'physics.js'), `export default function(){}/*PHYS_GLUE*/\n`);
+ writeFileSync(path.join(r, '_wasm', 'physics.wasm'), 'PHYSWASM');
+ }
+ return { r, o: path.join(r, 'dist') };
+ }
+
+ const run = (r: string, o: string) => exportGame({
+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,
+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',
+ });
+
+ // A game that spawns its bodies from script has none in the scene, so the scan
+ // sees nothing — and the package used to ship without physics.wasm while the
+ // config told the runtime to install physics. Both halves or neither.
+ it('inlines physics for a declared physics project whose scene has no bodies', async () => {
+ const { r, o } = setupRoot(true);
+ try {
+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [] }] }));
+ const res = await exportGame({
+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,
+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',
+ runtime: runtimeConfigOf({ features: { physics: { enabled: true, gravity: { x: 0, y: -20 } } } }),
+ });
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('"physics"');
+ expect(html).toContain(Buffer.from('PHYSWASM').toString('base64'));
+ // ...and the runtime is told to install it, plus the world it declared.
+ expect(html).toMatch(/"physicsEnabled":true/);
+ expect(html).toMatch(/"y":-20/);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ it('inlines physics into __SIDE_MODULES__ when the scene uses physics', async () => {
+ const { r, o } = setupRoot(true);
+ try {
+ const res = await run(r, o);
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('__SIDE_MODULES__');
+ expect(html).toContain('"physics"');
+ expect(html).toContain(Buffer.from('PHYSWASM').toString('base64')); // physics.wasm inlined
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ it('fails the export when the scene needs physics but physics.wasm is absent', async () => {
+ const { r, o } = setupRoot(false);
+ try {
+ const res = await run(r, o);
+ expect(res.ok).toBe(false);
+ expect(res.errors.join('\n')).toMatch(/physics/);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
+
+/**
+ * Spine: the skeleton + atlas share the authored meta type `spine`, so the exporter
+ * must discriminate by extension (`.skel` binary skeleton carries the version) — and
+ * the atlas's page image is a dependency the cook has to embed. A playable that lost
+ * either shipped a broken spine (module "not embedded" / texture 404) — this is that fix.
+ */
+describe('exportGame (playable) — spine embedding', () => {
+ const SSCN = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
+ const SKEL = 'ffffffff-ffff-4fff-8fff-ffffffffffff';
+ const ATLAS = '99999999-9999-4999-8999-999999999999';
+ const PAGE = '88888888-8888-4888-8888-888888888888';
+
+ // A minimal spine 4.x binary skeleton header: 8 bytes, then a varint length (7)
+ // and the version string "4.2.00" — exactly what detectSpineVersion reads.
+ const skel = Buffer.concat([Buffer.alloc(8), Buffer.from([7]), Buffer.from('4.2.00')]);
+ const atlas = ['hero.png', '\tsize: 64, 64', 'region', '\tbounds: 0, 0, 32, 32', ''].join('\n');
+
+ function setupRoot(withSpineArtifact: boolean): { r: string; o: string } {
+ const r = mkdtempSync(path.join(tmpdir(), 'estella-playable-spine-'));
+ mkdirSync(path.join(r, 'assets', 'spine'), { recursive: true });
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.png'), 'PNGDATA');
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.png.meta'), meta(PAGE, 'texture'));
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.atlas'), atlas);
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.atlas.meta'), meta(ATLAS, 'spine'));
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.skel'), skel);
+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.skel.meta'), meta(SKEL, 'spine'));
+ mkdirSync(path.join(r, 'scenes'), { recursive: true });
+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),
+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'SpineAnimation', data: { skeletonPath: 'assets/spine/hero.skel', atlasPath: 'assets/spine/hero.atlas' } }] }] }));
+ writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(SSCN, 'scene'));
+ mkdirSync(path.join(r, '_sdk'), { recursive: true });
+ writeFileSync(path.join(r, '_sdk', 'index.js'),
+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\nexport function parseThemeOverrides(){}
+export function packagedAppOptions(c){return c;}
+export function packagedRuntimeInit(c){return c;}\n`);
+ mkdirSync(path.join(r, '_wasm'), { recursive: true });
+ writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);
+ writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');
+ if (withSpineArtifact) {
+ writeFileSync(path.join(r, '_wasm', 'spine42.js'), `export default function(){}/*SPINE_GLUE*/\n`);
+ writeFileSync(path.join(r, '_wasm', 'spine42.wasm'), 'SPINE42WASM');
+ }
+ return { r, o: path.join(r, 'dist') };
+ }
+
+ const run = (r: string, o: string) => exportGame({
+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,
+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',
+ });
+
+ it('inlines spine:4.2 (detected from the .skel) and embeds the atlas page texture', async () => {
+ const { r, o } = setupRoot(true);
+ try {
+ const res = await run(r, o);
+ expect(res.ok).toBe(true);
+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');
+ expect(html).toContain('__SIDE_MODULES__');
+ expect(html).toContain('"spine:4.2"');
+ expect(html).toContain(Buffer.from('SPINE42WASM').toString('base64')); // spine42.wasm inlined
+ // The atlas page image is embedded + path-mapped (the dep the cook now follows).
+ expect(html).toMatch(/"assets\/spine\/hero\.png":"@uuid:/);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ it('fails the export when the scene needs spine but spine42.wasm is absent', async () => {
+ const { r, o } = setupRoot(false);
+ try {
+ const res = await run(r, o);
+ expect(res.ok).toBe(false);
+ expect(res.errors.join('\n')).toMatch(/spine/i);
+ } finally {
+ rmSync(r, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/pipeline/tests/export-progress.test.ts b/pipeline/tests/export-progress.test.ts
new file mode 100644
index 000000000..c44a05807
--- /dev/null
+++ b/pipeline/tests/export-progress.test.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Export progress events — the pipeline emits a phase per major step so the
+ * Package Project dialog can show a live build log.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+import type { ExportProgress } from '../src/export/exportProgress';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+let root: 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-progress-'));
+ 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('M', { n: 1 });\n`);
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('export progress', () => {
+ it('emits a phase per major step (web)', async () => {
+ const phases: string[] = [];
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: path.join(root, 'out'),
+ platform: 'web',
+ onProgress: (p: ExportProgress) => phases.push(p.phase),
+ });
+
+ expect(res.ok).toBe(true);
+ for (const expected of ['Cooking assets', 'Bundling game host', 'Bundling project scripts', 'Copying SDK + runtime', 'Writing host page']) {
+ expect(phases).toContain(expected);
+ }
+ // Cooking is first; writing the host page is among the last.
+ expect(phases.indexOf('Cooking assets')).toBeLessThan(phases.indexOf('Writing host page'));
+ }, 60_000);
+
+ it('does not claim a step a native target never takes', async () => {
+ // A progress line is a report of work. Desktop writes no host page — there is
+ // no browser to boot the game — and a log that says it did is one a developer
+ // reads while looking for what actually happened.
+ const phases: string[] = [];
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: path.join(root, 'out-desktop'),
+ platform: 'desktop',
+ onProgress: (p: ExportProgress) => phases.push(p.phase),
+ });
+
+ expect(res.ok).toBe(true);
+ expect(phases).toContain('Cooking assets');
+ expect(phases).not.toContain('Writing host page');
+ }, 60_000);
+});
diff --git a/pipeline/tests/export-project-platform.test.ts b/pipeline/tests/export-project-platform.test.ts
new file mode 100644
index 000000000..bb8c2f8a8
--- /dev/null
+++ b/pipeline/tests/export-project-platform.test.ts
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Exporting for a platform the EDITOR DOES NOT SHIP: the project supplies a
+// profile and the vendor-neutral mini-game pipeline runs with it.
+//
+// The case worth pinning down is the join between a vendor's two halves. The
+// packaging profile is data; the runtime profile is where the host global and
+// any replaced capability live (a game writing its own video decoder puts it
+// there). They are separate objects in separate processes, and the generated
+// entry is the only thing that can bring them together — `esengine/minigame`
+// deliberately installs no platform until the game names a host, so if the entry
+// does not install one, the package builds cleanly and then throws on device.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { exportGame } from '../src/export/exportGame';
+import { loadProjectPlatform } from '../src/export/platformCatalog';
+
+const TEX = '11111111-1111-4111-8111-111111111111';
+const SCN = '22222222-2222-4222-8222-222222222222';
+
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, type, importer: {} });
+
+let root: string;
+let out: string;
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'es-projplat-'));
+
+ 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'));
+
+ // The runtime half: the host global plus a capability this vendor replaces.
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'acme-runtime.js'), `
+export default {
+ id: 'acme-play',
+ hostLabel: 'ACME Play',
+ get global() { return globalThis.acme; },
+ // The point of the exercise: this vendor ships its own video decoding.
+ createVideoBackend(ctx) { return { name: 'acme-software', createStream() {}, dispose() {} }; },
+};
+`);
+
+ // The packaging half, naming the runtime one.
+ mkdirSync(path.join(root, '.esengine', 'platforms'), { recursive: true });
+ writeFileSync(path.join(root, '.esengine', 'platforms', 'acme-play.mjs'), `
+export default {
+ id: 'acme-play',
+ label: 'ACME Play',
+ defaultOut: 'dist-acme',
+ runtimeProfile: 'src/acme-runtime.js',
+ emitConfigFiles(ctx) {
+ return [{ file: 'game.json', content: JSON.stringify({ appName: ctx.title, orientation: ctx.orientation }) + '\\n' }];
+ },
+};
+`);
+
+ // Stub SDK dist: the bundle aliases `esengine` → <sdkDir>/index.minigame.js,
+ // the family entry that installs nothing on import.
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(
+ path.join(root, '_sdk', 'index.minigame.js'),
+ `export function initMiniGameRuntime(){return Promise.resolve();}\nexport function installMiniGamePlatform(){}\nexport function defineComponent(){}\n`,
+ );
+ // Stub engine runtime — the default glue candidate is the standard esengine.js.
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'wasmbytes');
+
+ out = path.join(root, 'dist-acme');
+}, 60_000);
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('exportGame — a platform the project defines', () => {
+ it('packages through the mini-game pipeline and joins the vendor\'s two halves', async () => {
+ const platform = await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), wechat: path.join(root, '_wasm') });
+ expect(platform).not.toBeNull();
+
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: platform!.wasmDir,
+ outDir: out,
+ title: 'ACME Game',
+ platform: 'acme-play',
+ miniGameProfile: platform!.profile,
+ orientation: 'portrait',
+ });
+
+ expect(res.errors).toEqual([]);
+ expect(res.ok).toBe(true);
+ // The result carries the project's id — which is also the cook's per-platform
+ // Import Settings key, so this vendor's texture overrides would apply.
+ expect(res.platform).toBe('acme-play');
+
+ // The project's own config emitter ran.
+ const gameJson = JSON.parse(readFileSync(path.join(out, 'game.json'), 'utf8'));
+ expect(gameJson).toEqual({ appName: 'ACME Game', orientation: 'portrait' });
+
+ // The default entry emitter ran (no vendor override needed for game.js).
+ const entry = readFileSync(path.join(out, 'game.js'), 'utf8');
+ expect(entry).toContain("require('./wasm/esengine.js')");
+ expect(entry).toContain("require('./game-bundle.js')");
+
+ // THE JOIN: the bundle installs the runtime profile before booting, and the
+ // vendor's replaced capability rode in with it.
+ const bundle = readFileSync(path.join(out, 'game-bundle.js'), 'utf8');
+ expect(bundle).toContain('installMiniGamePlatform');
+ expect(bundle).toContain('acme-software');
+ expect(bundle).toContain('initMiniGameRuntime');
+
+ // Scene + manifest assembled the same way as any other mini-game target. The
+ // staged name comes from the source FILE ('scenes/main.esscene' → 'main'), which
+ // is what `SceneManager.switchTo` addresses — not the document's display name.
+ expect(readFileSync(path.join(out, 'scenes', 'main.json'), 'utf8')).toContain(TEX);
+ expect(readFileSync(path.join(out, 'asset-manifest.json'), 'utf8')).toContain(TEX);
+ }, 60_000);
+
+ it('omits the install when the project installs its own platform', async () => {
+ // Same vendor, minus the runtimeProfile link: the game is then responsible
+ // for calling installMiniGamePlatform itself, so the entry must not guess.
+ const bare = { ...(await loadProjectPlatform(root, 'acme-play', { web: path.join(root, '_wasm'), wechat: path.join(root, '_wasm') }))!.profile };
+ delete (bare as { runtimeProfileModule?: string }).runtimeProfileModule;
+
+ const outBare = path.join(root, 'dist-bare');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: outBare,
+ title: 'ACME Game',
+ platform: 'acme-play',
+ miniGameProfile: bare,
+ });
+
+ expect(res.ok).toBe(true);
+ const bundle = readFileSync(path.join(outBare, 'game-bundle.js'), 'utf8');
+ expect(bundle).not.toContain('installMiniGamePlatform');
+ expect(bundle).toContain('initMiniGameRuntime');
+ }, 60_000);
+});
diff --git a/pipeline/tests/export-side-modules.test.ts b/pipeline/tests/export-side-modules.test.ts
new file mode 100644
index 000000000..e09265fc8
--- /dev/null
+++ b/pipeline/tests/export-side-modules.test.ts
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which optional modules a web package carries: the ones its content can
+ * ask for, and no others. A dropped module is a 404 at boot.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+import { runtimeConfigOf } from '../src/project/runtimeConfig';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+const SCN = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
+const PFB = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+/** Every module the engine ships, so a test can assert what did NOT come along. */
+const ALL_MODULES = [
+ 'physics', 'physics3d', 'basis', 'videodec', 'dragonbones',
+ 'spine21', 'spine38', 'spine41', 'spine42', 'spine43',
+];
+
+interface Fixture { root: string; out: string }
+
+function setup(scene: unknown, extra?: (root: string) => void): Fixture {
+ const root = mkdtempSync(path.join(tmpdir(), 'estella-sidemod-'));
+ mkdirSync(path.join(root, 'scenes'), { recursive: true });
+ writeFileSync(path.join(root, 'scenes', 'main.esscene'), JSON.stringify(scene));
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'ENGINE');
+ writeFileSync(path.join(root, '_wasm', 'wasm.manifest.json'), JSON.stringify({ schema: 1 }));
+ for (const m of ALL_MODULES) {
+ writeFileSync(path.join(root, '_wasm', `${m}.js`), `export default () => {};/*${m}*/`);
+ writeFileSync(path.join(root, '_wasm', `${m}.wasm`), m.toUpperCase());
+ }
+ extra?.(root);
+ return { root, out: path.join(root, 'dist') };
+}
+
+const run = (f: Fixture, runtime?: Parameters<typeof exportGame>[0]['runtime']) => exportGame({
+ root: f.root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST,
+ sdkDistDir: path.join(f.root, '_sdk'), wasmDir: path.join(f.root, '_wasm'),
+ outDir: f.out, ...(runtime ? { runtime } : {}),
+});
+
+/** The module artifact base names the package actually carries. */
+function shipped(out: string): string[] {
+ return ALL_MODULES.filter((m) => existsSync(path.join(out, 'wasm', `${m}.wasm`)));
+}
+
+const entities = (...components: Array<{ type: string; data?: unknown }>) =>
+ [{ id: 0, components }];
+
+describe('web package side modules', () => {
+ it('carries the engine and nothing optional for a scene that asks for nothing', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'Sprite', data: {} }) });
+ try {
+ const res = await run(f);
+ expect(res.errors).toEqual([]);
+ expect(shipped(f.out)).toEqual([]);
+ // The engine core and the dir's other contents are never the scan's to drop.
+ expect(existsSync(path.join(f.out, 'wasm', 'esengine.wasm'))).toBe(true);
+ expect(existsSync(path.join(f.out, 'wasm', 'esengine.js'))).toBe(true);
+ expect(existsSync(path.join(f.out, 'wasm', 'wasm.manifest.json'))).toBe(true);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('carries the 2D solver for a scene with a body', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'RigidBody', data: { bodyType: 1 } }) });
+ try {
+ expect(shipped((await run(f), f.out))).toEqual(['physics']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('carries the 2D solver a project declares but no scene uses', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'Sprite', data: {} }) });
+ try {
+ await run(f, runtimeConfigOf({ features: { physics: { enabled: true } } }));
+ expect(shipped(f.out)).toEqual(['physics']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('carries the 3D solver for a 3D body, and never implies it from the 2D flag', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'RigidBody3D', data: {} }) });
+ try {
+ await run(f);
+ expect(shipped(f.out)).toEqual(['physics3d']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ // Joints and mesh colliders are 3D physics components like the bodies are;
+ // the scan answers for every type the runtime's own gate counts.
+ it('carries the 3D solver for a joint, not only for a body', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'HingeJoint3D', data: {} }) });
+ try {
+ await run(f);
+ expect(shipped(f.out)).toEqual(['physics3d']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('carries the 3D solver for a mesh collider', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'MeshCollider3D', data: {} }) });
+ try {
+ await run(f);
+ expect(shipped(f.out)).toEqual(['physics3d']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ // The runtime expands prefabs before it asks whether the scene needs physics,
+ // so a body reachable only through a prefab is one the package must carry.
+ it('carries what a shipped prefab needs, not only what a scene holds', async () => {
+ const f = setup(
+ { version: '1.0', name: 'Main', entities: entities({ type: 'Spawner', data: { prefab: `@uuid:${PFB}` } }) },
+ (root) => {
+ mkdirSync(path.join(root, 'prefabs'), { recursive: true });
+ writeFileSync(path.join(root, 'prefabs', 'enemy.esprefab'), JSON.stringify({
+ version: '1.0', name: 'Enemy', rootEntityId: 'r',
+ entities: [{ prefabEntityId: 'r', name: 'Enemy', parent: null, children: [], visible: true, components: [{ type: 'RigidBody', data: { bodyType: 1 } }] }],
+ }));
+ writeFileSync(path.join(root, 'prefabs', 'enemy.esprefab.meta'), meta(PFB, 'prefab'));
+ },
+ );
+ try {
+ const res = await run(f);
+ expect(res.errors).toEqual([]);
+ expect(shipped(f.out)).toEqual(['physics']);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('fails the export when the content needs a module the wasm dir has not built', async () => {
+ const f = setup({ version: '1.0', name: 'Main', entities: entities({ type: 'RigidBody3D', data: {} }) });
+ rmSync(path.join(f.root, '_wasm', 'physics3d.js'));
+ try {
+ const res = await run(f);
+ expect(res.ok).toBe(false);
+ expect(res.errors.join('\n')).toMatch(/physics3d/);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+});
diff --git a/pipeline/tests/export-source-maps.test.ts b/pipeline/tests/export-source-maps.test.ts
new file mode 100644
index 000000000..bc25cf683
--- /dev/null
+++ b/pipeline/tests/export-source-maps.test.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Whether a web package carries source maps. One answer covers the
+ * bundles the export writes and the SDK tree it copies beside them.
+ */
+import { describe, it, expect } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+const SCN = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
+const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
+
+function setup(): { root: string; out: string } {
+ const root = mkdtempSync(path.join(tmpdir(), 'estella-srcmap-'));
+ 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: [] }] }));
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+
+ mkdirSync(path.join(root, '_sdk', 'shared'), { recursive: true });
+ // Exactly how the SDK build writes them: the script names its map on the last
+ // line, and the map sits beside it.
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;\n//# sourceMappingURL=index.js.map\n');
+ writeFileSync(path.join(root, '_sdk', 'index.js.map'), '{"version":3}');
+ writeFileSync(path.join(root, '_sdk', 'shared', 'resource.js'), 'export const r = 1;\n//# sourceMappingURL=resource.js.map');
+ writeFileSync(path.join(root, '_sdk', 'shared', 'resource.js.map'), '{"version":3}');
+
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ writeFileSync(path.join(root, '_wasm', 'esengine.wasm'), 'ENGINE');
+ return { root, out: path.join(root, 'dist') };
+}
+
+const run = (f: { root: string; out: string }, sourcemap?: boolean) => exportGame({
+ root: f.root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST,
+ sdkDistDir: path.join(f.root, '_sdk'), wasmDir: path.join(f.root, '_wasm'),
+ outDir: f.out, ...(sourcemap === undefined ? {} : { sourcemap }),
+});
+
+describe('source maps in a web package', () => {
+ it('ships none by default, and leaves no script asking for one', async () => {
+ const f = setup();
+ try {
+ const res = await run(f);
+ expect(res.errors).toEqual([]);
+ expect(existsSync(path.join(f.out, 'sdk', 'index.js.map'))).toBe(false);
+ expect(existsSync(path.join(f.out, 'sdk', 'shared', 'resource.js.map'))).toBe(false);
+ // A dangling reference is a 404 the moment anyone opens devtools on the
+ // shipped game, so the copy drops the line as well as the file.
+ for (const rel of ['sdk/index.js', 'sdk/shared/resource.js']) {
+ expect([rel, readFileSync(path.join(f.out, rel), 'utf8')]).toEqual([rel, expect.not.stringContaining('sourceMappingURL')]);
+ }
+ // Stripping the comment is all it does to the script.
+ expect(readFileSync(path.join(f.out, 'sdk', 'index.js'), 'utf8')).toContain('export const x = 1;');
+ expect(existsSync(path.join(f.out, 'game.js.map'))).toBe(false);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+
+ it('ships them when the build asks for them', async () => {
+ const f = setup();
+ try {
+ const res = await run(f, true);
+ expect(res.errors).toEqual([]);
+ expect(existsSync(path.join(f.out, 'sdk', 'index.js.map'))).toBe(true);
+ expect(existsSync(path.join(f.out, 'sdk', 'shared', 'resource.js.map'))).toBe(true);
+ expect(readFileSync(path.join(f.out, 'sdk', 'index.js'), 'utf8')).toContain('sourceMappingURL');
+ // The export's own bundles answer the same question the same way.
+ expect(existsSync(path.join(f.out, 'game.js.map'))).toBe(true);
+ } finally { rmSync(f.root, { recursive: true, force: true }); }
+ }, 60_000);
+});
diff --git a/pipeline/tests/export-wechat.test.ts b/pipeline/tests/export-wechat.test.ts
new file mode 100644
index 000000000..a4619eb5d
--- /dev/null
+++ b/pipeline/tests/export-wechat.test.ts
@@ -0,0 +1,616 @@
+// 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), @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 { runtimeConfigOf } from '../src/project/runtimeConfig';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } 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 SUBTEX = '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-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'));
+ // 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'), `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'),
+ wasmDir: path.join(root, '_wxwasm'),
+ outDir: out,
+ title: 'My Game',
+ platform: 'wechat',
+ wechatAppid: '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).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')");
+ // 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');
+ 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).toBe('subpackages/level2/extra.png');
+ expect(gjson.subPackages).toContainEqual({ name: 'level2', root: 'subpackages/level2' });
+ expect(existsSync(path.join(out, 'subpackages', 'level2', 'extra.png'))).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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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(20 * 1024 * 1024);
+ expect(initial?.status).toBe('ok');
+ expect(res.size?.byKind.find((k) => k.kind === 'engine')?.bytes).toBeGreaterThan(0);
+ // The fixture's subpackage asset (`subpackages/level2/extra.png`, 8 bytes of
+ // "PNG2DATA") is in the package but NOT in the main one — the distinction the
+ // 4MB limit is judged on, measured end-to-end on the real mini-game path.
+ expect(res.size?.lazyBytes).toBe(8);
+ expect(res.size?.packageBytes).toBe(res.size!.initialBytes + 8);
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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(20 * 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 });
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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 });
+ }, 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 });
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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 });
+ }, 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes-spine/spine.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes-spine/spine.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes-ktx2/ktx2.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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.
+ expect(existsSync(path.join(outKtx, 'assets', 'pre.ktx2.bin'))).toBe(true);
+ expect(existsSync(path.join(outKtx, 'assets', 'pre.ktx2'))).toBe(false);
+ 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).toBe('assets/pre.ktx2.bin');
+ 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({
+ root,
+ entryScene: 'scenes-ktx2/ktx2.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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({
+ root,
+ entryScene: 'scenes-multi/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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).toBe('assets/lv2.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 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'), 'export function initWeChatRuntime(){return Promise.resolve();}\n');
+ 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({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: 'unused-for-wechat',
+ 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 }); });
+
+ 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);
+});
diff --git a/pipeline/tests/fbx-import.test.ts b/pipeline/tests/fbx-import.test.ts
new file mode 100644
index 000000000..5093b7ca2
--- /dev/null
+++ b/pipeline/tests/fbx-import.test.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FBX import: what the products say, from geometry to bind pose to clip.
+ *
+ * The claims here are the ones a format conversion gets wrong quietly — units,
+ * the uv origin, which matrix is the bind pose, which entity a track drives —
+ * so each is asserted against a fixture whose numbers are written out in
+ * `scripts/lib/fbxFixtures.mjs` rather than hidden in a binary.
+ */
+import { describe, it, expect } from 'vitest';
+import { importFbxMeshes } from '../src/assets/fbxImport';
+import { assembleModelPrefab, materialProducts,
+ type ImportedMesh, type ImportedNode } from '../src/assets/modelImport';
+import { MeshChannel } from 'esengine';
+import { texturedTriangle, skinnedBar } from './fixtures/fbxFixtures.mjs';
+
+/** One channel's floats for vertex `index`, read back out of the packed buffer. */
+function attribute(mesh: ImportedMesh, semantic: number, index: number, comps: number): number[] {
+ const channel = mesh.data.channels.find(c => c.semantic === semantic)!;
+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ const at = index * mesh.data.vertexStride + channel.offset;
+ return Array.from({ length: comps }, (_, c) => view.getFloat32(at + c * 4, true));
+}
+
+/** Every node of the tree, flattened, so a test can find one by name. */
+function flatten(nodes: ImportedNode[]): ImportedNode[] {
+ return nodes.flatMap(node => [node, ...flatten(node.children)]);
+}
+
+describe('fbx geometry', () => {
+ it('keeps the source units — a metre stays a world unit', async () => {
+ const { meshes, warnings } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ expect(warnings).toEqual([]);
+ expect(meshes).toHaveLength(1);
+ const mesh = meshes[0]!;
+ expect(mesh.vertexCount).toBe(3);
+ expect(mesh.triangleCount).toBe(1);
+ // The fixture's UnitScaleFactor is 100 (centimetres to a metre), so the
+ // vertices arrive as authored rather than a hundredth of that.
+ expect(mesh.data.aabbMin).toEqual([0, 0, 0]);
+ expect(mesh.data.aabbMax).toEqual([2, 2, 0]);
+ });
+
+ it('reads uvs with the origin FBX puts them in', async () => {
+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ const mesh = meshes[0]!;
+ // (0,0), (1,0), (0,1) as authored. A glTF would arrive flipped in v — its
+ // origin is the image's top left — and flipping these too would put the
+ // texture on upside down.
+ const uvs = [0, 1, 2].map(i => attribute(mesh, MeshChannel.TexCoord0, i, 2));
+ const corner = (u: number, v: number): number[] | undefined =>
+ uvs.find(([a, b]) => Math.abs(a! - u) < 1e-6 && Math.abs(b! - v) < 1e-6);
+ expect(corner(0, 0)).toBeDefined();
+ expect(corner(1, 0)).toBeDefined();
+ expect(corner(0, 1)).toBeDefined();
+ });
+
+ it('carries the normals the source declares', async () => {
+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ expect(attribute(meshes[0]!, MeshChannel.Normal, 0, 3)).toEqual([0, 0, 1]);
+ });
+
+ it('triangulates a quad', async () => {
+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ expect(meshes[0]!.triangleCount).toBe(2);
+ expect(meshes[0]!.vertexCount).toBe(4);
+ });
+});
+
+describe('fbx hierarchy', () => {
+ it('places geometry by its node, not by the geometry', async () => {
+ const { nodes, meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ expect(nodes).toHaveLength(1);
+ const node = nodes[0]!;
+ expect(node.name).toBe('Tri');
+ expect(node.translation).toEqual([1, 2, 3]);
+ expect(node.meshes).toEqual([0]);
+ // The vertices themselves stay at the origin: moving them AND the node
+ // would place the triangle twice.
+ expect(meshes[0]!.data.aabbMin).toEqual([0, 0, 0]);
+ });
+
+ it('drops the scene root, which is ufbx\'s and not the artist\'s', async () => {
+ const { nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ expect(nodes.map(n => n.name)).toEqual(['Bar', 'Bone1']);
+ expect(flatten(nodes).map(n => n.name)).toContain('Bone2');
+ });
+});
+
+describe('fbx materials', () => {
+ it('reads a Phong material as the engine\'s own terms', async () => {
+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ const material = meshes[0]!.material!;
+ expect(material.baseColor).toEqual([1, 0, 0, 1]);
+ expect(material.emissive).toEqual([0, 0.5, 0]);
+ // A Phong material has no metalness; reporting one would invent a surface.
+ expect(material.metallic).toBe(0);
+ // Its roughness IS derived, from the specular exponent the fixture sets.
+ expect(material.roughness).toBeGreaterThan(0);
+ expect(material.roughness).toBeLessThan(1);
+ expect(material.opaque).toBe(true);
+ });
+
+ it('references an image beside the source instead of copying it', async () => {
+ const { meshes, textures, externalFiles } = await importFbxMeshes(
+ texturedTriangle(), 'tri', 'tri.fbx');
+ const image = meshes[0]!.material!.baseColorTexture!;
+ expect(image).toMatchObject({ file: 'textures/brick.png', external: true });
+ // Windows-authored paths reach the project with the separators every other
+ // reader here resolves.
+ expect(image.file).not.toContain('\\');
+ expect(textures).toEqual([]);
+ expect(externalFiles).toEqual(['textures/brick.png']);
+ });
+
+ it('writes an .esmaterial for what a Mesh2D cannot say', async () => {
+ const { meshes } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ const products = materialProducts(meshes, 'tri');
+ expect(products).toHaveLength(1);
+ expect(products[0]!.data.properties).toMatchObject({
+ u_metallic: 0,
+ u_emissive: { r: 0, g: 0.5, b: 0, a: 1 },
+ });
+ });
+});
+
+describe('fbx skinning', () => {
+ it('binds the mesh to the bone entities the prefab will hold', async () => {
+ const { meshes, nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ const mesh = meshes[0]!;
+ const named = new Map(flatten(nodes).map(n => [n.name, n.index]));
+ expect(mesh.skinJoints).toEqual([named.get('Bone1'), named.get('Bone2')]);
+
+ const prefab = assembleModelPrefab('bar', meshes, { nodes });
+ const skin = prefab.entities.flatMap(e => e.components)
+ .find(c => c.type === 'MeshSkin')!;
+ const joints = (skin.data as { joints: string[] }).joints;
+ const ids = new Set(prefab.entities.map(e => e.prefabEntityId));
+ // Every joint names an entity this same prefab defines; a joint pointing at
+ // nothing is a mesh that collapses to the origin at runtime.
+ for (const joint of joints) expect(ids.has(joint)).toBe(true);
+ });
+
+ it('carries the bind pose as the inverse of where the bone was', async () => {
+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ const matrices = meshes[0]!.data.inverseBindMatrices!;
+ expect(matrices).toHaveLength(32);
+ // Bone1 is bound at the origin, Bone2 one unit up — so undoing the bind
+ // pose is identity for the first and a step DOWN for the second.
+ expect([...matrices.slice(12, 15)]).toEqual([0, 0, 0]);
+ expect([...matrices.slice(28, 31)].map(v => Math.round(v))).toEqual([0, -1, 0]);
+ });
+
+ it('normalizes the weights it keeps', async () => {
+ const { meshes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ const mesh = meshes[0]!;
+ for (let i = 0; i < mesh.vertexCount; i++) {
+ const sum = attribute(mesh, MeshChannel.Weights, i, 4).reduce((a, b) => a + b, 0);
+ expect(sum).toBeCloseTo(1, 5);
+ }
+ });
+});
+
+describe('fbx animation', () => {
+ it('bakes the euler curves into a clip the runtime can play', async () => {
+ const { animations, nodes } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ expect(animations).toHaveLength(1);
+ const clip = animations[0]!;
+ expect(clip.name).toBe('bar_Take_001');
+ const doc = clip.document as {
+ duration: number;
+ tracks: { name: string; childPath: string; component: string;
+ channels: { property: string; keyframes: { time: number; value: number }[] }[] }[];
+ };
+ expect(doc.duration).toBeCloseTo(1, 6);
+ expect(doc.tracks).toHaveLength(1);
+ const track = doc.tracks[0]!;
+ expect(track.name).toBe('Bone2');
+ expect(track.component).toBe('Transform');
+ // The path the clip addresses has to be the one the prefab builds, or the
+ // track resolves to nothing and the model stands still.
+ const prefab = assembleModelPrefab('bar', [], { nodes });
+ const byId = new Map(prefab.entities.map(e => [e.prefabEntityId, e]));
+ let entity = byId.get(prefab.rootEntityId)!;
+ for (const step of track.childPath.split('/')) {
+ entity = entity.children.map(id => byId.get(id)!).find(e => e.name === step)!;
+ expect(entity).toBeDefined();
+ }
+ expect(entity.name).toBe('Bone2');
+ });
+
+ it('turns a quarter circle about Z, as the source says', async () => {
+ const { animations } = await importFbxMeshes(skinnedBar(), 'bar', 'bar.fbx');
+ const doc = animations[0]!.document as {
+ tracks: { channels: { property: string; keyframes: { time: number; value: number }[] }[] }[];
+ };
+ const channels = new Map(doc.tracks[0]!.channels.map(c => [c.property, c.keyframes]));
+ const last = (property: string): number => {
+ const keys = channels.get(property)!;
+ return keys[keys.length - 1]!.value;
+ };
+ // 90° about Z is (0, 0, sin45, cos45) — the components a Transform holds.
+ expect(last('rotation.x')).toBeCloseTo(0, 5);
+ expect(last('rotation.y')).toBeCloseTo(0, 5);
+ expect(Math.abs(last('rotation.z'))).toBeCloseTo(Math.SQRT1_2, 4);
+ expect(Math.abs(last('rotation.w'))).toBeCloseTo(Math.SQRT1_2, 4);
+ // Every keyframe is a unit quaternion; a track that drifts off the unit
+ // sphere scales the model as it turns.
+ const keys = channels.get('rotation.x')!.length;
+ for (let k = 0; k < keys; k++) {
+ const q = ['x', 'y', 'z', 'w'].map(a => channels.get(`rotation.${a}`)![k]!.value);
+ expect(Math.hypot(...q)).toBeCloseTo(1, 5);
+ }
+ });
+});
+
+describe('fbx reporting', () => {
+ it('says what a file carries that this import has no place for', async () => {
+ const { warnings } = await importFbxMeshes(texturedTriangle(), 'tri', 'tri.fbx');
+ // The fixture is entirely importable; a warning here would mean the reader
+ // is complaining about something it did in fact carry.
+ expect(warnings).toEqual([]);
+ });
+
+ it('refuses a file that is not an FBX at all', async () => {
+ await expect(importFbxMeshes(new TextEncoder().encode('not an fbx'), 'x', 'x.fbx'))
+ .rejects.toThrow();
+ });
+});
diff --git a/pipeline/tests/fixtures/fbxFixtures.d.mts b/pipeline/tests/fixtures/fbxFixtures.d.mts
new file mode 100644
index 000000000..5c517c718
--- /dev/null
+++ b/pipeline/tests/fixtures/fbxFixtures.d.mts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** @see fbxFixtures.mjs */
+
+/** A red-tinted triangle under a moved node, sampling an image beside the file. */
+export declare function texturedTriangle(): Uint8Array;
+
+/** Two bones and a quad bound to them, the upper bone turning 90° about Z. */
+export declare function skinnedBar(): Uint8Array;
diff --git a/pipeline/tests/fixtures/fbxFixtures.mjs b/pipeline/tests/fixtures/fbxFixtures.mjs
new file mode 100644
index 000000000..932ac4f73
--- /dev/null
+++ b/pipeline/tests/fixtures/fbxFixtures.mjs
@@ -0,0 +1,276 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FBX sources written by hand, in the format's own ASCII dialect.
+ *
+ * An FBX fixture is normally a binary blob nobody can read or edit, which makes
+ * a failing test a mystery. These are text: the vertices, the bind matrices and
+ * the keyframes a test asserts on are visible in the file that produced them.
+ * ufbx reads ASCII and binary through the same parser, so what they exercise is
+ * this project's reading of a scene, not one particular container.
+ *
+ * Shared because the same models are the claim in two places: a unit test on the
+ * importer, and a check that the real editor's import door reads them too.
+ */
+
+/** FBX stores time in ticks; this many are one second. */
+const TICKS_PER_SECOND = 46186158000;
+
+/** Keyframe interpolation flags (ufbxi_key_flags): linear, no tangents. */
+const KEY_LINEAR = 4;
+
+const header = (creator) => `; FBX 7.4.0 project file
+FBXHeaderExtension: {
+\tFBXHeaderVersion: 1003
+\tFBXVersion: 7400
+\tCreator: "${creator}"
+}
+GlobalSettings: {
+\tVersion: 1000
+\tProperties70: {
+\t\tP: "UpAxis", "int", "Integer", "",1
+\t\tP: "UpAxisSign", "int", "Integer", "",1
+\t\tP: "FrontAxis", "int", "Integer", "",2
+\t\tP: "FrontAxisSign", "int", "Integer", "",1
+\t\tP: "CoordAxis", "int", "Integer", "",0
+\t\tP: "CoordAxisSign", "int", "Integer", "",1
+\t\tP: "UnitScaleFactor", "double", "Number", "",100
+\t}
+}
+`;
+
+/** An FBX array literal: `*<count> { a: ... }`, indented to sit inside a node. */
+function array(name, values, indent) {
+ const pad = '\t'.repeat(indent);
+ return `${pad}${name}: *${values.length} {\n${pad}\ta: ${values.join(',')}\n${pad}}\n`;
+}
+
+/**
+ * A polygon's vertex indices as FBX spells them: the last index of each face is
+ * bit-flipped, which is how a reader finds the face boundary in a flat array.
+ */
+function polygons(faces) {
+ return faces.flatMap((face) => face.map((ix, i) => (i === face.length - 1 ? ~ix : ix)));
+}
+
+/**
+ * A mesh geometry with normals and UVs, both per polygon-vertex — the mapping
+ * an exporter uses when a vertex can carry different values per face.
+ */
+function geometry(id, name, { vertices, faces, normals, uvs, materials }) {
+ const corners = faces.flat().length;
+ return `\tGeometry: ${id}, "Geometry::${name}", "Mesh" {
+${array('Vertices', vertices, 2)}${array('PolygonVertexIndex', polygons(faces), 2)}\t\tGeometryVersion: 124
+\t\tLayerElementNormal: 0 {
+\t\t\tVersion: 102
+\t\t\tName: ""
+\t\t\tMappingInformationType: "ByPolygonVertex"
+\t\t\tReferenceInformationType: "Direct"
+${array('Normals', normals, 3)}\t\t}
+\t\tLayerElementUV: 0 {
+\t\t\tVersion: 101
+\t\t\tName: "UVMap"
+\t\t\tMappingInformationType: "ByPolygonVertex"
+\t\t\tReferenceInformationType: "Direct"
+${array('UV', uvs, 3)}${array('UVIndex', Array.from({ length: corners }, (_, i) => i), 3)}\t\t}
+${materials === undefined ? '' : `\t\tLayerElementMaterial: 0 {
+\t\t\tVersion: 101
+\t\t\tName: ""
+\t\t\tMappingInformationType: "ByPolygon"
+\t\t\tReferenceInformationType: "IndexToDirect"
+${array('Materials', materials, 3)}\t\t}
+`}\t\tLayer: 0 {
+\t\t\tVersion: 100
+\t\t\tLayerElement: {
+\t\t\t\tType: "LayerElementNormal"
+\t\t\t\tTypedIndex: 0
+\t\t\t}
+\t\t\tLayerElement: {
+\t\t\t\tType: "LayerElementUV"
+\t\t\t\tTypedIndex: 0
+\t\t\t}
+${materials === undefined ? '' : `\t\t\tLayerElement: {
+\t\t\t\tType: "LayerElementMaterial"
+\t\t\t\tTypedIndex: 0
+\t\t\t}
+`}\t\t}
+\t}
+`;
+}
+
+/** A scene node. `kind` is "Mesh", "LimbNode" or "Null" — what FBX calls it. */
+function model(id, name, kind, { translation, rotation, scale } = {}) {
+ const props = [
+ translation && `\t\t\tP: "Lcl Translation", "Lcl Translation", "", "A",${translation.join(',')}`,
+ rotation && `\t\t\tP: "Lcl Rotation", "Lcl Rotation", "", "A",${rotation.join(',')}`,
+ scale && `\t\t\tP: "Lcl Scaling", "Lcl Scaling", "", "A",${scale.join(',')}`,
+ ].filter(Boolean);
+ return `\tModel: ${id}, "Model::${name}", "${kind}" {
+\t\tVersion: 232
+\t\tProperties70: {
+${props.join('\n')}${props.length ? '\n' : ''}\t\t}
+\t}
+`;
+}
+
+/**
+ * A Phong material — what the overwhelming majority of FBX files carry, and the
+ * shading model ufbx derives roughness from (out of the specular exponent).
+ */
+function material(id, name, { diffuse = [0.8, 0.8, 0.8], emissive, shininess = 20, opacity = 1 } = {}) {
+ return `\tMaterial: ${id}, "Material::${name}", "" {
+\t\tVersion: 102
+\t\tShadingModel: "phong"
+\t\tMultiLayer: 0
+\t\tProperties70: {
+\t\t\tP: "DiffuseColor", "Color", "", "A",${diffuse.join(',')}
+\t\t\tP: "ShininessExponent", "double", "Number", "",${shininess}
+\t\t\tP: "Opacity", "double", "Number", "",${opacity}
+${emissive ? `\t\t\tP: "EmissiveColor", "Color", "", "A",${emissive.join(',')}
+\t\t\tP: "EmissiveFactor", "double", "Number", "",1
+` : ''}\t\t}
+\t}
+`;
+}
+
+/** A file texture. `relative` is the path as the FBX stores it. */
+function texture(id, name, relative) {
+ return `\tTexture: ${id}, "Texture::${name}", "" {
+\t\tType: "TextureVideoClip"
+\t\tVersion: 202
+\t\tTextureName: "Texture::${name}"
+\t\tFileName: "C:/art/${relative}"
+\t\tRelativeFilename: "${relative.split('/').join('\\')}"
+\t\tModelUVTranslation: 0,0
+\t\tModelUVScaling: 1,1
+\t\tTexture_Alpha_Source: "None"
+\t\tCropping: 0,0,0,0
+\t}
+`;
+}
+
+/**
+ * One animation curve. The flag/attribute arrays are run-length encoded against
+ * `KeyAttrRefCount`, so one entry covering every key is a whole curve of linear
+ * keyframes.
+ */
+function animCurve(id, times, values) {
+ return `\tAnimationCurve: ${id}, "AnimCurve::", "" {
+\t\tDefault: ${values[0] ?? 0}
+\t\tKeyVer: 4009
+${array('KeyTime', times.map((t) => Math.round(t * TICKS_PER_SECOND)), 2)}${array('KeyValueFloat', values, 2)}${array('KeyAttrFlags', [KEY_LINEAR], 2)}${array('KeyAttrDataFloat', [0, 0, 0, 0], 2)}${array('KeyAttrRefCount', [times.length], 2)}\t}
+`;
+}
+
+const connect = (child, parent) => `\tC: "OO",${child},${parent}\n`;
+const connectProp = (child, parent, property) => `\tC: "OP",${child},${parent}, "${property}"\n`;
+
+const encode = (text) => new TextEncoder().encode(text);
+
+/**
+ * A right triangle at the origin, drawn with a red Phong material that samples
+ * an image beside the FBX. The node carrying it is moved to (1,2,3), so a test
+ * can tell geometry from placement; the uvs are the unit corners in FBX's own
+ * convention, where (0,0) is the image's BOTTOM left.
+ */
+export function texturedTriangle() {
+ const objects = [
+ geometry(1000, 'tri', {
+ vertices: [0, 0, 0, 2, 0, 0, 0, 2, 0],
+ faces: [[0, 1, 2]],
+ normals: [0, 0, 1, 0, 0, 1, 0, 0, 1],
+ uvs: [0, 0, 1, 0, 0, 1],
+ materials: [0],
+ }),
+ model(2000, 'Tri', 'Mesh', { translation: [1, 2, 3] }),
+ material(3000, 'Red', { diffuse: [1, 0, 0], emissive: [0, 0.5, 0] }),
+ texture(4000, 'Brick', 'textures/brick.png'),
+ ].join('');
+ const connections = [
+ connect(2000, 0),
+ connect(1000, 2000),
+ connect(3000, 2000),
+ connectProp(4000, 3000, 'DiffuseColor'),
+ ].join('');
+ return encode(`${header('estella fbxFixtures')}Objects: {\n${objects}}\nConnections: {\n${connections}}\n`);
+}
+
+/**
+ * Two bones and a quad bound to them, the upper bone turning a quarter circle
+ * about Z over one second. The bind pose is deliberately plain — mesh and lower
+ * bone at the origin, upper bone one unit up — so the inverse bind matrix a test
+ * reads back is a translation it can check by eye.
+ */
+export function skinnedBar() {
+ const objects = [
+ geometry(1000, 'bar', {
+ vertices: [-1, 0, 0, 1, 0, 0, 1, 2, 0, -1, 2, 0],
+ faces: [[0, 1, 2, 3]],
+ normals: Array.from({ length: 4 }, () => [0, 0, 1]).flat(),
+ uvs: [0, 0, 1, 0, 1, 1, 0, 1],
+ }),
+ model(2000, 'Bar', 'Mesh'),
+ model(2100, 'Bone1', 'LimbNode'),
+ model(2200, 'Bone2', 'LimbNode', { translation: [0, 1, 0] }),
+ `\tDeformer: 5000, "Deformer::Skin", "Skin" {
+\t\tVersion: 101
+\t\tLink_DeformAcuracy: 50
+\t}
+`,
+ // Transform is the mesh-node-to-bone matrix — the bind pose, already
+ // inverted — and TransformLink is where the bone stood when it was bound.
+ cluster(5100, 'Bone1', [0, 1], [1, 1], IDENTITY, IDENTITY),
+ cluster(5200, 'Bone2', [2, 3], [1, 1], translation(0, -1, 0), translation(0, 1, 0)),
+ // Both ends of the range: a reader takes the pair or neither.
+ `\tAnimationStack: 6000, "AnimStack::Take 001", "" {
+\t\tProperties70: {
+\t\t\tP: "LocalStart", "KTime", "Time", "",0
+\t\t\tP: "LocalStop", "KTime", "Time", "",${TICKS_PER_SECOND}
+\t\t\tP: "ReferenceStart", "KTime", "Time", "",0
+\t\t\tP: "ReferenceStop", "KTime", "Time", "",${TICKS_PER_SECOND}
+\t\t}
+\t}
+`,
+ `\tAnimationLayer: 6100, "AnimLayer::BaseLayer", "" {
+\t}
+`,
+ `\tAnimationCurveNode: 6200, "AnimCurveNode::R", "" {
+\t\tProperties70: {
+\t\t\tP: "d", "Compound", "", ""
+\t\t\tP: "d|X", "Number", "", "A",0
+\t\t\tP: "d|Y", "Number", "", "A",0
+\t\t\tP: "d|Z", "Number", "", "A",0
+\t\t}
+\t}
+`,
+ animCurve(6300, [0, 1], [0, 90]),
+ ].join('');
+ const connections = [
+ connect(2000, 0),
+ connect(2100, 0),
+ connect(2200, 2100),
+ connect(1000, 2000),
+ connect(5000, 1000),
+ connect(5100, 5000),
+ connect(5200, 5000),
+ connect(2100, 5100),
+ connect(2200, 5200),
+ connect(6100, 6000),
+ connect(6200, 6100),
+ connectProp(6200, 2200, 'Lcl Rotation'),
+ connectProp(6300, 6200, 'd|Z'),
+ ].join('');
+ return encode(`${header('estella fbxFixtures')}Objects: {\n${objects}}\nConnections: {\n${connections}}\n`);
+}
+
+/** A 4x4 matrix as FBX writes one: sixteen numbers, translation in the last row. */
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+const translation = (x, y, z) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
+
+function cluster(id, bone, indexes, weights, transform, transformLink) {
+ return `\tDeformer: ${id}, "SubDeformer::Cluster ${bone}", "Cluster" {
+\t\tVersion: 100
+\t\tUserData: "", ""
+${array('Indexes', indexes, 2)}${array('Weights', weights, 2)}${array('Transform', transform, 2)}${array('TransformLink', transformLink, 2)}\t}
+`;
+}
diff --git a/pipeline/tests/fixtures/gltfFixtures.d.mts b/pipeline/tests/fixtures/gltfFixtures.d.mts
new file mode 100644
index 000000000..341658603
--- /dev/null
+++ b/pipeline/tests/fixtures/gltfFixtures.d.mts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+
+/** One triangle as a `.gltf`, its bytes stored plainly. */
+export function plainTriangle(): Uint8Array;
+
+/** The same triangle with every bufferView meshopt-compressed. */
+export function meshoptTriangle(): Promise<Uint8Array>;
+
+/** The same triangle with its geometry in a Draco blob. */
+export function dracoTriangle(): Promise<Uint8Array>;
diff --git a/pipeline/tests/fixtures/gltfFixtures.mjs b/pipeline/tests/fixtures/gltfFixtures.mjs
new file mode 100644
index 000000000..f4105317e
--- /dev/null
+++ b/pipeline/tests/fixtures/gltfFixtures.mjs
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file One triangle written two ways: plain, and meshopt-compressed.
+ *
+ * The compressed half is produced by the upstream encoder, so what it exercises
+ * is this project's wiring — extension parsing, the fallback buffer, the decoded
+ * bytes reaching an accessor — rather than a second reading of the codec. Shared
+ * because the same pair is the claim in two places: a unit test on the importer,
+ * and a check that the real editor's import door decodes it too.
+ */
+import { MeshoptEncoder } from 'meshoptimizer/encoder';
+
+const POSITIONS = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
+const UVS = new Float32Array([0, 0, 1, 0, 0, 1]);
+const INDICES = new Uint16Array([0, 1, 2]);
+
+const ACCESSORS = [
+ { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3' },
+ { bufferView: 1, componentType: 5126, count: 3, type: 'VEC2' },
+ { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },
+];
+const MESHES = [{
+ name: 'Tri',
+ primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4 }],
+}];
+
+const raw = (a) => new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
+const encode = (doc) => new TextEncoder().encode(JSON.stringify(doc));
+
+/**
+ * The triangle under a named node, turned a quarter circle about Y over a
+ * second — an exporter's node animation once nothing is skinned.
+ */
+export function animatedTriangle() {
+ const times = new Float32Array([0, 1]);
+ const rotations = new Float32Array([0, 0, 0, 1, 0, Math.SQRT1_2, 0, Math.SQRT1_2]);
+ const geo = Buffer.concat([Buffer.from(raw(POSITIONS)), Buffer.from(raw(UVS)), Buffer.from(raw(INDICES))]);
+ const pad = Buffer.alloc((4 - (geo.length % 4)) % 4);
+ const bytes = Buffer.concat([geo, pad, Buffer.from(raw(times)), Buffer.from(raw(rotations))]);
+ const timesAt = geo.length + pad.length;
+ return encode({
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [
+ { buffer: 0, byteOffset: 0, byteLength: 36 },
+ { buffer: 0, byteOffset: 36, byteLength: 24 },
+ { buffer: 0, byteOffset: 60, byteLength: 6 },
+ { buffer: 0, byteOffset: timesAt, byteLength: times.byteLength },
+ { buffer: 0, byteOffset: timesAt + times.byteLength, byteLength: rotations.byteLength },
+ ],
+ accessors: [
+ ...ACCESSORS,
+ { bufferView: 3, componentType: 5126, count: 2, type: 'SCALAR', min: [0], max: [1] },
+ { bufferView: 4, componentType: 5126, count: 2, type: 'VEC4' },
+ ],
+ meshes: MESHES,
+ nodes: [{ name: 'Turner', mesh: 0 }],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ animations: [{
+ name: 'Turn',
+ channels: [{ sampler: 0, target: { node: 0, path: 'rotation' } }],
+ samplers: [{ input: 3, output: 4, interpolation: 'LINEAR' }],
+ }],
+ });
+}
+
+/** The triangle with its bytes as they are — what any exporter writes by default. */
+export function plainTriangle() {
+ const bytes = Buffer.concat([Buffer.from(raw(POSITIONS)), Buffer.from(raw(UVS)), Buffer.from(raw(INDICES))]);
+ return encode({
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [
+ { buffer: 0, byteOffset: 0, byteLength: 36 },
+ { buffer: 0, byteOffset: 36, byteLength: 24 },
+ { buffer: 0, byteOffset: 60, byteLength: 6 },
+ ],
+ accessors: ACCESSORS,
+ meshes: MESHES,
+ });
+}
+
+/** The same triangle as gltfpack writes it: every bufferView meshopt-compressed. */
+export async function meshoptTriangle() {
+ await MeshoptEncoder.ready;
+ const parts = [
+ { packed: MeshoptEncoder.encodeVertexBuffer(raw(POSITIONS), 3, 12), stride: 12, count: 3, mode: 'ATTRIBUTES', length: 36 },
+ { packed: MeshoptEncoder.encodeVertexBuffer(raw(UVS), 3, 8), stride: 8, count: 3, mode: 'ATTRIBUTES', length: 24 },
+ { packed: MeshoptEncoder.encodeIndexBuffer(raw(INDICES), 3, 2), stride: 2, count: 3, mode: 'TRIANGLES', length: 6 },
+ ];
+ const compressed = Buffer.concat(parts.map((p) => Buffer.from(p.packed)));
+ let packedAt = 0;
+ let plainAt = 0;
+ const bufferViews = parts.map((p) => {
+ // A compressed view names the FALLBACK buffer and the size it decodes to;
+ // the bytes themselves are in the extension, in the compressed buffer.
+ const view = {
+ buffer: 1, byteOffset: plainAt, byteLength: p.length, byteStride: p.stride,
+ extensions: {
+ EXT_meshopt_compression: {
+ buffer: 0, byteOffset: packedAt, byteLength: p.packed.length,
+ byteStride: p.stride, count: p.count, mode: p.mode,
+ },
+ },
+ };
+ packedAt += p.packed.length;
+ plainAt += p.length;
+ return view;
+ });
+ return encode({
+ asset: { version: '2.0' },
+ extensionsRequired: ['EXT_meshopt_compression'],
+ buffers: [
+ { byteLength: compressed.length, uri: `data:application/octet-stream;base64,${compressed.toString('base64')}` },
+ { byteLength: 66, extensions: { EXT_meshopt_compression: { fallback: true } } },
+ ],
+ bufferViews,
+ accessors: ACCESSORS,
+ meshes: MESHES,
+ });
+}
+
+/**
+ * The same triangle Draco-compressed — what Blender writes when its glTF export
+ * has compression on, and the only compression Blender offers.
+ *
+ * Draco reorders vertices to compress them, so a product built from this is
+ * geometrically the same triangle rather than the same bytes.
+ */
+export async function dracoTriangle() {
+ const { createEncoderModule } = await import('draco3dgltf');
+ const draco = await createEncoderModule();
+ const mesh = new draco.Mesh();
+ const builder = new draco.MeshBuilder();
+ builder.AddFacesToMesh(mesh, 1, new Uint32Array(INDICES));
+ const position = builder.AddFloatAttributeToMesh(mesh, draco.POSITION, 3, 3, POSITIONS);
+ const texCoord = builder.AddFloatAttributeToMesh(mesh, draco.TEX_COORD, 3, 2, UVS);
+
+ const encoder = new draco.Encoder();
+ const encoded = new draco.DracoInt8Array();
+ const length = encoder.EncodeMeshToDracoBuffer(mesh, encoded);
+ const blob = new Uint8Array(length);
+ for (let i = 0; i < length; i++) blob[i] = encoded.GetValue(i) & 0xff;
+ for (const handle of [encoded, encoder, mesh, builder]) draco.destroy(handle);
+
+ return encode({
+ asset: { version: '2.0' },
+ extensionsRequired: ['KHR_draco_mesh_compression'],
+ buffers: [{ byteLength: blob.length, uri: `data:application/octet-stream;base64,${Buffer.from(blob).toString('base64')}` }],
+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: blob.length }],
+ // The accessors keep saying what the data MEANS — count and type — while
+ // Draco holds the data itself. That is the shape the spec asks for.
+ accessors: ACCESSORS.map(a => ({ ...a, bufferView: undefined })),
+ meshes: [{
+ name: 'Tri',
+ primitives: [{
+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4,
+ extensions: {
+ KHR_draco_mesh_compression: {
+ bufferView: 0, attributes: { POSITION: position, TEXCOORD_0: texCoord },
+ },
+ },
+ }],
+ }],
+ });
+}
diff --git a/pipeline/tests/fixtures/solidPng.d.mts b/pipeline/tests/fixtures/solidPng.d.mts
new file mode 100644
index 000000000..d8699e3c5
--- /dev/null
+++ b/pipeline/tests/fixtures/solidPng.d.mts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+
+/** A single-colour PNG, for fixtures that need real image bytes. */
+export function solidPng(
+ width: number,
+ height: number,
+ rgba?: readonly [number, number, number, number],
+): Buffer;
diff --git a/pipeline/tests/fixtures/solidPng.mjs b/pipeline/tests/fixtures/solidPng.mjs
new file mode 100644
index 000000000..87e1c752d
--- /dev/null
+++ b/pipeline/tests/fixtures/solidPng.mjs
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Minimal dependency-free solid-color PNG encoder (Node). Used to mint the
+ * hot-update demo's CDN textures deterministically — a green "shipped" art
+ * and a red "update" art — without committing binaries or pulling a codec.
+ */
+import zlib from 'node:zlib';
+
+const CRC_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+function crc32(buf) {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type, data) {
+ const typeBuf = Buffer.from(type, 'ascii');
+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0);
+ const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
+ return Buffer.concat([len, typeBuf, data, crc]);
+}
+
+/** Encode a `width`×`height` solid `[r,g,b,a]` (0–255) image as a PNG Buffer. */
+export function solidPng(width, height, [r, g, b, a] = [0, 0, 0, 255]) {
+ const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 6; // color type: RGBA
+ // ihdr[10..12] = 0: default compression / filter / no interlace.
+ const rowLen = width * 4;
+ const raw = Buffer.alloc((rowLen + 1) * height);
+ for (let y = 0; y < height; y++) {
+ const off = y * (rowLen + 1);
+ raw[off] = 0; // per-row filter: none
+ for (let x = 0; x < width; x++) {
+ const p = off + 1 + x * 4;
+ raw[p] = r; raw[p + 1] = g; raw[p + 2] = b; raw[p + 3] = a;
+ }
+ }
+ const idat = zlib.deflateSync(raw);
+ return Buffer.concat([sig, chunk('IHDR', ihdr), chunk('IDAT', idat), chunk('IEND', Buffer.alloc(0))]);
+}
diff --git a/pipeline/tests/gltf-import.test.ts b/pipeline/tests/gltf-import.test.ts
new file mode 100644
index 000000000..41e8aec15
--- /dev/null
+++ b/pipeline/tests/gltf-import.test.ts
@@ -0,0 +1,874 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file glTF material/image/node import: what the products say about each other.
+ *
+ * The pixel gates prove the chain end to end, but only for the files they draw.
+ * These cover the shapes those are not: an image in a GLB chunk, an image
+ * already on disk, a node given as a matrix, a file with no node tree at all.
+ */
+import { describe, it, expect } from 'vitest';
+import { importGltfMeshes } from '../src/assets/gltfImport';
+import {
+ assembleModelPrefab, materialProducts,
+ type ImportedMesh, type PrefabAssembly, type ProductRefs,
+} from '../src/assets/modelImport';
+import { BlendMode, CullMode, MESH_MAX_BONES, MeshChannel } from 'esengine';
+import { plainTriangle, meshoptTriangle, dracoTriangle } from './fixtures/gltfFixtures.mjs';
+
+const PNG_1PX = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
+
+/** POSITION x3 (VEC3) + TEXCOORD_0 x3 (VEC2) + 3 indices, as one data-uri buffer. */
+function geometryBuffer(): { uri: string; views: unknown[]; accessors: unknown[] } {
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
+ const uvs = new Float32Array([0, 0, 1, 0, 0, 1]);
+ const indices = new Uint16Array([0, 1, 2]);
+ const bytes = Buffer.concat([
+ Buffer.from(positions.buffer), Buffer.from(uvs.buffer), Buffer.from(indices.buffer),
+ ]);
+ return {
+ uri: `data:application/octet-stream;base64,${bytes.toString('base64')}`,
+ views: [
+ { buffer: 0, byteOffset: 0, byteLength: 36 },
+ { buffer: 0, byteOffset: 36, byteLength: 24 },
+ { buffer: 0, byteOffset: 60, byteLength: 6 },
+ ],
+ accessors: [
+ { bufferView: 0, componentType: 5126, count: 3, type: 'VEC3' },
+ { bufferView: 1, componentType: 5126, count: 3, type: 'VEC2' },
+ { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },
+ ],
+ };
+}
+
+function gltf(extra: Record<string, unknown>, primitives?: unknown[]): Uint8Array {
+ const geo = geometryBuffer();
+ const doc = {
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: 66, uri: geo.uri }],
+ bufferViews: geo.views,
+ accessors: geo.accessors,
+ meshes: [{
+ name: 'Tri',
+ primitives: primitives ?? [{
+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4,
+ }],
+ }],
+ ...extra,
+ };
+ return new TextEncoder().encode(JSON.stringify(doc));
+}
+
+/** The material every case below varies from: one baseColor image, one factor. */
+function withInlineImage(): Record<string, unknown> {
+ return {
+ images: [{ mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` }],
+ textures: [{ source: 0 }],
+ materials: [{
+ name: 'Base',
+ pbrMetallicRoughness: {
+ baseColorFactor: [0.25, 0.5, 0.75, 1], baseColorTexture: { index: 0 },
+ metallicFactor: 0,
+ },
+ }],
+ };
+}
+
+function texCoords(mesh: ImportedMesh): number[] {
+ const channel = mesh.data.channels.find(c => c.semantic === MeshChannel.TexCoord0)!;
+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ const out: number[] = [];
+ for (let i = 0; i < mesh.vertexCount; i++) {
+ const at = i * mesh.data.vertexStride + channel.offset;
+ out.push(view.getFloat32(at, true), view.getFloat32(at + 4, true));
+ }
+ return out;
+}
+
+describe('glTF material import', () => {
+ it('extracts an inline image and names it in the material', async () => {
+ const { meshes, textures, warnings } = await importGltfMeshes(gltf(withInlineImage()), 'model');
+ expect(warnings).toEqual([]);
+ expect(textures).toHaveLength(1);
+ expect(textures[0]!.name).toBe('model_0.png');
+ expect(textures[0]!.bytes.length).toBeGreaterThan(0);
+ expect(meshes[0]!.material).toMatchObject({
+ baseColor: [0.25, 0.5, 0.75, 1],
+ baseColorTexture: { file: 'model_0.png', external: false },
+ });
+ });
+
+ it('references an image already on disk instead of copying it', async () => {
+ const doc = withInlineImage();
+ doc.images = [{ uri: 'textures/diffuse%20map.png' }];
+ const { meshes, textures } = await importGltfMeshes(gltf(doc), 'model');
+ expect(textures).toEqual([]);
+ expect(meshes[0]!.material?.baseColorTexture)
+ .toEqual({ file: 'textures/diffuse map.png', external: true });
+ });
+
+ it('reads an image out of a GLB binary chunk', async () => {
+ const png = Buffer.from(PNG_1PX, 'base64');
+ const geo = geometryBuffer();
+ const bin = Buffer.concat([Buffer.from(geo.uri.split(',')[1]!, 'base64'), png]);
+ const json = Buffer.from(JSON.stringify({
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bin.length }],
+ bufferViews: [
+ ...(geo.views as { byteLength: number }[]),
+ { buffer: 0, byteOffset: 66, byteLength: png.length },
+ ],
+ accessors: geo.accessors,
+ images: [{ mimeType: 'image/png', bufferView: 3 }],
+ textures: [{ source: 0 }],
+ materials: [{ pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],
+ meshes: [{ primitives: [{
+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4,
+ }] }],
+ }));
+ const pad = (b: Buffer, fill: number) =>
+ Buffer.concat([b, Buffer.alloc((4 - (b.length % 4)) % 4, fill)]);
+ const jsonChunk = pad(json, 0x20);
+ const binChunk = pad(bin, 0);
+ const header = Buffer.alloc(12);
+ header.writeUInt32LE(0x46546c67, 0);
+ header.writeUInt32LE(2, 4);
+ header.writeUInt32LE(12 + 8 + jsonChunk.length + 8 + binChunk.length, 8);
+ const chunk = (body: Buffer, kind: number) => {
+ const head = Buffer.alloc(8);
+ head.writeUInt32LE(body.length, 0);
+ head.writeUInt32LE(kind, 4);
+ return Buffer.concat([head, body]);
+ };
+ const glb = Buffer.concat([
+ header, chunk(jsonChunk, 0x4e4f534a), chunk(binChunk, 0x004e4942),
+ ]);
+
+ const { meshes, textures } = await importGltfMeshes(new Uint8Array(glb), 'robot');
+ expect(textures).toHaveLength(1);
+ expect(textures[0]!.name).toBe('robot_0.png');
+ expect(Buffer.from(textures[0]!.bytes).equals(png)).toBe(true);
+ expect(meshes[0]!.material?.baseColorTexture?.file).toBe('robot_0.png');
+ });
+
+ it('reports the PBR channels it cannot draw rather than dropping them', async () => {
+ const doc = withInlineImage();
+ doc.materials = [{
+ name: 'Metal',
+ pbrMetallicRoughness: { metallicFactor: 1, roughnessFactor: 0.3 },
+ normalTexture: { index: 0, scale: 0.4 }, emissiveFactor: [1, 0, 0],
+ alphaMode: 'MASK', alphaCutoff: 0.4, doubleSided: false,
+ extensions: { KHR_materials_clearcoat: {} },
+ }];
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
+ const line = warnings.join('\n');
+ expect(line).toContain('normal-map scale 0.4');
+ expect(line).toContain('KHR_materials_clearcoat');
+ // The channels that DO reach a shader are products, not warnings — metal and
+ // roughness among them now that the lighting model has a view direction.
+ expect(line).not.toContain('metallic-roughness');
+ expect(line).not.toContain('emissive');
+ expect(line).not.toContain('alpha cutoff');
+ expect(materialProducts(meshes, 'model')[0]!.data.properties)
+ .toMatchObject({ u_metallic: 1, u_roughness: 0.3 });
+ });
+
+ it('is opaque and single-sided unless the source says otherwise', async () => {
+ // Both are the glTF's own defaults, so a model arrives occluding itself the
+ // way it was authored rather than as a stack of blended planes.
+ const plain = (await importGltfMeshes(gltf(withInlineImage()), 'model')).meshes[0]!;
+ expect(plain.material).toMatchObject({ opaque: true, cullBackfaces: true });
+
+ const doc = withInlineImage();
+ (doc.materials as Record<string, unknown>[])[0]!.alphaMode = 'BLEND';
+ (doc.materials as Record<string, unknown>[])[0]!.doubleSided = true;
+ const blended = (await importGltfMeshes(gltf(doc), 'model')).meshes[0]!;
+ expect(blended.material).toMatchObject({ opaque: false, cullBackfaces: false });
+ });
+
+ it('carries a normal map, extracting its image like any other', async () => {
+ const doc = withInlineImage();
+ doc.images = [
+ { mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` },
+ { uri: 'bump.png' },
+ ];
+ doc.textures = [{ source: 0 }, { source: 1 }];
+ (doc.materials as { normalTexture?: unknown }[])[0]!.normalTexture = { index: 1 };
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
+ expect(warnings).toEqual([]);
+ expect(meshes[0]!.material?.normalTexture)
+ .toEqual({ file: 'bump.png', external: true });
+ });
+
+ it('says so when a Draco blob will not decode, rather than reading zeroes', async () => {
+ // The accessors of a Draco primitive point at nothing by design, so a blob
+ // that fails to decode has to be reported: read as ordinary accessors, the
+ // very same file is a mesh of vertices on the origin.
+ const doc = {
+ ...withInlineImage(),
+ accessors: [
+ { componentType: 5126, count: 3, type: 'VEC3' },
+ { componentType: 5126, count: 3, type: 'VEC2' },
+ { componentType: 5123, count: 3, type: 'SCALAR' },
+ ],
+ };
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc, [{
+ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4,
+ extensions: { KHR_draco_mesh_compression: { bufferView: 0, attributes: {} } },
+ }]), 'model');
+ expect(meshes).toEqual([]);
+ expect(warnings.join('\n')).toContain('Draco decode failed');
+ });
+
+ it('skips a primitive whose POSITION carries no data', async () => {
+ const doc = {
+ ...withInlineImage(),
+ accessors: [
+ { componentType: 5126, count: 3, type: 'VEC3' },
+ { bufferView: 1, componentType: 5126, count: 3, type: 'VEC2' },
+ { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },
+ ],
+ };
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
+ expect(meshes).toEqual([]);
+ expect(warnings.join('\n')).toContain('POSITION has no data');
+ });
+
+ it('applies a sparse accessor, which is the geometry it actually has', async () => {
+ // Replaces vertex 1's position; the base view is the ordinary one.
+ const target = Buffer.alloc(2);
+ target.writeUInt16LE(1, 0);
+ const value = Buffer.from(new Float32Array([9, 9, 9]).buffer);
+ const extra = Buffer.concat([target, value]);
+ const geo = geometryBuffer();
+ const base = Buffer.from(geo.uri.split(',')[1]!, 'base64');
+ const bytes = Buffer.concat([base, extra]);
+ const doc = {
+ ...withInlineImage(),
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [
+ ...(geo.views as unknown[]),
+ { buffer: 0, byteOffset: 66, byteLength: 2 },
+ { buffer: 0, byteOffset: 68, byteLength: 12 },
+ ],
+ accessors: [
+ {
+ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3',
+ sparse: {
+ count: 1,
+ indices: { bufferView: 3, componentType: 5123 },
+ values: { bufferView: 4 },
+ },
+ },
+ { bufferView: 1, componentType: 5126, count: 3, type: 'VEC2' },
+ { bufferView: 2, componentType: 5123, count: 3, type: 'SCALAR' },
+ ],
+ };
+ const { meshes } = await importGltfMeshes(gltf(doc), 'model');
+ expect(meshes[0]!.data.aabbMax).toEqual([9, 9, 9]);
+ });
+
+ it("carries a sampler's filter and wrap as import settings", async () => {
+ const doc = withInlineImage();
+ doc.samplers = [{ magFilter: 9728, wrapS: 33071, wrapT: 33071 }];
+ (doc.textures as { sampler?: number }[])[0]!.sampler = 0;
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
+ expect(warnings).toEqual([]);
+ expect(meshes[0]!.material?.baseColorTexture?.settings)
+ .toEqual({ filterMode: 'nearest', wrapMode: 'clamp' });
+ });
+
+ it('says which wrap it kept when the source addresses u and v differently', async () => {
+ const doc = withInlineImage();
+ doc.samplers = [{ wrapS: 33071, wrapT: 10497 }];
+ (doc.textures as { sampler?: number }[])[0]!.sampler = 0;
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
+ expect(warnings.join('\n')).toContain('wrapS and wrapT differ');
+ expect(meshes[0]!.material?.baseColorTexture?.settings?.wrapMode).toBe('clamp');
+ });
+
+ it('reports deformation it cannot carry: morph targets, and joints nothing binds', async () => {
+ const doc = {
+ ...withInlineImage(),
+ skins: [{}],
+ nodes: [{ mesh: 0, skin: 0 }], scenes: [{ nodes: [0] }], scene: 0,
+ };
+ const { warnings } = await importGltfMeshes(gltf(doc, [{
+ attributes: { POSITION: 0, TEXCOORD_0: 1, JOINTS_0: 1 }, indices: 2, material: 0, mode: 4,
+ targets: [{}, {}],
+ }]), 'model');
+ const line = warnings.join('\n');
+ expect(line).toContain('2 morph target(s) not imported');
+ expect(line).toContain('a skin naming joints');
+ });
+
+ it('reports a uv rewrite it does not apply', async () => {
+ const doc = withInlineImage();
+ (doc.materials as { pbrMetallicRoughness: { baseColorTexture: Record<string, unknown> } }[])[0]!
+ .pbrMetallicRoughness.baseColorTexture.extensions = { KHR_texture_transform: { scale: [2, 2] } };
+ const { warnings } = await importGltfMeshes(gltf(doc), 'model');
+ expect(warnings.join('\n')).toContain('KHR_texture_transform not imported');
+ });
+
+ it("flips V, because glTF's uv origin is the image's top-left", async () => {
+ const { meshes } = await importGltfMeshes(gltf(withInlineImage()), 'model');
+ expect(texCoords(meshes[0]!)).toEqual([0, 1, 1, 1, 0, 0]);
+ });
+});
+
+describe('glTF material products', () => {
+ const shaded = (extra: Record<string, unknown>): Record<string, unknown> => {
+ const doc = withInlineImage();
+ doc.materials = [{ name: 'Shaded', ...extra }];
+ return doc;
+ };
+ const productsOf = async (doc: Record<string, unknown>, refs: ProductRefs = {}) => {
+ const { meshes } = await importGltfMeshes(gltf(doc), 'model');
+ return { meshes, products: materialProducts(meshes, 'model', refs) };
+ };
+
+ it('writes nothing for a material a Mesh2D already carries whole', async () => {
+ // baseColor is the component's own texture x colour, so a material here
+ // would be a second file saying what the first one says.
+ const { products } = await productsOf(withInlineImage());
+ expect(products).toEqual([]);
+ });
+
+ it('carries the channels a component has no room for', async () => {
+ const { products } = await productsOf(shaded({
+ emissiveFactor: [1, 0.5, 0], emissiveTexture: { index: 0 },
+ occlusionTexture: { index: 0, strength: 0.25 },
+ alphaMode: 'MASK', alphaCutoff: 0.4,
+ }), { prefix: 'assets/models/' });
+ expect(products).toHaveLength(1);
+ expect(products[0]!.name).toBe('model_m0');
+ expect(products[0]!.data.shader).toBe('builtin:model');
+ // A material with no pbrMetallicRoughness block is glTF's default: fully
+ // metallic, fully rough. Written out, since the engine's own default is not.
+ expect(products[0]!.data.properties).toEqual({
+ u_emissive: { r: 1, g: 0.5, b: 0, a: 1 },
+ u_emissiveMap: 'model_0.png',
+ u_occlusionMap: 'model_0.png',
+ u_occlusionStrength: 0.25,
+ u_alphaCutoff: 0.4,
+ u_metallic: 1,
+ u_roughness: 1,
+ });
+ });
+
+ it('takes the normal map WITH it, off the component', async () => {
+ // A material shader samples its own units; a map left on the component
+ // would be one nothing reads.
+ const { meshes, products } = await productsOf(
+ shaded({ normalTexture: { index: 0 }, emissiveFactor: [1, 1, 1] }),
+ { prefix: 'assets/models/' });
+ expect(products[0]!.data.properties.u_normalMap).toBe('model_0.png');
+ const prefab = assembleModelPrefab('model', meshes, { refs: { prefix: 'assets/models/' } });
+ const mesh2d = prefab.entities[1]!.components[1]!.data;
+ expect(mesh2d.material).toBe('assets/models/model_m0.esmaterial');
+ expect(mesh2d.normalMap).toBeUndefined();
+ });
+
+ it('says the render state the draw would otherwise have said itself', async () => {
+ // A material REPLACES the draw's blend/depth/cull, so a model told to
+ // occlude itself must keep saying so through the material.
+ const opaque = await productsOf(shaded({ emissiveFactor: [1, 1, 1] }));
+ expect(opaque.products[0]!.data).toMatchObject({
+ blendMode: BlendMode.None, depthTest: true, depthWrite: true, cull: CullMode.Back,
+ });
+ const blended = await productsOf(shaded({
+ emissiveFactor: [1, 1, 1], alphaMode: 'BLEND', doubleSided: true,
+ }));
+ expect(blended.products[0]!.data).toMatchObject({
+ blendMode: BlendMode.Normal, depthTest: false, depthWrite: false, cull: CullMode.None,
+ });
+ });
+
+ it('writes one product for a material several primitives share', async () => {
+ const doc = shaded({ emissiveFactor: [0, 0, 1] });
+ const { meshes } = await importGltfMeshes(gltf(doc, [
+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4 },
+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4 },
+ ]), 'model');
+ const refs = { prefix: 'assets/models/' };
+ expect(materialProducts(meshes, 'model', refs)).toHaveLength(1);
+ const prefab = assembleModelPrefab('model', meshes, { refs });
+ const refsUsed = prefab.entities.flatMap(e => e.components
+ .filter(c => c.type === 'Mesh2D').map(c => c.data.material));
+ expect(refsUsed).toEqual(['assets/models/model_m0.esmaterial',
+ 'assets/models/model_m0.esmaterial']);
+ });
+
+ it('spells an image already in the project as a logical path', async () => {
+ // A material resolves a relative ref against its own directory, and this one
+ // is not beside it.
+ const doc = shaded({ emissiveTexture: { index: 0 } });
+ doc.images = [{ uri: 'shared/glow.png' }];
+ const inAssets = await productsOf(doc, {
+ prefix: 'assets/models/', external: (uri) => `assets/${uri}`,
+ });
+ expect(inAssets.products[0]!.data.properties.u_emissiveMap).toBe('assets/shared/glow.png');
+ const elsewhere = await productsOf(doc, {
+ prefix: 'models/', external: (uri) => `art/${uri}`,
+ });
+ expect(elsewhere.products[0]!.data.properties.u_emissiveMap).toBe('/art/shared/glow.png');
+ });
+});
+
+describe('glTF prefab assembly', () => {
+ const assemble = async (bytes: Uint8Array, options: Partial<PrefabAssembly> = {}) => {
+ const { meshes, nodes } = await importGltfMeshes(bytes, 'model');
+ return assembleModelPrefab('model', meshes, { nodes, ...options });
+ };
+ const oneNode = { nodes: [{ mesh: 0 }], scenes: [{ nodes: [0] }], scene: 0 };
+
+ it('draws a single-primitive node from the node itself', async () => {
+ const prefab = await assemble(gltf({ ...withInlineImage(), ...oneNode }),
+ { refs: { prefix: 'assets/models/' } });
+ expect(prefab.entities).toHaveLength(1);
+ expect(prefab.rootEntityId).toBe('n0');
+ expect(prefab.entities[0]!.components[1]).toEqual({
+ type: 'Mesh2D',
+ data: {
+ mesh: 'assets/models/model.esmesh',
+ texture: 'assets/models/model_0.png',
+ color: { r: 0.25, g: 0.5, b: 0.75, a: 1 },
+ opaque: true,
+ cullBackfaces: true,
+ enabled: true,
+ },
+ });
+ });
+
+ it('points the root at a clip, stopped', async () => {
+ const prefab = await assemble(gltf({ ...withInlineImage(), ...oneNode }),
+ { timeline: 'assets/models/model_Spin.estimeline' });
+ // Stopped: the products say what the model HAS. Playing it is the scene's.
+ expect(prefab.entities[0]!.components.at(-1)).toEqual({
+ type: 'TimelinePlayer',
+ data: { timeline: 'assets/models/model_Spin.estimeline', playing: false },
+ });
+ });
+
+ it('hangs a node’s further primitives off it', async () => {
+ const two = [
+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0, mode: 4 },
+ { attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4 },
+ ];
+ const prefab = await assemble(gltf({ ...withInlineImage(), ...oneNode }, two));
+ expect(prefab.entities.map(e => e.prefabEntityId)).toEqual(['n0', 'n0_p0', 'n0_p1']);
+ expect(prefab.entities[0]!.children).toEqual(['n0_p0', 'n0_p1']);
+ expect(prefab.entities[1]!.parent).toBe('n0');
+ // The second primitive names no material: no texture, no tint, engine defaults.
+ expect(prefab.entities[2]!.components[1]!.data).toEqual({
+ mesh: 'model_0_1.esmesh', enabled: true,
+ }); // no material named: engine defaults, blended and two-sided
+ });
+
+ it('places each node where the source puts it, parents included', async () => {
+ const doc = {
+ ...withInlineImage(),
+ nodes: [
+ { name: 'Model', translation: [40, 0, 0], children: [1, 2] },
+ { name: 'Left', mesh: 0, translation: [-120, 60, 0] },
+ { name: 'Right', mesh: 0, scale: [0.5, 0.5, 1] },
+ ],
+ scenes: [{ nodes: [0] }], scene: 0,
+ };
+ const prefab = await assemble(gltf(doc));
+ expect(prefab.entities.map(e => e.name)).toEqual(['Model', 'Left', 'Right']);
+ expect(prefab.entities[0]!.components[0]!.data)
+ .toEqual({ position: { x: 40, y: 0, z: 0 } });
+ expect(prefab.entities[1]!.components[0]!.data)
+ .toEqual({ position: { x: -120, y: 60, z: 0 } });
+ expect(prefab.entities[2]!.components[0]!.data)
+ .toEqual({ scale: { x: 0.5, y: 0.5, z: 1 } });
+ // One mesh drawn by two nodes is one product referenced twice.
+ expect(prefab.entities[1]!.components[1]!.data.mesh)
+ .toBe(prefab.entities[2]!.components[1]!.data.mesh);
+ });
+
+ it('decomposes a node given as a matrix', async () => {
+ const doc = {
+ ...withInlineImage(),
+ // 90° about Z, scaled 2, moved to (10, 20, 30) — column-major.
+ nodes: [{ mesh: 0, matrix: [0, 2, 0, 0, -2, 0, 0, 0, 0, 0, 2, 0, 10, 20, 30, 1] }],
+ scenes: [{ nodes: [0] }], scene: 0,
+ };
+ const data = (await assemble(gltf(doc))).entities[0]!.components[0]!.data as {
+ position: { x: number }; rotation: { z: number; w: number }; scale: { x: number };
+ };
+ expect(data.position).toEqual({ x: 10, y: 20, z: 30 });
+ expect(data.scale.x).toBeCloseTo(2);
+ expect(data.rotation.z).toBeCloseTo(Math.SQRT1_2);
+ expect(data.rotation.w).toBeCloseTo(Math.SQRT1_2);
+ });
+
+ it('leaves out a normal map the geometry has no normals for', async () => {
+ const doc = withInlineImage();
+ doc.images = [
+ { mimeType: 'image/png', uri: `data:image/png;base64,${PNG_1PX}` },
+ { uri: 'bump.png' },
+ ];
+ doc.textures = [{ source: 0 }, { source: 1 }];
+ (doc.materials as { normalTexture?: unknown }[])[0]!.normalTexture = { index: 1 };
+ // The fixture's primitive declares no NORMAL, so the engine draws it unlit —
+ // a normal map there would be a ref to something nothing reads.
+ const prefab = await assemble(gltf({ ...doc, ...oneNode }));
+ expect(prefab.entities[0]!.components[1]!.data.normalMap).toBeUndefined();
+ });
+
+ it('scales the root, since a glTF is in metres', async () => {
+ const prefab = await assemble(gltf({ ...withInlineImage(), ...oneNode }), { scale: 32 });
+ expect(prefab.entities[0]!.components[0]!.data)
+ .toEqual({ scale: { x: 32, y: 32, z: 32 } });
+ });
+
+ it('lays the meshes under a holder when the file has no nodes', async () => {
+ const prefab = await assemble(gltf(withInlineImage()));
+ expect(prefab.entities.map(e => e.prefabEntityId)).toEqual(['root', 'm0']);
+ expect(prefab.entities[1]!.parent).toBe('root');
+ });
+
+ it('spells an external image through the project resolver', async () => {
+ const doc = withInlineImage();
+ doc.images = [{ uri: '../textures/skin.png' }];
+ const prefab = await assemble(gltf({ ...doc, ...oneNode }), {
+ refs: {
+ prefix: 'assets/models/',
+ external: uri => `assets/${uri.replace('../', '')}`,
+ },
+ });
+ expect(prefab.entities[0]!.components[1]!.data.texture).toBe('assets/textures/skin.png');
+ });
+});
+
+/**
+ * A glTF whose animation sampler data is appended to the geometry buffer.
+ * Accessors 0-2 are the triangle; 3 is the sampler input, 4 its output.
+ */
+function animatedGltf(opts: {
+ times: number[]; values: number[]; components: number;
+ path?: string; interpolation?: string;
+ nodes?: unknown[]; targetNode?: number; skins?: unknown[];
+}): Uint8Array {
+ const geo = geometryBuffer();
+ const geoBytes = Buffer.from(geo.uri.split(',')[1]!, 'base64');
+ const pad = Buffer.alloc((4 - (geoBytes.length % 4)) % 4);
+ const times = Buffer.from(new Float32Array(opts.times).buffer);
+ const values = Buffer.from(new Float32Array(opts.values).buffer);
+ const bytes = Buffer.concat([geoBytes, pad, times, values]);
+ const timesAt = geoBytes.length + pad.length;
+ const type = ['SCALAR', '', 'VEC2', 'VEC3', 'VEC4'][opts.components]!;
+
+ const doc = {
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [
+ ...(geo.views as Record<string, unknown>[]),
+ { buffer: 0, byteOffset: timesAt, byteLength: times.length },
+ { buffer: 0, byteOffset: timesAt + times.length, byteLength: values.length },
+ ],
+ accessors: [
+ ...(geo.accessors as Record<string, unknown>[]),
+ { bufferView: 3, componentType: 5126, count: opts.times.length, type: 'SCALAR' },
+ { bufferView: 4, componentType: 5126, count: opts.values.length / opts.components, type },
+ ],
+ meshes: [{ name: 'Tri', primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, mode: 4 }] }],
+ nodes: opts.nodes ?? [{ name: 'Root', children: [1] }, { name: 'Spinner', mesh: 0 }],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ ...(opts.skins ? { skins: opts.skins } : {}),
+ animations: [{
+ name: 'Spin',
+ channels: [{ sampler: 0, target: { node: opts.targetNode ?? 1, path: opts.path ?? 'rotation' } }],
+ samplers: [{ input: 3, output: 4, interpolation: opts.interpolation ?? 'LINEAR' }],
+ }],
+ };
+ return new TextEncoder().encode(JSON.stringify(doc));
+}
+
+describe('glTF animation import', () => {
+ const HALF = Math.SQRT1_2;
+
+ it('turns a rotation channel into four component channels on the target node', async () => {
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0, 1], values: [0, 0, 0, 1, 0, HALF, 0, HALF], components: 4,
+ }), 'robot');
+
+ expect(result.animations).toHaveLength(1);
+ const doc = result.animations[0]!.document as any;
+ expect(result.animations[0]!.name).toBe('robot_Spin');
+ expect(doc.duration).toBe(1);
+ expect(doc.tracks).toHaveLength(1);
+ // The lone root IS the prefab root, so its child is addressed by its name.
+ expect(doc.tracks[0].childPath).toBe('Spinner');
+ expect(doc.tracks[0].component).toBe('Transform');
+ expect(doc.tracks[0].channels.map((c: any) => c.property))
+ .toEqual(['rotation.x', 'rotation.y', 'rotation.z', 'rotation.w']);
+ const y = doc.tracks[0].channels[1].keyframes;
+ expect(y[0]).toMatchObject({ time: 0, value: 0, interpolation: 'linear' });
+ expect(y[1].value).toBeCloseTo(HALF, 6);
+ });
+
+ it('carries a CUBICSPLINE tangent into the keyframe it belongs to', async () => {
+ // Per key: [inTangent, value, outTangent] — one scalar-per-component triple.
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0, 1], components: 3, path: 'translation', interpolation: 'CUBICSPLINE',
+ values: [
+ 0, 0, 0, /* v0 */ 0, 0, 0, /* out */ 2, 0, 0,
+ 3, 0, 0, /* v1 */ 10, 0, 0, /* out */ 0, 0, 0,
+ ],
+ }), 'robot');
+
+ const x = (result.animations[0]!.document as any).tracks[0].channels[0].keyframes;
+ expect(x[0]).toMatchObject({ value: 0, inTangent: 0, outTangent: 2, interpolation: 'hermite' });
+ expect(x[1]).toMatchObject({ value: 10, inTangent: 3, outTangent: 0 });
+ });
+
+ it('flips a quaternion keyframe that would interpolate the long way round', async () => {
+ // 170° about Y, then the SAME rotation written negated: component-wise that
+ // is a 190° turn backwards unless the sign is aligned.
+ const s = Math.sin((170 * Math.PI) / 180 / 2);
+ const c = Math.cos((170 * Math.PI) / 180 / 2);
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0, 1], components: 4, values: [0, s, 0, c, -0, -s, -0, -c],
+ }), 'robot');
+
+ const ch = (result.animations[0]!.document as any).tracks[0].channels;
+ const yEnd = ch[1].keyframes[1].value;
+ const wEnd = ch[3].keyframes[1].value;
+ expect(yEnd).toBeCloseTo(s, 6);
+ expect(wEnd).toBeCloseTo(c, 6);
+ });
+
+ it('gives two siblings of the same name distinct paths', async () => {
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0], components: 3, path: 'translation', values: [1, 2, 3], targetNode: 2,
+ nodes: [
+ { name: 'Root', children: [1, 2] },
+ { name: 'Arm', mesh: 0 },
+ { name: 'Arm' },
+ ],
+ }), 'robot');
+
+ const paths = result.nodes[0]!.children.map(n => n.name);
+ expect(paths).toEqual(['Arm', 'Arm_2']);
+ expect((result.animations[0]!.document as any).tracks[0].childPath).toBe('Arm_2');
+ });
+
+ it('says a channel aimed at a skinned mesh node moves nothing', async () => {
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0, 1], components: 4, values: [0, 0, 0, 1, 0, HALF, 0, HALF],
+ skins: [{ joints: [1] }],
+ nodes: [{ name: 'Root', children: [1] }, { name: 'Spinner', mesh: 0, skin: 0 }],
+ }), 'robot');
+
+ expect(result.animations).toHaveLength(1);
+ expect(result.warnings.some(w => /moves nothing/.test(w))).toBe(true);
+ });
+
+ it('reports a morph-weight channel rather than dropping it', async () => {
+ const result = await importGltfMeshes(animatedGltf({
+ times: [0, 1], components: 1, path: 'weights', values: [0, 1],
+ }), 'robot');
+
+ expect(result.animations).toHaveLength(0);
+ expect(result.warnings.some(w => /weights/.test(w))).toBe(true);
+ });
+});
+
+/**
+ * The triangle bound to two joints. Accessors 3/4 are JOINTS_0 (u16) and
+ * WEIGHTS_0; 5 is the skin's inverse bind matrices unless the caller drops it.
+ */
+function skinnedGltf(opts: {
+ noBindMatrices?: boolean; skinOnNode?: boolean; weights?: boolean; extraJoints?: number;
+} = {}): Uint8Array {
+ const geo = geometryBuffer();
+ const geoBytes = Buffer.from(geo.uri.split(',')[1]!, 'base64');
+ const pad = Buffer.alloc((4 - (geoBytes.length % 4)) % 4);
+ const joints = Buffer.from(new Uint16Array([0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0]).buffer);
+ const weights = Buffer.from(new Float32Array([
+ 0.75, 0.25, 0, 0, 1, 0, 0, 0, 0.5, 0.5, 0, 0,
+ ]).buffer);
+ // Joint 1's bind pose sits 30 along x; joint 0's is identity.
+ const bind = new Float32Array(32);
+ for (let j = 0; j < 2; j++) for (let c = 0; c < 4; c++) bind[j * 16 + c * 5] = 1;
+ bind[16 + 12] = 30;
+ const parts = [geoBytes, pad, joints, weights, Buffer.from(bind.buffer)];
+ const bytes = Buffer.concat(parts);
+ let at = geoBytes.length + pad.length;
+ const views: Record<string, unknown>[] = [];
+ for (const p of [joints, weights, Buffer.from(bind.buffer)]) {
+ views.push({ buffer: 0, byteOffset: at, byteLength: p.length });
+ at += p.length;
+ }
+
+ const extra = Array.from({ length: opts.extraJoints ?? 0 });
+ const doc: Record<string, unknown> = {
+ asset: { version: '2.0' },
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [...(geo.views as Record<string, unknown>[]), ...views],
+ accessors: [
+ ...(geo.accessors as Record<string, unknown>[]),
+ { bufferView: 3, componentType: 5123, count: 3, type: 'VEC4' },
+ { bufferView: 4, componentType: 5126, count: 3, type: 'VEC4' },
+ { bufferView: 5, componentType: 5126, count: 2, type: 'MAT4' },
+ ],
+ meshes: [{
+ name: 'Tri',
+ primitives: [{
+ attributes: {
+ POSITION: 0, TEXCOORD_0: 1, JOINTS_0: 3,
+ ...(opts.weights === false ? {} : { WEIGHTS_0: 4 }),
+ },
+ indices: 2, mode: 4,
+ }],
+ }],
+ nodes: [
+ { name: 'Rig', children: [1, 2, 3, ...extra.map((_, i) => 4 + i)] },
+ { name: 'Hip' },
+ { name: 'Knee', translation: [30, 0, 0] },
+ { name: 'Body', mesh: 0, ...(opts.skinOnNode === false ? {} : { skin: 0 }) },
+ ...extra.map((_, i) => ({ name: `Spare${i}` })),
+ ],
+ scenes: [{ nodes: [0] }],
+ scene: 0,
+ skins: [{
+ joints: [1, 2, ...extra.map((_, i) => 4 + i)],
+ // A longer joint list than the accessor has matrices for is its own
+ // (already covered) warning, so drop the accessor when the list grows.
+ ...(opts.noBindMatrices || extra.length > 0 ? {} : { inverseBindMatrices: 5 }),
+ }],
+ };
+ return new TextEncoder().encode(JSON.stringify(doc));
+}
+
+describe('glTF skinning import', () => {
+ it('carries the joint channel, the weights and the bind pose', async () => {
+ const { meshes, warnings } = await importGltfMeshes(skinnedGltf(), 'rig');
+ const mesh = meshes[0]!;
+
+ const joints = mesh.data.channels.find((c) => c.semantic === MeshChannel.Joints);
+ const weights = mesh.data.channels.find((c) => c.semantic === MeshChannel.Weights);
+ expect(joints).toMatchObject({ components: 4, type: 2 /* UInt16 */ });
+ expect(weights).toMatchObject({ components: 4, type: 0 /* Float32 */ });
+
+ const dv = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ expect(dv.getUint16(joints!.offset + 2, true)).toBe(1);
+ expect(dv.getFloat32(weights!.offset, true)).toBeCloseTo(0.75, 6);
+
+ // The bind pose comes from the SKIN, and the joints are its node list.
+ expect(mesh.data.inverseBindMatrices).toHaveLength(32);
+ expect(mesh.data.inverseBindMatrices![16 + 12]).toBe(30);
+ expect(mesh.skinJoints).toEqual([1, 2]);
+ expect(warnings.filter((w) => /skin/i.test(w))).toEqual([]);
+ });
+
+ it('treats a missing bind accessor as an identity bind pose', async () => {
+ const { meshes } = await importGltfMeshes(skinnedGltf({ noBindMatrices: true }), 'rig');
+ const bind = meshes[0]!.data.inverseBindMatrices!;
+ expect(bind[0]).toBe(1);
+ expect(bind[16 + 12]).toBe(0);
+ });
+
+ it('imports static, and says so, when nothing binds the joints', async () => {
+ for (const opts of [{ skinOnNode: false }, { weights: false }]) {
+ const { meshes, warnings } = await importGltfMeshes(skinnedGltf(opts), 'rig');
+ expect(meshes[0]!.data.channels.some((c) => c.semantic === MeshChannel.Joints)).toBe(false);
+ expect(meshes[0]!.skinJoints).toBeUndefined();
+ expect(warnings.some((w) => /JOINTS_0 without/.test(w))).toBe(true);
+ }
+ });
+
+ it('imports static, and says the budget, when a skin binds more joints than a draw can pose', async () => {
+ // The joint indices in the vertices index the SKIN's list, so a list longer
+ // than the pose block means indices no uploaded matrix answers to. Drawn
+ // wrong, the vertices go somewhere arbitrary; this is the file saying so.
+ const over = MESH_MAX_BONES + 1;
+ const { meshes, warnings } = await importGltfMeshes(
+ skinnedGltf({ extraJoints: over - 2 }), 'rig');
+ expect(meshes[0]!.data.channels.some((c) => c.semantic === MeshChannel.Joints)).toBe(false);
+ expect(meshes[0]!.data.inverseBindMatrices).toBeUndefined();
+ expect(meshes[0]!.skinJoints).toBeUndefined();
+ expect(warnings.some((w) => w.includes(`binds ${over} joints`)
+ && w.includes(`${MESH_MAX_BONES}`) && /imported static/.test(w))).toBe(true);
+ });
+
+ it('poses a skin that fills the budget exactly', async () => {
+ // The boundary itself, so the check cannot be an off-by-one that quietly
+ // costs a rig its last bone.
+ const { meshes, warnings } = await importGltfMeshes(
+ skinnedGltf({ extraJoints: MESH_MAX_BONES - 2 }), 'rig');
+ expect(meshes[0]!.skinJoints).toHaveLength(MESH_MAX_BONES);
+ expect(warnings.some((w) => /imported static/.test(w))).toBe(false);
+ });
+
+ it('names the joint entities the prefab gives those nodes', async () => {
+ const { meshes, nodes } = await importGltfMeshes(skinnedGltf(), 'rig');
+ const prefab = assembleModelPrefab('rig', meshes, { nodes });
+ const body = prefab.entities.find((e) => e.name === 'Body')!;
+ const skin = body.components.find((c) => c.type === 'MeshSkin');
+ expect(skin?.data).toEqual({ joints: ['n1', 'n2'] });
+ // Those ids are entities the same prefab carries — a joint list pointing
+ // outside it would resolve to nothing at instantiation.
+ const ids = prefab.entities.map((e) => e.prefabEntityId);
+ expect(ids).toEqual(expect.arrayContaining(['n1', 'n2']));
+ });
+});
+
+describe('meshopt-compressed geometry', () => {
+ it('imports to the very same mesh the uncompressed file does', async () => {
+ // The claim is not what the codec does — it is that compression is invisible
+ // above the bufferView, which is the whole reason it can be decoded there.
+ const plain = (await importGltfMeshes(plainTriangle(), 'model')).meshes[0]!;
+ const packed = (await importGltfMeshes(await meshoptTriangle(), 'model')).meshes[0]!;
+ expect(packed.vertexCount).toBe(plain.vertexCount);
+ expect(packed.triangleCount).toBe(plain.triangleCount);
+ expect([...packed.data.vertices]).toEqual([...plain.data.vertices]);
+ expect([...packed.data.indices]).toEqual([...plain.data.indices]);
+ expect(packed.data.channels).toEqual(plain.data.channels);
+ });
+
+ it('says nothing about it — a fallback buffer is not a missing one', async () => {
+ // It declares a length and no uri by design; reporting it as unreadable would
+ // send a user looking for a file that is not supposed to exist.
+ const { warnings } = await importGltfMeshes(await meshoptTriangle(), 'model');
+ expect(warnings).toEqual([]);
+ });
+});
+
+describe('Draco-compressed geometry', () => {
+ /** Every vertex as one "x,y,z/u,v" string, sorted — Draco reorders vertices to
+ * compress them, so what survives is the set of them, not their order. */
+ const vertexSet = (mesh: ImportedMesh): string[] => {
+ const view = new DataView(mesh.data.vertices.buffer, mesh.data.vertices.byteOffset);
+ const at = (semantic: number): number =>
+ mesh.data.channels.find(c => c.semantic === semantic)!.offset;
+ const out: string[] = [];
+ for (let i = 0; i < mesh.vertexCount; i++) {
+ const base = i * mesh.data.vertexStride;
+ const read = (offset: number, n: number): string => Array.from({ length: n },
+ (_, c) => view.getFloat32(base + offset + c * 4, true).toFixed(3)).join(',');
+ out.push(`${read(at(MeshChannel.Position), 3)}/${read(at(MeshChannel.TexCoord0), 2)}`);
+ }
+ return out.sort();
+ };
+
+ it('imports to the same triangle the uncompressed file does', async () => {
+ const plain = (await importGltfMeshes(plainTriangle(), 'model')).meshes[0]!;
+ const packed = (await importGltfMeshes(await dracoTriangle(), 'model')).meshes[0]!;
+ expect(packed.vertexCount).toBe(plain.vertexCount);
+ expect(packed.triangleCount).toBe(plain.triangleCount);
+ expect(vertexSet(packed)).toEqual(vertexSet(plain));
+ });
+
+ it('reads it without complaint, accessors and all', async () => {
+ // A Draco accessor has no bufferView by spec. Read as an ordinary one it is
+ // "no data" — the check that catches a genuinely empty POSITION.
+ const { warnings, meshes } = await importGltfMeshes(await dracoTriangle(), 'model');
+ expect(warnings).toEqual([]);
+ expect(meshes).toHaveLength(1);
+ });
+});
diff --git a/pipeline/tests/hotupdate-verify-fixture.test.ts b/pipeline/tests/hotupdate-verify-fixture.test.ts
new file mode 100644
index 000000000..49a3246d9
--- /dev/null
+++ b/pipeline/tests/hotupdate-verify-fixture.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Produces the two cooked builds headless-hotupdate-verify.mjs drives — a
+ * shipped build of examples/hot-update-demo (green CDN art) and a "CDN
+ * update" of the same project with the remote art swapped to red (a
+ * different content hash → a new url + manifest revision). Guarded by
+ * ESTELLA_HOTUPDATE_FIXTURE; the verify:render:hotupdate script sets it.
+ * Proves a hot update end-to-end: change a `remote`-group asset, re-cook,
+ * and the shipped runtime fetches the new content — no re-ship.
+ */
+import { describe, it, expect } from 'vitest';
+import { writeFileSync, cpSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { exportGame } from '../src/export/exportGame';
+import { solidPng } from './fixtures/solidPng.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const EXAMPLE = path.resolve(HERE, '..', '..', 'examples', 'hot-update-demo');
+const ROOT = path.resolve(HERE, '..', '.hotupdate-verify');
+const BUILD = path.join(ROOT, 'build');
+const CDN = path.join(ROOT, 'cdn');
+const REDSRC = path.join(ROOT, 'red-src');
+
+const opts = (root: string, outDir: string) => ({
+ root,
+ entryScene: 'assets/scenes/main.esscene',
+ gameHostEntry: path.resolve(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts'),
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.resolve(HERE, '..', '..', 'sdk', 'dist'),
+ wasmDir: path.resolve(HERE, '..', '..', 'build', 'wasm', 'web'),
+ outDir,
+ title: 'Hot Update Demo',
+ contentAddressed: true,
+});
+
+describe.skipIf(!process.env.ESTELLA_HOTUPDATE_FIXTURE)('hot-update verify fixture', () => {
+ it('cooks a shipped build (green CDN art) + a CDN update (red CDN art)', async () => {
+ rmSync(ROOT, { recursive: true, force: true });
+
+ // 1. Ship build: the example exactly as committed — green art in remote/cdn/.
+ const build = await exportGame(opts(EXAMPLE, BUILD));
+ expect(build.ok, build.errors.join('; ')).toBe(true);
+
+ // 2. CDN update: the SAME project but the remote art is now RED. A different
+ // hash → a new content-addressed url + a new manifest revision, so the
+ // runtime's diff sees exactly one changed asset.
+ cpSync(EXAMPLE, REDSRC, {
+ recursive: true,
+ // Copy the project but drop generated / heavy trees. Keep the committed
+ // .esengine/asset-groups.json — it's what makes assets/cdn a remote group.
+ filter: (src) => {
+ const p = src.replace(/\\/g, '/');
+ if (p.includes('/node_modules') || p.includes('/dist')) return false;
+ const i = p.indexOf('/.esengine/');
+ return i < 0 || p.slice(i + '/.esengine/'.length).startsWith('asset-groups.json');
+ },
+ });
+ writeFileSync(path.join(REDSRC, 'assets', 'cdn', 'art.png'), solidPng(64, 64, [220, 40, 40, 255]));
+ const cdn = await exportGame(opts(REDSRC, CDN));
+ expect(cdn.ok, cdn.errors.join('; ')).toBe(true);
+ }, 180_000);
+});
diff --git a/pipeline/tests/native-template.test.ts b/pipeline/tests/native-template.test.ts
new file mode 100644
index 000000000..00db3f4e3
--- /dev/null
+++ b/pipeline/tests/native-template.test.ts
@@ -0,0 +1,423 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The runtime-template store. A native app's compiled half ships as an artifact
+// rather than being rebuilt on every user's machine, so what is pinned here is the
+// contract between the emitter and the editor:
+//
+// 1. A template is matched EXACTLY on version — the SDK bundle is compiled into
+// the app binary, so a near-miss fails on a device instead of in the dialog.
+// 2. An archive is untrusted input, and an incomplete one must not replace a
+// working install.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ resolveNativeTemplate, iosSourcesFromTemplate, installNativeTemplate,
+ listNativeTemplates, removeNativeTemplate, downloadNativeTemplate,
+} from '../src/export/nativeTemplates';
+import { listPlatforms } from '../src/export/platformCatalog';
+import {
+ requiredTemplateFiles, templateLayout, installedTemplateDir, parseTemplateIndex,
+ missingTemplateEntries, isTemplatePlatform,
+ TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_INDEX, TEMPLATE_PLATFORMS,
+ type TemplatePlatform,
+} from '../../build-tools/utils/nativeTemplate.js';
+import { verifyTemplateZip } from '../../build-tools/tasks/verifyTemplate.js';
+import { makeZip } from '../../build-tools/utils/zip.js';
+
+const VERSION = '9.9.9';
+
+let store: string;
+let scratch: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(path.join(tmpdir(), 'es-tmpl-'));
+ store = path.join(scratch, 'templates');
+ process.env.ESTELLA_NATIVE_TEMPLATES = store;
+});
+
+afterEach(() => {
+ delete process.env.ESTELLA_NATIVE_TEMPLATES;
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+/** Every file the layout declares required, with a stand-in body — so the fixture
+ * follows the contract rather than a copy of it that can go stale. */
+function templateEntries(
+ version: string, omit?: string, platform: TemplatePlatform = 'ios',
+): { name: string; data: Buffer }[] {
+ const entries = requiredTemplateFiles(platform)
+ .filter((rel) => rel !== omit)
+ .map((rel) => ({ name: rel, data: Buffer.from(`stand-in for ${rel}`) }));
+ entries.push({
+ name: TEMPLATE_MANIFEST,
+ data: Buffer.from(JSON.stringify({
+ kind: 'estella-native-template',
+ formatVersion: TEMPLATE_FORMAT,
+ id: platform,
+ platform,
+ engineVersion: version,
+ spineVersion: '4.2',
+ deploymentTarget: '17.0',
+ })),
+ });
+ return entries;
+}
+
+function writeTemplateZip(version: string, omit?: string, platform: TemplatePlatform = 'ios'): string {
+ const file = path.join(scratch, `template-${version}-${platform}.zip`);
+ writeFileSync(file, makeZip(templateEntries(version, omit, platform)));
+ return file;
+}
+
+describe('installing a runtime template', () => {
+ it('installs an archive and makes the platform resolvable', () => {
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+
+ const res = installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ expect(res.ok).toBe(true);
+ expect(res.versionMismatch).toBe(false);
+ expect(res.dir).toBe(installedTemplateDir(VERSION, 'ios', store));
+
+ const resolved = resolveNativeTemplate('ios', VERSION);
+ expect(resolved?.manifest.engineVersion).toBe(VERSION);
+ const sources = iosSourcesFromTemplate(VERSION)!;
+ expect(existsSync(sources.xcframework)).toBe(true);
+ expect(existsSync(sources.mainM)).toBe(true);
+ expect(existsSync(sources.infoPlistIn)).toBe(true);
+ });
+
+ it('stores a template built for another release, but does not offer it', () => {
+ const res = installNativeTemplate(writeTemplateZip('1.0.0'), VERSION);
+
+ expect(res.ok).toBe(true);
+ // Named, so the dialog can say which version the archive was for.
+ expect(res.versionMismatch).toBe(true);
+ expect(res.engineVersion).toBe('1.0.0');
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ expect(listNativeTemplates(VERSION)).toEqual([
+ expect.objectContaining({ id: 'ios', engineVersion: '1.0.0', current: false }),
+ ]);
+ });
+
+ it('rejects an incomplete archive, and leaves the installed one alone', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ const res = installNativeTemplate(writeTemplateZip(VERSION, 'App/main.m'), VERSION);
+
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain('App/main.m');
+ // The working install survived the bad one.
+ expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
+ });
+
+ it('rejects an archive that is not a template at all', () => {
+ const file = path.join(scratch, 'random.zip');
+ writeFileSync(file, makeZip([{ name: 'readme.txt', data: Buffer.from('hi') }]));
+
+ expect(installNativeTemplate(file, VERSION).error).toContain('template.json');
+ });
+
+ it('refuses an archive that would write outside the store', () => {
+ const file = path.join(scratch, 'evil.zip');
+ writeFileSync(file, makeZip([{ name: '../escaped.txt', data: Buffer.from('x') }]));
+
+ expect(installNativeTemplate(file, VERSION).error).toContain('unsafe');
+ expect(existsSync(path.join(scratch, 'escaped.txt'))).toBe(false);
+ });
+
+ it('treats a half-deleted install as absent rather than usable', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+ rmSync(path.join(installedTemplateDir(VERSION, 'ios', store), 'App', 'main.m'));
+
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ });
+
+ it('removes an installed template', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ expect(removeNativeTemplate('ios', VERSION)).toBe(true);
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ expect(removeNativeTemplate('ios', VERSION)).toBe(false);
+ });
+});
+
+describe('downloading a template from a release', () => {
+ /** A stand-in release: the published index plus the archive it describes. */
+ function release(overrides: { sha256?: string; bytes?: number; templates?: unknown[] } = {}) {
+ const zip = readFileSync(writeTemplateZip(VERSION));
+ const index = {
+ kind: 'estella-native-templates',
+ formatVersion: TEMPLATE_FORMAT,
+ engineVersion: VERSION,
+ templates: overrides.templates ?? [{
+ id: 'ios', platform: 'ios',
+ file: `estella-native-ios-${VERSION}.zip`,
+ bytes: overrides.bytes ?? zip.length,
+ sha256: overrides.sha256 ?? createHash('sha256').update(zip).digest('hex'),
+ }],
+ };
+ const served: string[] = [];
+ const fetchImpl = (async (url: string) => {
+ served.push(url);
+ if (url.endsWith(TEMPLATE_INDEX)) {
+ return { ok: true, status: 200, json: async () => index } as unknown as Response;
+ }
+ return {
+ ok: true,
+ status: 200,
+ // Two chunks, so progress is reported more than once.
+ body: (async function* () {
+ yield zip.subarray(0, 100);
+ yield zip.subarray(100);
+ })(),
+ } as unknown as Response;
+ }) as unknown as typeof fetch;
+ return { fetchImpl, served, zip };
+ }
+
+ // Desktop templates are published per OS, and the download path takes them by
+ // that name rather than by the one export target they share.
+ it('installs a DESKTOP template, which is published per OS', async () => {
+ const zip = readFileSync(writeTemplateZip(VERSION, undefined, 'windows'));
+ const index = {
+ kind: 'estella-native-templates',
+ formatVersion: TEMPLATE_FORMAT,
+ engineVersion: VERSION,
+ templates: [{
+ id: 'windows', platform: 'windows',
+ file: `estella-native-windows-${VERSION}.zip`,
+ bytes: zip.length,
+ sha256: createHash('sha256').update(zip).digest('hex'),
+ }],
+ };
+ const fetchImpl = (async (url: string) => (url.endsWith(TEMPLATE_INDEX)
+ ? { ok: true, status: 200, json: async () => index } as unknown as Response
+ : { ok: true, status: 200, body: (async function* () { yield zip; })() } as unknown as Response
+ )) as unknown as typeof fetch;
+
+ const res = await downloadNativeTemplate('windows', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
+ expect(res).toMatchObject({ ok: true, id: 'windows' });
+ expect(resolveNativeTemplate('windows', VERSION)).not.toBeNull();
+ });
+
+ // `desktop` is an export target, not a template platform: the index publishes
+ // three desktop templates and none of them under that name.
+ it('says so when asked for a platform no template is published for', async () => {
+ const { fetchImpl } = release();
+ const res = await downloadNativeTemplate('desktop' as TemplatePlatform, VERSION, {
+ fetchImpl, baseUrl: 'https://example.test/r',
+ });
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain('no desktop template');
+ });
+
+ it('installs what the index describes, and reports progress on the way', async () => {
+ const { fetchImpl, served, zip } = release();
+ const progress: number[] = [];
+
+ const res = await downloadNativeTemplate('ios', VERSION, {
+ fetchImpl, baseUrl: 'https://example.test/r', onProgress: (p) => progress.push(p.received),
+ });
+
+ expect(res).toMatchObject({ ok: true, id: 'ios', versionMismatch: false });
+ expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
+ expect(served).toEqual([
+ `https://example.test/r/${TEMPLATE_INDEX}`,
+ `https://example.test/r/estella-native-ios-${VERSION}.zip`,
+ ]);
+ expect(progress).toEqual([100, zip.length]);
+ });
+
+ it('refuses an archive whose checksum does not match the index', async () => {
+ const { fetchImpl } = release({ sha256: 'f'.repeat(64) });
+
+ const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
+
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain('checksum mismatch');
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ });
+
+ it('refuses a truncated download before it is unpacked', async () => {
+ const { fetchImpl } = release({ bytes: 999_999 });
+
+ const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
+
+ expect(res.error).toContain('999999');
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ });
+
+ it('says so when this version publishes no template for the platform', async () => {
+ const { fetchImpl } = release();
+
+ const res = await downloadNativeTemplate('android', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
+
+ expect(res.error).toContain('no android template');
+ });
+
+ it('treats an unreadable index as no index — a 404 page is not a template list', async () => {
+ const fetchImpl = (async () => ({
+ ok: true, status: 200, json: async () => ({ error: 'Not Found' }),
+ } as unknown as Response)) as unknown as typeof fetch;
+
+ const res = await downloadNativeTemplate('ios', VERSION, { fetchImpl, baseUrl: 'https://example.test/r' });
+
+ expect(res.error).toContain('not readable');
+ });
+
+ it('rejects an index published for another version', () => {
+ expect(parseTemplateIndex({
+ kind: 'estella-native-templates', formatVersion: TEMPLATE_FORMAT, engineVersion: '1.0.0',
+ templates: [{ id: 'ios', platform: 'ios', file: 'x.zip', bytes: 1, sha256: 'a'.repeat(64) }],
+ }, VERSION)).toBeNull();
+ });
+
+ it('drops an entry whose filename could escape the download directory', () => {
+ expect(parseTemplateIndex({
+ kind: 'estella-native-templates', formatVersion: TEMPLATE_FORMAT, engineVersion: VERSION,
+ templates: [{ id: 'ios', platform: 'ios', file: '../evil.zip', bytes: 1, sha256: 'a'.repeat(64) }],
+ }, VERSION)).toBeNull();
+ });
+});
+
+describe('the iOS row reports what is missing', () => {
+ const dirs = () => ({ web: path.join(scratch, 'web'), wechat: path.join(scratch, 'wx') });
+ const iosRow = async () => (await listPlatforms(null, dirs(), VERSION)).find((r) => r.id === 'ios')!;
+
+ it('asks for the runtime template before anything about Xcode', async () => {
+ const row = await iosRow();
+
+ expect(row.ready).toBe(false);
+ expect(row.prereq).toEqual({ kind: 'template-missing', id: 'ios', version: VERSION });
+ });
+
+ it('moves on to the toolchain once a template is installed', async () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ const row = await iosRow();
+
+ // On a Mac with Xcode that is everything; elsewhere the toolchain is the
+ // remaining gap — and the export still writes a project to carry to a Mac.
+ if (row.ready) expect(row.prereq).toBeUndefined();
+ else expect(row.prereq?.kind).toBe('toolchain-missing');
+ });
+});
+
+describe('the template layout is the one source of filenames', () => {
+ it('assembles the iOS project from paths inside the installed template', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+ const dir = installedTemplateDir(VERSION, 'ios', store);
+
+ const sources = iosSourcesFromTemplate(VERSION)!;
+
+ expect(sources.xcframework).toBe(path.join(dir, 'Estella.xcframework'));
+ expect(sources.mainM).toBe(path.join(dir, 'App', 'main.m'));
+ expect(sources.infoPlistIn).toBe(path.join(dir, 'App', 'Info.plist.in'));
+ // And every one of them is a file the layout declares — including the
+ // bytecode, which is optional (a build machine without a host compiler ships a
+ // template without it, and the app compiles on first launch instead).
+ const declared = templateLayout('ios').map((e) => e.rel);
+ for (const file of Object.values(sources)) {
+ expect(declared).toContain(path.relative(dir, file).split(path.sep).join('/'));
+ }
+ expect(requiredTemplateFiles('ios')).not.toContain(
+ path.relative(dir, sources.bytecode).split(path.sep).join('/'));
+ });
+});
+
+describe('what a PUBLISHED template must carry', () => {
+ // The bytecode is optional for a local build and not for a release, and reading
+ // "optional" as one answer to both is what let v0.36.0 ship an Android template
+ // without it — every game packaged from that template opened on a black screen
+ // while the host compiled the bundle on the device.
+ const BYTECODE = 'assets/esengine.native.qjsbc';
+
+ // What v0.36.0 actually published, minus the bytecode: complete by the rule a
+ // contributor's build is held to.
+ const shipped = (extra: string[] = []) => [
+ 'AndroidManifest.xml.in', 'classes.dex', 'icon.png',
+ 'java/com/estella/host/TextEditor.java',
+ 'lib/arm64-v8a/libestella_js_host.so', 'lib/arm64-v8a/libwebgpu_dawn.so',
+ 'lib/arm64-v8a/libc++_shared.so',
+ 'lib/x86_64/libestella_js_host.so', 'lib/x86_64/libwebgpu_dawn.so',
+ 'lib/x86_64/libc++_shared.so',
+ 'template.json', ...extra,
+ ];
+
+ it('accepts a template without bytecode, and refuses to publish it', () => {
+ expect(missingTemplateEntries(shipped(), 'android')).toEqual([]);
+ expect(missingTemplateEntries(shipped(), 'android', { release: true })).toEqual([BYTECODE]);
+ expect(missingTemplateEntries(shipped([BYTECODE]), 'android', { release: true })).toEqual([]);
+ });
+
+ it('holds a release to every ABI the template claims', () => {
+ // One ABI is a usable template; a release builds both, and losing the emulator
+ // one leaves everybody without a phone unable to run the game at all.
+ const oneAbi = shipped([BYTECODE]).filter((n) => !n.startsWith('lib/x86_64/'));
+ expect(missingTemplateEntries(oneAbi, 'android')).toEqual([]);
+ expect(missingTemplateEntries(oneAbi, 'android', { release: true }))
+ .toEqual(expect.arrayContaining(['lib/x86_64/libestella_js_host.so']));
+ });
+
+ it('counts a directory entry as held when something inside it is', () => {
+ // A zip stores files, never the folder — so `java` is present because
+ // `java/com/...` is, and absent when nothing under it shipped.
+ const noJava = shipped([BYTECODE]).filter((n) => !n.startsWith('java/'));
+ expect(missingTemplateEntries(noJava, 'android', { release: true })).toEqual(['java']);
+ });
+
+ it('reads Windows separators, since that is where an archive may be listed', () => {
+ const win = shipped([BYTECODE]).map((n) => n.split('/').join(String.fromCharCode(92)));
+ expect(missingTemplateEntries(win, 'android', { release: true })).toEqual([]);
+ });
+});
+
+describe('the platforms templates are published for', () => {
+ /** A release-complete archive for any platform, built from that platform's own
+ * layout so the fixture follows the contract instead of restating it. */
+ function releaseZip(platform: TemplatePlatform): Buffer {
+ const entries = requiredTemplateFiles(platform, { release: true })
+ .map((rel: string) => ({ name: rel, data: Buffer.from(`stand-in for ${rel}`) }));
+ entries.push({
+ name: TEMPLATE_MANIFEST,
+ data: Buffer.from(JSON.stringify({
+ kind: 'estella-native-template',
+ formatVersion: TEMPLATE_FORMAT,
+ id: platform,
+ platform,
+ engineVersion: VERSION,
+ })),
+ });
+ return makeZip(entries);
+ }
+
+ it('all have a layout, and the list is what asks', () => {
+ // The release gate kept its own pair of names while three desktop platforms
+ // landed in templateLayout, so v0.47.0 built five templates correctly and
+ // then refused to publish three. One list, and the layouts cannot part from it.
+ for (const p of TEMPLATE_PLATFORMS) {
+ expect(isTemplatePlatform(p)).toBe(true);
+ expect(templateLayout(p).length).toBeGreaterThan(0);
+ }
+ expect(isTemplatePlatform('playstation')).toBe(false);
+ expect(() => templateLayout('playstation' as TemplatePlatform)).toThrow();
+ });
+
+ it('are each accepted by the release verifier', () => {
+ // Through the verifier's own entry point, not a copy of its rule — having a
+ // copy was the defect.
+ for (const p of TEMPLATE_PLATFORMS) {
+ const zip = path.join(scratch, `t-${p}.zip`);
+ writeFileSync(zip, releaseZip(p));
+ const res = verifyTemplateZip(zip);
+ expect(res.platform).toBe(p);
+ expect(res.problems).toEqual([]);
+ expect(res.ok).toBe(true);
+ }
+ });
+});
diff --git a/pipeline/tests/platform-catalog.test.ts b/pipeline/tests/platform-catalog.test.ts
new file mode 100644
index 000000000..ab495d2b7
--- /dev/null
+++ b/pipeline/tests/platform-catalog.test.ts
@@ -0,0 +1,416 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The platform catalog: what the Package dialog can offer, and whether each
+// target can actually run. Two behaviours worth pinning down —
+//
+// 1. Readiness is a PROBE, not a constant. The dialog used to carry static
+// "requires the X runtime" prose that was true whether or not you had built
+// it (and, for playable, was simply wrong).
+// 2. A project can add a platform the editor never heard of, and a broken one
+// must not take the dialog down with it.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ listPlatforms, loadProjectPlatform, createProjectPlatform, PROJECT_PLATFORM_DIR,
+ listPlayableNetworks, loadPlayableProfile,
+} from '../src/export/platformCatalog';
+import { BUILTIN_PLATFORMS } from '../src/project/platforms';
+
+let root: string;
+let webDir: string;
+let wxDir: string;
+
+/** The editor version the probes run as. A native runtime template is matched
+ * against it exactly, so the tests own both ends of that comparison. */
+const VERSION = '9.9.9';
+
+const dirs = () => ({ web: webDir, wechat: wxDir });
+
+function writePlatform(name: string, source: string): void {
+ const dir = path.join(root, PROJECT_PLATFORM_DIR);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), source);
+}
+
+beforeEach(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'es-platcat-'));
+ webDir = path.join(root, 'rt-web');
+ wxDir = path.join(root, 'rt-wechat');
+ mkdirSync(webDir, { recursive: true });
+ mkdirSync(wxDir, { recursive: true });
+ // The native probes read the machine's template store; point it at this test's
+ // own empty one, or the result would depend on what the developer has installed.
+ process.env.ESTELLA_NATIVE_TEMPLATES = path.join(root, 'templates');
+});
+
+afterEach(() => {
+ delete process.env.ESTELLA_NATIVE_TEMPLATES;
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('listPlatforms — built-in readiness is probed', () => {
+ it('web/desktop/playable are not ready without the web engine glue', async () => {
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const byId = Object.fromEntries(rows.map((r) => [r.id, r]));
+
+ expect(byId.web.ready).toBe(false);
+ expect(byId.desktop.ready).toBe(false);
+ expect(byId.playable.ready).toBe(false);
+ expect((byId.web.prereq as { command?: string } | undefined)?.command).toContain('build -t web');
+ });
+
+ it('the web glue makes playable ready too — it inlines the WEB runtime, not a -t playable one', async () => {
+ writeFileSync(path.join(webDir, 'esengine.js'), '//');
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const byId = Object.fromEntries(rows.map((r) => [r.id, r]));
+
+ expect(byId.web.ready).toBe(true);
+ expect(byId.playable.ready).toBe(true);
+ expect(byId.playable.prereq).toBeUndefined();
+ // WeChat has its own runtime and is unaffected by the web one.
+ expect(byId.wechat.ready).toBe(false);
+ expect((byId.wechat.prereq as { command?: string } | undefined)?.command).toContain('build -t wechat');
+ });
+
+ it('WeChat accepts either its own glue or a web-aligned one', async () => {
+ writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
+ expect((await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat')?.ready).toBe(true);
+
+ rmSync(path.join(wxDir, 'esengine.wxgame.js'));
+ writeFileSync(path.join(wxDir, 'esengine.js'), '//');
+ expect((await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat')?.ready).toBe(true);
+ });
+
+ it('reports paths with forward slashes, whatever the platform separator', async () => {
+ const wx = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat');
+ expect((wx?.prereq as { dir?: string } | undefined)?.dir).not.toContain('\\');
+ });
+});
+
+describe('listPlatforms — platforms the project defines', () => {
+ it('finds a profile and lifts its display data', async () => {
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'ACME Play', blurb: 'ACME package.', defaultOut: 'dist-acme',
+ emitConfigFiles: () => [{ file: 'game.json', content: '{}' }],
+ };`);
+ writeFileSync(path.join(webDir, 'esengine.js'), '//');
+
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const acme = rows.find((r) => r.id === 'acme');
+ expect(acme).toBeDefined();
+ expect(acme!.source).toBe('project');
+ expect(acme!.label).toBe('ACME Play');
+ expect(acme!.defaultOut).toBe('dist-acme');
+ // No wasmDir of its own → the editor's web runtime, which exists here.
+ expect(acme!.ready).toBe(true);
+ });
+
+ it('probes the profile\'s own runtime dir when it names one', async () => {
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'ACME Play', wasmDir: 'build/wasm/acme',
+ emitConfigFiles: () => [],
+ };`);
+ writeFileSync(path.join(webDir, 'esengine.js'), '//');
+
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
+ expect(acme!.ready).toBe(false);
+ expect((acme!.prereq as { dir?: string } | undefined)?.dir).toBe('build/wasm/acme');
+ // The editor does not know how a project builds its own runtime, so it
+ // reports where it looked and offers no command.
+ expect((acme!.prereq as { command?: string } | undefined)?.command).toBeUndefined();
+ });
+
+ it('a broken profile is listed with its error, not silently dropped', async () => {
+ writePlatform('bad.mjs', 'export default { this is not valid javascript');
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const bad = rows.find((r) => r.id === 'bad');
+ expect(bad).toBeDefined();
+ expect(bad!.ready).toBe(false);
+ expect(bad!.error).toBeTruthy();
+ // Every built-in still came through.
+ expect(rows.filter((r) => r.source === 'builtin').map((r) => r.id)).toEqual([...BUILTIN_PLATFORMS]);
+ });
+
+ it('rejects a profile that shadows a built-in, or has no id/label/emitter', async () => {
+ writePlatform('a.mjs', `export default { id: 'wechat', label: 'Fake', emitConfigFiles: () => [] };`);
+ writePlatform('b.mjs', `export default { id: 'Bad Id', label: 'X', emitConfigFiles: () => [] };`);
+ writePlatform('c.mjs', `export default { id: 'ok-id', emitConfigFiles: () => [] };`);
+ writePlatform('d.mjs', `export default { id: 'ok-id2', label: 'X' };`);
+
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const errs = rows.filter((r) => r.source === 'project').map((r) => r.error);
+ expect(errs).toHaveLength(4);
+ expect(errs[0]).toContain('built-in');
+ expect(errs[1]).toContain('lowercase');
+ expect(errs[2]).toContain('label');
+ expect(errs[3]).toContain('emitConfigFiles');
+ // The real WeChat row is untouched by the impostor.
+ expect(rows.filter((r) => r.id === 'wechat' && r.source === 'builtin')).toHaveLength(1);
+ });
+
+ it('lists only built-ins when no project is open', async () => {
+ const rows = await listPlatforms(null, dirs(), VERSION);
+ expect(rows.every((r) => r.source === 'builtin')).toBe(true);
+ });
+});
+
+describe('createProjectPlatform — scaffolding', () => {
+ it('writes both halves, already joined, and the result is discoverable', async () => {
+ const res = await createProjectPlatform(root, 'acme-play', 'ACME Play', 'src');
+ expect(res.ok).toBe(true);
+ expect(res.packagingFile).toBe('.esengine/platforms/acme-play.mjs');
+ expect(res.runtimeFile).toBe('src/platforms/acme-play.runtime.ts');
+ // Reported with forward slashes, like every other path the dialog shows.
+ expect(res.packagingFile).not.toContain('\\');
+
+ const packaging = readFileSync(path.join(root, res.packagingFile!), 'utf8');
+ const runtime = readFileSync(path.join(root, res.runtimeFile!), 'utf8');
+ // THE JOIN: the packaging half names the runtime half.
+ expect(packaging).toContain(`runtimeProfile: 'src/platforms/acme-play.runtime.ts'`);
+ expect(runtime).toContain(`id: 'acme-play'`);
+ expect(runtime).toContain(`hostLabel: 'ACME Play'`);
+ // The overrides a vendor might want are present as guidance, commented out.
+ expect(runtime).toContain('createVideoBackend');
+ expect(runtime).toContain('instantiateWasm');
+
+ // What was scaffolded is immediately a real platform.
+ writeFileSync(path.join(webDir, 'esengine.js'), '//');
+ const rows = await listPlatforms(root, dirs(), VERSION);
+ const acme = rows.find((r) => r.id === 'acme-play');
+ expect(acme?.source).toBe('project');
+ expect(acme?.label).toBe('ACME Play');
+ expect(acme?.error).toBeUndefined();
+ expect(acme?.ready).toBe(true);
+
+ // And it loads into a complete export profile.
+ const loaded = await loadProjectPlatform(root, 'acme-play', dirs());
+ expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'platforms', 'acme-play.runtime.ts'));
+ expect(loaded!.defaultOut).toBe('dist-acme-play');
+ expect(loaded!.profile.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' })[0].file)
+ .toBe('game.json');
+ });
+
+ it('refuses an id that shadows a built-in or is malformed', async () => {
+ expect((await createProjectPlatform(root, 'wechat', 'Fake', 'src')).error).toContain('built-in');
+ expect((await createProjectPlatform(root, 'Bad Id', 'X', 'src')).error).toContain('lowercase');
+ expect((await createProjectPlatform(root, 'ok-id', ' ', 'src')).error).toContain('label');
+ });
+
+ it('never clobbers an existing platform, or a runtime half already written', async () => {
+ await createProjectPlatform(root, 'acme', 'ACME', 'src');
+ const runtimeAbs = path.join(root, 'src', 'platforms', 'acme.runtime.ts');
+ writeFileSync(runtimeAbs, 'export default { mine: true };');
+
+ const again = await createProjectPlatform(root, 'acme', 'ACME', 'src');
+ expect(again.ok).toBe(false);
+ expect(again.error).toContain('already exists');
+ expect(readFileSync(runtimeAbs, 'utf8')).toBe('export default { mine: true };');
+ });
+});
+
+describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {
+ it('merges over the family defaults, so a minimal profile is complete', async () => {
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'ACME Play',
+ emitConfigFiles: (ctx) => [{ file: 'game.json', content: JSON.stringify({ t: ctx.title }) }],
+ };`);
+
+ const loaded = await loadProjectPlatform(root, 'acme', dirs());
+ expect(loaded).not.toBeNull();
+ const p = loaded!.profile;
+
+ // Supplied by the project.
+ expect(p.id).toBe('acme');
+ // Defaulted — a standard mini-game host needs none of these spelled out.
+ expect(p.sdkEntryFile).toBe('index.minigame.js');
+ expect(p.runtimeInit).toBe('initMiniGameRuntime');
+ expect(p.engineGlueCandidates).toEqual(['esengine.js']);
+ expect(p.esTarget).toBe('es2017');
+ expect(p.subpackageDir).toBe('subpackages');
+ expect(typeof p.emitEntry).toBe('function');
+
+ // The default entry is the same CommonJS shape WeChat ships.
+ const entry = p.emitEntry({ sideModules: [{ id: 'physics', file: 'physics' }], engineGlueFile: 'esengine.js' });
+ expect(entry).toContain("require('./wasm/esengine.js')");
+ expect(entry).toContain(`"physics": asFactory(require('./wasm/physics.js'))`);
+ expect(entry).toContain("require('./game-bundle.js')");
+
+ // And the project's own emitter is what runs for config.
+ expect(p.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [], hasOpenData: false, openDataRoot: 'open-data' }))
+ .toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);
+ });
+
+ it('resolves wasmDir against the project root, defaulting to the web runtime', async () => {
+ writePlatform('a.mjs', `export default { id: 'a', label: 'A', wasmDir: 'rt/a', emitConfigFiles: () => [] };`);
+ writePlatform('b.mjs', `export default { id: 'b', label: 'B', emitConfigFiles: () => [] };`);
+
+ expect((await loadProjectPlatform(root, 'a', dirs()))!.wasmDir).toBe(path.join(root, 'rt', 'a'));
+ expect((await loadProjectPlatform(root, 'b', dirs()))!.wasmDir).toBe(webDir);
+ expect((await loadProjectPlatform(root, 'b', dirs()))!.defaultOut).toBe('dist-b');
+ });
+
+ // A vendor has two halves: the .mjs describes packaging, a runtime module
+ // describes the host (and any capability it replaces — its own video decoder,
+ // audio backend, socket). Naming the second from the first is what joins them,
+ // and the generated entry installs it before booting.
+ it('resolves the runtime half to an absolute module path', async () => {
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'acme-runtime.ts'), 'export default {};');
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'ACME Play', runtimeProfile: 'src/acme-runtime.ts',
+ emitConfigFiles: () => [],
+ };`);
+
+ const loaded = await loadProjectPlatform(root, 'acme', dirs());
+ expect(loaded!.profile.runtimeProfileModule).toBe(path.join(root, 'src', 'acme-runtime.ts'));
+ });
+
+ it('leaves runtimeProfileModule undefined when the project installs its own platform', async () => {
+ writePlatform('acme.mjs', `export default { id: 'acme', label: 'A', emitConfigFiles: () => [] };`);
+ const loaded = await loadProjectPlatform(root, 'acme', dirs());
+ expect(loaded!.profile.runtimeProfileModule).toBeUndefined();
+ });
+
+ it('flags a runtime half that points nowhere, instead of shipping a broken import', async () => {
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'ACME Play', runtimeProfile: 'src/missing.ts',
+ emitConfigFiles: () => [],
+ };`);
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
+ expect(acme!.ready).toBe(false);
+ expect(acme!.error).toContain('runtimeProfile');
+ });
+
+ it('accepts a runtime half written without its extension', async () => {
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ writeFileSync(path.join(root, 'src', 'rt.ts'), 'export default {};');
+ writePlatform('acme.mjs', `export default {
+ id: 'acme', label: 'A', runtimeProfile: 'src/rt', emitConfigFiles: () => [],
+ };`);
+ writeFileSync(path.join(webDir, 'esengine.js'), '//');
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
+ expect(acme!.error).toBeUndefined();
+ expect(acme!.ready).toBe(true);
+ });
+
+ it('is null for a built-in id, so the built-in pipeline keeps it', async () => {
+ expect(await loadProjectPlatform(root, 'wechat', dirs())).toBeNull();
+ expect(await loadProjectPlatform(root, 'nope', dirs())).toBeNull();
+ });
+});
+
+// A playable ad network is a variant of the built-in `playable` target, not a rival
+// platform: it is chosen inside that target, and a project-defined one must reach the
+// export through exactly the path a built-in does.
+describe('playable ad networks', () => {
+ it('lists the built-ins, then the project\'s own', async () => {
+ writePlatform('acme-ads.mjs', `export default {
+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads',
+ maxBytes: 3145728, limitNote: 'Acme docs say 3MB',
+ };`);
+ const rows = await listPlayableNetworks(root);
+ expect(rows.filter((r) => r.source === 'builtin').map((r) => r.id))
+ .toEqual(['generic', 'meta', 'google', 'mraid', 'unity', 'applovin']);
+ // A project network names the file that defines it, so the dialog can point at it
+ // (and at the error, when one fails to load). Built-ins have no file.
+ expect(rows.find((r) => r.id === 'acme-ads')).toMatchObject({
+ label: 'Acme Ads', source: 'project', file: '.esengine/platforms/acme-ads.mjs',
+ });
+ expect(rows.find((r) => r.id === 'meta')!.file).toBeUndefined();
+ });
+
+ it('resolves a project network to a profile the export can run with', async () => {
+ writePlatform('acme-ads.mjs', `export default {
+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads',
+ maxBytes: 3145728, limitNote: 'Acme docs say 3MB',
+ emitHead: (ctx) => '<meta name="acme" content="' + ctx.orientation + '">',
+ emitBridge: () => 'window.__ESTELLA_PLAYABLE__={cta:function(){}};',
+ };`);
+ const profile = await loadPlayableProfile(root, 'acme-ads');
+ expect(profile).toMatchObject({ id: 'acme-ads', maxBytes: 3145728 });
+ expect(profile!.emitHead!({ title: 'T', orientation: 'portrait' })).toBe('<meta name="acme" content="portrait">');
+ expect(profile!.emitBridge!({ title: 'T', orientation: 'portrait' })).toContain('__ESTELLA_PLAYABLE__');
+ });
+
+ it('resolves the built-ins, and nothing for an unknown id', async () => {
+ expect((await loadPlayableProfile(root, 'meta'))!.emitBridge!({ title: 'T', orientation: 'landscape' }))
+ .toContain('FbPlayableAd.onCTAClick');
+ // Google's exit API must be a LITERAL head script (its docs forbid injecting it
+ // from JS), and its upload is a ZIP this export does not produce — hence the note.
+ const google = (await loadPlayableProfile(root, 'google'))!;
+ expect(google.emitHead!({ title: 'T', orientation: 'portrait' }))
+ .toContain('<script src="https://tpc.googlesyndication.com/pagead/gadgets/html5/api/exitapi.js"></script>');
+ expect(google.emitHead!({ title: 'T', orientation: 'portrait' })).toContain('content="portrait"');
+ expect(google.emitBridge!({ title: 'T', orientation: 'portrait' })).toContain('ExitApi.exit');
+ // Google takes an archive, and the export writes one for it.
+ expect(google.delivery).toBe('zip');
+ // The MRAID family clicks through with mraid.open() and needs nothing in head —
+ // the host webview injects mraid itself.
+ for (const id of ['mraid', 'unity', 'applovin']) {
+ const p = (await loadPlayableProfile(root, id))!;
+ expect(p.emitBridge!({ title: 'T', orientation: 'landscape' })).toContain('mraid.open()');
+ expect(p.emitHead).toBeUndefined();
+ }
+ // No selection ⇒ generic, so a project that never chose still exports.
+ expect((await loadPlayableProfile(root, undefined))!.id).toBe('generic');
+ // An id naming nothing is NOT silently generic — the caller reports it.
+ expect(await loadPlayableProfile(root, 'nope')).toBeNull();
+ });
+
+ it('carries a project profile\'s zip delivery through to the export', async () => {
+ writePlatform('zipnet.mjs', `export default {
+ id: 'zipnet', kind: 'playable', label: 'Zip Net',
+ maxBytes: 5242880, limitNote: 'Zip Net docs', delivery: 'zip',
+ deliveryNote: 'name the archive after the campaign',
+ };`);
+ const profile = await loadPlayableProfile(root, 'zipnet');
+ expect(profile).toMatchObject({ delivery: 'zip', deliveryNote: 'name the archive after the campaign' });
+ });
+
+ it('rejects a delivery mode that is neither shape', async () => {
+ writePlatform('oddnet.mjs', `export default {
+ id: 'oddnet', kind: 'playable', label: 'Odd Net',
+ maxBytes: 1, limitNote: 'x', delivery: 'tarball',
+ };`);
+ const row = (await listPlayableNetworks(root)).find((r) => r.id === 'oddnet');
+ expect(row!.error).toMatch(/delivery/);
+ });
+
+ it('rejects a playable profile missing the facts the warning needs', async () => {
+ writePlatform('bad.mjs', "export default { id: 'bad', kind: 'playable', label: 'Bad' };");
+ const row = (await listPlayableNetworks(root)).find((r) => r.id === 'bad');
+ expect(row!.error).toMatch(/maxBytes/);
+ // Named WITH its file — an error you cannot locate is barely an error report.
+ expect(row!.file).toBe('.esengine/platforms/bad.mjs');
+ });
+
+ it('keeps networks out of the platform list, and platforms out of the network list', async () => {
+ writePlatform('acme-ads.mjs', `export default {
+ id: 'acme-ads', kind: 'playable', label: 'Acme Ads', maxBytes: 100, limitNote: 'x',
+ };`);
+ writePlatform('acme-mini.mjs', `export default {
+ id: 'acme-mini', label: 'Acme MiniGame', emitConfigFiles: () => [],
+ };`);
+ expect((await listPlatforms(root, dirs(), VERSION)).map((r) => r.id)).not.toContain('acme-ads');
+ expect((await listPlayableNetworks(root)).map((r) => r.id)).not.toContain('acme-mini');
+ // And a network id must not shadow a network the editor ships.
+ writePlatform('meta.mjs', "export default { id: 'meta', kind: 'playable', label: 'Mine', maxBytes: 1, limitNote: 'x' };");
+ expect((await listPlayableNetworks(root)).find((r) => r.label === 'Mine')).toBeUndefined();
+ });
+
+ it('scaffolds a playable network as one file (the host is still the browser)', async () => {
+ const res = await createProjectPlatform(root, 'acme-ads', 'Acme Ads', 'src', 'playable');
+ expect(res.ok).toBe(true);
+ expect(res.runtimeFile).toBeUndefined();
+ const written = readFileSync(path.join(root, res.packagingFile!), 'utf8');
+ expect(written).toContain("kind: 'playable'");
+ expect(written).toContain('__ESTELLA_PLAYABLE__');
+ // The scaffold must satisfy its own contract, or the first export after
+ // scaffolding reports an error the developer did not write.
+ const row = (await listPlayableNetworks(root)).find((r) => r.id === 'acme-ads');
+ expect(row?.error).toBeUndefined();
+ });
+});
diff --git a/pipeline/tests/project-acceptance.test.ts b/pipeline/tests/project-acceptance.test.ts
new file mode 100644
index 000000000..a69933868
--- /dev/null
+++ b/pipeline/tests/project-acceptance.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The claims a PROJECT makes about itself, in its manifest.
+ *
+ * The reader is a whitelist, so a field with no branch persists and does
+ * nothing — which for this one would mean a project whose standing checks were
+ * silently never run, while the file said they were there.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest } from '../src/project/format';
+
+const project = (acceptance: unknown) =>
+ parseManifest({ formatVersion: '1', name: 'Platformer', acceptance });
+
+describe('standing acceptance in the manifest', () => {
+ it('survives the read — it is not a field that persists and does nothing', () => {
+ const m = project([{ says: 'the player can always reach the exit', probe: 'reachable()' }]);
+ expect(m.acceptance).toEqual([
+ { says: 'the player can always reach the exit', probe: 'reachable()' },
+ ]);
+ });
+
+ it('keeps one only a person can settle, with the reason', () => {
+ const m = project([{ says: 'the HUD reads at 1080p', manual: 'a judgement about legibility' }]);
+ expect(m.acceptance).toEqual([
+ { says: 'the HUD reads at 1080p', manual: 'a judgement about legibility' },
+ ]);
+ });
+
+ // A hand-edited claim that settles nothing must not become a claim that
+ // silently holds. Dropped here rather than failing the load: a bad line must
+ // not cost anyone their project (the same rule screenPresets follows).
+ it('drops a claim that names nothing to settle it', () => {
+ expect(project([{ says: 'it feels good' }]).acceptance).toBeUndefined();
+ });
+
+ it('drops a claim that says nothing', () => {
+ expect(project([{ probe: 'true' }]).acceptance).toBeUndefined();
+ expect(project([{ says: ' ', probe: 'true' }]).acceptance).toBeUndefined();
+ });
+
+ it('keeps the good ones when one is bad', () => {
+ const m = project([
+ { says: 'good', probe: 'ok' },
+ { says: 'bad' },
+ { says: 'also good', manual: 'a look' },
+ ]);
+ expect(m.acceptance?.map((c) => c.says)).toEqual(['good', 'also good']);
+ });
+
+ // One criterion, one thing that settles it — the probe wins, because it is
+ // the half a machine can act on.
+ it('keeps one settler for a claim that gave two', () => {
+ const m = project([{ says: 'x', probe: 'ok', manual: 'also a look' }]);
+ expect(m.acceptance).toEqual([{ says: 'x', probe: 'ok' }]);
+ });
+
+ it('leaves a project with none alone', () => {
+ expect(project(undefined).acceptance).toBeUndefined();
+ expect(project([]).acceptance).toBeUndefined();
+ expect(project('nonsense').acceptance).toBeUndefined();
+ });
+});
diff --git a/pipeline/tests/project-modules.test.ts b/pipeline/tests/project-modules.test.ts
new file mode 100644
index 000000000..beb103a54
--- /dev/null
+++ b/pipeline/tests/project-modules.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Optional native modules a project supplies.
+ *
+ * The engine's own side modules (physics, basis, the spine runtimes) get real
+ * treatment on every target: acquired through one host, staged into the package,
+ * required by name on a mini-game. A third-party runtime had none of it, and the
+ * platform where doing it by hand is impossible — a mini-game, with no `fetch`
+ * and a binary that must be IN the package — is the platform this engine targets
+ * first.
+ *
+ * The invariant that matters most here is the boring one: a module is DECLARED
+ * only if it was STAGED. A declaration whose binary is not in the package turns
+ * "this target doesn't support it" into "the file 404'd", which is a much harder
+ * thing to understand from a device.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, mkdir, readFile, readdir } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ loadProjectModules, sideModuleDeclarations, stageProjectModules, PROJECT_MODULES_DIR,
+} from '../src/export/projectModules';
+
+let root: string;
+
+/** A module directory as a project would lay one out. */
+async function writeModule(id: string, opts: {
+ manifest?: Record<string, unknown> | null;
+ builds?: Record<string, string[]>;
+} = {}): Promise<void> {
+ const dir = path.join(root, PROJECT_MODULES_DIR, id);
+ await mkdir(dir, { recursive: true });
+ if (opts.manifest !== null) {
+ await writeFile(path.join(dir, 'module.json'), JSON.stringify(opts.manifest ?? { file: id }));
+ }
+ for (const [platform, files] of Object.entries(opts.builds ?? {})) {
+ await mkdir(path.join(dir, platform), { recursive: true });
+ for (const f of files) await writeFile(path.join(dir, platform, f), `/* ${f} */`);
+ }
+}
+
+beforeEach(async () => { root = await mkdtemp(path.join(tmpdir(), 'es-modules-')); });
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+describe('discovery', () => {
+ it('finds nothing in a project that declares nothing', async () => {
+ expect(await loadProjectModules(root, 'web')).toEqual([]);
+ });
+
+ it('takes the directory name as the id, and the manifest for the rest', async () => {
+ await writeModule('rive', {
+ manifest: { file: 'rive_runtime', globalName: 'RiveModule' },
+ builds: { web: ['rive_runtime.js', 'rive_runtime.wasm'] },
+ });
+ const [m] = await loadProjectModules(root, 'web');
+ expect(m.id).toBe('rive');
+ expect(m.file).toBe('rive_runtime');
+ expect(m.globalName).toBe('RiveModule');
+ expect(m.buildDir).toContain(path.join('rive', 'web'));
+ });
+
+ it('needs no manifest when the files follow the convention', async () => {
+ await writeModule('lottie', { manifest: null, builds: { web: ['lottie.js', 'lottie.wasm'] } });
+ const [m] = await loadProjectModules(root, 'web');
+ expect(m).toMatchObject({ id: 'lottie', file: 'lottie' });
+ expect(m.buildDir).not.toBeNull();
+ });
+
+ it('serves desktop and playable from the web build — same glue, same engine', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ for (const platform of ['web', 'desktop', 'playable'] as const) {
+ expect((await loadProjectModules(root, platform))[0].buildDir).not.toBeNull();
+ }
+ });
+
+ it('will not serve a mini-game from the web build', async () => {
+ // WeChat needs its own emscripten build (WXWebAssembly glue, a different
+ // es-target) — which is why the engine builds its own modules twice too.
+ // Substituting the web one produces a package that fails on a device.
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ expect((await loadProjectModules(root, 'wechat'))[0].buildDir).toBeNull();
+ });
+
+ it('lets a project vendor use its own directory, else the wechat build', async () => {
+ await writeModule('rive', { builds: { wechat: ['rive.js'], 'acme-play': ['rive.js'] } });
+ expect((await loadProjectModules(root, 'acme-play'))[0].buildDir).toContain('acme-play');
+ await rm(path.join(root, PROJECT_MODULES_DIR, 'rive', 'acme-play'), { recursive: true });
+ expect((await loadProjectModules(root, 'acme-play'))[0].buildDir).toContain('wechat');
+ });
+});
+
+describe('declarations', () => {
+ it('declares only what was staged', async () => {
+ await writeModule('has-build', { builds: { web: ['has-build.js'] } });
+ await writeModule('no-build', {});
+ const modules = await loadProjectModules(root, 'web');
+ expect(sideModuleDeclarations(modules, 'web').map((d) => d.id)).toEqual(['has-build']);
+ });
+
+ it('declares nothing for native, which cannot load one', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const modules = await loadProjectModules(root, 'android');
+ expect(sideModuleDeclarations(modules, 'android')).toEqual([]);
+ });
+
+ it('carries globalName only when there is one', async () => {
+ await writeModule('a', { manifest: { file: 'a', globalName: 'AModule' }, builds: { web: ['a.js'] } });
+ await writeModule('b', { builds: { web: ['b.js'] } });
+ const decls = sideModuleDeclarations(await loadProjectModules(root, 'web'), 'web');
+ expect(decls.find((d) => d.id === 'a')).toEqual({ id: 'a', file: 'a', globalName: 'AModule' });
+ expect(decls.find((d) => d.id === 'b')).toEqual({ id: 'b', file: 'b' });
+ });
+});
+
+describe('staging', () => {
+ let out: string;
+ beforeEach(async () => { out = await mkdtemp(path.join(tmpdir(), 'es-wasm-')); });
+ afterEach(async () => { await rm(out, { recursive: true, force: true }); });
+
+ it('puts glue and binary where every transport already looks', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js', 'rive.wasm'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'web'), out, 'web');
+ expect(warnings).toEqual([]);
+ expect((await readdir(out)).sort()).toEqual(['rive.js', 'rive.wasm']);
+ });
+
+ it('tolerates a build whose binary is embedded in the glue', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'web'), out, 'web');
+ expect(warnings).toEqual([]);
+ expect(await readdir(out)).toEqual(['rive.js']);
+ });
+
+ it('names the module and where it looked when there is no build for the target', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'wechat'), out, 'wechat');
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toContain('"rive"');
+ expect(warnings[0]).toContain('wechat/rive.js');
+ expect(existsSync(path.join(out, 'rive.js'))).toBe(false);
+ });
+
+ it('stages nothing on native, and says why', async () => {
+ await writeModule('rive', { builds: { web: ['rive.js'] } });
+ const warnings = await stageProjectModules(await loadProjectModules(root, 'android'), out, 'android');
+ expect(warnings.join('\n')).toContain('app binary');
+ expect(await readdir(out)).toEqual([]);
+ });
+
+ it('rewrites the glue when the vendor demands it', async () => {
+ // Mini-game hosts reject syntax emscripten emits by default; the export
+ // already down-levels the engine's glue, and a project module's glue is the
+ // same kind of file.
+ await writeModule('rive', { builds: { wechat: ['rive.js', 'rive.wasm'] } });
+ await stageProjectModules(await loadProjectModules(root, 'wechat'), out, 'wechat',
+ async (code) => `${code}// down-levelled`);
+ expect(await readFile(path.join(out, 'rive.js'), 'utf8')).toContain('// down-levelled');
+ // …and leaves the binary alone.
+ expect(await readFile(path.join(out, 'rive.wasm'), 'utf8')).not.toContain('down-levelled');
+ });
+});
diff --git a/pipeline/tests/project-packaging.test.ts b/pipeline/tests/project-packaging.test.ts
new file mode 100644
index 000000000..fb47f4ed2
--- /dev/null
+++ b/pipeline/tests/project-packaging.test.ts
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { parseManifest, resolveOrientation, orientationFromDesignResolution } from '../src/project/format';
+
+describe('parseManifest — packaging', () => {
+ it('parses a valid packaging section', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: {
+ platform: 'wechat', config: 'shipping', sourceMaps: false, openFolder: true,
+ outDir: { wechat: 'out/wx', web: 'out/web' },
+ },
+ });
+ expect(m.packaging).toEqual({
+ platform: 'wechat', config: 'shipping', sourceMaps: false, openFolder: true,
+ outDir: { wechat: 'out/wx', web: 'out/web' },
+ });
+ });
+
+ it('drops invalid config + non-string outDir entries', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { config: 'debug', sourceMaps: 'yes', outDir: { web: 'ok', desktop: 123 } },
+ });
+ expect(m.packaging).toEqual({ outDir: { web: 'ok' } });
+ });
+
+ // The platform id is OPEN: a project can define its own target in
+ // .esengine/platforms/, so the manifest parser cannot tell an unknown id from
+ // a bad one. It keeps any non-empty string and drops everything else.
+ it('keeps an unknown platform id (a project may define one) but drops non-strings', () => {
+ expect(parseManifest({ name: 'X', packaging: { platform: 'acme-play' } }).packaging?.platform).toBe('acme-play');
+ // An id an older editor wrote migrates to what this one spells: 'native' was
+ // one row for both mobile targets, and reopens on the one that builds anywhere.
+ expect(parseManifest({ name: 'X', packaging: { platform: 'native' } }).packaging?.platform).toBe('android');
+ expect(parseManifest({ name: 'X', packaging: { platform: '' } }).packaging).toBeUndefined();
+ expect(parseManifest({ name: 'X', packaging: { platform: 7 } }).packaging).toBeUndefined();
+ });
+
+ it('keeps per-platform output dirs for project-defined platforms', () => {
+ const m = parseManifest({ name: 'X', packaging: { outDir: { 'acme-play': 'dist-acme', android: 'dist-android' } } });
+ expect(m.packaging?.outDir).toEqual({ 'acme-play': 'dist-acme', android: 'dist-android' });
+ });
+
+ // The size budget round-trips, keyed like outDir. Caught on a real export: the
+ // dialog wrote it to the manifest and the parser — which is a whitelist —
+ // dropped it on the way back, so the build was still judged by the platform's
+ // limit and the field looked like it did nothing.
+ it('parses per-platform size budgets, migrating legacy platform ids', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { sizeBudget: { wechat: 2097152, native: 40 * 1024 * 1024, 'acme-play': 5000 } },
+ });
+ expect(m.packaging?.sizeBudget).toEqual({
+ wechat: 2097152, android: 40 * 1024 * 1024, 'acme-play': 5000,
+ });
+ });
+
+ it('drops size budgets that could not be judged against', () => {
+ // A zero would read as "every build is infinitely over"; absence means the
+ // target keeps its own limit, which is the honest state for a bad value.
+ const m = parseManifest({
+ name: 'X',
+ packaging: { sizeBudget: { web: 0, wechat: -1, desktop: 'big', ios: Number.NaN, android: 10 } },
+ });
+ expect(m.packaging?.sizeBudget).toEqual({ android: 10 });
+ expect(parseManifest({ name: 'X', packaging: { sizeBudget: { web: 0 } } }).packaging?.sizeBudget)
+ .toBeUndefined();
+ });
+
+ it('parses excludeScenes, dropping non-string / empty entries', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { excludeScenes: ['assets/scenes/dev.esscene', '', 7, 'assets/scenes/test.esscene'] },
+ });
+ expect(m.packaging?.excludeScenes).toEqual(['assets/scenes/dev.esscene', 'assets/scenes/test.esscene']);
+ // An empty list is no list.
+ expect(parseManifest({ name: 'X', packaging: { excludeScenes: [] } }).packaging).toBeUndefined();
+ });
+
+ it('omits packaging when absent', () => {
+ expect(parseManifest({ name: 'X' }).packaging).toBeUndefined();
+ });
+
+ it('parses per-platform packaging config, dropping unknown fields', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: {
+ platforms: {
+ wechat: { appid: 'wx123', junk: 1 },
+ desktop: { appId: 'com.x.y', productName: 'Y', extra: 'z' },
+ },
+ },
+ });
+ expect(m.packaging?.platforms).toEqual({
+ wechat: { appid: 'wx123' },
+ desktop: { appId: 'com.x.y', productName: 'Y' },
+ });
+ });
+});
+
+describe('parseManifest — orientation (unified, project-wide)', () => {
+ it('parses a top-level orientation', () => {
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'landscape' } }).packaging?.orientation).toBe('landscape');
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'portrait' } }).packaging?.orientation).toBe('portrait');
+ });
+
+ it('parses the playable ad network, and drops an empty one', () => {
+ expect(parseManifest({ name: 'X', packaging: { platforms: { playable: { network: 'meta' } } } })
+ .packaging?.platforms?.playable?.network).toBe('meta');
+ // An empty string is not a selection — it must fall through to generic.
+ expect(parseManifest({ name: 'X', packaging: { platforms: { playable: { network: '' } } } })
+ .packaging?.platforms).toBeUndefined();
+ });
+
+ it('drops an invalid top-level orientation', () => {
+ expect(parseManifest({ name: 'X', packaging: { orientation: 'diagonal' } }).packaging).toBeUndefined();
+ });
+
+ it('migrates a legacy wechat.orientation to the top level, dropping the per-platform field', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { wechat: { appid: 'wx1', orientation: 'landscape' } } },
+ });
+ expect(m.packaging?.orientation).toBe('landscape');
+ expect(m.packaging?.platforms).toEqual({ wechat: { appid: 'wx1' } }); // orientation hoisted out
+ });
+
+ it('migrates a legacy playable.orientation and drops the (now-empty) playable block', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { playable: { orientation: 'portrait' } } },
+ });
+ expect(m.packaging?.orientation).toBe('portrait');
+ expect(m.packaging?.platforms).toBeUndefined(); // playable had only orientation → gone
+ });
+
+ it('prefers an explicit top-level orientation over a legacy per-platform one', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { orientation: 'portrait', platforms: { wechat: { orientation: 'landscape' } } },
+ });
+ expect(m.packaging?.orientation).toBe('portrait');
+ });
+
+ it('prefers wechat over playable when both legacy fields are present', () => {
+ const m = parseManifest({
+ name: 'X',
+ packaging: { platforms: { wechat: { orientation: 'landscape' }, playable: { orientation: 'portrait' } } },
+ });
+ expect(m.packaging?.orientation).toBe('landscape');
+ });
+});
+
+describe('resolveOrientation / orientationFromDesignResolution', () => {
+ it('derives orientation from the design resolution aspect', () => {
+ expect(orientationFromDesignResolution({ width: 1920, height: 1080 })).toBe('landscape');
+ expect(orientationFromDesignResolution({ width: 1080, height: 1920 })).toBe('portrait');
+ expect(orientationFromDesignResolution({ width: 800, height: 800 })).toBe('landscape'); // square ⇒ landscape
+ expect(orientationFromDesignResolution(undefined)).toBe('landscape'); // engine default 1920×1080
+ });
+
+ it('resolves the explicit setting first, else derives from the design resolution', () => {
+ expect(resolveOrientation({ packaging: { orientation: 'portrait' }, designResolution: { width: 1920, height: 1080 } })).toBe('portrait');
+ expect(resolveOrientation({ designResolution: { width: 1080, height: 1920 } })).toBe('portrait');
+ expect(resolveOrientation({ designResolution: { width: 1280, height: 720 } })).toBe('landscape');
+ expect(resolveOrientation({})).toBe('landscape'); // no packaging, no design res
+ });
+});
diff --git a/pipeline/tests/project-physics.test.ts b/pipeline/tests/project-physics.test.ts
new file mode 100644
index 000000000..57079f584
--- /dev/null
+++ b/pipeline/tests/project-physics.test.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file parseManifest — physics world config (Project Settings → Physics). Guards that
+ * the solver tuning + collision matrix round-trip through project.esproject and
+ * that invalid values are dropped/clamped.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest } from '../src/project/format';
+
+describe('parseManifest — physics', () => {
+ it('parses the full physics world config', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: {
+ physics: {
+ enabled: true,
+ gravity: { x: 0, y: -20 },
+ collisionLayers: ['Default', 'Player'],
+ collisionLayerMasks: [0xffff, 0x0005],
+ fixedTimestep: 0.02,
+ subStepCount: 6,
+ contactHertz: 60,
+ contactDampingRatio: 5,
+ contactSpeed: 8,
+ enableSleep: false,
+ enableContinuous: false,
+ },
+ },
+ });
+ expect(m.features?.physics).toMatchObject({
+ enabled: true,
+ gravity: { x: 0, y: -20 },
+ collisionLayerMasks: [0xffff, 0x0005],
+ fixedTimestep: 0.02,
+ subStepCount: 6,
+ contactHertz: 60,
+ contactDampingRatio: 5,
+ contactSpeed: 8,
+ enableSleep: false,
+ enableContinuous: false,
+ });
+ expect(m.features?.physics?.collisionLayers?.slice(0, 2)).toEqual(['Default', 'Player']);
+ });
+
+ it('drops non-numeric solver values and masks bad matrix rows to all-collide', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: { physics: { fixedTimestep: 'fast', contactHertz: 90, collisionLayerMasks: [3, 'x', 7] } },
+ });
+ const p = m.features?.physics;
+ expect(p?.fixedTimestep).toBeUndefined(); // invalid → dropped (runtime default applies)
+ expect(p?.contactHertz).toBe(90);
+ expect(p?.collisionLayerMasks).toEqual([3, 0xffff, 7]); // bad row → all-collide
+ });
+
+ it('omits physics when absent', () => {
+ expect(parseManifest({ name: 'X' }).features?.physics).toBeUndefined();
+ });
+});
diff --git a/pipeline/tests/project-rendering.test.ts b/pipeline/tests/project-rendering.test.ts
new file mode 100644
index 000000000..3897a4896
--- /dev/null
+++ b/pipeline/tests/project-rendering.test.ts
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file parseManifest — rendering feature (Project Settings → Rendering). Guards the
+ * colorSpace project setting: 'linear' persists, the default 'gamma' is expressed
+ * by absence, and junk values are dropped.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ parseManifest, cameraScaleModeValue, resolveScreenFit, trimSortingLayers, SORTING_LAYER_COUNT,
+} from '../src/project/format';
+
+describe('parseManifest — rendering.colorSpace', () => {
+ it("keeps 'linear'", () => {
+ const m = parseManifest({ name: 'X', features: { rendering: { colorSpace: 'linear' } } });
+ expect(m.features?.rendering?.colorSpace).toBe('linear');
+ });
+
+ it("drops 'gamma' (default = absence) and junk values", () => {
+ for (const v of ['gamma', 'LINEAR', 42, true, null]) {
+ const m = parseManifest({ name: 'X', features: { rendering: { colorSpace: v } } });
+ expect(m.features?.rendering?.colorSpace).toBeUndefined();
+ }
+ });
+
+ it('coexists with sorting/y-sort config', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: { rendering: { sortingLayers: ['BG', 'FG'], ySortLayers: [1], colorSpace: 'linear' } },
+ });
+ expect(m.features?.rendering).toEqual({
+ sortingLayers: ['BG', 'FG'],
+ ySortLayers: [1],
+ colorSpace: 'linear',
+ });
+ });
+});
+
+describe('sorting layers — slot count', () => {
+ it('names every slot up to the y-sort mask width, and drops the rest', () => {
+ const names = Array.from({ length: SORTING_LAYER_COUNT + 4 }, (_, i) => `L${i}`);
+ const parsed = parseManifest({ name: 'X', features: { rendering: { sortingLayers: names } } });
+ expect(parsed.features?.rendering?.sortingLayers).toHaveLength(SORTING_LAYER_COUNT);
+ expect(parsed.features?.rendering?.sortingLayers?.[SORTING_LAYER_COUNT - 1]).toBe(`L${SORTING_LAYER_COUNT - 1}`);
+ });
+
+ it('y-sorts the last nameable layer but nothing past it (the mask is 32 bits)', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: { rendering: { ySortLayers: [0, SORTING_LAYER_COUNT - 1, SORTING_LAYER_COUNT, -1] } },
+ });
+ expect(m.features?.rendering?.ySortLayers).toEqual([0, SORTING_LAYER_COUNT - 1]);
+ });
+});
+
+describe('trimSortingLayers', () => {
+ it('drops trailing empties — the control sends a full-width list', () => {
+ expect(trimSortingLayers(['back', 'mid', '', '', ''])).toEqual(['back', 'mid']);
+ expect(trimSortingLayers(Array.from({ length: SORTING_LAYER_COUNT }, () => ''))).toEqual([]);
+ });
+
+ it('keeps an interior gap — a slot means its index, so the gap is a real z-order step', () => {
+ expect(trimSortingLayers(['back', '', 'front', ''])).toEqual(['back', '', 'front']);
+ });
+
+ it('never stores more than the nameable slots', () => {
+ const names = Array.from({ length: SORTING_LAYER_COUNT + 5 }, (_, i) => `L${i}`);
+ expect(trimSortingLayers(names)).toHaveLength(SORTING_LAYER_COUNT);
+ });
+});
+
+describe('parseManifest — rendering.cameraScaleMode', () => {
+ it('keeps every real fit mode + clamps cameraMatch to 0..1', () => {
+ for (const mode of ['fixed-width', 'fixed-height', 'expand', 'shrink', 'match'] as const) {
+ expect(parseManifest({ name: 'X', features: { rendering: { cameraScaleMode: mode } } })
+ .features?.rendering?.cameraScaleMode).toBe(mode);
+ }
+ expect(parseManifest({ name: 'X', features: { rendering: { cameraMatch: 5 } } })
+ .features?.rendering?.cameraMatch).toBe(1);
+ expect(parseManifest({ name: 'X', features: { rendering: { cameraMatch: -2 } } })
+ .features?.rendering?.cameraMatch).toBe(0);
+ });
+
+ it("drops 'none' (default = absence) and junk", () => {
+ for (const v of ['none', 'diagonal', 42, true]) {
+ expect(parseManifest({ name: 'X', features: { rendering: { cameraScaleMode: v } } })
+ .features?.rendering?.cameraScaleMode).toBeUndefined();
+ }
+ });
+});
+
+describe('cameraScaleModeValue / resolveScreenFit', () => {
+ it('maps names to the engine CanvasScaleMode value (-1 = off)', () => {
+ expect(cameraScaleModeValue('fixed-width')).toBe(0);
+ expect(cameraScaleModeValue('fixed-height')).toBe(1);
+ expect(cameraScaleModeValue('expand')).toBe(2);
+ expect(cameraScaleModeValue('shrink')).toBe(3);
+ expect(cameraScaleModeValue('match')).toBe(4);
+ expect(cameraScaleModeValue('none')).toBe(-1);
+ expect(cameraScaleModeValue(undefined)).toBe(-1);
+ });
+
+ it('builds the runtime screenFit from design resolution + fit; off by default', () => {
+ expect(resolveScreenFit({ designResolution: { width: 1280, height: 720 } }))
+ .toEqual({ designWidth: 1280, designHeight: 720, scaleMode: -1, matchWidthOrHeight: 0.5 });
+ expect(resolveScreenFit({
+ designResolution: { width: 1080, height: 1920 },
+ features: { rendering: { cameraScaleMode: 'expand', cameraMatch: 0.25 } },
+ })).toEqual({ designWidth: 1080, designHeight: 1920, scaleMode: 2, matchWidthOrHeight: 0.25 });
+ // No design resolution ⇒ the engine default, still off.
+ expect(resolveScreenFit({})).toEqual({ designWidth: 1920, designHeight: 1080, scaleMode: -1, matchWidthOrHeight: 0.5 });
+ });
+});
diff --git a/pipeline/tests/project-ui-theme.test.ts b/pipeline/tests/project-ui-theme.test.ts
new file mode 100644
index 000000000..41aae0e01
--- /dev/null
+++ b/pipeline/tests/project-ui-theme.test.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file parseManifest — ui feature (Project Settings → UI). Guards the widget
+ * theme + per-role color overrides: 'light' persists (dark = absence),
+ * overrides keep only known roles with valid hex, and an empty ui block
+ * disappears entirely.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest } from '../src/project/format';
+
+describe('parseManifest — features.ui', () => {
+ it("keeps theme 'light'; dark/junk = absence", () => {
+ expect(parseManifest({ name: 'X', features: { ui: { theme: 'light' } } }).features?.ui?.theme).toBe('light');
+ for (const v of ['dark', 'LIGHT', 42, null]) {
+ expect(parseManifest({ name: 'X', features: { ui: { theme: v } } }).features?.ui).toBeUndefined();
+ }
+ });
+
+ it('keeps only known roles with valid hex (lowercased), drops the rest', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: {
+ ui: {
+ colors: {
+ primary: '#FF0000',
+ backdrop: '#00000080',
+ surface: 'red',
+ notARole: '#00ff00',
+ control: 42,
+ },
+ },
+ },
+ });
+ expect(m.features?.ui?.colors).toEqual({ primary: '#ff0000', backdrop: '#00000080' });
+ });
+
+ it('colors coexist with a light base; all-junk colors vanish', () => {
+ const m = parseManifest({ name: 'X', features: { ui: { theme: 'light', colors: { primary: '#123456' } } } });
+ expect(m.features?.ui).toEqual({ theme: 'light', colors: { primary: '#123456' } });
+ const m2 = parseManifest({ name: 'X', features: { ui: { colors: { nope: 'junk' } } } });
+ expect(m2.features?.ui).toBeUndefined();
+ });
+});
diff --git a/pipeline/tests/runtime-config.test.ts b/pipeline/tests/runtime-config.test.ts
new file mode 100644
index 000000000..6f4583d51
--- /dev/null
+++ b/pipeline/tests/runtime-config.test.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file runtimeConfig — the one derivation of "what the game will run with".
+ *
+ * The play realm and every exported build read this, so what it says a project
+ * runs with IS what both do. The cases here are the ones a second, hand-written
+ * copy of the list used to get wrong: a mask that never made it out of the
+ * editor, and a default that has to stay expressed by ABSENCE or an untouched
+ * project ships different bytes.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, runtimeConfigOf,
+} from '../src/project/runtimeConfig';
+
+describe('runtimeConfigOf', () => {
+ it('answers with the engine defaults for a project that declares nothing', () => {
+ const rc = runtimeConfigOf({});
+ expect(rc.ySortLayers).toBe(0);
+ expect(rc.depthLayers).toBe(0);
+ expect(rc.colorSpace).toBe('gamma');
+ expect(rc.uiTheme).toBe('dark');
+ expect(rc.uiThemeColors).toEqual({});
+ expect(rc.physicsEnabled).toBe(false);
+ expect(rc.audioConfig).toEqual({});
+ expect(rc.screenFit.scaleMode).toBe(-1); // fit off
+ expect(rc.physicsConfig.gravity).toEqual({ x: 0, y: -9.81 });
+ expect(rc).toEqual(DEFAULT_RUNTIME_CONFIG);
+ });
+
+ it('turns the sorting-layer lists into the masks the renderer takes', () => {
+ const rc = runtimeConfigOf({
+ features: { rendering: { ySortLayers: [0, 3], depthLayers: [1, 2] } },
+ });
+ expect(rc.ySortLayers).toBe(0b1001);
+ expect(rc.depthLayers).toBe(0b0110);
+ });
+
+ it('drops layer indices no 32-bit mask can carry, rather than wrapping them', () => {
+ const rc = runtimeConfigOf({
+ features: { rendering: { depthLayers: [-1, 0, 31, 32, 1.5] } },
+ });
+ // Bit 31 + bit 0, UNSIGNED: the mask crosses to C++ as a u32, so a signed
+ // `|` result here would be a different number than the renderer receives.
+ expect(rc.depthLayers).toBe(((1 << 31) >>> 0) + 1);
+ });
+
+ it('sends the collision matrix only when it actually restricts a pair', () => {
+ const open = runtimeConfigOf({ features: { physics: { collisionLayerMasks: [0xffff, 0xffff] } } });
+ expect(open.physicsConfig.collisionLayerMasks).toBeUndefined();
+
+ const restricted = runtimeConfigOf({ features: { physics: { collisionLayerMasks: [0xfffe] } } });
+ expect(restricted.physicsConfig.collisionLayerMasks?.[0]).toBe(0xfffe);
+ expect(restricted.physicsConfig.collisionLayerMasks).toHaveLength(16); // padded to the filter bits
+ });
+
+ it('folds the solver defaults in, so the settings page and the game agree', () => {
+ const rc = runtimeConfigOf({ features: { physics: { enabled: true, subStepCount: 8 } } });
+ expect(rc.physicsEnabled).toBe(true);
+ expect(rc.physicsConfig.subStepCount).toBe(8);
+ expect(rc.physicsConfig.fixedTimestep).toBeCloseTo(1 / 60, 9);
+ expect(rc.physicsConfig.enableSleep).toBe(true);
+ });
+});
+
+describe('packagedRuntimeFields', () => {
+ // Absence IS the default in game.config.json, so an untouched project carries
+ // nothing it did not declare.
+ it('carries only the design resolution for a project that declared nothing', () => {
+ // Not a setting a project opts into: every project HAS a design resolution,
+ // and a desktop window opens at it. Everything else stays absent so a build
+ // with default settings keeps the config it has always had.
+ expect(packagedRuntimeFields(runtimeConfigOf({}))).toEqual({
+ screenFit: { designWidth: 1920, designHeight: 1080, scaleMode: -1, matchWidthOrHeight: 0.5 },
+ });
+ });
+
+ it('carries the 2.5D depth mask — the field that used to reach Play and no build', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ features: { rendering: { depthLayers: [1, 2] } },
+ }));
+ expect(fields.depthLayers).toBe(0b110);
+ });
+
+ it('carries every non-default and nothing else', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ designResolution: { width: 800, height: 600 },
+ features: {
+ rendering: { ySortLayers: [1], depthLayers: [2], colorSpace: 'linear', cameraScaleMode: 'expand' },
+ ui: { theme: 'light', colors: { accent: '#ff0000ff' } },
+ },
+ }));
+ expect(Object.keys(fields).sort()).toEqual(
+ ['colorSpace', 'depthLayers', 'screenFit', 'uiTheme', 'uiThemeColors', 'ySortLayers'],
+ );
+ expect(fields.screenFit).toEqual({
+ designWidth: 800, designHeight: 600, scaleMode: 2, matchWidthOrHeight: 0.5,
+ });
+ });
+
+ // The design resolution is what a desktop window opens at, and a window has a
+ // size whether or not the camera scales to it — so it ships even with the fit
+ // off, which is the case every project starts in.
+ it('carries the design resolution even when the camera fit is off', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ designResolution: { width: 1080, height: 1920 },
+ }));
+ expect(fields.screenFit).toEqual({
+ designWidth: 1080, designHeight: 1920, scaleMode: -1, matchWidthOrHeight: 0.5,
+ });
+ });
+
+ // Physics and the mixer used to reach Play and no shipped build at all, so a
+ // game verified in Play could ship with different gravity and a silent mixer.
+ it('carries physics and the mixer, which used to reach Play and no build', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ features: {
+ physics: { enabled: true, gravity: { x: 0, y: -20 }, collisionLayerMasks: [0xfffe] },
+ audio: { buses: [{ name: 'sfx', volume: 0.5 }] },
+ },
+ }));
+ expect(fields.physicsEnabled).toBe(true);
+ expect(fields.physicsConfig?.gravity).toEqual({ x: 0, y: -20 });
+ expect(fields.physicsConfig?.collisionLayerMasks?.[0]).toBe(0xfffe);
+ expect(fields.audioConfig?.buses?.[0]).toEqual({ name: 'sfx', volume: 0.5 });
+ });
+
+ // ...but only when declared: a default world would otherwise be spelled out in
+ // every existing build's config, and a runtime falls back to the same values.
+ it('omits a physics world and a mixer that are just the defaults', () => {
+ const declaredButDefault = packagedRuntimeFields(runtimeConfigOf({
+ features: { physics: { gravity: { x: 0, y: -9.81 } }, audio: {} },
+ }));
+ expect(declaredButDefault.physicsConfig).toBeUndefined();
+ expect(declaredButDefault.audioConfig).toBeUndefined();
+ expect(declaredButDefault.physicsEnabled).toBeUndefined();
+ });
+
+ // The editor's live project state is not a manifest object, but it has the two
+ // fields this reads — that structural match is what lets one derivation serve
+ // the renderer and the main process.
+ it('reads a project state as readily as a parsed manifest', () => {
+ const state = { name: 'X', root: '/p', designResolution: { width: 640, height: 480 }, features: {} };
+ expect(runtimeConfigOf(state).screenFit.designWidth).toBe(640);
+ });
+});
diff --git a/pipeline/tests/size-report.test.ts b/pipeline/tests/size-report.test.ts
new file mode 100644
index 000000000..7ca286ad7
--- /dev/null
+++ b/pipeline/tests/size-report.test.ts
@@ -0,0 +1,270 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a package weighs, and against what.
+ *
+ * Two claims carry the whole feature, and both are easy to get quietly wrong:
+ *
+ * Bytes are attributed by DELIVERY, not by existing. A group the project
+ * marked `remote` is downloaded from a CDN and costs the package nothing, so
+ * counting it would report a build over a limit it is nowhere near — the exact
+ * failure that makes a size report something a developer learns to ignore.
+ *
+ * The package and the uploaded file are the SAME content twice. An .apk sits
+ * inside the directory whose files it contains; a playable's zip is an archive
+ * of the html beside it. Counting both doubles the build.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ summarizeBuildFiles, bucketIndexFrom, kindOf, measureBuild, collectBuildFiles,
+} from '../src/export/sizeReport';
+import { resolveSizeBudgets, evaluateSizeBudget, formatBytes, PROJECT_BUDGET_NOTE } from '../src/project/sizeBudget';
+
+const MB = 1024 * 1024;
+
+/** A manifest shaped like the one every export writes: one group per delivery mode. */
+const MANIFEST = {
+ version: '2.0',
+ groups: {
+ main: {
+ bundleMode: 'local',
+ assets: { 'uuid-a': { path: 'assets/hero.png' } },
+ },
+ levels: {
+ bundleMode: 'lazy',
+ assets: { 'uuid-b': { path: 'subpackages/levels/assets/level2.png' } },
+ },
+ dlc: {
+ bundleMode: 'remote',
+ assets: { 'uuid-c': { path: 'remote/dlc/assets/movie.mp4' } },
+ },
+ },
+};
+
+describe('bucketing by delivery', () => {
+ it('attributes each asset to the mode its group ships in', () => {
+ const buckets = bucketIndexFrom(MANIFEST);
+ expect(buckets.get('assets/hero.png')).toBe('initial');
+ expect(buckets.get('subpackages/levels/assets/level2.png')).toBe('lazy');
+ expect(buckets.get('remote/dlc/assets/movie.mp4')).toBe('remote');
+ });
+
+ it('counts anything the manifest does not claim as initial — the runtime is not optional', () => {
+ const report = summarizeBuildFiles([
+ { path: 'wasm/engine.wasm', bytes: 900 },
+ { path: 'game.js', bytes: 100 },
+ { path: 'index.html', bytes: 10 },
+ ], { buckets: bucketIndexFrom(MANIFEST) });
+ expect(report.initialBytes).toBe(1010);
+ expect(report.lazyBytes).toBe(0);
+ });
+
+ it('keeps CDN content out of the package, while still reporting it', () => {
+ const report = summarizeBuildFiles([
+ { path: 'assets/hero.png', bytes: 1000 },
+ { path: 'subpackages/levels/assets/level2.png', bytes: 2000 },
+ { path: 'remote/dlc/assets/movie.mp4', bytes: 90_000 },
+ ], { buckets: bucketIndexFrom(MANIFEST) });
+ expect(report.initialBytes).toBe(1000);
+ expect(report.lazyBytes).toBe(2000);
+ expect(report.packageBytes).toBe(3000);
+ expect(report.remoteBytes).toBe(90_000);
+ expect(report.totalBytes).toBe(93_000);
+ // …and the CDN's 90KB of video is not part of what fills the package.
+ expect(report.byKind.find((k) => k.kind === 'video')).toBeUndefined();
+ });
+
+ it('drops build intermediates and sourcemaps — neither is downloaded', () => {
+ const report = summarizeBuildFiles([
+ { path: 'assets.manifest.json', bytes: 5000 },
+ { path: 'game.js.map', bytes: 8000 },
+ { path: 'game.js', bytes: 100 },
+ ]);
+ expect(report.totalBytes).toBe(100);
+ expect(report.fileCount).toBe(1);
+ });
+});
+
+describe('composition', () => {
+ it('reads emscripten glue as engine, not as the game\'s own scripts', () => {
+ expect(kindOf('wasm/estella.js')).toBe('engine');
+ expect(kindOf('wasm/estella.wasm')).toBe('engine');
+ expect(kindOf('scripts.mjs')).toBe('scripts');
+ });
+
+ it('separates scenes from the rest of the JSON', () => {
+ expect(kindOf('scenes/level1.json')).toBe('scene');
+ expect(kindOf('game.config.json')).toBe('data');
+ });
+
+ it('classifies cooked textures whatever the cook renamed them to', () => {
+ expect(kindOf('assets/9f8a7c.ktx2')).toBe('texture');
+ expect(kindOf('assets/9f8a7c.png')).toBe('texture');
+ });
+
+ it('sees through a mini-game packer\'s .bin restaging', () => {
+ // WeChat refuses .ktx2, so the export ships it as .ktx2.bin. Filing those
+ // bytes under "data" would send a developer looking through their JSON for
+ // megabytes that are in their art — caught on a real WeChat export.
+ expect(kindOf('assets/pack/tile0.ktx2.bin')).toBe('texture');
+ expect(kindOf('assets/voice.mp3.bin')).toBe('audio');
+ expect(kindOf('assets/blob.bin')).toBe('data'); // a genuinely opaque blob
+ });
+
+ it('ranks kinds by weight and names the largest files', () => {
+ const report = summarizeBuildFiles([
+ { path: 'assets/a.png', bytes: 300 },
+ { path: 'assets/b.png', bytes: 200 },
+ { path: 'music.mp3', bytes: 400 },
+ { path: 'game.js', bytes: 50 },
+ ]);
+ expect(report.byKind.map((k) => k.kind)).toEqual(['texture', 'audio', 'scripts']);
+ expect(report.byKind[0]).toEqual({ kind: 'texture', bytes: 500, count: 2 });
+ expect(report.largest[0].path).toBe('music.mp3');
+ });
+});
+
+describe('budgets', () => {
+ it('judges WeChat against the main package, not the whole build', () => {
+ const budgets = resolveSizeBudgets('wechat');
+ const report = summarizeBuildFiles([
+ { path: 'assets/hero.png', bytes: 3 * MB },
+ { path: 'subpackages/levels/assets/level2.png', bytes: 12 * MB },
+ ], { buckets: bucketIndexFrom(MANIFEST), budgets });
+ const initial = report.verdicts.find((v) => v.budget.scope === 'initial');
+ const total = report.verdicts.find((v) => v.budget.scope === 'total');
+ expect(initial?.status).toBe('ok'); // 3MB main package, under 4
+ expect(total?.status).toBe('ok'); // 15MB all in, under 20
+ expect(initial?.budget.note).toMatch(/main package at 4MB/);
+ // The 12MB subpackage is over the MAIN package limit and is not judged by
+ // it — putting the level behind a subpackage is exactly the fix.
+ expect(initial?.measuredBytes).toBe(3 * MB);
+ });
+
+ it('reports over-limit by how much, so 1% over does not read like double', () => {
+ const report = summarizeBuildFiles([{ path: 'assets/hero.png', bytes: 5 * MB }], {
+ budgets: resolveSizeBudgets('wechat'),
+ });
+ const initial = report.verdicts.find((v) => v.budget.scope === 'initial')!;
+ expect(initial.status).toBe('over');
+ expect(initial.measuredBytes - initial.budget.maxBytes).toBe(1 * MB);
+ expect(initial.ratio).toBeCloseTo(1.25);
+ });
+
+ it('warns before the limit rather than at it', () => {
+ expect(evaluateSizeBudget(3.7 * MB, { scope: 'initial', maxBytes: 4 * MB, note: '' }).status).toBe('near');
+ expect(evaluateSizeBudget(3.5 * MB, { scope: 'initial', maxBytes: 4 * MB, note: '' }).status).toBe('ok');
+ });
+
+ it('lets a project replace the platform\'s limit with its own', () => {
+ const budgets = resolveSizeBudgets('wechat', { projectMaxBytes: 2 * MB });
+ const initial = budgets.find((b) => b.scope === 'initial')!;
+ expect(initial.maxBytes).toBe(2 * MB);
+ expect(initial.note).toBe(PROJECT_BUDGET_NOTE);
+ // The platform's OTHER limit still applies — a project ceiling is not a waiver.
+ expect(budgets.find((b) => b.scope === 'total')?.maxBytes).toBe(20 * MB);
+ });
+
+ it('gives a target with no limit of its own the project\'s, measured before play', () => {
+ const budgets = resolveSizeBudgets('web', { projectMaxBytes: 6 * MB });
+ expect(budgets).toEqual([{ scope: 'initial', maxBytes: 6 * MB, note: PROJECT_BUDGET_NOTE }]);
+ expect(resolveSizeBudgets('web')).toEqual([]);
+ });
+
+ it('prefers a vendor profile\'s limit over the built-in for the same scope', () => {
+ const budgets = resolveSizeBudgets('wechat', {
+ profile: [{ scope: 'initial', maxBytes: 8 * MB, note: 'this host raised it' }],
+ });
+ expect(budgets.find((b) => b.scope === 'initial')?.maxBytes).toBe(8 * MB);
+ expect(budgets.find((b) => b.scope === 'total')?.maxBytes).toBe(20 * MB);
+ });
+
+ it('skips a deliverable limit when no upload file was produced', () => {
+ // An Android export that stopped at the content payload: reporting it as
+ // comfortably under the limit would be a reassuring lie.
+ const report = summarizeBuildFiles([{ path: 'assets/hero.png', bytes: 10 }], {
+ budgets: [{ scope: 'deliverable', maxBytes: 2 * MB, note: 'network cap' }],
+ });
+ expect(report.verdicts).toEqual([]);
+ });
+});
+
+describe('measuring a build on disk', () => {
+ let dir: string;
+ beforeEach(async () => { dir = await mkdtemp(path.join(tmpdir(), 'es-size-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ const write = async (rel: string, bytes: number): Promise<void> => {
+ const abs = path.join(dir, rel);
+ await mkdir(path.dirname(abs), { recursive: true });
+ await writeFile(abs, Buffer.alloc(bytes));
+ };
+
+ it('walks nested output and reports paths in the shipped shape', async () => {
+ await write('wasm/engine.wasm', 64);
+ await write('assets/hero.png', 32);
+ const files = await collectBuildFiles(dir);
+ expect(files.map((f) => f.path).sort()).toEqual(['assets/hero.png', 'wasm/engine.wasm']);
+ });
+
+ it('counts the package once when the upload file sits inside it', async () => {
+ await write('assets/hero.png', 1000);
+ await write('game.js', 500);
+ await write('com.estella.game.apk', 1500); // the same content, packaged
+ const report = await measureBuild({
+ root: dir,
+ platform: 'android',
+ deliverable: path.join(dir, 'com.estella.game.apk'),
+ packages: [path.join(dir, 'com.estella.game.apk')],
+ });
+ expect(report.packageBytes).toBe(1500); // NOT 3000
+ expect(report.deliverableBytes).toBe(1500);
+ expect(report.deliverableName).toBe('com.estella.game.apk');
+ });
+
+ it('measures a desktop app as the directory it is, and counts it once', async () => {
+ // A desktop package is a DIRECTORY, and stat() on one reports a few dozen
+ // bytes of bookkeeping — so measured as a file it weighs nothing and passes
+ // every limit, while its contents are still counted loose beside it.
+ await write('assets/hero.png', 1000);
+ await write('game.config.json', 20);
+ await write('Cool Game/Cool Game.exe', 4000);
+ await write('Cool Game/Content/assets/hero.png', 1000);
+ await write('Cool Game/Content/game.config.json', 20);
+ const app = path.join(dir, 'Cool Game');
+ const report = await measureBuild({
+ root: dir, platform: 'desktop', deliverable: app, packages: [app],
+ });
+ expect(report.packageBytes).toBe(1020); // the loose content only
+ expect(report.deliverableBytes).toBe(5020); // everything inside the app
+ });
+
+ it('reads the manifest the export wrote, so buckets agree with the runtime', async () => {
+ await write('asset-manifest.json', 0);
+ await writeFile(path.join(dir, 'asset-manifest.json'), JSON.stringify(MANIFEST));
+ await write('assets/hero.png', 1000);
+ await write('remote/dlc/assets/movie.mp4', 50_000);
+ const report = await measureBuild({ root: dir, platform: 'web' });
+ expect(report.initialBytes).toBe(1000 + report.byKind.reduce((n, k) => k.kind === 'data' ? n + k.bytes : n, 0));
+ expect(report.remoteBytes).toBe(50_000);
+ });
+
+ it('never fails a build: an output dir that is not there measures as empty', async () => {
+ const report = await measureBuild({ root: path.join(dir, 'nope'), platform: 'web' });
+ expect(report.fileCount).toBe(0);
+ expect(report.packageBytes).toBe(0);
+ });
+});
+
+describe('one spelling of a byte size', () => {
+ it('is binary, and drops the decimal once the number is big enough to not need it', () => {
+ expect(formatBytes(900)).toBe('900 B');
+ expect(formatBytes(1536)).toBe('1.5 KB');
+ expect(formatBytes(4 * MB)).toBe('4.0 MB');
+ expect(formatBytes(40 * MB)).toBe('40 MB');
+ expect(formatBytes(3 * 1024 * MB)).toBe('3.0 GB');
+ });
+});
diff --git a/pipeline/tests/spine-cook-deps.test.ts b/pipeline/tests/spine-cook-deps.test.ts
new file mode 100644
index 000000000..9dff8d8fe
--- /dev/null
+++ b/pipeline/tests/spine-cook-deps.test.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Regression: a Spine `.atlas` names its page image(s) as texture dependencies.
+ * The `.atlas` is a TEXT manifest (not JSON), so the dep scan must parse it and
+ * follow atlas → page image — otherwise the cook culls the texture and every
+ * ship target (playable/web/…) requests it as an external file and 404s it.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase } from '../src/assets/assetDb';
+import { cookAssets } from '../src/assets/cookAssets';
+
+let root: string;
+
+const PAGE_TEX = '11111111-1111-4111-8111-111111111111';
+const ATLAS = '22222222-2222-4222-8222-222222222222';
+const SKEL = '33333333-3333-4333-8333-333333333333';
+const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+function writeAsset(rel: string, type: string, uuid: string, body: string | Uint8Array = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+// A spine atlas: the page image name sits at column 0, its region properties indented.
+// The page ref (`hero.png`) is relative to the atlas file (a sibling under assets/spine/).
+const atlas = [
+ 'hero.png',
+ '\tsize: 64, 64',
+ '\tfilter: Linear, Linear',
+ 'region',
+ '\tbounds: 0, 0, 32, 32',
+ '',
+].join('\n');
+
+// The scene references BOTH the skeleton and the atlas (SpineAnimation fields), the way
+// discoverSceneAssets pairs them at runtime — so both are reachable directly.
+const scene = JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [{
+ id: 1, name: 'S', parent: null, children: [], components: [{
+ type: 'SpineAnimation',
+ data: { skeletonPath: 'assets/spine/hero.skel', atlasPath: 'assets/spine/hero.atlas' },
+ }],
+ }],
+});
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-spinecook-'));
+ writeAsset('assets/spine/hero.png', 'texture', PAGE_TEX, 'PNG');
+ writeAsset('assets/spine/hero.atlas', 'spine', ATLAS, atlas);
+ writeAsset('assets/spine/hero.skel', 'spine', SKEL, new Uint8Array([1, 2, 3, 4]));
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, scene);
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+describe('spine atlas page images are cooked dependencies', () => {
+ it('links atlas → page image in the dep scan (a .atlas is text, not JSON)', async () => {
+ const { index } = await scanAssetDatabase(root, { write: false });
+ expect(index.deps[ATLAS]).toContain(PAGE_TEX);
+ });
+
+ it('embeds the atlas page texture (reachable through the atlas — not culled)', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ expect(res.ok).toBe(true);
+ expect(res.included).toEqual(expect.arrayContaining([SCENE, ATLAS, SKEL, PAGE_TEX]));
+ expect(res.unused).not.toEqual(expect.arrayContaining([PAGE_TEX]));
+ });
+});
diff --git a/pipeline/tests/steam-settings.test.ts b/pipeline/tests/steam-settings.test.ts
new file mode 100644
index 000000000..b1a37f40b
--- /dev/null
+++ b/pipeline/tests/steam-settings.test.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The Steam packaging settings, and the merge that keeps them.
+ *
+ * `steam` is the one nested object in packaging, and setPlatformPackaging merges
+ * exactly one level — so patching `{ steam: { appId } }` through it would drop
+ * the depot ids the project had. That is the whole reason these setters exist.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest, type SteamPackaging } from '../src/project/format';
+
+/** The merge, as the store performs it, over a plain object. */
+function mergeSteam(prev: SteamPackaging | undefined, patch: Partial<SteamPackaging>): SteamPackaging | undefined {
+ const steam = { ...prev, ...patch };
+ for (const key of Object.keys(steam) as (keyof SteamPackaging)[]) {
+ if (steam[key] === undefined) delete steam[key];
+ }
+ return Object.keys(steam).length > 0 ? steam : undefined;
+}
+
+function setDepot(prev: SteamPackaging | undefined, os: 'macos' | 'windows', id: number | undefined) {
+ const depots = { ...prev?.depots };
+ if (id === undefined) delete depots[os]; else depots[os] = id;
+ return mergeSteam(prev, { depots: Object.keys(depots).length > 0 ? depots : undefined });
+}
+
+describe('the Steam packaging settings', () => {
+ it('setting the App ID keeps depot ids the project already had', () => {
+ const prev: SteamPackaging = { appId: 480, depots: { macos: 90210 } };
+ expect(mergeSteam(prev, { appId: 500 })).toEqual({ appId: 500, depots: { macos: 90210 } });
+ });
+
+ it('setting one depot keeps the others and the App ID', () => {
+ const prev: SteamPackaging = { appId: 480, depots: { macos: 1 } };
+ expect(setDepot(prev, 'windows', 2)).toEqual({ appId: 480, depots: { macos: 1, windows: 2 } });
+ });
+
+ it('clearing the last value leaves nothing rather than an empty husk', () => {
+ expect(mergeSteam({ appId: 480 }, { appId: undefined })).toBeUndefined();
+ expect(setDepot({ depots: { macos: 1 } }, 'macos', undefined)).toBeUndefined();
+ });
+
+ it('keeps the SDK path across an App ID change, and drops a blank one', () => {
+ // The SDK is where the redistributable comes from; losing it on an
+ // unrelated edit turns achievements off with nothing said.
+ const prev: SteamPackaging = { appId: 480, sdkPath: '/opt/steamworks_sdk' };
+ expect(mergeSteam(prev, { appId: 500 })?.sdkPath).toBe('/opt/steamworks_sdk');
+ expect(mergeSteam(prev, { sdkPath: undefined })).toEqual({ appId: 480 });
+ });
+
+ it('a zero App ID is absence, not a game id', () => {
+ // The settings row maps 0 to undefined; a build with appId 0 would write
+ // scripts naming an app that is not anyone's.
+ expect(mergeSteam(undefined, { appId: undefined })).toBeUndefined();
+ });
+});
+
+describe('the declared achievement ids', () => {
+ const parsed = (achievements: unknown) =>
+ parseManifest({ name: 'p', packaging: { achievements } }).packaging?.achievements;
+
+ it('are trimmed and deduplicated, because a store keys on the exact string', () => {
+ // Two rows differing only in whitespace are one achievement and one that
+ // never fires — and the settings table cannot tell them apart on screen.
+ expect(parsed(['FIRST_BLOOD', ' FIRST_BLOOD ', 'ALL_LEVELS'])).toEqual(['FIRST_BLOOD', 'ALL_LEVELS']);
+ });
+
+ it('are absent rather than empty when a project declares none', () => {
+ // Absence means "check nothing", which is what an older project gets; an
+ // empty list would have to mean the same thing in a second way.
+ expect(parsed([])).toBeUndefined();
+ expect(parsed([' '])).toBeUndefined();
+ expect(parsed(undefined)).toBeUndefined();
+ });
+});
diff --git a/pipeline/tests/target-support.test.ts b/pipeline/tests/target-support.test.ts
new file mode 100644
index 000000000..5e7275964
--- /dev/null
+++ b/pipeline/tests/target-support.test.ts
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a build target cannot render, and the export saying so.
+ *
+ * The native app compiles a subset of the engine, so a project can author
+ * content that will not appear on the device. Two things are asserted: that the
+ * scan sees the authored vocabulary (scenes, prefabs, nested entities), and that
+ * the declared native gaps still match `native/CMakeLists.txt` — the build file
+ * is the truth about which sources are compiled, and flipping a flag there is
+ * what deletes an entry from the table.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, copyFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import {
+ collectSubsystems, subsystemGapWarnings, targetGaps, SUBSYSTEM_CMAKE_FLAG, type Subsystem,
+} from '../src/project/targetSupport';
+import { exportGame } from '../src/export/exportGame';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO = path.resolve(HERE, '..', '..');
+const GAME_HOST = path.join(HERE, '..', '..', 'pipeline', 'src', 'runtime', 'gameHost.ts');
+
+describe('collectSubsystems', () => {
+ it('sees components wherever they sit in the document', () => {
+ const scene = {
+ version: '1.0',
+ entities: [
+ { id: 0, components: [{ type: 'Transform' }, { type: 'Sprite' }] },
+ { id: 1, components: [{ type: 'TilemapLayer', data: { tileset: '@uuid:x' } }] },
+ { id: 2, children: [{ id: 3, components: [{ type: 'Text', data: { text: 'hi' } }] }] },
+ ],
+ };
+ expect([...collectSubsystems(scene)].sort()).toEqual(['text', 'tilemap']);
+ });
+
+ it('sees a prefab body and its physics vocabulary', () => {
+ const prefab = { version: '1.0', root: { components: [{ type: 'RigidBody' }, { type: 'BoxCollider' }] } };
+ expect([...collectSubsystems(prefab)]).toEqual(['physics']);
+ });
+
+ it('says nothing about a project that only uses what every target has', () => {
+ const scene = { entities: [{ components: [{ type: 'Sprite' }, { type: 'Light2D' }, { type: 'TrailRenderer' }] }] };
+ expect(collectSubsystems(scene).size).toBe(0);
+ });
+
+ it('ignores non-component `type` fields', () => {
+ expect(collectSubsystems({ importer: { type: 'texture' }, asset: { type: 'scene' } }).size).toBe(0);
+ });
+});
+
+describe('subsystemGapWarnings', () => {
+ const usage = new Map<Subsystem, string[]>([['spine', ['scenes/b.esscene', 'scenes/a.esscene']]]);
+
+ it('names the subsystem, the reason and the files', () => {
+ // Driven through a declared gap rather than a real one: every subsystem is
+ // supported on every target today, and the reporting still has to work for the
+ // day one is not (a flag turned off, a new platform-bound feature).
+ const declared = [{ subsystem: 'spine' as Subsystem, why: 'a made-up gap, for this test' }];
+ const [warning, ...rest] = subsystemGapWarnings('android', usage, declared);
+ expect(rest).toEqual([]);
+ expect(warning).toContain('Spine animation will not render');
+ expect(warning).toContain('a made-up gap, for this test');
+ expect(warning).toContain('scenes/a.esscene, scenes/b.esscene');
+ });
+
+ it('is silent about a gap the content does not use', () => {
+ const declared = [{ subsystem: 'spine' as Subsystem, why: 'a made-up gap' }];
+ expect(subsystemGapWarnings('android', new Map(), declared)).toEqual([]);
+ });
+
+ it('says nothing at all now that every target compiles every subsystem', () => {
+ expect(subsystemGapWarnings('android', usage)).toEqual([]);
+ expect(subsystemGapWarnings('web', usage)).toEqual([]);
+ });
+
+ it('reports the same gaps for both native targets — they compile one CMakeLists', () => {
+ expect(targetGaps('ios')).toEqual(targetGaps('android'));
+ });
+});
+
+describe('the native gaps match the native build', () => {
+ const cmake = readFileSync(path.join(REPO, 'native', 'CMakeLists.txt'), 'utf8');
+ const enabled = new Set([...cmake.matchAll(/set\(\s*(ES_ENABLE_\w+)\s+ON\s*\)/g)].map((m) => m[1]));
+ const gaps = new Set(targetGaps('android').map((g) => g.subsystem));
+
+ it.each(Object.entries(SUBSYSTEM_CMAKE_FLAG) as [Subsystem, string][])(
+ '%s: a source set the native build omits is declared unsupported', (subsystem, flag) => {
+ if (!enabled.has(flag)) expect(gaps).toContain(subsystem);
+ },
+ );
+
+ it.each(Object.keys(SUBSYSTEM_CMAKE_FLAG) as Subsystem[])(
+ '%s: a source set the native build compiles is not declared unsupported', (subsystem) => {
+ if (enabled.has(SUBSYSTEM_CMAKE_FLAG[subsystem]!)) expect(gaps).not.toContain(subsystem);
+ },
+ );
+});
+
+describe('exportGame warns about content the target cannot render', () => {
+ let root: 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-target-support-'));
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
+ copyFileSync(path.join(REPO, 'examples', 'hello-world', 'assets', 'textures', 'logo.png'), path.join(root, 'assets', 'hero.png'));
+ 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}` } }] },
+ { id: 1, components: [{ type: 'Text', data: { text: 'score' } }] },
+ { id: 2, components: [{ type: 'ParticleEmitter', data: {} }] },
+ { id: 3, components: [{ type: 'TilemapLayer', data: {} }] },
+ { id: 4, components: [{ type: 'RigidBody', data: {} }] },
+ { id: 5, components: [{ type: 'SpineAnimation', data: {} }] },
+ ],
+ }));
+ writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ mkdirSync(path.join(root, '_sdk'), { recursive: true });
+ writeFileSync(path.join(root, '_sdk', 'index.js'), 'export const x = 1;');
+ mkdirSync(path.join(root, '_wasm'), { recursive: true });
+ writeFileSync(path.join(root, '_wasm', 'esengine.js'), 'export default () => {};');
+ });
+
+ afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+ const run = (platform: 'android' | 'web', outDir: string) => exportGame({
+ root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST,
+ sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
+ outDir, platform, title: 'Game',
+ });
+
+ it('warns about nothing: the native build renders everything this scene uses', async () => {
+ // The scene deliberately authors every optional subsystem — text, particles,
+ // tilemaps, physics and spine — and the native app compiles all of them now, so
+ // any warning here would be false. The reporting mechanism itself is covered
+ // above, against a declared gap.
+ const res = await run('android', path.join(root, 'dist-android'));
+ expect(res.errors).toEqual([]);
+ expect(res.ok).toBe(true);
+ const gaps = res.warnings.filter((w) => w.startsWith('android:'));
+ expect(gaps).toEqual([]);
+ }, 60_000);
+
+ it('stays quiet for a target that renders all of it', async () => {
+ const res = await run('web', path.join(root, 'dist-web'));
+ expect(res.warnings.filter((w) => w.includes('will not render'))).toEqual([]);
+ }, 60_000);
+});
diff --git a/pipeline/tests/tilemap-cook-deps.test.ts b/pipeline/tests/tilemap-cook-deps.test.ts
new file mode 100644
index 000000000..b36c72371
--- /dev/null
+++ b/pipeline/tests/tilemap-cook-deps.test.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Regression: a Tiled map's tileset images are dependencies. The dep scan must
+ * follow tilemap → tileset image (collapsing the Tiled-relative `../`), and the
+ * cook must rewrite that image ref to a logical project path — otherwise the
+ * single-file playable never embeds the tileset and 404s it as an external file.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { cookAssets } from '../src/assets/cookAssets';
+
+let root: string;
+
+const TILES_TEX = '11111111-1111-4111-8111-111111111111';
+const PROPS_TEX = '22222222-2222-4222-8222-222222222222';
+const TILEMAP = '33333333-3333-4333-8333-333333333333';
+const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+function writeAsset(rel: string, type: string, uuid: string, body = ''): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+// A .tmj at assets/maps/ whose tilesets reference images in ../textures/ (the Tiled
+// convention: relative to the map file, so it climbs out of maps/ into textures/).
+const tmj = JSON.stringify({
+ type: 'map', version: '1.10', orientation: 'orthogonal', renderorder: 'right-down',
+ width: 2, height: 2, tilewidth: 16, tileheight: 16, infinite: false,
+ nextlayerid: 2, nextobjectid: 1,
+ tilesets: [
+ { firstgid: 1, name: 'tiles', image: '../textures/tiles.png', imagewidth: 32, imageheight: 32, tilewidth: 16, tileheight: 16, columns: 2, tilecount: 4, margin: 0, spacing: 0 },
+ { firstgid: 5, name: 'props', image: '../textures/props.png', imagewidth: 16, imageheight: 16, tilewidth: 16, tileheight: 16, columns: 1, tilecount: 1, margin: 0, spacing: 0 },
+ ],
+ layers: [{ type: 'tilelayer', name: 'L', width: 2, height: 2, x: 0, y: 0, opacity: 1, visible: true, data: [1, 2, 5, 4] }],
+});
+
+const scene = JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [{ id: 1, name: 'T', parent: null, children: [], components: [{ type: 'Tilemap', data: { source: `@uuid:${TILEMAP}` } }] }],
+});
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-tmcook-'));
+ writeAsset('assets/textures/tiles.png', 'texture', TILES_TEX, 'TILES');
+ writeAsset('assets/textures/props.png', 'texture', PROPS_TEX, 'PROPS');
+ writeAsset('assets/maps/level.tmj', 'tilemap', TILEMAP, tmj);
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, scene);
+});
+
+afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+describe('tilemap tileset images are cooked dependencies', () => {
+ it('embeds a tilemap\'s tileset images (dep scan follows the ../ relative image)', async () => {
+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ expect(res.ok).toBe(true);
+ // Both tileset images are reachable through the tilemap — not culled.
+ expect(res.included).toEqual(expect.arrayContaining([SCENE, TILEMAP, TILES_TEX, PROPS_TEX]));
+ expect(res.unused).not.toEqual(expect.arrayContaining([TILES_TEX, PROPS_TEX]));
+ });
+
+ it('rewrites the cooked .tmj tileset image refs to logical project paths', async () => {
+ await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ const cooked = JSON.parse(readFileSync(path.join(root, 'build', 'assets/maps/level.tmj'), 'utf8'));
+ // "../textures/tiles.png" (map-relative) → "assets/textures/tiles.png" (project-relative),
+ // so the @uuid-loaded map resolves it to the embedded asset in the single-file playable.
+ expect(cooked.tilesets[0].image).toBe('assets/textures/tiles.png');
+ expect(cooked.tilesets[1].image).toBe('assets/textures/props.png');
+ });
+});
diff --git a/pipeline/tests/video-cook.test.ts b/pipeline/tests/video-cook.test.ts
new file mode 100644
index 000000000..bb2b9cac8
--- /dev/null
+++ b/pipeline/tests/video-cook.test.ts
@@ -0,0 +1,177 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Cook-time video: mp4 → `.esv` (MPEG-1 PS for the wasm decoder) + `.m4a`
+ * audio-track sibling, through the real bundled ffmpeg. Sources are generated
+ * at test time with the same binary (lavfi), so no binary fixtures ship.
+ * When the videodec wasm is built locally, the cooked `.esv` is decoded
+ * end-to-end and its frames asserted.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { existsSync, readFileSync } from 'node:fs';
+import { mkdtemp } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { resolveFfmpeg, transcodeVideoForWasm, videoImportSettings } from '../src/assets/videoCook';
+import { cookAssets } from '../src/assets/cookAssets';
+
+const execFileAsync = promisify(execFile);
+
+const WASM_DIR = path.resolve(__dirname, '../../build/wasm/web');
+const HAS_VIDEODEC = existsSync(path.join(WASM_DIR, 'videodec.wasm'));
+
+const ffmpeg = await resolveFfmpeg();
+let tmp = '';
+
+beforeAll(async () => {
+ tmp = await mkdtemp(path.join(tmpdir(), 'estella-videocook-test-'));
+});
+
+/** Generate a source clip: solid lime video, optional 440Hz tone, ODD width. */
+async function makeSource(name: string, withAudio: boolean): Promise<string> {
+ const out = path.join(tmp, name);
+ const args = ['-y', '-f', 'lavfi', '-i', 'color=c=lime:s=63x32:r=25:d=1'];
+ if (withAudio) args.push('-f', 'lavfi', '-i', 'sine=frequency=440:duration=1', '-c:a', 'aac', '-shortest');
+ args.push('-c:v', 'libx264', '-pix_fmt', 'yuv420p', out);
+ await execFileAsync(ffmpeg!, args);
+ return out;
+}
+
+describe('videoImportSettings', () => {
+ it('defaults and clamps', () => {
+ expect(videoImportSettings(undefined)).toEqual({ quality: 4, audioBitrateKbps: 128 });
+ expect(videoImportSettings({ quality: 8, audioBitrateKbps: 192 })).toEqual({ quality: 8, audioBitrateKbps: 192 });
+ expect(videoImportSettings({ quality: 99, audioBitrateKbps: 7 })).toEqual({ quality: 4, audioBitrateKbps: 128 });
+ });
+});
+
+describe.skipIf(!ffmpeg)('transcodeVideoForWasm', () => {
+ it('produces an MPEG-PS .esv and an .m4a audio track', async () => {
+ const src = await makeSource('with-audio.mp4', true);
+ const res = await transcodeVideoForWasm(src, videoImportSettings(undefined));
+ expect(res.warnings).toEqual([]);
+ expect(res.esv).not.toBeNull();
+ // MPEG-PS pack header: 00 00 01 BA.
+ expect(Array.from(res.esv!.subarray(0, 4))).toEqual([0, 0, 1, 0xba]);
+ expect(res.audio).not.toBeNull();
+ // MP4/M4A container: 'ftyp' at offset 4.
+ expect(Buffer.from(res.audio!.subarray(4, 8)).toString('ascii')).toBe('ftyp');
+ });
+
+ it('a silent source yields esv with no audio sibling and no warnings', async () => {
+ const src = await makeSource('silent.mp4', false);
+ const res = await transcodeVideoForWasm(src, videoImportSettings(undefined));
+ expect(res.warnings).toEqual([]);
+ expect(res.esv).not.toBeNull();
+ expect(res.audio).toBeNull();
+ });
+
+ it('reports failure for an undecodable source', async () => {
+ const bogus = path.join(tmp, 'bogus.mp4');
+ const fs = await import('node:fs/promises');
+ await fs.writeFile(bogus, Buffer.alloc(256, 0x42));
+ const res = await transcodeVideoForWasm(bogus, videoImportSettings(undefined));
+ expect(res.esv).toBeNull();
+ expect(res.warnings.length).toBeGreaterThan(0);
+ });
+
+ it.skipIf(!HAS_VIDEODEC)('cooked .esv decodes in the real videodec module with evened dimensions', async () => {
+ const src = await makeSource('roundtrip.mp4', false);
+ const res = await transcodeVideoForWasm(src, videoImportSettings(undefined));
+ expect(res.esv).not.toBeNull();
+
+ const factory = (await import(path.join(WASM_DIR, 'videodec.js'))).default;
+ const mod = await factory({ wasmBinary: readFileSync(path.join(WASM_DIR, 'videodec.wasm')) });
+ const ptr = mod._malloc(res.esv!.length);
+ mod.HEAPU8.set(res.esv!, ptr);
+ const h = mod._es_video_open(ptr, res.esv!.length);
+ expect(h).toBeGreaterThan(0);
+ // The odd 63px source width is evened for MPEG-1 macroblocks.
+ expect(mod._es_video_width(h)).toBe(62);
+ expect(mod._es_video_height(h)).toBe(32);
+
+ expect(mod._es_video_advance(h, 0.05)).toBe(1);
+ const out = mod._malloc(62 * 32 * 4);
+ expect(mod._es_video_frame_rgba(h, out, 62 * 32 * 4)).toBe(1);
+ const px = out + ((16 * 62) + 31) * 4;
+ const [r, g, b, a] = Array.from(mod.HEAPU8.subarray(px, px + 4)) as number[];
+ expect(g).toBeGreaterThan(200);
+ expect(r).toBeLessThan(60);
+ expect(b).toBeLessThan(60);
+ expect(a).toBe(255);
+ mod._free(out);
+ mod._es_video_close(h);
+ });
+});
+
+describe.skipIf(!ffmpeg)('cookAssets video wiring', () => {
+ const VIDEO_UUID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+ const SCENE_UUID = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';
+
+ async function makeProject(): Promise<string> {
+ const fs = await import('node:fs');
+ const root = await mkdtemp(path.join(tmpdir(), 'estella-videowire-'));
+ const write = (rel: string, body: string | Uint8Array, meta: object) => {
+ const abs = path.join(root, rel);
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
+ fs.writeFileSync(abs, body);
+ fs.writeFileSync(`${abs}.meta`, JSON.stringify({ version: '2.0', importer: {}, ...meta }));
+ };
+ const clip = readFileSync(await makeSource('wire-src.mp4', true));
+ write('assets/videos/clip.mp4', clip, { uuid: VIDEO_UUID, type: 'video' });
+ write('assets/scenes/main.esscene', JSON.stringify({
+ version: '1.0', name: 'v',
+ entities: [{ id: 1, name: 'V', parent: null, children: [], components: [
+ { type: 'Sprite', data: { texture: 0 } },
+ { type: 'Video', data: { source: `@uuid:${VIDEO_UUID}` } },
+ ] }],
+ }), { uuid: SCENE_UUID, type: 'scene' });
+ return root;
+ }
+
+ it('transcodeVideo stages .esv plus the .m4a sibling, both in the manifest', async () => {
+ const root = await makeProject();
+ const res = await cookAssets(root, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build', transcodeVideo: true,
+ });
+ expect(res.warnings).toEqual([]);
+ const manifest = JSON.parse(readFileSync(path.join(root, 'build/assets.manifest.json'), 'utf8'));
+ const video = manifest.entries.find((e: { uuid: string }) => e.uuid === VIDEO_UUID);
+ expect(video.path).toBe('assets/videos/clip.esv');
+ expect(video.sourcePath).toBe('assets/videos/clip.mp4');
+ const audio = manifest.entries.find((e: { uuid: string }) => e.uuid === `${VIDEO_UUID}-audio`);
+ expect(audio.path).toBe('assets/videos/clip.esv.m4a');
+ expect(audio.type).toBe('audio');
+ expect(existsSync(path.join(root, 'build/assets/videos/clip.esv'))).toBe(true);
+ expect(existsSync(path.join(root, 'build/assets/videos/clip.esv.m4a'))).toBe(true);
+ });
+
+ it('without transcodeVideo the mp4 passes through untouched', async () => {
+ const root = await makeProject();
+ await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });
+ const manifest = JSON.parse(readFileSync(path.join(root, 'build/assets.manifest.json'), 'utf8'));
+ const video = manifest.entries.find((e: { uuid: string }) => e.uuid === VIDEO_UUID);
+ expect(video.path).toBe('assets/videos/clip.mp4');
+ expect(manifest.entries.find((e: { uuid: string }) => e.uuid === `${VIDEO_UUID}-audio`)).toBeUndefined();
+ });
+
+ it('content-addressed staging names the audio sibling by ITS OWN hash', async () => {
+ const root = await makeProject();
+ await cookAssets(root, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build',
+ transcodeVideo: true, contentAddressed: true,
+ });
+ const manifest = JSON.parse(readFileSync(path.join(root, 'build/assets.manifest.json'), 'utf8'));
+ const video = manifest.entries.find((e: { uuid: string }) => e.uuid === VIDEO_UUID);
+ const audio = manifest.entries.find((e: { uuid: string }) => e.uuid === `${VIDEO_UUID}-audio`);
+ expect(video.path).toMatch(/^assets\/[0-9a-f]{16}\.esv$/);
+ expect(audio.path).toMatch(/^assets\/[0-9a-f]{16}\.m4a$/);
+ // Named by the AUDIO bytes, not the video's — different soundtracks over
+ // identical footage must not dedup to one file.
+ expect(audio.path).toBe(`assets/${audio.contentHash}.m4a`);
+ expect(audio.contentHash).not.toBe(video.contentHash);
+ expect(existsSync(path.join(root, 'build', audio.path))).toBe(true);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cff447417..f119cc895 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -30,6 +30,9 @@ importers:
madge:
specifier: ^8.0.0
version: 8.0.0([email protected])
+ vitest:
+ specifier: ^2.1.9
desktop:
dependencies:
diff --git a/tools/gates.mjs b/tools/gates.mjs
index fbd0a1003..d3f8adf1f 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -62,6 +62,9 @@ export const GATES = [
// could survive fails here rather than in someone else's project.
{ id: 'tsc-plugins', run: 'pnpm -r --filter "./plugins/*" exec tsc --noEmit' },
{ id: 'plugin-tests', run: 'pnpm -r --filter "./plugins/*" test' },
+ // The engine's own TS suites (pipeline + tooling). They lived in desktop/tests
+ // until the editor split, where a checkout without the editor ran none of them.
+ { id: 'engine-tests', run: 'pnpm run test' },
// The plugins we ship prove the public API only if they are held to it.
{ id: 'plugin-boundary', run: 'node tools/check-plugin-boundary.mjs' },
// Same shape of rule, other direction: what builds a project may not need the
diff --git a/tools/releaseGate.mjs b/tools/releaseGate.mjs
index abd310444..16992e1c1 100644
--- a/tools/releaseGate.mjs
+++ b/tools/releaseGate.mjs
@@ -86,7 +86,7 @@ export const CRITERIA = [
answeredBy: 'pnpm --filter @estella/editor run verify:render:hotupdate',
needs: [
'desktop/scripts/headless-hotupdate-verify.mjs',
- 'desktop/tests/hotupdate-verify-fixture.test.ts',
+ 'pipeline/tests/hotupdate-verify-fixture.test.ts',
],
},
{
diff --git a/tools/tests/api-baseline.test.ts b/tools/tests/api-baseline.test.ts
new file mode 100644
index 000000000..3834bd6e5
--- /dev/null
+++ b/tools/tests/api-baseline.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file api-baseline.test.ts — the rule that decides a broken API promise.
+ *
+ * It only fires the release AFTER a symbol is frozen, so without these it would
+ * first be exercised on the day it had to be right.
+ */
+import { describe, it, expect } from 'vitest';
+// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
+import { parseSnapshot, baselineFindings, isAdditiveMembers, UNCLAIMED } from '../lib/apiSnapshot.mjs';
+
+type Entry = { kind: string; tier: string; deprecated: boolean; body: string };
+
+function snapshot(...sections: string[]): Map<string, Entry> {
+ return parseSnapshot(`# API surface — esengine/test\n\n${sections.join('\n\n')}\n`);
+}
+
+const sig = (heading: string, body: string) => `## ${heading}\n\`\`\`\n${body}\n\`\`\``;
+
+describe('parseSnapshot', () => {
+ it('reads the tier and the deprecation as separate axes', () => {
+ const s = snapshot(
+ sig('defineComponent — function @public', '(name: string): ComponentDef'),
+ sig('oldThing — function @public @deprecated', '(): void'),
+ sig('graph — const @beta', 'MaterialGraph'),
+ );
+ expect(s.get('defineComponent')).toMatchObject({ tier: 'public', deprecated: false });
+ expect(s.get('oldThing')).toMatchObject({ tier: 'public', deprecated: true });
+ expect(s.get('graph')).toMatchObject({ tier: 'beta', deprecated: false });
+ });
+
+ it('reads a snapshot written before the tiers existed as claiming nothing', () => {
+ const s = snapshot(sig('Query — class', 'call ()'));
+ expect(s.get('Query')?.tier).toBe(UNCLAIMED);
+ });
+});
+
+describe('baselineFindings', () => {
+ const frozen = snapshot(sig('Commands — class @public', 'spawn(): Entity'));
+
+ it('passes when the frozen signature is untouched', () => {
+ const now = snapshot(sig('Commands — class @public', 'spawn(): Entity'));
+ expect(baselineFindings(frozen, now).failures).toEqual([]);
+ });
+
+ it('fails a removal that never went through @deprecated', () => {
+ const now = snapshot(sig('Other — class @public', 'x(): void'));
+ expect(baselineFindings(frozen, now).failures).toEqual([
+ expect.stringContaining('Commands — removed while @public and never @deprecated'),
+ ]);
+ });
+
+ it('allows a removal that was deprecated in the release before it', () => {
+ const was = snapshot(sig('Commands — class @public @deprecated', 'spawn(): Entity'));
+ expect(baselineFindings(was, snapshot()).failures).toEqual([]);
+ });
+
+ it('fails a changed signature', () => {
+ const now = snapshot(sig('Commands — class @public', 'spawn(name: string): Entity'));
+ expect(baselineFindings(frozen, now).failures).toEqual([
+ expect.stringContaining('@public signature changed'),
+ ]);
+ });
+
+ it('fails a kind change', () => {
+ const now = snapshot(sig('Commands — interface @public', 'spawn(): Entity'));
+ expect(baselineFindings(frozen, now).failures).toEqual([
+ expect.stringContaining('class became a interface'),
+ ]);
+ });
+
+ it('fails a thaw back to a weaker tier', () => {
+ const now = snapshot(sig('Commands — class @public', 'spawn(): Entity')
+ .replace('@public', '@beta'));
+ expect(baselineFindings(frozen, now).failures).toEqual([
+ expect.stringContaining('a freeze does not thaw'),
+ ]);
+ });
+
+ it('notes but does not fail a @beta change', () => {
+ const was = snapshot(sig('graph — const @beta', 'MaterialGraph'));
+ const { failures, notes } = baselineFindings(was, snapshot());
+ expect(failures).toEqual([]);
+ expect(notes).toEqual([expect.stringContaining('@beta removed')]);
+ });
+
+ it('claims nothing about a symbol no release tiered', () => {
+ const was = snapshot(sig('legacy — function', '(): void'));
+ const { failures, notes } = baselineFindings(was, snapshot());
+ expect(failures).toEqual([]);
+ expect(notes).toEqual([]);
+ });
+
+ it('lets an @internal member change, because none was promised', () => {
+ const was = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: string'));
+ const now = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: number'));
+ expect(baselineFindings(was, now).failures).toEqual([]);
+ });
+
+ it('still fails when a promised member beside an @internal one changes', () => {
+ const was = snapshot(sig('Handle — class @public', 'get(): number\n@internal _raw: string'));
+ const now = snapshot(sig('Handle — class @public', 'get(): string\n@internal _raw: string'));
+ expect(baselineFindings(was, now).failures).toEqual([
+ expect.stringContaining('@public signature changed'),
+ ]);
+ });
+});
+
+describe('an interface that gains an optional member', () => {
+ const was = snapshot(sig('Options — interface @public', 'name: string | undefined'));
+
+ it('is not a broken promise: nothing that compiled stops compiling', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: string | undefined\ntouches: Touches | undefined'));
+ const { failures, notes } = baselineFindings(was, now);
+ expect(failures).toEqual([]);
+ expect(notes.join()).toMatch(/optional member/);
+ });
+
+ it('still fails when the added member is required', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: string | undefined\ntouches: Touches'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('still fails when an existing member changed', () => {
+ const now = snapshot(sig('Options — interface @public',
+ 'name: number | undefined\ntouches: Touches | undefined'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('still fails when a member was dropped', () => {
+ const now = snapshot(sig('Options — interface @public', 'touches: Touches | undefined'));
+ expect(baselineFindings(was, now).failures).toHaveLength(1);
+ });
+
+ it('is not additive when nothing was added', () => {
+ expect(isAdditiveMembers('a: string | undefined', 'a: string | undefined')).toBe(false);
+ });
+});
diff --git a/tools/tests/dead-gpu.test.ts b/tools/tests/dead-gpu.test.ts
new file mode 100644
index 000000000..2b453029c
--- /dev/null
+++ b/tools/tests/dead-gpu.test.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file dead-gpu.test.ts — when a measurement counts and when it is retaken.
+ *
+ * The property that matters is the one a retry policy can destroy: a game that
+ * genuinely draws nothing must still fail, on the first attempt, with no retry to
+ * hide it. Everything else here is about not reporting a runner's dead GPU as a
+ * verdict on the game.
+ */
+import { describe, it, expect } from 'vitest';
+// @ts-expect-error — a .mjs tool module, typed by its own JSDoc
+import { retryOnDeadGpu, gpuNeverCameUp, deadGpuVerdict } from '../lib/deadGpu.mjs';
+
+const DEAD = 'Exiting GPU process due to errors during initialization';
+const BLANK = 'painted=true live=false errors=0';
+
+/** Drive the policy over a scripted sequence of attempt outputs; `null` = success. */
+function run(outputs: Array<string | null>) {
+ let attempts = 0;
+ const notes: boolean[] = [];
+ const result = retryOnDeadGpu(
+ () => {
+ const out = outputs[Math.min(attempts++, outputs.length - 1)];
+ return { ok: out === null, output: out ?? '' };
+ },
+ (died: boolean) => notes.push(died),
+ 0, // no backoff: there is no GPU process to wait for here
+ );
+ return { ...result, attempts, notes };
+}
+
+/** The same, for runs that report whether they reached a verdict. */
+type Attempt = { ok: boolean; output?: string; measured?: boolean; drew?: boolean };
+function runReporting(attempts_: Attempt[]) {
+ let attempts = 0;
+ const notes: boolean[] = [];
+ const result = retryOnDeadGpu(
+ () => ({ output: '', ...attempts_[Math.min(attempts++, attempts_.length - 1)] }),
+ (noVerdict: boolean) => notes.push(noVerdict),
+ 0,
+ );
+ return { ...result, attempts, notes };
+}
+
+describe('gpuNeverCameUp', () => {
+ it('recognises the three ways a runner says it has no GPU', () => {
+ expect(gpuNeverCameUp(DEAD)).toBe(true);
+ expect(gpuNeverCameUp('GPU device lost\nFailed to create framebuffer')).toBe(true);
+ expect(gpuNeverCameUp('WebGL2 is not available')).toBe(true);
+ });
+
+ it('does not read a verdict about pixels as one about the GPU', () => {
+ expect(gpuNeverCameUp(BLANK)).toBe(false);
+ // Device loss alone is a scene some gates drive on purpose; only paired
+ // with a framebuffer that could not be made is it a runner with no GPU.
+ expect(gpuNeverCameUp('GPU device lost')).toBe(false);
+ });
+});
+
+describe('retryOnDeadGpu', () => {
+ it('a game that draws nothing fails on the first attempt', () => {
+ // The whole point: no retry may stand between a black frame and a red gate.
+ const r = run([BLANK]);
+ expect(r.ok).toBe(false);
+ expect(r.attempts).toBe(1);
+ expect(r.notes).toEqual([]);
+ });
+
+ it('takes one measurement when the GPU is up', () => {
+ const r = run([null]);
+ expect(r.ok).toBe(true);
+ expect(r.attempts).toBe(1);
+ expect(r.retried).toBe(false);
+ });
+
+ it('measures again when the GPU died before it drew', () => {
+ const r = run([DEAD, null]);
+ expect(r.ok).toBe(true);
+ expect(r.attempts).toBe(2);
+ expect(r.notes).toEqual([true]);
+ });
+
+ it('measures again for a blank frame that FOLLOWS a death in the chain', () => {
+ // The case that made this necessary: a GPU process that dies and restarts
+ // leaves the next launch on a context-lost renderer, which paints a blank
+ // frame and prints nothing about why.
+ const r = run([DEAD, BLANK, null]);
+ expect(r.ok).toBe(true);
+ expect(r.attempts).toBe(3);
+ expect(r.notes).toEqual([true, false]);
+ });
+
+ it('reads a lost device that then fails to make TEXTURES', () => {
+ // Verbatim from the runner, the day the second clause was found to only
+ // know about framebuffers.
+ const real = [
+ '[ERROR] GPU device lost: context-lost [backend=WebGL2, vendor=Google Inc.]',
+ '[ERROR] Texture::initialize: createTexture failed for 70x70',
+ '[ERROR] Failed to create texture from spec',
+ ].join('\n');
+ expect(gpuNeverCameUp(real)).toBe(true);
+ });
+
+ it('words the give-up once, for both runners', () => {
+ // The two of them each had their own sentence for it, and one of them
+ // blamed the game — the failure this file exists to keep apart.
+ expect(deadGpuVerdict('the game')).toContain('says nothing about the game');
+ expect(deadGpuVerdict('the scene')).toContain('never came up');
+ });
+
+ // The runner this policy runs on prints the dead-GPU line on runs that then
+ // succeed, so text alone made every failure look like an outage: one job
+ // spent 71 retries and never named the scene that broke.
+ it('a run that reached a verdict is not retried, whatever the log says', () => {
+ const r = runReporting([{ ok: false, output: DEAD, measured: true, drew: true }]);
+ expect(r.ok).toBe(false);
+ expect(r.attempts).toBe(1);
+ expect(r.notes).toEqual([]);
+ });
+
+ it('retries a run that reached no verdict, whatever the log says', () => {
+ // Nothing in this output mentions a GPU; the run simply never got far
+ // enough to judge anything, which is not a verdict about the subject.
+ const r = runReporting([
+ { ok: false, output: 'launch timed out', measured: false },
+ { ok: true },
+ ]);
+ expect(r.ok).toBe(true);
+ expect(r.attempts).toBe(2);
+ expect(r.notes).toEqual([true]);
+ });
+
+ it('still retries a blank frame that follows a run with no verdict', () => {
+ const r = runReporting([
+ { ok: false, measured: false },
+ { ok: false, measured: true, drew: false },
+ { ok: true },
+ ]);
+ expect(r.ok).toBe(true);
+ expect(r.attempts).toBe(3);
+ expect(r.notes).toEqual([true, false]);
+ });
+
+ it('stops retrying once a run draws, even after an outage', () => {
+ // A drawn frame that fails its assertion is the subject's own failure;
+ // the outage is over and further attempts only hide it.
+ const r = runReporting([
+ { ok: false, measured: false },
+ { ok: false, measured: true, drew: true },
+ ]);
+ expect(r.ok).toBe(false);
+ expect(r.attempts).toBe(2);
+ expect(r.gpuDied).toBeUndefined();
+ });
+
+ it('gives up at the cap and says the GPU is why', () => {
+ const r = run([DEAD]);
+ expect(r.ok).toBe(false);
+ expect(r.attempts).toBe(6);
+ expect(r.gpuDied).toBe(true);
+ });
+});
diff --git a/tools/tests/frame-compare.test.ts b/tools/tests/frame-compare.test.ts
new file mode 100644
index 000000000..4c30160d5
--- /dev/null
+++ b/tools/tests/frame-compare.test.ts
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The score behind "the package shows what the editor showed".
+ *
+ * It has to separate two runs of one game from two different games by a
+ * wide margin, or the tolerance is guesswork. Measured on real captures:
+ * the same game lands at 0.001–0.006 and two different games at
+ * 0.37–0.48, which is the gap these cases pin down synthetically.
+ */
+import { describe, it, expect } from 'vitest';
+import { deflateSync } from 'node:zlib';
+// @ts-expect-error — plain-JS tool module, no d.ts
+import { downsample, gridDistance, cellMaxDistance, frameDistance, frameCellMax, DEFAULT_INSET } from '../frameCompare.mjs';
+
+interface Img { w: number; h: number; px(x: number, y: number): [number, number, number] }
+
+/** An image from a function of position, duck-typed like the PNG reader's result. */
+const img = (w: number, h: number, f: (x: number, y: number) => [number, number, number]): Img =>
+ ({ w, h, px: (x, y) => f(x, y) });
+
+const solid = (w: number, h: number, c: [number, number, number]) => img(w, h, () => c);
+/** Left half one colour, right half another — a layout the score must notice moving. */
+const split = (w: number, h: number, a: [number, number, number], b: [number, number, number]) =>
+ img(w, h, (x) => (x < w / 2 ? a : b));
+
+describe('downsample', () => {
+ it('averages a region to its mean colour', () => {
+ const g = downsample(solid(40, 20, [10, 20, 30]), 4, 2);
+ expect([...g.slice(0, 3)]).toEqual([10, 20, 30]);
+ expect(g).toHaveLength(4 * 2 * 3);
+ });
+
+ it('keeps left and right distinguishable at a coarse grid', () => {
+ const g = downsample(split(40, 20, [0, 0, 0], [255, 255, 255]), 2, 1);
+ expect(g[0]).toBeLessThan(10); // left cell
+ expect(g[3]).toBeGreaterThan(245); // right cell
+ });
+
+ it('drops the inset border — the editor draws a play frame around its surface', () => {
+ // A green ring one tenth deep around a black field: with the ring included the
+ // mean is polluted; inset past it and the field reads as the field.
+ const ring = img(100, 100, (x, y) =>
+ (x < 10 || y < 10 || x >= 90 || y >= 90 ? [0, 255, 0] : [0, 0, 0]));
+ const withRing = downsample(ring, 1, 1, 0);
+ const inside = downsample(ring, 1, 1, 0.12);
+ expect(withRing[1]).toBeGreaterThan(50);
+ expect(inside[1]).toBe(0);
+ });
+});
+
+describe('gridDistance', () => {
+ it('is zero for a grid against itself', () => {
+ const g = downsample(split(20, 10, [12, 34, 56], [200, 100, 50]), 4, 4);
+ expect(gridDistance(g, g)).toBe(0);
+ });
+
+ it('is one for black against white', () => {
+ const a = downsample(solid(8, 8, [0, 0, 0]), 2, 2);
+ const b = downsample(solid(8, 8, [255, 255, 255]), 2, 2);
+ expect(gridDistance(a, b)).toBeCloseTo(1, 6);
+ });
+
+ it('separates a shifted layout from an identical one by an order of magnitude', () => {
+ const base = downsample(split(64, 32, [20, 40, 60], [220, 180, 140]), 16, 8);
+ const jitter = downsample(
+ img(64, 32, (x) => (x < 33 ? [20, 40, 60] : [220, 180, 140])), 16, 8,
+ ); // the seam moved one pixel — drift, not a different game
+ const other = downsample(split(64, 32, [220, 180, 140], [20, 40, 60]), 16, 8); // mirrored
+ expect(gridDistance(base, jitter)).toBeLessThan(0.02);
+ expect(gridDistance(base, other)).toBeGreaterThan(0.3);
+ });
+
+ it('refuses grids of different sizes rather than scoring nonsense', () => {
+ expect(() => gridDistance(new Float64Array(3), new Float64Array(6))).toThrow(/mismatch/);
+ });
+});
+
+/** A minimal 8-bit RGB PNG, so the size guard can be tested on real input rather
+ * than on a buffer that fails to decode for unrelated reasons. */
+function png(w: number, h: number, c: [number, number, number]): Buffer {
+ const crcTable = Array.from({ length: 256 }, (_, n) => {
+ let v = n;
+ for (let k = 0; k < 8; k++) v = v & 1 ? 0xedb88320 ^ (v >>> 1) : v >>> 1;
+ return v >>> 0;
+ });
+ const crc = (b: Buffer) => {
+ let v = 0xffffffff;
+ for (const byte of b) v = crcTable[(v ^ byte) & 0xff] ^ (v >>> 8);
+ return (v ^ 0xffffffff) >>> 0;
+ };
+ const chunk = (type: string, data: Buffer) => {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
+ const cr = Buffer.alloc(4);
+ cr.writeUInt32BE(crc(body));
+ return Buffer.concat([len, body, cr]);
+ };
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(w, 0);
+ ihdr.writeUInt32BE(h, 4);
+ ihdr[8] = 8; ihdr[9] = 2; // 8-bit, truecolour
+ const raw = Buffer.alloc(h * (w * 3 + 1));
+ for (let y = 0; y < h; y++) {
+ const row = y * (w * 3 + 1);
+ raw[row] = 0; // no filter
+ for (let x = 0; x < w; x++) {
+ raw[row + 1 + x * 3] = c[0];
+ raw[row + 2 + x * 3] = c[1];
+ raw[row + 3 + x * 3] = c[2];
+ }
+ }
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0)),
+ ]);
+}
+
+/**
+ * The second question: not "is this the same game" but "did anything answer".
+ * Measured on real packages — driven 0.37, undriven drift 0.04, input silently
+ * dropped 0.09 — which is why the tolerance sits at 0.15 and not below it.
+ */
+describe('cellMaxDistance', () => {
+ const field = (w: number, h: number) => solid(w, h, [30, 30, 30]);
+ /** The same field with one small bright block, as a sprite at a position. */
+ const withSprite = (w: number, h: number, sx: number) =>
+ img(w, h, (x, y) => (x >= sx && x < sx + 4 && y >= 8 && y < 12 ? [255, 255, 255] : [30, 30, 30]));
+
+ it('is zero against itself', () => {
+ const g = downsample(withSprite(64, 32, 10), 16, 8);
+ expect(cellMaxDistance(g, g)).toBe(0);
+ });
+
+ it('sees a small sprite move where the mean does not', () => {
+ const a = downsample(withSprite(64, 32, 8), 16, 8);
+ const b = downsample(withSprite(64, 32, 40), 16, 8);
+ expect(gridDistance(a, b)).toBeLessThan(0.05); // averaged away
+ expect(cellMaxDistance(a, b)).toBeGreaterThan(0.3); // the moved cell shows
+ });
+
+ it('stays near zero when nothing moved but the field is busy', () => {
+ const a = downsample(field(64, 32), 16, 8);
+ const b = downsample(img(64, 32, (x, y) => (((x + y) % 17 === 0) ? [34, 34, 34] : [30, 30, 30])), 16, 8);
+ expect(cellMaxDistance(a, b)).toBeLessThan(0.05);
+ });
+
+ it('refuses grids of different sizes', () => {
+ expect(() => cellMaxDistance(new Float64Array(3), new Float64Array(6))).toThrow(/mismatch/);
+ });
+});
+
+describe('frameDistance', () => {
+ it('scores two identical captures at zero', () => {
+ expect(frameDistance(png(32, 18, [40, 80, 120]), png(32, 18, [40, 80, 120]))).toBe(0);
+ });
+
+ it('scores black against white at one', () => {
+ expect(frameDistance(png(32, 18, [0, 0, 0]), png(32, 18, [255, 255, 255]))).toBeCloseTo(1, 6);
+ });
+
+ it('refuses captures of different sizes — they letterbox differently', () => {
+ expect(() => frameDistance(png(32, 18, [0, 0, 0]), png(64, 18, [0, 0, 0])))
+ .toThrow(/differ in size/);
+ });
+
+ it('insets by default, so a play border never counts as a difference', () => {
+ expect(DEFAULT_INSET).toBeGreaterThan(0);
+ });
+
+ it('frameCellMax refuses mismatched sizes too — both reducers share the guard', () => {
+ expect(() => frameCellMax(png(32, 18, [0, 0, 0]), png(64, 18, [0, 0, 0]))).toThrow(/differ in size/);
+ });
+});
diff --git a/tools/tests/shader-twin-permutations.test.ts b/tools/tests/shader-twin-permutations.test.ts
new file mode 100644
index 000000000..5ce7b8e33
--- /dev/null
+++ b/tools/tests/shader-twin-permutations.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Twin generation for a shader with toggles. WGSL has no preprocessor, so
+ * every permutation has to be in the body and selected at assembly by the
+ * same `#ifdef` the GLSL side gets from a real define.
+ */
+import { describe, it, expect } from 'vitest';
+// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
+import { needsTwin, permutationsOf, composePermutations } from '../gen-shader-twins.mjs';
+
+const GLSL_ONLY = '#pragma shader "X"\n#pragma switch USE_GREEN default(off)\n#pragma fragment\nvoid main() {}\n#pragma end\n';
+
+describe('needsTwin', () => {
+ it('asks for a twin for a shader with switches', () => {
+ expect(needsTwin(GLSL_ONLY)).toBe(true);
+ });
+
+ it('leaves a hand-authored twin alone', () => {
+ expect(needsTwin('#pragma fragment wgsl\n@fragment fn fs_main() {}\n#pragma end\n')).toBe(false);
+ });
+});
+
+describe('permutationsOf', () => {
+ it('is the empty combination when there is nothing to toggle', () => {
+ expect(permutationsOf([])).toEqual([[]]);
+ });
+
+ it('covers every on/off combination', () => {
+ const got = permutationsOf(['A', 'B']).map((c: string[]) => c.join('') || '-');
+ expect(new Set(got)).toEqual(new Set(['-', 'A', 'B', 'AB']));
+ });
+});
+
+describe('composePermutations', () => {
+ it('emits the single body verbatim when nothing toggles', () => {
+ expect(composePermutations([], new Map([['', 'BODY']]))).toBe('BODY');
+ });
+
+ it('selects one toggle with #ifdef/#else', () => {
+ const bodies = new Map([['', 'OFF'], ['A', 'ON']]);
+ expect(composePermutations(['A'], bodies)).toBe('#ifdef A\nON\n#else\nOFF\n#endif');
+ });
+
+ it('nests two toggles so every combination is reachable', () => {
+ const bodies = new Map([['', 'oo'], ['A', 'Ao'], ['B', 'oB'], ['A,B', 'AB']]);
+ const out = composePermutations(['A', 'B'], bodies);
+ for (const body of ['oo', 'Ao', 'oB', 'AB']) expect(out).toContain(body);
+ expect(out.startsWith('#ifdef A')).toBe(true);
+ // Balanced: one #endif per #ifdef, or the assembly-time preprocessor
+ // silently swallows the rest of the stage.
+ expect((out.match(/#ifdef/g) ?? []).length).toBe((out.match(/#endif/g) ?? []).length);
+ });
+});
diff --git a/vitest.engine.config.ts b/vitest.engine.config.ts
new file mode 100644
index 000000000..a19e813dd
--- /dev/null
+++ b/vitest.engine.config.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { defineConfig } from 'vitest/config';
+
+/**
+ * The engine's own TypeScript suites — the asset pipeline and the build tooling.
+ *
+ * They used to live in desktop/tests, which made them the EDITOR's tests to run:
+ * once the editor became an optional private submodule, a checkout without it had
+ * no coverage of cook, export, the asset database or the gate libraries at all,
+ * and nothing said so. What a test exercises decides where it lives.
+ *
+ * The SDK keeps its own config (sdk/vitest.config.ts) because it builds and runs
+ * against a different target.
+ *
+ * NOT named vitest.config.ts: vitest walks up from its cwd, so a config at the
+ * repo root becomes the one every workspace without its own picks up — which
+ * pointed plugins/* at this include list and left them with no test files.
+ */
+export default defineConfig({
+ test: {
+ include: ['pipeline/tests/**/*.test.ts', 'tools/tests/**/*.test.ts'],
+ environment: 'node',
+ // The cook and export suites shell out and touch temp directories; the
+ // default 5s is not enough for the ones that package a whole project.
+ testTimeout: 30_000,
+ hookTimeout: 30_000,
+ },
+});