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.

22.1 KB
Raw Blame
// 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,
  logicalIndexFrom, inclusionChain, entriesOf, summarizeEntries,
} from '../src/export/sizeReport';
import {
  compareSizes, readSizeRecord, recordOf, writeSizeRecord, type SizeRecord,
} from '../src/export/sizeHistory';
import type { Inclusion } from '../src/assets/cookAssets';
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('still reads the engine binary once it is compressed and moved to a subpackage', () => {
    // Both halves of the move matter: the `wasm/` prefix is gone and `.wasm.br`
    // is not `.wasm`, and either alone files it under "other".
    expect(kindOf('subpackages/engine/esengine.wxgame.wasm.br')).toBe('engine');
    expect(kindOf('subpackages/engine/esengine.wxgame.wasm')).toBe('engine');
    expect(kindOf('wasm/esengine.wxgame.wasm.br')).toBe('engine');
    // One layer, not a guess: a compressed texture is still a texture.
    expect(kindOf('assets/9f8a7c.ktx2.br')).toBe('texture');
    expect(kindOf('notes.br')).toBe('other');
  });

  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(30 * 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(30 * 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, maxRetries: 10, retryDelay: 50 }); });

  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('still weighs the single file a playable ships, which is the build rather than a copy of it', async () => {
    // One index.html, nothing loose beside it to double-count, so the .apk
    // repackaging rule does not apply. Note there is no `packages` here — the
    // shape the two cases above never exercise.
    await write('index.html', 3_444_304);
    const report = await measureBuild({
      root: dir,
      platform: 'playable',
      deliverable: path.join(dir, 'index.html'),
    });
    expect(report.fileCount).toBe(1);
    expect(report.packageBytes).toBe(3_444_304);
    expect(report.byKind).toEqual([{ kind: 'other', bytes: 3_444_304, count: 1 }]);
    expect(report.largest[0]?.path).toBe('index.html');
    expect(report.deliverableBytes).toBe(3_444_304);   // and still weighed as the upload
  });

  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');
  });
});

describe('why a file is in the package', () => {
  /** What the cook answers: one edge per asset, back to whatever let it in. */
  const INCLUSION: Record<string, Inclusion> = {
    'scenes/level1.esscene': { reason: 'entry' },
    'assets/hero.esprefab': { reason: 'dependency', via: 'scenes/level1.esscene' },
    'assets/hero.png': { reason: 'dependency', via: 'assets/hero.esprefab' },
    'assets/strings.eslocale': { reason: 'locale' },
    'subpackages/levels/level2.esscene': { reason: 'group' },
  };

  it('walks a dependency back to the scene that pulled it in', () => {
    const why = inclusionChain('assets/hero.png', INCLUSION)!;
    expect(why.reason).toBe('entry');
    expect(why.chain).toEqual(['assets/hero.png', 'assets/hero.esprefab', 'scenes/level1.esscene']);
  });

  it('names the rule for content no scene references', () => {
    expect(inclusionChain('assets/strings.eslocale', INCLUSION))
      .toEqual({ reason: 'locale', chain: ['assets/strings.eslocale'] });
    expect(inclusionChain('subpackages/levels/level2.esscene', INCLUSION))
      .toEqual({ reason: 'group', chain: ['subpackages/levels/level2.esscene'] });
  });

  it('stops on a reference cycle instead of walking it forever', () => {
    const cyclic: Record<string, Inclusion> = {
      'a.esprefab': { reason: 'dependency', via: 'b.esprefab' },
      'b.esprefab': { reason: 'dependency', via: 'a.esprefab' },
    };
    const why = inclusionChain('a.esprefab', cyclic)!;
    expect(why.chain).toEqual(['a.esprefab', 'b.esprefab']);
  });

  it('says nothing about a file the cook never staged', () => {
    expect(inclusionChain('wasm/esengine.wasm', INCLUSION)).toBeUndefined();
  });

  it('finds the logical path behind a content-addressed name', () => {
    const logical = logicalIndexFrom({
      groups: {
        main: {
          assets: {
            'assets/hero.png': { path: 'assets/9f8e7d6c.png', address: 'assets/hero.png' },
            '@uuid:1234': { path: 'assets/9f8e7d6c.png', address: 'assets/hero.png' },
            'scenes/level1.esscene': { path: 'scenes/level1.esscene' },
          },
        },
      },
    });
    expect(logical.get('assets/9f8e7d6c.png')).toBe('assets/hero.png');
    expect(logical.get('scenes/level1.esscene')).toBe('scenes/level1.esscene');
  });

  it('carries the answer onto the file the report names', () => {
    const report = summarizeBuildFiles(
      [{ path: 'assets/9f8e7d6c.png', bytes: 4 * MB }, { path: 'wasm/esengine.wasm', bytes: MB }],
      {
        logical: new Map([['assets/9f8e7d6c.png', 'assets/hero.png']]),
        inclusion: INCLUSION,
      },
    );
    const texture = report.largest.find((e) => e.path === 'assets/9f8e7d6c.png')!;
    expect(texture.why?.chain).toEqual(['assets/hero.png', 'assets/hero.esprefab', 'scenes/level1.esscene']);
    expect(report.largest.find((e) => e.path === 'wasm/esengine.wasm')!.why).toBeUndefined();
  });
});

describe('this build against the last one', () => {
  const settings = { compressTextures: true, minify: true };
  const record = (files: { path: string; bytes: number }[], at: string, s = settings): SizeRecord => {
    const entries = entriesOf(files);
    return recordOf(summarizeEntries(entries), 'web', s, entries, at);
  };

  it('names what is new, gone and resized, biggest change first', () => {
    const before = record([
      { path: 'assets/hero.png', bytes: 1 * MB },
      { path: 'assets/old.png', bytes: 2 * MB },
      { path: 'wasm/esengine.wasm', bytes: 3 * MB },
    ], '2026-09-17T00:00:00.000Z');
    const after = record([
      { path: 'assets/hero.png', bytes: 5 * MB },
      { path: 'assets/new.mp3', bytes: 1 * MB },
      { path: 'wasm/esengine.wasm', bytes: 3 * MB },
    ], '2026-09-18T00:00:00.000Z');

    const since = compareSizes(before, after);
    expect(since.at).toBe('2026-09-17T00:00:00.000Z');
    expect(since.packageDelta).toBe(0 + (5 - 1) * MB - 2 * MB + 1 * MB);
    expect(since.changes.map((c) => [c.path, c.wasBytes, c.bytes])).toEqual([
      ['assets/hero.png', 1 * MB, 5 * MB],
      ['assets/old.png', 2 * MB, 0],
      ['assets/new.mp3', 0, 1 * MB],
    ]);
    // The file nobody touched is not a change, and a report full of them hides
    // the three that are.
    expect(since.changes.some((c) => c.path === 'wasm/esengine.wasm')).toBe(false);
  });

  it('says when the two builds were made with different settings', () => {
    const before = record([{ path: 'assets/hero.png', bytes: 4 * MB }], '2026-09-17T00:00:00.000Z',
                          { compressTextures: false, minify: true });
    const after = record([{ path: 'assets/hero.png', bytes: 1 * MB }], '2026-09-18T00:00:00.000Z');
    const since = compareSizes(before, after);
    expect(since.settingsChanged).toEqual(['compressTextures']);
    expect(since.packageDelta).toBe(-3 * MB);
  });

  it('is silent about settings when the same ones were used', () => {
    const before = record([{ path: 'a.png', bytes: MB }], '2026-09-17T00:00:00.000Z');
    const after = record([{ path: 'a.png', bytes: 2 * MB }], '2026-09-18T00:00:00.000Z');
    expect(compareSizes(before, after).settingsChanged).toEqual([]);
  });

  it('compares against the last build of the SAME platform, and leaves a record for the next', async () => {
    const root = await mkdtemp(path.join(tmpdir(), 'size-history-'));
    try {
      const first = record([{ path: 'a.png', bytes: MB }], '2026-09-17T00:00:00.000Z');
      expect(await readSizeRecord(root, 'web')).toBeNull();
      await writeSizeRecord(root, 'web', first);
      expect((await readSizeRecord(root, 'web'))?.files).toEqual(first.files);
      // Another platform's history is its own: a WeChat package and a web build
      // weigh different things and comparing them would be noise.
      expect(await readSizeRecord(root, 'wechat')).toBeNull();
    } finally {
      await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
    }
  });
});

/**
 * A WeChat limit is judged on PACKED bytes, so every figure the report carries
 * is the packed one and a reader has no way to see what the packing bought.
 * The export is the only place both numbers exist.
 */
describe('what the export packed', () => {
    const packed = (over: Partial<Record<string, number>> = {}) => entriesOf(
        [
            { path: 'wasm/esengine.wasm.br', bytes: 363617 },
            { path: 'game-bundle.js', bytes: 1064880 },
        ],
        { packedFrom: { 'wasm/esengine.wasm.br': 1828959, ...over } },
    );

    it('rides the entry it belongs to, and only that one', () => {
        const e = packed();
        expect(e.find((x) => x.path === 'wasm/esengine.wasm.br')?.sourceBytes).toBe(1828959);
        expect(e.find((x) => x.path === 'game-bundle.js')).not.toHaveProperty('sourceBytes');
    });

    it('is summed into one figure a reader can act on', () => {
        expect(summarizeEntries(packed()).packing)
            .toEqual({ fromBytes: 1828959, toBytes: 363617, fileCount: 1 });
    });

    // `bytes` stays what ships: a budget judged against the pre-packed number
    // would fail a package that fits.
    it('never changes what the package is judged to weigh', () => {
        expect(summarizeEntries(packed()).packageBytes).toBe(363617 + 1064880);
    });

    it('is absent when the export packed nothing, rather than zero', () => {
        expect(summarizeEntries(entriesOf([{ path: 'game-bundle.js', bytes: 10 }])).packing)
            .toBeUndefined();
    });
});

describe('a cap on each subpackage', () => {
  const entry = (path: string, bytes: number, bucket: 'initial' | 'lazy') => ({ path, bytes, bucket, kind: 'other' as const });

  it('is judged on the heaviest one, not their sum', () => {
    const budget = { scope: 'eachSubpackage' as const, maxBytes: 4 * MB, note: 'each subpackage' };
    const report = summarizeEntries([
      entry('game-bundle.js', 1 * MB, 'initial'),
      entry('subpackages/a/one.bin', 3 * MB, 'lazy'),
      entry('subpackages/a/two.bin', 2 * MB, 'lazy'),
      entry('subpackages/b/three.bin', 3 * MB, 'lazy'),
    ], { budgets: [budget] });
    expect(report.largestSubpackage).toEqual({ root: 'subpackages/a', bytes: 5 * MB });
    expect(report.verdicts).toHaveLength(1);
    expect(report.verdicts[0]).toMatchObject({ measuredBytes: 5 * MB, status: 'over' });
  });

  it('says nothing about a build with no subpackages', () => {
    const report = summarizeEntries([entry('game-bundle.js', 9 * MB, 'initial')], {
      budgets: [{ scope: 'eachSubpackage', maxBytes: 4 * MB, note: 'each subpackage' }],
    });
    expect(report.largestSubpackage).toBeUndefined();
    expect(report.verdicts).toEqual([]);
  });
});