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
feat(docs): media capture pipeline and tutorial figures
nirholasa1802206beb4
diff --git a/data/doc-media.json b/data/doc-media.jsonnew file mode 100644index 000000000..6cbcde005--- /dev/null+++ b/data/doc-media.json@@ -0,0 +1,141 @@+{+ "$comment": "Recipes for every screenshot and loop the docs own. Each entry is captured from the running site by scripts/capture-doc-media.mjs and lands in public/docs/img/<id>.webp with provenance in public/docs/media-manifest.json. Edit the recipe, re-run the script; never hand-place a file the docs reference.",+ "defaults": {+ "viewport": "desktop",+ "theme": "dark",+ "settle": 3500+ },+ "shots": [+ {+ "id": "forge-prompt-panel",+ "url": "/create/prompt",+ "alt": "The three.ws prompt-to-3D page with the description field and quality tier picker",+ "caption": "Describe it to 3D: the prompt field and the tier picker are the whole interface.",+ "usedBy": ["tutorials/text-to-3d", "tutorials/first-prompt-to-3d"]+ },+ {+ "id": "forge-hero",+ "url": "/forge",+ "alt": "The Forge page showing text and image to 3D generation options",+ "caption": "The Forge accepts a sentence or an image and returns a textured GLB.",+ "usedBy": ["tutorials/prompts-for-3d", "tutorials/generate-3d-api"]+ },+ {+ "id": "image-to-3d-page",+ "url": "/image-to-3d",+ "alt": "The image-to-3D page with its upload dropzone",+ "caption": "Drop a photo here and the same pipeline returns a mesh instead of a render.",+ "usedBy": ["tutorials/image-to-3d"]+ },+ {+ "id": "avatar-studio",+ "url": "/avatar-studio",+ "alt": "The three.ws Avatar Studio with a rigged avatar in the viewport and the customisation rail",+ "caption": "Avatar Studio: the rig on the left, every appearance control on the right.",+ "settle": 6000,+ "usedBy": ["tutorials/customize-appearance", "tutorials/swap-avatar-in-studio"]+ },+ {+ "id": "animation-studio",+ "url": "/pose",+ "alt": "The Animation Studio timeline with an avatar mid-clip",+ "caption": "Animation Studio drives the same canonical clip library the embeds use.",+ "settle": 6000,+ "usedBy": ["tutorials/animate-your-avatar", "tutorials/animate-your-agent"]+ },+ {+ "id": "start-checklist",+ "url": "/start",+ "alt": "The three.ws getting-started checklist showing the first setup steps",+ "caption": "The getting-started checklist is the shortest path from account to first agent.",+ "usedBy": ["tutorials/getting-started", "tutorials/first-agent"]+ },+ {+ "id": "marketplace-grid",+ "url": "/marketplace",+ "alt": "The three.ws marketplace grid of published agents",+ "caption": "Published agents land here, forkable by anyone.",+ "usedBy": ["tutorials/share-your-agent"]+ },+ {+ "id": "skills-marketplace",+ "url": "/skills",+ "alt": "The skills marketplace listing paid and free agent skills",+ "caption": "Skills are sold, trialled and installed from this catalogue.",+ "usedBy": ["tutorials/custom-skill", "tutorials/sell-a-skill-with-a-trial"]+ },+ {+ "id": "character-library",+ "url": "/character-library",+ "alt": "The character library grid of ready-to-use rigged characters",+ "caption": "Every character here is a real rigged GLB you can embed as-is.",+ "settle": 5000,+ "usedBy": ["tutorials/character-library-to-embed"]+ },+ {+ "id": "voice-lab",+ "url": "/voice",+ "alt": "The Voice Lab page with the voice catalogue and preview controls",+ "caption": "Voice Lab previews every voice the speech and lipsync stack can drive.",+ "usedBy": ["tutorials/voice-and-lipsync", "tutorials/greeting-and-first-speech"]+ },+ {+ "id": "scene-studio",+ "url": "/scene",+ "alt": "Scene Studio with a 3D scene in the viewport and the object rail",+ "caption": "Scene Studio composes objects and avatars into one shareable scene.",+ "settle": 6000,+ "usedBy": ["tutorials/build-a-scene"]+ },+ {+ "id": "widget-studio",+ "url": "/studio",+ "alt": "The Widget Studio configurator with a live avatar preview and generated embed code",+ "caption": "Widget Studio writes the embed snippet while you watch the result.",+ "settle": 6000,+ "usedBy": ["tutorials/embed-on-website", "tutorials/embed-in-30-seconds"]+ },+ {+ "id": "gallery-grid",+ "url": "/gallery",+ "alt": "The public avatar gallery grid",+ "caption": "Every avatar in the gallery is a real GLB with a public render URL.",+ "settle": 5000,+ "usedBy": ["tutorials/import-avatar-url", "tutorials/upload-custom-glb"]+ },+ {+ "id": "names-claim",+ "url": "/threews/claim",+ "alt": "The threews.sol subdomain claim page with the name availability field",+ "caption": "Claiming a name is one field and one signature.",+ "usedBy": ["tutorials/claim-threews-name"]+ },+ {+ "id": "walk-mobile",+ "url": "/walk",+ "viewport": "mobile",+ "alt": "The Walk experience on a phone-sized viewport with the avatar on screen",+ "caption": "Walk on a phone: the same rig, the same clips, thumb-sized controls.",+ "settle": 8000,+ "usedBy": ["tutorials/walk-companion", "tutorials/view-in-ar"]+ },+ {+ "id": "walk-loop",+ "url": "/walk",+ "alt": "Animated loop of a three.ws avatar walking in the Walk experience",+ "caption": "Captured live: the default rig running the canonical walk clip.",+ "settle": 9000,+ "motion": { "seconds": 3, "fps": 12 },+ "usedBy": ["tutorials/walk-companion"]+ },+ {+ "id": "docs-world-loop",+ "url": "/docs/world",+ "alt": "Animated loop of the 3D Docs World with the guide avatar on the plaza",+ "caption": "The documentation as a place you can walk through.",+ "settle": 10000,+ "motion": { "seconds": 3, "fps": 12 },+ "usedBy": ["tutorials/explore-docs-world"]+ }+ ]+}diff --git a/data/examples.json b/data/examples.jsonindex 37547f1c1..27a2707cb 100644--- a/data/examples.json+++ b/data/examples.json@@ -453,14 +453,14 @@"kind": "package","group": "Package examples","title": "agent-payments-sdk/src/solana",- "description": "",+ "description": "Runnable examples for the Solana half of @three-ws/agent-payments. They read live mainnet data and never sign or send a transaction, so nothing here can spend.","path": "agent-payments-sdk/src/solana/examples","files": ["listen-pump-events.ts"],"run": null,"runKind": "command",- "readme": null,+ "readme": "agent-payments-sdk/src/solana/examples/README.md","owner": "agent-payments-sdk/src/solana"},{diff --git a/data/guide-shots.capture.json b/data/guide-shots.capture.jsonnew file mode 100644index 000000000..6ae4a67e8--- /dev/null+++ b/data/guide-shots.capture.json@@ -0,0 +1,164 @@+{+ "base": "https://three.ws",+ "shots": 11,+ "failed": 0,+ "results": [+ {+ "id": "forge-compose",+ "tutorials": [+ "text-to-3d",+ "nvidia-3d-free"+ ],+ "url": "/forge",+ "path": "/docs/img/guides/forge-compose.png",+ "ok": true,+ "bytes": 251193,+ "width": 484,+ "height": 686,+ "ms": 21953,+ "pageErrors": []+ },+ {+ "id": "forge-quality-tiers",+ "tutorials": [+ "text-to-3d",+ "nvidia-3d-free"+ ],+ "url": "/forge",+ "path": "/docs/img/guides/forge-quality-tiers.png",+ "ok": true,+ "bytes": 109172,+ "width": 442,+ "height": 270,+ "ms": 13636,+ "pageErrors": []+ },+ {+ "id": "forge-stage",+ "tutorials": [+ "text-to-3d",+ "nvidia-3d-free"+ ],+ "url": "/forge",+ "path": "/docs/img/guides/forge-stage.png",+ "ok": true,+ "bytes": 61648,+ "width": 875,+ "height": 732,+ "ms": 10671,+ "pageErrors": []+ },+ {+ "id": "forge-photo-mode",+ "tutorials": [+ "image-to-3d"+ ],+ "url": "/forge",+ "path": "/docs/img/guides/forge-photo-mode.png",+ "ok": true,+ "bytes": 234415,+ "width": 484,+ "height": 924,+ "ms": 11387,+ "pageErrors": []+ },+ {+ "id": "forge-example-chips",+ "tutorials": [+ "prompts-for-3d"+ ],+ "url": "/forge",+ "path": "/docs/img/guides/forge-example-chips.png",+ "ok": true,+ "bytes": 42587,+ "width": 472,+ "height": 131,+ "ms": 7448,+ "pageErrors": []+ },+ {+ "id": "create-intent-hub",+ "tutorials": [+ "getting-started"+ ],+ "url": "/create",+ "path": "/docs/img/guides/create-intent-hub.png",+ "ok": true,+ "bytes": 471808,+ "width": 920,+ "height": 1508,+ "ms": 27387,+ "pageErrors": []+ },+ {+ "id": "studio-workbench",+ "tutorials": [+ "swap-avatar-in-studio"+ ],+ "url": "/studio",+ "path": "/docs/img/guides/studio-workbench.png",+ "ok": true,+ "bytes": 742893,+ "width": 1440,+ "height": 1404,+ "ms": 27228,+ "pageErrors": []+ },+ {+ "id": "app-chat-dock",+ "tutorials": [+ "add-a-3d-assistant"+ ],+ "url": "/app",+ "path": "/docs/img/guides/app-chat-dock.png",+ "ok": true,+ "bytes": 127807,+ "width": 676,+ "height": 131,+ "ms": 88600,+ "pageErrors": []+ },+ {+ "id": "app-action-bar",+ "tutorials": [+ "animate-your-agent"+ ],+ "url": "/app",+ "path": "/docs/img/guides/app-action-bar.png",+ "ok": true,+ "bytes": 62743,+ "width": 696,+ "height": 80,+ "ms": 107857,+ "pageErrors": []+ },+ {+ "id": "docs-sidebar",+ "tutorials": [+ "explore-docs-world"+ ],+ "url": "/docs",+ "path": "/docs/img/guides/docs-sidebar.png",+ "ok": true,+ "bytes": 133786,+ "width": 296,+ "height": 876,+ "ms": 18462,+ "pageErrors": []+ },+ {+ "id": "agents-index",+ "tutorials": [+ "share-your-agent"+ ],+ "url": "/agents",+ "path": "/docs/img/guides/agents-index.png",+ "ok": true,+ "bytes": 310235,+ "width": 1200,+ "height": 360,+ "ms": 9609,+ "pageErrors": []+ }+ ]+}diff --git a/data/guide-shots.json b/data/guide-shots.jsonnew file mode 100644index 000000000..1abfd3090--- /dev/null+++ b/data/guide-shots.json@@ -0,0 +1,182 @@+{+ "_readme": "Every screenshot in docs/tutorials/*.md is declared here and captured from the live product by scripts/capture-guide-shots.mjs. Add a shot, run the capture, run sync:guide-media. Never hand-place an image in a tutorial: check:guide-media fails on anything this file does not describe. See docs/guide-media.md.",+ "defaults": {+ "viewport": { "width": 1440, "height": 900 },+ "scale": 2,+ "settle": 4000+ },+ "shots": [+ {+ "id": "forge-compose",+ "url": "/forge",+ "clip": "form.composer",+ "pad": 22,+ "callouts": [+ { "selector": "#tab-text", "note": "**Describe it** is the text-to-3D tab, and the one the Forge opens on." },+ { "selector": "#prompt", "note": "The prompt box. One object, one material, no scenery." },+ { "selector": "#surprise", "note": "**Surprise me** fills the box with a known-good prompt; **Enhance** rewrites yours into a richer one." },+ { "selector": "#tier", "note": "Quality tier. Draft and Standard are free for everyone." },+ { "selector": "#generate", "note": "Generate. Results stream into the stage on the right." }+ ],+ "alt": "The three.ws Forge compose panel, with the Describe it tab, prompt box, Surprise me and Enhance buttons, the quality tier row, and the Generate button each marked with a numbered callout.",+ "caption": "The Forge compose panel. Everything you need for a text-to-3D run is in this one column.",+ "placements": [+ { "tutorial": "text-to-3d", "anchor": "Step 2 — Describe the object" },+ { "tutorial": "nvidia-3d-free", "anchor": "Step 2 — Describe one object" }+ ]+ },+ {+ "id": "forge-quality-tiers",+ "url": "/forge",+ "clip": ".forge-quality",+ "pad": 18,+ "callouts": [+ { "selector": "#tier", "note": "Draft, Standard and High. Start on Draft or Standard, then re-run the winning prompt on High." },+ { "selector": ".fq-row--engine", "note": "The engine row. Lanes marked FREE need no key and no account." }+ ],+ "alt": "The Forge quality panel showing the Draft, Standard and High tier buttons above a row of generation engines, several labelled FREE, with numbered callouts on the tier row and the engine row.",+ "caption": "Tier and engine sit together: tier decides how much detail you get, engine decides who renders it.",+ "placements": [+ { "tutorial": "text-to-3d", "anchor": "Step 3 — Pick a quality tier" },+ { "tutorial": "nvidia-3d-free", "anchor": "Step 3 — Pick a tier (both free lanes)" }+ ]+ },+ {+ "id": "forge-stage",+ "url": "/forge",+ "clip": "section.stage",+ "pad": 16,+ "alt": "The Forge stage panel, the large viewport where a finished 3D model is displayed and can be orbited.",+ "caption": "The stage. Finished models land here and can be orbited, zoomed and downloaded without leaving the page.",+ "placements": [+ { "tutorial": "text-to-3d", "anchor": "Step 5 — Inspect your model" },+ { "tutorial": "nvidia-3d-free", "anchor": "Step 4 — Generate and inspect" }+ ]+ },+ {+ "id": "forge-photo-mode",+ "url": "/forge",+ "prep": [{ "click": "#tab-image" }, { "wait": 1200 }],+ "clip": "form.composer",+ "pad": 22,+ "callouts": [+ { "selector": "#tab-image", "note": "**From photos** switches the Forge into photo-to-3D mode." },+ { "selector": "#views-grid", "note": "Drop up to six photos of the same object here, taken from different angles." },+ { "selector": "#views-counter", "note": "The view counter. More angles means a more complete reconstruction." }+ ],+ "alt": "The Forge in photo mode, showing the From photos tab selected, an empty grid of reference view slots, and a view counter, each marked with a numbered callout.",+ "caption": "Photo mode. The same panel, swapped from a prompt box to a reference-photo grid.",+ "placements": [+ { "tutorial": "image-to-3d", "anchor": "Step 2 — Open the Forge in photo mode" }+ ]+ },+ {+ "id": "forge-example-chips",+ "url": "/forge",+ "clip": "#examples",+ "pad": 16,+ "callouts": [+ { "selector": "#chips-more", "note": "Expands the list to the full set of worked example prompts." }+ ],+ "alt": "A row of example prompt chips beneath the Forge prompt box, each one a complete ready-to-run prompt, with a callout on the button that reveals more.",+ "caption": "Example chips are complete prompts, not keywords. Tap one to load it, then edit a word or two.",+ "placements": [+ { "tutorial": "prompts-for-3d", "anchor": "The four rules" }+ ]+ },+ {+ "id": "create-intent-hub",+ "url": "/create",+ "clip": "#avatar-options",+ "pad": 20,+ "callouts": [+ { "selector": "#card-default-editor", "note": "Start from a ready-made avatar. Fastest route to something on screen." },+ { "selector": "#card-prompt", "note": "Describe the character you want and have it generated." },+ { "selector": "#card-selfie", "note": "Turn a selfie into an avatar." },+ { "selector": "#card-upload-glb", "note": "Bring a GLB you already have." }+ ],+ "alt": "The three.ws create page showing the avatar option cards: start from a default avatar, describe one, use a selfie, or upload a GLB, each marked with a numbered callout.",+ "caption": "Every route to an avatar starts here. They all end in the same editor, so the choice is reversible.",+ "placements": [+ { "tutorial": "getting-started", "anchor": "Step 1: Open the create flow" }+ ]+ },+ {+ "id": "studio-workbench",+ "url": "/studio",+ "clip": "main.studio-layout",+ "pad": 14,+ "callouts": [+ { "selector": "#avatar-list", "note": "The avatar gallery. Pick a body without leaving the page." },+ { "selector": "#preview-frame", "note": "Live preview. It renders the real widget, not a picture of one." },+ { "selector": "#config-form", "note": "Widget settings. Every change re-renders the preview immediately." },+ { "selector": "#generate-btn", "note": "Produces the embed snippet to paste into your site." }+ ],+ "alt": "The three.ws Widget Studio, a three-column workbench with an avatar gallery on the left, a live widget preview in the middle, and a configuration form on the right, with numbered callouts on each.",+ "caption": "Widget Studio: pick on the left, watch in the middle, configure on the right, and leave with an embed snippet.",+ "placements": [+ { "tutorial": "swap-avatar-in-studio", "anchor": "Step 1 — Open Widget Studio" }+ ]+ },+ {+ "id": "app-chat-dock",+ "url": "/app",+ "clip": "#nxt-chat-dock",+ "pad": 18,+ "callouts": [+ { "selector": "#nxt-chat-input", "note": "Talk to the agent in plain language. It answers in character and moves while it does." },+ { "selector": "#nxt-chat-chips", "note": "Suggested openers, so an empty input is never a dead end." }+ ],+ "alt": "The chat dock in the three.ws viewer, with a message input and a row of suggested opening prompts, each marked with a numbered callout.",+ "caption": "The chat dock. Suggested prompts mean a first-time visitor never has to guess what to type.",+ "placements": [+ { "tutorial": "add-a-3d-assistant", "anchor": "Step 1: the one-tag embed" }+ ]+ },+ {+ "id": "app-action-bar",+ "url": "/app",+ "clip": ".nxt-action-bar--secondary",+ "pad": 18,+ "callouts": [+ { "selector": "#nxt-anim-btn", "note": "Browse the animation library and play any clip on the current avatar. Keyboard: `A`." },+ { "selector": "#nxt-avatar-btn", "note": "Swap the avatar. The scene keeps its camera and backdrop." },+ { "selector": "#nxt-backdrop-btn", "note": "Change the backdrop behind the agent." }+ ],+ "alt": "The secondary action bar in the three.ws viewer with Animations, Avatar and Backdrop buttons, each marked with a numbered callout.",+ "caption": "The action bar. Animations, avatar and backdrop are the three things worth changing first.",+ "placements": [+ { "tutorial": "animate-your-agent", "anchor": "See the whole vocabulary" }+ ]+ },+ {+ "id": "docs-sidebar",+ "url": "/docs",+ "clip": "#sidebar",+ "pad": 14,+ "callouts": [+ { "selector": "#search-input", "note": "Search filters the whole documentation tree as you type." }+ ],+ "alt": "The three.ws documentation sidebar, with a search box above a long navigation tree of sections, and a callout on the search box.",+ "caption": "The docs sidebar. Searching filters the tree in place rather than sending you to a results page.",+ "placements": [+ { "tutorial": "explore-docs-world", "anchor": "Use the index instead of walking" }+ ]+ },+ {+ "id": "agents-index",+ "url": "/agents",+ "clip": "section.hero",+ "pad": 18,+ "callouts": [+ { "selector": "#ag-search", "note": "Search across every published agent." },+ { "selector": "#ag-sort", "note": "Reorder the index. Useful for finding recently published agents." }+ ],+ "alt": "The header of the three.ws agents index, with a wide search field and a sort selector, each marked with a numbered callout.",+ "caption": "The public agents index. Your agent appears here once it is published, and this is the page visitors search.",+ "placements": [+ { "tutorial": "share-your-agent", "anchor": "Step 1 — Find your agent's public URL" }+ ]+ }+ ]+}diff --git a/docs/examples.md b/docs/examples.mdindex 201a19225..622786490 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -774,7 +774,7 @@ The repo ships 40 examples: 11 web component demos, 10 end-to-end projects, and| [`x402-modal-sdk/examples`](../x402-modal-sdk/examples) | A drop-in payment modal for any x402 paid endpoint. | `node x402-modal-sdk/examples/server.mjs` || [`packages/x402-server/examples`](../packages/x402-server/examples) | Runnable examples for the seller half of x402. Each is a standalone .mjs file. | `node packages/x402-server/examples/express-metered-api.mjs` || [`examples`](../examples) | Runnable demos for the three.ws SDKs and agent runtime. Two kinds live here: | `npm run dev, then open /examples/agent-presence.html` |-| [`agent-payments-sdk/src/solana/examples`](../agent-payments-sdk/src/solana/examples) | See the directory for details. | Reference files, nothing to execute |+| [`agent-payments-sdk/src/solana/examples`](../agent-payments-sdk/src/solana/examples) | Runnable examples for the Solana half of @three-ws/agent-payments. They read live mainnet data and never sign or send a transaction, so nothing here can spend. | Reference files, nothing to execute |### Web component demosdiff --git a/docs/tutorials/animate-your-avatar.md b/docs/tutorials/animate-your-avatar.mdindex 78cf83b4e..e9ae4adef 100644--- a/docs/tutorials/animate-your-avatar.md+++ b/docs/tutorials/animate-your-avatar.md@@ -50,8 +50,12 @@ Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `## Step 1: Open the Studio and load an avatar++Open **[/pose](/pose)**. You'll land on the built-in **mannequin** — a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.++In the top bar, click **Load avatar** and pick one of your rigged avatars (or a public one). The right-panel **Animation** section unlocks the moment a compatible rig is loaded.If you'd rather skip the picker, deep-link directly:diff --git a/docs/tutorials/embed-in-30-seconds.md b/docs/tutorials/embed-in-30-seconds.mdindex 30ae760fa..82ebbd201 100644--- a/docs/tutorials/embed-in-30-seconds.md+++ b/docs/tutorials/embed-in-30-seconds.md@@ -20,6 +20,8 @@ Every embedded agent on three.ws has a permanent ID. The `<agent-3d>` tag uses tOpen [https://three.ws/create](https://three.ws/create) in a new tab. The editor loads with a default avatar in the centre of the canvas. You have two paths from here.++### Path A — Use the default and saveIf you want to ship something working as fast as possible, skip every panel for now and click **Save** in the top-right of the editor. The platform creates an agent with the default body, the default personality, and a default greeting. Once saved, the URL in your browser's address bar becomes something like:diff --git a/docs/tutorials/explore-docs-world.md b/docs/tutorials/explore-docs-world.mdindex 7edca88cd..c6d4e5a73 100644--- a/docs/tutorials/explore-docs-world.md+++ b/docs/tutorials/explore-docs-world.md@@ -6,6 +6,8 @@ Time: about 5 minutes. You need a browser and nothing else. By the end you willOpen [three.ws/docs/world](https://three.ws/docs/world).++You spawn in a plaza. Around you is a ring of fourteen glowing pavilions, one per section of the [classic docs](/docs) sidebar: Start here, Creation studios, Trading & markets, SDK / API reference, and so on. The label above each pavilion tells you its section and how many pages it holds.If your device cannot run WebGL you will see a notice with a button to the classic docs instead. Nothing is lost either way; both surfaces render the same markdown files.diff --git a/docs/tutorials/getting-started.md b/docs/tutorials/getting-started.mdindex c78026da8..8c1ee614b 100644--- a/docs/tutorials/getting-started.md+++ b/docs/tutorials/getting-started.md@@ -18,6 +18,8 @@ You: pick a body → name it → describe its personalityResult: three.ws/@aria → a 3D character that talks, on a page you can share```++A concrete example. Say you run a small coffee roaster and want a friendly guide on your site:```@@ -52,6 +54,8 @@ For a deeper take on the distinction, see [Agents vs. Avatars](/docs/agents-vs-aGo to **[/create](/create)**. This is the launchpad for every way to make a body.++You'll see a few starting points. For the fastest five-minute path, you have two good choices:- **Customize a base avatar** (the recommended hero card) — click **Open editor** to sculpt a face, pick outfits, and adjust colors in the browser. Free, no sign-in to start, about a minute.@@ -128,6 +132,21 @@ Each has its own **Copy** button. For sharing in a message, copy the **Direct liThat's it. You created a body, gave it a brain, and shipped a shareable URL.+### See the directory you just joined++Publishing puts your agent in the public directory, and that directory is a plain public API. Press Run below and this page calls it live, from your browser, with no key and no account. The first agent it returns is rendered underneath the response.++```try+GET /api/agents/public?limit=3+title: The public agent directory+note: The same endpoint the marketplace reads. Your published agent appears in this list.+pick: agents[0].avatar_thumbnail+render: image+alt: The portrait of the first agent in the live public directory+```++Every field you filled in above (name, description, skills) is in that JSON. That is what makes an agent embeddable, searchable, and reachable by other agents.+---## Troubleshootingdiff --git a/docs/tutorials/import-avatar-url.md b/docs/tutorials/import-avatar-url.mdindex 0cb5004ae..984343ce2 100644--- a/docs/tutorials/import-avatar-url.md+++ b/docs/tutorials/import-avatar-url.md@@ -65,6 +65,8 @@ The only hard requirements: the URL is `http://` or `https://`, it's publicly reGo to **[/import/rpm](/import/rpm)** (linked from [/create](/create) as the "bring your own avatar" path).++You'll see an import card with two tabs. Leave it on **Paste URL** (the default). The warning banner up top spells out the model: the file is fetched on three.ws servers, so CORS-restricted CDNs all work; the Upload tab is the fallback for files on disk or dead hosts.If you're not signed in, the import call returns a `401` and the page bounces you to `/login?return=/import/rpm` — sign in and you land right back on the importer.diff --git a/docs/tutorials/mint-pumpfun-token.md b/docs/tutorials/mint-pumpfun-token.mdindex 29344a86f..d3508d6b6 100644--- a/docs/tutorials/mint-pumpfun-token.md+++ b/docs/tutorials/mint-pumpfun-token.md@@ -206,6 +206,17 @@ Click your token. The detail panel shows:- Curve fill percentage (how close to graduation)- A trade list with each buy/sell, the wallet, and the amount+The ribbon is rendered from a public endpoint, so you can check the same list without opening the page. Press Run and this tutorial calls it against the live site:++```try+GET /api/pump/launches?limit=5+title: Coins launched through three.ws+note: Public and unauthenticated. Every entry carries the mint plus the agent that launched it.+pick: data.launches[0].mint+```++Copy the mint out of that response and paste it into a Solana explorer to confirm it on-chain. If your token is missing here but visible on Pump.fun, the bonding step (Step 7) did not complete.+This is the same data surfaced on the per-agent dashboard at:```diff --git a/docs/tutorials/render-avatar-images.md b/docs/tutorials/render-avatar-images.mdindex 88323688e..7a1ad4421 100644--- a/docs/tutorials/render-avatar-images.md+++ b/docs/tutorials/render-avatar-images.md@@ -2,6 +2,8 @@By the end of this tutorial you will be rendering live 3D avatars as ordinary images, from a URL, with no 3D engine anywhere in your stack. No three.js, no WebGL context, no GLB loader, no canvas. Just an `<img src>` that happens to point at a headless renderer.++That unlocks the places WebGL cannot go: Open Graph and Twitter cards, transactional email, a Notion page, a PDF, a React Server Component, a Discord bot, a print sheet, an e-ink display, a Rust service that has no business booting a browser. Anywhere an image works, a posed and expressive 3D character now works too.**What you'll build:**diff --git a/docs/tutorials/selfie-to-avatar.md b/docs/tutorials/selfie-to-avatar.mdindex 1a3c24a8a..650587e3f 100644--- a/docs/tutorials/selfie-to-avatar.md+++ b/docs/tutorials/selfie-to-avatar.md@@ -59,6 +59,8 @@ You don't need a studio. A normal selfie in a well-lit room is plenty.Go to **[/scan](/scan)** (it lands you on [/create/selfie](/create/selfie)).++You'll see one required slot: **Add a front-facing photo**. Two ways to fill it:- **Use camera** — opens your camera in the browser with live face guides. Hold still inside the oval; the page checks framing, lighting, blur, and head angle and captures when it's a good frame.diff --git a/docs/tutorials/text-to-3d.md b/docs/tutorials/text-to-3d.mdindex 84b08085f..5ee38c91d 100644--- a/docs/tutorials/text-to-3d.md+++ b/docs/tutorials/text-to-3d.md@@ -12,6 +12,8 @@ Type a sentence, get a downloadable 3D model. That's the whole tutorial. By theGo to [three.ws/forge](/forge).++You'll land on the **Describe it** tab — that's the text-to-3D mode. (The other tabs, **From photos** and **From a sketch**, turn images into models; see [Turn Photos into a 3D Model](/tutorials/image-to-3d) for those.)---@@ -74,6 +76,8 @@ Draft takes roughly 15 seconds; Standard about a minute; High a couple of minuteWhen generation finishes, the model appears in a live 3D viewer:++- **Drag** to rotate, **scroll** to zoom.- Press **F** for cinema mode — a fullscreen turntable. Press **Esc** to exit.- On a phone or AR-capable device, use the AR button to place the model in your room.diff --git a/docs/tutorials/wallet-sign-in.md b/docs/tutorials/wallet-sign-in.mdindex 41f05a13d..9be9e78b2 100644--- a/docs/tutorials/wallet-sign-in.md+++ b/docs/tutorials/wallet-sign-in.md@@ -68,6 +68,14 @@ A real response:Note `domain` and `uri`. Step 3 explains why they are in there.+Do not take that sample on faith. Run the call yourself, from this page, against the live API:++```live+{ "step": "siws-nonce" }+```++That is a real nonce, minted for you a moment ago, expiring five minutes from when you pressed the button. It signs you into nothing: a nonce only becomes a session once a matching signature reaches `verify`. The `csrf` field is hidden in the card because a page that displays a live CSRF token is a page you should not screenshot; your own call receives the real value.+---## Step 3 - Build the message (the step everyone gets wrong)@@ -110,6 +118,14 @@ Three rules about this block:- **`Chain ID` must be `mainnet`, `devnet`, or `testnet`.** A numeric EVM-style chain id gets `invalid_chain`.- **Put the Terms agreement inside the statement.** The signature then evidences acceptance, which is what lets you send `tosAccepted: true` on verify honestly.+Here is that assembly running on the nonce you just minted. Paste your own address if you want to see the exact bytes your wallet would be handed, or leave it blank and read the shape:++```live+{ "step": "siws-message" }+```++Count the blank lines in the output. Line 3 and line 5 are empty, and they are the two most common reasons a first integration returns `invalid_message`.+---## Step 4 - Sign it, then verify@@ -162,6 +178,14 @@ A signed-in response carries `id`, `email`, `display_name`, `plan`, `is_admin`,For a wallet-created account, `email` is a synthetic placeholder like `[email protected]` and `display_name` is the truncated address. Treat both as display fallbacks, not as a real inbox.+Run it against your own browser. The card sends your cookies, so what comes back depends on whether you are signed in to three.ws right now, and either answer is the lesson:++```live+{ "step": "auth-me" }+```++If you are signed out you should see `200` with `{"user": null}`, which is exactly the shape that fools a `status === 401` check. If you are signed in, note that `sid` comes back redacted in this view for the reason above.+---## Step 6 - Turn error codes into instructionsdiff --git a/pages/tutorial.html b/pages/tutorial.htmlindex 9e7622ea1..d738eddae 100644--- a/pages/tutorial.html+++ b/pages/tutorial.html@@ -44,6 +44,8 @@href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"/><link rel="stylesheet" href="/mobile.css" />+ <!-- Runnable ```live blocks: real API calls rendered inline. See /docs/live-steps. -->+ <link rel="stylesheet" href="/live-steps.css" /><scriptsrc="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"integrity="sha384-odPBjvtXVM/5hOYIr3A1dB+flh0c3wAT3bSesIOqEGmyUA4JoKf/YTWy0XKOYAY7"@@ -57,6 +59,7 @@<script defer src="/nav.js"></script><script defer src="/footer-newsletter.js"></script><script defer src="/tutorials-manifest.js"></script>+ <script defer src="/live-steps.js"></script><scripttype="module"src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"@@ -857,6 +860,7 @@height: 18px;}+@media (prefers-reduced-motion: reduce) {.tdoc-progress-fill,.tdoc-copy-btn,@@ -878,6 +882,11 @@<meta property="og:image:alt" content="Tutorial · Text Prompt to 3D Model — three.ws"><meta name="twitter:site" content="@trythreews"><script src="/model-viewer-meshopt.js"></script>+ <!-- Resolves the `figure:` directives in tutorial markdown into real captured+ media, live 3D viewers, and a keyboard-navigable lightbox. The stylesheet+ is shared with the cookbook recipe viewer, so both render figures alike. -->+ <link rel="stylesheet" href="/tutorial-figures.css">+ <script src="/tutorial-figures.js"></script></head><body class="home-page tutorial-page tut-doc-page"><div class="cursor" id="cursor" aria-hidden="true"></div>@@ -1338,8 +1347,19 @@});article.innerHTML = marked.parse(md);++ // Swap every ```live block for a card that calls the real API.+ // Runs before the highlight pass so those blocks are already+ // gone by the time hljs walks the remaining code samples.+ window.LiveSteps?.mount(article);+article.querySelectorAll('pre code').forEach((b) => hljs.highlightElement(b));+ // Figures collect their placeholders synchronously, so this is+ // safe to leave unawaited: the media arrives into boxes that+ // were already reserved, and nothing below them moves.+ window.tutorialFigures?.mount(article);+// Rewrite internal .md links and /docs/* refs so they navigate cleanlyarticle.querySelectorAll('a[href]').forEach((a) => {const h = a.getAttribute('href');diff --git a/public/doc-figures.css b/public/doc-figures.cssnew file mode 100644index 000000000..0bbdcde6f--- /dev/null+++ b/public/doc-figures.css@@ -0,0 +1,401 @@+/*+ * doc-figures.css — presentation for the figures /doc-figures.js builds.+ *+ * Loaded by both markdown viewers (docs/index.html and pages/tutorial.html).+ * The docs shell is dark-only; the tutorial viewer honours [data-theme='light'],+ * so every colour here is a token with a light override at the bottom rather+ * than a hard-coded value.+ */++.doc-figure {+ --df-border: rgba(255, 255, 255, 0.09);+ --df-surface: rgba(255, 255, 255, 0.028);+ --df-surface-hover: rgba(255, 255, 255, 0.05);+ --df-text: rgba(224, 224, 224, 0.85);+ --df-muted: rgba(224, 224, 224, 0.55);+ --df-accent: #8b5cf6;+ margin: 2rem 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.6rem;+}++/* The image is a button so it is reachable by keyboard and announced as an+ action, not decoration. Everything below strips the default button chrome. */+.doc-figure-open {+ position: relative;+ display: block;+ width: 100%;+ padding: 0;+ border: 1px solid var(--df-border);+ border-radius: 14px;+ background: var(--df-surface);+ cursor: zoom-in;+ overflow: hidden;+ font: inherit;+ color: inherit;+ transition:+ border-color 0.18s ease,+ background 0.18s ease,+ transform 0.18s ease,+ box-shadow 0.18s ease;+}++.doc-figure-open:hover {+ border-color: rgba(139, 92, 246, 0.45);+ background: var(--df-surface-hover);+ transform: translateY(-1px);+ box-shadow: 0 12px 34px rgba(0, 0, 0, 0.34);+}++.doc-figure-open:focus-visible {+ outline: 2px solid var(--df-accent);+ outline-offset: 3px;+}++/* Sized from the manifest's intrinsic dimensions, so the box exists before the+ image decodes and the article never reflows around it. */+.doc-figure-media {+ display: block;+ width: 100%;+ background:+ linear-gradient(135deg, rgba(139, 92, 246, 0.07), transparent 60%),+ rgba(255, 255, 255, 0.02);+}++.doc-figure-media img {+ display: block;+ width: 100%;+ height: auto;+ margin: 0;+ border: 0;+ border-radius: 0;+}++.doc-figure-badge {+ position: absolute;+ top: 10px;+ left: 10px;+ display: inline-flex;+ align-items: center;+ gap: 0.4em;+ padding: 0.28em 0.66em;+ border-radius: 999px;+ background: rgba(9, 9, 15, 0.78);+ border: 1px solid rgba(139, 92, 246, 0.5);+ color: #e9ddff;+ font-size: 0.72rem;+ font-weight: 600;+ letter-spacing: 0.02em;+ backdrop-filter: blur(6px);+}++.doc-figure-badge::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #8b5cf6;+ box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.25);+}++.doc-figure-zoom {+ position: absolute;+ right: 10px;+ bottom: 10px;+ display: grid;+ place-items: center;+ width: 30px;+ height: 30px;+ border-radius: 9px;+ background: rgba(9, 9, 15, 0.72);+ border: 1px solid rgba(255, 255, 255, 0.14);+ color: #fff;+ opacity: 0;+ transform: translateY(4px);+ transition:+ opacity 0.18s ease,+ transform 0.18s ease;+ backdrop-filter: blur(6px);+}++.doc-figure-open:hover .doc-figure-zoom,+.doc-figure-open:focus-visible .doc-figure-zoom {+ opacity: 1;+ transform: translateY(0);+}++.doc-figure-caption {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.4rem 0.9rem;+ font-size: 0.88rem;+ line-height: 1.55;+ color: var(--df-muted);+}++.doc-figure-text {+ color: var(--df-text);+}++.doc-figure-source {+ font-size: 0.78rem;+ color: var(--df-muted);+ text-decoration: none;+ border-bottom: 1px dashed rgba(255, 255, 255, 0.22);+ white-space: nowrap;+}++.doc-figure-source:hover {+ color: var(--df-accent);+ border-bottom-color: currentColor;+}++/* ── Lightbox ───────────────────────────────────────────────────────────── */++html.doc-lightbox-locked {+ overflow: hidden;+}++.doc-lightbox {+ position: fixed;+ inset: 0;+ z-index: 3000;+ display: grid;+ place-items: center;+ opacity: 0;+ transition: opacity 0.18s ease;+}++.doc-lightbox.open {+ opacity: 1;+}++.doc-lightbox[hidden] {+ display: none;+}++.doc-lightbox-backdrop {+ position: absolute;+ inset: 0;+ background: rgba(4, 4, 9, 0.86);+ backdrop-filter: blur(10px);+ cursor: zoom-out;+}++.doc-lightbox-frame {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.9rem;+ max-width: min(94vw, 1500px);+ max-height: 92vh;+ padding: 0 3.4rem;+ pointer-events: none;+}++.doc-lightbox-frame > * {+ pointer-events: auto;+}++.doc-lightbox-figure {+ margin: 0;+ display: flex;+ flex-direction: column;+ gap: 0.7rem;+ min-height: 0;+}++.doc-lightbox-img {+ display: block;+ max-width: 100%;+ max-height: 78vh;+ width: auto;+ height: auto;+ border-radius: 12px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ box-shadow: 0 30px 90px rgba(0, 0, 0, 0.6);+ cursor: zoom-in;+ transition: transform 0.22s ease;+}++.doc-lightbox-img.zoomed {+ transform: scale(2);+ cursor: zoom-out;+}++.doc-lightbox-caption {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ align-items: baseline;+ gap: 0.35rem 0.85rem;+ max-width: 68ch;+ margin: 0 auto;+ text-align: center;+ font-size: 0.9rem;+ line-height: 1.55;+ color: rgba(235, 235, 245, 0.82);+}++.doc-lightbox-source {+ font-size: 0.79rem;+ color: rgba(235, 235, 245, 0.6);+ text-decoration: none;+ border-bottom: 1px dashed rgba(255, 255, 255, 0.28);+}++.doc-lightbox-source:hover {+ color: #c4b5fd;+}++.doc-lightbox-close,+.doc-lightbox-nav {+ position: absolute;+ display: grid;+ place-items: center;+ width: 42px;+ height: 42px;+ border-radius: 50%;+ border: 1px solid rgba(255, 255, 255, 0.16);+ background: rgba(18, 18, 28, 0.82);+ color: #fff;+ cursor: pointer;+ transition:+ background 0.16s ease,+ border-color 0.16s ease,+ transform 0.16s ease;+}++.doc-lightbox-close:hover,+.doc-lightbox-nav:hover {+ background: rgba(139, 92, 246, 0.3);+ border-color: rgba(139, 92, 246, 0.6);+ transform: scale(1.06);+}++.doc-lightbox-close:focus-visible,+.doc-lightbox-nav:focus-visible {+ outline: 2px solid #8b5cf6;+ outline-offset: 3px;+}++.doc-lightbox-close {+ top: -6px;+ right: 0;+}++.doc-lightbox-prev {+ left: 0;+ top: 50%;+ transform: translateY(-50%);+}++.doc-lightbox-next {+ right: 0;+ top: 50%;+ transform: translateY(-50%);+}++.doc-lightbox-prev:hover,+.doc-lightbox-next:hover {+ transform: translateY(-50%) scale(1.06);+}++.doc-lightbox-nav[hidden] {+ display: none;+}++.doc-lightbox-count {+ font-size: 0.78rem;+ letter-spacing: 0.06em;+ color: rgba(235, 235, 245, 0.5);+ font-variant-numeric: tabular-nums;+}++/* ── Small screens ──────────────────────────────────────────────────────── */++@media (max-width: 640px) {+ .doc-figure {+ margin: 1.5rem 0;+ }++ .doc-lightbox-frame {+ padding: 0 0.75rem;+ max-width: 100vw;+ }++ /* Side arrows would sit on top of the image at this width; drop them to the+ bottom rail where the thumb already is. */+ .doc-lightbox-prev,+ .doc-lightbox-next {+ top: auto;+ bottom: -4px;+ transform: none;+ }++ .doc-lightbox-prev:hover,+ .doc-lightbox-next:hover {+ transform: scale(1.06);+ }++ .doc-lightbox-prev {+ left: 12%;+ }++ .doc-lightbox-next {+ right: 12%;+ }++ .doc-lightbox-img {+ max-height: 62vh;+ }++ .doc-lightbox-caption {+ font-size: 0.83rem;+ }+}++/* ── Light theme (the tutorial viewer supports it; the docs shell is dark) ── */++[data-theme='light'] .doc-figure {+ --df-border: rgba(15, 17, 26, 0.12);+ --df-surface: rgba(15, 17, 26, 0.02);+ --df-surface-hover: rgba(15, 17, 26, 0.045);+ --df-text: rgba(20, 22, 32, 0.88);+ --df-muted: rgba(20, 22, 32, 0.6);+}++[data-theme='light'] .doc-figure-open:hover {+ box-shadow: 0 12px 30px rgba(20, 22, 40, 0.12);+}++[data-theme='light'] .doc-figure-source {+ border-bottom-color: rgba(15, 17, 26, 0.24);+}++[data-theme='light'] .doc-figure-media {+ background:+ linear-gradient(135deg, rgba(139, 92, 246, 0.08), transparent 60%),+ rgba(15, 17, 26, 0.03);+}++/* ── Motion preferences ─────────────────────────────────────────────────── */++@media (prefers-reduced-motion: reduce) {+ .doc-figure-open,+ .doc-figure-zoom,+ .doc-lightbox,+ .doc-lightbox-img,+ .doc-lightbox-close,+ .doc-lightbox-nav {+ transition: none;+ }++ .doc-figure-open:hover {+ transform: none;+ }+}diff --git a/public/doc-figures.js b/public/doc-figures.jsnew file mode 100644index 000000000..61f3deaf9--- /dev/null+++ b/public/doc-figures.js@@ -0,0 +1,340 @@+/**+ * doc-figures.js — turns plain markdown images into first-class documentation figures.+ *+ * Both documentation surfaces render the same markdown files with `marked`: the+ * docs shell (/docs/…) and the standalone tutorial viewer (/tutorials/…). Left+ * alone, `marked` emits a bare `<img>`: no caption, no intrinsic size (so the+ * article jumps when it decodes), no way to see detail in a 1200px screenshot+ * squeezed into a 720px column, and no answer to the reader's real question,+ * "is this what the product looks like *now*?".+ *+ * This upgrades every image the docs own into a <figure> that answers all four:+ *+ * • Intrinsic dimensions come from /docs/media-manifest.json before the image+ * loads, so the box is reserved and nothing shifts.+ * • The markdown title becomes a real <figcaption>.+ * • Provenance ("captured from /create/prompt") links to the live route, so a+ * reader can check the screenshot against the product in one click.+ * • Click or press Enter to open a lightbox with zoom, arrow-key paging+ * between every figure on the page, and a focus trap.+ *+ * Authors write nothing but ordinary markdown:+ *+ * + *+ * so the same file still renders correctly on GitHub, in an LLM's plain-text+ * fetch, and in any other markdown viewer. Progressive enhancement only: with+ * this script blocked, every image is still a working image.+ *+ * Usage (both viewers do exactly this after setting innerHTML):+ *+ * DocFigures.upgrade(document.getElementById('docs-content'));+ */+(function () {+ 'use strict';++ var MANIFEST_URL = '/docs/media-manifest.json';+ var OWNED_PREFIX = '/docs/img/';+ var manifestPromise = null;++ function loadManifest() {+ if (!manifestPromise) {+ manifestPromise = fetch(MANIFEST_URL)+ .then(function (res) {+ return res.ok ? res.json() : { shots: {} };+ })+ .catch(function () {+ // The manifest is an enhancement, not a dependency: without it the+ // figures still render, they just size themselves on decode.+ return { shots: {} };+ });+ }+ return manifestPromise;+ }++ function shotIdFor(src) {+ var path = src.split('?')[0].split('#')[0];+ if (path.indexOf(OWNED_PREFIX) === -1) return null;+ var file = path.slice(path.indexOf(OWNED_PREFIX) + OWNED_PREFIX.length);+ return file.replace(/\.(webp|png|jpe?g|gif|avif)$/i, '') || null;+ }++ function prefersReducedMotion() {+ return window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ }++ function formatCapturedAt(iso) {+ var date = new Date(iso);+ if (isNaN(date.getTime())) return null;+ return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });+ }++ // ── Lightbox ────────────────────────────────────────────────────────────────+ // One instance per page, built on first open and reused. It owns the figures+ // of whichever article opened it, so arrow keys page through that article.++ var lightbox = null;++ function buildLightbox() {+ var overlay = document.createElement('div');+ overlay.className = 'doc-lightbox';+ overlay.setAttribute('role', 'dialog');+ overlay.setAttribute('aria-modal', 'true');+ overlay.setAttribute('aria-label', 'Image viewer');+ overlay.hidden = true;+ overlay.innerHTML =+ '<div class="doc-lightbox-backdrop" data-close></div>' ++ '<div class="doc-lightbox-frame">' ++ '<figure class="doc-lightbox-figure">' ++ '<img class="doc-lightbox-img" alt="" />' ++ '<figcaption class="doc-lightbox-caption"><span class="doc-lightbox-text"></span> <a class="doc-lightbox-source" target="_blank" rel="noopener"></a></figcaption>' ++ '</figure>' ++ '<button type="button" class="doc-lightbox-close" data-close aria-label="Close image viewer">' ++ '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>' ++ '</button>' ++ '<button type="button" class="doc-lightbox-nav doc-lightbox-prev" aria-label="Previous image">' ++ '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 5-7 7 7 7"/></svg>' ++ '</button>' ++ '<button type="button" class="doc-lightbox-nav doc-lightbox-next" aria-label="Next image">' ++ '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 5 7 7-7 7"/></svg>' ++ '</button>' ++ '<div class="doc-lightbox-count" aria-live="polite"></div>' ++ '</div>';+ document.body.appendChild(overlay);++ var state = { items: [], index: 0, opener: null, zoomed: false };+ var img = overlay.querySelector('.doc-lightbox-img');+ var text = overlay.querySelector('.doc-lightbox-text');+ var source = overlay.querySelector('.doc-lightbox-source');+ var count = overlay.querySelector('.doc-lightbox-count');+ var prev = overlay.querySelector('.doc-lightbox-prev');+ var next = overlay.querySelector('.doc-lightbox-next');+ var closeBtn = overlay.querySelector('.doc-lightbox-close');++ function setZoom(on) {+ state.zoomed = on;+ img.classList.toggle('zoomed', on);+ img.setAttribute('aria-label', on ? 'Zoomed in. Click to zoom out.' : 'Click to zoom in.');+ }++ function show(index) {+ if (!state.items.length) return;+ state.index = (index + state.items.length) % state.items.length;+ var item = state.items[state.index];+ setZoom(false);+ img.src = item.src;+ img.alt = item.alt || '';+ text.textContent = item.caption || item.alt || '';+ if (item.route) {+ source.textContent = 'View ' + item.route;+ source.href = item.route;+ source.hidden = false;+ } else {+ source.hidden = true;+ }+ count.textContent = state.items.length > 1 ? state.index + 1 + ' / ' + state.items.length : '';+ var multiple = state.items.length > 1;+ prev.hidden = !multiple;+ next.hidden = !multiple;+ }++ function close() {+ overlay.hidden = true;+ overlay.classList.remove('open');+ document.documentElement.classList.remove('doc-lightbox-locked');+ img.src = '';+ if (state.opener && document.contains(state.opener)) state.opener.focus();+ state.opener = null;+ }++ function onKey(event) {+ if (overlay.hidden) return;+ if (event.key === 'Escape') {+ event.preventDefault();+ close();+ } else if (event.key === 'ArrowRight') {+ event.preventDefault();+ show(state.index + 1);+ } else if (event.key === 'ArrowLeft') {+ event.preventDefault();+ show(state.index - 1);+ } else if (event.key === 'Tab') {+ // Focus trap: the overlay is modal, so Tab must never reach the+ // article behind it.+ var focusable = Array.prototype.filter.call(+ overlay.querySelectorAll('button:not([hidden]), a[href]:not([hidden])'),+ function (el) {+ return el.offsetParent !== null;+ },+ );+ if (!focusable.length) return;+ var first = focusable[0];+ var last = focusable[focusable.length - 1];+ if (event.shiftKey && document.activeElement === first) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && document.activeElement === last) {+ event.preventDefault();+ first.focus();+ }+ }+ }++ overlay.addEventListener('click', function (event) {+ if (event.target.hasAttribute('data-close') || event.target.closest('[data-close]')) close();+ });+ prev.addEventListener('click', function () {+ show(state.index - 1);+ });+ next.addEventListener('click', function () {+ show(state.index + 1);+ });+ img.addEventListener('click', function () {+ setZoom(!state.zoomed);+ });+ img.addEventListener('mousemove', function (event) {+ if (!state.zoomed) return;+ var rect = img.getBoundingClientRect();+ img.style.transformOrigin =+ ((event.clientX - rect.left) / rect.width) * 100 ++ '% ' ++ ((event.clientY - rect.top) / rect.height) * 100 ++ '%';+ });+ document.addEventListener('keydown', onKey);++ return {+ open: function (items, index, opener) {+ state.items = items;+ state.opener = opener || null;+ overlay.hidden = false;+ document.documentElement.classList.add('doc-lightbox-locked');+ if (!prefersReducedMotion()) {+ requestAnimationFrame(function () {+ overlay.classList.add('open');+ });+ } else {+ overlay.classList.add('open');+ }+ show(index);+ closeBtn.focus();+ },+ };+ }++ // ── Figure upgrade ──────────────────────────────────────────────────────────++ function upgradeImage(img, shot, group) {+ var caption = img.getAttribute('title') || (shot && shot.caption) || '';+ var figure = document.createElement('figure');+ figure.className = 'doc-figure';+ if (shot && shot.animated) figure.classList.add('is-animated');++ var button = document.createElement('button');+ button.type = 'button';+ button.className = 'doc-figure-open';+ button.setAttribute(+ 'aria-label',+ 'Open image' + (img.alt ? ': ' + img.alt : '') + ' in the full-size viewer',+ );++ var media = document.createElement('span');+ media.className = 'doc-figure-media';+ if (shot && shot.width && shot.height) {+ // Reserve the exact box the image will occupy. This is the whole+ // reason the manifest carries dimensions.+ media.style.aspectRatio = shot.width + ' / ' + shot.height;+ }++ img.removeAttribute('title');+ img.loading = 'lazy';+ img.decoding = 'async';+ if (shot && shot.width) img.width = shot.width;+ if (shot && shot.height) img.height = shot.height;+ if (!img.alt && shot && shot.alt) img.alt = shot.alt;++ img.parentNode.insertBefore(figure, img);+ media.appendChild(img);+ button.appendChild(media);++ if (shot && shot.animated) {+ var badge = document.createElement('span');+ badge.className = 'doc-figure-badge';+ badge.textContent = 'Live capture';+ button.appendChild(badge);+ }++ var zoomHint = document.createElement('span');+ zoomHint.className = 'doc-figure-zoom';+ zoomHint.setAttribute('aria-hidden', 'true');+ zoomHint.innerHTML =+ '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6M11 8.4v5.2M8.4 11h5.2"/></svg>';+ button.appendChild(zoomHint);+ figure.appendChild(button);++ if (caption || (shot && shot.route)) {+ var figcaption = document.createElement('figcaption');+ figcaption.className = 'doc-figure-caption';+ if (caption) {+ var span = document.createElement('span');+ span.className = 'doc-figure-text';+ span.textContent = caption;+ figcaption.appendChild(span);+ }+ if (shot && shot.route) {+ var meta = document.createElement('a');+ meta.className = 'doc-figure-source';+ meta.href = shot.route;+ var when = shot.capturedAt ? formatCapturedAt(shot.capturedAt) : null;+ meta.textContent = 'Captured from ' + shot.route + (when ? ' · ' + when : '');+ meta.title = 'Open the live page this image was captured from';+ figcaption.appendChild(meta);+ }+ figure.appendChild(figcaption);+ }++ var item = {+ src: img.currentSrc || img.src,+ alt: img.alt,+ caption: caption,+ route: shot ? shot.route : null,+ };+ group.push(item);+ var index = group.length - 1;+ button.addEventListener('click', function () {+ if (!lightbox) lightbox = buildLightbox();+ lightbox.open(group, index, button);+ });+ }++ /**+ * Upgrade every markdown image inside `root`. Safe to call repeatedly; an+ * already-upgraded image is skipped.+ *+ * @param {Element} root container holding freshly rendered markdown+ * @returns {Promise<number>} how many figures were upgraded+ */+ function upgrade(root) {+ if (!root) return Promise.resolve(0);+ return loadManifest().then(function (manifest) {+ var shots = (manifest && manifest.shots) || {};+ var images = Array.prototype.slice.call(root.querySelectorAll('img'));+ var group = [];+ var upgraded = 0;+ images.forEach(function (img) {+ if (img.closest('.doc-figure')) return;+ // Inline badges (shields, icons) are not figures; only images the+ // docs own, or any image an author explicitly opted in, qualify.+ var src = img.getAttribute('src') || '';+ var id = shotIdFor(src);+ var optedIn = img.hasAttribute('data-figure');+ if (!id && !optedIn) return;+ upgradeImage(img, id ? shots[id] : null, group);+ upgraded++;+ });+ return upgraded;+ });+ }++ window.DocFigures = { upgrade: upgrade, loadManifest: loadManifest };+})();diff --git a/public/docs/img/asl-alphabet-hero.png b/public/docs/img/asl-alphabet-hero.pngindex 866141951..0cbc33f16 100644Binary files a/public/docs/img/asl-alphabet-hero.png and b/public/docs/img/asl-alphabet-hero.png differdiff --git a/public/docs/img/asl-practice.png b/public/docs/img/asl-practice.pngindex 1061a47cd..2c96855ec 100644Binary files a/public/docs/img/asl-practice.png and b/public/docs/img/asl-practice.png differdiff --git a/public/docs/img/asl-sign-language-hero.png b/public/docs/img/asl-sign-language-hero.pngindex 658f82972..fface8adb 100644Binary files a/public/docs/img/asl-sign-language-hero.png and b/public/docs/img/asl-sign-language-hero.png differdiff --git a/public/docs/img/gestures-override.png b/public/docs/img/gestures-override.pngindex 012a6bb74..636bf2e1e 100644Binary files a/public/docs/img/gestures-override.png and b/public/docs/img/gestures-override.png differdiff --git a/public/docs/img/guides/agents-index.png b/public/docs/img/guides/agents-index.pngnew file mode 100644index 000000000..a5c11fd4cBinary files /dev/null and b/public/docs/img/guides/agents-index.png differdiff --git a/public/docs/img/guides/app-action-bar.png b/public/docs/img/guides/app-action-bar.pngnew file mode 100644index 000000000..c4ff4e176Binary files /dev/null and b/public/docs/img/guides/app-action-bar.png differdiff --git a/public/docs/img/guides/app-chat-dock.png b/public/docs/img/guides/app-chat-dock.pngnew file mode 100644index 000000000..986ff31daBinary files /dev/null and b/public/docs/img/guides/app-chat-dock.png differdiff --git a/public/docs/img/guides/create-intent-hub.png b/public/docs/img/guides/create-intent-hub.pngnew file mode 100644index 000000000..63e226bddBinary files /dev/null and b/public/docs/img/guides/create-intent-hub.png differdiff --git a/public/docs/img/guides/docs-sidebar.png b/public/docs/img/guides/docs-sidebar.pngnew file mode 100644index 000000000..63d2b676cBinary files /dev/null and b/public/docs/img/guides/docs-sidebar.png differdiff --git a/public/docs/img/guides/forge-compose.png b/public/docs/img/guides/forge-compose.pngnew file mode 100644index 000000000..74e8b061eBinary files /dev/null and b/public/docs/img/guides/forge-compose.png differdiff --git a/public/docs/img/guides/forge-example-chips.png b/public/docs/img/guides/forge-example-chips.pngnew file mode 100644index 000000000..3fb6ddde5Binary files /dev/null and b/public/docs/img/guides/forge-example-chips.png differdiff --git a/public/docs/img/guides/forge-photo-mode.png b/public/docs/img/guides/forge-photo-mode.pngnew file mode 100644index 000000000..183bd807aBinary files /dev/null and b/public/docs/img/guides/forge-photo-mode.png differdiff --git a/public/docs/img/guides/forge-quality-tiers.png b/public/docs/img/guides/forge-quality-tiers.pngnew file mode 100644index 000000000..161b2c4ebBinary files /dev/null and b/public/docs/img/guides/forge-quality-tiers.png differdiff --git a/public/docs/img/guides/forge-stage.png b/public/docs/img/guides/forge-stage.pngnew file mode 100644index 000000000..e2638dc54Binary files /dev/null and b/public/docs/img/guides/forge-stage.png differdiff --git a/public/docs/img/guides/studio-workbench.png b/public/docs/img/guides/studio-workbench.pngnew file mode 100644index 000000000..2526411abBinary files /dev/null and b/public/docs/img/guides/studio-workbench.png differdiff --git a/public/docs/img/start-checklist.webp b/public/docs/img/start-checklist.webpnew file mode 100644index 000000000..ae1b38fbcBinary files /dev/null and b/public/docs/img/start-checklist.webp differdiff --git a/public/docs/img/tutorials/animate-your-avatar/page-pose-6e5f8fe8.webp b/public/docs/img/tutorials/animate-your-avatar/page-pose-6e5f8fe8.webpnew file mode 100644index 000000000..664bf54aaBinary files /dev/null and b/public/docs/img/tutorials/animate-your-avatar/page-pose-6e5f8fe8.webp differdiff --git a/public/docs/img/tutorials/embed-in-30-seconds/page-create-c95f4de2.webp b/public/docs/img/tutorials/embed-in-30-seconds/page-create-c95f4de2.webpnew file mode 100644index 000000000..2eb127b2eBinary files /dev/null and b/public/docs/img/tutorials/embed-in-30-seconds/page-create-c95f4de2.webp differdiff --git a/public/docs/img/tutorials/explore-docs-world/page-docs-world-98864ac3.webp b/public/docs/img/tutorials/explore-docs-world/page-docs-world-98864ac3.webpnew file mode 100644index 000000000..1cc4de2b6Binary files /dev/null and b/public/docs/img/tutorials/explore-docs-world/page-docs-world-98864ac3.webp differdiff --git a/public/docs/img/tutorials/import-avatar-url/page-import-rpm-42d33be8.webp b/public/docs/img/tutorials/import-avatar-url/page-import-rpm-42d33be8.webpnew file mode 100644index 000000000..0a7111920Binary files /dev/null and b/public/docs/img/tutorials/import-avatar-url/page-import-rpm-42d33be8.webp differdiff --git a/public/docs/img/tutorials/render-avatar-images/glb-avatars-michelle-565d843d.webp b/public/docs/img/tutorials/render-avatar-images/glb-avatars-michelle-565d843d.webpnew file mode 100644index 000000000..1880069e9Binary files /dev/null and b/public/docs/img/tutorials/render-avatar-images/glb-avatars-michelle-565d843d.webp differdiff --git a/public/docs/img/tutorials/selfie-to-avatar/page-scan-cec4b358.webp b/public/docs/img/tutorials/selfie-to-avatar/page-scan-cec4b358.webpnew file mode 100644index 000000000..555cf4758Binary files /dev/null and b/public/docs/img/tutorials/selfie-to-avatar/page-scan-cec4b358.webp differdiff --git a/public/docs/img/tutorials/text-to-3d/page-forge-be755d6a.webp b/public/docs/img/tutorials/text-to-3d/page-forge-be755d6a.webpnew file mode 100644index 000000000..1eeda33a6Binary files /dev/null and b/public/docs/img/tutorials/text-to-3d/page-forge-be755d6a.webp differdiff --git a/public/docs/media-manifest.json b/public/docs/media-manifest.jsonnew file mode 100644index 000000000..0d87bfbe5--- /dev/null+++ b/public/docs/media-manifest.json@@ -0,0 +1,22 @@+{+ "generatedBy": "scripts/capture-doc-media.mjs",+ "generatedAt": "2026-07-31T06:28:53.164Z",+ "shots": {+ "start-checklist": {+ "id": "start-checklist",+ "src": "/docs/img/start-checklist.webp",+ "alt": "The three.ws getting-started checklist showing the first setup steps",+ "caption": "The getting-started checklist is the shortest path from account to first agent.",+ "route": "/start",+ "viewport": "desktop",+ "animated": false,+ "capturedAt": "2026-07-31T06:26:37.985Z",+ "capturedFrom": "http://localhost:3000",+ "commit": "75883898b",+ "sha256": "57f49a4e06061c0f50ea15ee04f72fc65d76318bdef17bda4cae94a2242abde3",+ "bytes": 64358,+ "width": 1800,+ "height": 1125+ }+ }+}diff --git a/public/examples.json b/public/examples.jsonindex 46dbfb9a2..1d6ed2588 100644--- a/public/examples.json+++ b/public/examples.json@@ -453,14 +453,14 @@"kind": "package","group": "Package examples","title": "agent-payments-sdk/src/solana",- "description": "",+ "description": "Runnable examples for the Solana half of @three-ws/agent-payments. They read live mainnet data and never sign or send a transaction, so nothing here can spend.","path": "agent-payments-sdk/src/solana/examples","files": ["listen-pump-events.ts"],"run": null,"runKind": "command",- "readme": null,+ "readme": "agent-payments-sdk/src/solana/examples/README.md","owner": "agent-payments-sdk/src/solana"},{@@ -468,7 +468,7 @@"kind": "html-demo","group": "Web component demos","title": "<agent-3d wallet> - the portable agent wallet",- "description": "Finding a public agent to show…",+ "description": "The wallet is portable on its own too - mount it into any element (here, a light-DOM card; it also works inside a closed shadow root).","path": "examples/agent-wallet-embed.html","files": ["agent-wallet-embed.html"diff --git a/public/tutorial-figures.css b/public/tutorial-figures.cssnew file mode 100644index 000000000..2b4569c48--- /dev/null+++ b/public/tutorial-figures.css@@ -0,0 +1,411 @@+/*+ * tutorial-figures.css: the shared presentation layer for `figure:` media.+ *+ * Pairs with /tutorial-figures.js, which turns the `figure:` directives in+ * markdown into captioned, zoomable <figure> elements. These rules used to live+ * inline in pages/tutorial.html, which meant only the tutorial viewer could show+ * a figure. They are a file now so every markdown viewer can link them: the+ * tutorial viewer (.tdoc-article) and the cookbook recipe viewer (.cb-article)+ * both do.+ *+ * Adding a third viewer is one more selector in the :is() lists below, not a+ * copy of this file.+ */++/* ── Figures ─────────────────────────────────────────────────+ Mounted by /tutorial-figures.js from the `figure:` directives in+ the markdown. Every frame declares its intrinsic aspect ratio, so+ the article reserves the exact box before the image arrives and+ nothing under it moves. */++:is(.tdoc-article, .cb-article) .tfig {+ margin: 2rem 0;+ padding: 0;+}++.tfig-body {+ position: relative;+ border-radius: 12px;+ overflow: hidden;+ border: 1px solid rgba(255, 255, 255, 0.09);+ background:+ linear-gradient(180deg, rgba(255, 255, 255, 0.035), rgba(255, 255, 255, 0.008));+ box-shadow: 0 12px 40px -18px rgba(0, 0, 0, 0.85);+}++.tfig-frame {+ position: relative;+ display: block;+ width: 100%;+ background-size: cover;+ background-position: center;+}++.tfig-frame-img.is-loading::after {+ content: '';+ position: absolute;+ inset: 0;+ backdrop-filter: blur(12px);+ background: rgba(8, 8, 8, 0.25);+}++:is(.tdoc-article, .cb-article) .tfig-img {+ display: block;+ width: 100%;+ height: auto;+ margin: 0;+ border: none;+ border-radius: 0;+ opacity: 0;+ transition: opacity 0.45s ease;+}++.tfig-frame.is-ready .tfig-img {+ opacity: 1;+}++.tfig-frame.is-broken .tfig-img {+ opacity: 1;+}++.tfig-frame-live {+ aspect-ratio: 4 / 3;+ background:+ radial-gradient(ellipse 70% 70% at 50% 45%, var(--tdoc-accent-soft, rgba(255, 255, 255, 0.1)) 0%, transparent 70%),+ #0b0b0c;+}++.tfig-frame-live model-viewer {+ width: 100%;+ height: 100%;+ --poster-color: transparent;+ background: transparent;+}++.tfig-frame-live model-viewer:focus-visible {+ outline: 2px solid var(--tdoc-accent, #fff);+ outline-offset: -2px;+}++/* Fallback card: shown when a page figure has no capture yet. It is a+ real link to the real page, never a broken image. */+.tfig-frame-card {+ aspect-ratio: 16 / 7;+}++.tfig-card {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ justify-content: center;+ gap: 0.4rem;+ padding: clamp(1rem, 4vw, 2rem);+ text-decoration: none;+ background:+ radial-gradient(ellipse 60% 100% at 0% 50%, var(--tdoc-accent-soft, rgba(255, 255, 255, 0.1)) 0%, transparent 70%);+ transition: background 0.2s ease;+}++.tfig-card:hover {+ background:+ radial-gradient(ellipse 80% 120% at 0% 50%, var(--tdoc-accent-soft, rgba(255, 255, 255, 0.16)) 0%, transparent 70%);+}++.tfig-card:focus-visible {+ outline: 2px solid var(--tdoc-accent, #fff);+ outline-offset: -3px;+}++.tfig-card-eyebrow {+ font-family: var(--font-display);+ font-size: 0.64rem;+ font-weight: 700;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--tdoc-accent, rgba(255, 255, 255, 0.6));+}++.tfig-card-path {+ font-family: 'JetBrains Mono', monospace;+ font-size: clamp(1rem, 3vw, 1.35rem);+ color: rgba(255, 255, 255, 0.92);+}++.tfig-card-cta {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ font-family: 'Inter', sans-serif;+ font-size: 0.82rem;+ color: rgba(255, 255, 255, 0.55);+}++/* Zoom affordance */+.tfig-body.is-zoomable .tfig-img {+ cursor: zoom-in;+}++.tfig-zoom {+ position: absolute;+ top: 0.6rem;+ right: 0.6rem;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ border-radius: 8px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(10, 10, 10, 0.66);+ backdrop-filter: blur(8px);+ color: rgba(255, 255, 255, 0.78);+ cursor: zoom-in;+ opacity: 0;+ transform: translateY(-4px);+ transition:+ opacity 0.18s ease,+ transform 0.18s ease,+ color 0.18s ease;+}++.tfig-body:hover .tfig-zoom,+.tfig-zoom:focus-visible {+ opacity: 1;+ transform: translateY(0);+}++.tfig-zoom:hover {+ color: #fff;+ border-color: var(--tdoc-accent, #fff);+}++.tfig-zoom:focus-visible {+ outline: 2px solid var(--tdoc-accent, #fff);+ outline-offset: 2px;+}++@media (hover: none) {+ .tfig-zoom {+ opacity: 1;+ transform: none;+ }+}++:is(.tdoc-article, .cb-article) .tfig-caption {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.5rem;+ margin: 0.7rem 0 0;+ font-family: 'Inter', sans-serif;+ font-size: 0.82rem;+ line-height: 1.55;+ color: rgba(255, 255, 255, 0.52);+}++.tfig-num {+ font-family: var(--font-display);+ font-size: 0.64rem;+ font-weight: 700;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--tdoc-accent, rgba(255, 255, 255, 0.7));+ white-space: nowrap;+}++.tfig-text {+ flex: 1 1 14rem;+ min-width: 0;+}++.tfig-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ padding: 0.16rem 0.5rem;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ font-size: 0.68rem;+ color: rgba(255, 255, 255, 0.42);+ white-space: nowrap;+}++.tfig-badge svg {+ flex-shrink: 0;+}++/* ── Lightbox ──────────────────────────────────────────────── */++html.tfig-lb-open,+html.tfig-lb-open body {+ overflow: hidden;+}++.tfig-lightbox {+ position: fixed;+ inset: 0;+ z-index: 900;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: clamp(1rem, 4vw, 3rem);+ background: rgba(4, 4, 5, 0.9);+ backdrop-filter: blur(10px);+ animation: tfig-fade 0.18s ease;+}++.tfig-lightbox[hidden] {+ display: none;+}++@keyframes tfig-fade {+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }+}++.tfig-lb-inner {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.9rem;+ max-width: min(1200px, 100%);+ max-height: 100%;+}++.tfig-lb-img {+ max-width: 100%;+ max-height: calc(100vh - 9rem);+ width: auto;+ height: auto;+ border-radius: 10px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ box-shadow: 0 30px 90px -30px rgba(0, 0, 0, 0.9);+}++.tfig-lb-bar {+ display: flex;+ align-items: baseline;+ gap: 0.9rem;+ flex-wrap: wrap;+ justify-content: center;+ font-family: 'Inter', sans-serif;+ font-size: 0.85rem;+ color: rgba(255, 255, 255, 0.72);+ text-align: center;+}++.tfig-lb-count {+ font-family: 'JetBrains Mono', monospace;+ font-size: 0.72rem;+ color: rgba(255, 255, 255, 0.4);+}++.tfig-lb-close,+.tfig-lb-nav {+ position: absolute;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 10px;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(16, 16, 18, 0.8);+ color: rgba(255, 255, 255, 0.8);+ cursor: pointer;+ transition:+ color 0.15s ease,+ border-color 0.15s ease;+}++.tfig-lb-close {+ top: clamp(0.75rem, 3vw, 1.5rem);+ right: clamp(0.75rem, 3vw, 1.5rem);+ width: 40px;+ height: 40px;+}++.tfig-lb-nav {+ top: 50%;+ transform: translateY(-50%);+ width: 44px;+ height: 44px;+ font-size: 1.1rem;+ line-height: 1;+}++.tfig-lb-nav.prev {+ left: clamp(0.5rem, 2vw, 1.5rem);+}+.tfig-lb-nav.next {+ right: clamp(0.5rem, 2vw, 1.5rem);+}++.tfig-lb-close:hover,+.tfig-lb-nav:hover {+ color: #fff;+ border-color: rgba(255, 255, 255, 0.5);+}++.tfig-lb-close:focus-visible,+.tfig-lb-nav:focus-visible {+ outline: 2px solid #fff;+ outline-offset: 2px;+}++@media (max-width: 540px) {+ .tfig-lb-nav {+ top: auto;+ bottom: clamp(0.5rem, 3vw, 1.5rem);+ transform: none;+ }+ :is(.tdoc-article, .cb-article) .tfig-caption {+ font-size: 0.78rem;+ }+}++/* Light theme: the frames sit on paper, so the borders and captions+ invert rather than staying ghost-white on white. */+html[data-theme='light'] .tfig-body {+ border-color: rgba(0, 0, 0, 0.1);+ background: linear-gradient(180deg, rgba(0, 0, 0, 0.02), rgba(0, 0, 0, 0.005));+ box-shadow: 0 10px 30px -20px rgba(0, 0, 0, 0.35);+}+html[data-theme='light'] .tfig-frame-live {+ background:+ radial-gradient(ellipse 70% 70% at 50% 45%, var(--tdoc-accent-soft, rgba(0, 0, 0, 0.06)) 0%, transparent 70%),+ #f4f4f5;+}+html[data-theme='light'] :is(.tdoc-article, .cb-article) .tfig-caption {+ color: rgba(0, 0, 0, 0.58);+}+html[data-theme='light'] .tfig-badge {+ border-color: rgba(0, 0, 0, 0.12);+ color: rgba(0, 0, 0, 0.45);+}+html[data-theme='light'] .tfig-card-path {+ color: rgba(0, 0, 0, 0.86);+}+html[data-theme='light'] .tfig-card-cta {+ color: rgba(0, 0, 0, 0.5);+}+html[data-theme='light'] .tfig-zoom {+ background: rgba(255, 255, 255, 0.8);+ border-color: rgba(0, 0, 0, 0.12);+ color: rgba(0, 0, 0, 0.7);+}++@media (prefers-reduced-motion: reduce) {+ .tfig-zoom,+ :is(.tdoc-article, .cb-article) .tfig-img,+ .tfig-card {+ transition: none;+ }+ .tfig-lightbox {+ animation: none;+ }+}diff --git a/public/tutorial-figures.js b/public/tutorial-figures.jsnew file mode 100644index 000000000..42f9fa8f3--- /dev/null+++ b/public/tutorial-figures.js@@ -0,0 +1,363 @@+/*+ * tutorial-figures.js — resolves the `figure:` directives in tutorial markdown+ * into real, captioned, zoomable media.+ *+ * A tutorial author writes an ordinary markdown image:+ *+ * + * + * + *+ * marked turns that into <img src="figure:page:/forge">, which no browser can+ * load. This script runs immediately after the parse and swaps each one for a+ * <figure>: a numbered caption, an intrinsic-size box so the page never shifts,+ * a blurred placeholder that resolves into the real capture, and click-to-zoom.+ *+ * Media comes from /tutorial-media.json, written by+ * scripts/capture-tutorial-media.mjs from real screenshots of the deployed site+ * and real renders from /api/render/glb. Nothing is drawn or stock-sourced.+ *+ * Every kind has a real fallback, so a missing capture degrades instead of+ * breaking: a model figure falls back to the interactive <model-viewer> of the+ * same GLB, and a page figure falls back to a link card that opens the real+ * page. A tutorial never renders a broken image icon.+ */+(function () {+ 'use strict';++ var MANIFEST_URL = '/tutorial-media.json';+ var manifestPromise = null;++ function loadManifest() {+ if (!manifestPromise) {+ manifestPromise = fetch(MANIFEST_URL, { headers: { accept: 'application/json' } })+ .then(function (res) {+ if (!res.ok) throw new Error('HTTP ' + res.status);+ return res.json();+ })+ .then(function (json) {+ return (json && json.figures) || {};+ })+ .catch(function () {+ // A missing manifest is not a page failure: every figure has a+ // live fallback, so the tutorial still renders completely.+ return {};+ });+ }+ return manifestPromise;+ }++ function parseDirective(raw) {+ var body = raw.slice('figure:'.length);+ var colon = body.indexOf(':');+ if (colon === -1) return null;+ var kind = body.slice(0, colon);+ if (kind !== 'page' && kind !== 'glb' && kind !== 'live') return null;+ var rest = body.slice(colon + 1);+ var q = rest.indexOf('?');+ return {+ kind: kind,+ target: q === -1 ? rest : rest.slice(0, q),+ params: new URLSearchParams(q === -1 ? '' : rest.slice(q + 1)),+ };+ }++ function el(tag, className, text) {+ var node = document.createElement(tag);+ if (className) node.className = className;+ if (text != null) node.textContent = text;+ return node;+ }++ var ICON_ZOOM =+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5M11 8v6M8 11h6"/></svg>';+ var ICON_ORBIT =+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><ellipse cx="12" cy="12" rx="10" ry="4.5" transform="rotate(-24 12 12)"/></svg>';+ var ICON_LINK =+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/></svg>';+ var ICON_CLOSE =+ '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>';++ function badge(icon, label) {+ var span = el('span', 'tfig-badge');+ span.innerHTML = icon;+ span.appendChild(el('span', null, label));+ return span;+ }++ /** An interactive viewer, used both as the `live` kind and as the model fallback. */+ function buildViewer(target, orbit) {+ var viewer = document.createElement('model-viewer');+ viewer.setAttribute('src', target);+ viewer.setAttribute('camera-controls', '');+ // A turntable that never stops is motion the reader did not ask for.+ // Orbiting by hand still works; only the automatic spin is dropped.+ var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ if (!reduce) {+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('auto-rotate-delay', '600');+ }+ viewer.setAttribute('rotation-per-second', '16deg');+ viewer.setAttribute('interaction-prompt', 'none');+ viewer.setAttribute('shadow-intensity', '0');+ viewer.setAttribute('exposure', '0.95');+ viewer.setAttribute('environment-image', 'neutral');+ viewer.setAttribute('camera-orbit', orbit || '0deg 78deg 4.5m');+ viewer.setAttribute('field-of-view', '32deg');+ viewer.setAttribute('loading', 'lazy');+ viewer.setAttribute('alt', '');+ viewer.setAttribute('tabindex', '0');+ return viewer;+ }++ function buildImage(record, alt) {+ var frame = el('div', 'tfig-frame tfig-frame-img');+ frame.style.aspectRatio = record.width + ' / ' + record.height;+ if (record.placeholder) {+ frame.style.backgroundImage = 'url("' + record.placeholder + '")';+ frame.classList.add('is-loading');+ }+ var img = new Image();+ img.src = record.src;+ img.alt = alt;+ img.width = record.width;+ img.height = record.height;+ img.loading = 'lazy';+ img.decoding = 'async';+ img.className = 'tfig-img';+ img.addEventListener('load', function () {+ frame.classList.remove('is-loading');+ frame.classList.add('is-ready');+ });+ img.addEventListener('error', function () {+ frame.classList.remove('is-loading');+ frame.classList.add('is-broken');+ });+ frame.appendChild(img);+ return { frame: frame, img: img };+ }++ /** The honest fallback for a page figure with no capture yet: go see the real thing. */+ function buildPageCard(target, alt) {+ var frame = el('div', 'tfig-frame tfig-frame-card');+ var link = el('a', 'tfig-card');+ link.href = target;+ link.rel = 'noopener';+ link.innerHTML =+ '<span class="tfig-card-eyebrow">Live page</span>' ++ '<span class="tfig-card-path"></span>' ++ '<span class="tfig-card-cta">Open it and follow along ' ++ ICON_LINK ++ '</span>';+ link.querySelector('.tfig-card-path').textContent = target;+ link.setAttribute('aria-label', alt + ' (opens ' + target + ')');+ frame.appendChild(link);+ return frame;+ }++ function mountFigure(img, record, index, lightbox) {+ var raw = img.getAttribute('src') || '';+ var directive = parseDirective(raw);+ if (!directive) return null;++ var alt = (img.getAttribute('alt') || '').trim() || 'Figure ' + index;+ var figure = el('figure', 'tfig');+ figure.id = 'figure-' + index;+ var body = el('div', 'tfig-body');+ var zoomable = null;+ var kindBadge = null;++ if (directive.kind === 'live' || (!record && (directive.kind === 'glb' || directive.kind === 'live'))) {+ var orbit = (record && record.orbit) || directive.params.get('orbit');+ var frame = el('div', 'tfig-frame tfig-frame-live');+ frame.appendChild(buildViewer(directive.target, orbit));+ body.appendChild(frame);+ kindBadge = badge(ICON_ORBIT, 'Drag to orbit');+ } else if (record && record.src) {+ var built = buildImage(record, alt);+ body.appendChild(built.frame);+ zoomable = built;+ kindBadge = badge(ICON_ZOOM, 'Click to enlarge');+ } else {+ body.appendChild(buildPageCard(directive.target, alt));+ kindBadge = badge(ICON_LINK, 'Open the page');+ }++ if (zoomable) {+ var button = el('button', 'tfig-zoom');+ button.type = 'button';+ button.setAttribute('aria-label', 'Enlarge figure ' + index + ': ' + alt);+ button.innerHTML = ICON_ZOOM;+ body.appendChild(button);+ body.classList.add('is-zoomable');+ var open = function () {+ lightbox.open(index);+ };+ button.addEventListener('click', open);+ zoomable.img.addEventListener('click', open);+ }++ figure.appendChild(body);++ var caption = el('figcaption', 'tfig-caption');+ var num = el('span', 'tfig-num', 'Figure ' + index);+ caption.appendChild(num);+ caption.appendChild(el('span', 'tfig-text', alt));+ if (kindBadge) caption.appendChild(kindBadge);+ figure.appendChild(caption);++ return { figure: figure, alt: alt, record: record, kind: directive.kind, target: directive.target };+ }++ // ── Lightbox ───────────────────────────────────────────────────────────────+ // One dialog for the whole page. Arrow keys move between figures, Escape+ // closes, and focus returns to the control that opened it.++ function createLightbox() {+ var shots = [];+ var current = 0;+ var opener = null;+ var dialog = el('div', 'tfig-lightbox');+ dialog.setAttribute('role', 'dialog');+ dialog.setAttribute('aria-modal', 'true');+ dialog.setAttribute('aria-label', 'Figure viewer');+ dialog.hidden = true;+ dialog.innerHTML =+ '<div class="tfig-lb-inner">' ++ '<img class="tfig-lb-img" alt="" />' ++ '<div class="tfig-lb-bar">' ++ '<span class="tfig-lb-caption"></span>' ++ '<span class="tfig-lb-count"></span>' ++ '</div>' ++ '</div>' ++ '<button type="button" class="tfig-lb-close" aria-label="Close figure viewer">' ++ ICON_CLOSE ++ '</button>' ++ '<button type="button" class="tfig-lb-nav prev" aria-label="Previous figure">←</button>' ++ '<button type="button" class="tfig-lb-nav next" aria-label="Next figure">→</button>';++ var lbImg = dialog.querySelector('.tfig-lb-img');+ var lbCaption = dialog.querySelector('.tfig-lb-caption');+ var lbCount = dialog.querySelector('.tfig-lb-count');+ var closeBtn = dialog.querySelector('.tfig-lb-close');+ var prevBtn = dialog.querySelector('.tfig-lb-nav.prev');+ var nextBtn = dialog.querySelector('.tfig-lb-nav.next');++ function show(i) {+ if (!shots.length) return;+ current = (i + shots.length) % shots.length;+ var shot = shots[current];+ lbImg.src = shot.record.src;+ lbImg.alt = shot.alt;+ lbCaption.textContent = shot.alt;+ lbCount.textContent = shots.length > 1 ? current + 1 + ' of ' + shots.length : '';+ var multi = shots.length > 1;+ prevBtn.hidden = !multi;+ nextBtn.hidden = !multi;+ }++ function close() {+ dialog.hidden = true;+ document.documentElement.classList.remove('tfig-lb-open');+ document.removeEventListener('keydown', onKey, true);+ if (opener && typeof opener.focus === 'function') opener.focus();+ opener = null;+ }++ function onKey(ev) {+ if (ev.key === 'Escape') {+ ev.preventDefault();+ close();+ } else if (ev.key === 'ArrowRight') {+ ev.preventDefault();+ show(current + 1);+ } else if (ev.key === 'ArrowLeft') {+ ev.preventDefault();+ show(current - 1);+ } else if (ev.key === 'Tab') {+ // Keep focus inside the dialog while it is modal.+ var focusable = [closeBtn, prevBtn, nextBtn].filter(function (b) {+ return !b.hidden;+ });+ var at = focusable.indexOf(document.activeElement);+ ev.preventDefault();+ var nextIndex = ev.shiftKey ? at - 1 : at + 1;+ focusable[(nextIndex + focusable.length) % focusable.length].focus();+ }+ }++ closeBtn.addEventListener('click', close);+ prevBtn.addEventListener('click', function () {+ show(current - 1);+ });+ nextBtn.addEventListener('click', function () {+ show(current + 1);+ });+ dialog.addEventListener('click', function (ev) {+ if (ev.target === dialog || ev.target.classList.contains('tfig-lb-inner')) close();+ });++ return {+ node: dialog,+ register: function (shot) {+ shots.push(shot);+ return shots.length - 1;+ },+ open: function (figureIndex) {+ var at = shots.findIndex(function (s) {+ return s.figureIndex === figureIndex;+ });+ if (at === -1) return;+ opener = document.activeElement;+ dialog.hidden = false;+ document.documentElement.classList.add('tfig-lb-open');+ show(at);+ closeBtn.focus();+ document.addEventListener('keydown', onKey, true);+ },+ };+ }++ // ── Mount ──────────────────────────────────────────────────────────────────++ function mount(article) {+ if (!article) return Promise.resolve(0);+ var placeholders = Array.prototype.slice.call(article.querySelectorAll('img[src^="figure:"]'));+ if (!placeholders.length) return Promise.resolve(0);++ return loadManifest().then(function (figures) {+ var lightbox = document.querySelector('.tfig-lightbox') ? null : createLightbox();+ if (lightbox) document.body.appendChild(lightbox.node);+ else lightbox = window.__tfigLightbox;+ window.__tfigLightbox = lightbox;++ var mounted = 0;+ placeholders.forEach(function (img, i) {+ var raw = img.getAttribute('src') || '';+ var index = i + 1;+ var built = mountFigure(img, figures[raw], index, lightbox);+ if (!built) {+ img.remove();+ return;+ }+ // marked wraps a lone image in a paragraph; a <figure> inside a <p>+ // is invalid and the browser will hoist it, so replace the wrapper.+ var host = img.parentElement;+ var replaceTarget =+ host && host.tagName === 'P' && host.childNodes.length === 1 ? host : img;+ replaceTarget.replaceWith(built.figure);+ if (built.record && built.record.src && built.kind !== 'live') {+ lightbox.register({+ figureIndex: index,+ alt: built.alt,+ record: built.record,+ });+ }+ mounted += 1;+ });+ return mounted;+ });+ }++ window.tutorialFigures = { mount: mount };+})();diff --git a/public/tutorial-media.json b/public/tutorial-media.jsonnew file mode 100644index 000000000..40af4c761--- /dev/null+++ b/public/tutorial-media.json@@ -0,0 +1,114 @@+{+ "$comment": "GENERATED by scripts/capture-tutorial-media.mjs. Do not edit; run `npm run tutorials:media`.",+ "base": "https://three.ws",+ "site": "https://three.ws",+ "commit": "56c50559f9907778747340d1e9fea105c54148f1",+ "capturedAt": "2026-07-31T06:38:18.622Z",+ "figures": {+ "figure:glb:/avatars/michelle.glb?w=1200&h=1000": {+ "kind": "glb",+ "src": "/docs/img/tutorials/render-avatar-images/glb-avatars-michelle-565d843d.webp",+ "width": 1200,+ "height": 1000,+ "placeholder": "data:image/webp;base64,UklGRnYBAABXRUJQVlA4WAoAAAAQAAAAEwAAEAAAQUxQSKsAAAANuTJE9D80cBxJcuScoAL5/5dqrTlvqMa5VyjajRp3sMKdsehETMAEbOL7iXNn3t279r91Yd3Br3yT6Wcv6h4t8htptFfUrZoOwsT3qT0gLtXVjyKI72YoGvspAYT8gx2s1LGPMfwToGn8sanFwK/UhAxNQqAwwYM6D3affgMFA6MBLnAqNGXaKHVjx1S7XGBEg68ARCFlADnCJWBMTskoNj0hj1mGCWQ1fgYAVlA4IKQAAABwBACdASoUABEAPu1sq1EppaOiqAqpMB2JbAC7DBIwFBkNwqlW4MfaCN6ACAD+pfdBIUKtq4ZKOGmfHKZE+8jwHoBSisvAx9TLrP2Pz1tEvO2DZuxrACcmfgbAPD58BWiRKnEfp/dLEgItbjBBtsjKG3rsC7zP5aRP/+8ie0XTDbzWMvfo6mGKrkQ/4HmHFZUfQywDhDc6kuALwFcsQPui1gAAAA==",+ "source": "https://three.ws/avatars/michelle.glb",+ "tutorials": [+ "render-avatar-images"+ ]+ },+ "figure:live:/avatars/default.glb": {+ "kind": "live",+ "model": "/avatars/default.glb",+ "orbit": null,+ "source": "https://three.ws/avatars/default.glb",+ "tutorials": [+ "getting-started"+ ]+ },+ "figure:live:/avatars/fox.glb?orbit=25deg+72deg+3.2m": {+ "kind": "live",+ "model": "/avatars/fox.glb",+ "orbit": "25deg 72deg 3.2m",+ "source": "https://three.ws/avatars/fox.glb",+ "tutorials": [+ "text-to-3d"+ ]+ },+ "figure:live:/avatars/mannequin.glb": {+ "kind": "live",+ "model": "/avatars/mannequin.glb",+ "orbit": null,+ "source": "https://three.ws/avatars/mannequin.glb",+ "tutorials": [+ "animate-your-avatar"+ ]+ },+ "figure:page:/create": {+ "kind": "page",+ "src": "/docs/img/tutorials/embed-in-30-seconds/page-create-c95f4de2.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRj4AAABXRUJQVlA4IDIAAAAwAwCdASoUAAwAPu1iqk2ppaQiMAgBMB2JaQAAetHT2BoAAP7wtpvEmNXE0SZyoAAAAA==",+ "source": "https://three.ws/create",+ "tutorials": [+ "embed-in-30-seconds",+ "getting-started"+ ]+ },+ "figure:page:/docs/world?settle=9000": {+ "kind": "page",+ "src": "/docs/img/tutorials/explore-docs-world/page-docs-world-98864ac3.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAADQAgCdASoUAAwAPu1iqU2ppaOiMAgBMB2JaQAAijeAAP7wtGuwmzAgTsUKAAAA",+ "source": "https://three.ws/docs/world",+ "tutorials": [+ "explore-docs-world"+ ]+ },+ "figure:page:/forge": {+ "kind": "page",+ "src": "/docs/img/tutorials/text-to-3d/page-forge-be755d6a.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRkQAAABXRUJQVlA4IDgAAAAwAwCdASoUAAwAPu1iqU2ppaOiMAgBMB2JaQAAW+lhScUwAP7w1SjXcRIn1IbJjhAFFveexJwAAA==",+ "source": "https://three.ws/forge",+ "tutorials": [+ "text-to-3d"+ ]+ },+ "figure:page:/import/rpm": {+ "kind": "page",+ "src": "/docs/img/tutorials/import-avatar-url/page-import-rpm-42d33be8.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRj4AAABXRUJQVlA4IDIAAAAwAwCdASoUAAwAPu1iqU2ppaOiMAgBMB2JaQAAW+qpUSgAAP7ypwE0v0XD7ktY4TQAAA==",+ "source": "https://three.ws/import/rpm",+ "tutorials": [+ "import-avatar-url"+ ]+ },+ "figure:page:/pose?settle=6000": {+ "kind": "page",+ "src": "/docs/img/tutorials/animate-your-avatar/page-pose-6e5f8fe8.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRkIAAABXRUJQVlA4IDYAAAAQAwCdASoUAAwAPu1iqk4ppaQiMAgBMB2JaQAAetGDHAAA/vCeu2zZVGzaoRW1uMN9vyKQAAA=",+ "source": "https://three.ws/pose",+ "tutorials": [+ "animate-your-avatar"+ ]+ },+ "figure:page:/scan": {+ "kind": "page",+ "src": "/docs/img/tutorials/selfie-to-avatar/page-scan-cec4b358.webp",+ "width": 2560,+ "height": 1520,+ "placeholder": "data:image/webp;base64,UklGRjQAAABXRUJQVlA4ICgAAACwAgCdASoUAAwAPu1iqU2ppaQiMAgBMB2JaQAAeyAA/vDtzS+UgAAA",+ "source": "https://three.ws/scan",+ "tutorials": [+ "selfie-to-avatar"+ ]+ }+ }+}diff --git a/scripts/audit-overlays.mjs b/scripts/audit-overlays.mjsnew file mode 100644index 000000000..c70849ff9--- /dev/null+++ b/scripts/audit-overlays.mjs@@ -0,0 +1,578 @@+#!/usr/bin/env node+/**+ * audit-overlays.mjs — prove that no floating widget covers another.+ *+ * three.ws grew a lot of persistent, viewport-anchored UI: the Walk Companion,+ * the corner stack ("Getting started", feature discovery, the language FAB),+ * cookie and consent bars, sticky headers and CTA rails, chat launchers, the+ * command palette. Each one is independently correct. Together they compete for+ * the same few hundred pixels, and the failure is invisible to unit tests and to+ * whoever built either widget — it only appears on the one page where both are+ * on, at the one viewport where they touch.+ *+ * Every fix for that class of bug so far has been a bug report, a hand+ * measurement, and a magic offset. This script replaces the hand measurement.+ * It drives a real Chromium over real routes at real viewports, finds every+ * painted `position: fixed | sticky` overlay root, and computes the pairwise+ * intersections. A collision is reported when two independent overlays overlap+ * enough to hide each other's controls.+ *+ * It writes visual evidence, not just a list: each finding gets a screenshot of+ * the page with the two offenders outlined and their intersection filled, and+ * the run produces a browsable report at reports/overlays/index.html.+ *+ * ── What counts as a collision ────────────────────────────────────────────────+ * • Both parties are painted (they have a background, border, shadow, or a+ * canvas/img/video/svg inside). A transparent positioning wrapper hides+ * nothing and is not a finding.+ * • At least one party is interactive (focusable, or contains something+ * focusable that can receive pointer events). Two decorative layers+ * overlapping is a design choice.+ * • The overlap clears both thresholds: --min-area px² and --min-ratio of the+ * SMALLER party's area. Ratio alone flags hairline seams on huge bars;+ * area alone flags a 1% clip of two full-width rails.+ * • Neither party is an ancestor of the other, and they are not the same+ * stacking family (a widget's own dropdown is allowed to sit on it).+ *+ * Full-viewport scrims (>= 90% of the viewport) are classified as `layer` and+ * reported separately: a modal backdrop covering the page is correct, a stray+ * one is a serious bug, and neither is an overlay-vs-overlay collision.+ *+ * ── Usage ─────────────────────────────────────────────────────────────────────+ * npm run audit:overlays # curated widget-heavy routes, 3 viewports+ * npm run audit:overlays -- --all # every HTML route in data/pages.json+ * npm run audit:overlays -- --routes /,/examples,/docs+ * npm run audit:overlays -- --base https://three.ws+ * npm run audit:overlays -- --viewport mobile+ * npm run audit:overlays -- --json # machine-readable findings on stdout+ * npm run audit:overlays -- --no-widgets # audit the page's own chrome only+ *+ * Exits 1 when any collision is found, so it can gate a release. Everything it+ * writes lands under reports/ (gitignored).+ */+import { chromium } from 'playwright';+import { mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const OUT_DIR = path.join(ROOT, 'reports/overlays');++// ── CLI ───────────────────────────────────────────────────────────────────────+const argv = process.argv.slice(2);+const has = (n) => argv.includes(`--${n}`);+const opt = (n, d) => {+ const i = argv.indexOf(`--${n}`);+ return i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d;+};++const BASE = (opt('base', process.env.BASE_URL || 'http://localhost:3000')).replace(/\/$/, '');+const JSON_ONLY = has('json');+const ALL_ROUTES = has('all');+const WITH_WIDGETS = !has('no-widgets');+const SETTLE_MS = Math.max(0, Number(opt('settle', 6000)) || 6000);+const MIN_AREA = Math.max(0, Number(opt('min-area', 900)) || 900);+const MIN_RATIO = Math.max(0, Number(opt('min-ratio', 0.06)) || 0.06);+const CONCURRENCY = Math.max(1, Number(opt('concurrency', 2)) || 2);++const VIEWPORTS = [+ { id: 'desktop', width: 1440, height: 900 },+ { id: 'tablet', width: 834, height: 1112 },+ { id: 'mobile', width: 390, height: 844 },+];+const viewportFilter = opt('viewport', null);+const viewports = viewportFilter+ ? VIEWPORTS.filter((v) => v.id === viewportFilter)+ : VIEWPORTS;++// Routes where persistent widgets actually stack up: the marketing surfaces a+// first-time visitor lands on, the doc surfaces the companion follows them+// onto, and the dense app pages where a covered control is unrecoverable.+const CURATED_ROUTES = [+ '/',+ '/examples',+ '/docs',+ '/create',+ '/agents',+ '/marketplace',+ '/pricing',+ '/walk',+ '/embed',+ '/pay',+];++function manifestRoutes() {+ const pages = JSON.parse(readFileSync(path.join(ROOT, 'data/pages.json'), 'utf8'));+ const out = [];+ for (const s of pages.sections || []) {+ if (s.id === 'machine') continue;+ for (const p of s.pages || []) {+ if (!p.path || !p.path.startsWith('/') || /[:*]/.test(p.path)) continue;+ if (/\.(xml|txt|json|js|png|svg|ico)$/.test(p.path)) continue;+ if (p.path.startsWith('/.well-known')) continue;+ if (p.auth) continue;+ out.push(p.path);+ }+ }+ return [...new Set(out)];+}++const explicit = (opt('routes', '') || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+const routes = explicit.length ? explicit : ALL_ROUTES ? manifestRoutes() : CURATED_ROUTES;++// ── The in-page collector ─────────────────────────────────────────────────────+// Serialised into the browser. Everything it needs must live inside it.+function collectOverlays() {+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const FOCUSABLE =+ 'a[href],button,input,select,textarea,summary,[tabindex]:not([tabindex="-1"]),[role="button"],[role="link"],[contenteditable="true"]';++ const clip = (r) => ({+ left: Math.max(0, r.left),+ top: Math.max(0, r.top),+ right: Math.min(vw, r.right),+ bottom: Math.min(vh, r.bottom),+ });+ const areaOf = (b) => Math.max(0, b.right - b.left) * Math.max(0, b.bottom - b.top);++ // A wrapper that paints nothing cannot hide anything behind it. Shadows count:+ // a large blurred shadow is exactly how a floating card asserts itself.+ function paints(el, cs) {+ if (cs.backgroundImage && cs.backgroundImage !== 'none') return true;+ if (cs.boxShadow && cs.boxShadow !== 'none') return true;+ if (cs.borderTopWidth !== '0px' && cs.borderTopColor !== 'rgba(0, 0, 0, 0)') return true;+ if (cs.backdropFilter && cs.backdropFilter !== 'none') return true;+ const bg = cs.backgroundColor || '';+ const m = bg.match(/rgba?\(([^)]+)\)/);+ if (m) {+ const parts = m[1].split(',').map((n) => parseFloat(n));+ const alpha = parts.length > 3 ? parts[3] : 1;+ if (alpha > 0.02) return true;+ }+ if (el.querySelector('canvas,img,video,svg,picture')) return true;+ // Bare text on a transparent background still occludes visually.+ if ((el.textContent || '').trim().length > 0 && el.children.length === 0) return true;+ return false;+ }++ function interactive(el, cs) {+ if (cs.pointerEvents !== 'none' && el.matches(FOCUSABLE)) return true;+ for (const child of el.querySelectorAll(FOCUSABLE)) {+ if (getComputedStyle(child).pointerEvents !== 'none') return true;+ }+ return false;+ }++ function label(el) {+ if (el.id) return '#' + el.id;+ const cls = (el.getAttribute('class') || '')+ .split(/\s+/)+ .filter(Boolean)+ .slice(0, 2)+ .join('.');+ const tag = el.tagName.toLowerCase();+ return cls ? `${tag}.${cls}` : tag;+ }++ function measurable(el) {+ const cs = getComputedStyle(el);+ if (cs.display === 'none' || cs.visibility === 'hidden') return null;+ if (parseFloat(cs.opacity || '1') < 0.05) return null;+ if (el.hasAttribute('hidden')) return null;+ const box = clip(el.getBoundingClientRect());+ const area = areaOf(box);+ if (area < 400) return null;+ if (box.right - box.left < 12 || box.bottom - box.top < 12) return null;+ return { el, cs, box, area };+ }++ // Pass 1: the viewport anchors — every visible fixed/sticky box, outermost only.+ const anchors = [];+ for (const el of document.querySelectorAll('body *')) {+ const cs = getComputedStyle(el);+ if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;+ const m = measurable(el);+ if (!m) continue;+ anchors.push(m);+ }+ const outerAnchors = anchors.filter((a) => !anchors.some((o) => o !== a && o.el.contains(a.el)));++ // Pass 2: resolve each anchor to the boxes a visitor actually sees.+ //+ // An anchor that paints nothing is a positioning shell, not an overlay — and+ // the shells are where the interesting collisions hide. #tws-corner-stack is+ // a transparent, pointer-events:none flex column whose MEMBERS are+ // position:relative; auditing only fixed/sticky elements would have declared+ // that whole family invisible and missed the exact bug this exists to catch.+ // So a non-painting anchor is replaced by its outermost painted descendants,+ // each treated as an overlay in its own right.+ const roots = [];+ const seen = new Set();+ function push(m) {+ if (seen.has(m.el)) return;+ seen.add(m.el);+ roots.push(m);+ }+ function descend(el, depth) {+ if (depth > 6) return;+ for (const child of el.children) {+ const m = measurable(child);+ if (!m) continue;+ if (paints(child, m.cs)) push(m);+ else descend(child, depth + 1);+ }+ }+ for (const a of outerAnchors) {+ if (paints(a.el, a.cs)) push(a);+ else descend(a.el, 0);+ }++ return roots.map((c, i) => ({+ index: i,+ label: label(c.el),+ role: c.el.getAttribute('role') || null,+ ariaHidden: c.el.getAttribute('aria-hidden') === 'true',+ position: c.cs.position,+ zIndex: c.cs.zIndex === 'auto' ? null : Number(c.cs.zIndex),+ pointerEvents: c.cs.pointerEvents,+ interactive: interactive(c.el, c.cs),+ box: c.box,+ area: Math.round(c.area),+ coverage: +(c.area / (vw * vh)).toFixed(3),+ isDialog: c.el.tagName === 'DIALOG' || c.el.getAttribute('role') === 'dialog',+ }));+}++// ── Analysis (node side) ──────────────────────────────────────────────────────+function intersect(a, b) {+ const left = Math.max(a.left, b.left);+ const top = Math.max(a.top, b.top);+ const right = Math.min(a.right, b.right);+ const bottom = Math.min(a.bottom, b.bottom);+ if (right <= left || bottom <= top) return null;+ return { left, top, right, bottom, area: (right - left) * (bottom - top) };+}++const SCRIM_COVERAGE = 0.9;++function findCollisions(overlays) {+ const widgets = overlays.filter((o) => o.coverage < SCRIM_COVERAGE);+ const out = [];+ for (let i = 0; i < widgets.length; i++) {+ for (let j = i + 1; j < widgets.length; j++) {+ const a = widgets[i];+ const b = widgets[j];+ // Decorative-on-decorative is a design decision, not a defect.+ if (!a.interactive && !b.interactive) continue;+ // A dialog is meant to sit on everything while it is open.+ if (a.isDialog || b.isDialog) continue;+ if (a.ariaHidden && b.ariaHidden) continue;+ const hit = intersect(a.box, b.box);+ if (!hit) continue;+ const smaller = Math.min(a.area, b.area);+ const ratio = hit.area / smaller;+ if (hit.area < MIN_AREA || ratio < MIN_RATIO) continue;+ // Whichever paints last wins the pixel; that is the one hiding the other.+ const az = a.zIndex ?? 0;+ const bz = b.zIndex ?? 0;+ const top = az === bz ? (a.index > b.index ? a : b) : az > bz ? a : b;+ out.push({+ a: a.label,+ b: b.label,+ covering: top.label,+ covered: (top === a ? b : a).label,+ zIndexA: a.zIndex,+ zIndexB: b.zIndex,+ overlapPx: Math.round(hit.area),+ overlapRatio: +ratio.toFixed(3),+ rect: {+ left: Math.round(hit.left),+ top: Math.round(hit.top),+ right: Math.round(hit.right),+ bottom: Math.round(hit.bottom),+ },+ boxes: [a.box, b.box],+ });+ }+ }+ return out.sort((x, y) => y.overlapPx - x.overlapPx);+}++function findStrayScrims(overlays) {+ return overlays+ .filter((o) => o.coverage >= SCRIM_COVERAGE && !o.isDialog && o.pointerEvents !== 'none')+ .filter((o) => o.interactive === false)+ .map((o) => ({ label: o.label, coverage: o.coverage, zIndex: o.zIndex }));+}++// ── Capture ───────────────────────────────────────────────────────────────────+// Widget state a first-time visitor actually gets. Without this the audit runs+// against a page with every persistent widget switched off and finds nothing —+// which is exactly the blind spot that let these collisions ship.+const FIRST_VISIT_STATE = () => {+ try {+ localStorage.setItem('walk:companion:enabled', '1');+ localStorage.removeItem('tws:getting-started:dismissed');+ localStorage.removeItem('tws:feature-discovery:seen');+ } catch (e) {+ /* storage disabled: the page still renders its own chrome */+ }+};++async function auditRoute(browser, route, viewport) {+ const ctx = await browser.newContext({+ viewport: { width: viewport.width, height: viewport.height },+ deviceScaleFactor: 1,+ reducedMotion: 'reduce',+ });+ if (WITH_WIDGETS) await ctx.addInitScript(FIRST_VISIT_STATE);+ const page = await ctx.newPage();+ const result = { route, viewport: viewport.id, collisions: [], scrims: [], error: null };+ try {+ const res = await page.goto(BASE + route, {+ waitUntil: 'domcontentloaded',+ timeout: 45000,+ });+ if (res && res.status() >= 400) {+ result.error = `HTTP ${res.status()}`;+ await ctx.close();+ return result;+ }+ await page.waitForTimeout(SETTLE_MS);+ const overlays = await page.evaluate(collectOverlays);+ result.overlayCount = overlays.length;+ result.collisions = findCollisions(overlays);+ result.scrims = findStrayScrims(overlays);++ if (result.collisions.length) {+ const slug =+ (route === '/' ? 'home' : route.replace(/^\//, '').replace(/\//g, '-')) ++ '-' ++ viewport.id;+ const file = path.join(OUT_DIR, 'shots', `${slug}.png`);+ mkdirSync(path.dirname(file), { recursive: true });+ await annotate(page, result.collisions);+ await page.screenshot({ path: file });+ result.shot = path.relative(OUT_DIR, file);+ }+ } catch (err) {+ result.error = err?.message || String(err);+ }+ await ctx.close();+ return result;+}++/** Draw the offenders and their intersection onto the live page before shooting. */+async function annotate(page, collisions) {+ await page.evaluate((hits) => {+ const layer = document.createElement('div');+ layer.id = 'tws-overlay-audit-layer';+ layer.style.cssText =+ 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;font:600 11px/1.2 ui-monospace,monospace';+ const draw = (box, css, text) => {+ const d = document.createElement('div');+ d.style.cssText =+ `position:absolute;left:${box.left}px;top:${box.top}px;` ++ `width:${box.right - box.left}px;height:${box.bottom - box.top}px;` ++ css;+ if (text) {+ const t = document.createElement('span');+ t.textContent = text;+ t.style.cssText =+ 'position:absolute;left:0;top:-15px;white-space:nowrap;padding:1px 4px;' ++ 'border-radius:3px;background:#ff2d55;color:#fff';+ d.appendChild(t);+ }+ layer.appendChild(d);+ };+ for (const hit of hits) {+ for (const b of hit.boxes) draw(b, 'outline:2px dashed rgba(255,45,85,.85);', null);+ draw(+ hit.rect,+ 'background:rgba(255,45,85,.38);outline:2px solid #ff2d55;',+ `${hit.covering} over ${hit.covered}`,+ );+ }+ document.body.appendChild(layer);+ }, collisions);+}++// ── Report ────────────────────────────────────────────────────────────────────+const esc = (s) =>+ String(s).replace(+ /[&<>"]/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c],+ );++function writeReport(results, meta) {+ const bad = results.filter((r) => r.collisions.length);+ const cards = bad+ .map(+ (r) => `+ <article class="card">+ <header>+ <h2><a href="${esc(meta.base + r.route)}">${esc(r.route)}</a></h2>+ <span class="vp">${esc(r.viewport)}</span>+ <span class="count">${r.collisions.length} collision${r.collisions.length === 1 ? '' : 's'}</span>+ </header>+ ${r.shot ? `<a class="shot" href="${esc(r.shot)}"><img loading="lazy" src="${esc(r.shot)}" alt="Annotated screenshot of ${esc(r.route)} at ${esc(r.viewport)} width"></a>` : ''}+ <ul>+ ${r.collisions+ .map(+ (c) => `<li>+ <code>${esc(c.covering)}</code> covers <code>${esc(c.covered)}</code>+ <span class="meta">${c.overlapPx.toLocaleString()} px² · ${Math.round(c.overlapRatio * 100)}% of the smaller box · z ${c.zIndexA ?? 'auto'} / ${c.zIndexB ?? 'auto'}</span>+ </li>`,+ )+ .join('')}+ </ul>+ </article>`,+ )+ .join('');++ const html = `<!doctype html>+<html lang="en"><head><meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Overlay collisions — three.ws</title>+<style>+:root{color-scheme:dark;--bg:#0b0d12;--panel:#12151d;--line:#232837;--fg:#e8ecf4;--dim:#8b93a7;--bad:#ff2d55;--ok:#3ddc97}+*{box-sizing:border-box}+body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 system-ui,-apple-system,'Segoe UI',sans-serif}+.wrap{max-width:1040px;margin:0 auto;padding:48px 20px 96px}+h1{font-size:30px;letter-spacing:-.02em;margin:0 0 6px}+.sub{color:var(--dim);margin:0 0 28px}+.stats{display:flex;flex-wrap:wrap;gap:10px;margin:0 0 32px;padding:0;list-style:none}+.stats li{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 14px}+.stats b{display:block;font-size:22px;letter-spacing:-.02em}+.stats span{color:var(--dim);font-size:12px;text-transform:uppercase;letter-spacing:.08em}+.card{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px;margin:0 0 18px}+.card header{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px}+.card h2{font-size:17px;margin:0}+.card h2 a{color:var(--fg);text-decoration:none;border-bottom:1px solid var(--line)}+.card h2 a:hover{border-color:var(--fg)}+.vp,.count{font:600 11px/1 ui-monospace,monospace;letter-spacing:.06em;text-transform:uppercase;padding:5px 8px;border-radius:999px}+.vp{background:#1b2130;color:var(--dim)}+.count{background:rgba(255,45,85,.16);color:var(--bad)}+.shot{display:block;border:1px solid var(--line);border-radius:10px;overflow:hidden;margin-bottom:12px}+.shot img{display:block;width:100%;height:auto}+.card ul{margin:0;padding-left:18px}+.card li{margin:0 0 6px}+code{background:#1b2130;border-radius:5px;padding:1px 6px;font:600 12.5px/1 ui-monospace,monospace}+.meta{display:block;color:var(--dim);font-size:12.5px}+.clean{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--ok);border-radius:12px;padding:22px}+.clean h2{margin:0 0 6px;font-size:18px}+.clean p{margin:0;color:var(--dim)}+footer{color:var(--dim);font-size:13px;margin-top:36px;border-top:1px solid var(--line);padding-top:16px}+@media (max-width:640px){.wrap{padding:28px 14px 64px}h1{font-size:24px}}+</style></head><body><div class="wrap">+<h1>Overlay collisions</h1>+<p class="sub">Every painted <code>fixed</code> / <code>sticky</code> overlay on each route, intersected pairwise. Dashed boxes are the two offenders; the filled box is what one hides of the other.</p>+<ul class="stats">+ <li><b>${meta.routes}</b><span>routes</span></li>+ <li><b>${meta.viewports}</b><span>viewports</span></li>+ <li><b>${meta.checks}</b><span>page renders</span></li>+ <li><b>${meta.collisions}</b><span>collisions</span></li>+</ul>+${bad.length ? cards : '<div class="clean"><h2>No collisions.</h2><p>No two interactive overlays overlapped past the thresholds on any audited route.</p></div>'}+<footer>${esc(meta.base)} · captured ${esc(meta.at)} · thresholds: ${MIN_AREA} px² and ${Math.round(MIN_RATIO * 100)}% of the smaller box · regenerate with <code>npm run audit:overlays</code></footer>+</div></body></html>`;++ mkdirSync(OUT_DIR, { recursive: true });+ writeFileSync(path.join(OUT_DIR, 'index.html'), html);+ writeFileSync(+ path.join(OUT_DIR, 'report.json'),+ JSON.stringify({ meta, results }, null, '\t'),+ );+}++// ── Main ──────────────────────────────────────────────────────────────────────+async function main() {+ if (!viewports.length) {+ console.error(`Unknown --viewport. Choose one of: ${VIEWPORTS.map((v) => v.id).join(', ')}`);+ process.exit(2);+ }+ // A stale shot from a route that no longer collides would misreport the run.+ if (existsSync(path.join(OUT_DIR, 'shots'))) {+ rmSync(path.join(OUT_DIR, 'shots'), { recursive: true, force: true });+ }++ const jobs = [];+ for (const route of routes) for (const vp of viewports) jobs.push({ route, vp });++ if (!JSON_ONLY) {+ console.log(`Overlay audit — ${routes.length} routes x ${viewports.length} viewports on ${BASE}`);+ }++ const browser = await chromium.launch();+ const results = [];+ let cursor = 0;+ async function worker() {+ while (cursor < jobs.length) {+ const job = jobs[cursor++];+ const r = await auditRoute(browser, job.route, job.vp);+ results.push(r);+ if (!JSON_ONLY) {+ const mark = r.error ? '!' : r.collisions.length ? 'x' : '.';+ const note = r.error+ ? ` ${r.error}`+ : r.collisions.length+ ? ` ${r.collisions.length} collision(s)`+ : '';+ console.log(` ${mark} ${r.route} @ ${r.viewport}${note}`);+ }+ }+ }+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, jobs.length) }, worker));+ await browser.close();++ results.sort((a, b) => a.route.localeCompare(b.route) || a.viewport.localeCompare(b.viewport));+ const collisions = results.reduce((n, r) => n + r.collisions.length, 0);+ const errored = results.filter((r) => r.error);+ const meta = {+ base: BASE,+ at: new Date().toISOString(),+ routes: routes.length,+ viewports: viewports.length,+ checks: results.length,+ collisions,+ widgetsEnabled: WITH_WIDGETS,+ };+ writeReport(results, meta);++ if (JSON_ONLY) {+ console.log(JSON.stringify({ meta, results }, null, '\t'));+ } else {+ console.log('');+ for (const r of results.filter((x) => x.collisions.length)) {+ console.log(`${r.route} @ ${r.viewport}`);+ for (const c of r.collisions) {+ console.log(+ ` ${c.covering} covers ${c.covered} — ${c.overlapPx} px2 (${Math.round(c.overlapRatio * 100)}% of the smaller box)`,+ );+ }+ }+ const strays = results.filter((r) => r.scrims.length);+ for (const r of strays) {+ for (const s of r.scrims) {+ console.log(`${r.route} @ ${r.viewport}: full-viewport layer ${s.label} blocks the page`);+ }+ }+ if (errored.length) {+ console.log(`\n${errored.length} route(s) could not be rendered:`);+ for (const r of errored) console.log(` ${r.route} @ ${r.viewport}: ${r.error}`);+ }+ console.log(+ `\n${collisions} collision(s) across ${results.length} renders. Report: reports/overlays/index.html`,+ );+ }+ process.exit(collisions > 0 ? 1 : 0);+}++main().catch((err) => {+ console.error(err);+ process.exit(2);+});diff --git a/scripts/capture-doc-media.mjs b/scripts/capture-doc-media.mjsnew file mode 100644index 000000000..b861333ee--- /dev/null+++ b/scripts/capture-doc-media.mjs@@ -0,0 +1,420 @@+#!/usr/bin/env node+/**+ * capture-doc-media.mjs — the docs' media, captured from the real product.+ *+ * Tutorials used to be walls of text: 68 of them, 6 with any image. The reason+ * was never laziness about writing `![...]()`, it was that a screenshot is a+ * liability. Someone has to take it, nobody knows which build it came from, and+ * the day the UI moves it silently starts lying to readers.+ *+ * So the screenshots are not assets here, they are *output*. Every image under+ * public/docs/img/ that this script owns is declared in data/doc-media.json as a+ * recipe (a route, an optional interaction script, a crop) and produced by+ * driving the actual site in a real Chromium. Re-running the script re-derives+ * every image from the current code, so "is this screenshot still true?" is a+ * command, not an argument.+ *+ * Two kinds of capture:+ * • still — one frame, PNG out of Chromium, WebP through sharp.+ * • motion — N frames at a fixed fps assembled by ffmpeg into an animated+ * WebP. This platform's product is movement (an avatar walking,+ * a viseme firing, a forge job filling in); a still undersells it.+ *+ * Provenance is written next to the pixels: public/docs/media-manifest.json+ * records, per shot, the route it came from, the commit that was checked out,+ * the capture time, byte size, intrinsic dimensions, and a sha256. The docs+ * renderer (public/doc-figures.js) reads that manifest to size the figure box+ * before the image loads (no layout shift) and to print a "captured from <route>"+ * line the reader can click.+ *+ * ── Usage ────────────────────────────────────────────────────────────────────+ * node scripts/capture-doc-media.mjs # every shot, against localhost:3000+ * node scripts/capture-doc-media.mjs --only forge-prompt,walk-hero+ * node scripts/capture-doc-media.mjs --base https://three.ws+ * node scripts/capture-doc-media.mjs --list # print the shot table, capture nothing+ * node scripts/capture-doc-media.mjs --concurrency 2 # default 2; 3D routes are GPU-less and heavy+ *+ * Target defaults to http://localhost:3000 (`npm run dev`) so a capture reflects+ * the working tree rather than whatever is deployed. Pass --base to shoot prod.+ *+ * Headless Chromium renders WebGL through ANGLE/SwiftShader, which is slower+ * than a GPU but faithful; `settle` per shot is the knob when a 3D route needs+ * longer to finish loading its rig.+ */+import { chromium } from 'playwright';+import { execFile, execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';+import sharp from 'sharp';++const run = promisify(execFile);+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const SPEC_FILE = path.join(ROOT, 'data/doc-media.json');+const OUT_DIR = path.join(ROOT, 'public/docs/img');+const MANIFEST_FILE = path.join(ROOT, 'public/docs/media-manifest.json');++// ── CLI ───────────────────────────────────────────────────────────────────────+const argv = process.argv.slice(2);+const flag = (name) => argv.includes(`--${name}`);+const opt = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;+};++const BASE = (opt('base', process.env.BASE_URL || 'http://localhost:3000')).replace(/\/$/, '');+const CONCURRENCY = Math.max(1, Number(opt('concurrency', 2)) || 2);+const ONLY = (opt('only', '') || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);++// Logical viewports. Captures run at deviceScaleFactor 2 and are downscaled on+// the way out, so UI text stays crisp on retina without shipping 2x bytes.+const VIEWPORTS = {+ desktop: { width: 1280, height: 800 },+ wide: { width: 1600, height: 900 },+ mobile: { width: 390, height: 844 },+ square: { width: 900, height: 900 },+};++const SCALE = 2;+/** Cap the emitted pixel width. Beyond this the extra bytes buy nothing in a doc column. */+const MAX_OUT_WIDTH = 1800;++function readSpec() {+ if (!existsSync(SPEC_FILE)) {+ fail(`missing ${path.relative(ROOT, SPEC_FILE)} — nothing to capture`);+ }+ const spec = JSON.parse(readFileSync(SPEC_FILE, 'utf8'));+ const defaults = spec.defaults || {};+ const shots = (spec.shots || []).map((shot) => ({ ...defaults, ...shot }));+ const seen = new Set();+ for (const shot of shots) {+ if (!shot.id) fail('every shot needs an id');+ if (seen.has(shot.id)) fail(`duplicate shot id: ${shot.id}`);+ seen.add(shot.id);+ if (!shot.url) fail(`shot ${shot.id} has no url`);+ if (!shot.alt) fail(`shot ${shot.id} has no alt text (a doc image without alt is a bug)`);+ if (!VIEWPORTS[shot.viewport || 'desktop']) {+ fail(`shot ${shot.id} has unknown viewport "${shot.viewport}"`);+ }+ }+ return shots;+}++function fail(message) {+ console.error(`capture-doc-media: ${message}`);+ process.exit(1);+}++function currentCommit() {+ try {+ return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: ROOT })+ .toString()+ .trim();+ } catch {+ return null;+ }+}++/**+ * Run a shot's interaction script. Each action is deliberately small and+ * declarative so a spec stays readable as documentation of the flow itself.+ */+async function applyActions(page, actions = []) {+ for (const action of actions) {+ switch (action.type) {+ case 'click':+ await page.click(action.selector, { timeout: action.timeout || 15000 });+ break;+ case 'fill':+ await page.fill(action.selector, action.value, { timeout: action.timeout || 15000 });+ break;+ case 'press':+ await page.press(action.selector || 'body', action.key, {+ timeout: action.timeout || 15000,+ });+ break;+ case 'hover':+ await page.hover(action.selector, { timeout: action.timeout || 15000 });+ break;+ case 'scroll':+ await page.evaluate(+ ([sel, top]) => {+ if (sel) document.querySelector(sel)?.scrollIntoView({ block: 'center' });+ else window.scrollTo(0, top || 0);+ },+ [action.selector || null, action.top || 0],+ );+ break;+ case 'waitFor':+ await page.waitForSelector(action.selector, {+ state: action.state || 'visible',+ timeout: action.timeout || 20000,+ });+ break;+ case 'wait':+ await page.waitForTimeout(action.ms || 500);+ break;+ default:+ fail(`unknown action type "${action.type}"`);+ }+ }+}++/** Everything a page needs to look like a real, settled visit before we shoot. */+async function preparePage(page, shot) {+ const url = shot.url.startsWith('http') ? shot.url : BASE + shot.url;+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });+ await page.waitForLoadState('networkidle', { timeout: 45000 }).catch(() => {+ /* long-poll and 3D routes may never idle; the settle below covers them */+ });+ await page.evaluate(() => document.fonts?.ready).catch(() => {});+ // Dismiss anything that would sit on top of the subject in a first visit.+ await page+ .evaluate(() => {+ for (const sel of ['#cookie-banner', '.cookie-banner', '[data-consent-banner]']) {+ document.querySelector(sel)?.remove();+ }+ })+ .catch(() => {});+ await applyActions(page, shot.actions);+ await page.waitForTimeout(shot.settle ?? 3500);+}++/** Resolve the element (or full viewport) a shot is framed on. */+async function subjectOf(page, shot) {+ if (!shot.clip) return page;+ const handle = await page.waitForSelector(shot.clip, { state: 'visible', timeout: 25000 });+ await handle.scrollIntoViewIfNeeded();+ await page.waitForTimeout(250);+ return handle;+}++/** PNG buffer from Chromium → optimised WebP on disk. Returns the written metadata. */+async function writeStill(buffer, outPath) {+ const image = sharp(buffer);+ const meta = await image.metadata();+ const targetWidth = Math.min(MAX_OUT_WIDTH, Math.round((meta.width || MAX_OUT_WIDTH) / SCALE) * 2);+ const out = await image+ .resize({ width: Math.min(meta.width || targetWidth, targetWidth), withoutEnlargement: true })+ .webp({ quality: 90, effort: 6 })+ .toBuffer();+ writeFileSync(outPath, out);+ const final = await sharp(out).metadata();+ return { bytes: out.length, width: final.width, height: final.height };+}++/**+ * Animated capture. Chromium has no video encoder we can trust for a short+ * looping clip, so we sample real frames on a fixed cadence and let ffmpeg+ * assemble them. The result is a genuine recording of the running product,+ * not a synthesised animation.+ */+async function writeMotion(page, shot, subject, outPath) {+ const fps = Math.min(24, Math.max(4, shot.motion.fps || 12));+ const seconds = Math.min(10, Math.max(1, shot.motion.seconds || 3));+ const frameCount = Math.round(fps * seconds);+ const frameDir = mkdtempSync(path.join(tmpdir(), 'docmedia-'));+ try {+ const interval = 1000 / fps;+ for (let i = 0; i < frameCount; i++) {+ const started = Date.now();+ const buffer = await subject.screenshot({ type: 'png', animations: 'allow' });+ writeFileSync(path.join(frameDir, `f${String(i).padStart(4, '0')}.png`), buffer);+ const elapsed = Date.now() - started;+ if (elapsed < interval) await page.waitForTimeout(interval - elapsed);+ }+ // Downscale on the way in so the encoder is not fed 2x frames it will+ // only shrink again, and keep width even (some encoders reject odd sizes).+ const first = await sharp(path.join(frameDir, 'f0000.png')).metadata();+ const width = Math.min(MAX_OUT_WIDTH, Math.round((first.width || MAX_OUT_WIDTH) / SCALE) * 2);+ await run('ffmpeg', [+ '-y',+ '-loglevel',+ 'error',+ '-framerate',+ String(fps),+ '-i',+ path.join(frameDir, 'f%04d.png'),+ '-vf',+ `scale=${width - (width % 2)}:-2:flags=lanczos`,+ '-loop',+ '0',+ '-quality',+ '82',+ '-compression_level',+ '6',+ outPath,+ ]);+ const out = readFileSync(outPath);+ const meta = await sharp(out, { animated: true }).metadata();+ return {+ bytes: out.length,+ width: meta.width,+ // sharp reports an animated WebP's height as pages*height; the frame+ // height is what a layout box needs.+ height: meta.pageHeight || meta.height,+ frames: frameCount,+ fps,+ };+ } finally {+ rmSync(frameDir, { recursive: true, force: true });+ }+}++async function captureShot(browser, shot, commit) {+ const viewport = VIEWPORTS[shot.viewport || 'desktop'];+ const context = await browser.newContext({+ viewport,+ deviceScaleFactor: SCALE,+ colorScheme: shot.theme === 'light' ? 'light' : 'dark',+ reducedMotion: shot.motion ? 'no-preference' : 'reduce',+ });+ // The site persists its own theme; set it before any script runs so the+ // first paint is already the theme the shot asked for.+ await context.addInitScript((theme) => {+ try {+ localStorage.setItem('twx_theme', theme);+ } catch {+ /* storage disabled: the colorScheme hint above still applies */+ }+ }, shot.theme === 'light' ? 'light' : 'dark');++ const page = await context.newPage();+ const ext = shot.motion ? 'webp' : 'webp';+ const outPath = path.join(OUT_DIR, `${shot.id}.${ext}`);+ try {+ await preparePage(page, shot);+ const subject = await subjectOf(page, shot);+ const written = shot.motion+ ? await writeMotion(page, shot, subject, outPath)+ : await writeStill(+ await subject.screenshot({+ type: 'png',+ ...(subject === page ? { fullPage: Boolean(shot.fullPage) } : {}),+ }),+ outPath,+ );+ const sha256 = createHash('sha256').update(readFileSync(outPath)).digest('hex');+ return {+ id: shot.id,+ src: `/docs/img/${shot.id}.${ext}`,+ alt: shot.alt,+ caption: shot.caption || null,+ route: shot.url,+ viewport: shot.viewport || 'desktop',+ animated: Boolean(shot.motion),+ capturedAt: new Date().toISOString(),+ capturedFrom: BASE,+ commit,+ sha256,+ ...written,+ };+ } finally {+ await context.close();+ }+}++async function main() {+ let shots = readSpec();+ if (ONLY.length) {+ const known = new Set(shots.map((s) => s.id));+ for (const id of ONLY) if (!known.has(id)) fail(`--only names an unknown shot: ${id}`);+ shots = shots.filter((s) => ONLY.includes(s.id));+ }++ if (flag('list')) {+ for (const shot of shots) {+ console.log(+ `${shot.id.padEnd(30)} ${shot.motion ? 'motion' : 'still '} ${(shot.viewport || 'desktop').padEnd(8)} ${shot.url}`,+ );+ }+ console.log(`\n${shots.length} shot(s)`);+ return;+ }++ const reachable = await fetch(BASE + '/', { method: 'GET' })+ .then((r) => r.ok || r.status < 500)+ .catch(() => false);+ if (!reachable) {+ fail(`${BASE} is not answering. Start it with \`npm run dev\` or pass --base https://three.ws`);+ }++ mkdirSync(OUT_DIR, { recursive: true });+ const commit = currentCommit();+ const browser = await chromium.launch({+ args: [+ '--no-sandbox',+ '--disable-dev-shm-usage',+ // Give the WebGL routes the best software renderer available; without+ // these the 3D shots come back as empty black boxes.+ '--ignore-gpu-blocklist',+ '--enable-unsafe-swiftshader',+ '--use-gl=angle',+ '--use-angle=swiftshader',+ ],+ });++ const results = [];+ const failures = [];+ const queue = [...shots];+ const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length || 1) }, async () => {+ for (;;) {+ const shot = queue.shift();+ if (!shot) return;+ const started = Date.now();+ try {+ const entry = await captureShot(browser, shot, commit);+ results.push(entry);+ console.log(+ ` ok ${shot.id.padEnd(30)} ${String(entry.width)}x${entry.height} ${(entry.bytes / 1024).toFixed(0)}kB ${((Date.now() - started) / 1000).toFixed(1)}s`,+ );+ } catch (err) {+ failures.push({ id: shot.id, message: String(err?.message || err).split('\n')[0] });+ console.error(` FAIL ${shot.id.padEnd(30)} ${String(err?.message || err).split('\n')[0]}`);+ }+ }+ });+ await Promise.all(workers);+ await browser.close();++ // Merge into the existing manifest so a targeted --only run never drops the+ // provenance of the shots it did not take.+ const previous = existsSync(MANIFEST_FILE)+ ? JSON.parse(readFileSync(MANIFEST_FILE, 'utf8'))+ : { shots: {} };+ const merged = { ...(previous.shots || {}) };+ for (const entry of results) merged[entry.id] = entry;+ // Drop manifest entries whose spec was deleted: a stale entry would keep+ // promising a figure the docs can no longer render.+ const specIds = new Set(readSpec().map((s) => s.id));+ for (const id of Object.keys(merged)) if (!specIds.has(id)) delete merged[id];++ writeFileSync(+ MANIFEST_FILE,+ `${JSON.stringify(+ {+ generatedBy: 'scripts/capture-doc-media.mjs',+ generatedAt: new Date().toISOString(),+ shots: Object.fromEntries(Object.entries(merged).sort(([a], [b]) => a.localeCompare(b))),+ },+ null,+ '\t',+ )}\n`,+ );++ console.log(+ `\n${results.length} captured, ${failures.length} failed → ${path.relative(ROOT, MANIFEST_FILE)}`,+ );+ if (failures.length) process.exit(1);+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/scripts/capture-guide-shots.mjs b/scripts/capture-guide-shots.mjsnew file mode 100644index 000000000..bc4b3331a--- /dev/null+++ b/scripts/capture-guide-shots.mjs@@ -0,0 +1,297 @@+#!/usr/bin/env node+// capture-guide-shots.mjs — capture every tutorial screenshot from the real,+// running product.+//+// Tutorial media on three.ws is never hand-cropped and never mocked. Each+// picture in docs/tutorials/*.md is declared as a "shot" in data/guide-shots.json+// (which page, which element, which controls to point at) and produced by this+// script driving the live site in a real browser. Re-running it after a UI+// change regenerates every picture, so the guides cannot drift away from the+// product they document.+//+// Usage:+// node scripts/capture-guide-shots.mjs # capture all, against production+// node scripts/capture-guide-shots.mjs --base http://localhost:3000+// node scripts/capture-guide-shots.mjs --only forge-compose,create-hub+// node scripts/capture-guide-shots.mjs --list+//+// Writes PNGs to public/docs/img/guides/ and a per-shot result report to+// data/guide-shots.capture.json. Exits non-zero if any shot failed, so a+// selector that no longer exists is a loud failure rather than a stale picture.++import { chromium } from 'playwright';+import { readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const MANIFEST = join(ROOT, 'data', 'guide-shots.json');+const REPORT = join(ROOT, 'data', 'guide-shots.capture.json');+const OUT_DIR = join(ROOT, 'public', 'docs', 'img', 'guides');++// ── args ─────────────────────────────────────────────────────────────────────++function arg(name, fallback = null) {+ const i = process.argv.indexOf(`--${name}`);+ return i > -1 && process.argv[i + 1] ? process.argv[i + 1] : fallback;+}+const BASE = (arg('base', 'https://three.ws')).replace(/\/+$/, '');+const ONLY = arg('only') ? new Set(arg('only').split(',').map(s => s.trim())) : null;+const LIST = process.argv.includes('--list');++// ── the frame: what a capture must never contain ─────────────────────────────+// Site chrome that follows the user around (the onboarding pill, the corner+// stack, discovery cards, an in-progress tour) is real product, but it is not+// what any given guide step is about, and it moves between runs. Suppressing it+// keeps a shot about its subject and keeps re-captures byte-stable.++const SUPPRESS_CSS = `+ #page-loading,+ #tws-corner-stack,+ .twg-root, .twg-modal-overlay,+ .tws-disc-card, .tws-disc-new,+ .tour-overlay, .tour-bubble, .tour-spotlight,+ [data-tws-capture-hide] { display: none !important; }+ *, *::before, *::after {+ transition: none !important;+ animation-duration: 0s !important;+ animation-delay: 0s !important;+ caret-color: transparent !important;+ }+ html { scrollbar-width: none !important; }+ ::-webkit-scrollbar { display: none !important; }+`;++// ── annotation: numbered callouts drawn over the live page ───────────────────+// Rendered into the page itself (not composited afterwards) so the pins sit in+// the same pixel space as the UI they point at, at whatever the real layout is.++const ANNOTATE = (callouts) => {+ const ACCENT = '#7c5cff';+ document.querySelectorAll('[data-tws-callout]').forEach(n => n.remove());+ const missing = [];+ const layer = document.createElement('div');+ layer.setAttribute('data-tws-callout', 'layer');+ Object.assign(layer.style, {+ position: 'absolute', inset: '0', pointerEvents: 'none', zIndex: '2147483000',+ });+ document.body.appendChild(layer);++ callouts.forEach((c, i) => {+ const el = document.querySelector(c.selector);+ if (!el) { missing.push(c.selector); return; }+ const r = el.getBoundingClientRect();+ if (!r.width || !r.height) { missing.push(c.selector); return; }+ const top = r.top + window.scrollY;+ const left = r.left + window.scrollX;++ const ring = document.createElement('div');+ Object.assign(ring.style, {+ position: 'absolute',+ top: (top - 4) + 'px', left: (left - 4) + 'px',+ width: (r.width + 8) + 'px', height: (r.height + 8) + 'px',+ border: '2px solid ' + ACCENT,+ borderRadius: (parseFloat(getComputedStyle(el).borderRadius) || 8) + 6 + 'px',+ boxShadow: '0 0 0 4px rgba(124,92,255,0.22), 0 0 22px rgba(124,92,255,0.38)',+ pointerEvents: 'none',+ });+ layer.appendChild(ring);++ const pin = document.createElement('div');+ pin.textContent = String(c.n || i + 1);+ // Nudge the pin inside the viewport when the target hugs the left edge.+ const pinLeft = Math.max(4, left - 15);+ Object.assign(pin.style, {+ position: 'absolute',+ top: (top - 15) + 'px', left: pinLeft + 'px',+ width: '30px', height: '30px', borderRadius: '999px',+ background: ACCENT, color: '#fff',+ font: '700 15px/30px Inter, system-ui, sans-serif',+ textAlign: 'center',+ boxShadow: '0 2px 10px rgba(0,0,0,0.45), 0 0 0 3px rgba(10,10,14,0.85)',+ pointerEvents: 'none',+ });+ layer.appendChild(pin);+ });+ return missing;+};++// A transparent, absolutely-positioned rect used as the screenshot target. Using+// an element (rather than a raw clip box) keeps padding unambiguous: Playwright+// scrolls it into view and captures exactly its bounds.+const FRAME = ({ selector, pad }) => {+ document.getElementById('tws-capture-frame')?.remove();+ const el = document.querySelector(selector);+ if (!el) return null;+ const r = el.getBoundingClientRect();+ if (!r.width || !r.height) return null;+ const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);+ const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);+ const x = Math.max(0, r.left + window.scrollX - pad);+ const y = Math.max(0, r.top + window.scrollY - pad);+ const w = Math.min(docW - x, r.width + pad * 2);+ const h = Math.min(docH - y, r.height + pad * 2);+ const frame = document.createElement('div');+ frame.id = 'tws-capture-frame';+ Object.assign(frame.style, {+ position: 'absolute', top: y + 'px', left: x + 'px',+ width: w + 'px', height: h + 'px',+ pointerEvents: 'none', background: 'transparent', zIndex: '0',+ });+ document.body.appendChild(frame);+ return { w: Math.round(w), h: Math.round(h) };+};++// ── prep steps: drive the UI into the state a guide step describes ────────────++async function runPrep(page, prep) {+ for (const step of prep) {+ if (step.click) {+ const loc = page.locator(step.click).first();+ await loc.waitFor({ state: 'visible', timeout: 15000 });+ await loc.click({ timeout: 15000 });+ }+ if (step.fill) {+ const loc = page.locator(step.fill.selector).first();+ await loc.waitFor({ state: 'visible', timeout: 15000 });+ await loc.fill(step.fill.value, { timeout: 15000 });+ }+ if (step.scrollTo) {+ await page.locator(step.scrollTo).first()+ .scrollIntoViewIfNeeded({ timeout: 15000 });+ }+ if (step.wait) await page.waitForTimeout(step.wait);+ }+}++// ── main ─────────────────────────────────────────────────────────────────────++const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));+const defaults = manifest.defaults || {};+const shots = manifest.shots.filter(s => !ONLY || ONLY.has(s.id));++const tutorialsOf = s => (s.placements || []).map(p => p.tutorial);++if (LIST) {+ for (const s of manifest.shots) {+ console.log(`${s.id.padEnd(24)} ${s.url.padEnd(16)} -> ${tutorialsOf(s).join(', ')}`);+ }+ const covered = new Set(manifest.shots.flatMap(tutorialsOf));+ console.log(`\n${manifest.shots.length} shots, ${covered.size} tutorials covered`);+ process.exit(0);+}++if (!shots.length) {+ console.error('No shots matched. Use --list to see available ids.');+ process.exit(1);+}++mkdirSync(OUT_DIR, { recursive: true });+console.log(`Capturing ${shots.length} shot(s) against ${BASE}\n`);++const browser = await chromium.launch({+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader',+ '--hide-scrollbars', '--force-color-profile=srgb'],+});++const results = [];++for (const shot of shots) {+ const started = Date.now();+ const viewport = shot.viewport || defaults.viewport || { width: 1440, height: 900 };+ const settle = shot.settle ?? defaults.settle ?? 3500;+ const outPath = join(OUT_DIR, `${shot.id}.png`);+ const rel = `/docs/img/guides/${shot.id}.png`;++ // A fresh context per shot: no cookie, storage, or tour state carries over,+ // so every capture is what a first-time visitor actually sees.+ const ctx = await browser.newContext({+ viewport,+ deviceScaleFactor: shot.scale ?? defaults.scale ?? 2,+ colorScheme: 'dark',+ reducedMotion: 'reduce',+ userAgent: defaults.userAgent,+ });+ const page = await ctx.newPage();+ const consoleErrors = [];+ page.on('pageerror', e => consoleErrors.push(String(e.message).slice(0, 200)));++ try {+ const res = await page.goto(BASE + shot.url, {+ waitUntil: 'domcontentloaded', timeout: 60000,+ });+ const status = res?.status() ?? 0;+ if (status >= 400) throw new Error(`HTTP ${status} for ${shot.url}`);++ await page.addStyleTag({ content: SUPPRESS_CSS });+ await page.waitForTimeout(settle);+ try { await page.evaluate(() => document.fonts?.ready); } catch {}++ if (shot.prep?.length) {+ await runPrep(page, shot.prep);+ await page.waitForTimeout(shot.prepSettle ?? 900);+ }++ // Re-apply after prep: a click can mount fresh chrome.+ await page.addStyleTag({ content: SUPPRESS_CSS });++ let missing = [];+ if (shot.callouts?.length) {+ missing = await page.evaluate(ANNOTATE, shot.callouts);+ }+ if (missing.length) {+ throw new Error(`callout target(s) not found: ${missing.join(', ')}`);+ }++ let dims = null;+ if (shot.clip) {+ dims = await page.evaluate(FRAME, { selector: shot.clip, pad: shot.pad ?? 20 });+ if (!dims) throw new Error(`clip target not found or zero-size: ${shot.clip}`);+ await page.locator('#tws-capture-frame').screenshot({+ path: outPath, timeout: 90000, animations: 'disabled',+ });+ } else {+ await page.screenshot({+ path: outPath, timeout: 90000, animations: 'disabled',+ fullPage: !!shot.fullPage,+ });+ dims = { w: viewport.width, h: viewport.height };+ }++ const bytes = statSync(outPath).size;+ if (bytes < 2048) throw new Error(`suspiciously small image (${bytes} bytes)`);++ results.push({+ id: shot.id, tutorials: tutorialsOf(shot), url: shot.url, path: rel,+ ok: true, bytes, width: dims.w, height: dims.h,+ ms: Date.now() - started, pageErrors: consoleErrors.slice(0, 3),+ });+ console.log(` ok ${shot.id.padEnd(30)} ${String(Math.round(bytes / 1024)).padStart(5)} KB ${dims.w}x${dims.h}`);+ } catch (err) {+ results.push({+ id: shot.id, tutorials: tutorialsOf(shot), url: shot.url, path: rel,+ ok: false, error: String(err.message).slice(0, 300), ms: Date.now() - started,+ });+ console.log(` FAIL ${shot.id.padEnd(30)} ${String(err.message).slice(0, 90)}`);+ } finally {+ await ctx.close();+ }+}++await browser.close();++const failed = results.filter(r => !r.ok);+writeFileSync(REPORT, JSON.stringify({+ base: BASE,+ shots: results.length,+ failed: failed.length,+ results,+}, null, '\t') + '\n');++console.log(`\n${results.length - failed.length}/${results.length} captured -> public/docs/img/guides/`);+console.log(`report: data/guide-shots.capture.json`);+if (failed.length) {+ console.error(`\n${failed.length} shot(s) failed:`);+ for (const f of failed) console.error(` ${f.id}: ${f.error}`);+ process.exit(1);+}diff --git a/scripts/capture-tutorial-media.mjs b/scripts/capture-tutorial-media.mjsnew file mode 100644index 000000000..15eed393f--- /dev/null+++ b/scripts/capture-tutorial-media.mjs@@ -0,0 +1,393 @@+#!/usr/bin/env node+/**+ * capture-tutorial-media.mjs+ *+ * Turns the `figure:` directives written inside docs/tutorials/*.md into real+ * captured media, and records what it captured in public/tutorial-media.json.+ *+ * Why this exists: 68 tutorials shipped with zero images. Every honest way to+ * fix that is a capture pipeline, because the only images we are allowed to+ * publish are ones the platform actually produced. Nothing here draws, mocks,+ * or stock-sources an image: a page figure is a real Chromium screenshot of the+ * real deployed page, and a model figure is a real render returned by our own+ * /api/render/glb endpoint.+ *+ * ── Author syntax (plain markdown, no custom parser) ─────────────────────────+ * A figure is an ordinary markdown image whose src uses the `figure:` scheme,+ * so an unprocessed file still reads correctly in any markdown viewer:+ *+ * + * + * + *+ * Kinds:+ * page:<path> screenshot of https://three.ws<path> in a real browser+ * glb:<path> PNG returned by GET /api/render/glb?glbUrl=…+ * live:<path> an interactive <model-viewer>, mounted at runtime. No capture+ * happens here; it is listed in the manifest so the checker can+ * confirm the GLB itself resolves.+ *+ * Options ride along as query params on the directive:+ * page: w, h (viewport, default 1280x760), sel (clip to a CSS selector),+ * full=1 (full-page), settle (ms to wait after load, default 3500),+ * theme (dark|light, default dark)+ * glb: w, h (default 1200x900), bg (default transparent)+ * live: orbit (camera-orbit string passed to <model-viewer>)+ *+ * ── Usage ────────────────────────────────────────────────────────────────────+ * npm run tutorials:media capture anything missing+ * npm run tutorials:media -- --force re-capture everything+ * npm run tutorials:media -- --check capture nothing; exit 1 on a gap+ * npm run tutorials:media -- --only embed-in-30-seconds+ * BASE_URL=http://localhost:3000 npm run tutorials:media+ *+ * Output: public/docs/img/tutorials/<slug>/<name>-<hash>.webp plus a manifest+ * carrying intrinsic width/height and a blurred inline placeholder, so the page+ * reserves the exact box before the byte arrives and never shifts layout.+ */+import { chromium } from 'playwright';+import sharp from 'sharp';+import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync, rmSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');+// Where a reader goes when they click through a figure. This is deliberately+// NOT the capture base: figures are usually shot against a local server running+// the commit being shipped, and a doorway into localhost is a dead link.+const SITE_URL = (process.env.SITE_URL || 'https://three.ws').replace(/\/$/, '');+const TUTORIAL_DIR = resolve(ROOT, 'docs/tutorials');+const IMG_ROOT = resolve(ROOT, 'public/docs/img/tutorials');+const MANIFEST = resolve(ROOT, 'public/tutorial-media.json');++const argv = process.argv.slice(2);+const has = (name) => argv.includes(`--${name}`);+const opt = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;+};+const FORCE = has('force');+const CHECK_ONLY = has('check');+const ONLY = opt('only', '');+const QUALITY = Math.max(40, Math.min(100, Number(opt('quality', 82)) || 82));++const FIGURE_RE = /!\[([^\]]*)\]\((figure:[^)\s]+)\)/g;+const KINDS = new Set(['page', 'glb', 'live']);++// ── Parse ────────────────────────────────────────────────────────────────────++/** Split `figure:page:/forge?sel=.x` into its kind, target and options. */+function parseDirective(raw) {+ const body = raw.slice('figure:'.length);+ const colon = body.indexOf(':');+ if (colon === -1) return { error: 'a figure needs a kind, as in figure:page:/create' };+ const kind = body.slice(0, colon);+ if (!KINDS.has(kind)) return { error: `unknown figure kind "${kind}" (use page, glb or live)` };+ const rest = body.slice(colon + 1);+ const q = rest.indexOf('?');+ const target = q === -1 ? rest : rest.slice(0, q);+ const params = new URLSearchParams(q === -1 ? '' : rest.slice(q + 1));+ if (!target.startsWith('/')) return { error: `figure target must be a site-absolute path, got "${target}"` };+ return { kind, target, params };+}++function collectDirectives() {+ const files = readdirSync(TUTORIAL_DIR)+ .filter((f) => f.endsWith('.md'))+ .filter((f) => !ONLY || f === `${ONLY}.md`);+ const found = [];+ const problems = [];+ for (const file of files) {+ const slug = file.replace(/\.md$/, '');+ const md = readFileSync(resolve(TUTORIAL_DIR, file), 'utf8');+ for (const match of md.matchAll(FIGURE_RE)) {+ const [, alt, raw] = match;+ const parsed = parseDirective(raw);+ if (parsed.error) {+ problems.push(`${file}: ${parsed.error}`);+ continue;+ }+ if (!alt.trim()) {+ problems.push(`${file}: ${raw} has an empty caption. Every figure needs one, for the caption and the alt text.`);+ continue;+ }+ found.push({ slug, alt: alt.trim(), raw, ...parsed });+ }+ }+ return { found, problems };+}++/** A short, stable name so a re-run overwrites rather than accumulates. */+function assetName(entry) {+ const stem =+ entry.target+ .replace(/^\//, '')+ .replace(/\.[a-z0-9]+$/i, '')+ .replace(/[^a-z0-9]+/gi, '-')+ .replace(/^-+|-+$/g, '')+ .toLowerCase()+ .slice(0, 40) || 'root';+ const hash = createHash('sha256').update(entry.raw).digest('hex').slice(0, 8);+ return `${entry.kind}-${stem}-${hash}`;+}++// ── Capture ──────────────────────────────────────────────────────────────────++async function capturePage(browser, entry) {+ const width = Math.max(320, Math.min(1920, Number(entry.params.get('w')) || 1280));+ const height = Math.max(240, Math.min(1600, Number(entry.params.get('h')) || 760));+ const settle = Math.max(0, Number(entry.params.get('settle')) || 3500);+ const selector = entry.params.get('sel');+ const fullPage = entry.params.get('full') === '1';+ const theme = entry.params.get('theme') === 'light' ? 'light' : 'dark';++ const context = await browser.newContext({+ viewport: { width, height },+ deviceScaleFactor: 2,+ colorScheme: theme,+ reducedMotion: 'reduce',+ });+ // The site reads its theme from localStorage before first paint, so setting+ // it as an init script is the only way to capture the light theme honestly.+ await context.addInitScript(`try{localStorage.setItem('twx_theme',${JSON.stringify(theme)})}catch(e){}`);+ const page = await context.newPage();+ try {+ const url = `${BASE_URL}${entry.target}`;+ const res = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });+ if (res && res.status() >= 400) throw new Error(`${url} returned HTTP ${res.status()}`);+ await page.waitForTimeout(settle);+ // Floating chrome is not the UI a tutorial is teaching, and most of it+ // rotates its contents per visit, so leaving it in makes every re-capture+ // a spurious diff. Strip it, then let the layout settle before shooting.+ await page.evaluate(() => {+ const noise = [+ '#cookie-banner',+ '.cookie-banner',+ '[data-role="consent"]',+ '.newsletter-toast',+ '#tws-corner-stack', // rotating "Have you tried…" + Getting started progress+ 'lang-switcher', // runtime i18n picker, injected on every page+ '.walk-c2w-fx', // full-viewport walk-mode effect layer+ '.nav-skip',+ ];+ for (const sel of noise) document.querySelectorAll(sel).forEach((el) => el.remove());+ // Any leftover fixed overlay pinned to a viewport corner is chrome too.+ for (const el of document.querySelectorAll('body > *')) {+ if (getComputedStyle(el).position !== 'fixed') continue;+ const r = el.getBoundingClientRect();+ if (r.width > 0 && r.width < 420 && r.bottom > window.innerHeight - 220) el.remove();+ }+ });+ await page.waitForTimeout(400);++ let shot;+ if (selector) {+ const el = await page.waitForSelector(selector, { timeout: 15000, state: 'visible' });+ shot = await el.screenshot({ type: 'png' });+ } else {+ shot = await page.screenshot({ type: 'png', fullPage });+ }+ return shot;+ } finally {+ await context.close();+ }+}++async function captureGlb(entry) {+ const width = Math.max(64, Math.min(2048, Number(entry.params.get('w')) || 1200));+ const height = Math.max(64, Math.min(2048, Number(entry.params.get('h')) || 900));+ const background = entry.params.get('bg') || 'transparent';+ const glbUrl = `${BASE_URL}${entry.target}`;+ const url = `${BASE_URL}/api/render/glb?glbUrl=${encodeURIComponent(glbUrl)}&width=${width}&height=${height}&background=${encodeURIComponent(background)}`;+ const res = await fetch(url, { signal: AbortSignal.timeout(120000) });+ if (!res.ok) {+ const detail = await res.text().catch(() => '');+ throw new Error(`render/glb returned HTTP ${res.status} for ${entry.target} ${detail.slice(0, 200)}`);+ }+ const buf = Buffer.from(await res.arrayBuffer());+ if (buf.length < 1000) throw new Error(`render/glb returned ${buf.length} bytes for ${entry.target}, which is not an image`);+ return buf;+}++/** Confirm a live figure's model actually resolves, so the page never mounts a dead viewer. */+async function verifyLive(entry) {+ const url = `${BASE_URL}${entry.target}`;+ const res = await fetch(url, { method: 'GET', headers: { range: 'bytes=0-64' }, signal: AbortSignal.timeout(30000) });+ if (!res.ok) throw new Error(`${url} returned HTTP ${res.status}`);+ return null;+}++/** Encode to webp, and derive the inline placeholder that holds the layout. */+async function encode(png, outPath) {+ const image = sharp(png);+ const meta = await image.metadata();+ // Retina captures are 2x; publish at half so the intrinsic size matches the+ // CSS box and the browser still has the denser pixels to sample from.+ const width = meta.width || 1200;+ const height = meta.height || 800;+ await sharp(png).webp({ quality: QUALITY, effort: 5 }).toFile(outPath);+ const placeholder = await sharp(png)+ .resize(20, null, { fit: 'inside' })+ .blur(1.2)+ .webp({ quality: 40 })+ .toBuffer();+ return {+ width,+ height,+ placeholder: `data:image/webp;base64,${placeholder.toString('base64')}`,+ };+}++/** The revision the captures were taken from, or null outside a git checkout. */+function headCommit() {+ try {+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: ROOT, encoding: 'utf8' }).trim() || null;+ } catch {+ return null;+ }+}++// ── Run ──────────────────────────────────────────────────────────────────────++async function main() {+ const { found, problems } = collectDirectives();+ if (problems.length) {+ for (const p of problems) console.error(` bad figure ${p}`);+ console.error(`\ncapture-tutorial-media: ${problems.length} malformed figure directive(s). Fix the markdown.`);+ process.exit(1);+ }++ const previous = existsSync(MANIFEST) ? JSON.parse(readFileSync(MANIFEST, 'utf8')) : { figures: {} };+ const prevFigures = previous.figures || {};++ // One entry per unique directive: the same figure may be reused across+ // tutorials and must not be captured, or stored, twice.+ const byDirective = new Map();+ for (const entry of found) {+ if (!byDirective.has(entry.raw)) byDirective.set(entry.raw, { ...entry, slugs: new Set() });+ byDirective.get(entry.raw).slugs.add(entry.slug);+ }+ const entries = [...byDirective.values()];+ console.log(`capture-tutorial-media: ${entries.length} figure(s) across ${new Set(found.map((f) => f.slug)).size} tutorial(s), base ${BASE_URL}`);++ if (CHECK_ONLY) {+ const missing = entries.filter((e) => e.kind !== 'live' && !prevFigures[e.raw]);+ const orphaned = entries.filter((e) => {+ const rec = prevFigures[e.raw];+ return rec && rec.src && !existsSync(resolve(ROOT, 'public', rec.src.replace(/^\//, '')));+ });+ for (const e of missing) console.error(` uncaptured ${e.raw} (in ${[...e.slugs].join(', ')})`);+ for (const e of orphaned) console.error(` file gone ${e.raw} (in ${[...e.slugs].join(', ')})`);+ if (missing.length || orphaned.length) {+ console.error('\ncapture-tutorial-media --check failed. Run `npm run tutorials:media` to capture the gaps.');+ process.exit(1);+ }+ console.log('capture-tutorial-media: every figure has its media. OK');+ return;+ }++ let browser = null;+ const needsBrowser = entries.some((e) => e.kind === 'page' && (FORCE || !prevFigures[e.raw]));+ if (needsBrowser) browser = await chromium.launch({ args: ['--no-sandbox', '--disable-dev-shm-usage'] });++ const figures = {};+ let captured = 0;+ let reused = 0;+ const failures = [];++ try {+ for (const entry of entries) {+ const slugs = [...entry.slugs].sort();+ const name = assetName(entry);+ const rel = `docs/img/tutorials/${slugs[0]}/${name}.webp`;+ const outPath = resolve(ROOT, 'public', rel);+ const prior = prevFigures[entry.raw];++ if (entry.kind === 'live') {+ try {+ await verifyLive(entry);+ figures[entry.raw] = {+ kind: 'live',+ model: entry.target,+ orbit: entry.params.get('orbit') || null,+ source: `${SITE_URL}${entry.target}`,+ tutorials: slugs,+ };+ console.log(` live ${entry.target}`);+ } catch (err) {+ failures.push(`${entry.raw}: ${err.message}`);+ }+ continue;+ }++ if (!FORCE && prior && prior.src && existsSync(resolve(ROOT, 'public', prior.src.replace(/^\//, '')))) {+ figures[entry.raw] = { ...prior, tutorials: slugs };+ reused += 1;+ continue;+ }++ try {+ const png = entry.kind === 'page' ? await capturePage(browser, entry) : await captureGlb(entry);+ mkdirSync(dirname(outPath), { recursive: true });+ const { width, height, placeholder } = await encode(png, outPath);+ figures[entry.raw] = {+ kind: entry.kind,+ src: `/${rel}`,+ width,+ height,+ placeholder,+ source: `${SITE_URL}${entry.target}`,+ tutorials: slugs,+ };+ captured += 1;+ console.log(` wrote /${rel} ${width}x${height}`);+ } catch (err) {+ failures.push(`${entry.raw}: ${err.message}`);+ console.error(` FAIL ${entry.raw}\n ${err.message}`);+ }+ }+ } finally {+ if (browser) await browser.close();+ }++ // Drop assets whose directive no longer exists, so the folder tracks the+ // markdown instead of growing forever.+ const live = new Set(Object.values(figures).map((f) => f.src).filter(Boolean));+ for (const rec of Object.values(prevFigures)) {+ if (!rec.src || live.has(rec.src)) continue;+ const stale = resolve(ROOT, 'public', rec.src.replace(/^\//, ''));+ if (existsSync(stale)) {+ rmSync(stale);+ console.log(` pruned /${rec.src.replace(/^\//, '')}`);+ }+ }++ const payload = {+ $comment: 'GENERATED by scripts/capture-tutorial-media.mjs. Do not edit; run `npm run tutorials:media`.',+ base: BASE_URL,+ site: SITE_URL,+ // The commit the product was on when these figures were shot. A figure is+ // only honest about a screen that existed at a known revision, so the+ // manifest carries that revision instead of leaving readers to guess.+ commit: headCommit(),+ capturedAt: new Date().toISOString(),+ figures: Object.fromEntries(Object.entries(figures).sort(([a], [b]) => a.localeCompare(b))),+ };+ mkdirSync(dirname(MANIFEST), { recursive: true });+ writeFileSync(MANIFEST, `${JSON.stringify(payload, null, '\t')}\n`);+ console.log(`capture-tutorial-media: ${captured} captured, ${reused} reused, ${Object.keys(figures).length} in manifest`);++ if (failures.length) {+ console.error(`\ncapture-tutorial-media: ${failures.length} figure(s) failed:`);+ for (const f of failures) console.error(` ${f}`);+ process.exit(1);+ }+}++main().catch((err) => {+ console.error(`capture-tutorial-media: ${err.stack || err.message}`);+ process.exit(1);+});diff --git a/vite.config.shot.mjs b/vite.config.shot.mjsnew file mode 100644index 000000000..3ae3848b8--- /dev/null+++ b/vite.config.shot.mjs@@ -0,0 +1,2845 @@+import { defineConfig } from 'vite';+import { resolve } from 'path';+import {+ readFileSync,+ readdirSync,+ cpSync,+ createReadStream,+ existsSync,+ statSync,+ rmSync,+} from 'fs';+import { extname, basename, relative, sep } from 'path';+import { VitePWA } from 'vite-plugin-pwa';+import { nodePolyfills } from 'vite-plugin-node-polyfills';++// The build emits two targets controlled by the TARGET env var:+//+// TARGET=lib → builds dist-lib/agent-3d.js (ES module + UMD) for CDN use+// TARGET=app → (default) builds the editor/app site into dist/+//+// npm run build → app+// npm run build:lib → lib+// npm run build:all → both+const TARGET = process.env.TARGET || 'app';++// Prepended to every emitted chunk (app AND lib). `Object.hasOwn` is an ES2022+// *runtime API*, so esbuild's `target` never lowers it. It ships raw and throws+// "Object.hasOwn is not a function" on anything older than Chrome 93 / Safari+// 15.4. That killed /walk-embed outright on an Android 12 WebView (Chrome 91) in+// production. The embed's whole point is running inside third-party pages we+// don't control, so the floor has to be the old WebView, not our dev browser.+// defineProperty (not assignment) keeps it non-enumerable like the native one,+// so `for...in` over Object stays clean.+const LEGACY_RUNTIME_POLYFILL =+ 'if(!Object.hasOwn){Object.defineProperty(Object,"hasOwn",{value:function(o,k){' ++ 'if(o==null)throw new TypeError("Cannot convert undefined or null to object");' ++ 'return Object.prototype.hasOwnProperty.call(Object(o),k)},' ++ 'configurable:true,writable:true});}';++// Vercel serverless functions live under /api/* in production but Vite dev+// does not run them. Forward /api/* to a real upstream (default: production)+// so pages like /pumpfun see real SSE feeds and JSON responses in dev.+// Override with DEV_API_PROXY=http://localhost:3001 to point at vercel-dev.+const DEV_API_PROXY = process.env.DEV_API_PROXY || 'https://three.ws';+// Local override for /api/x402-pay (the demo's paid-call backend) so the agent+// payments settle from a locally-funded wallet in dev. Spin up the helper with+// `node scripts/dev-x402-pay-server.mjs` (reads .env for the agent wallet); Vite+// routes /api/x402-pay → here while other /api/* still proxy to prod. Defaults to+// the helper's port so a plain `npm run dev` works without an env prefix; if the+// helper isn't running the proxy's error handler below returns a clean 502 (not a+// crash). Set X402_PAY_DEV_URL='' to disable and fall back to the prod payer.+const X402_PAY_DEV_URL = process.env.X402_PAY_DEV_URL ?? 'http://localhost:3032';++// Auto-discover dashboard-next sub-pages so each agent can add an HTML file+// under pages/dashboard-next/ without touching this config. The Rollup input+// key is `dn-<filename>` (e.g. dn-index, dn-avatars). Missing directory is+// tolerated so the build keeps working before any page has landed.+function discoverDashboardNextInputs() {+ const dir = resolve(__dirname, 'pages/dashboard-next');+ if (!existsSync(dir)) return {};+ const entries = {};+ for (const f of readdirSync(dir)) {+ if (!f.endsWith('.html')) continue;+ const name = basename(f, '.html');+ entries[`dn-${name}`] = resolve(dir, f);+ }+ return entries;+}++// In a GitHub Codespace the browser reaches the dev server through the+// forwarded HTTPS domain (`<name>-3000.app.github.dev`) on port 443, not+// localhost:3000. Vite's HMR client otherwise tries to open a websocket to+// the raw host:port and both attempts fail ("[vite] failed to connect to+// websocket"), killing live-reload. Point the HMR client at the forwarded+// domain over wss/443 when those env vars are present; no-op locally.+const CODESPACE_HMR =+ process.env.CODESPACE_NAME && process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN+ ? {+ host: `${process.env.CODESPACE_NAME}-3000.${process.env.GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN}`,+ protocol: 'wss',+ clientPort: 443,+ }+ : undefined;++// Set by the threews-i18n-external-entry plugin's configResolved hook, read by+// its resolveId hook: a closure var rather than `this`, since Vite-only hooks+// (configResolved) aren't guaranteed the same PluginContext as Rollup hooks+// (resolveId).+let i18nExternalEntryIsBuild = true;++const appConfig = {+ server: {+ // Bind to 0.0.0.0 so the Codespace port-forwarder can reach the server.+ host: true,+ ...(CODESPACE_HMR ? { hmr: CODESPACE_HMR } : {}),+ proxy: {+ '/r2-proxy': {+ target: 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/r2-proxy/, ''),+ },+ // PostHog serves its loader bundle and remote config from the assets+ // host under both /static/* and /array/* — route BOTH there. Without+ // the /array rule, `/ingest/array/<token>/config.js` falls through to+ // us.i.posthog.com (which doesn't serve it) and the browser refuses+ // the empty-MIME response: "not executable".+ '/ingest/static': {+ target: 'https://us-assets.i.posthog.com',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/ingest/, ''),+ },+ '/ingest/array': {+ target: 'https://us-assets.i.posthog.com',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/ingest/, ''),+ },+ '/ingest': {+ target: 'https://us.i.posthog.com',+ changeOrigin: true,+ rewrite: (path) => path.replace(/^\/ingest/, ''),+ },+ '/chat': {+ // The chat UI is a separate Vite app served on :5174 (run+ // `cd chat && npm run dev`). `npm run dev` does not start it, so when+ // it's down the proxy would surface a bare HTTP 500 on every /chat+ // navigation. Degrade to a clean, self-contained 200 placeholder that+ // explains how to start it — no console error, honest dev guidance.+ target: 'http://localhost:5174',+ changeOrigin: true,+ configure: (proxy) => {+ proxy.on('error', (err, _req, res) => {+ if (!res || res.headersSent || res.writableEnded) return;+ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.end(+ `<!doctype html><meta charset="utf-8"><title>Chat — dev server offline</title>` ++ `<style>html{color-scheme:dark}body{margin:0;min-height:100vh;display:grid;place-items:center;` ++ `background:#0a0a0f;color:#e8e8f0;font:15px/1.6 ui-sans-serif,system-ui,sans-serif}` ++ `main{max-width:34rem;padding:2rem;text-align:center}code{background:#1a1a24;padding:.15em .45em;` ++ `border-radius:6px;font-size:.92em}a{color:#8ab4ff}</style>` ++ `<main><h1 style="margin:.2em 0;font-size:1.4rem">Chat dev server isn't running</h1>` ++ `<p>The chat UI is a separate app. Start it in another terminal:</p>` ++ `<p><code>cd chat && npm run dev</code></p>` ++ `<p style="opacity:.6;font-size:.9em">It serves on <code>:5174</code>; this page proxies to it. ` ++ `In production <code>/chat</code> is the deployed build — this notice is dev-only ` ++ `(${(err && err.code) || 'upstream offline'}).</p></main>`,+ );+ });+ },+ },+ ...(X402_PAY_DEV_URL+ ? {+ '/api/x402-pay': {+ target: X402_PAY_DEV_URL,+ changeOrigin: true,+ secure: false,+ configure: (proxy) => {+ proxy.on('error', (err, _req, res) => {+ if (!res || res.headersSent || res.writableEnded) return;+ res.statusCode = 502;+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ error: 'bad_gateway',+ message: `x402-pay dev helper unreachable at ${X402_PAY_DEV_URL}: ${err.message}`,+ }),+ );+ });+ },+ },+ }+ : {}),+ // /openapi.json is generated by the api/openapi-json function and+ // rewritten from /openapi.json in prod (vercel.json). Vite dev does+ // not run that function, so forward the bare path to the upstream so+ // the API-reference link on /pump-dashboard resolves in dev too.+ '/openapi.json': {+ target: DEV_API_PROXY,+ changeOrigin: true,+ secure: true,+ },+ '/api': {+ target: DEV_API_PROXY,+ changeOrigin: true,+ secure: true,+ ws: true,+ // `api/_lib/**` is source code (library modules shared by serverless+ // handlers), never a routable endpoint — the leading underscore is+ // this repo's established "not a route" convention (mirrors Next/+ // Vercel). A few isomorphic BNB modules (src/bnb/move-sender.js,+ // src/agora/onchain-presence.js — prompts 15/16) import straight from+ // api/_lib/bnb/*.js via a relative path so the exact same code runs+ // server- and client-side with zero duplication. That relative import+ // resolves in the BROWSER to a same-origin request for+ // /api/_lib/bnb/*.js, which this proxy would otherwise swallow and+ // forward upstream (404 — no such route exists there), breaking those+ // modules in `vite dev` even though the production bundle (which+ // inlines everything at build time) never hits this path. Bypassing+ // the proxy for /api/_lib/** lets Vite's own static/module server+ // return the real source file instead, so dev and prod both work.+ bypass: (req) => {+ if (req.url && req.url.startsWith('/api/_lib/')) return req.url;+ },+ // SSE responses (text/event-stream) must not be buffered.+ // http-proxy + Node's stream pipe handle this when we don't+ // touch the response, so leave selfHandleResponse off.+ configure: (proxy) => {+ proxy.on('proxyReq', (proxyReq) => {+ // Disable any compression that would force buffering+ // of streaming responses on the upstream side.+ proxyReq.setHeader('accept-encoding', 'identity');+ });+ proxy.on('error', (err, _req, res) => {+ // Without this handler, an upstream connection failure+ // (ECONNREFUSED on a transient blip) bubbles up as an+ // uncaught exception and kills the dev server.+ if (!res || res.headersSent || res.writableEnded) return;+ // With ws:true, a failed WebSocket upgrade passes the raw+ // net.Socket here instead of an http ServerResponse. A socket+ // has no setHeader/statusCode, so calling them would itself+ // throw an uncaught exception and crash the dev server — which+ // is exactly the failure this handler exists to prevent. Just+ // close the socket and bail.+ if (typeof res.setHeader !== 'function') {+ res.destroy?.();+ return;+ }+ res.statusCode = 502;+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({+ error: 'bad_gateway',+ message: `api proxy → ${DEV_API_PROXY} failed: ${err.message}`,+ }),+ );+ });+ },+ },+ },+ },+ esbuild: {+ jsx: 'transform',+ jsxFactory: 'vhtml',+ jsxFragment: '"div"',+ jsxDev: false,+ },+ resolve: {+ // Force a single Three.js instance — addons (GLTFLoader, OrbitControls,+ // etc.) must share the same `three` module as the app, otherwise+ // Three's module-scoped registry warns "Multiple instances of Three.js".+ dedupe: ['three'],+ alias: {+ // Resolve `buffer` to the real (CommonJS) npm package instead of the+ // ESM shim vite-plugin-node-polyfills would otherwise alias it to. The+ // shim exposes only named exports, but Vite's dep-optimizer rewrites+ // `import { Buffer } from 'buffer'` into a CJS-interop *default* import+ // (`import m from 'buffer'; m.Buffer`). With the named-only shim that+ // default is missing and the module fails to link in dev with+ // "buffer.js does not provide an export named 'default'" (hit on /cz,+ // whose lib.js pulls Solana/Anchor deps served as source). The CJS+ // package, once prebundled by esbuild, exposes both default and named.+ buffer: resolve(__dirname, 'node_modules/buffer/index.js'),+ },+ },+ optimizeDeps: {+ include: [+ // Prebundle the real `buffer` package (see resolve.alias above) so+ // esbuild's CJS interop synthesizes the `default` export Vite's+ // dep-optimizer expects when rewriting named buffer imports.+ 'buffer',+ 'three',+ 'three/addons/loaders/GLTFLoader.js',+ 'three/addons/loaders/DRACOLoader.js',+ 'three/addons/controls/OrbitControls.js',+ 'three/addons/environments/RoomEnvironment.js',+ 'three/addons/libs/meshopt_decoder.module.js',+ ],+ exclude: ['@three-ws/agent-payments'],+ },+ // Web Workers go through their OWN rollup pass, so build.rollupOptions below+ // does not reach them: without this the grinder workers shipped unguarded+ // `Object.hasOwn` (eoa-grinder-worker did) and died on the same old WebViews.+ worker: {+ rollupOptions: { output: { banner: LEGACY_RUNTIME_POLYFILL } },+ },+ build: {+ chunkSizeWarningLimit: 1000,+ // Skip computing gzip/brotli sizes during build — saves several seconds on+ // large bundles (Three.js, ethers) without affecting the output.+ reportCompressedSize: false,+ rollupOptions: {+ external: [+ '/launch/launch.js',+ '/launch-studio/launch-studio.js',+ '/studio/launch-panel.js',+ '/studio/fees-panel.js',+ './fees-panel.js',+ /^@three-ws\/agent-payments(\/.*)?$/,+ ],+ output: {+ // Every chunk, not just entries: with ES modules a shared chunk's+ // body evaluates BEFORE the entry that imports it, so an+ // entry-only banner would land too late to protect it.+ banner: LEGACY_RUNTIME_POLYFILL,+ manualChunks(id) {+ // Node polyfills (buffer/process shims) get their own tiny chunk.+ // Without this, Rollup colocates the `buffer` module inside the+ // 1 MB `solana` chunk — and any chunk that needs the injected+ // Buffer global (e.g. three-addons via its exporters) then+ // imports the whole solana chunk, which transitively chains+ // ethers too. That single colocation put ~1.4 MB of crypto code+ // on the home page's critical path.+ if (+ id.includes('node_modules/buffer/') ||+ id.includes('node_modules/process/') ||+ id.includes('vite-plugin-node-polyfills')+ )+ return 'node-polyfills';+ if (id.includes('node_modules/three/')) {+ if (id.includes('three/examples/') || id.includes('three/addons/'))+ return 'three-addons';+ return 'three-core';+ }+ if (id.includes('node_modules/ethers/')) return 'ethers';+ if (+ id.includes('node_modules/@solana/') ||+ id.includes('node_modules/@coral-xyz/')+ )+ return 'solana';+ if (id.includes('node_modules/@mediapipe/')) return 'mediapipe';+ },+ // A few entries need stable, unhashed filenames so plain public/+ // scripts can load them by a predictable URL without knowing the+ // build hash: footer.js → /footer-bot.js, nav.js → /walk-companion.js.+ entryFileNames: (chunk) =>+ chunk.name === 'footer-bot' ||+ chunk.name === 'walk-companion' ||+ chunk.name === 'walk-playground' ||+ chunk.name === 'feature-tour' ||+ chunk.name === 'notifications' ||+ chunk.name === 'nav-tier-badge' ||+ chunk.name === 'agent-bus'+ || chunk.name === 'i18n'+ ? `${chunk.name}.js`+ : 'assets/[name]-[hash].js',+ },+ input: {+ 'footer-bot': resolve(__dirname, 'src/footer-bot.js'),+ 'walk-companion': resolve(__dirname, 'src/walk-companion.js'),+ 'agent-bus': resolve(__dirname, 'src/agents/agent-bus.js'),+ 'walk-playground': resolve(__dirname, 'src/walk-playground.js'),+ 'feature-tour': resolve(__dirname, 'src/feature-tour.js'),+ notifications: resolve(__dirname, 'src/notifications.js'),+ 'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),+ i18n: resolve(__dirname, 'src/i18n.js'),+ app: resolve(__dirname, 'pages/app.html'),+ proof: resolve(__dirname, 'pages/proof.html'),+ integrity: resolve(__dirname, 'pages/integrity.html'),+ 'app-next': resolve(__dirname, 'pages/app-next.html'),+ home: resolve(__dirname, 'pages/home.html'),+ 'what-is': resolve(__dirname, 'pages/what-is.html'),+ tour: resolve(__dirname, 'pages/tour.html'),+ concierge: resolve(__dirname, 'pages/concierge.html'),+ 'tour-builder': resolve(__dirname, 'pages/tour-builder.html'),+ 'agent-identities': resolve(__dirname, 'pages/agent-identities.html'),+ 'mcp-tools': resolve(__dirname, 'pages/mcp-tools.html'),+ inspect: resolve(__dirname, 'pages/inspect.html'),+ pitch: resolve(__dirname, 'pages/pitch.html'),+ timeline: resolve(__dirname, 'pages/timeline.html'),+ tracker: resolve(__dirname, 'pages/tracker.html'),+ features: resolve(__dirname, 'pages/features.html'),+ 'features-ar': resolve(__dirname, 'pages/features/ar.html'),+ 'features-forge': resolve(__dirname, 'pages/features/forge.html'),+ 'features-scan': resolve(__dirname, 'pages/features/scan.html'),+ 'features-play': resolve(__dirname, 'pages/features/play.html'),+ 'features-walk': resolve(__dirname, 'pages/features/walk.html'),+ 'features-studio': resolve(__dirname, 'pages/features/studio.html'),+ 'features-marketplace': resolve(__dirname, 'pages/features/marketplace.html'),+ 'features-agent-exchange': resolve(__dirname, 'pages/features/agent-exchange.html'),+ 'features-deploy': resolve(__dirname, 'pages/features/deploy.html'),+ tutorials: resolve(__dirname, 'pages/tutorials.html'),+ tutorial: resolve(__dirname, 'pages/tutorial.html'),+ cookbook: resolve(__dirname, 'pages/cookbook.html'),+ recipe: resolve(__dirname, 'pages/recipe.html'),+ 'pipeline-studio': resolve(__dirname, 'pages/pipeline-studio.html'),+ glossary: resolve(__dirname, 'pages/glossary.html'),+ playground: resolve(__dirname, 'pages/playground.html'),+ coin3d: resolve(__dirname, 'pages/coin3d.html'),+ 'hero-demo': resolve(__dirname, 'pages/hero-demo.html'),+ constellation: resolve(__dirname, 'pages/constellation.html'),+ embed: resolve(__dirname, 'pages/embed.html'),+ 'embed-demo': resolve(__dirname, 'pages/embed-demo.html'),+ assistant: resolve(__dirname, 'pages/assistant.html'),+ 'assistant-frame': resolve(__dirname, 'pages/assistant-frame.html'),+ // Embodiment embed: a living, rigged agent body (lip-sync + emotion+ // + idle) that renders inline in ChatGPT/Claude. Registered as an+ // input so its inline module graph — /apps-sdk/embodiment/* → three+ // → src/animation-* + src/embodiment/* — gets bundled to /assets/*+ // chunks instead of shipping unresolved bare imports.+ 'embodiment-embed': resolve(__dirname, 'pages/embodiment/embed.html'),+ integrations: resolve(__dirname, 'pages/integrations.html'),+ partners: resolve(__dirname, 'pages/partners.html'),+ sperax: resolve(__dirname, 'pages/sperax.html'),+ widget: resolve(__dirname, 'pages/widget.html'),+ launchpad: resolve(__dirname, 'pages/launchpad.html'),+ launch: resolve(__dirname, 'pages/launch.html'),+ 'launch-studio': resolve(__dirname, 'pages/launch-studio.html'),+ start: resolve(__dirname, 'pages/start.html'),+ create: resolve(__dirname, 'pages/create.html'),+ 'create-agent': resolve(__dirname, 'pages/create-agent.html'),+ forge: resolve(__dirname, 'pages/forge.html'),+ 'nim-forge': resolve(__dirname, 'pages/nim-forge.html'),+ 'forge-nim': resolve(__dirname, 'pages/forge-nim.html'),+ 'forge-spark': resolve(__dirname, 'pages/forge-spark.html'),+ dad: resolve(__dirname, 'pages/dad.html'),+ 'forge-studio': resolve(__dirname, 'pages/forge-studio.html'),+ 'forge-embed': resolve(__dirname, 'pages/forge-embed.html'),+ restyle: resolve(__dirname, 'pages/restyle.html'),+ scene: resolve(__dirname, 'pages/scene.html'),+ segment: resolve(__dirname, 'pages/segment.html'),+ 'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),+ 'create-prompt': resolve(__dirname, 'pages/create-prompt.html'),+ genesis: resolve(__dirname, 'pages/genesis.html'),+ worlds: resolve(__dirname, 'pages/worlds.html'),+ 'docs-world': resolve(__dirname, 'pages/docs-world.html'),+ 'avatar-studio': resolve(__dirname, 'pages/avatar-studio.html'),+ 'create-review': resolve(__dirname, 'pages/create-review.html'),+ 'import-rpm': resolve(__dirname, 'pages/import-rpm.html'),+ marketplace: resolve(__dirname, 'pages/marketplace.html'),+ 'marketplace-walk': resolve(__dirname, 'pages/marketplace-walk.html'),+ 'marketplace-analytics': resolve(__dirname, 'pages/marketplace-analytics.html'),+ collection: resolve(__dirname, 'pages/collection.html'),+ // Key must NOT be `notifications` — that key at the top of this input+ // object is the nav-bell module (src/notifications.js), which nav.js+ // loads on every page as /notifications.js. A duplicate key here+ // silently replaced it (later key wins), so the bell only worked+ // because this page's bundle happened to import the bell module+ // transitively. HTML output paths come from the source file path,+ // not the input key, so the page still emits dist/notifications.html.+ 'notifications-page': resolve(__dirname, 'pages/notifications.html'),+ 'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),+ 'agent-mind': resolve(__dirname, 'pages/agent-mind.html'),+ 'avatar-edit': resolve(__dirname, 'pages/avatar-edit.html'),+ 'create-video': resolve(__dirname, 'pages/create/video.html'),+ 'extension-privacy': resolve(__dirname, 'pages/extension-privacy.html'),+ 'extension-terms': resolve(__dirname, 'pages/extension-terms.html'),+ 'embed-walk': resolve(__dirname, 'pages/embed-walk.html'),+ 'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),+ 'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),+ 'agent-detail-classic': resolve(__dirname, 'pages/agent-detail-classic.html'),+ 'agent-screen': resolve(__dirname, 'pages/agent-screen.html'),+ 'agents-live': resolve(__dirname, 'pages/agents-live.html'),+ 'agent-wallet': resolve(__dirname, 'pages/agent-wallet.html'),+ wallet: resolve(__dirname, 'pages/wallet.html'),+ guardian: resolve(__dirname, 'pages/guardian.html'),+ launches: resolve(__dirname, 'pages/launches.html'),+ minted: resolve(__dirname, 'pages/minted.html'),+ creations: resolve(__dirname, 'pages/creations.html'),+ pulse: resolve(__dirname, 'pages/pulse.html'),+ symphony: resolve(__dirname, 'pages/symphony.html'),+ diorama: resolve(__dirname, 'pages/diorama.html'),+ 'x402-revenue': resolve(__dirname, 'pages/x402-revenue.html'),+ receipts: resolve(__dirname, 'pages/receipts.html'),+ fits: resolve(__dirname, 'pages/fits.html'),+ viability: resolve(__dirname, 'pages/viability.html'),+ deployments: resolve(__dirname, 'pages/deployments.html'),+ 'admin-launcher': resolve(__dirname, 'pages/admin/launcher.html'),+ 'admin-seeder': resolve(__dirname, 'pages/admin/seeder.html'),+ 'admin-ring': resolve(__dirname, 'pages/admin/ring.html'),+ 'admin-economy': resolve(__dirname, 'pages/admin/economy.html'),+ 'admin-ops': resolve(__dirname, 'pages/admin/ops.html'),+ 'admin-irl-analytics': resolve(__dirname, 'pages/admin/irl-analytics.html'),+ launcher: resolve(__dirname, 'pages/launcher.html'),+ 'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),+ watchlist: resolve(__dirname, 'pages/watchlist.html'),+ leaderboard: resolve(__dirname, 'pages/leaderboard.html'),+ 'labor-market': resolve(__dirname, 'pages/labor-market.html'),+ vaults: resolve(__dirname, 'pages/vaults.html'),+ 'alpha-copilot': resolve(__dirname, 'pages/alpha-copilot.html'),+ 'reasoning-ledger': resolve(__dirname, 'pages/reasoning-ledger.html'),+ 'fact-check': resolve(__dirname, 'pages/fact-check.html'),+ mirror: resolve(__dirname, 'pages/mirror.html'),+ strategies: resolve(__dirname, 'pages/strategies.html'),+ swarms: resolve(__dirname, 'pages/swarms.html'),+ 'ui-juice': resolve(__dirname, 'pages/ui-juice.html'),+ terminal: resolve(__dirname, 'pages/terminal.html'),+ trader: resolve(__dirname, 'pages/trader.html'),+ signals: resolve(__dirname, 'pages/signals.html'),+ 'signal-detail': resolve(__dirname, 'pages/signal-detail.html'),+ trades: resolve(__dirname, 'pages/trades.html'),+ trading: resolve(__dirname, 'pages/trading.html'),+ 'exit-lab': resolve(__dirname, 'pages/exit-lab.html'),+ 'claim-wallet': resolve(__dirname, 'pages/claim-wallet.html'),+ 'meta-allocator': resolve(__dirname, 'pages/meta-allocator.html'),+ 'clip-director': resolve(__dirname, 'pages/clip-director.html'),+ 'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),+ 'avatar-wallet-chat': resolve(__dirname, 'pages/avatar-wallet-chat.html'),+ 'agent-exchange': resolve(__dirname, 'pages/agent-exchange.html'),+ 'demo-economy': resolve(__dirname, 'pages/demo-economy.html'),+ live: resolve(__dirname, 'pages/live.html'),+ 'agent-economy': resolve(__dirname, 'pages/agent-economy.html'),+ 'agent-economy-volume': resolve(__dirname, 'pages/agent-economy-volume.html'),+ economy: resolve(__dirname, 'pages/economy.html'),+ 'overlay-control': resolve(__dirname, 'pages/overlay-control.html'),+ 'mocap-studio': resolve(__dirname, 'pages/mocap-studio.html'),+ handle: resolve(__dirname, 'pages/handle.html'),+ 'a-embed': resolve(__dirname, 'pages/a-embed.html'),+ 'a-edit': resolve(__dirname, 'pages/a-edit.html'),+ 'a-me': resolve(__dirname, 'pages/a-me.html'),+ labs: resolve(__dirname, 'pages/labs.html'),+ 'quality-bench': resolve(__dirname, 'pages/quality-bench.html'),+ search: resolve(__dirname, 'pages/search.html'),+ rankings: resolve(__dirname, 'pages/rankings.html'),+ 'daily-match': resolve(__dirname, 'pages/daily-match.html'),+ 'fact-checker': resolve(__dirname, 'pages/fact-checker.html'),+ unstoppable: resolve(__dirname, 'pages/unstoppable.html'),+ shopper: resolve(__dirname, 'pages/shopper.html'),+ go: resolve(__dirname, 'pages/go.html'),+ bounties: resolve(__dirname, 'pages/bounties.html'),+ bounty: resolve(__dirname, 'pages/bounty.html'),+ 'pump-live': resolve(__dirname, 'pages/pump-live.html'),+ radar: resolve(__dirname, 'pages/radar.html'),+ oracle: resolve(__dirname, 'pages/oracle.html'),+ 'oracle-docs': resolve(__dirname, 'pages/oracle-docs.html'),+ arm: resolve(__dirname, 'pages/arm.html'),+ ca2x402: resolve(__dirname, 'pages/ca2x402.html'),+ activity: resolve(__dirname, 'pages/activity.html'),+ guards: resolve(__dirname, 'pages/guards.html'),+ pipeline: resolve(__dirname, 'pages/pipeline.html'),+ 'coin-intel': resolve(__dirname, 'pages/coin-intel.html'),+ coins: resolve(__dirname, 'pages/coins.html'),+ coin: resolve(__dirname, 'pages/coin.html'),+ drop: resolve(__dirname, 'pages/drop.html'),+ markets: resolve(__dirname, 'pages/markets.html'),+ 'markets-news': resolve(__dirname, 'pages/markets-news.html'),+ 'news-digest': resolve(__dirname, 'pages/news-digest.html'),+ 'news-article': resolve(__dirname, 'pages/news-article.html'),+ 'news-archive': resolve(__dirname, 'pages/news-archive.html'),+ 'fear-greed': resolve(__dirname, 'pages/fear-greed.html'),+ heatmap: resolve(__dirname, 'pages/heatmap.html'),+ gas: resolve(__dirname, 'pages/gas.html'),+ compare: resolve(__dirname, 'pages/compare.html'),+ screener: resolve(__dirname, 'pages/screener.html'),+ categories: resolve(__dirname, 'pages/categories.html'),+ exchanges: resolve(__dirname, 'pages/exchanges.html'),+ derivatives: resolve(__dirname, 'pages/derivatives.html'),+ converter: resolve(__dirname, 'pages/converter.html'),+ defi: resolve(__dirname, 'pages/defi.html'),+ chains: resolve(__dirname, 'pages/chains.html'),+ stablecoins: resolve(__dirname, 'pages/stablecoins.html'),+ exchange: resolve(__dirname, 'pages/exchange.html'),+ category: resolve(__dirname, 'pages/category.html'),+ yields: resolve(__dirname, 'pages/yields.html'),+ protocol: resolve(__dirname, 'pages/protocol.html'),+ chain: resolve(__dirname, 'pages/chain.html'),+ stablecoin: resolve(__dirname, 'pages/stablecoin.html'),+ 'markets-trending': resolve(__dirname, 'pages/markets-trending.html'),+ 'markets-robinhood': resolve(__dirname, 'pages/markets-robinhood.html'),+ fees: resolve(__dirname, 'pages/fees.html'),+ 'sniper-experiments': resolve(__dirname, 'pages/sniper-experiments.html'),+ 'dex-volumes': resolve(__dirname, 'pages/dex-volumes.html'),+ hacks: resolve(__dirname, 'pages/hacks.html'),+ bnb: resolve(__dirname, 'pages/bnb.html'),+ 'bnb-latency': resolve(__dirname, 'pages/bnb-latency.html'),+ vault: resolve(__dirname, 'pages/vault.html'),+ trending: resolve(__dirname, 'pages/trending.html'),+ compose: resolve(__dirname, 'pages/compose.html'),+ 'create-next': resolve(__dirname, 'pages/create-next.html'),+ 'mint-success': resolve(__dirname, 'pages/mint-success.html'),+ 'bulk-launch': resolve(__dirname, 'pages/bulk-launch.html'),+ 'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),+ autopilot: resolve(__dirname, 'pages/autopilot.html'),+ 'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),+ crypto: resolve(__dirname, 'pages/crypto.html'),+ 'crypto-api': resolve(__dirname, 'pages/crypto-api.html'),+ three: resolve(__dirname, 'pages/three.html'),+ 'three-live': resolve(__dirname, 'pages/three-live.html'),+ 'three-token': resolve(__dirname, 'pages/three-token.html'),+ 'avatar-artifact': resolve(__dirname, 'pages/avatar-artifact.html'),+ 'launch-week': resolve(__dirname, 'pages/three-ws-launch-week.html'),+ community: resolve(__dirname, 'pages/community.html'),+ profile: resolve(__dirname, 'pages/profile.html'),+ feed: resolve(__dirname, 'pages/feed.html'),+ 'threews-claim': resolve(__dirname, 'pages/threews-claim.html'),+ 'events-build-3d-agents-live': resolve(__dirname, 'pages/events/build-3d-agents-live.html'),+ 'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),+ 'avatar-sdk': resolve(__dirname, 'pages/avatar-sdk.html'),+ 'avatar-cli': resolve(__dirname, 'pages/avatar-cli.html'),+ 'rig-doctor': resolve(__dirname, 'pages/rig-doctor.html'),+ brain: resolve(__dirname, 'pages/brain.html'),+ 'agent-studio': resolve(__dirname, 'pages/agent-studio.html'),+ cosmos: resolve(__dirname, 'pages/cosmos.html'),+ voice: resolve(__dirname, 'pages/voice.html'),+ galaxy: resolve(__dirname, 'pages/galaxy.html'),+ examples: resolve(__dirname, 'pages/examples.html'),+ genome: resolve(__dirname, 'pages/genome.html'),+ 'ar-page': resolve(__dirname, 'pages/ar.html'),+ pricing: resolve(__dirname, 'pages/pricing.html'),+ billing: resolve(__dirname, 'pages/billing.html'),+ credits: resolve(__dirname, 'pages/credits.html'),+ payments: resolve(__dirname, 'pages/payments.html'),+ 'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),+ 'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),+ status: resolve(__dirname, 'pages/status.html'),+ xr: resolve(__dirname, 'pages/xr.html'),+ temporary: resolve(__dirname, 'pages/temporary.html'),+ irl: resolve(__dirname, 'pages/irl.html'),+ daily: resolve(__dirname, 'pages/daily.html'),+ 'ar-studio': resolve(__dirname, 'pages/ar-studio.html'),+ 'irl-privacy': resolve(__dirname, 'pages/irl-privacy.html'),+ 'world-lines': resolve(__dirname, 'pages/world-lines.html'),+ communities: resolve(__dirname, 'pages/communities.html'),+ clash: resolve(__dirname, 'pages/clash.html'),+ 'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),+ 'walk-landing': resolve(__dirname, 'pages/walk-landing.html'),+ 'walk-leaderboard': resolve(__dirname, 'pages/walk-leaderboard.html'),+ 'walk-analytics': resolve(__dirname, 'pages/walk-analytics.html'),+ city: resolve(__dirname, 'pages/city.html'),+ agora: resolve(__dirname, 'pages/agora.html'),+ play: resolve(__dirname, 'pages/play.html'),+ 'play-agent-wallet': resolve(__dirname, 'pages/play/agent-wallet.html'),+ 'play-arena': resolve(__dirname, 'pages/play/arena.html'),+ 'play-ufo': resolve(__dirname, 'pages/play/ufo.html'),+ 'play-economy': resolve(__dirname, 'pages/play/economy.html'),+ agi: resolve(__dirname, 'pages/agi.html'),+ arena: resolve(__dirname, 'pages/arena.html'),+ 'smart-money': resolve(__dirname, 'pages/smart-money.html'),+ pose: resolve(__dirname, 'pages/pose.html'),+ 'pose-mini': resolve(__dirname, 'pages/pose-mini.html'),+ animations: resolve(__dirname, 'pages/animations.html'),+ gestures: resolve(__dirname, 'pages/gestures.html'),+ choreograph: resolve(__dirname, 'pages/choreograph.html'),+ 'character-library': resolve(__dirname, 'pages/character-library.html'),+ 'sign-language': resolve(__dirname, 'pages/sign-language.html'),+ 'asl-alphabet': resolve(__dirname, 'pages/asl-alphabet.html'),+ objects: resolve(__dirname, 'pages/objects.html'),+ forged: resolve(__dirname, 'pages/forged.html'),+ wardrobe: resolve(__dirname, 'pages/wardrobe.html'),+ 'avatar-engines': resolve(__dirname, 'pages/avatar-engines.html'),+ splat: resolve(__dirname, 'pages/splat.html'),+ capture: resolve(__dirname, 'pages/capture.html'),+ 'motion-swap': resolve(__dirname, 'pages/motion-swap.html'),+ club: resolve(__dirname, 'pages/club.html'),+ theater: resolve(__dirname, 'pages/theater.html'),+ stage: resolve(__dirname, 'pages/stage.html'),+ skills: resolve(__dirname, 'pages/skills.html'),+ 'agenc-embodied': resolve(__dirname, 'pages/agenc/embodied.html'),+ 'agenc-room': resolve(__dirname, 'pages/agenc/room.html'),+ studio: resolve(__dirname, 'public/studio/index.html'),+ reputation: resolve(__dirname, 'public/reputation/index.html'),+ hydrate: resolve(__dirname, 'public/hydrate/index.html'),+ // /agent/index.html is reachable as a static page (vercel.json+ // routes it to itself). Registering it as a Vite input bundles+ // its inline modules (incl. pump-modals, agent-token-widget)+ // instead of shipping /src/* refs that 404 in production.+ 'agent-token-page': resolve(__dirname, 'public/agent/index.html'),+ // /login lives in public/ but its inline avatar module imports the+ // bare `@three-ws/agent-ui` specifier. Registering it as an input+ // bundles that module so the sign-in avatar renders in production+ // instead of shipping an unresolvable bare import.+ login: resolve(__dirname, 'public/login.html'),+ register: resolve(__dirname, 'public/register.html'),+ // /agents and /validation live in public/ and load module+ // scripts that pull bare npm specifiers (`ethers`, JSX+ // components). Registering them as inputs bundles those graphs+ // so resolved /assets/* chunks ship instead of raw /src/* refs+ // that throw "Failed to resolve module specifier" / "text/jsx"+ // in production. Promoted over the raw publicDir copy below.+ 'agents-directory': resolve(__dirname, 'public/agents/index.html'),+ validation: resolve(__dirname, 'public/validation/index.html'),+ // /characters and /character/:id load `/src/characters.js` and+ // `/src/character.js`, both of which `import './ui-juice.css'` — a+ // Vite-only construct. Served raw, the browser fetched that CSS as a+ // module script, got `text/css`, and refused it under strict MIME+ // checking. The entry module never executed, so BOTH pages rendered an+ // empty grid in production. Registering them as inputs bundles the+ // graph and extracts the CSS into a <link>. Promoted below.+ characters: resolve(__dirname, 'public/characters.html'),+ character: resolve(__dirname, 'public/character.html'),+ // BEGIN:DISCOVER_ROUTE+ 'my-agents': resolve(__dirname, 'public/my-agents/index.html'),+ discover: resolve(__dirname, 'public/discover/index.html'),+ gallery: resolve(__dirname, 'public/gallery/index.html'),+ // END:DISCOVER_ROUTE+ 'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),+ 'vanity-verify': resolve(__dirname, 'public/vanity/verify/index.html'),+ 'vanity-gallery': resolve(__dirname, 'public/vanity/gallery/index.html'),+ 'vanity-premium': resolve(__dirname, 'public/vanity/premium/index.html'),+ 'vanity-bounties': resolve(__dirname, 'public/vanity/bounties/index.html'),+ 'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),+ 'evm-wallet': resolve(__dirname, 'public/evm-wallet.html'),+ pay: resolve(__dirname, 'public/pay/index.html'),+ 'pay-calls': resolve(__dirname, 'public/pay/calls/index.html'),+ 'pay-checkout': resolve(__dirname, 'public/pay/c/index.html'),+ 'x402-stripe': resolve(__dirname, 'public/x402-stripe.html'),+ 'x402-dashboard': resolve(__dirname, 'public/dashboard/x402.html'),+ sitemap: resolve(__dirname, 'public/sitemap/index.html'),+ 'avatar-os-hub': resolve(__dirname, 'public/demo/avatar-os/index.html'),+ 'avatar-os-studio': resolve(__dirname, 'public/demo/avatar-os/studio.html'),+ 'avatar-os-selfie': resolve(__dirname, 'public/demo/avatar-os/selfie.html'),+ 'avatar-os-combined': resolve(__dirname, 'public/demo/avatar-os/combined.html'),+ 'demos-brain': resolve(__dirname, 'public/demos/brain.html'),+ 'demos-lipsync-tts': resolve(__dirname, 'public/demos/lipsync-tts.html'),+ 'demos-lipsync-mic': resolve(__dirname, 'public/demos/lipsync-mic.html'),+ 'demos-audio2face': resolve(__dirname, 'public/demos/audio2face.html'),+ 'demos-erc8004': resolve(__dirname, 'public/demos/erc8004.html'),+ 'demos-button-jump': resolve(__dirname, 'public/demos/button-jump.html'),+ 'demos-button': resolve(__dirname, 'public/demos/button.html'),+ 'demos-3d-home': resolve(__dirname, 'public/demos/3d-home.html'),+ 'demos-halfbody-xr': resolve(__dirname, 'public/demos/halfbody-xr.html'),+ // /demos/agents/* — agent interaction lab.+ 'agents-index': resolve(__dirname, 'public/demos/agents/index.html'),+ 'agents-cursor-follower': resolve(+ __dirname,+ 'public/demos/agents/cursor-follower.html',+ ),+ 'agents-high-five': resolve(__dirname, 'public/demos/agents/high-five.html'),+ 'agents-pickup-drop': resolve(__dirname, 'public/demos/agents/pickup-drop.html'),+ 'agents-fall-from-top': resolve(+ __dirname,+ 'public/demos/agents/fall-from-top.html',+ ),+ 'agents-trampoline': resolve(__dirname, 'public/demos/agents/trampoline.html'),+ 'agents-wrecking-ball': resolve(+ __dirname,+ 'public/demos/agents/wrecking-ball.html',+ ),+ 'agents-climb-title': resolve(__dirname, 'public/demos/agents/climb-title.html'),+ 'agents-skateboard': resolve(__dirname, 'public/demos/agents/skateboard.html'),+ 'agents-sit-in-body': resolve(__dirname, 'public/demos/agents/sit-in-body.html'),+ 'agents-scroll-inertia': resolve(+ __dirname,+ 'public/demos/agents/scroll-inertia.html',+ ),+ 'agents-walks-gutter': resolve(__dirname, 'public/demos/agents/walks-gutter.html'),+ 'agents-holds-cta': resolve(__dirname, 'public/demos/agents/holds-cta.html'),+ 'agents-falls-asleep': resolve(__dirname, 'public/demos/agents/falls-asleep.html'),+ 'agents-builds-button': resolve(+ __dirname,+ 'public/demos/agents/builds-button.html',+ ),+ 'agents-face-mocap': resolve(__dirname, 'public/demos/agents/face-mocap.html'),+ 'agents-gemini-live': resolve(__dirname, 'public/demos/agents/gemini-live.html'),+ 'agents-auto-rig': resolve(__dirname, 'public/demos/agents/auto-rig.html'),+ 'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),+ aws: resolve(__dirname, 'pages/aws/index.html'),+ openai: resolve(__dirname, 'pages/openai/index.html'),+ nvidia: resolve(__dirname, 'pages/nvidia/index.html'),+ press: resolve(__dirname, 'pages/press/index.html'),+ 'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),+ 'autopilot-activity': resolve(__dirname, 'pages/autopilot-activity.html'),+support: resolve(__dirname, 'pages/support.html'),+ // dashboard-next prototype — sub-pages auto-discovered so the parallel+ // agents that land new pages/dashboard-next/*.html files don't have to+ // touch this config to register them as Rollup inputs.+ ...discoverDashboardNextInputs(),+ },+ },+ },+ plugins: [+ // Resolve the shared runtime i18n entry as an EXTERNAL script — but only+ // during BUILD. Many static pages load the locale runtime via+ // `<script type="module" src="/i18n.js">` (injected by+ // scripts/i18n-annotate.mjs --wire). That path is emitted at the dist root+ // by the `i18n` rollupOptions.input entry (see entryFileNames above), so it+ // exists at runtime. Without marking it external, Vite's build tries to+ // resolve `/i18n.js` as an on-disk module while processing each page's HTML+ // and fails ("Failed to resolve /i18n.js from pages/<page>.html"), breaking+ // the whole build for every wired page. Marking it external leaves the tag+ // untouched in the output HTML and lets the emitted chunk serve it.+ //+ // In DEV/serve mode there is no dist chunk yet, so treating it as external+ // left every wired page with a real 404 on `/i18n.js` (a console error+ // against the Definition-of-Done "no console errors" bar). Dev instead+ // resolves the tag straight to the source file, so the runtime loads and+ // behaves identically to the built page. Applies only to the exact+ // absolute path so nothing else is affected.+ {+ name: 'threews-i18n-external-entry',+ enforce: 'pre',+ configResolved(config) {+ i18nExternalEntryIsBuild = config.command === 'build';+ },+ resolveId(source) {+ if (source !== '/i18n.js') return null;+ if (i18nExternalEntryIsBuild) return { id: '/i18n.js', external: true };+ return resolve(__dirname, 'src/i18n.js');+ },+ },+ // Strip the VitePWA service-worker registration <script> from any+ // page meant to be embedded in a third-party iframe. Without this,+ // the slim /widget shell — loaded under arbitrary origins as an+ // iframe — would register a service worker scoped to three.ws, then+ // intercept and cache requests across every other page on the same+ // origin. Privacy & correctness hazard for embedders.+ //+ // VitePWA itself injects the script via its own enforce:'post'+ // transformIndexHtml, so this strip has to run *after* the bundle is+ // emitted to disk — a closeBundle hook on the dist/ output directory+ // is the only ordering that's stable across Vite versions.+ {+ name: 'three-ws-strip-sw-from-embeds',+ apply: 'build',+ closeBundle: {+ sequential: true,+ order: 'post',+ async handler() {+ const { readdirSync, statSync, readFileSync, writeFileSync } =+ await import('node:fs');+ const { join, resolve: resolvePath } = await import('node:path');+ const EMBED_ENTRIES = new Set([+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',+ 'agent-token-page.html',+ 'assistant-frame.html',+ ]);+ const RE =+ /<script[^>]*id=["']vite-plugin-pwa:register-sw["'][^>]*><\/script>\s*/g;+ const outDir = resolvePath(__dirname, 'dist');+ const stripped = [];+ const walk = (dir) => {+ let entries;+ try {+ entries = readdirSync(dir);+ } catch {+ return;+ }+ for (const name of entries) {+ const full = join(dir, name);+ let s;+ try {+ s = statSync(full);+ } catch {+ continue;+ }+ if (s.isDirectory()) {+ walk(full);+ continue;+ }+ if (!EMBED_ENTRIES.has(name)) continue;+ const html = readFileSync(full, 'utf8');+ const next = html.replace(RE, '');+ if (next === html) continue;+ writeFileSync(full, next);+ stripped.push(full);+ }+ };+ walk(outDir);+ if (stripped.length) {+ // eslint-disable-next-line no-console+ console.log(+ '[strip-sw] removed registerSW script from:',+ stripped.map((p) => p.replace(outDir + '/', '')).join(', '),+ );+ }+ },+ },+ },+ // Polyfill the Node `process` global so @solana/web3.js (and any other dep+ // that touches `process`) works in the browser without the "Module has+ // been externalized" console warning. Scoped narrowly — we don't blanket-+ // polyfill all Node builtins because most pages don't need them.+ //+ // `buffer` is intentionally NOT in `include`: the plugin would alias it to+ // an ESM shim with named exports only, but Vite's dep-optimizer rewrites+ // named buffer imports into a CJS-interop *default* import, which then+ // fails to link ("buffer.js does not provide an export named 'default'").+ // Instead resolve.alias points `buffer` at the real CJS package (which+ // prebundles with both default and named) and `globals.Buffer` still+ // injects the global from it.+ nodePolyfills({+ include: ['process'],+ globals: { Buffer: true, process: true, global: true },+ protocolImports: true,+ }),+ // Dev only: serve the <agent-3d> custom-element bundle from the locally+ // built dist-lib/ and rewrite pages' absolute CDN loader to a same-origin+ // path. The homepage and other surfaces hardcode+ // https://three.ws/agent-3d/latest/agent-3d.js, which on localhost loads+ // the separately-deployed (and possibly stale) CDN bundle instead of the+ // local build — so element.js changes never showed up in dev. This makes+ // dev reflect the local lib. No effect on production builds (apply:'serve').+ {+ name: 'dev-local-agent-3d',+ apply: 'serve',+ configureServer(server) {+ const libFiles = {+ js: resolve(__dirname, 'dist-lib/agent-3d.js'),+ 'umd.cjs': resolve(__dirname, 'dist-lib/agent-3d.umd.cjs'),+ };+ server.middlewares.use((req, res, next) => {+ const path = (req.url || '').split('?')[0];+ const m = /^\/agent-3d\/[^/]+\/agent-3d\.(js|umd\.cjs)$/.exec(path);+ if (!m) return next();+ const file = libFiles[m[1]];+ if (!file || !existsSync(file)) {+ res.statusCode = 503;+ res.setHeader('content-type', 'text/plain; charset=utf-8');+ return res.end('agent-3d dev bundle missing — run `npm run build:lib`');+ }+ res.setHeader('content-type', 'text/javascript; charset=utf-8');+ res.setHeader('cache-control', 'no-cache');+ res.setHeader('access-control-allow-origin', '*');+ return res.end(readFileSync(file));+ });+ },+ // Vite's dev-server warmup (server.preTransformRequests, on by default)+ // crawls <script type="module"> URLs found in HTML entry points and+ // resolves/loads/transforms them in-process via environment.warmupRequest,+ // which never touches the connect middleware above (that middleware only+ // intercepts real browser HTTP requests, which it does successfully).+ // Two problems for the warmup path specifically:+ // 1. No resolveId/load hook -> falls through to Vite's fs resolver,+ // which can't find this virtual path on disk -> "Pre-transform+ // error ... Does the file exist?".+ // 2. Loading the real dist-lib bundle lets Vite's import-analysis+ // parse it, which chokes on the bundle's own internal+ // dynamic import("/risk-ack.js") of a /public asset (not+ // analyzable as an ES import per Vite's rules).+ // Neither affects real page loads (already served above), so for+ // warmup purposes only, resolve to a no-op stub that satisfies the+ // warmup without Vite ever parsing the real bundle.+ resolveId(id) {+ return /^\/agent-3d\/[^/]+\/agent-3d\.(js|umd\.cjs)$/.test(id) ? id : null;+ },+ load(id) {+ return /^\/agent-3d\/[^/]+\/agent-3d\.(js|umd\.cjs)$/.test(id) ? 'export {};' : null;+ },+ transformIndexHtml: {+ order: 'pre',+ handler(html) {+ // Only the real loader <script src="…"></script> is rewritten;+ // the copy-paste snippet strings keep the absolute URL embedders+ // need (their escaped `\n`/`<\/script>` don't match this pattern).+ return html.replace(+ /(<script\b[^>]*\bsrc=")https:\/\/three\.ws(\/agent-3d\/[^"]+\/agent-3d\.js"\s*)><\/script>/g,+ '$1$2></script>',+ );+ },+ },+ },+ // public/risk-ack.js is the canonical runtime module for the money-gate+ // acknowledgment: app code reaches it via the src/shared/risk-ack.js+ // wrapper's non-analyzable dynamic import('/risk-ack.js'). In production+ // the file is served as-is from the public root, but Vite's dev transform+ // middleware 500s a module request for a /public asset ("should not be+ // imported from source code") — so in dev every money gate silently+ // degraded to the confirm() fallback. Serve it raw ahead of the transform+ // middleware so dev matches production. Serve-only; no build effect.+ {+ name: 'dev-serve-risk-ack',+ apply: 'serve',+ configureServer(server) {+ const file = resolve(__dirname, 'public/risk-ack.js');+ server.middlewares.use((req, res, next) => {+ if ((req.url || '').split('?')[0] !== '/risk-ack.js') return next();+ res.setHeader('content-type', 'text/javascript; charset=utf-8');+ res.setHeader('cache-control', 'no-cache');+ return res.end(readFileSync(file));+ });+ },+ },+ {+ name: 'vercel-rewrites',+ configureServer(server) {+ const root = resolve(__dirname);+ const fileMap = {+ '/tour-builder': resolve(root, 'pages/tour-builder.html'),+ '/tour-builder/': resolve(root, 'pages/tour-builder.html'),+ '/agent-identities': resolve(root, 'pages/agent-identities.html'),+ '/agent-identities/': resolve(root, 'pages/agent-identities.html'),+ '/app': resolve(root, 'pages/app.html'),+ '/widget': resolve(root, 'pages/widget.html'),+ '/widget/': resolve(root, 'pages/widget.html'),+ '/login': resolve(root, 'public/login.html'),+ '/deploy': resolve(root, 'pages/app.html'),+ '/showcase': resolve(root, 'pages/app.html'),+ '/showcase/': resolve(root, 'pages/app.html'),+ '/agents': resolve(root, 'public/agents/index.html'),+ '/agents/': resolve(root, 'public/agents/index.html'),+ '/agents-live': resolve(root, 'pages/agents-live.html'),+ '/agents-live/': resolve(root, 'pages/agents-live.html'),+ '/start': resolve(root, 'pages/start.html'),+ '/start/': resolve(root, 'pages/start.html'),+ '/create': resolve(root, 'pages/create.html'),+ '/create-agent': resolve(root, 'pages/create-agent.html'),+ '/create/selfie': resolve(root, 'pages/create-selfie.html'),+ '/create/selfie/': resolve(root, 'pages/create-selfie.html'),+ '/create/prompt': resolve(root, 'pages/create-prompt.html'),+ '/create/prompt/': resolve(root, 'pages/create-prompt.html'),+ '/genesis': resolve(root, 'pages/genesis.html'),+ '/genesis/': resolve(root, 'pages/genesis.html'),+ '/create/video': resolve(root, 'pages/create/video.html'),+ '/create/video/': resolve(root, 'pages/create/video.html'),+ '/extension/privacy': resolve(root, 'pages/extension-privacy.html'),+ '/extension/privacy/': resolve(root, 'pages/extension-privacy.html'),+ '/extension/terms': resolve(root, 'pages/extension-terms.html'),+ '/extension/terms/': resolve(root, 'pages/extension-terms.html'),+ '/embed/walk': resolve(root, 'pages/embed-walk.html'),+ '/embed/walk/': resolve(root, 'pages/embed-walk.html'),+ '/paywall': resolve(root, 'public/paywall.html'),+ '/paywall/': resolve(root, 'public/paywall.html'),+ '/image-to-3d': resolve(root, 'pages/forge.html'),+ '/image-to-3d/': resolve(root, 'pages/forge.html'),+ '/forge-max': resolve(root, 'pages/forge.html'),+ '/forge-max/': resolve(root, 'pages/forge.html'),+ '/worlds': resolve(root, 'pages/worlds.html'),+ '/worlds/': resolve(root, 'pages/worlds.html'),+ '/create/studio': resolve(root, 'pages/avatar-studio.html'),+ '/create/studio/': resolve(root, 'pages/avatar-studio.html'),+ '/create-review': resolve(root, 'pages/create-review.html'),+ '/create-review/': resolve(root, 'pages/create-review.html'),+ '/import/rpm': resolve(root, 'pages/import-rpm.html'),+ '/import/rpm/': resolve(root, 'pages/import-rpm.html'),+ '/dashboard': resolve(root, 'pages/dashboard-next/index.html'),+ '/dashboard/': resolve(root, 'pages/dashboard-next/index.html'),+ '/dashboard-classic': null,+ '/dashboard-classic/': null,+ '/dashboard-next': resolve(root, 'pages/dashboard-next/index.html'),+ '/dashboard-next/': resolve(root, 'pages/dashboard-next/index.html'),+ '/dashboard/avatars': resolve(root, 'pages/dashboard-next/avatars.html'),+ '/dashboard/avatars/': resolve(root, 'pages/dashboard-next/avatars.html'),+ '/dashboard-next/avatars': resolve(root, 'pages/dashboard-next/avatars.html'),+ '/dashboard-next/avatars/': resolve(root, 'pages/dashboard-next/avatars.html'),+ '/dashboard/holders': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard/holders/': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard/copy': resolve(root, 'pages/dashboard-next/copy.html'),+ '/dashboard/copy/': resolve(root, 'pages/dashboard-next/copy.html'),+ '/dashboard-next/holders': resolve(root, 'pages/dashboard-next/holders.html'),+ '/dashboard-next/holders/': resolve(root, 'pages/dashboard-next/holders.html'),+ '/studio': resolve(root, 'public/studio/index.html'),+ '/studio/': resolve(root, 'public/studio/index.html'),+ '/widgets': resolve(root, 'public/widgets-gallery/index.html'),+ '/widgets/': resolve(root, 'public/widgets-gallery/index.html'),+ '/docs/widgets': resolve(root, 'public/docs-widgets.html'),+ '/cz': resolve(root, 'public/cz/index.html'),+ '/cz/': resolve(root, 'public/cz/index.html'),+ '/validation': resolve(root, 'public/validation/index.html'),+ '/validation/': resolve(root, 'public/validation/index.html'),+ '/reputation': resolve(root, 'public/reputation/index.html'),+ '/reputation/': resolve(root, 'public/reputation/index.html'),+ '/hydrate': resolve(root, 'public/hydrate/index.html'),+ '/hydrate/': resolve(root, 'public/hydrate/index.html'),+ '/artifact': resolve(root, 'public/artifact/index.html'),+ '/artifact/': resolve(root, 'public/artifact/index.html'),+ // BEGIN:DISCOVER_ROUTE+ '/my-agents': resolve(root, 'public/my-agents/index.html'),+ '/my-agents/': resolve(root, 'public/my-agents/index.html'),+ '/discover': resolve(root, 'public/discover/index.html'),+ '/discover/': resolve(root, 'public/discover/index.html'),+ '/gallery': resolve(root, 'public/gallery/index.html'),+ '/gallery/': resolve(root, 'public/gallery/index.html'),+ '/gallery-picker': resolve(root, 'pages/gallery-picker.html'),+ '/gallery-picker/': resolve(root, 'pages/gallery-picker.html'),+ '/status': resolve(root, 'pages/status.html'),+ '/status/': resolve(root, 'pages/status.html'),+ '/marketplace': resolve(root, 'pages/marketplace.html'),+ '/marketplace/': resolve(root, 'pages/marketplace.html'),+ '/marketplace-walk': resolve(root, 'pages/marketplace-walk.html'),+ '/marketplace-walk/': resolve(root, 'pages/marketplace-walk.html'),+ '/marketplace/tools': resolve(root, 'pages/marketplace.html'),+ '/pay': resolve(root, 'public/pay/index.html'),+ '/pay/': resolve(root, 'public/pay/index.html'),+ '/pay/calls': resolve(root, 'public/pay/calls/index.html'),+ '/pay/calls/': resolve(root, 'public/pay/calls/index.html'),+ '/x402': resolve(root, 'public/x402-stripe.html'),+ '/x402/': resolve(root, 'public/x402-stripe.html'),+ '/dashboard/x402': resolve(root, 'public/dashboard/x402.html'),+ '/explore': resolve(root, 'public/discover/index.html'),+ '/explore/': resolve(root, 'public/discover/index.html'),+ // END:DISCOVER_ROUTE+ '/tutorials': resolve(root, 'pages/tutorials.html'),+ '/tutorials/': resolve(root, 'pages/tutorials.html'),+ '/cookbook': resolve(root, 'pages/cookbook.html'),+ '/cookbook/': resolve(root, 'pages/cookbook.html'),+ '/cookbook/pipeline': resolve(root, 'pages/pipeline-studio.html'),+ '/cookbook/pipeline/': resolve(root, 'pages/pipeline-studio.html'),+ '/glossary': resolve(root, 'pages/glossary.html'),+ '/glossary/': resolve(root, 'pages/glossary.html'),+ '/go': resolve(root, 'pages/go.html'),+ '/go/': resolve(root, 'pages/go.html'),+ '/bounties': resolve(root, 'pages/bounties.html'),+ '/bounties/': resolve(root, 'pages/bounties.html'),+ '/launches': resolve(root, 'pages/launches.html'),+ '/launches/': resolve(root, 'pages/launches.html'),+ '/wardrobe': resolve(root, 'pages/wardrobe.html'),+ '/wardrobe/': resolve(root, 'pages/wardrobe.html'),+ '/minted': resolve(root, 'pages/minted.html'),+ '/minted/': resolve(root, 'pages/minted.html'),+ '/creations': resolve(root, 'pages/creations.html'),+ '/creations/': resolve(root, 'pages/creations.html'),+ '/pulse': resolve(root, 'pages/pulse.html'),+ '/pulse/': resolve(root, 'pages/pulse.html'),+ '/symphony': resolve(root, 'pages/symphony.html'),+ '/symphony/': resolve(root, 'pages/symphony.html'),+ '/x402-revenue': resolve(root, 'pages/x402-revenue.html'),+ '/x402-revenue/': resolve(root, 'pages/x402-revenue.html'),+ '/receipts': resolve(root, 'pages/receipts.html'),+ '/receipts/': resolve(root, 'pages/receipts.html'),+ '/fits': resolve(root, 'pages/fits.html'),+ '/fits/': resolve(root, 'pages/fits.html'),+ '/viability': resolve(root, 'pages/viability.html'),+ '/viability/': resolve(root, 'pages/viability.html'),+ '/deployments': resolve(root, 'pages/deployments.html'),+ '/deployments/': resolve(root, 'pages/deployments.html'),+ '/admin/launcher': resolve(root, 'pages/admin/launcher.html'),+ '/admin/launcher/': resolve(root, 'pages/admin/launcher.html'),+ '/admin/seeder': resolve(root, 'pages/admin/seeder.html'),+ '/admin/seeder/': resolve(root, 'pages/admin/seeder.html'),+ '/admin/economy': resolve(root, 'pages/admin/economy.html'),+ '/admin/economy/': resolve(root, 'pages/admin/economy.html'),+ '/admin/ring': resolve(root, 'pages/admin/ring.html'),+ '/admin/ring/': resolve(root, 'pages/admin/ring.html'),+ '/admin/ops': resolve(root, 'pages/admin/ops.html'),+ '/admin/ops/': resolve(root, 'pages/admin/ops.html'),+ '/launcher': resolve(root, 'pages/launcher.html'),+ '/launcher/': resolve(root, 'pages/launcher.html'),+ '/clash': resolve(root, 'pages/clash.html'),+ '/clash/': resolve(root, 'pages/clash.html'),+ '/watchlist': resolve(root, 'pages/watchlist.html'),+ '/watchlist/': resolve(root, 'pages/watchlist.html'),+ '/leaderboard': resolve(root, 'pages/leaderboard.html'),+ '/leaderboard/': resolve(root, 'pages/leaderboard.html'),+ '/proof': resolve(root, 'pages/proof.html'),+ '/proof/': resolve(root, 'pages/proof.html'),+ '/integrity': resolve(root, 'pages/integrity.html'),+ '/integrity/': resolve(root, 'pages/integrity.html'),+ '/labor-market': resolve(root, 'pages/labor-market.html'),+ '/labor-market/': resolve(root, 'pages/labor-market.html'),+ '/vaults': resolve(root, 'pages/vaults.html'),+ '/vaults/': resolve(root, 'pages/vaults.html'),+ '/alpha-copilot': resolve(root, 'pages/alpha-copilot.html'),+ '/alpha-copilot/': resolve(root, 'pages/alpha-copilot.html'),+ '/arena': resolve(root, 'pages/arena.html'),+ '/arena/': resolve(root, 'pages/arena.html'),+ '/mirror': resolve(root, 'pages/mirror.html'),+ '/mirror/': resolve(root, 'pages/mirror.html'),+ '/fact-check': resolve(root, 'pages/fact-check.html'),+ '/fact-check/': resolve(root, 'pages/fact-check.html'),+ '/strategies': resolve(root, 'pages/strategies.html'),+ '/strategies/': resolve(root, 'pages/strategies.html'),+ '/swarms': resolve(root, 'pages/swarms.html'),+ '/swarms/': resolve(root, 'pages/swarms.html'),+ '/ui-juice': resolve(root, 'pages/ui-juice.html'),+ '/ui-juice/': resolve(root, 'pages/ui-juice.html'),+ '/diorama': resolve(root, 'pages/diorama.html'),+ '/diorama/': resolve(root, 'pages/diorama.html'),+ '/trader': resolve(root, 'pages/trader.html'),+ '/trader/': resolve(root, 'pages/trader.html'),+ '/signals': resolve(root, 'pages/signals.html'),+ '/signals/': resolve(root, 'pages/signals.html'),+ '/trades': resolve(root, 'pages/trades.html'),+ '/trades/': resolve(root, 'pages/trades.html'),+ '/trading': resolve(root, 'pages/trading.html'),+ '/trading/': resolve(root, 'pages/trading.html'),+ '/exit-lab': resolve(root, 'pages/exit-lab.html'),+ '/exit-lab/': resolve(root, 'pages/exit-lab.html'),+ '/terminal': resolve(root, 'pages/terminal.html'),+ '/terminal/': resolve(root, 'pages/terminal.html'),+ '/claim-wallet': resolve(root, 'pages/claim-wallet.html'),+ '/claim-wallet/': resolve(root, 'pages/claim-wallet.html'),+ '/pump-live': resolve(root, 'pages/pump-live.html'),+ '/pump-live/': resolve(root, 'pages/pump-live.html'),+ '/radar': resolve(root, 'pages/radar.html'),+ '/radar/': resolve(root, 'pages/radar.html'),+ '/oracle': resolve(root, 'pages/oracle.html'),+ '/oracle/': resolve(root, 'pages/oracle.html'),+ '/oracle/docs': resolve(root, 'pages/oracle-docs.html'),+ '/oracle/docs/': resolve(root, 'pages/oracle-docs.html'),+ '/oracle/arm': resolve(root, 'pages/arm.html'),+ '/oracle/arm/': resolve(root, 'pages/arm.html'),+ '/arm': resolve(root, 'pages/arm.html'),+ '/arm/': resolve(root, 'pages/arm.html'),+ '/ca2x402': resolve(root, 'pages/ca2x402.html'),+ '/ca2x402/': resolve(root, 'pages/ca2x402.html'),+ '/activity': resolve(root, 'pages/activity.html'),+ '/activity/': resolve(root, 'pages/activity.html'),+ '/guards': resolve(root, 'pages/guards.html'),+ '/guards/': resolve(root, 'pages/guards.html'),+ '/pipeline': resolve(root, 'pages/pipeline.html'),+ '/pipeline/': resolve(root, 'pages/pipeline.html'),+ '/trending': resolve(root, 'pages/trending.html'),+ '/trending/': resolve(root, 'pages/trending.html'),+ '/coin-intel': resolve(root, 'pages/coin-intel.html'),+ '/coin-intel/': resolve(root, 'pages/coin-intel.html'),+ '/coins': resolve(root, 'pages/coins.html'),+ '/coins/': resolve(root, 'pages/coins.html'),+ '/markets': resolve(root, 'pages/markets.html'),+ '/markets/': resolve(root, 'pages/markets.html'),+ '/markets/robinhood': resolve(root, 'pages/markets-robinhood.html'),+ '/markets/robinhood/': resolve(root, 'pages/markets-robinhood.html'),+ '/markets/news': resolve(root, 'pages/markets-news.html'),+ '/markets/news/': resolve(root, 'pages/markets-news.html'),+ '/markets/digest': resolve(root, 'pages/news-digest.html'),+ '/markets/digest/': resolve(root, 'pages/news-digest.html'),+ '/markets/news/article': resolve(root, 'pages/news-article.html'),+ '/markets/news/article/': resolve(root, 'pages/news-article.html'),+ '/markets/archive': resolve(root, 'pages/news-archive.html'),+ '/markets/archive/': resolve(root, 'pages/news-archive.html'),+ '/fear-greed': resolve(root, 'pages/fear-greed.html'),+ '/fear-greed/': resolve(root, 'pages/fear-greed.html'),+ '/heatmap': resolve(root, 'pages/heatmap.html'),+ '/heatmap/': resolve(root, 'pages/heatmap.html'),+ '/gas': resolve(root, 'pages/gas.html'),+ '/gas/': resolve(root, 'pages/gas.html'),+ '/compare': resolve(root, 'pages/compare.html'),+ '/compare/': resolve(root, 'pages/compare.html'),+ '/screener': resolve(root, 'pages/screener.html'),+ '/screener/': resolve(root, 'pages/screener.html'),+ '/categories': resolve(root, 'pages/categories.html'),+ '/categories/': resolve(root, 'pages/categories.html'),+ '/exchanges': resolve(root, 'pages/exchanges.html'),+ '/exchanges/': resolve(root, 'pages/exchanges.html'),+ '/derivatives': resolve(root, 'pages/derivatives.html'),+ '/derivatives/': resolve(root, 'pages/derivatives.html'),+ '/converter': resolve(root, 'pages/converter.html'),+ '/converter/': resolve(root, 'pages/converter.html'),+ '/defi': resolve(root, 'pages/defi.html'),+ '/defi/': resolve(root, 'pages/defi.html'),+ '/chains': resolve(root, 'pages/chains.html'),+ '/chains/': resolve(root, 'pages/chains.html'),+ '/stablecoins': resolve(root, 'pages/stablecoins.html'),+ '/stablecoins/': resolve(root, 'pages/stablecoins.html'),+ '/yields': resolve(root, 'pages/yields.html'),+ '/yields/': resolve(root, 'pages/yields.html'),+ '/fees': resolve(root, 'pages/fees.html'),+ '/fees/': resolve(root, 'pages/fees.html'),+ '/sniper/experiments': resolve(root, 'pages/sniper-experiments.html'),+ '/sniper/experiments/': resolve(root, 'pages/sniper-experiments.html'),+ '/dex-volumes': resolve(root, 'pages/dex-volumes.html'),+ '/dex-volumes/': resolve(root, 'pages/dex-volumes.html'),+ '/hacks': resolve(root, 'pages/hacks.html'),+ '/hacks/': resolve(root, 'pages/hacks.html'),+ '/markets/trending': resolve(root, 'pages/markets-trending.html'),+ '/markets/trending/': resolve(root, 'pages/markets-trending.html'),+ '/bnb': resolve(root, 'pages/bnb.html'),+ '/bnb/': resolve(root, 'pages/bnb.html'),+ '/bnb-latency': resolve(root, 'pages/bnb-latency.html'),+ '/bnb-latency/': resolve(root, 'pages/bnb-latency.html'),+ '/vault': resolve(root, 'pages/vault.html'),+ '/vault/': resolve(root, 'pages/vault.html'),+ '/compose': resolve(root, 'pages/compose.html'),+ '/compose/': resolve(root, 'pages/compose.html'),+ '/create/next': resolve(root, 'pages/create-next.html'),+ '/create/next/': resolve(root, 'pages/create-next.html'),+ '/mint-success': resolve(root, 'pages/mint-success.html'),+ '/mint-success/': resolve(root, 'pages/mint-success.html'),+ '/pump-dashboard': resolve(root, 'pages/pump-dashboard.html'),+ '/pump-dashboard/': resolve(root, 'pages/pump-dashboard.html'),+ '/wallet': resolve(root, 'pages/wallet.html'),+ '/wallet/': resolve(root, 'pages/wallet.html'),+ '/autopilot': resolve(root, 'pages/autopilot.html'),+ '/autopilot/': resolve(root, 'pages/autopilot.html'),+ '/pump-visualizer': resolve(root, 'pages/pump-visualizer.html'),+ '/pump-visualizer/': resolve(root, 'pages/pump-visualizer.html'),+ '/three': resolve(root, 'pages/three.html'),+ '/three/': resolve(root, 'pages/three.html'),+ '/three-live': resolve(root, 'pages/three-live.html'),+ '/three-live/': resolve(root, 'pages/three-live.html'),+ '/three-token': resolve(root, 'pages/three-token.html'),+ '/three-token/': resolve(root, 'pages/three-token.html'),+ '/avatar-artifact': resolve(root, 'pages/avatar-artifact.html'),+ '/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),+ '/temporary': resolve(root, 'pages/temporary.html'),+ '/temporary/': resolve(root, 'pages/temporary.html'),+ '/irl': resolve(root, 'pages/irl.html'),+ '/irl/': resolve(root, 'pages/irl.html'),+ '/ar/studio': resolve(root, 'pages/ar-studio.html'),+ '/ar/studio/': resolve(root, 'pages/ar-studio.html'),+ '/daily': resolve(root, 'pages/daily.html'),+ '/daily/': resolve(root, 'pages/daily.html'),+ '/irl-privacy': resolve(root, 'pages/irl-privacy.html'),+ '/irl-privacy/': resolve(root, 'pages/irl-privacy.html'),+ '/world-lines': resolve(root, 'pages/world-lines.html'),+ '/world-lines/': resolve(root, 'pages/world-lines.html'),+ '/play': resolve(root, 'pages/play.html'),+ '/play/': resolve(root, 'pages/play.html'),+ '/play/agent-wallet': resolve(root, 'pages/play/agent-wallet.html'),+ '/play/agent-wallet/': resolve(root, 'pages/play/agent-wallet.html'),+ '/play/arena': resolve(root, 'pages/play/arena.html'),+ '/play/arena/': resolve(root, 'pages/play/arena.html'),+ '/smart-money': resolve(root, 'pages/smart-money.html'),+ '/smart-money/': resolve(root, 'pages/smart-money.html'),+ '/guardian': resolve(root, 'pages/guardian.html'),+ '/guardian/': resolve(root, 'pages/guardian.html'),+ '/walk-embed': resolve(root, 'pages/walk-embed.html'),+ '/walk-embed/': resolve(root, 'pages/walk-embed.html'),+ '/assistant': resolve(root, 'pages/assistant.html'),+ '/assistant/': resolve(root, 'pages/assistant.html'),+ '/assistant-frame': resolve(root, 'pages/assistant-frame.html'),+ '/assistant-frame/': resolve(root, 'pages/assistant-frame.html'),+ '/walk': resolve(root, 'pages/walk-landing.html'),+ '/walk/': resolve(root, 'pages/walk-landing.html'),+ '/walk/app': resolve(root, 'pages/walk-embed.html'),+ '/walk/app/': resolve(root, 'pages/walk-embed.html'),+ '/walk-leaderboard': resolve(root, 'pages/walk-leaderboard.html'),+ '/walk-leaderboard/': resolve(root, 'pages/walk-leaderboard.html'),+ '/walk-analytics': resolve(root, 'pages/walk-analytics.html'),+ '/walk-analytics/': resolve(root, 'pages/walk-analytics.html'),+ '/demo': resolve(root, 'pages/demo-economy.html'),+ '/demo/': resolve(root, 'pages/demo-economy.html'),+ '/live': resolve(root, 'pages/live.html'),+ '/live/': resolve(root, 'pages/live.html'),+ '/avatar-wallet-chat': resolve(root, 'pages/avatar-wallet-chat.html'),+ '/avatar-wallet-chat/': resolve(root, 'pages/avatar-wallet-chat.html'),+ '/agent-exchange': resolve(root, 'pages/agent-exchange.html'),+ '/agent-exchange/': resolve(root, 'pages/agent-exchange.html'),+ '/pose': resolve(root, 'pages/pose.html'),+ '/pose/': resolve(root, 'pages/pose.html'),+ '/pose-mini': resolve(root, 'pages/pose-mini.html'),+ '/pose-mini/': resolve(root, 'pages/pose-mini.html'),+ '/club': resolve(root, 'pages/club.html'),+ '/club/': resolve(root, 'pages/club.html'),+ '/theater': resolve(root, 'pages/theater.html'),+ '/theater/': resolve(root, 'pages/theater.html'),+ '/stage': resolve(root, 'pages/stage.html'),+ '/stage/': resolve(root, 'pages/stage.html'),+ '/dad': resolve(root, 'pages/dad.html'),+ '/dad/': resolve(root, 'pages/dad.html'),+ '/embodiment/embed': resolve(root, 'pages/embodiment/embed.html'),+ '/embodiment/embed/': resolve(root, 'pages/embodiment/embed.html'),+ '/agenc/embodied': resolve(root, 'pages/agenc/embodied.html'),+ '/agenc/embodied/': resolve(root, 'pages/agenc/embodied.html'),+ '/agenc/room': resolve(root, 'pages/agenc/room.html'),+ '/agenc/room/': resolve(root, 'pages/agenc/room.html'),+ '/aws-marketplace/welcome': resolve(root, 'pages/aws-marketplace/welcome.html'),+ '/aws-marketplace/welcome/': resolve(+ root,+ 'pages/aws-marketplace/welcome.html',+ ),+ '/aws-marketplace/error': resolve(root, 'pages/aws-marketplace/welcome.html'),+ '/aws-marketplace/error/': resolve(root, 'pages/aws-marketplace/welcome.html'),+ '/aws': resolve(root, 'pages/aws/index.html'),+ '/aws/': resolve(root, 'pages/aws/index.html'),+ '/openai': resolve(root, 'pages/openai/index.html'),+ '/openai/': resolve(root, 'pages/openai/index.html'),+ '/nvidia': resolve(root, 'pages/nvidia/index.html'),+ '/nvidia/': resolve(root, 'pages/nvidia/index.html'),+ '/press': resolve(root, 'pages/press/index.html'),+ '/press/': resolve(root, 'pages/press/index.html'),+'/support': resolve(root, 'pages/support.html'),+ '/support/': resolve(root, 'pages/support.html'),+ // Top-level galaxy/constellation are routed in vercel.json (prod) and+ // linked from the global nav — mirror them here so local dev matches prod+ // instead of 404ing.+ '/galaxy': resolve(root, 'pages/galaxy.html'),+ '/galaxy/': resolve(root, 'pages/galaxy.html'),+ '/examples': resolve(root, 'pages/examples.html'),+ '/examples/': resolve(root, 'pages/examples.html'),+ '/constellation': resolve(root, 'pages/constellation.html'),+ '/constellation/': resolve(root, 'pages/constellation.html'),+ '/voice': resolve(root, 'pages/voice.html'),+ '/voice/': resolve(root, 'pages/voice.html'),+ '/avatar-engines': resolve(root, 'pages/avatar-engines.html'),+ '/avatar-engines/': resolve(root, 'pages/avatar-engines.html'),+ '/splat': resolve(root, 'pages/splat.html'),+ '/splat/': resolve(root, 'pages/splat.html'),+ '/capture': resolve(root, 'pages/capture.html'),+ '/capture/': resolve(root, 'pages/capture.html'),+ '/motion-swap': resolve(root, 'pages/motion-swap.html'),+ '/motion-swap/': resolve(root, 'pages/motion-swap.html'),+ '/brain': resolve(root, 'pages/brain.html'),+ '/brain/': resolve(root, 'pages/brain.html'),+ '/lipsync': resolve(root, 'public/demos/lipsync-tts.html'),+ '/lipsync/': resolve(root, 'public/demos/lipsync-tts.html'),+ '/lipsync/mic': resolve(root, 'public/demos/lipsync-mic.html'),+ '/lipsync/mic/': resolve(root, 'public/demos/lipsync-mic.html'),+ '/launch-week': resolve(root, 'pages/three-ws-launch-week.html'),+ '/launch-week/': resolve(root, 'pages/three-ws-launch-week.html'),+ '/launchpad': resolve(root, 'pages/launchpad.html'),+ '/launchpad/': resolve(root, 'pages/launchpad.html'),+ '/launch': resolve(root, 'pages/launch.html'),+ '/launch/': resolve(root, 'pages/launch.html'),+ '/p': resolve(root, 'public/p/index.html'),+ '/p/': resolve(root, 'public/p/index.html'),+ '/eth-vanity': resolve(root, 'public/eth-vanity.html'),+ '/eth-vanity/': resolve(root, 'public/eth-vanity.html'),+ '/vanity/verify': resolve(root, 'public/vanity/verify/index.html'),+ '/vanity/verify/': resolve(root, 'public/vanity/verify/index.html'),+ '/vanity/gallery': resolve(root, 'public/vanity/gallery/index.html'),+ '/vanity/gallery/': resolve(root, 'public/vanity/gallery/index.html'),+ '/vanity/premium': resolve(root, 'public/vanity/premium/index.html'),+ '/vanity/premium/': resolve(root, 'public/vanity/premium/index.html'),+ '/vanity/bounties': resolve(root, 'public/vanity/bounties/index.html'),+ '/vanity/bounties/': resolve(root, 'public/vanity/bounties/index.html'),+ '/evm-wallet': resolve(root, 'public/evm-wallet.html'),+ '/evm-wallet/': resolve(root, 'public/evm-wallet.html'),+ '/strategy-lab': resolve(root, 'public/strategy-lab.html'),+ '/strategy-lab/': resolve(root, 'public/strategy-lab.html'),+ '/sitemap': resolve(root, 'public/sitemap/index.html'),+ '/sitemap/': resolve(root, 'public/sitemap/index.html'),+ // Guessable aliases — prod 308s these to /sitemap (vercel.json)+ '/pages': resolve(root, 'public/sitemap/index.html'),+ '/directory': resolve(root, 'public/sitemap/index.html'),+ '/everything': resolve(root, 'public/sitemap/index.html'),+ '/all-pages': resolve(root, 'public/sitemap/index.html'),+ '/blog': resolve(root, 'blog/index.html'),+ '/blog/': resolve(root, 'blog/index.html'),+ '/demos': resolve(root, 'public/demos/index.html'),+ '/demos/': resolve(root, 'public/demos/index.html'),+ '/demos/agents': resolve(root, 'public/demos/agents/index.html'),+ '/demos/agents/': resolve(root, 'public/demos/agents/index.html'),+ '/demo/avatar-os': resolve(root, 'public/demo/avatar-os/index.html'),+ '/demo/avatar-os/': resolve(root, 'public/demo/avatar-os/index.html'),+ '/demo/coin': resolve(root, 'public/demo/coin/index.html'),+ '/demo/coin/': resolve(root, 'public/demo/coin/index.html'),+ '/': resolve(root, 'pages/home.html'),+ '/home': resolve(root, 'pages/home.html'),+ '/what-is': resolve(root, 'pages/what-is.html'),+ '/what-is/': resolve(root, 'pages/what-is.html'),+ '/pitch': resolve(root, 'pages/pitch.html'),+ '/pitch/': resolve(root, 'pages/pitch.html'),+ '/timeline': resolve(root, 'pages/timeline.html'),+ '/timeline/': resolve(root, 'pages/timeline.html'),+ '/tracker': resolve(root, 'pages/tracker.html'),+ '/tracker/': resolve(root, 'pages/tracker.html'),+ '/features': resolve(root, 'pages/features.html'),+ '/features/': resolve(root, 'pages/features.html'),+ '/docs': resolve(root, 'docs/index.html'),+ '/docs/': resolve(root, 'docs/index.html'),+ '/docs/world': resolve(root, 'pages/docs-world.html'),+ '/docs/world/': resolve(root, 'pages/docs-world.html'),+ '/bazaar': resolve(root, 'public/bazaar.html'),+ '/bazaar/': resolve(root, 'public/bazaar.html'),+ '/labs': resolve(root, 'pages/labs.html'),+ '/labs/': resolve(root, 'pages/labs.html'),+ '/quality-bench': resolve(root, 'pages/quality-bench.html'),+ '/quality-bench/': resolve(root, 'pages/quality-bench.html'),+ '/inspect': resolve(root, 'pages/inspect.html'),+ '/inspect/': resolve(root, 'pages/inspect.html'),+ '/search': resolve(root, 'pages/search.html'),+ '/search/': resolve(root, 'pages/search.html'),+ '/rankings': resolve(root, 'pages/rankings.html'),+ '/rankings/': resolve(root, 'pages/rankings.html'),+ '/daily-match': resolve(root, 'pages/daily-match.html'),+ '/daily-match/': resolve(root, 'pages/daily-match.html'),+ '/forever': resolve(root, 'public/forever.html'),+ '/forever/': resolve(root, 'public/forever.html'),+ '/arbitrage': resolve(root, 'public/arbitrage.html'),+ '/arbitrage/': resolve(root, 'public/arbitrage.html'),+ '/providers': resolve(root, 'public/providers.html'),+ '/providers/': resolve(root, 'public/providers.html'),+ };+ // Routes that resolve to public/<dir>/index.html — these need a+ // trailing slash so relative imports (./foo.js) inside the HTML+ // resolve to /<dir>/foo.js rather than /foo.js at the root.+ const dirRoutes = new Set([+ '/agents',+ '/dashboard',+ '/studio',+ '/widgets',+ '/cz',+ '/validation',+ '/reputation',+ '/hydrate',+ '/my-agents',+ '/discover',+ '/gallery',+ '/docs',+ '/demo/avatar-os',+ '/demo/coin',+ ]);+ server.middlewares.use(async (req, res, next) => {+ const url = req.url || '/';+ // Don't intercept Vite's internal html-proxy / module requests —+ // it needs to serve the inline-script content for our HTML.+ if (+ url.includes('html-proxy') ||+ url.includes('@id/') ||+ url.includes('@vite/')+ )+ return next();+ const path = url.split('?')[0];+ let filePath;+ // /api/* is handled by the http proxy in server.proxy above —+ // the middleware must not intercept those requests.+ if (dirRoutes.has(path)) {+ res.statusCode = 301;+ res.setHeader('Location', path + '/' + (req.url.slice(path.length) || ''));+ return res.end();+ }+ // Legacy homepage variants (home-v2/v3/v4, classic, next) were+ // reconciled into the single canonical pages/home.html. One front+ // door: 301 every old variant URL to /. Mirrors vercel.json.+ if (/^\/home-(v2|v3|v4|classic|next)\/?$/.test(path)) {+ res.statusCode = 301;+ res.setHeader('Location', '/');+ return res.end();+ }+ // /explore is an alias for /discover — share the same JS bundle+ if (path === '/explore' || path === '/explore/') {+ res.statusCode = 301;+ res.setHeader('Location', '/discover/');+ return res.end();+ }+ // /discover/avatar/:id → canonical /avatars/:id (avatar studio page)+ const discoverAvatarM = path.match(/^\/discover\/avatar\/([^/]+)\/?$/);+ if (discoverAvatarM) {+ res.statusCode = 301;+ res.setHeader('Location', `/avatars/${discoverAvatarM[1]}`);+ return res.end();+ }+ // /widget-studio was a legacy standalone page; /studio is canonical+ if (path === '/widget-studio' || path === '/widget-studio/') {+ res.statusCode = 301;+ res.setHeader('Location', '/studio');+ return res.end();+ }+ // Creation-surface consolidation (prompts/roadmap/creation-consolidation.md+ // Phase 2). Each of these mirrors a vercel.json rule so dev matches prod.+ //+ // C1: /scan merged into /create/selfie — the selfie flow owns both the+ // live-camera and the upload input, so the scanner URL is retired.+ if (path === '/scan' || path === '/scan/') {+ res.statusCode = 301;+ res.setHeader('Location', '/create/selfie');+ return res.end();+ }+ // C2: /agent/new → /create-agent. A request carrying the avatar handoff+ // params is REWRITTEN (not redirected) so the wizard still receives+ // them; src/create-agent.js consumes them and canonicalises the URL.+ if (path === '/agent/new' || path === '/agent/new/') {+ const q = url.slice(path.length);+ if (/[?&]avatar_(id|glb)=/.test(q)) {+ filePath = resolve(root, 'pages/create-agent.html');+ } else {+ res.statusCode = 301;+ res.setHeader('Location', '/create-agent');+ return res.end();+ }+ }+ // C4: the standalone /avatar-edit landing is retired — the editor is+ // only reachable in-flow at /avatars/:id/edit (or the legacy ?id= form).+ if ((path === '/avatar-edit' || path === '/avatar-edit/') && !/[?&]id=/.test(url)) {+ res.statusCode = 301;+ res.setHeader('Location', '/dashboard/avatars');+ return res.end();+ }+ // Bare /agent 301s to the agents directory in prod (vercel.json);+ // the standalone agent token page lives at /agent/index.html. Mirror+ // the redirect so dev matches prod instead of 404ing.+ if (path === '/agent' || path === '/agent/') {+ res.statusCode = 301;+ res.setHeader('Location', '/agents');+ return res.end();+ }+ // /coin is the legacy URL for /demo/coin (the lottery+reflection+ // demo). Kept as a 301 so old links and shares keep working.+ if (path === '/coin' || path === '/coin/') {+ res.statusCode = 301;+ res.setHeader('Location', '/demo/coin');+ return res.end();+ }+ // Chat sub-app is proxied to its own Vite dev server at :5174+ // which serves under /chat/. Redirect /chat → /chat/ so the+ // proxy can forward the trailing-slash form upstream.+ if (path === '/chat') {+ res.statusCode = 301;+ res.setHeader('Location', '/chat/');+ return res.end();+ }+ // /dashboard-classic/* → canonical /dashboard/* (mirrors vercel.json 301s)+ if (path === '/dashboard-classic' || path.startsWith('/dashboard-classic/')) {+ const classicSlugMap = {+ 'portfolio/asset': '/dashboard/portfolio',+ portfolio: '/dashboard/portfolio',+ wallets: '/dashboard/account',+ sessions: '/dashboard/settings',+ actions: '/dashboard/account',+ 'embed-policy': '/dashboard/api',+ memory: '/dashboard/agents',+ strategy: '/dashboard/library',+ voice: '/dashboard/settings',+ sns: '/dashboard/account',+ delegation: '/dashboard/account',+ tokens: '/dashboard/tokens',+ 'agent-pumpfun': '/dashboard/tokens',+ x402: '/dashboard/monetize',+ storage: '/dashboard/settings',+ usage: '/dashboard/analytics',+ };+ const slug = path.replace(/^\/dashboard-classic\/?/, '').replace(/\/$/, '');+ const dest = classicSlugMap[slug] || '/dashboard/';+ res.statusCode = 301;+ res.setHeader('Location', dest);+ return res.end();+ }+ if (!filePath) filePath = fileMap[path];+ // /blog/<slug> → resolves to blog/<slug>.html on disk+ if (!filePath && /^\/blog\/[a-z0-9-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/blog\//, '').replace(/\/$/, '');+ filePath = resolve(root, `blog/${slug}.html`);+ }+ // /news and /news/<slug> → public/news/(index|<slug>).html on disk.+ // Mirrors the prod vercel.json rewrite so the homepage press-strip+ // links resolve in dev instead of 404ing (slug allows underscores+ // and the numeric post ids used by some entries).+ else if (!filePath && /^\/news\/?$/.test(path)) {+ filePath = resolve(root, 'public/news/index.html');+ } else if (!filePath && /^\/news\/[a-z0-9_-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/news\//, '').replace(/\/$/, '');+ const candidate = resolve(root, `public/news/${slug}.html`);+ if (existsSync(candidate)) filePath = candidate;+ }+ // /demos/<slug> or /demos/<slug>.html → resolves to public/demos/<slug>.html on disk+ else if (!filePath && /^\/demos\/[a-z0-9-]+(\.html)?\/?$/.test(path)) {+ const slug = path+ .replace(/^\/demos\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');+ filePath = resolve(root, `public/demos/${slug}.html`);+ }+ // /demos/agents/<slug>(.html)? → public/demos/agents/<slug>.html.+ // Goes through transformIndexHtml so the inline `'three'` imports+ // inside each demo's <script type="module"> get bundled.+ else if (!filePath && /^\/demos\/agents\/[a-z0-9-]+(\.html)?\/?$/.test(path)) {+ const slug = path+ .replace(/^\/demos\/agents\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');+ filePath = resolve(root, `public/demos/agents/${slug}.html`);+ }+ // /demo/coin/<base58 mint> → demo/coin index hydrates from the+ // mint address in the URL path. Mirrors vercel.json.+ else if (+ !filePath &&+ /^\/demo\/coin\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)+ ) {+ filePath = resolve(root, 'public/demo/coin/index.html');+ }+ // /tutorials/<slug> → dedicated tutorial viewer template+ else if (!filePath && /^\/tutorials\/[a-z0-9-]+\/?$/.test(path))+ filePath = resolve(root, 'pages/tutorial.html');+ // /cookbook/self-correcting-3d → the committed notebook export, which is a+ // static nbconvert page, NOT a markdown recipe. It has to be matched before+ // the generic slug rule below or the viewer would shadow it. Mirrors vercel.json.+ else if (!filePath && /^\/cookbook\/self-correcting-3d\/?$/.test(path))+ filePath = resolve(root, 'public/cookbook/self-correcting-3d/index.html');+ // /cookbook/pipeline → Pipeline Studio, an app page rather than a recipe.+ // Same reason as above: it must beat the generic slug rule. Mirrors vercel.json.+ else if (!filePath && /^\/cookbook\/pipeline\/?$/.test(path))+ filePath = resolve(root, 'pages/pipeline-studio.html');+ // /cookbook/<slug> → recipe viewer, renders /docs/cookbook/<slug>.md+ else if (!filePath && /^\/cookbook\/[a-z0-9-]+\/?$/.test(path))+ filePath = resolve(root, 'pages/recipe.html');+ // /p/<slug> → public Launchpad Studio renderer (hydrates from /api/launchpad/get)+ else if (!filePath && /^\/p\/[a-z0-9-]+\/?$/.test(path))+ filePath = resolve(root, 'public/p/index.html');+ // /pay/c/<slug> → hosted x402 checkout page (hydrates from /api/x402-skus?slug=)+ else if (!filePath && /^\/pay\/c\/[a-z0-9][a-z0-9-]+\/?$/.test(path))+ filePath = resolve(root, 'public/pay/c/index.html');+ // /dashboard/x402 → x402 SKU dashboard (already in fileMap)+ else if (!filePath && /^\/marketplace\/agents\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'pages/marketplace.html');+ else if (!filePath && /^\/marketplace\/avatars\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'pages/marketplace.html');+ else if (+ !filePath &&+ /^\/marketplace\/(tools|skills|animations|onchain)\/[^/]+\/?$/.test(path)+ )+ filePath = resolve(root, 'pages/marketplace.html');+ // /agents/:id → rich detail page (UUID expected, validated client-side)+ else if (!filePath && /^\/bounty\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'pages/bounty.html');+ // /signals/<slug> → signal feed detail page (hydrates from /api/signals/feed)+ else if (!filePath && /^\/signals\/[^/.]+\/?$/.test(path))+ filePath = resolve(root, 'pages/signal-detail.html');+ // /ledger and /ledger/:agentId → the Reasoning Ledger surface+ else if (!filePath && /^\/ledger(\/[^/.]+)?\/?$/.test(path))+ filePath = resolve(root, 'pages/reasoning-ledger.html');+ // `[^/.]+` (no dot) mirrors vercel.json's `/agents/([^/.]+)` so+ // static assets like /agents/boot.js fall through to public/+ // instead of being served the agent-detail HTML shell.+ // /agent/:id/wallet and /agents/:id/wallet → Agent Wallet hub+ // (must precede the /agent/:id and /agents/:id catch-alls below).+ else if (!filePath && /^\/agents?\/[^/.]+\/wallet\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-wallet.html');+ // /agents/:id/classic → the preserved pre-redesign profile layout+ else if (!filePath && /^\/agents?\/[^/.]+\/classic\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-detail-classic.html');+ else if (!filePath && /^\/agents\/[^/.]+\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-detail.html');+ else if (!filePath && /^\/agent\/[^/]+\/mind\/?$/.test(path))+ filePath = resolve(root, 'pages/agent-mind.html');+ else if (!filePath && /^\/agent\/[^/]+\/edit$/.test(path))+ filePath = resolve(root, 'pages/agent-edit.html');+ else if (!filePath && /^\/agent\/[^/]+\/embed$/.test(path))+ filePath = resolve(root, 'pages/agent-embed.html');+ else if (!filePath && /^\/agent\/[^/]+$/.test(path))+ filePath = resolve(root, 'pages/agent-detail.html');+ else if (!filePath && /^\/character\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'public/character.html');+ else if (!filePath && (path === '/characters' || path === '/characters/'))+ filePath = resolve(root, 'public/characters.html');+ // /a/<chainId>/<agentId>/edit → chain-edit page+ else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/edit\/?$/.test(path))+ filePath = resolve(root, 'pages/a-edit.html');+ // /a/<chainId>/<agentId>/embed or /a/<chainId>/<registry>/<agentId>/embed → iframe viewer+ else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/embed\/?$/.test(path))+ filePath = resolve(root, 'pages/a-embed.html');+ // /embed/avatar → portable avatar embed (?id= / ?model=)+ // /embed/avatar/:handle → portable avatar embed by handle+ else if (!filePath && /^\/embed\/avatar(\/[a-z0-9_-]{3,30})?\/?$/i.test(path))+ filePath = resolve(root, 'pages/avatar-embed.html');+ // /avatars/:id/ar → dedicated AR experience (mirrors vercel.json rewrite)+ else if (!filePath && /^\/avatars\/[^/.]+\/ar\/?$/.test(path))+ filePath = resolve(root, 'pages/ar.html');+ // /avatars/:id/edit → avatar customize page (mirrors vercel.json rewrite)+ else if (!filePath && /^\/avatars\/[^/.]+\/edit\/?$/.test(path))+ filePath = resolve(root, 'pages/avatar-edit.html');+ // /avatars/:id → avatar studio page (mirrors vercel.json rewrite)+ else if (!filePath && /^\/avatars\/[^/.]+\/?$/.test(path))+ filePath = resolve(root, 'pages/avatar-page.html');+ // /changelog → public changelog page (mirrors vercel.json rewrite)+ else if (!filePath && /^\/events\/[a-z0-9][a-z0-9-]*\/?$/.test(path)) {+ const slug = path.replace(/^\/events\//, '').replace(/\/$/, '');+ const candidate = resolve(root, `pages/events/${slug}.html`);+ if (existsSync(candidate)) filePath = candidate;+ }+ // /changelog → public changelog page (mirrors vercel.json rewrite)+ else if (!filePath && /^\/changelog\/?$/.test(path))+ filePath = resolve(root, 'public/changelog/index.html');+ // /town → communities (alias; mirrors vercel.json rewrite)+ else if (!filePath && /^\/town\/?$/.test(path))+ filePath = resolve(root, 'pages/communities.html');+ // /communities/:mint → coin profile deep link+ else if (+ !filePath &&+ /^\/communities\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)+ )+ filePath = resolve(root, 'pages/communities.html');+ // /launches/:mint → rich coin detail page+ else if (+ !filePath &&+ /^\/launches\/[1-9A-HJ-NP-Za-km-z]{32,44}\/?$/.test(path)+ )+ filePath = resolve(root, 'pages/launch-detail.html');+ // /coin/:id → global coin detail page (CoinGecko slug or Solana mint)+ else if (+ !filePath &&+ /^\/coin\/[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}\/?$/.test(path)+ )+ filePath = resolve(root, 'pages/coin.html');+ // /markets/robinhood/stock/:symbol → Robinhood Chain Stock Token detail+ else if (!filePath && /^\/markets\/robinhood\/stock\/[A-Za-z0-9.-]{1,10}\/?$/.test(path))+ filePath = resolve(root, 'pages/robinhood-stock.html');+ // /markets/robinhood/coin/:address → Robinhood Chain coin detail+ else if (!filePath && /^\/markets\/robinhood\/coin\/0x[0-9a-fA-F]{40}\/?$/.test(path))+ filePath = resolve(root, 'pages/robinhood-coin.html');+ // /drop/:id → sealed wallet gift claim page (24 lowercase hex chars,+ // matching api/vanity/drops.js's id format)+ else if (!filePath && /^\/drop\/[0-9a-f]{24}\/?$/.test(path))+ filePath = resolve(root, 'pages/drop.html');+ // /exchange/:id → exchange detail page (CoinGecko exchange slug)+ else if (!filePath && /^\/exchange\/[a-z0-9_-]{1,60}\/?$/i.test(path))+ filePath = resolve(root, 'pages/exchange.html');+ // /category/:id → crypto category detail page+ else if (!filePath && /^\/category\/[a-z0-9-]{1,80}\/?$/.test(path))+ filePath = resolve(root, 'pages/category.html');+ // /protocol/:slug → DeFi protocol detail page+ else if (!filePath && /^\/protocol\/[a-z0-9.-]{1,80}\/?$/i.test(path))+ filePath = resolve(root, 'pages/protocol.html');+ // /chain/:name → chain TVL detail page+ else if (!filePath && /^\/chain\/[A-Za-z0-9 ._%-]{1,40}\/?$/.test(path))+ filePath = resolve(root, 'pages/chain.html');+ // /stablecoin/:id → stablecoin detail page+ else if (!filePath && /^\/stablecoin\/[0-9]{1,6}\/?$/.test(path))+ filePath = resolve(root, 'pages/stablecoin.html');+ // /@<handle> → public live profile page+ else if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))+ filePath = resolve(root, 'pages/handle.html');+ else if (+ !filePath &&+ /^\/u\/(?:0x[0-9a-fA-F]{40}|[a-z0-9_-]{3,30})\/?$/i.test(path)+ )+ filePath = resolve(root, 'pages/profile.html');+ // /a/<chainId>/<agentId> or /a/<chainId>/<registry>/<agentId>+ else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/?$/.test(path))+ filePath = resolve(root, 'pages/app.html');+ // /pay/calls/<base58 tx sig> → permalink for a paid x402 call+ else if (!filePath && /^\/pay\/calls\/[1-9A-HJ-NP-Za-km-z]+\/?$/.test(path))+ filePath = resolve(root, 'public/pay/calls/index.html');+ // /dashboard/<tab> and /dashboard/edit/<id> → pages/dashboard-next/index.html (new SPA)+ else if (+ !filePath &&+ // `billing` left out on purpose: /dashboard/billing is a real+ // dashboard-next page (pages/dashboard-next/billing.html), not a+ // legacy SPA tab.+ /^\/dashboard\/(?:agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|revenue|withdrawals|earnings|account)\/?$/.test(+ path,+ )+ )+ filePath = resolve(root, 'pages/dashboard-next/index.html');+ else if (!filePath && /^\/dashboard\/edit\/[^/]+\/?$/.test(path))+ filePath = resolve(root, 'pages/dashboard-next/index.html');+ // /dashboard-next/<slug> → pages/dashboard-next/<slug>.html+ // Mirrors vercel.json so the dev server resolves the sub-pages+ // landed by parallel agents without each one having to touch+ // this rewrite map.+ else if (!filePath && /^\/dashboard-next\/[a-z0-9][a-z0-9-]*\/?$/.test(path)) {+ const slug = path.replace(/^\/dashboard-next\//, '').replace(/\/$/, '');+ const candidate = resolve(root, `pages/dashboard-next/${slug}.html`);+ if (existsSync(candidate)) filePath = candidate;+ }+ // /dashboard/<page> → pages/dashboard-next/<page>.html+ else if (!filePath && /^\/dashboard\/[a-z0-9][a-z0-9-]*\/?$/.test(path)) {+ const slug = path.replace(/^\/dashboard\//, '').replace(/\/$/, '');+ const candidate = resolve(root, `pages/dashboard-next/${slug}.html`);+ if (existsSync(candidate)) filePath = candidate;+ }+ // /features/<slug> → pages/features/<slug>.html+ // Mirrors vercel.json so per-feature SEO landing pages work in dev.+ else if (!filePath && /^\/features\/[a-z0-9][a-z0-9-]*\/?$/.test(path)) {+ const slug = path.replace(/^\/features\//, '').replace(/\/$/, '');+ const candidate = resolve(root, `pages/features/${slug}.html`);+ if (existsSync(candidate)) filePath = candidate;+ }+ // Generic fallback: /<slug> or /<slug>.html → pages/<slug>.html+ // Catches the long tail of bundled root-level pages (community,+ // playground, embed, profile, …) without bloating fileMap.+ // /docs/<topic> -> mirror vercel.json: the walk sub-site is its own built+ // dir; every other topic is the docs SPA (docs/index.html), which client-+ // routes and fetches public/docs/<topic>.md at runtime.+ else if (!filePath && /^\/docs\/walk(\/[a-z0-9-]+)?\/?$/.test(path)) {+ const sub = path.replace(/^\/docs\/walk\/?/, '').replace(/\/$/, '');+ const cand = sub+ ? resolve(root, `public/docs/walk/${sub}.html`)+ : resolve(root, 'public/docs/walk/index.html');+ if (existsSync(cand)) filePath = cand;+ } else if (!filePath && /^\/docs\/[a-z0-9][a-z0-9-]*\/?$/.test(path))+ filePath = resolve(root, 'docs/index.html');+ // /legal/<slug> -> public/legal/<slug>.html (privacy, tos)+ else if (!filePath && /^\/legal\/[a-z0-9-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/legal\//, '').replace(/\/$/, '');+ const cand = resolve(root, `public/legal/${slug}.html`);+ if (existsSync(cand)) filePath = cand;+ }+ // /x402/<slug> -> public/x402/<slug>.html (e.g. /x402/studio)+ else if (!filePath && /^\/x402\/[a-z0-9-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/x402\//, '').replace(/\/$/, '');+ const cand = resolve(root, `public/x402/${slug}.html`);+ if (existsSync(cand)) filePath = cand;+ }+ // /threews/<slug> -> pages/threews-<slug>.html (e.g. /threews/claim)+ else if (!filePath && /^\/threews\/[a-z0-9-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/threews\//, '').replace(/\/$/, '');+ const cand = resolve(root, `pages/threews-${slug}.html`);+ if (existsSync(cand)) filePath = cand;+ }+ // /marketplace/analytics -> pages/marketplace-analytics.html+ else if (!filePath && path.replace(/\/$/, '') === '/marketplace/analytics')+ filePath = resolve(root, 'pages/marketplace-analytics.html');+ // /play/<slug> -> pages/play/<slug>.html (e.g. /play/ufo)+ else if (!filePath && /^\/play\/[a-z0-9-]+\/?$/.test(path)) {+ const slug = path.replace(/^\/play\//, '').replace(/\/$/, '');+ const cand = resolve(root, `pages/play/${slug}.html`);+ if (existsSync(cand)) filePath = cand;+ }+ // Generic fallback: /<slug> or /<slug>.html resolves to the page's HTML on+ // disk -- pages/ first, then public/ (file, then dir index). Catches the long+ // tail of root-level pages (community, playground, pumpfun, lookup, register,+ // settings, ...) without bloating fileMap.+ else if (!filePath && /^\/[a-z0-9][a-z0-9-]*(\.html)?\/?$/.test(path)) {+ const slug = path+ .replace(/^\//, '')+ .replace(/\.html$/, '')+ .replace(/\/$/, '');+ for (const rel of [+ `pages/${slug}.html`,+ `public/${slug}.html`,+ `public/${slug}/index.html`,+ ]) {+ const candidate = resolve(root, rel);+ if (existsSync(candidate)) {+ filePath = candidate;+ break;+ }+ }+ }+ // /footer-bot.js — serve the Vite-processed src/footer-bot.js at a+ // stable URL in dev so footer.js can load it without knowing the hash.+ if (path === '/footer-bot.js') {+ req.url = '/src/footer-bot.js';+ return next();+ }+ // /walk-companion.js — same trick for nav.js's Walk Companion module+ // (built to a stable, unhashed name in prod; served from src in dev).+ if (path === '/walk-companion.js') {+ req.url = '/src/walk-companion.js';+ return next();+ }+ // /agent-bus.js — the Living-Agents nervous system at a stable URL so+ // nav.js can load it on any page for the ?agentbus=1 debug overlay.+ if (path === '/agent-bus.js') {+ req.url = '/src/agents/agent-bus.js';+ return next();+ }+ // /walk-playground.js — stable URL so any page (not just the nav+ // companion) can launch the full-page walk playground on demand.+ if (path === '/walk-playground.js') {+ req.url = '/src/walk-playground.js';+ return next();+ }+ // /feature-tour.js — nav.js's Guided Tour module, served from src+ // in dev at the stable, unhashed name it ships under in prod.+ if (path === '/feature-tour.js') {+ req.url = '/src/feature-tour.js';+ return next();+ }+ // /notifications.js — nav.js loads this module for the per-user inbox.+ if (path === '/notifications.js') {+ req.url = '/src/notifications.js';+ return next();+ }+ // /nav-tier-badge.js — nav.js loads this module for the $THREE+ // holder tier chip (built to a stable, unhashed name in prod).+ if (path === '/nav-tier-badge.js') {+ req.url = '/src/nav-tier-badge.js';+ return next();+ }+ // /i18n.js — runtime locale swap + <lang-switcher>, served from+ // src in dev at the stable, unhashed name it ships under in prod so+ // any page can localize itself with one script tag.+ if (path === '/i18n.js') {+ req.url = '/src/i18n.js';+ return next();+ }+ // Avatar Studio (rebranded Character Studio fork) — serve the+ // production build out of character-studio/build/ at /avatar-studio/*+ // so the demo iframe works in dev. Run `npm run build --prefix+ // character-studio` first to populate the build dir.+ if (path === '/avatar-studio' || path === '/avatar-studio/') {+ const indexPath = resolve(root, 'character-studio/build/index.html');+ if (existsSync(indexPath)) {+ res.setHeader('Content-Type', 'text/html; charset=utf-8');+ return createReadStream(indexPath).pipe(res);+ }+ res.statusCode = 503;+ return res.end(+ 'Avatar Studio build missing — run `npm run build --prefix character-studio`',+ );+ }+ if (path.startsWith('/avatar-studio/')) {+ const ext = path.split('.').pop().toLowerCase();+ const mimes = {+ js: 'application/javascript',+ map: 'application/json',+ css: 'text/css',+ json: 'application/json',+ html: 'text/html',+ ogg: 'audio/ogg',+ mp3: 'audio/mpeg',+ wav: 'audio/wav',+ glb: 'model/gltf-binary',+ gltf: 'model/gltf+json',+ vrm: 'application/octet-stream',+ obj: 'text/plain',+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ svg: 'image/svg+xml',+ ico: 'image/x-icon',+ woff2: 'font/woff2',+ woff: 'font/woff',+ ttf: 'font/ttf',+ otf: 'font/otf',+ wasm: 'application/wasm',+ };+ const rel = path.slice('/avatar-studio/'.length);+ const fileDisk = resolve(root, 'character-studio/build', rel);+ if (existsSync(fileDisk) && statSync(fileDisk).isFile()) {+ res.setHeader('Content-Type', mimes[ext] || 'application/octet-stream');+ return createReadStream(fileDisk).pipe(res);+ }+ return next();+ }+ if (!filePath) return next();+ try {+ const html = readFileSync(filePath, 'utf8');+ // Always use the actual on-disk file path as the URL for+ // transformIndexHtml so Vite can resolve html-proxy requests+ // for inline <script type="module"> back to the correct file,+ // regardless of which dynamic URL the page was served from.+ const rel = filePath.slice(root.length + 1).replace(/\\/g, '/');+ const fileUrl = '/' + rel;+ const transformed = await server.transformIndexHtml(fileUrl, html);+ res.setHeader('Content-Type', 'text/html; charset=utf-8');+ res.end(transformed);+ } catch {+ next();+ }+ });+ },+ },+ {+ name: 'posthog-analytics',+ transformIndexHtml: {+ order: 'pre',+ handler(_html, ctx) {+ const EMBED_FILES = new Set([+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',+ ]);+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();+ if (EMBED_FILES.has(filename)) return [];+ const SNIPPET = `!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",p.onerror=function(){window.__posthog_blocked=!0},(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias set_config reset opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing get_distinct_id get_session_id get_session_replay_url register register_once unregister on onFeatureFlags reloadFeatureFlags getFeatureFlag getFeatureFlagPayload isFeatureEnabled addExceptionStep captureException".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('phc_kvi8nrXqrNkLNy2NhaiwkbGyj77XpSJo54P5k2ZHYo9n',{api_host:'/ingest',ui_host:'https://us.posthog.com',defaults:'2026-01-30',person_profiles:'identified_only'})`;+ return [{ tag: 'script', children: SNIPPET, injectTo: 'head' }];+ },+ },+ },+ {+ // First-party client-side error reporting on every page (embeds+ // included — errors inside third-party iframe placements are exactly+ // the ones nobody's DevTools ever sees). The inline bootstrap installs+ // window error/unhandledrejection listeners synchronously so failures+ // during page load are captured, queuing raw events into+ // window.__threeErrQ; the deferred /error-reporter.js (public/) drains+ // the queue, dedupes/batches, and beacons to /api/client-errors.+ name: 'client-error-reporter',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ const BOOTSTRAP =+ "window.__threeErrQ=window.__threeErrQ||[];window.__threeErrCap=1;addEventListener('error',function(e){window.__threeErrQ.push(e)},!0);addEventListener('unhandledrejection',function(e){window.__threeErrQ.push(e)});";+ return [+ { tag: 'script', children: BOOTSTRAP, injectTo: 'head' },+ { tag: 'script', attrs: { defer: true, src: '/error-reporter.js' }, injectTo: 'head' },+ ];+ },+ },+ },+ {+ // Feature Tour boot gate — injected on every Vite-processed page so the+ // guided tour can re-hydrate after it navigates (location.assign) to ANY+ // route, not just the ~79 pages that load public/nav.js. The bespoke+ // full-screen pages the tour visits (/create/selfie, /scan, /club, …)+ // deliberately skip nav.js; without this they had no way to re-inject the+ // engine, so the tour died the moment it stepped onto one of them.+ //+ // This is the SINGLE source of the gate (nav.js no longer carries its own+ // copy). It's a tiny synchronous check — read the live tour state / ?tour=+ // param and only pull in the heavy /feature-tour.js module when a tour is+ // actually starting or in progress, so a page that never tours pays+ // nothing. Idempotent: the script-tag guard stops a double mount if+ // anything else races to load the engine. Embeds (iframes) are skipped to+ // match the other injectors, and the gate also self-guards on window.top+ // so an embed can never spawn the tour.+ name: 'feature-tour-boot',+ transformIndexHtml: {+ order: 'pre',+ handler(_html, ctx) {+ const EMBED_FILES = new Set([+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',+ ]);+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();+ if (EMBED_FILES.has(filename)) return [];+ const GATE =+ "(function(){if(window.top!==window.self)return;var a=false;try{var r=sessionStorage.getItem('tws:tour:state');a=!!r&&JSON.parse(r).active===true}catch(e){}var p=new URLSearchParams(location.search).get('tour');if(!(p==='start'||p==='1'||(p!=='0'&&a)))return;if(document.querySelector('script[src=\"/feature-tour.js\"]'))return;var s=document.createElement('script');s.type='module';s.src='/feature-tour.js';document.head.appendChild(s)})();";+ return [{ tag: 'script', children: GATE, injectTo: 'head' }];+ },+ },+ },+ {+ // Vercel Speed Insights — real-user Core Web Vitals (LCP/INP/CLS/TTFB)+ // for every page, collected from actual visitors and surfaced in the+ // Vercel dashboard. This is the "measure, don't guess" complement to the+ // first-party error reporter above: it tells us which pages are slow for+ // real users under load instead of inferring it from synthetic audits.+ //+ // Injected ONLY on Vercel builds (process.env.VERCEL is set there). The+ // script is served by the platform at /_vercel/speed-insights/script.js+ // once Speed Insights is enabled for the project; off-Vercel (the+ // push-only mirror, local dev) it would 404, so we never emit it there.+ // Zero ingestion code by design — the platform owns collection + storage.+ name: 'vercel-speed-insights',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ if (!process.env.VERCEL) return [];+ return [+ {+ tag: 'script',+ attrs: { defer: true, src: '/_vercel/speed-insights/script.js' },+ injectTo: 'head',+ },+ ];+ },+ },+ },+ {+ // Native View Transitions for internal nav. Chrome/Safari ship it,+ // Firefox falls back to a normal location change (no UX regression).+ // Skip on embed pages — they're iframes and shouldn't intercept clicks.+ name: 'view-transitions',+ transformIndexHtml: {+ order: 'pre',+ handler(_html, ctx) {+ const EMBED_FILES = new Set([+ 'widget.html',+ 'embed.html',+ 'avatar-embed.html',+ 'agent-embed.html',+ 'a-embed.html',+ // Runtime-fetched FRAGMENTS, not documents: nav.js / footer.js+ // fetch these and assign them via innerHTML. In dev, Vite's+ // transformIndexHtml runs on them too, and injecting a script+ // here gets it interleaved with Vite's own /@vite/client tag —+ // the fragment parser then closes the script early and renders+ // the remainder of its source as DOM text/elements inside the+ // nav/footer containers. The page document already carries the+ // inline script; fragments must never get it.+ 'nav.html',+ 'footer.html',+ ]);+ const filename = (ctx.filename || ctx.path || '')+ .replace(/\\/g, '/')+ .split('/')+ .pop();+ if (EMBED_FILES.has(filename)) return [];+ // Inline the dependency-free source directly as a classic+ // (non-module) script. Two failure modes this avoids:+ // 1. A `type=module` inline script gets externalized by Vite+ // into a `?html-proxy` request that 404s to the SPA HTML+ // fallback for repo-root dir-index pages (e.g. /docs).+ // 2. A dynamic `import('/src/view-transitions.js')` is rewritten+ // by the prod build into `import('data:text/javascript;…')`,+ // which the site CSP (no `data:` in script-src) blocks — the+ // transition wiring then silently never runs.+ // Inlining the actual source sidesteps both: it runs under the+ // existing `'unsafe-inline'` allowance with no extra fetch. The+ // file stays the single source of truth (dev imports it directly).+ const vtSource = readFileSync(+ resolve(__dirname, 'src/view-transitions.js'),+ 'utf8',+ ).replace(/^export\s+function/m, 'function');+ return [+ {+ tag: 'script',+ children: `(function(){${vtSource}\ntry{enableViewTransitions();}catch(e){}})();`,+ injectTo: 'head',+ },+ ];+ },+ },+ },+ {+ // Stamp every Vite-processed HTML page so footer.js can detect that+ // Three.js is already bundled and skip loading the model-viewer CDN script.+ name: 'three-bundle-meta',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ return [+ {+ tag: 'meta',+ attrs: { name: 'has-three-bundle', content: 'true' },+ injectTo: 'head',+ },+ ];+ },+ },+ },+ (() => {+ // Suppress the cosmetic "Multiple instances of Three.js being imported"+ // warning. Three.js does `if (window.__THREE__) warn(); else __THREE__ = REVISION;`+ // so the naive "pre-claim the global" trick actively triggers the warning+ // instead of suppressing it. Instead, install a property accessor whose+ // getter always returns undefined and whose setter is a no-op — every+ // three.js instance's check then passes silently. Runs in head-prepend+ // so it executes before model-viewer's bundled three or our app bundle.+ const GUARD =+ 'try{Object.defineProperty(window,"__THREE__",{configurable:true,get:function(){return undefined},set:function(){}})}catch(_){}';+ return {+ name: 'three-multi-instance-guard',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ // `injectTo: 'head'` (end of head) rather than 'head-prepend'+ // so any importmap declared by the source page stays the first+ // child of <head> — vite's html lint warns whenever ANY script+ // precedes an importmap, even a sync classic script like ours.+ // The guard is a sync <script>, so it still runs before any+ // deferred type=module script. Closing-bundle pass below+ // guarantees the marker exists in every dist HTML even if the+ // transform was skipped for that entry.+ return [{ tag: 'script', children: GUARD, injectTo: 'head' }];+ },+ },+ closeBundle: {+ sequential: true,+ order: 'post',+ async handler() {+ const { readdirSync, statSync, readFileSync, writeFileSync } =+ await import('fs');+ const { join } = await import('path');+ const distDir = resolve(__dirname, 'dist');+ if (!existsSync(distDir)) return;+ const MARKER = 'Object.defineProperty(window,"__THREE__"';+ const LEGACY =+ /<script>\s*window\.__THREE__\s*=\s*window\.__THREE__\s*\|\|\s*["'][^"']+["']\s*;?\s*<\/script>\s*/g;+ const tag = `<script>${GUARD}</script>`;+ const walk = (dir) => {+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ let stat;+ try {+ stat = statSync(full);+ } catch {+ continue;+ }+ if (stat.isDirectory()) walk(full);+ else if (entry.endsWith('.html')) {+ const html = readFileSync(full, 'utf8');+ let next = html.replace(LEGACY, '');+ if (!next.includes(MARKER)) {+ next = next.replace(+ /<head(\s[^>]*)?>/i,+ (m) => `${m}\n\t\t${tag}`,+ );+ }+ if (next !== html) writeFileSync(full, next);+ }+ }+ };+ walk(distDir);+ },+ },+ };+ })(),+ {+ name: 'copy-static-docs',+ closeBundle() {+ // dist/docs is served publicly: /docs/<topic>.md is fetched by the docs+ // SPA, and every other file under it is reachable as a static asset.+ // These subtrees are written for operators, not readers — the ops+ // runbooks name the GCP project, service accounts, and which env vars+ // gate which routes; the security reviews describe attacks against+ // live code, some still open. Keep them in the repo, off the website.+ const PRIVATE_DOCS = new Set(['internal', 'ops', 'security']);+ const docsRoot = resolve(__dirname, 'docs');+ cpSync(docsRoot, resolve(__dirname, 'dist/docs'), {+ recursive: true,+ filter: (src) => {+ const rel = relative(docsRoot, src);+ return !rel || !PRIVATE_DOCS.has(rel.split(sep)[0]);+ },+ });+ },+ },+ {+ name: 'copy-blog',+ closeBundle() {+ const blogSrc = resolve(__dirname, 'blog');+ if (existsSync(blogSrc)) {+ cpSync(blogSrc, resolve(__dirname, 'dist/blog'), { recursive: true });+ }+ },+ },+ {+ // The IBM × three.ws x402 demo (pages/ibm/x402-demo.html) is a hand-+ // authored, self-contained partner artifact — inline CSS+JS, self-hosted+ // fonts under pages/ibm/fonts/, a vendored <model-viewer> under+ // pages/ibm/vendor/, absolute three.ws URLs. It ships to IBM to+ // host on a foreign origin under a strict CSP, so it must stay byte-for-byte+ // identical wherever it's served. We therefore copy it VERBATIM to dist/ibm/+ // instead of registering it as a Rollup input: a Vite input would minify the+ // HTML, hash the relative ./fonts/ URLs (so they no longer travel with the+ // file), and inject the site's analytics / error-reporter / three-guard+ // scripts via the transformIndexHtml plugins above — each of which diverges+ // the preview from the standalone file and pulls in origins the page's+ // `script-src 'self' three.ws` CSP forbids. The .md hosting guide is+ // source-only and excluded from the copy.+ //+ // The same applies to the partnership page. pages/ibm/hello.live.html is the+ // editable source; pages/ibm/hello.html is GENERATED from it (npm run+ // build:ibm-shell, also wired into build:vercel) as a SELF-CONTAINED,+ // publish-once page: it bakes in the full page (renders with zero three.ws+ // dependency) and, on load, fetches the latest from three.ws/ibm/hello.live+ // and swaps it in if reachable — so content stays editable after the file is+ // locked on the host, without ever risking a blank page. Both ship verbatim+ // (the closeBundle copies the whole pages/ibm/ dir), and the dev middleware+ // below serves /ibm/hello + /ibm/hello.live so it resolves locally too.+ name: 'copy-ibm-x402-demo',+ configureServer(server) {+ const dir = resolve(__dirname, 'pages/ibm');+ const MIME = {+ '.html': 'text/html; charset=utf-8',+ '.woff2': 'font/woff2',+ // model-viewer.min.js loads as <script type="module">; a JS MIME is+ // mandatory or the browser refuses the module ("not executable").+ '.js': 'text/javascript; charset=utf-8',+ };+ server.middlewares.use((req, res, next) => {+ const path = (req.url || '').split('?')[0];+ let rel = null;+ if (path === '/ibm/x402-demo' || path === '/ibm/x402-demo.html')+ rel = 'x402-demo.html';+ else if (path === '/ibm/hello' || path === '/ibm/hello.html')+ rel = 'hello.html';+ else if (path === '/ibm/hello.live' || path === '/ibm/hello.live.html')+ rel = 'hello.live.html';+ else if (path.startsWith('/ibm/fonts/'))+ rel = 'fonts/' + path.slice('/ibm/fonts/'.length);+ else if (path.startsWith('/ibm/vendor/'))+ rel = 'vendor/' + path.slice('/ibm/vendor/'.length);+ if (!rel) return next();+ const file = resolve(dir, rel);+ // Path-traversal guard: never serve outside pages/ibm/.+ if (!file.startsWith(dir + '/') || !existsSync(file) || !statSync(file).isFile())+ return next();+ res.setHeader('Content-Type', MIME[extname(file)] || 'application/octet-stream');+ createReadStream(file).pipe(res);+ });+ },+ closeBundle() {+ const src = resolve(__dirname, 'pages/ibm');+ if (!existsSync(src)) return;+ // Ship the page, its fonts, and the vendored model-viewer (recursive+ // copy covers pages/ibm/vendor/); the hosting guide stays in source.+ cpSync(src, resolve(__dirname, 'dist/ibm'), {+ recursive: true,+ filter: (s) => !s.endsWith('.md'),+ });+ },+ },+ {+ // Several static pages (dashboard, vanity-wallet, …) import ESM+ // directly from `/src/*.js`. Vite's dev server serves these from+ // the project root, but production needs them under dist/. Mirror+ // the tree so the runtime URLs resolve.+ name: 'copy-src-to-dist',+ closeBundle() {+ cpSync(resolve(__dirname, 'src'), resolve(__dirname, 'dist/src'), {+ recursive: true,+ });+ cpSync(+ resolve(__dirname, 'pump-fun-skills'),+ resolve(__dirname, 'dist/pump-fun-skills'),+ {+ recursive: true,+ },+ );+ },+ },+ {+ // Mirror the rebranded Character Studio build (the @m3-org fork in+ // character-studio/, served as "Avatar Studio" under three.ws) into+ // dist/avatar-studio/. The avatar-sdk Creator iframe loads this URL.+ // The fork must be built (`npm run build --prefix character-studio`)+ // before the main build runs — wired into npm run build:vercel.+ name: 'copy-avatar-studio',+ closeBundle() {+ const src = resolve(__dirname, 'character-studio/build');+ if (!existsSync(src)) {+ console.warn(+ '[copy-avatar-studio] character-studio/build/ missing — run `npm run build --prefix character-studio` first',+ );+ return;+ }+ cpSync(src, resolve(__dirname, 'dist/avatar-studio'), { recursive: true });+ },+ },+ {+ // Rewrite R2 public-bucket URLs in proxied /api/avatars/* responses so+ // the <agent-3d> component (loaded from CDN) always receives /r2-proxy/*+ // URLs instead of raw r2.dev URLs that fail CORS in Codespaces / localhost.+ name: 'r2-url-rewrite-api',+ configureServer(server) {+ const R2_PUBLIC_RE = /https?:\/\/pub-[a-f0-9]+\.r2\.dev\//g;+ server.middlewares.use(async (req, res, next) => {+ if (!req.url?.startsWith('/api/avatars/')) return next();+ // Only rewrite GET/HEAD responses — POSTs and mutations must flow+ // through the normal proxy with their original method and body intact.+ if (req.method !== 'GET' && req.method !== 'HEAD') return next();+ try {+ const upstream = new URL(req.url, DEV_API_PROXY);+ // Forward the caller's credentials: without them this refetch is+ // anonymous, so private avatars 404 in dev even when the browser+ // session is logged in (the editor's fetchAvatar sends cookies).+ const resp = await fetch(upstream.href, {+ headers: {+ accept: 'application/json',+ ...(req.headers.cookie ? { cookie: req.headers.cookie } : {}),+ ...(req.headers.authorization+ ? { authorization: req.headers.authorization }+ : {}),+ },+ });+ const text = await resp.text();+ const rewritten = text.replace(R2_PUBLIC_RE, '/r2-proxy/');+ res.statusCode = resp.status;+ res.setHeader(+ 'content-type',+ resp.headers.get('content-type') || 'application/json',+ );+ res.end(rewritten);+ } catch (err) {+ next();+ }+ });+ },+ },+ {+ // Serve `/api/widgets/wdgt_demo_*` from the local fixture file in dev.+ // Without this, those requests fall through to the `/api` proxy and hit+ // production — which may not yet have new demo IDs, so the gallery+ // renders dead iframes locally even though the fixture exists in source.+ // Production resolves the same IDs via api/widgets/[id].js → fixtures.+ name: 'widgets-demo-fixtures',+ configureServer(server) {+ server.middlewares.use(async (req, res, next) => {+ const url = req.url || '';+ const m = url.match(/^\/api\/widgets\/(wdgt_demo_[A-Za-z0-9_-]+)(?:[?#]|$)/);+ if (!m) return next();+ try {+ const mod = await server.ssrLoadModule('/api/widgets/_demo-fixtures.js');+ const widget = mod.getDemoWidget(m[1]);+ if (!widget) {+ res.statusCode = 404;+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({ error: 'not_found', message: 'widget not found' }),+ );+ return;+ }+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json');+ res.setHeader('cache-control', 'public, max-age=60');+ res.end(JSON.stringify({ widget }));+ } catch (err) {+ res.statusCode = 500;+ res.setHeader('content-type', 'application/json');+ res.end(+ JSON.stringify({ error: 'fixture_load_failed', message: err.message }),+ );+ }+ });+ },+ },+ {+ // Serve /avatar-sdk/** in dev from the avatar-sdk/ directory at the repo+ // root (Vite's publicDir only covers public/). In production, copy+ // avatar-sdk/dist and avatar-sdk/src into dist/avatar-sdk/ so the same+ // URL paths resolve after deploy.+ name: 'avatar-sdk-static',+ configureServer(server) {+ const MIME = {+ '.js': 'application/javascript',+ '.mjs': 'application/javascript',+ '.css': 'text/css',+ '.json': 'application/json',+ '.ts': 'application/typescript',+ '.html': 'text/html',+ };+ server.middlewares.use((req, res, next) => {+ if (!req.url?.startsWith('/avatar-sdk/')) return next();+ const rel = req.url.replace(/\?.*$/, '').slice('/avatar-sdk/'.length);+ const file = resolve(__dirname, 'avatar-sdk', rel);+ if (!existsSync(file) || statSync(file).isDirectory()) return next();+ const mime = MIME[extname(file)] ?? 'application/octet-stream';+ res.setHeader('Content-Type', mime);+ createReadStream(file).pipe(res);+ });+ },+ closeBundle() {+ const sdkRoot = resolve(__dirname, 'avatar-sdk');+ const outRoot = resolve(__dirname, 'dist/avatar-sdk');+ for (const sub of ['dist', 'src']) {+ const src = resolve(sdkRoot, sub);+ if (existsSync(src)) {+ cpSync(src, resolve(outRoot, sub), { recursive: true });+ }+ }+ },+ },+ {+ // publicDir copies `public/agent/index.html` verbatim to+ // `dist/agent/index.html`, but we also register it as a Vite+ // input so its inline modules are bundled (Solana SDKs etc.).+ // The bundled output lands at `dist/public/agent/index.html`;+ // swap it into the serving path and drop the duplicate tree+ // so Vercel doesn't ship the raw-imports version that 404s on+ // `/src/*` in production.+ name: 'promote-bundled-public-html',+ closeBundle() {+ const pairs = [+ ['dist/public/agent/index.html', 'dist/agent/index.html'],+ ['dist/public/login.html', 'dist/login.html'],+ ['dist/public/register.html', 'dist/register.html'],+ ['dist/public/characters.html', 'dist/characters.html'],+ ['dist/public/character.html', 'dist/character.html'],+ ['dist/public/agents/index.html', 'dist/agents/index.html'],+ ['dist/public/validation/index.html', 'dist/validation/index.html'],+ ['dist/public/gallery/index.html', 'dist/gallery/index.html'],+ ['dist/public/demos/brain.html', 'dist/demos/brain.html'],+ ['dist/public/demos/lipsync-tts.html', 'dist/demos/lipsync-tts.html'],+ ['dist/public/demos/lipsync-mic.html', 'dist/demos/lipsync-mic.html'],+ ['dist/public/demos/erc8004.html', 'dist/demos/erc8004.html'],+ ['dist/public/demos/button-jump.html', 'dist/demos/button-jump.html'],+ ['dist/public/demos/button.html', 'dist/demos/button.html'],+ ['dist/public/demos/3d-home.html', 'dist/demos/3d-home.html'],+ ['dist/public/eth-vanity.html', 'dist/eth-vanity.html'],+ ['dist/public/evm-wallet.html', 'dist/evm-wallet.html'],+ // /vanity-wallet: its sealed-drops controller pulls bare deps+ // (bs58, @noble/*, qrcode) that only resolve through the bundler.+ // Serving the raw publicDir copy threw "Failed to resolve module+ // specifier bs58" in production; promote the bundled output.+ ['dist/public/vanity-wallet.html', 'dist/vanity-wallet.html'],+ // Grind-bounty market: its controller pulls bare deps (bs58, @noble,+ // sealed-envelope) through the bundler, so the BUNDLED output must be+ // served — promote it over the raw publicDir copy before dist/public+ // is wiped.+ ['dist/public/vanity/bounties/index.html', 'dist/vanity/bounties/index.html'],+ ];+ for (const [from, to] of pairs) {+ const src = resolve(__dirname, from);+ const dst = resolve(__dirname, to);+ if (!existsSync(src)) continue;+ cpSync(src, dst, { force: true });+ }+ const publicMirror = resolve(__dirname, 'dist/public');+ if (existsSync(publicMirror)) {+ rmSync(publicMirror, { recursive: true, force: true });+ }+ },+ },+ {+ // Root-level HTML files now live under `pages/`. Vite bundles them+ // to `dist/pages/<name>.html`; flatten into `dist/<name>.html` so+ // vercel.json `dest` paths and existing /name URLs continue to+ // resolve without rewriting every route.+ name: 'flatten-pages-dir',+ closeBundle: {+ sequential: true,+ order: 'post',+ async handler() {+ const pagesOut = resolve(__dirname, 'dist/pages');+ if (!existsSync(pagesOut)) return;+ const { readdirSync, statSync } = await import('fs');+ for (const entry of readdirSync(pagesOut)) {+ const from = resolve(pagesOut, entry);+ const to = resolve(__dirname, 'dist', entry);+ const stat = statSync(from);+ if (stat.isFile()) {+ cpSync(from, to, { force: true });+ } else if (stat.isDirectory()) {+ // Nested page directories (e.g. pages/dashboard-next/) keep+ // their structure inside dist/ so /dashboard-next/<page> URLs+ // resolve. Recursive merge preserves any sibling assets+ // already copied from public/dashboard-next/.+ cpSync(from, to, { recursive: true, force: true });+ }+ }+ rmSync(pagesOut, { recursive: true, force: true });+ },+ },+ },+ VitePWA({+ registerType: 'autoUpdate',+ includeAssets: ['favicon.ico', 'pwa-192x192.png', 'pwa-512x512.png', 'pwa-icon.svg'],+ manifest: {+ name: 'three.ws — Give Your AI a Body',+ short_name: 'three.ws',+ description:+ 'Create 3D AI agents, give them a voice and body, trade them on-chain, and embed them anywhere. The 3D layer for the agentic web.',+ lang: 'en',+ dir: 'ltr',+ theme_color: '#000000',+ background_color: '#080814',+ display: 'standalone',+ display_override: ['window-controls-overlay', 'standalone', 'browser'],+ orientation: 'natural',+ scope: '/',+ start_url: '/?source=pwa',+ categories: ['productivity', 'entertainment', 'social', 'utilities'],+ icons: [+ { src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },+ { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },+ {+ src: 'pwa-512x512.png',+ sizes: '512x512',+ type: 'image/png',+ purpose: 'maskable',+ },+ ],+ shortcuts: [+ {+ name: 'Create Avatar',+ short_name: 'Create',+ description: 'Build a new 3D AI avatar',+ url: '/create?source=pwa-shortcut',+ icons: [{ src: 'pwa-192x192.png', sizes: '192x192' }],+ },+ {+ name: 'Marketplace',+ short_name: 'Discover',+ description: 'Browse AI agents and avatars',+ url: '/marketplace?source=pwa-shortcut',+ icons: [{ src: 'pwa-192x192.png', sizes: '192x192' }],+ },+ {+ name: 'My Agents',+ short_name: 'My Agents',+ description: 'Manage your AI agents',+ url: '/agents?source=pwa-shortcut',+ icons: [{ src: 'pwa-192x192.png', sizes: '192x192' }],+ },+ ],+ screenshots: [+ {+ src: 'screenshots/landing.png',+ sizes: '1280x800',+ type: 'image/png',+ form_factor: 'wide',+ label: 'three.ws home — Give Your AI a Body',+ },+ {+ src: 'screenshots/create.png',+ sizes: '1280x800',+ type: 'image/png',+ form_factor: 'wide',+ label: 'Create a 3D avatar',+ },+ {+ src: 'screenshots/discover.png',+ sizes: '1280x800',+ type: 'image/png',+ form_factor: 'wide',+ label: 'Discover AI agents on the marketplace',+ },+ {+ src: 'screenshots/studio.png',+ sizes: '1280x800',+ type: 'image/png',+ form_factor: 'wide',+ label: 'Agent studio and customization',+ },+ {+ src: 'screenshots/features.png',+ sizes: '1280x800',+ type: 'image/png',+ form_factor: 'wide',+ label: 'Platform features overview',+ },+ ],+ },+ workbox: {+ maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,+ // Pull in the Web Push handlers (push + notificationclick). Kept in+ // public/push-sw.js as a classic script so the generated Workbox SW+ // importScripts it without switching to an injectManifest build.+ importScripts: ['/push-sw.js'],+ // MPA: every route is a separate HTML file served by the server.+ // No navigation fallback — uncached navigations go to the network.+ // HTML is intentionally excluded from globPatterns so it is never+ // precached: (1) the SW install is dramatically faster (hundreds fewer+ // files), (2) old SWs can activate the new one in seconds instead of+ // minutes, (3) navigation requests fall through to the network and+ // always return the current page from Vercel's edge — no stale HTML+ // and no offline.html served to online users.+ navigateFallback: null,+ // Precache ONLY stable, rarely-renamed assets (icons + fonts).+ // JS/CSS are intentionally excluded from the precache manifest and+ // served via runtime StaleWhileRevalidate instead (see runtimeCaching+ // below). Reason: every JS/CSS chunk is content-hashed and Vercel's+ // production alias only serves the *latest* deployment's assets. When+ // a new deploy lands while a user still holds an older page/SW — or+ // while a fresh SW is mid-install — the precache manifest references+ // chunks (e.g. assets/stage-<hash>.js) that now 404. Workbox treats a+ // single 404 as fatal `bad-precaching-response` and aborts the ENTIRE+ // SW install, leaving the user with no SW at all. Runtime caching makes+ // a 404 non-fatal: it's just a missed fetch the page's own dynamic+ // import handles, and autoUpdate still rolls the new SW forward.+ globPatterns: ['**/*.{ico,woff2}'],+ globIgnores: [+ 'pages/**',+ '**/animations/**',+ '**/avatars/**',+ '**/screenshots/**',+ '**/docs/**',+ '**/og-image.*',+ '**/three.svg',+ '**/3d.png',+ '**/ddd.png',+ 'chat/**',+ 'pump-fun-skills/**',+ ],+ skipWaiting: true,+ clientsClaim: true,+ cleanupOutdatedCaches: true,+ runtimeCaching: [+ // Embed surfaces (/widget, /embed, /a-embed, /agent-embed)+ // must never be served from the SW cache — embedders rely+ // on the iframe always reflecting the latest config.+ {+ urlPattern: /^https?:\/\/[^/]+\/widget(\/.*|\?.*|#.*|$)/i,+ handler: 'NetworkOnly',+ },+ {+ urlPattern:+ /^https?:\/\/[^/]+\/(embed|a-embed|agent-embed|avatar-embed)(\/.*|\?.*|#.*|$)/i,+ handler: 'NetworkOnly',+ },+ {+ urlPattern: /^https?:\/\/[^/]+\/api\/widgets\//i,+ handler: 'NetworkOnly',+ },+ // Content-hashed build chunks under /assets/ (e.g.+ // assets/marketplace-Cn45GLvE.js, assets/index-<hash>.css).+ // These are immutable: the filename changes whenever the bytes+ // change, so the cached copy can NEVER be stale for a URL that+ // still resolves. StaleWhileRevalidate is correct and fast here —+ // serve instantly, refresh in the background; a 404 during a+ // deploy rollover is a non-fatal background miss the page's own+ // dynamic import handles, never a broken SW install.+ {+ urlPattern: ({ url, request, sameOrigin }) =>+ sameOrigin &&+ url.pathname.startsWith('/assets/') &&+ (request.destination === 'script' ||+ request.destination === 'style'),+ handler: 'StaleWhileRevalidate',+ options: {+ cacheName: 'app-assets',+ expiration: {+ maxEntries: 200,+ maxAgeSeconds: 60 * 60 * 24 * 30,+ },+ cacheableResponse: { statuses: [200] },+ },+ },+ // Stable-named same-origin scripts & styles served verbatim from+ // public/ (/style.css, /marketplace.css, /nav.css, /mobile.css,+ // /nav.js, /footer.js, ...). Unlike the hashed chunks above these+ // keep ONE URL across deploys while their BYTES change — so+ // StaleWhileRevalidate would hand a returning user last deploy's+ // CSS against this deploy's freshly-served HTML. When a redesign+ // renames classes or restructures the header/marketplace markup,+ // the stale stylesheet no longer matches: the header collapses to+ // overlapping text and the tab rail stacks vertically (the exact+ // FOUC users hit "again" after every deploy). NetworkFirst pins+ // the live deploy's CSS/JS to its HTML — always fetch fresh, fall+ // back to cache only when offline. A short network timeout keeps+ // repeat visits fast. Placed after the /assets/ rule so hashed+ // chunks keep their immutable SWR fast path.+ {+ urlPattern: ({ request, sameOrigin }) =>+ sameOrigin &&+ (request.destination === 'script' ||+ request.destination === 'style'),+ handler: 'NetworkFirst',+ options: {+ cacheName: 'app-shell-assets',+ networkTimeoutSeconds: 4,+ expiration: {+ maxEntries: 80,+ maxAgeSeconds: 60 * 60 * 24 * 30,+ },+ cacheableResponse: { statuses: [200] },+ },+ },+ {+ urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,+ handler: 'CacheFirst',+ options: {+ cacheName: 'google-fonts-cache',+ expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },+ cacheableResponse: { statuses: [0, 200] },+ },+ },+ {+ urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,+ handler: 'CacheFirst',+ options: {+ cacheName: 'gstatic-fonts-cache',+ expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },+ cacheableResponse: { statuses: [0, 200] },+ },+ },+ // NOTE: /api/* is intentionally NOT registered as a runtime+ // route. No route → the SW never calls respondWith for API+ // requests, so the browser fetches them natively (still+ // network-only, never cached). A NetworkOnly rule here would+ // be behaviourally identical on success but re-wraps any+ // transient fetch rejection as an uncaught `no-response`+ // WorkboxError, spamming the console. Let the page's own+ // fetch().catch own those failures instead.+ ],+ },+ }),+ ],+};++// Library build — the web component + public API, for CDN drop-in:+// <script type="module" src="https://cdn.example.com/agent-3d.js"></script>+//+// Three.js and ethers stay bundled (the element must be self-contained for a+// zero-install embed). Size will be ~600-900KB gzipped; split via dynamic+// imports in a later pass.+const libConfig = {+ resolve: {+ dedupe: ['three'],+ },+ // Same separate-rollup-pass caveat as the app config above.+ worker: {+ rollupOptions: { output: { banner: LEGACY_RUNTIME_POLYFILL } },+ },+ build: {+ outDir: 'dist-lib',+ emptyOutDir: true,+ chunkSizeWarningLimit: 2000,+ lib: {+ entry: resolve(__dirname, 'src/lib.js'),+ name: 'Agent3D',+ formats: process.env.LIB_FORMATS ? process.env.LIB_FORMATS.split(',') : ['es'],+ fileName: (format) => (format === 'es' ? 'agent-3d.js' : 'agent-3d.umd.cjs'),+ },+ rollupOptions: {+ // No externals — self-contained drop-in embed.+ // inlineDynamicImports keeps the output as a single file so CDN+ // consumers get one <script type="module"> with no chunk fetches.+ // The lib IS the third-party embed, so it needs the old-WebView+ // polyfill even more than the app does.+ output: { inlineDynamicImports: true, banner: LEGACY_RUNTIME_POLYFILL },+ },+ },+};++export default defineConfig(TARGET === 'lib' ? libConfig : appConfig);