Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Check bundle size budgets on pull requests

Nguyen Xuan An63b9500bbd56
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 0d8ec7c4..4d251311 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -22,6 +22,7 @@ jobs:
package-manager-cache: false
- run: npm install --global [email protected]
- run: npm ci --ignore-scripts
+ - run: npm run size
- run: npm test
- run: npm run prepare:release
- run: npm run smoke:package
diff --git a/bench/size/README.md b/bench/size/README.md
new file mode 100644
index 00000000..55e6b374
--- /dev/null
+++ b/bench/size/README.md
@@ -0,0 +1,44 @@
+# Bundle size budgets
+
+`npm run size` bundles each package entry with esbuild, minified and tree-shaken, and compares its gzip size with a budget. The `Test` workflow runs it on every pull request.
+
+## What it measures
+
+- **`entry:<name>`:** everything that one package entry exports. This is the most that an app can pay for the entry.
+- **`scene:<name>`:** a small app that uses only what it needs. `lit-box`, `gltf-box` and `agent-scene` are the numbers that the goal in issue 23 uses.
+- **three.js:** the same `lit-box` and `gltf-box` scenes, at the version in `package.json`. They have no budget, because this project does not control them.
+
+`manifold-3d` and `@dimforge/rapier3d-compat` are optional peers that load separately, so no bundle counts them.
+
+## Baseline
+
+Measured on 2026-10-31 with three.js 0.186.1. Sizes are bytes gzip.
+
+| Scene | 67.js | three.js | Goal |
+| --- | --- | --- | --- |
+| `lit-box` | 48,762 | 133,652 | 50,000 |
+| `gltf-box` | 159,422 | 155,814 | 80,000 |
+| `agent-scene` | 185,592 | no equivalent | 100,000 |
+
+`bench/size/baseline.json` holds every size. The goals are proposals from issue 23.
+
+## When a check fails
+
+The output names the bundle, its size and its budget.
+
+1. Find out why the bundle grew. A new import of a large module is the usual cause.
+2. If the growth is a mistake, remove it.
+3. If the growth is worth its cost, raise the number in `bench/size/budgets.json`.
+4. State the reason in the pull request. The budget change is then visible in the diff.
+
+## After a change lands
+
+Run `node scripts/measure-size.mjs --update-baseline` to record the new sizes, so the next pull request shows its own change. The budget does not move.
+
+Use `--set-budgets` to reset every budget to 2% over the current size. Use it after work that makes bundles smaller, so that the saving stays. A reset also hides any growth since the last reset, so check the diff.
+
+## Limits
+
+The check reads gzip size only. It does not measure parse time, memory or runtime speed.
+
+The check reports a status. It can not block a merge, because this private repository has no branch protection (issue 32).
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
new file mode 100644
index 00000000..e87b9e8d
--- /dev/null
+++ b/bench/size/baseline.json
@@ -0,0 +1,167 @@
+{
+ "threeVersion": "0.186.1",
+ "three": {
+ "lit-box": {
+ "min": 533773,
+ "gzip": 133652,
+ "brotli": 110257
+ },
+ "gltf-box": {
+ "min": 614592,
+ "gzip": 155814,
+ "brotli": 128198
+ }
+ },
+ "bundles": {
+ "entry:core": {
+ "min": 232517,
+ "gzip": 65730,
+ "brotli": 56178
+ },
+ "entry:model": {
+ "min": 40093,
+ "gzip": 14025,
+ "brotli": 11542
+ },
+ "entry:nature": {
+ "min": 35653,
+ "gzip": 12874,
+ "brotli": 10578
+ },
+ "entry:film": {
+ "min": 628052,
+ "gzip": 153667,
+ "brotli": 124418
+ },
+ "entry:motion": {
+ "min": 39159,
+ "gzip": 13304,
+ "brotli": 11153
+ },
+ "entry:canvas2d": {
+ "min": 27190,
+ "gzip": 9149,
+ "brotli": 7331
+ },
+ "entry:gltf": {
+ "min": 533687,
+ "gzip": 134659,
+ "brotli": 111762
+ },
+ "entry:modeling": {
+ "min": 309436,
+ "gzip": 74404,
+ "brotli": 61979
+ },
+ "entry:sculpt": {
+ "min": 5937,
+ "gzip": 2391,
+ "brotli": 2184
+ },
+ "entry:surface": {
+ "min": 314055,
+ "gzip": 72974,
+ "brotli": 60264
+ },
+ "entry:mesh-query": {
+ "min": 344039,
+ "gzip": 85555,
+ "brotli": 71174
+ },
+ "entry:mesh": {
+ "min": 95451,
+ "gzip": 32718,
+ "brotli": 28879
+ },
+ "entry:shrinkwrap": {
+ "min": 348855,
+ "gzip": 86779,
+ "brotli": 72407
+ },
+ "entry:surface-attachment": {
+ "min": 36920,
+ "gzip": 11484,
+ "brotli": 9398
+ },
+ "entry:physics": {
+ "min": 50023,
+ "gzip": 16121,
+ "brotli": 13649
+ },
+ "entry:spume": {
+ "min": 24434,
+ "gzip": 8793,
+ "brotli": 7088
+ },
+ "entry:retarget": {
+ "min": 46336,
+ "gzip": 15313,
+ "brotli": 12962
+ },
+ "entry:skeleton-pose": {
+ "min": 51635,
+ "gzip": 16806,
+ "brotli": 14274
+ },
+ "entry:vehicle": {
+ "min": 42067,
+ "gzip": 14395,
+ "brotli": 12172
+ },
+ "entry:vegetation": {
+ "min": 49217,
+ "gzip": 17468,
+ "brotli": 14786
+ },
+ "entry:terrain": {
+ "min": 6661,
+ "gzip": 3006,
+ "brotli": 2712
+ },
+ "entry:grass": {
+ "min": 9441,
+ "gzip": 4236,
+ "brotli": 3822
+ },
+ "entry:clutter": {
+ "min": 12056,
+ "gzip": 5185,
+ "brotli": 4675
+ },
+ "entry:texture-set": {
+ "min": 1837,
+ "gzip": 874,
+ "brotli": 762
+ },
+ "entry:agent-scene": {
+ "min": 586176,
+ "gzip": 161435,
+ "brotli": 135409
+ },
+ "entry:agent-asset": {
+ "min": 612778,
+ "gzip": 168878,
+ "brotli": 141774
+ },
+ "entry:hdri": {
+ "min": 8075,
+ "gzip": 3138,
+ "brotli": 2801
+ },
+ "scene:lit-box": {
+ "min": 178412,
+ "gzip": 48762,
+ "brotli": 41832
+ },
+ "scene:gltf-box": {
+ "min": 629811,
+ "gzip": 159422,
+ "brotli": 132670
+ },
+ "scene:agent-scene": {
+ "min": 678447,
+ "gzip": 185592,
+ "brotli": 155797
+ }
+ }
+}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
new file mode 100644
index 00000000..ff10a18f
--- /dev/null
+++ b/bench/size/budgets.json
@@ -0,0 +1,39 @@
+{
+ "goals": {
+ "lit-box": 50000,
+ "gltf-box": 80000,
+ "agent-scene": 100000
+ },
+ "budgets": {
+ "entry:core": 67100,
+ "entry:model": 14400,
+ "entry:nature": 13200,
+ "entry:film": 156800,
+ "entry:motion": 13600,
+ "entry:canvas2d": 9400,
+ "entry:gltf": 137400,
+ "entry:modeling": 75900,
+ "entry:sculpt": 2500,
+ "entry:surface": 74500,
+ "entry:mesh-query": 87300,
+ "entry:mesh": 33400,
+ "entry:shrinkwrap": 88600,
+ "entry:surface-attachment": 11800,
+ "entry:physics": 16500,
+ "entry:spume": 9000,
+ "entry:retarget": 15700,
+ "entry:skeleton-pose": 17200,
+ "entry:vehicle": 14700,
+ "entry:vegetation": 17900,
+ "entry:terrain": 3100,
+ "entry:grass": 4400,
+ "entry:clutter": 5300,
+ "entry:texture-set": 100,
+ "entry:agent-scene": 164700,
+ "entry:agent-asset": 172300,
+ "entry:hdri": 3300,
+ "scene:lit-box": 49800,
+ "scene:gltf-box": 162700,
+ "scene:agent-scene": 189400
+ }
+}
diff --git a/docs/parity.md b/docs/parity.md
index ed3ea100..c7fbb40e 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -237,7 +237,7 @@ The goal also needs this work, and no page in the Blender manual covers it.
| Work | Status | Why | Issues |
| --- | --- | --- | --- |
| Parity evidence | partial | This ledger exists. The Blender comparisons do not. | #24, #25, #26 |
-| Bundle size | partial | The package has a 1 MiB limit. Entries have no budgets, and three.js is still in the glTF and modeling paths. | #27, #33, #34, #35, #36 |
+| Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is still in the glTF and modeling paths. | #27, #33, #34, #35, #36 |
| Runtime speed | partial | One benchmark scene. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38 |
| Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 |
| Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 |
diff --git a/package-lock.json b/package-lock.json
index 05779996..a7bd1674 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -19,6 +19,7 @@
"@dimforge/rapier3d-compat": "0.21.0",
"@modelcontextprotocol/client": "2.3.1",
"@modelcontextprotocol/server": "2.3.1",
+ "esbuild": "0.28.2",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
"manifold-3d": "3.5.4",
diff --git a/package.json b/package.json
index 9af94d29..13020750 100644
--- a/package.json
+++ b/package.json
@@ -131,7 +131,8 @@
"smoke:agent-character": "node scripts/smoke-agent-character.mjs",
"smoke:agent-review": "node scripts/smoke-agent-review.mjs",
"parity": "node scripts/parity-report.mjs",
- "reference": "node bench/reference/run.mjs"
+ "reference": "node bench/reference/run.mjs",
+ "size": "node scripts/measure-size.mjs"
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0",
@@ -153,6 +154,7 @@
"@dimforge/rapier3d-compat": "0.21.0",
"@modelcontextprotocol/client": "2.3.1",
"@modelcontextprotocol/server": "2.3.1",
+ "esbuild": "0.28.2",
"gl-matrix": "3.4.4",
"highlight.js": "11.12.0",
"manifold-3d": "3.5.4",
diff --git a/scripts/measure-size.mjs b/scripts/measure-size.mjs
new file mode 100644
index 00000000..2b96dcb8
--- /dev/null
+++ b/scripts/measure-size.mjs
@@ -0,0 +1,131 @@
+// Measures what an app pays for each package entry, and for small scenes against three.js: npm run size
+// It fails when a bundle passes its budget in bench/size/budgets.json. --update-baseline rewrites the baseline after a
+// merge-ready change, and --set-budgets also resets each budget to 2% over its current size.
+import { readFile, writeFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { brotliCompressSync, gzipSync } from 'node:zlib';
+import { build } from 'esbuild';
+import { budgetsFrom, compareToBudgets, formatRows } from './size-budget.mjs';
+
+const BUDGETS_PATH = 'bench/size/budgets.json';
+const BASELINE_PATH = 'bench/size/baseline.json';
+const EXTERNAL_PACKAGES = ['manifold-3d', '@dimforge/rapier3d-compat'];
+const CORE_ENTRY = 'core';
+
+// Each scene does the same small job in both engines, so a size difference is the cost of the engine.
+const SCENES = {
+ 'lit-box': {
+ three: `
+ import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshStandardMaterial, DirectionalLight } from 'three';
+ const scene = new Scene();
+ const renderer = new WebGLRenderer();
+ scene.add(new Mesh(new BoxGeometry(), new MeshStandardMaterial()), new DirectionalLight());
+ renderer.render(scene, new PerspectiveCamera());`,
+ engine: `
+ import { Renderer67 } from './src/renderer.js';
+ import { box } from './src/geometry.js';
+ const material = { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5 };
+ const parts = [{ name: 'box', geometry: box(0, 1), matrix: new Float32Array(16), material }];
+ new Renderer67(document.createElement('canvas'), parts, {}).render({ eye: [3, 3, 3], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 100 });`,
+ },
+ 'gltf-box': {
+ three: `
+ import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshStandardMaterial, DirectionalLight } from 'three';
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+ const scene = new Scene();
+ const renderer = new WebGLRenderer();
+ new GLTFLoader().load('x.glb', model => scene.add(model.scene));
+ scene.add(new Mesh(new BoxGeometry(), new MeshStandardMaterial()), new DirectionalLight());
+ renderer.render(scene, new PerspectiveCamera());`,
+ engine: `
+ import { Renderer67 } from './src/renderer.js';
+ import { parseGltf } from './src/gltf.js';
+ parseGltf(new ArrayBuffer(0)).then(asset => new Renderer67(document.createElement('canvas'), asset.parts, {}).render({}));`,
+ },
+ 'agent-scene': {
+ engine: `
+ import { createAgentScene } from './src/agent-scene.js';
+ import { Renderer67 } from './src/renderer.js';
+ const scene = createAgentScene({});
+ new Renderer67(document.createElement('canvas'), scene.parts, {}).render(scene.camera);`,
+ },
+};
+
+async function measureSource(contents) {
+ const result = await build({
+ stdin: { contents, resolveDir: process.cwd(), loader: 'js' },
+ bundle: true, minify: true, format: 'esm', write: false, treeShaking: true,
+ external: EXTERNAL_PACKAGES, logLevel: 'silent', target: 'es2022',
+ loader: { '.css': 'empty', '.json': 'json' },
+ define: { 'process.env.NODE_ENV': '"production"' },
+ });
+ const output = result.outputFiles[0].contents;
+ return { min: output.length, gzip: gzipSync(output, { level: 9 }).length, brotli: brotliCompressSync(output).length };
+}
+
+async function packageEntries() {
+ const manifest = JSON.parse(await readFile('package.json', 'utf8'));
+ const addons = Object.keys(manifest.exports).filter(key => key.startsWith('./addons/')).map(key => key.slice('./addons/'.length));
+ return { [CORE_ENTRY]: 'src/index.js', ...Object.fromEntries(addons.map(name => [name, `src/${name}.js`])) };
+}
+
+async function measureAll() {
+ const measured = {};
+ for (const [name, path] of Object.entries(await packageEntries())) {
+ const absolute = resolve(path).replace(/\\/g, '/');
+ measured[`entry:${name}`] = await measureSource(`export * from '${absolute}';`);
+ }
+ for (const [name, scene] of Object.entries(SCENES)) measured[`scene:${name}`] = await measureSource(scene.engine);
+ return measured;
+}
+
+async function measureThree() {
+ const measured = {};
+ for (const [name, scene] of Object.entries(SCENES)) {
+ if (scene.three) measured[name] = await measureSource(scene.three);
+ }
+ return measured;
+}
+
+async function readJson(path) {
+ return JSON.parse(await readFile(path, 'utf8'));
+}
+
+async function writeJson(path, value) {
+ await writeFile(path, `${JSON.stringify(value, null, 1)}\n`);
+}
+
+function printComparisonWithThree(measured, three, goals) {
+ console.log('\nThe same scene in both engines, in bytes gzip:');
+ for (const [name, threeSize] of Object.entries(three)) {
+ const engineSize = measured[`scene:${name}`].gzip;
+ const goal = goals[name] === undefined ? '' : `, goal ${goals[name]}`;
+ console.log(` ${name.padEnd(14)} 67.js ${engineSize}, three.js ${threeSize.gzip}${goal}`);
+ }
+ for (const [name, goal] of Object.entries(goals)) {
+ if (!three[name]) console.log(` ${name.padEnd(14)} 67.js ${measured[`scene:${name}`].gzip}, no three.js equivalent, goal ${goal}`);
+ }
+}
+
+const flags = new Set(process.argv.slice(2));
+const measured = await measureAll();
+const three = await measureThree();
+const budgetFile = await readJson(BUDGETS_PATH);
+const baselineFile = await readJson(BASELINE_PATH);
+
+if (flags.has('--set-budgets')) budgetFile.budgets = budgetsFrom(measured);
+if (flags.has('--set-budgets') || flags.has('--update-baseline')) {
+ const threeManifest = await readJson('node_modules/three/package.json');
+ await writeJson(BUDGETS_PATH, budgetFile);
+ await writeJson(BASELINE_PATH, { threeVersion: threeManifest.version, three, bundles: measured });
+}
+
+const { rows, problems } = compareToBudgets(measured, budgetFile.budgets, baselineFile.bundles);
+console.log(formatRows(rows));
+printComparisonWithThree(measured, three, budgetFile.goals);
+if (problems.length) {
+ console.error(`\n${problems.length} size problem(s):`);
+ for (const problem of problems) console.error(`- ${problem}`);
+ process.exit(1);
+}
+console.log('\nEvery bundle is within its budget.');
diff --git a/scripts/size-budget.mjs b/scripts/size-budget.mjs
new file mode 100644
index 00000000..b2e14f77
--- /dev/null
+++ b/scripts/size-budget.mjs
@@ -0,0 +1,46 @@
+// Compares measured bundle sizes with their budgets. measure-size.mjs and its test share this file.
+const BUDGET_MARGIN = 0.02;
+const BUDGET_ROUNDING = 100;
+
+export function budgetFor(gzipBytes) {
+ return Math.ceil((gzipBytes * (1 + BUDGET_MARGIN)) / BUDGET_ROUNDING) * BUDGET_ROUNDING;
+}
+
+export function budgetsFrom(measured) {
+ return Object.fromEntries(Object.entries(measured).map(([name, size]) => [name, budgetFor(size.gzip)]));
+}
+
+// Returns one row per measured bundle, and a problem for each bundle that breaks a rule.
+export function compareToBudgets(measured, budgets, baseline = {}) {
+ const rows = [];
+ const problems = [];
+ for (const [name, size] of Object.entries(measured)) {
+ const budget = budgets[name];
+ const previous = baseline[name]?.gzip;
+ const change = previous === undefined ? null : size.gzip - previous;
+ rows.push({ name, min: size.min, gzip: size.gzip, budget: budget ?? null, change });
+ if (budget === undefined) {
+ problems.push(`${name} has no budget. Add it to bench/size/budgets.json.`);
+ } else if (size.gzip > budget) {
+ problems.push(`${name} is ${size.gzip} bytes gzip, over its budget of ${budget} by ${size.gzip - budget}. Reduce it, or raise the budget in bench/size/budgets.json and say why in the pull request.`);
+ }
+ }
+ for (const name of Object.keys(budgets)) {
+ if (!(name in measured)) problems.push(`${name} has a budget and no bundle. Remove it from bench/size/budgets.json.`);
+ }
+ return { rows, problems };
+}
+
+function signedBytes(change) {
+ if (change === null) return 'new';
+ return change > 0 ? `+${change}` : String(change);
+}
+
+export function formatRows(rows) {
+ const header = `${'bundle'.padEnd(30)}${'min'.padStart(10)}${'gzip'.padStart(10)}${'budget'.padStart(10)}${'change'.padStart(10)}`;
+ const lines = rows.map(row => [
+ row.name.padEnd(30), String(row.min).padStart(10), String(row.gzip).padStart(10),
+ String(row.budget ?? '-').padStart(10), signedBytes(row.change).padStart(10),
+ ].join(''));
+ return [header, ...lines].join('\n');
+}
diff --git a/tests/size-budget.test.js b/tests/size-budget.test.js
new file mode 100644
index 00000000..fb43fea2
--- /dev/null
+++ b/tests/size-budget.test.js
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict';
+import { existsSync, readFileSync } from 'node:fs';
+import test from 'node:test';
+import { budgetFor, compareToBudgets, formatRows } from '../scripts/size-budget.mjs';
+
+const readJson = path => JSON.parse(readFileSync(new URL(path, import.meta.url), 'utf8'));
+const budgetFile = readJson('../bench/size/budgets.json');
+const baseline = readJson('../bench/size/baseline.json');
+const manifest = readJson('../package.json');
+
+test('a bundle over its budget is a problem that names the bundle and the fix', () => {
+ const { problems } = compareToBudgets({ 'entry:core': { min: 10, gzip: 101 } }, { 'entry:core': 100 });
+ assert.equal(problems.length, 1);
+ assert.match(problems[0], /entry:core is 101 bytes gzip, over its budget of 100 by 1/);
+ assert.match(problems[0], /Reduce it, or raise the budget/);
+});
+
+test('a bundle at its budget passes', () => {
+ assert.deepEqual(compareToBudgets({ 'entry:core': { min: 10, gzip: 100 } }, { 'entry:core': 100 }).problems, []);
+});
+
+test('a new bundle needs a budget, and a budget needs a bundle', () => {
+ const { problems } = compareToBudgets({ 'entry:new': { min: 1, gzip: 1 } }, { 'entry:gone': 1 });
+ assert.equal(problems.length, 2);
+ assert.match(problems[0], /entry:new has no budget/);
+ assert.match(problems[1], /entry:gone has a budget and no bundle/);
+});
+
+test('rows report the change from the baseline', () => {
+ const { rows } = compareToBudgets(
+ { first: { min: 5, gzip: 110 }, second: { min: 5, gzip: 90 }, third: { min: 5, gzip: 1 } },
+ { first: 200, second: 200, third: 200 },
+ { first: { gzip: 100 }, second: { gzip: 100 } },
+ );
+ assert.deepEqual(rows.map(row => row.change), [10, -10, null]);
+ const report = formatRows(rows);
+ assert.match(report, /\+10/);
+ assert.match(report, /-10/);
+ assert.match(report, /new/);
+});
+
+test('a budget leaves 2% of room, rounded up to 100 bytes', () => {
+ assert.equal(budgetFor(10000), 10200);
+ assert.equal(budgetFor(10001), 10300);
+});
+
+test('every package entry has a source file and a budget', () => {
+ const addons = Object.keys(manifest.exports).filter(key => key.startsWith('./addons/'));
+ assert.ok(addons.length > 0);
+ for (const key of addons) {
+ const name = key.slice('./addons/'.length);
+ assert.ok(existsSync(new URL(`../src/${name}.js`, import.meta.url)), `No source for ${key}`);
+ assert.ok(budgetFile.budgets[`entry:${name}`] > 0, `No budget for ${key}`);
+ }
+ assert.ok(budgetFile.budgets['entry:core'] > 0);
+});
+
+test('the baseline records the three.js version and its scene sizes', () => {
+ assert.equal(baseline.threeVersion, manifest.devDependencies.three);
+ assert.ok(baseline.three['lit-box'].gzip > 0);
+ assert.ok(baseline.three['gltf-box'].gzip > 0);
+});