A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(export): the size report says why a file is in the package, and what moved
esengine81e6c7e7cce3
diff --git a/.gitignore b/.gitignoreindex 5010dd25e..145ab6b99 100644--- a/.gitignore+++ b/.gitignore@@ -155,6 +155,9 @@ docs/local/# Conversations with the built-in agent (electron/agent/store.ts): one person's# working notes, holding whatever they typed and whatever the model read back.**/.esengine/agent/+# What each target weighed last build (pipeline/src/export/sizeHistory.ts) — one+# machine's measurement of one moment, which the next build compares against.+**/.esengine/build-size/# Generated by xcodegen from native/ios/project.ymlnative/ios/*.xcodeproj/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dc874886b..8a00c154d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,14 @@ published separately; it ships inside the editor.### Added+- **The build size report says why a file is in your package, and what changed since the+ last build.** A big texture now names the chain that pulled it in — the scene, prefab or+ material that references it, or the rule that force-included it (a subpackage group, an+ always-include folder, a locale table, a data file). Each platform's whole per-file+ measurement is kept with the project, so the next build of that target reports what is+ new, gone or resized, and says when a compression or minify setting changed rather than+ reading it as content that grew.+- **`getResourceStats()` reports the memory kept to survive a lost GPU.** To bring thepicture back after a graphics reset, the engine keeps a CPU copy of some textures andbuffers — a cost no GPU figure shows, and a real one on a mini-game's memory budget.diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex 35c17c297..a285d262c 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -108,6 +108,34 @@ export interface CookManifestEntry extends AssetEntry {};}+/**+ * Why an asset is in the build — the answer to "what is this doing in my package".+ *+ * `dependency` is the only one with a `via`: the asset that referenced it. Follow+ * those and the chain ends at whichever seed let it in, which is what a size+ * report shows beside a file nobody remembers adding.+ */+export type InclusionReason =+ /** An entry scene itself. */+ | 'entry'+ /** Referenced by another included asset (`via`). */+ | 'dependency'+ /** In a subpackage or remote group: delivered on demand, so nothing references it. */+ | 'group'+ /** In a group the project declared always-include. */+ | 'always-include'+ /** A locale table — loaded by code, so reachability would cull it. */+ | 'locale'+ /** A data asset (`.json`), named by the code that loads it. */+ | 'data';++/** How one asset got in: the reason, and for a dependency the asset that named it. */+export interface Inclusion {+ reason: InclusionReason;+ /** The referring asset's logical path, for `dependency`. */+ via?: string;+}+/** `assets.manifest.json` as the cook writes it — what the package carries. */export interface CookManifest {version: string;@@ -382,6 +410,11 @@ export interface CookResult {includedPaths: string[];/** uuids present in the project but unreachable — culled from the build. */unused: string[];+ /**+ * Why each included asset is in the build, by its logical (project-relative)+ * path. The size report walks `via` back to a seed to say what pulled a file in.+ */+ inclusion: Record<string, Inclusion>;warnings: string[];/*** Assets the game REACHES that could not be produced, as `<path>: <why>`. Each@@ -432,9 +465,13 @@ export async function cookAssets(// Seed reachability from the entry scenes (path → uuid)…const reachable = new Set<string>();const queue: string[] = [];- const seed = (uuid: string): void => {+ // Kept as it is discovered, not derived afterwards: the FIRST way in is the+ // shortest one, and re-deriving it later would answer a different question.+ const inclusionByUuid = new Map<string, Inclusion>();+ const seed = (uuid: string, how: Inclusion): void => {if (!reachable.has(uuid)) {reachable.add(uuid);+ inclusionByUuid.set(uuid, how);queue.push(uuid);}};@@ -444,7 +481,7 @@ export async function cookAssets(warnings.push(`entry scene not in asset index: ${scenePath}`);continue;}- seed(entry.uuid);+ seed(entry.uuid, { reason: 'entry' });}// Force-include lazy-subpackage assets: they're loaded on demand, so the entry// scene never references them — but they (and their deps) must still ship. A@@ -454,31 +491,32 @@ export async function cookAssets(const group = resolveAssetGroup(e.path, groupsConfig);// …and every non-local (subpackage / remote-CDN) asset: never scene-// referenced, but must be cooked + staged for its group's delivery.- if (group.delivery !== 'local') seed(e.uuid);+ if (group.delivery !== 'local') seed(e.uuid, { reason: 'group' });// …and every asset in a group the project declared always-include: what a// scene cannot reference because only code names it (a path built at run// time, a texture in rich-text markup). Reachability would cull it, and the// first anyone would hear of that is a missing image on a device.- else if (group.alwaysInclude) seed(e.uuid);+ else if (group.alwaysInclude) seed(e.uuid, { reason: 'always-include' });}// Force-include locale string tables: translations load by code / plugin// option (a scene never references them — Text carries KEYS, not paths), so// reachability would always cull them, and a build missing its languages is// strictly wrong. Text is tiny; dead tables cost nothing.for (const e of shippable) {- if (e.path.toLowerCase().endsWith('.eslocale')) seed(e.uuid);+ if (e.path.toLowerCase().endsWith('.eslocale')) seed(e.uuid, { reason: 'locale' });}// …and data assets, for the same reason one step further: a `.json` table is// named by the code that loads it, so nothing in the scene graph points at it.// Culling it produces the worst failure this pipeline can produce — it works in// the editor, which serves the whole project, and 404s only in the build.for (const e of shippable) {- if (e.type === 'json') seed(e.uuid);+ if (e.type === 'json') seed(e.uuid, { reason: 'data' });}// …then take the transitive closure over the dependency graph.while (queue.length > 0) {const uuid = queue.shift()!;- for (const dep of index.deps[uuid] ?? []) seed(dep);+ const from = byUuid.get(uuid)?.path;+ for (const dep of index.deps[uuid] ?? []) seed(dep, { reason: 'dependency', via: from });}const absOut = path.isAbsolute(opts.outDir) ? opts.outDir : path.join(root, opts.outDir);@@ -873,8 +911,16 @@ export async function cookAssets(warnings.push(`${defeatedByFormat.length} image(s) ask to be compressed but are not PNG, so they `+ `ship as they are — ${shown}${defeatedByFormat.length > 3 ? ', …' : ''}`);}+ // Keyed by logical path: that is what a reference names and what a report can+ // show, while the uuid is an identity nobody reading the report has.+ const inclusion: Record<string, Inclusion> = {};+ for (const [uuid, how] of inclusionByUuid) {+ const logical = byUuid.get(uuid)?.path;+ if (logical) inclusion[logical] = how;+ }return {ok: failed.length === 0,outDir: absOut, manifestPath, included: [...reachable], includedPaths, unused, warnings, failed,+ inclusion,};}diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex ddc371cc0..6f5c6582d 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -25,7 +25,7 @@ import { runtimeHostEntry } from '../bundle/runtimeHosts';import { writeFile, readFile, mkdir, cp, readdir, rm } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';-import { cookAssets, loadAssetGroups, type CookManifest } from '../assets/cookAssets';+import { cookAssets, loadAssetGroups, type CookManifest, type Inclusion } from '../assets/cookAssets';import { cookWorlds, streamedScenes } from '../world/cookWorld';import { buildAddressableManifest } from '../assets/addressableManifest';import { activeRemoteRoot } from '../../../sdk/src/asset/assetGroups';@@ -219,6 +219,10 @@ export interface ExportGameResult {outDir: string;/** Count of assets included (reachable from the entry scene). */included: number;+ /** @internal Why each asset is in the build, by logical path. Consumed by the+ * size report and dropped: a project's whole asset graph has no business+ * crossing to the editor on every build. */+ inclusion?: Record<string, Inclusion>;warnings: string[];errors: string[];/** Android: the generated Gradle project, for the editor to reveal. Absent@@ -508,10 +512,24 @@ async function attachSizeReport(result: ExportGameResult, opts: ExportGameOptiondeliverable,packages,inlineOf: result.inlineParts ? { file: 'index.html', parts: result.inlineParts } : undefined,+ inclusion: result.inclusion,+ // The project, not the build: what this target weighed last time lives with+ // the project, and the settings ride along so a compression change is not+ // read as content that grew.+ history: {+ projectRoot: opts.root,+ settings: {+ contentAddressed: opts.contentAddressed,+ compressTextures: opts.compressTextures,+ compressAudio: opts.compressAudio,+ atlasTextures: opts.atlasTextures,+ minify: opts.minify,+ },+ },});- return { ...result, size };+ return { ...result, size, inclusion: undefined };} catch {- return result; // measuring is reporting, never a reason to fail a build+ return { ...result, inclusion: undefined }; // measuring is reporting, never a reason to fail a build}}@@ -990,6 +1008,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>return {ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length,+ inclusion: cook.inclusion,warnings, errors, ...(xcodeProject ? { xcodeProject } : {}), ...(androidProject ? { androidProject } : {}),...(apkFile ? { apkFile } : {}), ...(aabFile ? { aabFile } : {}),...(appBundles.length > 0 ? { appBundles } : {}),diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.tsindex 2142a4ecf..2f9838fa6 100644--- a/pipeline/src/export/exportMiniGame.ts+++ b/pipeline/src/export/exportMiniGame.ts@@ -35,7 +35,7 @@ import {import { writeFile, mkdir, cp, readFile, rename, rm } from 'node:fs/promises';import { existsSync } from 'node:fs';import path from 'node:path';-import { cookAssets } from '../assets/cookAssets';+import { cookAssets, type Inclusion } from '../assets/cookAssets';import { buildAddressableManifest } from '../assets/addressableManifest';import type { ExportScene } from './exportGame';import type { OnExportProgress } from './exportProgress';@@ -55,6 +55,8 @@ export interface ExportMiniGameResult {included: number;warnings: string[];errors: string[];+ /** @internal Why each asset is in the build; the size report consumes and drops it. */+ inclusion?: Record<string, Inclusion>;}interface CookManifest {@@ -503,5 +505,8 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {warnings.push(...await stageProjectModules(projectModules, wasmOut, profile.id,async (code) => (await transform(code, { target: profile.esTarget, loader: 'js' })).code));- return { ok: errors.length === 0, platform: profile.id, outDir: absOut, included: cook.included.length, warnings, errors };+ return {+ ok: errors.length === 0, platform: profile.id, outDir: absOut,+ included: cook.included.length, warnings, errors, inclusion: cook.inclusion,+ };}diff --git a/pipeline/src/export/sizeHistory.ts b/pipeline/src/export/sizeHistory.tsnew file mode 100644index 000000000..b0df5cbf3--- /dev/null+++ b/pipeline/src/export/sizeHistory.ts@@ -0,0 +1,147 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What the last build of this target weighed, so this one can say what moved.+ *+ * A total is not an answer: "the package grew 3MB" sends a developer+ * hunting, while "these four files are new and this texture doubled" is the+ * fix. So the whole per-file record is kept per platform, beside the+ * project rather than inside the build — a shipped package has no business+ * carrying the last one's measurements.+ *+ * The record also carries the SETTINGS that decide size (compression,+ * content addressing, minification). Comparing a compressed build against+ * an uncompressed one otherwise reads as a regression nobody caused, which+ * is the one way a comparison like this becomes noise.+ */+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import type { BuildSizeEntry, BuildSizeReport } from './sizeReport';+import type { ExportPlatform } from '../project/platforms';++/** Build options that change what a package weighs, recorded with the measurement. */+export interface SizeSettings {+ contentAddressed?: boolean;+ compressTextures?: boolean;+ compressAudio?: boolean;+ atlasTextures?: boolean;+ minify?: boolean;+}++/** One build's measurement, as the history file stores it. */+export interface SizeRecord {+ /** ISO timestamp of the build that wrote it. */+ at: string;+ platform: ExportPlatform;+ settings: SizeSettings;+ initialBytes: number;+ lazyBytes: number;+ remoteBytes: number;+ packageBytes: number;+ totalBytes: number;+ fileCount: number;+ /** Every shipped file, not just the largest — this is what the next build diffs. */+ files: BuildSizeEntry[];+}++/** One file that is new, gone, or a different size than last build. */+export interface SizeChange {+ path: string;+ /** 0 when the file is gone. */+ bytes: number;+ /** 0 when the file is new. */+ wasBytes: number;+ /** Carried from the current build, so a grown file can say what pulled it in. */+ why?: BuildSizeEntry['why'];+}++/** This build against the last one of the same platform. */+export interface SizeComparison {+ /** When the build being compared against was made. */+ at: string;+ /**+ * Settings that differ between the two builds, by name. Non-empty means the+ * numbers below are not comparing the same thing being built two ways.+ */+ settingsChanged: string[];+ initialDelta: number;+ packageDelta: number;+ /** Biggest absolute change first, capped at {@link MOST_CHANGED}. */+ changes: SizeChange[];+}++/** How many changed files a comparison names. */+export const MOST_CHANGED = 12;++const RECORD_VERSION = 1;++/** Where a platform's last measurement sits: beside the project, not in the build. */+export function sizeRecordPath(projectRoot: string, platform: ExportPlatform): string {+ return path.join(projectRoot, '.esengine', 'build-size', `${platform}.json`);+}++/** The previous record, or null when this is the first build of this target. */+export async function readSizeRecord(+ projectRoot: string, platform: ExportPlatform,+): Promise<SizeRecord | null> {+ try {+ const raw = JSON.parse(await readFile(sizeRecordPath(projectRoot, platform), 'utf8')) as+ { version?: number; record?: SizeRecord };+ return raw.version === RECORD_VERSION && raw.record ? raw.record : null;+ } catch {+ return null; // absent or unreadable — a first build, which compares to nothing+ }+}++export async function writeSizeRecord(+ projectRoot: string, platform: ExportPlatform, record: SizeRecord,+): Promise<void> {+ const file = sizeRecordPath(projectRoot, platform);+ await mkdir(path.dirname(file), { recursive: true });+ await writeFile(file, JSON.stringify({ version: RECORD_VERSION, record }, null, 2) + '\n');+}++/** The record this build leaves for the next one. */+export function recordOf(+ report: BuildSizeReport, platform: ExportPlatform, settings: SizeSettings, files: readonly BuildSizeEntry[],+ at = new Date().toISOString(),+): SizeRecord {+ return {+ at, platform, settings,+ initialBytes: report.initialBytes,+ lazyBytes: report.lazyBytes,+ remoteBytes: report.remoteBytes,+ packageBytes: report.packageBytes,+ totalBytes: report.totalBytes,+ fileCount: report.fileCount,+ files: [...files],+ };+}++/** Which settings the two builds disagree on. */+export function settingsDiff(before: SizeSettings, after: SizeSettings): string[] {+ const names = new Set([...Object.keys(before), ...Object.keys(after)] as (keyof SizeSettings)[]);+ return [...names].filter((name) => (before[name] ?? false) !== (after[name] ?? false)).sort();+}++/** This build's files against the previous record's. Pure — the tests drive it. */+export function compareSizes(previous: SizeRecord, current: SizeRecord): SizeComparison {+ const was = new Map(previous.files.map((f) => [f.path, f.bytes]));+ const changes: SizeChange[] = [];+ for (const file of current.files) {+ const before = was.get(file.path);+ if (before === file.bytes) { was.delete(file.path); continue; }+ changes.push({ path: file.path, bytes: file.bytes, wasBytes: before ?? 0, ...(file.why ? { why: file.why } : {}) });+ was.delete(file.path);+ }+ // Whatever is left was shipped last time and is not shipped now.+ for (const [p, bytes] of was) changes.push({ path: p, bytes: 0, wasBytes: bytes });+ changes.sort((a, b) => Math.abs(b.bytes - b.wasBytes) - Math.abs(a.bytes - a.wasBytes));+ return {+ at: previous.at,+ settingsChanged: settingsDiff(previous.settings, current.settings),+ initialDelta: current.initialBytes - previous.initialBytes,+ packageDelta: current.packageBytes - previous.packageBytes,+ changes: changes.slice(0, MOST_CHANGED),+ };+}diff --git a/pipeline/src/export/sizeReport.ts b/pipeline/src/export/sizeReport.tsindex b8190de2a..b0b835565 100644--- a/pipeline/src/export/sizeReport.ts+++ b/pipeline/src/export/sizeReport.ts@@ -30,6 +30,11 @@ import {evaluateSizeBudget, resolveSizeBudgets,type SizeBudget, type SizeVerdict,} from '../project/sizeBudget';+import type { Inclusion, InclusionReason } from '../assets/cookAssets';+import {+ compareSizes, readSizeRecord, recordOf, writeSizeRecord,+ type SizeComparison, type SizeSettings,+} from './sizeHistory';/** Where a file sits in the delivery model — see the file header. */export type SizeBucket = 'initial' | 'lazy' | 'remote';@@ -43,6 +48,16 @@ export type SizeBucket = 'initial' | 'lazy' | 'remote';*/export type SizeKind = 'engine' | 'scripts' | 'texture' | 'audio' | 'video' | 'font' | 'scene' | 'data' | 'other';+/** Why a file is in the build: what let it in, and what it came in through. */+export interface SizeAttribution {+ reason: InclusionReason;+ /**+ * From the file's own logical path back to the seed that let it in — the+ * answer to "why is this in my package". One entry when it IS the seed.+ */+ chain: string[];+}+/** One file in the finished build. */export interface BuildSizeEntry {/** Path relative to the measured root, in POSIX form (the shipped shape). */@@ -50,6 +65,8 @@ export interface BuildSizeEntry {bytes: number;bucket: SizeBucket;kind: SizeKind;+ /** Absent for a file the cook did not stage (the engine runtime, the host page). */+ why?: SizeAttribution;}export interface KindTotal {@@ -84,6 +101,8 @@ export interface BuildSizeReport {/** Every limit in force, judged. Empty when the target declares none and the* project set no budget. */verdicts: SizeVerdict[];+ /** This build against the last one of the same platform; absent for the first. */+ since?: SizeComparison;}/** How many files the report names individually. Enough to find the offender,@@ -158,10 +177,77 @@ export function bucketIndexFrom(manifest: unknown): Map<string, SizeBucket> {const normalizeRel = (p: string): string => p.replace(/\\/g, '/').replace(/^\.?\//, '');+/**+ * Shipped path → the asset's LOGICAL path, off the same manifest the buckets come+ * from. Content-addressed staging renames the file, so without this the shipped+ * name matches nothing a reference (or a developer) knows it by.+ */+export function logicalIndexFrom(manifest: unknown): Map<string, string> {+ const index = new Map<string, string>();+ const groups = (manifest as { groups?: Record<string, { assets?: Record<string, { path?: string; address?: string }> }> } | null)?.groups;+ for (const group of Object.values(groups ?? {})) {+ for (const [key, asset] of Object.entries(group?.assets ?? {})) {+ if (!asset?.path) continue;+ const shipped = normalizeRel(asset.path);+ // `address` is the logical path when staging renamed the file; otherwise the+ // key IS a logical path (the manifest lists each asset under several aliases,+ // and a uuid alias is no use to a reader).+ const logical = asset.address ?? (key.startsWith('@uuid:') ? undefined : key);+ if (logical && !index.has(shipped)) index.set(shipped, normalizeRel(logical));+ }+ }+ return index;+}++/**+ * The chain from a logical path back to the seed that let it in. Stops at the+ * first repeat: a reference cycle is a graph a project can have, and a report+ * that hangs on one is worse than a chain that ends early.+ */+export function inclusionChain(logical: string, inclusion: Record<string, Inclusion>): SizeAttribution | undefined {+ const first = inclusion[logical];+ if (!first) return undefined;+ const chain = [logical];+ const seen = new Set([logical]);+ let step = first;+ while (step.reason === 'dependency' && step.via && !seen.has(step.via)) {+ chain.push(step.via);+ seen.add(step.via);+ const next = inclusion[step.via];+ if (!next) break;+ step = next;+ }+ // The REASON is the seed's, not this asset's: "a dependency" says nothing on+ // its own, and what a reader wants is the scene (or the rule) at the end.+ return { reason: step.reason, chain };+}+/** Whether @p rel is one of @p roots or sits inside one of them. */const isUnder = (rel: string, roots: readonly string[]): boolean =>roots.some((root) => rel === root || rel.startsWith(`${root}/`));+/** What the report counts, per shipped file. Pure — the tests drive it. */+export function entriesOf(+ files: readonly { path: string; bytes: number }[],+ opts: {+ buckets?: Map<string, SizeBucket>;+ logical?: Map<string, string>;+ inclusion?: Record<string, Inclusion>;+ } = {},+): BuildSizeEntry[] {+ const buckets = opts.buckets ?? new Map<string, SizeBucket>();+ const entries: BuildSizeEntry[] = [];+ for (const file of files) {+ const rel = normalizeRel(file.path);+ if (NOT_SHIPPED.has(rel) || isSourceMap(rel)) continue;+ const bucket = buckets.get(rel) ?? 'initial';+ const logical = opts.logical?.get(rel);+ const why = logical && opts.inclusion ? inclusionChain(logical, opts.inclusion) : undefined;+ entries.push({ path: rel, bytes: file.bytes, bucket, kind: kindOf(rel), ...(why ? { why } : {}) });+ }+ return entries;+}+/*** Turn measured files into the report. Pure — the tests drive it with a list of* paths and sizes, no build required.@@ -173,19 +259,30 @@ export function summarizeBuildFiles(budgets?: readonly SizeBudget[];deliverableBytes?: number;deliverableName?: string;+ /** Shipped path → logical path ({@link logicalIndexFrom}). */+ logical?: Map<string, string>;+ /** Why each asset is in the build, by logical path (the cook's answer). */+ inclusion?: Record<string, Inclusion>;+ } = {},+): BuildSizeReport {+ return summarizeEntries(entriesOf(files, opts), opts);+}++/** The report over entries already counted — what {@link measureBuild} keeps, so the+ * history record and the report are the same measurement. */+export function summarizeEntries(+ entries: readonly BuildSizeEntry[],+ opts: {+ budgets?: readonly SizeBudget[];+ deliverableBytes?: number;+ deliverableName?: string;} = {},): BuildSizeReport {- const buckets = opts.buckets ?? new Map<string, SizeBucket>();- const entries: BuildSizeEntry[] = [];let initialBytes = 0, lazyBytes = 0, remoteBytes = 0, totalBytes = 0;const kinds = new Map<SizeKind, KindTotal>();- for (const file of files) {- const rel = normalizeRel(file.path);- if (NOT_SHIPPED.has(rel) || isSourceMap(rel)) continue;- const bucket = buckets.get(rel) ?? 'initial';- const kind = kindOf(rel);- entries.push({ path: rel, bytes: file.bytes, bucket, kind });+ for (const file of entries) {+ const { bucket, kind } = file;totalBytes += file.bytes;if (bucket === 'remote') remoteBytes += file.bytes;else {@@ -303,6 +400,14 @@ export async function measureBuild(opts: {* `other`. Supplied by the assembly, which is where the bytes are joined.*/inlineOf?: { file: string; parts: readonly { path: string; bytes: number }[] };+ /** The cook's `inclusion` map — why each asset is in the build. */+ inclusion?: Record<string, Inclusion>;+ /**+ * Compare against this platform's last build and leave the record for the next.+ * `projectRoot` is the PROJECT, not the output: the history outlives one build+ * and a shipped package must not carry it.+ */+ history?: { projectRoot: string; settings: SizeSettings };}): Promise<BuildSizeReport> {const excluded: string[] = [];for (const file of opts.packages ?? []) {@@ -336,8 +441,12 @@ export async function measureBuild(opts: {} catch { /* not produced (no template installed) — the limit is then skipped */ }}- return summarizeBuildFiles(files, {+ const entries = entriesOf(files, {buckets: bucketIndexFrom(manifest),+ logical: logicalIndexFrom(manifest),+ inclusion: opts.inclusion,+ });+ const report = summarizeEntries(entries, {budgets: resolveSizeBudgets(opts.platform, {profile: opts.profileBudgets,projectMaxBytes: opts.projectMaxBytes,@@ -345,4 +454,14 @@ export async function measureBuild(opts: {deliverableBytes,deliverableName: opts.deliverable ? path.basename(opts.deliverable) : undefined,});++ if (opts.history) {+ const record = recordOf(report, opts.platform, opts.history.settings, entries);+ const previous = await readSizeRecord(opts.history.projectRoot, opts.platform);+ if (previous) report.since = compareSizes(previous, record);+ // Written after the comparison, so a failed write leaves the last good record+ // rather than a half-written one this build would then compare against.+ await writeSizeRecord(opts.history.projectRoot, opts.platform, record);+ }+ return report;}diff --git a/pipeline/tests/size-report.test.ts b/pipeline/tests/size-report.test.tsindex 38e6a2cfe..9776b2318 100644--- a/pipeline/tests/size-report.test.ts+++ b/pipeline/tests/size-report.test.ts@@ -20,7 +20,12 @@ 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;@@ -285,3 +290,132 @@ describe('one spelling of a byte size', () => {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 });+ }+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 29b44872d..b51bde472 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,9 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(export): the size report says why a file is in the package, and what moved':+ { note: 'The build size report says why a file is in your package, and what changed since the' },+'feat(render): a game is told the device came back, and which target it drew is blank':{ note: 'The picture comes back after the GPU is lost.' },