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(editor): every packaging target now says what it weighs
yhh248daa16398b
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex f55fafc91..e82e67cfb 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -33,7 +33,7 @@ import { exportWeChat } from './exportWeChat';import { exportMiniGame } from './exportMiniGame';import type { MiniGameExportProfile } from './miniGameExportProfile';import { exportPlayable } from './exportPlayable';-import type { PlayableAdProfile } from './playableAdProfile';+import { genericPlayableProfile, type PlayableAdProfile } from './playableAdProfile';import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';@@ -44,6 +44,8 @@ import { assembleApk, apkFileName } from '../../build-tools/utils/apk.js';import { assembleAab, aabFileName } from '../../build-tools/utils/aab.js';import { debugSigningKey, type SigningKey } from '../../build-tools/utils/androidKeystore.js';import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';+import type { SizeBudget } from '../src/project/sizeBudget';+import { measureBuild, type BuildSizeReport } from './sizeReport';import { collectSubsystems, subsystemGapWarnings, targetGaps, type Subsystem } from '../src/project/targetSupport';export type { ExportPlatform };@@ -171,6 +173,9 @@ export interface ExportGameResult {/** Playable, zip-delivery networks: the archive written beside the HTML — the file* the network takes an upload of. */zipFile?: string;+ /** What the package weighs, and how it fared against the limits in force.+ * Absent when the export failed, or when measuring itself did. */+ size?: BuildSizeReport;}/** The web host page. `orientation` pins the canvas to a screen orientation (rotate-@@ -348,14 +353,7 @@ async function stageDesktopApp(absOut: string, title: string, orientation: Screeawait writeFile(path.join(absOut, 'README.md'), desktopReadme(display));}-/**- * Export the open project. `entryScene` is the project-relative scene to boot;- * `gameHostEntry` the game-host esbuild entry — the prebuilt realm-host bundle- * (dist-electron/hosts/gameHost.js; a packaged app ships no src/ and esbuild- * cannot read app.asar) or any source esbuild can reach (tests). `wasmDir` is- * the engine runtime to copy. `platform` selects the target (default web).- */-export async function exportGame(opts: {+export interface ExportGameOptions {root: string;entryScene: string;/** Project-relative scenes dir (manifest layout); default the entry's dir.@@ -449,7 +447,83 @@ export async function exportGame(opts: {androidKey?: SigningKey;/** The app's launcher icon (project-relative). Omitted ⇒ the template's default. */appIcon?: string;-}): Promise<ExportGameResult> {+ /** `packaging.sizeBudget[platform]` — the project's own package-size ceiling in+ * bytes, replacing whatever limit the target declares. See sizeBudget.ts. */+ sizeBudgetBytes?: number;+}++/**+ * Export the open project. `entryScene` is the project-relative scene to boot;+ * `gameHostEntry` the game-host esbuild entry — the prebuilt realm-host bundle+ * (dist-electron/hosts/gameHost.js; a packaged app ships no src/ and esbuild+ * cannot read app.asar) or any source esbuild can reach (tests). `wasmDir` is+ * the engine runtime to copy. `platform` selects the target (default web).+ *+ * Every target's package is WEIGHED here, at the one point they all pass+ * through. The pipelines below return early for the mini-game, WeChat and+ * playable targets — measuring inside each of them would be four accountings+ * that drift, and a platform a project defines for itself would have none at+ * all. See sizeReport.ts for what is counted.+ */+export async function exportGame(opts: ExportGameOptions): Promise<ExportGameResult> {+ return attachSizeReport(await produceExport(opts), opts);+}++/**+ * The size limits an ad network's profile imposes, in the shape every target+ * states one.+ *+ * The playable profile predates this vocabulary and spells its cap+ * `maxBytes` + `limitNote`; a project's own network profile+ * (`.esengine/platforms/<id>.mjs`) is written against those names, so they stay+ * as the network's contract and are translated here — one conversion, rather+ * than a second shape for the rest of the editor to know about.+ */+function playableBudgets(profile: PlayableAdProfile | undefined): readonly SizeBudget[] {+ // The SAME fallback the playable pipeline picks when no network was chosen+ // (the strictest cap we know of), taken from the one place it is declared —+ // resolving it separately here is how the reported limit and the enforced one+ // drift apart.+ const resolved = profile ?? genericPlayableProfile;+ return [{ scope: 'deliverable', maxBytes: resolved.maxBytes, note: resolved.limitNote }];+}++/**+ * Weigh what the export produced, and judge it against the limits in force.+ *+ * Measures the PAYLOAD — for the desktop target the web build under `app/`, not+ * the Electron shell around it, which weighs the same for every game and would+ * bury the part a developer can act on. A failed export is not measured: half a+ * package has no meaningful size, and a number next to an error reads as if the+ * build were fine.+ */+async function attachSizeReport(result: ExportGameResult, opts: ExportGameOptions): Promise<ExportGameResult> {+ if (!result.ok) return result;+ // Packages written inside the output dir: each repackages content that is also+ // there loose, and the one a store/network takes is the deliverable the limit+ // applies to. The playable ships its single file as index.html unless a zip+ // was written for a zip-delivery network.+ const packages = [result.apkFile, result.aabFile, result.zipFile].filter((p): p is string => !!p);+ const deliverable = result.platform === 'playable'+ ? result.zipFile ?? path.join(result.outDir, 'index.html')+ : result.apkFile ?? result.aabFile;+ try {+ const size = await measureBuild({+ root: result.platform === 'desktop' ? path.join(result.outDir, 'app') : result.outDir,+ platform: result.platform,+ profileBudgets: opts.miniGameProfile?.sizeBudgets+ ?? (result.platform === 'playable' ? playableBudgets(opts.playableAdProfile) : undefined),+ projectMaxBytes: opts.sizeBudgetBytes,+ deliverable,+ packages,+ });+ return { ...result, size };+ } catch {+ return result; // measuring is reporting, never a reason to fail a build+ }+}++async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult> {const platform = opts.platform ?? 'web';const title = opts.title ?? 'Game';// One orientation for every target; default landscape (the engine's 1920×1080 Canvasdiff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex 339ae98a5..3a8321eb1 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -339,14 +339,12 @@ export async function exportPlayable(opts: {bytes = (await stat(zipFile)).size;}- // A full WASM engine + assets routinely exceeds what a network accepts, and each- // network caps differently — say which cap and where it comes from, so this reads- // as a fact to check rather than a number to trust.- if (bytes > adProfile.maxBytes) {- warnings.push(`playable is ~${(bytes / 1024 / 1024).toFixed(1)}MB, over the `- + `${(adProfile.maxBytes / 1024 / 1024).toFixed(1)}MB limit for ${adProfile.label} `- + `(${adProfile.limitNote}).`);- }+ // A full WASM engine + assets routinely exceeds what a network accepts, and this+ // export used to say so in an English sentence it composed itself. It no longer+ // does: `exportGame` weighs EVERY target against the limits in force and reports+ // the verdict structurally (the network's cap arrives there as a `SizeBudget`),+ // so the build dialog writes that sentence once, in the editor's language, for+ // the playable and the 4MB WeChat main package alike.if (adProfile.deliveryNote) warnings.push(adProfile.deliveryNote);return {diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 86129051b..77fd7b26b 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -1152,6 +1152,9 @@ ipcMain.handle(androidVersionCode: plat?.android?.versionCode,androidAppBundle: plat?.android?.appBundle,appIcon: manifest.packaging?.icon,+ // The project's own size ceiling for this target, when it declared one —+ // it replaces the platform's limit rather than adding to it.+ sizeBudgetBytes: manifest.packaging?.sizeBudget?.[opts?.platform ?? 'web'],// One project-wide orientation for every target: the explicit packaging// setting, else derived from the design resolution's aspect.orientation: resolveOrientation(manifest),diff --git a/desktop/electron/miniGameExportProfile.ts b/desktop/electron/miniGameExportProfile.tsindex 364f78ae0..45a8b53a3 100644--- a/desktop/electron/miniGameExportProfile.ts+++ b/desktop/electron/miniGameExportProfile.ts@@ -12,6 +12,7 @@* Adding a vendor = one profile object, not a fork of the pipeline.*/import { WECHAT_MODULE_BUILD_TARGET } from './sideModuleScan';+import type { SizeBudget } from '../src/project/sizeBudget';/*** A mini-game vendor's id. Open on purpose: the value is identity — the cook's@@ -105,6 +106,19 @@ export interface MiniGameExportProfile {/** Subpackage root prefix (files stage under `<subpackageDir>/<name>/`). */readonly subpackageDir: string;+ /**+ * What this host refuses to accept — the main package cap, the all-in cap.+ *+ * Every mini-game host has these limits and each states them differently, so+ * they are DATA like everything else here: a vendor the editor does not ship+ * declares its own and the build dialog reports it exactly as it reports+ * WeChat's. Built-in vendors leave this absent — their limits are the+ * platform's rule, not the export's, and live in+ * `src/project/sizeBudget.ts` where the settings UI can read them without+ * loading an export profile.+ */+ readonly sizeBudgets?: readonly SizeBudget[];+/*** Absolute path of a module whose DEFAULT EXPORT is the runtime* `MiniGameProfile` — the host global plus any capability this vendordiff --git a/desktop/electron/sizeReport.ts b/desktop/electron/sizeReport.tsnew file mode 100644index 000000000..2998c002f--- /dev/null+++ b/desktop/electron/sizeReport.ts@@ -0,0 +1,313 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What the finished build actually weighs.+ *+ * Measures the OUTPUT DIRECTORY rather than adding up what the cook+ * thought it wrote. Every target then gets a real number for free — the+ * engine runtime, the bundled scripts, the host page and the assets are+ * all just files on disk by the time this runs, so web, desktop, WeChat, a+ * project's own mini-game vendor and a native content payload are one code+ * path and cannot drift into per-target accounting.+ *+ * Where the bytes SIT is the part that matters, and the build already+ * knows: the AddressableManifest's `bundleMode` per group is the single+ * authored truth for delivery (`local` = in the main package, `lazy` = a+ * subpackage fetched on demand, `remote` = a CDN download that is not in+ * the package at all). This reads that same manifest, so the report agrees+ * with what the runtime will do by construction, and 30MB of hot-updatable+ * art is correctly reported as costing the package nothing. Anything on+ * disk the manifest does not claim — wasm, glue, bundles, index.html — is+ * part of what a player downloads before playing, so it counts as initial.+ *+ * Pure Node (fs). The arithmetic is separated from the walking so the+ * tests can check the accounting without a build on disk.+ */+import { readFile, stat, readdir } from 'node:fs/promises';+import path from 'node:path';+import type { ExportPlatform } from '../src/project/platforms';+import {+ evaluateSizeBudget, resolveSizeBudgets,+ type SizeBudget, type SizeVerdict,+} from '../src/project/sizeBudget';++/** Where a file sits in the delivery model — see the file header. */+export type SizeBucket = 'initial' | 'lazy' | 'remote';++/**+ * What a file IS, for the "who is eating my package" breakdown.+ *+ * Coarse on purpose: the answer a developer acts on is "textures are 60% of+ * this", and a finer taxonomy (which texture format, which script) is the+ * `largest` list's job.+ */+export type SizeKind = 'engine' | 'scripts' | 'texture' | 'audio' | 'video' | 'font' | 'scene' | 'data' | 'other';++/** One file in the finished build. */+export interface BuildSizeEntry {+ /** Path relative to the measured root, in POSIX form (the shipped shape). */+ path: string;+ bytes: number;+ bucket: SizeBucket;+ kind: SizeKind;+}++export interface KindTotal {+ kind: SizeKind;+ bytes: number;+ count: number;+}++/** The measurement, as the export result carries it and the build dialog draws it. */+export interface BuildSizeReport {+ /** Bytes a player downloads before the game is playable. */+ initialBytes: number;+ /** Bytes in subpackages, fetched when the game asks for that group. */+ lazyBytes: number;+ /** Bytes staged for a CDN — hot-updatable content, not in the package. */+ remoteBytes: number;+ /** `initial` + `lazy`: what the package weighs. Excludes `remote`. */+ packageBytes: number;+ /** Total on disk, including the CDN staging area. */+ totalBytes: number;+ fileCount: number;+ /** The single uploaded file, when the target has one (an ad network's+ * index.html/zip, an .apk). Absent for targets that ship a directory. */+ deliverableBytes?: number;+ /** That file's name, so the UI can say what was weighed. */+ deliverableName?: string;+ /** Largest first, capped at {@link LARGEST_FILES}. */+ largest: BuildSizeEntry[];+ /** Package composition (initial + lazy), largest kind first. Excludes remote:+ * the question this answers is what fills the PACKAGE. */+ byKind: KindTotal[];+ /** Every limit in force, judged. Empty when the target declares none and the+ * project set no budget. */+ verdicts: SizeVerdict[];+}++/** How many files the report names individually. Enough to find the offender,+ * short enough to read at a glance. */+export const LARGEST_FILES = 12;++/** Build artifacts that are not shipped content and must not be counted: the+ * intermediate flat manifest is deleted by the export, and sourcemaps are a+ * development aid the host never downloads. */+const NOT_SHIPPED = new Set(['assets.manifest.json']);+const isSourceMap = (rel: string): boolean => rel.endsWith('.map');++const EXT_KIND: Readonly<Record<string, SizeKind>> = {+ '.wasm': 'engine',+ '.png': 'texture', '.jpg': 'texture', '.jpeg': 'texture', '.webp': 'texture',+ '.ktx2': 'texture', '.basis': 'texture', '.astc': 'texture', '.pvr': 'texture',+ '.mp3': 'audio', '.ogg': 'audio', '.wav': 'audio', '.m4a': 'audio', '.aac': 'audio',+ '.mp4': 'video', '.esv': 'video', '.webm': 'video',+ '.ttf': 'font', '.otf': 'font', '.woff': 'font', '.woff2': 'font', '.fnt': 'font',+ '.js': 'scripts', '.mjs': 'scripts', '.cjs': 'scripts',+ '.json': 'data', '.txt': 'data', '.atlas': 'data', '.skel': 'data', '.tmj': 'data',+ '.esshader': 'data', '.eslocale': 'data', '.bin': 'data',+ '.html': 'other', '.css': 'other',+};++/**+ * What kind of thing a shipped file is.+ *+ * The wasm directory is engine whatever it holds: its JS is emscripten glue, not+ * game code, and reporting it as "scripts" would make every project look like it+ * shipped a megabyte of gameplay logic. Scenes are called out from the rest of+ * the JSON because "my scenes are huge" is a different fix than "my data is".+ */+export function kindOf(rel: string): SizeKind {+ const p = rel.toLowerCase();+ if (p === 'wasm' || p.startsWith('wasm/') || p.includes('/wasm/')) return 'engine';+ if (p.startsWith('scenes/') || p.endsWith('.esscene')) return 'scene';+ let ext = path.extname(p);+ // A mini-game packer that refuses an extension takes the file restaged as+ // `<name>.<ext>.bin` (miniGameExportProfile `binRestageExts`) — so a WeChat+ // package's textures arrive here as `.ktx2.bin`. They are still textures, and+ // a composition chart that filed them under "data" would send a developer+ // hunting through their JSON for megabytes that are in their art.+ if (ext === '.bin') {+ const inner = path.extname(p.slice(0, -'.bin'.length));+ if (inner) ext = inner;+ }+ return EXT_KIND[ext] ?? 'other';+}++/**+ * Delivery bucket per shipped path, read off the AddressableManifest the build+ * just wrote. Paths in the manifest are relative to the same root this measures,+ * so the lookup is direct.+ *+ * A build with no manifest (the playable's single inlined file, a legacy cook)+ * yields an empty index — every file then counts as initial, which is exactly+ * right for a target that has no subpackages.+ */+export function bucketIndexFrom(manifest: unknown): Map<string, SizeBucket> {+ const index = new Map<string, SizeBucket>();+ const groups = (manifest as { groups?: Record<string, { bundleMode?: string; assets?: Record<string, { path?: string }> }> } | null)?.groups;+ if (!groups) return index;+ for (const group of Object.values(groups)) {+ const bucket: SizeBucket = group?.bundleMode === 'lazy' ? 'lazy' : group?.bundleMode === 'remote' ? 'remote' : 'initial';+ for (const asset of Object.values(group?.assets ?? {})) {+ if (asset?.path) index.set(normalizeRel(asset.path), bucket);+ }+ }+ return index;+}++const normalizeRel = (p: string): string => p.replace(/\\/g, '/').replace(/^\.?\//, '');++/**+ * Turn measured files into the report. Pure — the tests drive it with a list of+ * paths and sizes, no build required.+ */+export function summarizeBuildFiles(+ files: readonly { path: string; bytes: number }[],+ opts: {+ buckets?: Map<string, SizeBucket>;+ 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 });+ totalBytes += file.bytes;+ if (bucket === 'remote') remoteBytes += file.bytes;+ else {+ if (bucket === 'lazy') lazyBytes += file.bytes;+ else initialBytes += file.bytes;+ // Composition answers "what fills the package", so CDN content is out.+ const total = kinds.get(kind) ?? { kind, bytes: 0, count: 0 };+ total.bytes += file.bytes;+ total.count++;+ kinds.set(kind, total);+ }+ }++ const packageBytes = initialBytes + lazyBytes;+ const report: BuildSizeReport = {+ initialBytes, lazyBytes, remoteBytes, packageBytes, totalBytes,+ fileCount: entries.length,+ largest: [...entries].sort((a, b) => b.bytes - a.bytes).slice(0, LARGEST_FILES),+ byKind: [...kinds.values()].sort((a, b) => b.bytes - a.bytes),+ verdicts: [],+ };+ if (opts.deliverableBytes != null) {+ report.deliverableBytes = opts.deliverableBytes;+ if (opts.deliverableName) report.deliverableName = opts.deliverableName;+ }+ report.verdicts = judge(report, opts.budgets ?? []);+ return report;+}++/**+ * Judge the report against each limit in force.+ *+ * A `deliverable` limit on a build that produced no single upload file is+ * SKIPPED rather than judged against zero: an Android export that stopped at the+ * content payload has not yet made the thing the limit applies to, and reporting+ * it as comfortably under would be a lie of the most reassuring kind.+ */+function judge(report: BuildSizeReport, budgets: readonly SizeBudget[]): SizeVerdict[] {+ const verdicts: SizeVerdict[] = [];+ for (const budget of budgets) {+ const measured = budget.scope === 'initial' ? report.initialBytes+ : budget.scope === 'total' ? report.packageBytes+ : report.deliverableBytes;+ if (measured == null) continue;+ verdicts.push(evaluateSizeBudget(measured, budget));+ }+ return verdicts;+}++/** Every file under `root`, with its size, relative to `root`. */+export async function collectBuildFiles(root: string): Promise<{ path: string; bytes: number }[]> {+ const out: { path: string; bytes: number }[] = [];+ const walk = async (dir: string, prefix: string): Promise<void> => {+ let items;+ try {+ items = await readdir(dir, { withFileTypes: true });+ } catch {+ return; // vanished mid-walk / unreadable — a size report never fails a build+ }+ for (const item of items) {+ const rel = prefix ? `${prefix}/${item.name}` : item.name;+ const abs = path.join(dir, item.name);+ if (item.isDirectory()) await walk(abs, rel);+ else if (item.isFile()) {+ try {+ out.push({ path: rel, bytes: (await stat(abs)).size });+ } catch { /* same */ }+ }+ }+ };+ await walk(root, '');+ return out;+}++/**+ * Measure a finished build.+ *+ * `root` is what shipped — the payload dir, which for the desktop target is the+ * web build nested under `app/` rather than the Electron shell around it, since+ * the shell is the same weight for every game and tells a developer nothing.+ */+export async function measureBuild(opts: {+ root: string;+ platform: ExportPlatform;+ /** Limits the vendor / ad-network profile driving this export declares. */+ profileBudgets?: readonly SizeBudget[];+ /** `packaging.sizeBudget[platform]`, in bytes. */+ projectMaxBytes?: number;+ /** Absolute path to the single uploaded file, when the target makes one. */+ deliverable?: string;+ /**+ * Absolute paths to packages written INSIDE `root` — the .apk, the .aab, the+ * playable's .zip.+ *+ * Each is a repackaging of content that also sits beside it as loose files, so+ * counting both would double every byte and report a build at twice its+ * weight. They are measured on their own (as the deliverable) and left out of+ * the directory totals.+ */+ packages?: readonly string[];+}): Promise<BuildSizeReport> {+ const excluded = new Set<string>();+ for (const file of [...(opts.packages ?? []), ...(opts.deliverable ? [opts.deliverable] : [])]) {+ const rel = path.relative(opts.root, file);+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) excluded.add(normalizeRel(rel));+ }+ const files = (await collectBuildFiles(opts.root)).filter((f) => !excluded.has(normalizeRel(f.path)));+ let manifest: unknown = null;+ try {+ manifest = JSON.parse(await readFile(path.join(opts.root, 'asset-manifest.json'), 'utf8'));+ } catch { /* no addressable manifest → everything is initial (see bucketIndexFrom) */ }++ let deliverableBytes: number | undefined;+ if (opts.deliverable) {+ try {+ deliverableBytes = (await stat(opts.deliverable)).size;+ } catch { /* not produced (no template installed) — the limit is then skipped */ }+ }++ return summarizeBuildFiles(files, {+ buckets: bucketIndexFrom(manifest),+ budgets: resolveSizeBudgets(opts.platform, {+ profile: opts.profileBudgets,+ projectMaxBytes: opts.projectMaxBytes,+ }),+ deliverableBytes,+ deliverableName: opts.deliverable ? path.basename(opts.deliverable) : undefined,+ });+}diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 67fbcab94..5bffa8e63 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -30,6 +30,9 @@ import {} from 'lucide-react';import type { ExportPlatform, NativeToolchain, PlatformPrereq } from '@/project/platforms';import type { PlayableNetworkOption } from '../../electron/platformCatalog';+import type { BuildSizeReport } from '../../electron/sizeReport';+import { formatBytes } from '@/project/sizeBudget';+import { BuildSizePanel } from '@/components/BuildSizePanel';import { Modal } from '@/components/Modal';import { Segmented } from '@/components/Segmented';import { Select } from '@/components/Select';@@ -61,6 +64,8 @@ interface Result {apkFile?: string;/** Android: the App Bundle, when the project asked for one. */aabFile?: string;+ /** What the package weighs, measured by the export (electron/sizeReport.ts). */+ size?: BuildSizeReport;}/** Nav groupings. Order here is the order they appear. */@@ -155,7 +160,22 @@ const BUILTIN_PLATFORMS: PlatformDef[] = [},];-const mb = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(1)} MB`;++/**+ * The size-budget field, both directions.+ *+ * Entered in MB — the unit every platform states its cap in — and stored in+ * bytes, so nothing downstream has to know which unit a limit was written in. A+ * blank or unreadable field is not an error but a value: no budget, and the+ * target goes back to being judged against its own limit.+ */+const BYTES_PER_MB = 1024 * 1024;+const bytesToMb = (bytes: number | undefined): string =>+ bytes && bytes > 0 ? String(+(bytes / BYTES_PER_MB).toFixed(2)) : '';+const mbToBytes = (text: string): number | undefined => {+ const mb = Number.parseFloat(text.trim());+ return Number.isFinite(mb) && mb > 0 ? Math.round(mb * BYTES_PER_MB) : undefined;+};/** Localized names for the native toolchain pieces the main process probes. */const TOOLCHAIN_TEXT: Record<NativeToolchain, string> = {@@ -208,6 +228,10 @@ export function BuildDialog() {const [platform, setPlatform] = useState<Platform>(initialPlatform);const [config, setConfig] = useState<Config>(saved.config ?? 'shipping');const [outDir, setOutDir] = useState(saved.outDir?.[initialPlatform] ?? initialDef.defaultOut);+ // The project's own ceiling for the selected target, edited in MB. Per platform+ // like the output dir, since a WeChat build and a desktop build are not judged+ // by the same number.+ const [sizeBudgetMb, setSizeBudgetMb] = useState(bytesToMb(saved.sizeBudget?.[initialPlatform]));const [openFolder, setOpenFolder] = useState(saved.openFolder ?? true);const [sourceMaps, setSourceMaps] = useState(saved.sourceMaps ?? false);// Publish-layer optimization switch: honor each asset's Import Settings, or skip@@ -359,6 +383,7 @@ export function BuildDialog() {setResult(null);// Restore this platform's saved output, else its suggested default.setOutDir(saved.outDir?.[p.id] ?? (p.id === 'playable' ? playableOut(adNetwork) : p.defaultOut));+ setSizeBudgetMb(bytesToMb(saved.sizeBudget?.[p.id]));};const startCreate = () => {@@ -709,7 +734,7 @@ export function BuildDialog() {? <><Loader2 size={12} className="spin" /> {downloading.total > 0? t('build.downloadingTemplatePct', {pct: String(Math.round((downloading.received / downloading.total) * 100)),- size: mb(downloading.total),+ size: formatBytes(downloading.total),}): t('build.downloadingTemplate')}</>: <><Package size={12} /> {t('build.downloadTemplate')}</>}@@ -901,6 +926,21 @@ export function BuildDialog() {onBlur={() => void ProjectStore.setActiveProfileRemoteRoot(cdnRoot.trim())}/></div>+ {/* The project's own ceiling for this target, in MB — entered in the+ unit every platform states its limit in, stored in bytes. Blank+ leaves the target judged against its own limit, if it has one. */}+ <div className="build__row">+ <span className="build__label" title={t('build.sizeBudgetHint')}>{t('build.sizeBudget')}</span>+ <input+ value={sizeBudgetMb}+ spellCheck={false}+ inputMode="decimal"+ placeholder={t('build.sizeBudgetPlaceholder')}+ title={t('build.sizeBudgetHint')}+ onChange={(e) => setSizeBudgetMb(e.target.value)}+ onBlur={() => void ProjectStore.setPackaging({ sizeBudget: { [platform]: mbToBytes(sizeBudgetMb) } })}+ />+ </div>{def.sourceMaps && (<label className="build__opt"><input type="checkbox" checked={sourceMaps} onChange={(e) => setSourceMaps(e.target.checked)} />@@ -937,8 +977,9 @@ export function BuildDialog() {{phase === 'done' && result && (<><span className="build__status-line selectable">- <CheckCircle2 size={14} /> {t('build.packagedSummary', { count: result.included, size: result.bytes ? ` · ${mb(result.bytes)}` : '', out: result.outDir })}+ <CheckCircle2 size={14} /> {t('build.packagedSummary', { count: result.included, size: result.bytes ? ` · ${formatBytes(result.bytes)}` : '', out: result.outDir })}</span>+ {result.size && <BuildSizePanel report={result.size} />}<div className="build__next selectable">{result.xcodeProject? t('build.next.iosProject')diff --git a/desktop/src/components/BuildSizePanel.tsx b/desktop/src/components/BuildSizePanel.tsxnew file mode 100644index 000000000..56a9ab6a2--- /dev/null+++ b/desktop/src/components/BuildSizePanel.tsx@@ -0,0 +1,150 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BuildSizePanel.tsx — what the package weighs, after a build.+ *+ * Answers the three questions in the order they get asked: does it fit,+ * what is in it, and which file is the problem. The limit comes first+ * because it is the only one with a wrong answer.+ *+ * Everything here is DRAWN, not decided: the main process measured the+ * build and judged it against the limits in force (see+ * electron/sizeReport.ts), and this writes those verdicts as sentences in+ * the editor's language — the split the export pipeline has always used,+ * where the process with no locale reports facts and the dialog says them.+ * A platform's own note ("WeChat caps a mini-game's main package at 4MB")+ * is quoted as it was written, so it can be checked against that+ * platform's docs rather than trusted.+ */+import { useState } from 'react';+import { ChevronRight } from 'lucide-react';+import type { BuildSizeReport, SizeBucket, SizeKind } from '../../electron/sizeReport';+import type { BudgetScope, SizeVerdict } from '@/project/sizeBudget';+import { formatBytes, PROJECT_BUDGET_NOTE } from '@/project/sizeBudget';+import { t } from '@/i18n';++const SCOPE_LABEL: Record<BudgetScope, () => string> = {+ initial: () => t('size.scope.initial'),+ total: () => t('size.scope.total'),+ deliverable: () => t('size.scope.deliverable'),+};++const KIND_LABEL: Record<SizeKind, () => string> = {+ engine: () => t('size.kind.engine'),+ scripts: () => t('size.kind.scripts'),+ texture: () => t('size.kind.texture'),+ audio: () => t('size.kind.audio'),+ video: () => t('size.kind.video'),+ font: () => t('size.kind.font'),+ scene: () => t('size.kind.scene'),+ data: () => t('size.kind.data'),+ other: () => t('size.kind.other'),+};++const BUCKET_LABEL: Record<SizeBucket, () => string> = {+ initial: () => t('size.bucket.initial'),+ lazy: () => t('size.bucket.lazy'),+ remote: () => t('size.bucket.remote'),+};++/** One limit, as a meter. Over-budget fills past the mark and says by how much —+ * a bar pinned at 100% would hide the difference between 1% over and double. */+function BudgetMeter({ verdict }: { verdict: SizeVerdict }): React.ReactElement {+ const { budget, measuredBytes, ratio, status } = verdict;+ return (+ <div className={`size__budget is-${status}`}>+ <div className="size__budget-head">+ <span className="size__budget-scope">{SCOPE_LABEL[budget.scope]()}</span>+ <span className="size__budget-num selectable">+ {t('size.ofLimit', { used: formatBytes(measuredBytes), max: formatBytes(budget.maxBytes) })}+ </span>+ </div>+ <div className="size__meter">+ <div className="size__meter-fill" style={{ width: `${Math.min(100, ratio * 100)}%` }} />+ </div>+ <div className="size__budget-note selectable">+ {status === 'over'+ ? t('size.over', { by: formatBytes(measuredBytes - budget.maxBytes) })+ : status === 'near' ? t('size.near', { pct: Math.round(ratio * 100) }) : null}+ {status !== 'ok' ? ' · ' : null}+ {budget.note === PROJECT_BUDGET_NOTE ? t('size.projectBudget') : budget.note}+ </div>+ </div>+ );+}++export function BuildSizePanel({ report }: { report: BuildSizeReport }): React.ReactElement {+ const [open, setOpen] = useState(false);+ // The composition bar is of the PACKAGE: CDN content is real, and is reported+ // beside it, but it is not what fills the thing being shipped.+ const total = report.packageBytes || 1;+ const buckets: { bucket: SizeBucket; bytes: number }[] = [+ { bucket: 'initial', bytes: report.initialBytes },+ { bucket: 'lazy', bytes: report.lazyBytes },+ { bucket: 'remote', bytes: report.remoteBytes },+ ];++ return (+ <div className="size">+ {report.verdicts.map((v, i) => <BudgetMeter key={i} verdict={v} />)}++ <div className="size__buckets">+ {buckets.filter((b) => b.bytes > 0).map((b) => (+ <span key={b.bucket} className={`size__bucket is-${b.bucket}`}>+ <span className="size__bucket-label">{BUCKET_LABEL[b.bucket]()}</span>+ <span className="size__bucket-bytes selectable">{formatBytes(b.bytes)}</span>+ </span>+ ))}+ {report.deliverableBytes != null && report.deliverableName && (+ <span className="size__bucket is-deliverable">+ <span className="size__bucket-label">{report.deliverableName}</span>+ <span className="size__bucket-bytes selectable">{formatBytes(report.deliverableBytes)}</span>+ </span>+ )}+ </div>++ {report.byKind.length > 0 && (+ <>+ <div className="size__bar" role="img" aria-label={t('size.composition')}>+ {report.byKind.map((k) => (+ <span+ key={k.kind}+ className={`size__seg is-${k.kind}`}+ style={{ width: `${(k.bytes / total) * 100}%` }}+ title={`${KIND_LABEL[k.kind]()} · ${formatBytes(k.bytes)}`}+ />+ ))}+ </div>+ <div className="size__legend">+ {report.byKind.map((k) => (+ <span key={k.kind} className="size__legend-item">+ <i className={`size__dot is-${k.kind}`} />+ {KIND_LABEL[k.kind]()}+ <span className="size__legend-bytes selectable">{formatBytes(k.bytes)}</span>+ </span>+ ))}+ </div>+ </>+ )}++ {report.largest.length > 0 && (+ <div className="size__files">+ <button type="button" className="size__disclose" onClick={() => setOpen(!open)} aria-expanded={open}>+ <ChevronRight size={12} className={open ? 'size__chev is-open' : 'size__chev'} />+ {t('size.largest', { count: report.fileCount })}+ </button>+ {open && (+ <ol className="size__file-list selectable">+ {report.largest.map((f) => (+ <li key={f.path} className={`size__file is-${f.bucket}`}>+ <span className="size__file-path">{f.path}</span>+ <span className="size__file-bytes">{formatBytes(f.bytes)}</span>+ </li>+ ))}+ </ol>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex cc82a8f9d..d7b08fbda 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -267,6 +267,37 @@ export const projectMessages = defineMessages({'build.warnings': { en: '{count} warning(s): {first}', zh: '{count} 个警告:{first}' },'build.noProjectOpen': { en: 'no project open', zh: '没有打开的项目' },+ // — What the package weighs (BuildSizePanel). A limit's own wording (a+ // platform's rule) is quoted from the profile, not translated here. —+ 'size.scope.initial': { en: 'Initial download', zh: '首包' },+ 'size.scope.total': { en: 'Package total', zh: '整包' },+ 'size.scope.deliverable': { en: 'Uploaded file', zh: '上传文件' },+ 'size.ofLimit': { en: '{used} of {max}', zh: '{used} / {max}' },+ 'size.over': { en: '{by} over the limit', zh: '超出上限 {by}' },+ 'size.near': { en: '{pct}% of the limit', zh: '已用上限的 {pct}%' },+ 'size.projectBudget': { en: "this project's own budget", zh: '本项目自定的体积预算' },+ 'size.bucket.initial': { en: 'Initial', zh: '首包' },+ 'size.bucket.lazy': { en: 'On demand', zh: '按需分包' },+ 'size.bucket.remote': { en: 'CDN (not packaged)', zh: 'CDN(不进包)' },+ 'size.composition': { en: 'Package composition', zh: '包体构成' },+ 'size.largest': { en: 'Largest files ({count} total)', zh: '最大的文件(共 {count} 个)' },+ 'size.kind.engine': { en: 'Engine', zh: '引擎' },+ 'size.kind.scripts': { en: 'Scripts', zh: '脚本' },+ 'size.kind.texture': { en: 'Textures', zh: '纹理' },+ 'size.kind.audio': { en: 'Audio', zh: '音频' },+ 'size.kind.video': { en: 'Video', zh: '视频' },+ 'size.kind.font': { en: 'Fonts', zh: '字体' },+ 'size.kind.scene': { en: 'Scenes', zh: '场景' },+ 'size.kind.data': { en: 'Data', zh: '数据' },+ 'size.kind.other': { en: 'Other', zh: '其他' },+ // — Packaging settings: the project's own ceiling for this target —+ 'build.sizeBudget': { en: 'Size budget', zh: '体积预算' },+ 'build.sizeBudgetPlaceholder': { en: 'MB (blank = the platform’s own limit)', zh: 'MB(留空 = 平台自身上限)' },+ 'build.sizeBudgetHint': {+ en: 'Judge this target against your own ceiling instead of the platform’s.',+ zh: '用你自己的上限来判定这个目标,而不是平台的。',+ },+// — Project-level feedback toasts (ProjectStore) —'proj.openFailed': { en: 'Could not open project: {message}', zh: '无法打开项目:{message}' },'proj.createFailed': { en: 'Could not create project: {message}', zh: '无法创建项目:{message}' },diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 725594e39..d43826b91 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -14,6 +14,7 @@ import { ProjectStore } from '@/project/ProjectStore';import { Toasts } from '@/store/Toasts';import { useSelection } from '@/store/selectionStore';import { IMAGE_RE, baseName, TYPE_CODE } from '@/project/assetMeta';+import { formatBytes } from '@/project/sizeBudget';import { openAssetOfType } from '@/project/assetOpen';import { assetTypeRegistry } from '@/project/assetTypes';import { contributedContextRows } from '@/plugins/contextMenus';@@ -128,18 +129,6 @@ function RenameInput({);}-function formatBytes(n: number): string {- if (n < 1024) return `${n} B`;- const units = ['KB', 'MB', 'GB'];- let v = n;- let i = -1;- do {- v /= 1024;- i++;- } while (v >= 1024 && i < units.length - 1);- return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;-}-function TipRow({ k, v, mono }: { k: string; v: string; mono?: boolean }) {return (<div className="cb-tip-row">diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex cb887670f..21380fbd2 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -58,6 +58,7 @@ import { fsRefresh } from '@/project/fsRefresh';import { Toasts } from '@/store/Toasts';import { baseName, IMAGE_RE } from '@/project/assetMeta';import { BUILTIN_PLATFORMS, type BuiltinPlatform } from '@/project/platforms';+import { formatBytes } from '@/project/sizeBudget';import { revealAsset } from '@/project/assetReveal';import { useSelection } from '@/store/selectionStore';import { usePrefabConflicts } from '@/store/prefabConflicts';@@ -3324,17 +3325,6 @@ function AnimClipAssetInspector({ path }: { path: string }) {);}-function formatBytes(n: number): string {- if (n < 1024) return `${n} B`;- const units = ['KB', 'MB', 'GB'];- let v = n;- let i = -1;- do {- v /= 1024;- i++;- } while (v >= 1024 && i < units.length - 1);- return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;-}function MetaRow({ k, v, mono }: { k: string; v: string; mono?: boolean }) {return (diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 7735b1f95..bf53d8f81 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1998,6 +1998,16 @@ class ProjectStoreImpl {...patch,outDir: { ...st.packaging?.outDir, ...patch.outDir },};+ // Per-platform size ceilings merge the way outDir does, with one difference:+ // clearing the field means the target goes back to being judged against its+ // OWN limit, so an entry patched to undefined is removed rather than+ // persisted, and a map with nothing left in it is dropped entirely.+ const sizeBudget: Record<string, number | undefined> = { ...st.packaging?.sizeBudget, ...patch.sizeBudget };+ for (const [target, bytes] of Object.entries(sizeBudget)) {+ if (bytes == null || !(bytes > 0)) delete sizeBudget[target];+ }+ if (Object.keys(sizeBudget).length > 0) packaging.sizeBudget = sizeBudget as ProjectPackaging['sizeBudget'];+ else delete packaging.sizeBudget;this.store.setState({ project: { ...st, packaging } });await this.patchManifest((raw) => {raw.packaging = packaging;diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 085aa6c41..e68bf545e 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -239,6 +239,17 @@ export interface ProjectPackaging {excludeScenes?: string[];/** Per-platform output-dir overrides (else the per-platform default). */outDir?: Partial<Record<ExportPlatform, string>>;+ /**+ * Per-platform package-size ceiling, in BYTES — what the build is judged+ * against instead of the limit the target declares for itself.+ *+ * Two teams need this for opposite reasons: one ships well under WeChat's 4MB+ * and wants to be told before it creeps up, the other targets a host whose cap+ * we do not know. Both are more authoritative about their own build than a+ * built-in number is. Absent ⇒ the target's own limit, if it has one (see+ * `sizeBudget.ts`).+ */+ sizeBudget?: Partial<Record<ExportPlatform, number>>;/*** The application identifier (reverse-DNS) every installable target needs: the* Android manifest package, the iOS bundle id, the Electron appId. One project@@ -520,6 +531,18 @@ export function parseManifest(raw: unknown): ProjectManifest {}if (Object.keys(out).length > 0) pkg.outDir = out;}+ // Per-platform size ceilings, keyed the same way the output dirs are. A+ // non-positive or unreadable value is DROPPED rather than carried as zero:+ // the field's absence means "judge this target by its own limit", and a 0+ // that survived would mean every build is infinitely over budget.+ if (p.sizeBudget && typeof p.sizeBudget === 'object') {+ const sb = p.sizeBudget as Record<string, unknown>;+ const budgets: NonNullable<ProjectPackaging['sizeBudget']> = {};+ for (const [k, v] of Object.entries(sb)) {+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) budgets[normalizePlatform(k)] = v;+ }+ if (Object.keys(budgets).length > 0) pkg.sizeBudget = budgets;+ }if (p.platforms && typeof p.platforms === 'object') {const pl = p.platforms as Record<string, unknown>;const platforms: NonNullable<ProjectPackaging['platforms']> = {};diff --git a/desktop/src/project/sizeBudget.ts b/desktop/src/project/sizeBudget.tsnew file mode 100644index 000000000..30f29eb2f--- /dev/null+++ b/desktop/src/project/sizeBudget.ts@@ -0,0 +1,173 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a packaging target's size limit is, and what it measures.+ *+ * A shipped game is refused by a store, a mini-game host or an ad network+ * for being too big far more often than for being wrong, and every target+ * counts differently: WeChat caps the MAIN package and, separately, the+ * sum of every subpackage; an ad network caps the one FILE it takes an+ * upload of. So a limit is not a number — it is a number, WHAT it counts,+ * and WHERE it comes from, and all three travel together.+ *+ * This vocabulary was already here, but it lived on one branch: the+ * playable export carried `maxBytes` + `limitNote` per ad network and+ * wrote its own warning sentence, while WeChat's 4MB main package — the+ * harder limit, on the platform this engine targets first — had nothing.+ * The shape that worked for one network is the shape every target gets.+ *+ * A budget is DATA, so it rides the same profile a vendor/network already+ * supplies (`MiniGameExportProfile`, `PlayableAdProfile`): adding a target+ * with a limit of its own stays one profile object, not a branch. Nothing+ * here reads the filesystem or React — the export measures, the build+ * dialog renders, and the tests check the arithmetic, all off this file.+ *+ * Deliberately absent: a made-up limit for targets that have none. The web+ * and the desktop shell impose no cap, so they get an empty list and the+ * project may declare its own budget — an invented "recommended" ceiling+ * would be a number a developer then designs around, sourced from us.+ */+import type { ExportPlatform } from './platforms';++/**+ * What a limit counts. The distinction is the whole point: 30MB of art behind a+ * lazy subpackage breaks a WeChat main-package limit not at all, and breaks an+ * ad network's single-file limit completely.+ */+export type BudgetScope =+ /** Bytes needed before the game can be played at all: the host page, the+ * engine runtime, the scripts, and the assets in `local` groups. What a+ * mini-game calls the main package. */+ | 'initial'+ /** Every byte inside the package — `initial` plus lazily-loaded subpackages.+ * Excludes `remote` groups, which are downloaded from a CDN and are not part+ * of what the host stores. */+ | 'total'+ /** The single file that gets uploaded: an ad network's index.html or archive,+ * a store's .apk. */+ | 'deliverable';++/** One limit a target imposes. */+export interface SizeBudget {+ readonly scope: BudgetScope;+ readonly maxBytes: number;+ /**+ * Where the number comes from, quoted verbatim wherever the limit is+ * reported — so a developer checks it against the platform's current docs+ * rather than trusting us. Left in the platform's own words (English) on+ * purpose: it cites an external rule, and a translation is a paraphrase of+ * someone else's contract.+ */+ readonly note: string;+}++/** Bytes per binary megabyte — the unit every platform states its cap in. */+const MB = 1024 * 1024;++/**+ * The limits a built-in target imposes, before any profile or project override.+ *+ * Only limits we can cite. `wechat` is here rather than on the WeChat profile+ * because it is the platform's rule, not the export's — a project-authored+ * mini-game profile for another vendor declares its own (see+ * {@link resolveSizeBudgets}).+ */+export function builtinSizeBudgets(platform: ExportPlatform): readonly SizeBudget[] {+ if (platform === 'wechat') return WECHAT_BUDGETS;+ return NO_BUDGETS;+}++const NO_BUDGETS: readonly SizeBudget[] = [];++const WECHAT_BUDGETS: readonly SizeBudget[] = [+ { scope: 'initial', maxBytes: 4 * MB, note: "WeChat caps a mini-game's main package at 4MB" },+ { scope: 'total', maxBytes: 20 * MB, note: 'WeChat caps a mini-game at 20MB across all subpackages' },+];++/**+ * The limits in force for one export, from the three places one can come from.+ *+ * Precedence is deliberate. A PROFILE limit replaces the built-in for the same+ * scope, because a vendor/network profile is more specific than the platform+ * default (a playable's cap is the chosen network's, not "playables in+ * general"). A PROJECT budget replaces both, because a team that ships under a+ * stricter self-imposed ceiling — or that knows their host raised the cap — is+ * the authority on their own build, and an engine that argued with them would+ * just be wrong on a schedule.+ */+export function resolveSizeBudgets(+ platform: ExportPlatform,+ opts?: {+ /** Limits declared by the vendor / ad-network profile driving this export. */+ profile?: readonly SizeBudget[];+ /** `packaging.sizeBudget[platform]` — bytes, replacing the primary limit. */+ projectMaxBytes?: number;+ },+): readonly SizeBudget[] {+ const byScope = new Map<BudgetScope, SizeBudget>();+ for (const b of builtinSizeBudgets(platform)) byScope.set(b.scope, b);+ for (const b of opts?.profile ?? NO_BUDGETS) byScope.set(b.scope, b);+ const budgets = [...byScope.values()];++ const override = opts?.projectMaxBytes;+ if (override != null && override > 0) {+ // Replaces the PRIMARY limit — the first one, which is the scope this+ // target is actually judged on (`initial` for a package, `deliverable`+ // for an upload). A project that sets a budget for a target with no+ // built-in limit gets `initial`: the bytes before play is the only+ // measure that means the same thing on every target.+ const primary = budgets[0]?.scope ?? 'initial';+ const at = budgets.findIndex((b) => b.scope === primary);+ const declared: SizeBudget = { scope: primary, maxBytes: override, note: PROJECT_BUDGET_NOTE };+ if (at >= 0) budgets[at] = declared;+ else budgets.unshift(declared);+ }+ return budgets;+}++/** Marks a limit as the project's own, so the UI attributes it rather than+ * quoting a platform rule that did not say this. */+export const PROJECT_BUDGET_NOTE = 'project budget';++/** How one measurement came out against one limit. */+export interface SizeVerdict {+ readonly budget: SizeBudget;+ /** Bytes measured for {@link SizeBudget.scope}. */+ readonly measuredBytes: number;+ /** Measured over the limit — 1 is exactly at it. Drives the meter, and is+ * what "close to the limit" is judged on. */+ readonly ratio: number;+ readonly status: 'ok' | 'near' | 'over';+}++/** Fraction of a limit at which a build is called `near` — close enough that the+ * next art pass breaks it, far enough that saying so is not noise. */+export const NEAR_LIMIT_RATIO = 0.9;++/** Judge one measurement against one limit. */+export function evaluateSizeBudget(measuredBytes: number, budget: SizeBudget): SizeVerdict {+ const ratio = budget.maxBytes > 0 ? measuredBytes / budget.maxBytes : 0;+ const status = ratio > 1 ? 'over' : ratio >= NEAR_LIMIT_RATIO ? 'near' : 'ok';+ return { budget, measuredBytes, ratio, status };+}++/**+ * Human byte size — ONE spelling for the whole editor.+ *+ * Three copies of this used to exist (the content browser, the inspector, and+ * the build dialog's MB-only variant), so the same file could be "1.4 MB" in one+ * panel and "1.4 MB" in another only by coincidence. Binary units, because every+ * limit this file carries is stated in them.+ */+export function formatBytes(n: number): string {+ if (!Number.isFinite(n) || n < 0) return '—';+ if (n < 1024) return `${Math.round(n)} B`;+ const units = ['KB', 'MB', 'GB'];+ let v = n;+ let i = -1;+ do {+ v /= 1024;+ i++;+ } while (v >= 1024 && i < units.length - 1);+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;+}diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.cssindex 5d221d001..43f97aa26 100644--- a/desktop/src/theme/menus.css+++ b/desktop/src/theme/menus.css@@ -387,6 +387,61 @@.build__adv.open .chev { transform: rotate(90deg); }.build__adv-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 0 2px 12px; }+/* — What the package weighs (BuildSizePanel), after a build. —+ Composition reuses the CATEGORY identity colors, so a texture is the same+ purple here that the Sprite component header is: one color vocabulary for+ "which domain is this", read on a bar instead of on a header. */+.size { display: flex; flex-direction: column; gap: 10px; }++.size__budget { display: flex; flex-direction: column; gap: 5px; }+.size__budget-head { display: flex; align-items: baseline; gap: 8px; }+.size__budget-scope { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); }+.size__budget-num { margin-left: auto; font-family: var(--mono); font-size: var(--fs-xs); color: var(--text-dim); }+.size__budget.is-near .size__budget-num { color: var(--warn); }+.size__budget.is-over .size__budget-num { color: var(--error); }+.size__budget-note { font-size: var(--fs-2xs); line-height: 1.5; color: var(--text-mute); overflow-wrap: anywhere; }+.size__meter { height: 6px; border-radius: 3px; background: var(--inset); overflow: hidden; }+.size__meter-fill { height: 100%; border-radius: 3px; background: var(--run); transition: width var(--t) var(--e-out); }+.size__budget.is-near .size__meter-fill { background: var(--warn); }+.size__budget.is-over .size__meter-fill { background: var(--error); }++.size__buckets { display: flex; flex-wrap: wrap; gap: 6px; }+.size__bucket { display: inline-flex; align-items: baseline; gap: 6px; padding: 3px 8px; border-radius: var(--r-xs); background: var(--srf-3); border: 1px solid var(--line-soft); }+.size__bucket-label { font-size: var(--fs-2xs); color: var(--text-mute); }+.size__bucket-bytes { font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-dim); }+/* CDN content is not in the package — stated, but visibly set apart from what is. */+.size__bucket.is-remote { background: none; border-style: dashed; }+.size__bucket.is-deliverable .size__bucket-label { font-family: var(--mono); }++.size__bar { display: flex; height: 8px; border-radius: var(--r-xs); overflow: hidden; background: var(--inset); }+.size__seg { height: 100%; min-width: 1px; }+.size__legend { display: flex; flex-wrap: wrap; gap: 4px 12px; }+.size__legend-item { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-mute); }+.size__legend-bytes { font-family: var(--mono); color: var(--text-dim); }+.size__dot { width: 7px; height: 7px; border-radius: 2px; flex-shrink: 0; }++.size__seg.is-engine, .size__dot.is-engine { background: var(--srf-6); }+.size__seg.is-scripts, .size__dot.is-scripts { background: var(--cat-script); }+.size__seg.is-texture, .size__dot.is-texture { background: var(--cat-render); }+.size__seg.is-audio, .size__dot.is-audio { background: var(--cat-audio); }+.size__seg.is-video, .size__dot.is-video { background: var(--gizmo-particle); }+.size__seg.is-font, .size__dot.is-font { background: var(--cat-collision); }+.size__seg.is-scene, .size__dot.is-scene { background: var(--cat-transform); }+.size__seg.is-data, .size__dot.is-data { background: var(--cat-physics); }+.size__seg.is-other, .size__dot.is-other { background: var(--text-mute); }++.size__files { display: flex; flex-direction: column; gap: 4px; }+.size__disclose { display: inline-flex; align-items: center; gap: 5px; align-self: flex-start; font-size: var(--fs-2xs); color: var(--text-mute); background: none; border: none; cursor: pointer; padding: 0; }+.size__disclose:hover { color: var(--text); }+.size__chev { transition: transform var(--t-fast); }+.size__chev.is-open { transform: rotate(90deg); }+.size__file-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 1px; max-height: 148px; overflow-y: auto; }+.size__file { display: flex; align-items: baseline; gap: 10px; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }+.size__file-path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; }+.size__file-bytes { flex-shrink: 0; color: var(--text-dim); }+/* A file that costs the package nothing reads as an aside, not as an offender. */+.size__file.is-remote { opacity: 0.55; }+/* "compression lives in Import Settings" pointer + footer scene/target summary. */.build__hint { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-mute); }.build__footsum { margin-right: auto; align-self: center; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsindex e83a29d8a..e69eac487 100644--- a/desktop/tests/export-playable.test.ts+++ b/desktop/tests/export-playable.test.ts@@ -126,8 +126,16 @@ describe('exportGame (playable)', () => {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 warning cites this network's cap and where it came from — not a constant.- expect(res.warnings.join('\n')).toMatch(/over the 0\.0MB limit for Acme Ads \(Acme caps playables at 16 bytes\)/);+ // 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@@ -159,6 +167,10 @@ describe('exportGame (playable)', () => {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 () => {@@ -174,6 +186,12 @@ describe('exportGame (playable)', () => {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 () => {diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.tsindex 7452a54c1..343ac848a 100644--- a/desktop/tests/export-wechat.test.ts+++ b/desktop/tests/export-wechat.test.ts@@ -141,6 +141,23 @@ describe('exportGame (wechat)', () => {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);it('fails fast when the -t wechat engine runtime is missing', async () => {diff --git a/desktop/tests/project-packaging.test.ts b/desktop/tests/project-packaging.test.tsindex df699ed2c..fb47f4ed2 100644--- a/desktop/tests/project-packaging.test.ts+++ b/desktop/tests/project-packaging.test.ts@@ -43,6 +43,32 @@ describe('parseManifest — packaging', () => {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',diff --git a/desktop/tests/size-report.test.ts b/desktop/tests/size-report.test.tsnew file mode 100644index 000000000..7f3628ab5--- /dev/null+++ b/desktop/tests/size-report.test.ts@@ -0,0 +1,253 @@+// 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 '../electron/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('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');+ });+});