Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
chore: add esbuild bundle guard, build docs, and feature-tour refinements
nirholas119d71233c66
diff --git a/docs/build.md b/docs/build.mdnew file mode 100644index 000000000..d61a5c38e--- /dev/null+++ b/docs/build.md@@ -0,0 +1,133 @@+# Build & deploy artifact integrity++How three.ws is built, how the local build maps to what Vercel runs, and the+guards that keep what we ship identical to what we wrote. Read this before+touching the build pipeline.++## Commands at a glance++| Command | What it does |+| --- | --- |+| `npm run build` | The app build: `prebuild` lifecycle → `vite build` (`--max-old-space-size=6144`) → `scripts/strip-sw-from-embeds.mjs`. Output → `dist/`. |+| `npm run build:vercel` | The **deploy** build orchestrator (`scripts/build-vercel.mjs`) — what Vercel actually runs. Superset of `npm run build` (see [CI parity](#ci-parity)). |+| `npm run clean` | `rm -rf dist/* dist-lib/*`. |+| `npm run check:dist` | Asserts the published `agent-3d` library bundle + `dist-lib` mirror exist and the version matches `package.json` (`scripts/check-dist.mjs`). |+| `npm run audit:deploy` | Pre-flight for the three 2026-06-11 outage classes: committed symlinks, unsatisfied peer deps, undeclared `api/` imports (`scripts/audit-deploy-artifacts.mjs`). |+| `npm run guard:esbuild` | esbuild-trap guard — blocks committing a bundled `api/*.js` (scans the git index). `:all` sweeps the working tree. |++## CI parity++Vercel is configured (`vercel.json`) with:++- `installCommand`: `npm ci --no-audit --no-fund`+- `buildCommand`: `npm run build:vercel`+- `outputDirectory`: `dist`+- `.npmrc`: `legacy-peer-deps=true` (npm never auto-installs peers — the reason+ `audit:deploy` checks the peer tree)+- Node `24.x` (`engines.node`)++There is **no GitHub Actions CI** on this account — the Vercel build is the only+automated checkpoint, which is why `build:vercel` front-loads the audit/verify+gates (`audit:deploy`, `test:gate`, `verify:solana`, `verify:onchain`,+`audit:mcp`) that a CI workflow would normally run.++**`npm run build` is a strict subset of `npm run build:vercel`.** The app's Vite+build is byte-for-byte the same step in both — `build:vercel`'s phase 4+(`buildApp`) runs the identical `vite build && strip-sw-from-embeds` with the+same `NODE_OPTIONS`. The deploy build additionally:++1. Runs the gates above (phase 1).+2. Bundles the API with esbuild (`scripts/bundle-api.mjs`) so Vercel's file+ tracer doesn't spend 45 min walking `node_modules` — **this is the step that+ overwrites `api/*.js` in place** (see [the trap](#the-esbuild-overwrite-trap)).+3. Builds the embeddable library + `avatar-sdk` (phase 2), `character-studio`+ and `chat` (phase 3).+4. Post-build: copies avatar-studio, publishes the lib, applies R2 CORS, pushes+ the changelog (phase 5).++To reproduce a deploy locally, prefer `npm run build:vercel` **in a throwaway+worktree** (because of step 2). To iterate on the front-end only, `npm run build`+is faithful and safe.++## The esbuild-overwrite trap++`npx vercel build` and `scripts/bundle-api.mjs` both esbuild every API route and+write the bundle back over the source: `esbuild ... --outdir=api+--allow-overwrite`. On Vercel the checkout is ephemeral, so this is correct and+fast. **Locally it destroys the hand-written route sources**, and if one of those+bundles is `git add`ed and committed, the real source is lost and the repo+balloons by millions of generated lines. This has happened twice+(commits `c94190b3`, `dabd5884` — both reverted).++A bundled file is unmistakable: its opening lines carry esbuild's interop+helpers (`__defProp`, `__commonJS`, `__toESM`, `__esm`) or the `bundle-api`+`createRequire` banner — none of which ever appear at the top of a hand-written+route.++### Guard: `scripts/guard-esbuild-bundles.mjs`++Refuses to commit a bundled `api/*.js`. It scans the **staged blob** (`git show+:path`) — what a commit would actually record, not just the working tree — and+exits non-zero on any bundle.++```bash+npm run guard:esbuild # scan staged api JS (pre-commit use)+npm run guard:esbuild:all # sweep every working-tree api/**/*.js+node scripts/guard-esbuild-bundles.mjs --files api/foo.js # explicit paths+```++Detection logic is unit-tested (`tests/guard-esbuild-bundles.test.js`): it must+catch real esbuild/banner output and must not false-positive on a hand-written+route (verified clean across all 1100+ `api/**/*.js`).++### Wiring it as a pre-commit hook++This repo's `.git/hooks` are managed by **git-lfs** (do not overwrite them). To+add the guard, chain it from a `pre-commit` hook that preserves any existing LFS+behavior:++```sh+# .git/hooks/pre-commit (chmod +x)+#!/bin/sh+node scripts/guard-esbuild-bundles.mjs || exit 1+# (git-lfs installs its own pre-commit on some setups — call it here if present)+command -v git-lfs >/dev/null 2>&1 && git lfs pre-commit "$@"+```++If you ever stage a bundle by accident, recover the source before committing:++```bash+git restore --staged -- api/ public/ # unstage the bundles+git restore -- api/ public/ # restore source from HEAD+```++### Recognizing it after the fact++```bash+head -1 api/<route>.js # bundle if it starts with __defProp / createRequire / esbuild+```++## Source-map & secret hygiene++- `dist/`, `dist-lib/`, `dist-artifact/`, `.vercel/`, and every `.env*` file are+ gitignored (`.gitignore`) — build output and secrets never reach git.+- The Vite app build emits **no `.js.map` source maps** into `dist/` (production+ config), so no source is shipped to clients.+- `scripts/audit-deploy-artifacts.mjs` blocks committed symlinks (Vercel's tracer+ can't resolve them) and undeclared `api/` imports (phantom hoisted deps that+ vanish on dedupe).++## Embed integrity++Embed surfaces (`/widget`, `/embed`, `/agent-embed`, `/a-embed`,+`/avatar-embed`, `/agent-token-page`) load inside third-party iframes. They must+**not** register the service worker — an SW registered from an iframe is scoped+to `https://three.ws/` and would intercept every other tab on the origin.++`scripts/strip-sw-from-embeds.mjs` runs as the last step of `npm run build` and+removes the VitePWA `register-sw` `<script>` from each embed HTML in `dist/`. It+is idempotent and fails loudly if no embed HTML is found. Verify with:++```bash+grep -l 'vite-plugin-pwa:register-sw' dist/widget.html dist/embed.html # expect: no matches+```diff --git a/package.json b/package.jsonindex afb3cdfcf..fa1209b1c 100644--- a/package.json+++ b/package.json@@ -110,6 +110,8 @@"i18n:lint": "node scripts/i18n-translate.mjs --lint","changelog:push": "node scripts/changelog-telegram.mjs","audit:deploy": "node scripts/audit-deploy-artifacts.mjs",+ "guard:esbuild": "node scripts/guard-esbuild-bundles.mjs",+ "guard:esbuild:all": "node scripts/guard-esbuild-bundles.mjs --all","verify:solana": "node scripts/verify-solana-parity.mjs","verify:onchain": "node scripts/verify-onchain-parity.mjs","verify:x402": "node scripts/build-x402-catalog.mjs --out=/tmp/x402-catalog.json && node scripts/verify-x402-discovery.mjs --file=/tmp/x402-catalog.json",diff --git a/public/changelog.json b/public/changelog.jsonindex 7ece30dc6..8a7e7a995 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T16:25:52.509Z",+ "generated_at": "2026-06-25T07:59:46.264Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 1bdf29b84..f5223ca24 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-24T16:25:52.492Z",+ "generated_at": "2026-06-25T07:59:46.215Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 755e54062..a488ad85d 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,25 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header class="sm-topbar">diff --git a/scripts/guard-esbuild-bundles.mjs b/scripts/guard-esbuild-bundles.mjsnew file mode 100644index 000000000..29d3b543e--- /dev/null+++ b/scripts/guard-esbuild-bundles.mjs@@ -0,0 +1,168 @@+#!/usr/bin/env node+/**+ * esbuild-trap guard — refuse to commit a bundled api/*.js source file.+ *+ * The trap (CLAUDE.md "Known traps"): `npx vercel build` and+ * scripts/bundle-api.mjs both esbuild every api route and write the bundle back+ * over the source with `--outdir=api --allow-overwrite`. On Vercel that's fine —+ * the checkout is ephemeral. Locally it destroys the hand-written route sources,+ * and if one of those multi-thousand-line bundles gets `git add`ed and committed+ * the repo balloons (commits c94190b3 and dabd5884 — both reverted) and the real+ * source is lost. The bundles are unmistakable: their first lines carry esbuild's+ * `__defProp`/`__commonJS`/`__toESM` helpers or the bundle-api `createRequire`+ * banner, neither of which ever appears at the top of a hand-written route.+ *+ * This guard scans the *staged* content of api JS files (what a commit would+ * actually record, not just the working tree) and exits non-zero if any of them+ * is a bundle. Wire it as a pre-commit check (see docs/build.md) so the bundle+ * can never be committed by accident.+ *+ * Usage:+ * node scripts/guard-esbuild-bundles.mjs # scan staged api JS (pre-commit)+ * node scripts/guard-esbuild-bundles.mjs --all # sweep every working-tree api JS+ * node scripts/guard-esbuild-bundles.mjs --files a.js b.js # scan explicit paths+ */+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { globSync } from 'glob';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');++// Markers that only an esbuild/bundle-api output carries near the top of the+// file. `__defProp`, `__commonJS`, `__toESM`, `__esm` are esbuild's CJS/ESM+// interop helpers; `createRequire` is the bundle-api `--banner:js` shim; the+// bare `esbuild` token catches the `// esbuild` provenance comments some+// configs emit. None of these appear in the opening lines of a hand-authored+// Vercel route (verified across all 1100+ api/**/*.js files), so a hit is an+// unambiguous bundle.+const BUNDLE_MARKER = /\b(?:__defProp|__commonJS|__toESM|__esm|createRequire|esbuild)\b/;++// Bundles announce themselves immediately. esbuild emits an optional+// `"use strict";` line before `var __defProp = ...`, and bundle-api's banner is+// line 1 — so the markers always land within the first handful of lines.+// Scanning only the head (not the whole multi-MB file) keeps this fast and makes+// a false positive on a legitimate deep-in-the-file occurrence impossible.+const HEAD_LINES = 5;++/**+ * Returns the matched bundle marker (string) if `content` looks like an esbuild+ * bundle, or null if it reads as hand-written source.+ */+export function detectBundleMarker(content) {+ const head = content.split('\n', HEAD_LINES).join('\n');+ const m = head.match(BUNDLE_MARKER);+ return m ? m[0] : null;+}++function isApiJs(rel) {+ const norm = rel.replace(/\\/g, '/');+ return /^api\//.test(norm) && norm.endsWith('.js');+}++/** Paths (repo-relative) of api JS files in the git index, added/copied/modified. */+function stagedApiJsFiles(cwd) {+ let out;+ try {+ out = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACMR'], {+ cwd,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ } catch {+ return [];+ }+ return out.split('\n').filter(Boolean).filter(isApiJs);+}++/** Reads the *staged* blob of a path (`git show :path`); null if absent from index. */+function readStagedBlob(rel, cwd) {+ try {+ return execFileSync('git', ['show', `:${rel}`], {+ cwd,+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ } catch {+ return null;+ }+}++/** Every working-tree api JS file (repo-relative). */+function allApiJsFiles(cwd) {+ return globSync('api/**/*.js', { cwd, ignore: ['**/node_modules/**'] }).sort();+}++/**+ * Scans the given (path → content) pairs and returns the ones that are bundles.+ * Exported for tests; the CLI wires it to either staged blobs or working-tree+ * files.+ */+export function findBundledFiles(entries) {+ const hits = [];+ for (const { path, content } of entries) {+ if (content == null) continue;+ const marker = detectBundleMarker(content);+ if (marker) hits.push({ path, marker });+ }+ return hits;+}++const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ const args = process.argv.slice(2);+ const cwd = ROOT;+ let entries;+ let mode;++ const fileFlagIdx = args.indexOf('--files');+ if (fileFlagIdx !== -1) {+ mode = 'explicit';+ const files = args.slice(fileFlagIdx + 1).filter((a) => !a.startsWith('--'));+ entries = files.map((path) => {+ let content = null;+ try {+ content = readFileSync(resolve(cwd, path), 'utf8');+ } catch {+ /* unreadable — skip */+ }+ return { path, content };+ });+ } else if (args.includes('--all')) {+ mode = 'working tree';+ entries = allApiJsFiles(cwd).map((path) => {+ let content = null;+ try {+ content = readFileSync(resolve(cwd, path), 'utf8');+ } catch {+ /* unreadable — skip */+ }+ return { path, content };+ });+ } else {+ mode = 'staged';+ entries = stagedApiJsFiles(cwd).map((path) => ({ path, content: readStagedBlob(path, cwd) }));+ }++ const hits = findBundledFiles(entries);+ if (hits.length) {+ console.error(+ `[guard:esbuild] BLOCKED — ${hits.length} bundled api file(s) detected (${mode}). These are esbuild/bundle-api output overwriting hand-written route sources; committing them destroys the source and balloons the repo:`,+ );+ for (const { path, marker } of hits) {+ console.error(` ${path} (matched "${marker}")`);+ }+ console.error(+ '\nRecover the real sources before committing:\n' ++ ' git restore --staged -- api/ public/ # unstage the bundles\n' ++ ' git restore -- api/ public/ # restore source from HEAD\n' ++ 'See docs/build.md → "The esbuild-overwrite trap".',+ );+ process.exit(1);+ }++ const n = entries.filter((e) => e.content != null).length;+ console.log(`[guard:esbuild] clean — ${n} api JS file(s) scanned (${mode}), no bundles.`);+}diff --git a/src/feature-tour/director.js b/src/feature-tour/director.jsindex d62e650aa..a529b4bc9 100644--- a/src/feature-tour/director.js+++ b/src/feature-tour/director.js@@ -576,6 +576,15 @@ export class TourDirector {// that clears the moment the real assets are mounted (or the load gives up)._showLoading() {if (this._loadingEl) return;+ // bootstrap() can fire (via ?tour=/resume) before <body> is parsed — appending+ // to a null document.body threw "Cannot read properties of null (reading+ // 'appendChild')". Defer to DOMContentLoaded once, then mount normally.+ if (typeof document === 'undefined' || !document.body) {+ if (typeof document !== 'undefined') {+ document.addEventListener('DOMContentLoaded', () => this._showLoading(), { once: true });+ }+ return;+ }ensureLoadingStyles();const el = document.createElement('div');el.className = 'tws-tour-loading';diff --git a/src/scene-studio/vendor/js/Menubar.View.js b/src/scene-studio/vendor/js/Menubar.View.jsindex 8e04f21fe..b994d3001 100644--- a/src/scene-studio/vendor/js/Menubar.View.js+++ b/src/scene-studio/vendor/js/Menubar.View.js@@ -105,25 +105,21 @@ function MenubarView( editor ) {option.setTextContent( strings.getKey( 'menubar/view/fullscreen' ) );option.onClick( function () {- if ( document.fullscreenElement === null ) {+ // Feature-detect each method before calling it: some webviews expose+ // document.fullscreenElement (as null) without the unprefixed+ // requestFullscreen, which threw "requestFullscreen is not a function".+ const el = document.documentElement;+ const inFullscreen = document.fullscreenElement || document.webkitFullscreenElement;- document.documentElement.requestFullscreen();+ if ( ! inFullscreen ) {- } else if ( document.exitFullscreen ) {+ if ( el.requestFullscreen ) el.requestFullscreen();+ else if ( el.webkitRequestFullscreen ) el.webkitRequestFullscreen();- document.exitFullscreen();-- }-- // Safari-- if ( document.webkitFullscreenElement === null ) {-- document.documentElement.webkitRequestFullscreen();-- } else if ( document.webkitExitFullscreen ) {+ } else {- document.webkitExitFullscreen();+ if ( document.exitFullscreen ) document.exitFullscreen();+ else if ( document.webkitExitFullscreen ) document.webkitExitFullscreen();}diff --git a/src/three-tier-page.js b/src/three-tier-page.jsindex 174b7d9d6..5e42dc367 100644--- a/src/three-tier-page.js+++ b/src/three-tier-page.js@@ -416,14 +416,6 @@ function mount() {}}-if (typeof document !== 'undefined') {- if (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', mount, { once: true });- } else {- mount();- }-}-// ── styles ──────────────────────────────────────────────────────────────────let _styled = false;@@ -532,3 +524,18 @@ function injectStyles() {el.textContent = css;document.head.appendChild(el);}++// ── bootstrap (must run last) ─────────────────────────────────────────────────+// Kept at the very end of the module: mount() → boot() → injectStyles() reads the+// `_styled` guard, so the bootstrap can only run after `let _styled` is initialized.+// When the DOM is already parsed (readyState !== 'loading') mount() runs during+// module evaluation, so invoking it before `let _styled` was declared hit that+// binding in its temporal dead zone — the intermittent "Cannot access '_styled'+// before initialization" / "Cannot access uninitialized variable" crash on /three.+if (typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', mount, { once: true });+ } else {+ mount();+ }+}diff --git a/tests/guard-esbuild-bundles.test.js b/tests/guard-esbuild-bundles.test.jsnew file mode 100644index 000000000..e43a211bb--- /dev/null+++ b/tests/guard-esbuild-bundles.test.js@@ -0,0 +1,67 @@+// Guards the esbuild-trap guard itself (scripts/guard-esbuild-bundles.mjs).+//+// `npx vercel build` / scripts/bundle-api.mjs esbuild every api route and write+// the bundle back over the source (--outdir=api --allow-overwrite). Committing+// one of those bundles destroys the hand-written route and balloons the repo+// (commits c94190b3, dabd5884 — both reverted). The guard refuses to commit a+// bundled api/*.js; these tests pin its detection so it can neither miss a real+// bundle nor false-positive on hand-written source.++import { describe, it, expect } from 'vitest';+import { detectBundleMarker, findBundledFiles } from '../scripts/guard-esbuild-bundles.mjs';++describe('detectBundleMarker', () => {+ it('flags esbuild __defProp helper on line 1', () => {+ expect(detectBundleMarker('var __defProp = Object.defineProperty;\n// ...\n')).toBe('__defProp');+ });++ it('flags __defProp after a leading "use strict" preamble (line 2)', () => {+ expect(detectBundleMarker('"use strict";\nvar __defProp = Object.defineProperty;\n')).toBe(+ '__defProp',+ );+ });++ it('flags the bundle-api createRequire banner', () => {+ const banner = "var require = (await import('node:module')).createRequire(import.meta.url);\n";+ expect(detectBundleMarker(banner)).toBe('createRequire');+ });++ it('flags esbuild __commonJS / __toESM interop helpers', () => {+ expect(detectBundleMarker('var __commonJS = (cb, mod) => ...\n')).toBe('__commonJS');+ expect(detectBundleMarker('var __toESM = (mod) => ...\n')).toBe('__toESM');+ });++ it('passes a hand-written route opening with a JSDoc block', () => {+ expect(detectBundleMarker('/**\n * GET /api/foo\n */\nexport default function handler() {}\n')).toBeNull();+ });++ it('passes a hand-written route opening with imports', () => {+ const src = "import { authenticateBearer } from './_lib/auth.js';\nexport default async function handler(req, res) {}\n";+ expect(detectBundleMarker(src)).toBeNull();+ });++ it('does NOT trip on a marker that appears only deep in the file (past the head window)', () => {+ const src =+ '// real source\n'.repeat(10) + 'const x = createRequire(import.meta.url);\n';+ expect(detectBundleMarker(src)).toBeNull();+ });+});++describe('findBundledFiles', () => {+ it('returns only the bundled entries, with their marker', () => {+ const entries = [+ { path: 'api/good.js', content: '/**\n * ok\n */\n' },+ { path: 'api/bad.js', content: 'var __defProp = Object.defineProperty;\n' },+ { path: 'api/skipped.js', content: null },+ ];+ expect(findBundledFiles(entries)).toEqual([{ path: 'api/bad.js', marker: '__defProp' }]);+ });++ it('returns [] when every entry is hand-written source', () => {+ const entries = [+ { path: 'api/a.js', content: 'export default function () {}\n' },+ { path: 'api/b.js', content: '// comment\nconst x = 1;\n' },+ ];+ expect(findBundledFiles(entries)).toEqual([]);+ });+});