Skip to content

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.

feat: walk-sdk package + slimmed playground/companion, x402-modal/payment-modal packaging, SDK docs

nirholas86cffc211019
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 447c3a8ad..8c4063e30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Fixed the clipped header on the agent wallet page** — The agent wallet page had a broken header — the agent's avatar and the green "Wallet ready" badge were chopped off behind a black bar, with the wallet name floating above it. A site-wide page-header style was leaking onto the wallet's own header row and forcing it into a short, clipped strip. The header now lays out properly, so the avatar, status badge, profile link, and network selector are all fully visible. `[fix]`
- **Fixed wallet sign-in returning an error** — Signing in with a Solana or Ethereum wallet was failing for everyone — the request that starts the sign-in handshake was erroring out before you could approve anything in your wallet. A misread site address on the server was the cause; it now self-corrects, and wallet sign-in works again. `[fix]`
- **Flappin UFO — a $THREE arcade demo is live** — A playable demo just landed at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard, which refreshes live every 15 seconds and highlights your entry. Consider it a taste: these arcade demos are warm-ups while we build something far bigger for $THREE. (`/play/ufo`) `[feature]`
+- **Forge a 3D model on the IBM x402 demo — free, no wallet** — The IBM × three.ws x402 demo now forges 3D models two ways. The paid Forge takes one USDC micropayment from your own wallet and settles on Solana; right below it, a free generator turns any sentence into a textured, downloadable GLB with no wallet, no API key and no payment — it runs Microsoft TRELLIS on NVIDIA NIM with automatic fallback across lanes so a model always comes back. The paid Forge now settles in USDC on Solana mainnet. (`/ibm/x402-demo`) `[feature, improvement]`
- **Freeze your agent wallet in one tap — plus hardened custody security** — Your agent's wallet now has a freeze switch. Open the wallet's Limits & Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too. `[feature, security]`
- **Fund any agent wallet by scanning a QR or copying the address — with live confirmation** — The agent wallet's Deposit tab is now a complete, public funding panel: a crisp QR code (generated on-device, no third-party service) that your phone wallet can scan, a one-tap copyable Solana address, an optional preset amount, and a Solana deep-link that opens Phantom, Solflare or Backpack on mobile. The panel watches the agent's real on-chain balance and confirms the moment your SOL lands — "◎0.5 SOL received" — instead of leaving you guessing. Anyone can fund an agent, not just its owner, and the new "Fund agent wallet" button on the create-agent success screen leads new users straight into it. `[feature]`
- **Funds and payments hardened: wallet-key isolation, spend-cap races, recipient checks** — Following the security audit, we strengthened everything that touches money. Custodial agent-wallet private keys now encrypt with a dedicated key — separate from the session secret — and a unique salt per wallet, so the secret guarding your funds no longer shares fate with anything else (existing wallets keep working; they re-key on next use). Per-agent daily spend limits, x402 payment de-duplication, and on-chain permission caps are now enforced atomically, closing races where a burst of concurrent requests could slip past a budget or run paid work twice for one payment. Pay-by-name sends re-check that the name still resolves to the exact address you approved before the agent signs, and reject look-alike or invalid targets; withdrawals now only ever pay out to a wallet you've already saved. We also removed a stored cross-site-scripting vector in uploaded 3D-model metadata and the admin panel, added clickjacking and permissions-policy protections site-wide, and moved IPFS pinning fully server-side so no upload credential ever ships to the browser. No action needed on your end. `[security]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 7138be306..204d06f2c 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -16,6 +16,7 @@ bottom.
|---|---|---|---|
| Web renderer / viewer | [avatar-sdk/](avatar-sdk) `→ /viewer` | Published as `@three-ws/avatar` | `<agent-3d>` web component |
| React avatar creator | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath |
+| Talking page guide | [page-agent-sdk/](page-agent-sdk) | Published as `@three-ws/page-agent` | Drop-in rigged 3D agent that narrates any page + visitor avatar picker. `<page-agent>` web component. Rigged-only catalog. See [page-agent-sdk/PUBLISHING.md](page-agent-sdk/PUBLISHING.md) |
| Avatar builder (full app) | [character-studio/](character-studio) | Fork of [m3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio), MIT, see [character-studio/LICENSE](character-studio/LICENSE) | Web-first character creator |
| Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene` | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export |
| Embed examples | [examples/](examples) | In-repo | `embed-test.html`, `web-component.html`, `two-agents.html`, `minimal.html` |
diff --git a/api/avatars/index.js b/api/avatars/index.js
index e000ac020..7915d4a36 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -100,7 +100,10 @@ async function handleCreate(req, res) {
// absent and the avatar reads as "unknown", exactly as before. Paths that
// already stamp the signal (reconstruct, forge, studio) pass their own
// source_meta; we only fill what inspection found and never clobber it.
- if (!body.source_meta || body.source_meta.is_rigged == null) {
+ const looksGlb =
+ /\.glb$/i.test(body.storage_key) ||
+ (body.content_type || head.ContentType || '').includes('gltf-binary');
+ if (looksGlb && (!body.source_meta || body.source_meta.is_rigged == null)) {
try {
const rig = await inspectStorageKeyRig(body.storage_key);
if (rig) body.source_meta = { ...rig, ...(body.source_meta || {}) };
diff --git a/data/changelog.json b/data/changelog.json
index 3e9924575..965395a40 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Forge a 3D model on the IBM x402 demo — free, no wallet",
+ "summary": "The IBM × three.ws x402 demo now forges 3D models two ways. The paid Forge takes one USDC micropayment from your own wallet and settles on Solana; right below it, a free generator turns any sentence into a textured, downloadable GLB with no wallet, no API key and no payment — it runs Microsoft TRELLIS on NVIDIA NIM with automatic fallback across lanes so a model always comes back. The paid Forge now settles in USDC on Solana mainnet.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/ibm/x402-demo"
+ },
{
"date": "2026-06-19",
"title": "Put a talking 3D guide on any website — new @three-ws/page-agent SDK",
diff --git a/package.json b/package.json
index 31d8bd0b5..d6077f218 100644
--- a/package.json
+++ b/package.json
@@ -52,7 +52,8 @@
"packages/ibm-watsonx-mcp",
"packages/ibm-x402-mcp",
"packages/three-token-mcp",
- "packages/threews-avatar-mcp"
+ "packages/threews-avatar-mcp",
+ "walk-sdk"
],
"main": "src/app.js",
"browserslist": [
diff --git a/page-agent-sdk/PUBLISHING.md b/page-agent-sdk/PUBLISHING.md
new file mode 100644
index 000000000..a92de5041
--- /dev/null
+++ b/page-agent-sdk/PUBLISHING.md
@@ -0,0 +1,47 @@
+# Shipping `@three-ws/page-agent`
+
+This package lives inside the three.ws monorepo today and is built to graduate
+to its own npm release — and, when there's external demand, its own repo —
+without code changes. Follow [STRUCTURE.md → Promotion path](../STRUCTURE.md#promotion-path).
+
+## Publish to npm (from the monorepo)
+
+```bash
+cd page-agent-sdk
+npm run build # → dist/page-agent.mjs, dist/page-agent.global.js, dist/page-agent.css
+npm test # catalog + lipsync unit tests
+npm publish --access public
+```
+
+`prepublishOnly` re-runs the build, so a bare `npm publish` is also safe. The
+published tarball ships `dist/`, `src/`, `types/`, `README.md`, and `LICENSE`
+(see the `files` field) — verify with:
+
+```bash
+npm pack --dry-run
+```
+
+## Split into a standalone repo (when external demand justifies it)
+
+The package is self-contained: its only runtime peer is `three`, and it imports
+nothing from the parent app. To cut it into its own repo with full history:
+
+```bash
+# from the repo root
+git subtree split --prefix=page-agent-sdk -b page-agent-split
+
+mkdir ../page-agent && cd ../page-agent
+git init && git pull ../three.ws page-agent-split
+git remote add origin https://github.com/<org>/page-agent.git
+git push -u origin main
+```
+
+Then, back in three.ws, either keep the workspace copy or replace it with the
+published npm dependency. Until that external need is real, splitting is
+premature — keeping it as a workspace costs nothing and keeps releases in lockstep
+with the avatar runtime it complements.
+
+## Versioning
+
+Semver, independent of the app version. Bump on every published change; the
+`version` field is the source of truth for the npm badge in the README.
diff --git a/page-agent-sdk/docs/README.md b/page-agent-sdk/docs/README.md
new file mode 100644
index 000000000..1f6ce01f5
--- /dev/null
+++ b/page-agent-sdk/docs/README.md
@@ -0,0 +1,102 @@
+# @three-ws/page-agent — Documentation
+
+A rigged 3D AI agent that talks your visitors through any web page. This is the
+full documentation. If you just want the elevator pitch and a one-line install,
+the [package README](../README.md) has it.
+
+> **New here?** Start with [Getting started](./getting-started.md). It takes ~5
+> minutes and assumes nothing.
+
+---
+
+## Learning path
+
+The docs are tiered. Pick your level — each guide links forward to the next.
+
+### 🟢 Basic — *"I want a guide on my site, today."*
+
+| Guide | What you'll learn |
+|-------|-------------------|
+| [Getting started](./getting-started.md) | Add the agent with one script tag. No build step, no framework, no account. |
+| [Narrating your page](./guide-narration.md) | Make the agent read the *right* things, in the *right* order, in your own words. |
+| [Troubleshooting & FAQ](./troubleshooting.md) | "No voice?" "Avatar won't load?" — the usual snags and their fixes. |
+
+### 🟡 Medium — *"I'm wiring this into a real app."*
+
+| Guide | What you'll learn |
+|-------|-------------------|
+| [Framework integration](./guide-frameworks.md) | Clean setup for React, Next.js, Vue, Svelte, Astro, and no-code (Webflow/WordPress). |
+| [Recipes](./recipes.md) | Copy-paste solutions: analytics, gated tours, multi-language, route-aware narration, and more. |
+| [API reference](./api-reference.md) | Every option, method, event, and type — the complete contract. |
+
+### 🔴 Advanced — *"I want to push it further."*
+
+| Guide | What you'll learn |
+|-------|-------------------|
+| [Custom avatars](./guide-custom-avatars.md) | Bring your own rigged GLB. Rigging, visemes, idle/talk clips, framing. |
+| [Building blocks](./guide-building-blocks.md) | Drop the default UI. Compose `AvatarStage`, `SpeechNarrator`, `AvatarPicker`, and the lipsync engine into your own experience. |
+| [Contributing](../CONTRIBUTING.md) | Add an agent, write a lipsync driver, ship a framework adapter — and the open roadmap of things worth building. |
+
+---
+
+## The three ways to use it
+
+Everything in these docs is one of three integration styles. They share the same
+engine; you can move between them as your needs grow.
+
+```
+┌─────────────────────────────────────────────────────────────────┐
+│ 1. Zero-JS script tag <script ... data-page-agent> │ 🟢 basic
+│ Drop one tag. Done. │
+├─────────────────────────────────────────────────────────────────┤
+│ 2. <page-agent> element <page-agent auto-narrate> │ 🟢 basic
+│ Declarative HTML. Methods + events on the element. │
+├─────────────────────────────────────────────────────────────────┤
+│ 3. new PageAgent(config) import { PageAgent } │ 🟡 medium
+│ Full programmatic control: narrate(), events, live swaps. │
+├─────────────────────────────────────────────────────────────────┤
+│ 4. Building blocks AvatarStage + SpeechNarrator + … │ 🔴 advanced
+│ Your own UI around the rendering/speech/lipsync engine. │
+└─────────────────────────────────────────────────────────────────┘
+```
+
+## Mental model in 30 seconds
+
+`PageAgent` is a thin controller that composes four pieces:
+
+```
+PageAgent ─┬─ AvatarStage three.js scene. Loads the rigged GLB, frames it
+ │ (bust/upper/full), keeps it alive with an idle
+ │ clip or procedural breathing + blink.
+ ├─ SpeechNarrator A speech queue on the Web Speech API. Picks a
+ │ voice per agent and drives lipsync on the frame loop.
+ ├─ AvatarPicker Accessible modal so the *visitor* chooses a guide.
+ └─ lipsync text → timed visemes → morph-target influences.
+```
+
+No backend, no API key, no audio files. Speech is the browser's
+`SpeechSynthesis`; lipsync is a deterministic text-to-viseme heuristic advanced
+on three.js's render loop. When speech is unavailable or muted, the avatar still
+"talks" visually and captions render — narration never silently stalls.
+
+## Requirements
+
+- A modern browser with WebGL. (Speech is best in Chrome/Edge/Safari; see
+ [Troubleshooting](./troubleshooting.md#speech) for the Firefox caveat.)
+- `three` >= 0.150 as a peer dependency **only** for the bundler/ESM path. The
+ CDN `/dist/page-agent.global.js` build inlines three, so the script-tag path
+ needs nothing.
+
+## Where the assets come from
+
+Avatars stream from the public three.ws asset host
+(`https://three.ws/avatars/*.glb`) by default — real, ready to use, no setup. To
+self-host, point [`assetBase`](./api-reference.md#config) (or an agent's `url`) at
+your own CDN. See [Custom avatars](./guide-custom-avatars.md).
+
+---
+
+Questions, bugs, ideas → [open an issue](https://github.com/nirholas/three.ws/issues)
+or read [CONTRIBUTING](../CONTRIBUTING.md). Part of the
+[three.ws](https://three.ws) platform for building, animating, rigging, and
+monetizing 3D AI agents.
diff --git a/page-agent-sdk/docs/getting-started.md b/page-agent-sdk/docs/getting-started.md
new file mode 100644
index 000000000..cc1c76e1d
--- /dev/null
+++ b/page-agent-sdk/docs/getting-started.md
@@ -0,0 +1,171 @@
+# Getting started 🟢
+
+**Goal:** put a talking 3D guide on a web page in about five minutes, with no
+build tools, no framework, and no account.
+
+If you can edit an HTML file, you can do this.
+
+---
+
+## Step 1 — Add one line
+
+Open the HTML file for any page and paste this just before the closing
+`</body>` tag:
+
+```html
+<script
+ src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent
+ data-avatar="nova"
+ data-auto-narrate
+ defer></script>
+```
+
+Save it. Open the page in your browser.
+
+That's the whole thing. A rigged avatar named **Nova** docks in the bottom-right
+corner and starts talking visitors through your page. A control bar lets them
+play/stop, mute, change the guide, or minimize it.
+
+> **What just happened?** The `data-page-agent` attribute tells the script to
+> auto-start. The other `data-*` attributes are its settings. The
+> `/dist/page-agent.global.js` build bundles everything it needs (including the
+> 3D engine), so there's nothing else to install.
+
+### Hear nothing?
+
+Browsers block audio until the visitor interacts with the page (a security rule —
+not a bug). Click anywhere, or click ▶ in the control bar. The avatar's mouth
+moves and captions show even before audio is allowed, so the guide never looks
+frozen. More in [Troubleshooting](./troubleshooting.md#speech).
+
+---
+
+## Step 2 — Make it say what you want
+
+By default the agent reads your page's headings and lead paragraphs. To control
+exactly what it says, add a `data-narrate` attribute to any element:
+
+```html
+<h1 data-narrate="Welcome! Let me show you around our new pricing page.">
+ Pricing
+</h1>
+
+<section data-narrate="Every plan includes unlimited projects and email support.">
+ …your normal content…
+</section>
+```
+
+When the agent walks the page, it speaks the `data-narrate` text for those
+elements (and highlights each one as it goes). Everything else is skipped. Full
+details in [Narrating your page](./guide-narration.md).
+
+---
+
+## Step 3 — Pick a different guide
+
+There are nine rigged guides. Swap `data-avatar` to any id:
+
+| id | who they are |
+|----|--------------|
+| `sol` | Calm, clear product guide *(default)* |
+| `nova` | Upbeat, friendly host |
+| `vera` | Composed, professional (British voice) |
+| `atlas` | Confident, grounded |
+| `echo` | Neutral, even-keeled |
+| `lumen` | Minimal studio presenter |
+| `kai` | Playful robot sidekick |
+| `mira` | Expressive, full-body |
+| `pax` | Laid-back explainer |
+
+Want to offer only a few in the visitor's picker? List them:
+
+```html
+<script
+ src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent
+ data-avatar="sol"
+ data-agents="sol,nova,kai"
+ data-auto-narrate
+ defer></script>
+```
+
+---
+
+## Step 4 — Position and behavior
+
+Every setting is a `data-*` attribute. The common ones:
+
+```html
+<script
+ src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent
+ data-avatar="vera"
+ data-position="bottom-left" <!-- bottom-right | bottom-left | top-right | top-left -->
+ data-greeting="Hi there — need a hand finding anything?"
+ data-collapsed <!-- start as a small pill the visitor can open -->
+ defer></script>
+```
+
+- `data-greeting="…"` — speak a single welcome line on load (instead of touring
+ the whole page).
+- `data-auto-narrate` — tour the page on load. Add a value to narrate only part
+ of it: `data-auto-narrate=".tour-section"` (a CSS selector).
+- `data-collapsed` — start minimized as an "Ask a guide" pill.
+- `data-muted` — start muted (the avatar still mouths the words + captions show).
+- `data-no-picker` — hide the "change guide" button.
+- `data-no-controls` — hide the whole control bar.
+
+The complete attribute list is in the [API reference](./api-reference.md#html-attributes).
+
+---
+
+## When you outgrow the script tag
+
+The script tag is perfect for static sites, landing pages, docs, and no-code
+builders. The moment you want to *react* to what the agent does — trigger
+narration on a button click, log which sections visitors heard, swap the guide
+based on the page — move up to the programmatic API:
+
+```html
+<script type="module">
+ import { PageAgent } from 'https://unpkg.com/@three-ws/page-agent/dist/page-agent.mjs';
+ // (note: the .mjs build needs `three` available — see the frameworks guide)
+
+ const guide = new PageAgent({ agent: 'atlas', autoNarrate: true });
+
+ guide.on('segment', ({ text, el }) => {
+ console.log('now reading:', text);
+ });
+
+ document.querySelector('#help').addEventListener('click', () => {
+ guide.narrate('Sure — this button saves your draft.', { interrupt: true });
+ });
+</script>
+```
+
+→ Continue with [Framework integration](./guide-frameworks.md) for a clean setup
+in React, Vue, Next, and friends, or the [API reference](./api-reference.md) for
+everything `PageAgent` can do.
+
+---
+
+## Cheat sheet
+
+```html
+<!-- Simplest possible -->
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent defer></script>
+
+<!-- Tour the page with a chosen guide, bottom-left -->
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent data-avatar="nova" data-position="bottom-left"
+ data-auto-narrate defer></script>
+
+<!-- Greet only, muted, start collapsed, no picker -->
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent data-greeting="Welcome back!" data-muted
+ data-collapsed data-no-picker defer></script>
+```
+
+Next: [Narrating your page →](./guide-narration.md)
diff --git a/page-agent-sdk/docs/guide-custom-avatars.md b/page-agent-sdk/docs/guide-custom-avatars.md
new file mode 100644
index 000000000..91fd0907f
--- /dev/null
+++ b/page-agent-sdk/docs/guide-custom-avatars.md
@@ -0,0 +1,166 @@
+# Custom avatars 🔴
+
+Every built-in guide is a **skeleton-rigged, lipsync-capable** glTF. This guide
+explains what that means, how to bring your own rig, and how to self-host the
+catalog.
+
+---
+
+## What makes a good page-agent avatar
+
+The runtime drives three things on your model every frame: **idle motion**,
+**blinking**, and **mouth/lipsync**. A model needs the right rig data for those
+to work — otherwise you get a frozen, dead-faced statue, which is exactly why the
+built-in catalog only ships verified rigs.
+
+Your GLB should have:
+
+| Feature | What the runtime looks for | If missing |
+|---------|----------------------------|------------|
+| **Skeleton** | A skinned mesh + armature (bones). | Required — no rig, no agent. |
+| **Idle clip** | An animation whose name contains `idle`, `breathing`, `stand`, or `rest` (else the first clip). | Falls back to **procedural** breathing + head sway. |
+| **Talk clip** | An animation named with `talk`, `talking`, `speak`, `gesture`, or `wave`. | Speaking still works via lipsync/head motion; just no body emphasis. |
+| **Visemes** | Oculus/ARKit morph targets: `viseme_aa`, `viseme_E`, `viseme_O`, `viseme_PP`, … (15 total). | Drops to jaw mode. |
+| **Jaw morph** | `jawOpen` or `mouthOpen` (used when no full visemes). | Drops to animation-only mouth. |
+| **Blink morphs** | `eyeBlinkLeft` / `eyeBlinkRight` / `eyesClosed` / `blink`. | No blinking. |
+| **Head bone** | A bone whose name matches `/head/i` (not `headtop`/`end`). | No procedural head sway/nod. |
+
+### The three lipsync tiers
+
+The runtime auto-detects which to use from the morph targets it finds:
+
+1. **`viseme`** *(best)* — the full ARKit set; phoneme-accurate mouth shapes.
+ This is what [Ready Player Me](https://readyplayer.me) and most ARKit
+ exporters produce.
+2. **`jaw`** — a single `jawOpen`/`mouthOpen` morph driven on a speech envelope.
+ Good enough to read as "talking."
+3. **animation** — no face morphs; the talk body clip + head motion carry the
+ speech (typical for Mixamo characters).
+
+> The full ARKit viseme list and detection logic live in
+> [`src/lipsync.js`](../src/lipsync.js) — read it if you're authoring a rig and
+> want to match the exact target names.
+
+---
+
+## Option A — Self-host the built-in catalog
+
+The simplest customization: keep the nine guides, but serve their GLBs from your
+own domain (for offline use, a CDN you control, or air-gapped deploys).
+
+Copy the avatar GLBs to your host, preserving the **filenames** the catalog
+expects (`realistic-halfbody.glb`, `selfie-girl.glb`, `xbot.glb`, …), then point
+`assetBase` at them:
+
+```js
+new PageAgent({ assetBase: 'https://cdn.example.com/guides/' });
+```
+
+```html
+<page-agent asset-base="https://cdn.example.com/guides/"></page-agent>
+```
+
+```js
+import { AGENTS } from '@three-ws/page-agent';
+// The exact filename each agent expects:
+AGENTS.forEach((a) => console.log(a.id, '→', a.file));
+```
+
+`assetBase` + `file` is how every default URL is built; an agent's optional
+absolute `url` overrides it entirely.
+
+---
+
+## Option B — Drive a single custom avatar yourself
+
+To render *your own* rigged character (not in the catalog) with full control over
+the UI, use the building blocks directly. `AvatarStage` will load any rigged GLB
+URL; `SpeechNarrator` speaks and lipsyncs against whatever morphs it finds:
+
+```js
+import { AvatarStage, SpeechNarrator } from '@three-ws/page-agent';
+
+const stage = new AvatarStage(document.querySelector('#guide'), { background: 'transparent' });
+await stage.load('/models/my-rigged-avatar.glb', { framing: 'upper' });
+
+const narrator = new SpeechNarrator(stage, {
+ onCaption: (t) => (captionEl.textContent = t || ''),
+});
+narrator.setAgent({
+ // a minimal RiggedAgent — voice is all the narrator needs
+ voice: { lang: 'en-US', rate: 1.0, pitch: 1.0, match: ['samantha', 'aria'] },
+});
+
+await narrator.speak('Hi — I'm a fully custom guide.');
+```
+
+This is the full advanced path — see [Building blocks](./guide-building-blocks.md)
+for the complete walkthrough (custom picker, your own control bar, render hooks).
+
+---
+
+## Verifying your rig
+
+Before shipping a custom GLB, confirm the runtime can drive it. `buildMorphMap`
+tells you which lipsync tier your model qualifies for:
+
+```js
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { buildMorphMap } from '@three-ws/page-agent';
+
+const gltf = await new GLTFLoader().loadAsync('/models/my-avatar.glb');
+const morph = buildMorphMap(gltf.scene);
+
+console.log('lipsync tier:', morph?.mode ?? 'animation (no face morphs)');
+console.log('clips:', gltf.animations.map((c) => c.name));
+```
+
+- `morph.mode === 'arkit'` → full visemes detected. 🎉
+- `morph.mode === 'jaw'` → only a jaw morph; consider adding visemes.
+- `null` → no mouth morphs; make sure you have a **talk** clip so speech reads.
+
+Checklist:
+
+- [ ] Loads in a [glTF viewer](https://gltf-viewer.donmccurdy.com/) without errors.
+- [ ] Has a skinned mesh + armature.
+- [ ] Has an `idle` (or first) clip that loops cleanly.
+- [ ] `buildMorphMap` returns `arkit` or `jaw` — **or** the model has a talk clip.
+- [ ] Reasonable poly/texture budget (these stream to every visitor).
+- [ ] Front-facing at the origin, feet near `y=0`, looking down +Z.
+
+---
+
+## Framing
+
+The camera crop is per-avatar. Choose what flatters your model:
+
+| `framing` | Crop | Use for |
+|-----------|------|---------|
+| `bust` | Head & shoulders | Realistic faces with great visemes. |
+| `upper` | Waist up | Most stylized characters. |
+| `full` | Whole body | Expressive/full-body talkers (robots, Mixamo). |
+
+```js
+await stage.load(url, { framing: 'full' });
+```
+
+---
+
+## Contributing an avatar to the catalog
+
+Want your rig to be one of the built-in guides everyone can pick by id? That's a
+welcome contribution. The catalog is a single, well-documented file
+([`src/catalog.js`](../src/catalog.js)), and adding an entry is a few lines plus
+a verified GLB. See **[CONTRIBUTING → Add an agent](../CONTRIBUTING.md#add-an-agent-to-the-catalog)**
+for the checklist (rig verification, voice profile, accent color, tests).
+
+> **Heads up:** the catalog is keyed into an internal lookup at module load, so
+> *runtime* mutation of the exported `AGENTS` array won't register a new id with
+> `setAgent()`. To add a guide to the picker the supported ways are: contribute
+> it to the catalog, or build your own roster with the
+> [building blocks](./guide-building-blocks.md).
+
+---
+
+Next: [Building blocks →](./guide-building-blocks.md) ·
+[Contributing →](../CONTRIBUTING.md)
diff --git a/page-agent-sdk/docs/guide-frameworks.md b/page-agent-sdk/docs/guide-frameworks.md
new file mode 100644
index 000000000..75285b9a1
--- /dev/null
+++ b/page-agent-sdk/docs/guide-frameworks.md
@@ -0,0 +1,247 @@
+# Framework integration 🟡
+
+Clean, production-ready setups for the common stacks. The golden rules:
+
+1. **`PageAgent` needs a browser.** Its constructor throws if `window` is
+ undefined, so never construct it during server-side rendering — build it in a
+ client-only effect/lifecycle hook.
+2. **The ESM build leaves `three` external.** Install it alongside:
+ ```bash
+ npm install @three-ws/page-agent three
+ ```
+ (The CDN `dist/page-agent.global.js` build inlines three and needs no install —
+ use that for no-code/script-tag setups.)
+3. **Always `dispose()` on unmount.** It tears down the WebGL context, speech
+ queue, and DOM. One agent at a time.
+
+---
+
+## React
+
+A reusable hook that owns the lifecycle:
+
+```jsx
+// usePageAgent.js
+import { useEffect, useRef, useState } from 'react';
+import { PageAgent } from '@three-ws/page-agent';
+
+export function usePageAgent(config = {}) {
+ const ref = useRef(null);
+ const [agent, setAgent] = useState(null);
+
+ useEffect(() => {
+ const guide = new PageAgent(config);
+ ref.current = guide;
+ setAgent(guide);
+ return () => { guide.dispose(); ref.current = null; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []); // construct once; change agents via methods, not re-render
+
+ return agent;
+}
+```
+
+```jsx
+// App.jsx
+import { usePageAgent } from './usePageAgent';
+
+export default function App() {
+ const guide = usePageAgent({ agent: 'sol', autoNarrate: true });
+
+ return (
+ <button onClick={() => guide?.narrate('This is the save button.', { interrupt: true })}>
+ Explain this
+ </button>
+ );
+}
+```
+
+> Construct **once** in an empty-dependency effect. To change the avatar or
+> narration later, call `guide.setAgent(id)` / `guide.narrate(...)` — don't tear
+> the instance down and rebuild it on every render.
+
+A published React wrapper also exists: [`@three-ws/react`](https://www.npmjs.com/package/@three-ws/react).
+
+---
+
+## Next.js (App Router)
+
+`PageAgent` is browser-only, so isolate it in a client component and construct it
+in `useEffect` (which never runs on the server):
+
+```jsx
+// components/Guide.jsx
+'use client';
+import { useEffect } from 'react';
+
+export default function Guide(props) {
+ useEffect(() => {
+ let guide;
+ // Dynamic import keeps the 3D engine out of the server bundle entirely.
+ import('@three-ws/page-agent').then(({ PageAgent }) => {
+ guide = new PageAgent({ agent: 'vera', autoNarrate: true, ...props });
+ });
+ return () => guide?.dispose();
+ }, []);
+ return null; // the agent docks itself to <body>
+}
+```
+
+```jsx
+// app/layout.jsx (or any page)
+import Guide from '@/components/Guide';
+export default function Layout({ children }) {
+ return (<>{children}<Guide /></>);
+}
+```
+
+Pages Router is the same idea — render `<Guide />` from a component and guard the
+constructor behind `useEffect`, or `next/dynamic` with `{ ssr: false }`.
+
+---
+
+## Vue 3
+
+```vue
+<script setup>
+import { onMounted, onBeforeUnmount } from 'vue';
+import { PageAgent } from '@three-ws/page-agent';
+
+let guide;
+onMounted(() => { guide = new PageAgent({ agent: 'nova', autoNarrate: true }); });
+onBeforeUnmount(() => guide?.dispose());
+
+defineExpose({ narrate: (t) => guide?.narrate(t, { interrupt: true }) });
+</script>
+
+<template><!-- the agent docks itself; nothing to render here --></template>
+```
+
+The `<page-agent>` custom element also works in Vue templates — tell Vue it's a
+custom element so it doesn't try to resolve it as a component:
+
+```js
+// vite.config.js
+export default {
+ plugins: [vue({ template: { compilerOptions: {
+ isCustomElement: (tag) => tag === 'page-agent',
+ }}})],
+};
+```
+
+```vue
+<script setup>import '@three-ws/page-agent';</script>
+<template><page-agent avatar="nova" auto-narrate /></template>
+```
+
+---
+
+## Svelte
+
+```svelte
+<script>
+ import { onMount } from 'svelte';
+ import { PageAgent } from '@three-ws/page-agent';
+
+ let guide;
+ onMount(() => {
+ guide = new PageAgent({ agent: 'atlas', autoNarrate: true });
+ return () => guide.dispose(); // onMount's return is the cleanup
+ });
+</script>
+```
+
+Custom-element form works too — Svelte passes unknown tags straight through:
+
+```svelte
+<script>import '@three-ws/page-agent';</script>
+<page-agent avatar="atlas" auto-narrate></page-agent>
+```
+
+---
+
+## Astro
+
+Astro ships zero JS by default, so opt in with a client directive. The
+script-tag/global build is the simplest path:
+
+```astro
+---
+// src/components/Guide.astro
+---
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent data-avatar="echo" data-auto-narrate defer is:inline></script>
+```
+
+Or, in a framework island (`client:only="react"`), use the React setup above.
+
+---
+
+## SolidJS / Qwik / Angular
+
+The pattern is identical everywhere: **construct in a client-only mount hook,
+`dispose()` in cleanup.**
+
+```js
+// Solid
+import { onMount, onCleanup } from 'solid-js';
+onMount(() => { const g = new PageAgent({ agent: 'pax' }); onCleanup(() => g.dispose()); });
+```
+
+For Angular, build it in `ngAfterViewInit` and dispose in `ngOnDestroy`; guard
+with `isPlatformBrowser` if you use Angular Universal (SSR).
+
+---
+
+## No-code & CMS (Webflow, WordPress, Framer, Shopify, etc.)
+
+Use the script-tag build — it needs no bundler and no `three` install. Paste it
+into the platform's "custom code / embed / footer scripts" slot:
+
+```html
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent data-avatar="nova" data-auto-narrate defer></script>
+```
+
+- **WordPress:** a "Custom HTML" block, or your theme's footer, or a headers-and-
+ footers plugin.
+- **Webflow:** Project Settings → Custom Code → Footer Code.
+- **Shopify:** `theme.liquid`, before `</body>`.
+
+Pin a version for stability (e.g. `@three-ws/[email protected]/dist/...`) so a
+future release can't change behavior under you.
+
+---
+
+## TypeScript
+
+Types ship in the package — no `@types/...` needed. Everything is exported:
+
+```ts
+import { PageAgent, type PageAgentConfig, type RiggedAgent } from '@three-ws/page-agent';
+
+const config: PageAgentConfig = { agent: 'sol', autoNarrate: true };
+const guide = new PageAgent(config);
+const current: RiggedAgent | null = guide.currentAgent;
+```
+
+For the `<page-agent>` element in JSX, declare it once:
+
+```ts
+// page-agent.d.ts
+import type { PageAgentElement } from '@three-ws/page-agent';
+declare global {
+ namespace JSX {
+ interface IntrinsicElements {
+ 'page-agent': React.DetailedHTMLProps<React.HTMLAttributes<PageAgentElement>, PageAgentElement>
+ & { avatar?: string; position?: string; 'auto-narrate'?: boolean | string };
+ }
+ }
+}
+```
+
+---
+
+Next: [API reference →](./api-reference.md) ·
+[Custom avatars →](./guide-custom-avatars.md) ·
+[Recipes →](./recipes.md)
diff --git a/page-agent-sdk/docs/guide-narration.md b/page-agent-sdk/docs/guide-narration.md
new file mode 100644
index 000000000..5eceea85e
--- /dev/null
+++ b/page-agent-sdk/docs/guide-narration.md
@@ -0,0 +1,185 @@
+# Narrating your page 🟢→🟡
+
+The agent's superpower is *talking visitors through your page*. This guide covers
+exactly what it reads, how to control it, and how to script richer tours.
+
+---
+
+## Two kinds of speech
+
+| Method | What it does |
+|--------|--------------|
+| `narrate(text)` | Speak **one line** you provide. |
+| `narratePage()` | **Walk the page** — speak each content segment in order, highlighting and scrolling to each one. |
+
+The script-tag / element `auto-narrate` setting calls `narratePage()` on load.
+`greeting` calls `narrate()` once.
+
+---
+
+## What `narratePage()` reads
+
+When the agent tours the page, it builds an ordered list of *segments*. It picks
+the **first** of these sources that yields anything:
+
+1. **Your selector** — elements matching the CSS selector you pass
+ (`narratePage({ selector: '.tour' })` or `auto-narrate=".tour"`).
+2. **`[data-narrate]` elements** — anything you've explicitly tagged.
+3. **Heading fallback** — visible `h1`/`h2`/`h3` inside `main`/`article` (then
+ page-wide `h1`/`h2`), each paired with its following lead paragraph.
+
+A few rules worth knowing:
+
+- Each segment's spoken text is trimmed and **capped at 600 characters** — keep
+ tagged blocks tight, or split them.
+- The heading fallback stops after **12 segments** so an untagged page doesn't
+ turn into a monologue. Tag your content to go beyond that.
+- Hidden elements (`display:none`, `visibility:hidden`, zero-size) are skipped.
+
+---
+
+## Marking up a guided page
+
+### Speak custom copy for an element
+
+Put the words in the attribute. The element's *visible* text stays whatever it
+was — `data-narrate` is what gets **spoken**:
+
+```html
+<h1 data-narrate="Welcome to the dashboard — here's where your day starts.">
+ Dashboard
+</h1>
+```
+
+### Tag a block to read its own text
+
+An empty `data-narrate` means "read this element's text content":
+
+```html
+<section data-narrate>
+ Your trial includes every feature. No credit card until you're ready.
+</section>
+```
+
+### Control the order
+
+By default tagged elements are read in DOM order. Override with
+`data-narrate-order` (lower numbers first):
+
+```html
+<div data-narrate data-narrate-order="2">Second.</div>
+<div data-narrate data-narrate-order="1">First, even though it's lower in the page.</div>
+```
+
+### Scope a tour to one region
+
+Pass a selector so only part of the page is toured:
+
+```html
+<page-agent avatar="sol" auto-narrate=".product-tour"></page-agent>
+```
+
+```js
+guide.narratePage({ selector: '.product-tour > *' });
+```
+
+---
+
+## Greeting first
+
+`narratePage({ greet: true })` speaks the agent's persona line before the page
+walk — a natural "Hi, I'm Nova, let me show you around." `auto-narrate` does this
+for you. To use your own greeting instead, call `narrate()` first, then tour:
+
+```js
+const guide = new PageAgent({ agent: 'nova' });
+guide.on('ready', async () => {
+ await guide.narrate('Welcome back, friend!');
+ guide.narratePage(); // greet:false — your line already played
+});
+```
+
+---
+
+## Driving narration from your app
+
+`narrate()` and `narratePage()` return promises that resolve when speech
+finishes, so you can sequence them:
+
+```js
+await guide.narrate('First, connect your wallet.');
+await guide.narrate('Now pick a network.');
+guide.narrate('Done — you're ready to trade.');
+```
+
+Use `{ interrupt: true }` to cut off whatever's playing and speak immediately
+(great for click handlers):
+
+```js
+helpButton.addEventListener('click', () => {
+ guide.narrate('This saves your draft without publishing.', { interrupt: true });
+});
+```
+
+Stop everything with `guide.stop()`.
+
+---
+
+## React to the tour with events
+
+```js
+guide
+ .on('segment', ({ text, el }) => {
+ // Fired as each segment begins. `el` is the DOM node being read.
+ el.classList.add('being-read');
+ })
+ .on('caption', (text) => {
+ // The live caption string, or null when speech ends.
+ })
+ .on('state', (s) => {
+ document.body.dataset.guideSpeaking = s === 'speaking';
+ });
+```
+
+On the `<page-agent>` element the same events arrive as DOM `CustomEvent`s:
+
+```js
+document.querySelector('page-agent')
+ .addEventListener('page-agent:segment', (e) => console.log(e.detail.text));
+```
+
+The agent already outlines the current segment in the active guide's accent
+color and smooth-scrolls it into view — you usually don't need to do anything for
+a polished tour.
+
+---
+
+## Patterns
+
+**A short, scripted welcome instead of a full read:**
+
+```html
+<page-agent avatar="sol" greeting="Hey! New here? Hit the tour button anytime."></page-agent>
+```
+
+**A "Take the tour" button that starts the walk on demand:**
+
+```js
+tourBtn.addEventListener('click', () => guide.narratePage({ greet: true }));
+```
+
+**Route-aware narration in a SPA** — re-tour when the view changes:
+
+```js
+router.afterEach(() => {
+ guide.stop();
+ guide.narratePage({ selector: '[data-view] [data-narrate]' });
+});
+```
+
+More of these in the [Recipes cookbook](./recipes.md).
+
+---
+
+Next: [Framework integration →](./guide-frameworks.md) ·
+[API reference →](./api-reference.md)
diff --git a/page-agent-sdk/package.json b/page-agent-sdk/package.json
index 782f3f779..5e279ac7b 100644
--- a/page-agent-sdk/package.json
+++ b/page-agent-sdk/package.json
@@ -50,7 +50,9 @@
"./style.css": "./dist/page-agent.css"
},
"files": [
- "dist",
+ "dist/page-agent.mjs",
+ "dist/page-agent.global.js",
+ "dist/page-agent.css",
"src",
"types",
"README.md",
diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.html
index 135a4eabf..39fed35f2 100644
--- a/pages/ibm/x402-demo.html
+++ b/pages/ibm/x402-demo.html
@@ -540,7 +540,7 @@ agent-3d:defined ~ .agent-skel{display:none}
</div>
<button id="fgBtn" class="btn" type="button"><span class="spin" aria-hidden="true"></span><span class="label">Pay $0.05 &amp; forge</span> <span class="arrow" aria-hidden="true">→</span></button>
</div>
- <div class="wallet-hint" id="fgWalletHint">On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.</div>
+ <div class="wallet-hint" id="fgWalletHint">On a phone? Open this page inside your <b>Phantom</b> wallet's in-app browser to pay.</div>
<!-- result. Not a live region (its success state holds a raw-JSON block);
concise spoken updates go to #fgAnnouncer instead. -->
@@ -552,7 +552,7 @@ agent-3d:defined ~ .agent-skel{display:none}
<!-- requirements -->
<div class="note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
- <p>You'll need a browser wallet — <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) — holding the model's price in <b>USDC</b> on mainnet. This spends <b>real USDC</b> — the price shown above — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost. Generation runs once the payment verifies and takes roughly a minute. No wallet? Use the <a href="https://three.ws/forge" target="_blank" rel="noopener">free Forge tool</a> instead.</p>
+ <p>You'll need the <b>Phantom</b> wallet on <b>Solana</b> — holding the model's price in <b>USDC</b> on Solana mainnet. This spends <b>real USDC</b> — the price shown above — from your own wallet. The payment itself is a gasless signature: the network fee is sponsored by the x402 facilitator, so it isn't added to your cost. Generation runs once the payment verifies and takes roughly a minute. No wallet? Forge one <b>free</b> below — no wallet, no key, no payment.</p>
</div>
</div>
</div>
diff --git a/public/changelog.json b/public/changelog.json
index 92e067077..e1e537ea7 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:11:07.149Z",
+ "generated_at": "2026-06-19T22:13:29.951Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -250,6 +250,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Forge a 3D model on the IBM x402 demo — free, no wallet",
+ "summary": "The IBM × three.ws x402 demo now forges 3D models two ways. The paid Forge takes one USDC micropayment from your own wallet and settles on Solana; right below it, a free generator turns any sentence into a textured, downloadable GLB with no wallet, no API key and no payment — it runs Microsoft TRELLIS on NVIDIA NIM with automatic fallback across lanes so a model always comes back. The paid Forge now settles in USDC on Solana mainnet.",
+ "link": "/ibm/x402-demo",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index c14a96c80..9a1929896 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -198,6 +198,14 @@
<category>feature</category>
<description>A playable demo just landed at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard, which refreshes live every 15 seconds and highlights your entry. Consider it a taste: these arcade demos are warm-ups while we build something far bigger for $THREE.</description>
</item>
+ <item>
+ <title>Forge a 3D model on the IBM x402 demo — free, no wallet</title>
+ <link>https://three.ws/ibm/x402-demo</link>
+ <guid isPermaLink="false">2026-06-19:Forge a 3D model on the IBM x402 demo — free, no wallet</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The IBM × three.ws x402 demo now forges 3D models two ways. The paid Forge takes one USDC micropayment from your own wallet and settles on Solana; right below it, a free generator turns any sentence into a textured, downloadable GLB with no wallet, no API key and no payment — it runs Microsoft TRELLIS on NVIDIA NIM with automatic fallback across lanes so a model always comes back. The paid Forge now settles in USDC on Solana mainnet.</description>
+ </item>
<item>
<title>Freeze your agent wallet in one tap — plus hardened custody security</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index bf1670d28..fe7a3fb0f 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:11:07.110Z",
+ "generated_at": "2026-06-19T22:13:29.930Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/backfill-rig-meta.mjs b/scripts/backfill-rig-meta.mjs
new file mode 100644
index 000000000..46c77ed7a
--- /dev/null
+++ b/scripts/backfill-rig-meta.mjs
@@ -0,0 +1,151 @@
+#!/usr/bin/env node
+// Backfill the rig classifier signal (source_meta.is_rigged + skeleton stats)
+// for avatars that predate the classifier or were direct uploads — i.e. any row
+// whose source_meta never recorded whether the GLB carries a skeleton.
+//
+// The gallery's Rig filter, per-card "Rigged / Not rigged" badge, and "Rigged
+// first" sort all read source_meta via the shared classifier
+// (src/shared/rig-classify.js). New uploads now self-classify at create time
+// (api/avatars/index.js → handleCreate); this script lights up the existing
+// catalog the same way.
+//
+// Uses the exact same access layer the API uses (api/_lib/db.js +
+// api/_lib/rig-inspect.js), so what this writes is precisely what the gallery
+// reads. Only the GLB's glTF JSON chunk is read via a ranged request — never the
+// mesh binary — so a large catalog is cheap to scan.
+//
+// Safety properties:
+// • Idempotent + resume-safe — only rows missing source_meta.is_rigged are
+// touched; a re-run after a crash continues where it left off.
+// • Throttled — bounded concurrency via a simple per-row delay.
+// • --dry-run prints what would change and writes NOTHING.
+// • Fail-open per row — an unreadable / non-GLB object is left untouched
+// (stays "unknown") and the run continues.
+//
+// Usage:
+// node scripts/backfill-rig-meta.mjs --dry-run
+// node scripts/backfill-rig-meta.mjs [--limit 1000] [--throttle-ms 50]
+//
+// Requires DATABASE_URL (+ S3/R2 credentials for bucket-backed objects) from
+// .env.local / .env / the environment.
+
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const root = resolve(__dirname, '..');
+
+function loadEnvFile(path) {
+ let raw;
+ try {
+ raw = readFileSync(path, 'utf8');
+ } catch {
+ return;
+ }
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
+ if (!m) continue;
+ const [, k, v] = m;
+ if (process.env[k]) continue;
+ process.env[k] = v.replace(/^["']|["']$/g, '');
+ }
+}
+
+function parseArgs(argv) {
+ const get = (name, dflt) => {
+ const hit = argv.find((a) => a === `--${name}` || a.startsWith(`--${name}=`));
+ if (!hit) return dflt;
+ if (hit === `--${name}`) return true;
+ return hit.split('=').slice(1).join('=');
+ };
+ return {
+ dryRun: get('dry-run', false) === true,
+ limit: Number(get('limit', 1000)) || 1000,
+ throttleMs: Number(get('throttle-ms', 50)) || 50,
+ };
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function main() {
+ loadEnvFile(resolve(root, '.env.local'));
+ loadEnvFile(resolve(root, '.env'));
+
+ const args = parseArgs(process.argv.slice(2));
+
+ if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is required.');
+ process.exit(1);
+ }
+
+ const { sql } = await import(pathToFileURL(resolve(root, 'api/_lib/db.js')));
+ const { inspectStorageKeyRig } = await import(
+ pathToFileURL(resolve(root, 'api/_lib/rig-inspect.js'))
+ );
+
+ // Rows never skeleton-inspected: no is_rigged key in source_meta. A positive
+ // skeleton_joint_count without the flag is already classified rigged, so it
+ // doesn't need a backfill — the `is_rigged` key absence is the precise signal.
+ const rows = await sql`
+ select id, name, storage_key
+ from avatars
+ where deleted_at is null
+ and storage_key is not null
+ and (source_meta is null or not (source_meta ? 'is_rigged'))
+ order by created_at desc
+ limit ${args.limit}
+ `;
+
+ console.log(
+ `Found ${rows.length} avatar(s) without a rig signal (limit ${args.limit}).`,
+ );
+ if (rows.length === 0) return;
+
+ if (args.dryRun) {
+ for (const r of rows.slice(0, 20)) {
+ console.log(` would inspect: ${r.id} "${r.name}" (${r.storage_key})`);
+ }
+ if (rows.length > 20) console.log(` …and ${rows.length - 20} more`);
+ console.log('\nDry run — nothing written. Re-run without --dry-run to apply.');
+ return;
+ }
+
+ let rigged = 0;
+ let staticCount = 0;
+ let skipped = 0;
+ for (const r of rows) {
+ let rig = null;
+ try {
+ rig = await inspectStorageKeyRig(r.storage_key);
+ } catch (e) {
+ console.warn(` ! ${r.id} inspect error: ${e?.message}`);
+ }
+ if (rig) {
+ // Merge so any other source_meta fields are preserved.
+ await sql`
+ update avatars
+ set source_meta = coalesce(source_meta, '{}'::jsonb) || ${JSON.stringify(rig)}::jsonb
+ where id = ${r.id}
+ `;
+ if (rig.is_rigged) rigged++;
+ else staticCount++;
+ console.log(
+ ` ✓ ${r.id} ${rig.is_rigged ? 'RIGGED' : 'static'} (${rig.skeleton_joint_count} joints) "${r.name}"`,
+ );
+ } else {
+ skipped++;
+ console.log(` · ${r.id} left unknown (not a readable GLB)`);
+ }
+ await sleep(args.throttleMs);
+ }
+
+ console.log(
+ `\nDone. ${rigged} rigged, ${staticCount} static, ${skipped} left unknown, ${rows.length} processed.`,
+ );
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/src/club-entrance.js b/src/club-entrance.js
index 21c3685d7..9249b8e32 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -25,6 +25,7 @@ import {
Box3,
BoxGeometry,
Color,
+ DoubleSide,
Fog,
Group,
HemisphereLight,
@@ -106,6 +107,16 @@ const DOOR_RANGE = 2.6; // how close you stand before the prompt shows
const CAM_DIST = 3.6;
const CAM_HEIGHT = 1.55;
const HEAD_Y = 1.2;
+// Camera-wall collision: keep this much clearance in front of any wall the
+// camera backs into. A fat skin matters because the near plane is small (0.08)
+// — at a thin standoff a wall pokes through the lens and the frame fills with
+// the wall's interior. CAM_MIN_DIST is only a floor so the camera never
+// collapses onto the avatar's head; it is deliberately small, NOT a comfortable
+// resting distance — clamping it up would shove the camera through any wall
+// closer than the floor. Walls closer than this are caught by the double-sided
+// env materials, which render solid from the inside instead of see-through.
+const CAM_WALL_SKIN = 0.4;
+const CAM_MIN_DIST = 0.5;
const ARRIVE = 0.9; // final fade (seconds) that reveals the pole stage
@@ -194,7 +205,7 @@ async function start(canvasEl) {
scene.background = new Color(0x05030a);
scene.fog = new Fog(0x05030a, 8, 34);
- const camera = new PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.05, 200);
+ const camera = new PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.08, 200);
// ── Light rig — moody, works for the alley and the interior ──────────────
// Keeps the noir palette but lifts the ambient/hemisphere floor so walls read
@@ -948,24 +959,52 @@ async function start(canvasEl) {
anim.crossfadeTo('walk', 0.2).catch(() => {});
}
+ // Distance from `target` at which the line of sight to the camera first hits a
+ // wall, or `fallback` when the path is clear. Shared by the desired-position
+ // solve and the post-lerp safety clamp so both use identical collision logic.
+ function wallClearance(target, dir, maxDist, fallback) {
+ camRay.set(target, dir);
+ camRay.far = maxDist;
+ const hit = camRay.intersectObject(env.root, true)[0];
+ if (!hit) return fallback;
+ return clamp(hit.distance - CAM_WALL_SKIN, CAM_MIN_DIST, maxDist);
+ }
+
function updateCamera(dt) {
const cosP = Math.cos(camPitch);
const off = new Vector3(Math.sin(camYaw) * cosP, Math.sin(camPitch), Math.cos(camYaw) * cosP);
const target = new Vector3(rig.position.x, rig.position.y + HEAD_Y, rig.position.z);
const desired = target.clone().addScaledVector(off, CAM_DIST);
desired.y = rig.position.y + CAM_HEIGHT + Math.sin(camPitch) * CAM_DIST;
- // Pull the camera in front of any wall between it and the avatar, so you
- // never see through walls or end up buried in geometry (a black frame).
+
+ // Pull the ideal position in front of any wall between it and the avatar,
+ // so the resting framing never buries the camera in geometry.
const toCam = desired.clone().sub(target);
const dist = toCam.length();
if (dist > 1e-3) {
- camRay.set(target, toCam.multiplyScalar(1 / dist));
- camRay.far = dist;
- const hit = camRay.intersectObject(env.root, true)[0];
- if (hit) desired.copy(target).addScaledVector(camRay.ray.direction, Math.max(0.5, hit.distance - 0.2));
+ const dir = toCam.multiplyScalar(1 / dist);
+ const clear = wallClearance(target, dir, dist, dist);
+ if (clear < dist) desired.copy(target).addScaledVector(dir, clear);
}
+
const a = 1 - Math.exp(-9 * dt);
camera.position.lerp(desired, a);
+
+ // Safety clamp on the *actual* (post-lerp) position. The smoothed camera
+ // lags the avatar, so during a fast turn or a step into a corner it can
+ // drift through a wall a frame before the lerp catches up — that's the
+ // flash of see-through brown geometry. Re-cast from the head to wherever
+ // the camera really is and hard-snap it in front of any wall it crossed.
+ // A hard snap (not a lerp) guarantees no frame is ever rendered from
+ // behind a wall.
+ const actual = camera.position.clone().sub(target);
+ const aDist = actual.length();
+ if (aDist > 1e-3) {
+ const dir = actual.multiplyScalar(1 / aDist);
+ const clear = wallClearance(target, dir, aDist, aDist);
+ if (clear < aDist) camera.position.copy(target).addScaledVector(dir, clear);
+ }
+
camera.lookAt(target);
}
@@ -1075,6 +1114,21 @@ function setJourneyStep(i) {
// recentre on the floor at the origin, add it, and return its box + the
// movement bounds (a margin inside the footprint so you don't clip walls).
function mountEnvironment(scene, root) {
+ // Render the walls solid from both faces. These venue GLBs export single-sided
+ // (FrontSide) walls, so the instant the chase camera grazes or dips behind a
+ // building face the front faces cull away and you see straight through the
+ // alley to the backfaces of the far walls — the geometry reads as abstract
+ // brown shards rather than a room. DoubleSide keeps every surface opaque from
+ // either side, so a tight camera angle can never punch a hole in the alley.
+ root.traverse((n) => {
+ if (!n.isMesh) return;
+ n.frustumCulled = true;
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) {
+ if (m) m.side = DoubleSide;
+ }
+ });
+
const box = new Box3().setFromObject(root);
const size = box.getSize(new Vector3());
root.scale.setScalar(ROOM_HEIGHT / (size.y || 1));
diff --git a/src/walk-companion.js b/src/walk-companion.js
index aa23fb62c..016c3fc3e 100644
--- a/src/walk-companion.js
+++ b/src/walk-companion.js
@@ -1,829 +1,30 @@
-// Site-wide Walk Companion
-// =========================
-// A persistent 3D avatar mascot that idles in the corner of every standard
-// three.ws page, turns to follow your cursor, waves when you navigate between
-// pages, and greets you with a page-aware tip. Opt-in: toggled from the nav
-// "Walk" button or with ?walk=1, and remembered across page loads via
-// localStorage (`walk:companion:enabled`).
+// Site-wide Walk Companion — three.ws integration entry.
+// ======================================================
+// The companion/playground engine now lives in the publishable SDK at
+// walk-sdk/ (@three-ws/walk). This file is the thin three.ws wiring: it builds
+// the platform-specific config, exposes the window API public/nav.js expects,
+// and kicks off the app's auto-mount/deep-link behaviour.
//
-// Delivery mirrors /footer-bot.js: this file is a Vite-bundled ES module
-// emitted to the stable, unhashed path /walk-companion.js (see
-// vite.config.js → rollupOptions.output.entryFileNames), and public/nav.js
-// injects it with <script type="module" src="/walk-companion.js"> only when the
-// companion is enabled — so there is zero footprint (no Three.js fetch) when
-// it's off.
-//
-// Motion reuses the same building blocks as the rest of the platform: the
-// default mascot is the shared RobotExpressive rig (also used by the footer
-// bot) with its embedded Idle / Walking / Wave clips, and a ?avatar=<id>
-// override loads that avatar's GLB and drives it with the retargeted shared
-// clip library via AnimationManager — the exact flow src/walk-embed.js uses.
-
-import {
- AmbientLight,
- AnimationMixer,
- Box3,
- Timer,
- DirectionalLight,
- Group,
- HemisphereLight,
- LoopOnce,
- LoopRepeat,
- PerspectiveCamera,
- Scene,
- Vector3,
- WebGLRenderer,
-} from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { AnimationManager } from './animation-manager.js';
-import { getMeshoptDecoder } from './viewer/internal.js';
-import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
-import { log } from './shared/log.js';
-
-// ── Config ──────────────────────────────────────────────────────────────────
-const ENABLED_KEY = 'walk:companion:enabled';
-const STATE_KEY = 'walk:companion:state';
-const AVATAR_KEY = 'walk:companion:avatar';
-const GREET_KEY = 'walk:companion:greet'; // sessionStorage flag set on internal nav
-const INVITE_KEY = 'walk:companion:invited'; // sessionStorage: showed the "click to walk" tip
-const ROBOT_URL = '/animations/robotexpressive.glb';
-const MANIFEST_URL = '/animations/manifest.json';
-
-// Retargeted shared-library clip names for the ?avatar= path (verified present
-// in /animations/manifest.json + /animations/clips/*.json).
-const AVATAR_CLIPS = { idle: 'idle', walk: 'av-walk-feminine', wave: 'wave' };
-
-const CANVAS_W = 200;
-const CANVAS_H = 280;
-const WAVE_MS = 1500;
-const CURSOR_IDLE_MS = 450; // cursor still longer than this → stop walking
-
-// Routes that already own the viewport with their own 3D / full-screen
-// experience, where a corner mascot would be redundant or intrusive.
-const EXCLUDED_PREFIXES = [
- '/walk',
- '/walk-embed',
- '/embed',
- '/play',
- '/club',
- '/city',
- '/xr',
- '/ar',
- '/pose',
- '/mocap-studio',
- '/avatar-studio',
-];
-
-// ── Small storage helpers (private-mode safe) ───────────────────────────────
-function lsGet(key) {
- try {
- return localStorage.getItem(key);
- } catch {
- return null;
- }
-}
-function lsSet(key, val) {
- try {
- localStorage.setItem(key, val);
- } catch {
- /* private mode / disabled storage — non-fatal */
- }
-}
-function ssGet(key) {
- try {
- return sessionStorage.getItem(key);
- } catch {
- return null;
- }
-}
-function ssSet(key, val) {
- try {
- sessionStorage.setItem(key, val);
- } catch {
- /* non-fatal */
- }
-}
-function ssDel(key) {
- try {
- sessionStorage.removeItem(key);
- } catch {
- /* non-fatal */
- }
-}
-
-function prefersReducedMotion() {
- try {
- return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
- } catch {
- return false;
- }
-}
-
-function isExcludedRoute() {
- if (window.top !== window.self) return true; // never inside an iframe/embed
- const path = location.pathname.replace(/\/$/, '') || '/';
- return EXCLUDED_PREFIXES.some((p) => path === p || path.startsWith(p + '/'));
-}
-
-// ── Page-context greeting ───────────────────────────────────────────────────
-// Real DOM reads, not canned data: the agent/avatar name comes from the page's
-// own heading; the pricing/features tips reference what's actually on screen.
-function contextGreeting() {
- const path = location.pathname.replace(/\/$/, '') || '/';
- if (path === '/pricing' || path === '/x-pricing') {
- return 'Picking a plan? I can point you to the popular one.';
- }
- if (path === '/features') {
- return 'Tap any feature card to see it in action.';
- }
- if (path.startsWith('/agent') || path.startsWith('/a/') || path.startsWith('/marketplace')) {
- const name = pageSubjectName();
- return name ? `Say hi to ${name}!` : 'Browse agents — I’ll tag along.';
- }
- if (path === '/' || path.startsWith('/home')) {
- return 'Hey! I’m your guide. I’ll walk with you.';
- }
- return 'I’ll walk along while you explore.';
-}
-
-function pageSubjectName() {
- const el = document.querySelector('[data-agent-name], .agent-name, h1');
- const txt = el?.textContent?.trim();
- if (!txt || txt.length > 40) return null;
- return txt;
-}
-
-// Element the avatar should orient toward for the current route, if present.
-function contextTargetEl() {
- const path = location.pathname.replace(/\/$/, '') || '/';
- if (path === '/pricing' || path === '/x-pricing') {
- return document.querySelector(
- '[data-recommended], .pricing-card.is-featured, .plan.is-popular, .pricing-card--popular',
- );
- }
- if (path === '/features') {
- return document.querySelector('.feature-card, [data-feature]');
- }
- return null;
-}
-
-// ── Motion controllers ──────────────────────────────────────────────────────
-// Both controllers expose the same interface: setBase('idle'|'walk'),
-// playWave(), update(dt), dispose(). The companion logic never branches on
-// which rig is loaded.
-
-function makeMixerController(root, clips) {
- const mixer = new AnimationMixer(root);
- const byName = (name) =>
- clips.find((c) => c.name.toLowerCase() === name.toLowerCase());
- const pick = (candidates) => {
- for (const n of candidates) {
- const c = byName(n);
- if (c) return c;
- }
- return clips[0] || null;
- };
-
- const map = {
- idle: pick(['Idle', 'idle']),
- walk: pick(['Walking', 'Walk', 'walk']),
- wave: pick(['Wave', 'wave']),
- };
- const action = {};
- for (const [state, clip] of Object.entries(map)) {
- if (!clip) continue;
- const a = mixer.clipAction(clip);
- a.enabled = true;
- action[state] = a;
- }
-
- let base = 'idle';
- let current = null;
- let waving = false;
-
- function crossfade(next, { once = false } = {}) {
- const a = action[next] || action.idle;
- if (!a) return;
- a.reset();
- a.setLoop(once ? LoopOnce : LoopRepeat, once ? 1 : Infinity);
- a.clampWhenFinished = once;
- a.fadeIn(0.3).play();
- if (current && current !== a) current.fadeOut(0.3);
- current = a;
- }
-
- mixer.addEventListener('finished', () => {
- if (waving) {
- waving = false;
- crossfade(base);
- }
- });
-
- crossfade('idle');
-
- return {
- setBase(next) {
- if (next === base) return;
- base = next;
- if (!waving) crossfade(base);
- },
- playWave() {
- if (!action.wave || waving) return;
- waving = true;
- crossfade('wave', { once: true });
- },
- update(dt) {
- mixer.update(dt);
- },
- dispose() {
- mixer.stopAllAction();
- mixer.uncacheRoot(root);
- },
- };
-}
-
-function makeManagerController(manager, baseClipName) {
- let base = 'idle';
- let waveTimer = null;
- // crossfadeTo is async (it lazy-loads the clip); the clips are preloaded via
- // loadAll() so these won't reject in practice, but swallow to be safe.
- const fade = (name, dur) => Promise.resolve(manager.crossfadeTo(name, dur)).catch(() => {});
-
- fade(AVATAR_CLIPS.idle, 0.0);
-
- function targetClip(state) {
- return state === 'walk' ? baseClipName : AVATAR_CLIPS.idle;
- }
-
- return {
- setBase(next) {
- if (next === base) return;
- base = next;
- if (!waveTimer) fade(targetClip(base), 0.3);
- },
- playWave() {
- if (waveTimer) return;
- fade(AVATAR_CLIPS.wave, 0.25);
- waveTimer = setTimeout(() => {
- waveTimer = null;
- fade(targetClip(base), 0.3);
- }, WAVE_MS);
- },
- update(dt) {
- manager.update(dt);
- },
- dispose() {
- clearTimeout(waveTimer);
- manager.dispose();
- },
- };
-}
-
-// ── The companion instance ──────────────────────────────────────────────────
-class WalkCompanion {
- constructor() {
- this.mounted = false;
- this.host = null;
- this.renderer = null;
- this.scene = null;
- this.camera = null;
- this.rig = null;
- this.controller = null;
- this.clock = null;
- this._raf = 0;
- this._reduced = prefersReducedMotion();
-
- // Cursor tracking (page coordinates), updated by a passive listener.
- this._cursorX = window.innerWidth * 0.5;
- this._cursorMovedAt = 0;
- this._yaw = 0;
- this._targetYaw = 0;
- this._onPointerMove = this._onPointerMove.bind(this);
- this._onLinkClick = this._onLinkClick.bind(this);
- this._onVisibility = this._onVisibility.bind(this);
- this._onPageHide = this._onPageHide.bind(this);
- this._tick = this._tick.bind(this);
- }
-
- async mount() {
- if (this.mounted || isExcludedRoute()) return;
- if (!this._webglSupported()) return;
- this.mounted = true;
-
- this._buildDom();
-
- try {
- await this._buildScene();
- } catch (err) {
- log.warn('[walk-companion] failed to load avatar:', err?.message || err);
- this._teardownScene();
- this._showError();
- return;
- }
-
- this._restoreState();
- this._bindEvents();
- this._greetForRoute();
- this.clock = new Timer();
- this._raf = requestAnimationFrame(this._tick);
- }
-
- unmount() {
- if (!this.mounted) return;
- this.mounted = false;
- cancelAnimationFrame(this._raf);
- this._raf = 0;
-
- window.removeEventListener('pointermove', this._onPointerMove);
- document.removeEventListener('click', this._onLinkClick, true);
- document.removeEventListener('visibilitychange', this._onVisibility);
- window.removeEventListener('pagehide', this._onPageHide);
-
- this._teardownScene();
- if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
- this.host = null;
- }
-
- // ── DOM / styles ────────────────────────────────────────────────────────
- _buildDom() {
- ensureStyles();
- const host = document.createElement('div');
- host.className = 'walk-companion';
- host.setAttribute('role', 'complementary');
- host.setAttribute('aria-label', 'Walk companion');
- host.innerHTML = `
- <button type="button" class="walk-companion-close" aria-label="Dismiss walk companion" title="Dismiss">×</button>
- <div class="walk-companion-bubble" hidden></div>
- <canvas class="walk-companion-canvas" width="${CANVAS_W}" height="${CANVAS_H}"></canvas>
- `;
- document.body.appendChild(host);
- this.host = host;
- this.canvas = host.querySelector('.walk-companion-canvas');
- this.bubble = host.querySelector('.walk-companion-bubble');
- host.querySelector('.walk-companion-close').addEventListener('click', (e) => {
- e.stopPropagation();
- disable();
- });
- // Clicking the avatar detaches it from the corner into Playground mode —
- // it walks out of this exact spot and roams the page. The corner companion
- // returns automatically when the playground is exited.
- this.canvas.addEventListener('click', () => detachToPlayground(this));
- requestAnimationFrame(() => host.classList.add('is-in'));
- }
-
- _showError() {
- // Avatar couldn't load (offline / GLB 404). Don't leave a dead canvas —
- // remove the host entirely; the toggle stays available to retry. The
- // WebGL budget was already released by _teardownScene (called first).
- if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
- this.host = null;
- this.mounted = false;
- }
-
- // ── Three.js scene ────────────────────────────────────────────────────────
- async _buildScene() {
- const renderer = new WebGLRenderer({
- canvas: this.canvas,
- alpha: true,
- antialias: true,
- });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
- renderer.setSize(CANVAS_W, CANVAS_H, false);
- this.renderer = renderer;
- // Count this context against the shared budget, paired with the
- // release in _teardownScene so reserve/release always balance.
- reserveWebGLContext();
-
- const scene = new Scene();
- this.scene = scene;
- scene.add(new AmbientLight(0xffffff, 0.85));
- const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.7);
- hemi.position.set(0, 4, 0);
- scene.add(hemi);
- const sun = new DirectionalLight(0xffffff, 1.6);
- sun.position.set(2, 5, 4);
- scene.add(sun);
-
- const camera = new PerspectiveCamera(40, CANVAS_W / CANVAS_H, 0.05, 100);
- this.camera = camera;
-
- const rig = new Group();
- scene.add(rig);
- this.rig = rig;
-
- const avatarId = this._resolveAvatarId();
- if (avatarId) {
- await this._loadAvatar(avatarId, rig, camera);
- } else {
- await this._loadRobot(rig, camera);
- }
- }
-
- _resolveAvatarId() {
- const param = new URLSearchParams(location.search).get('avatar');
- if (param) {
- lsSet(AVATAR_KEY, param);
- return param;
- }
- return lsGet(AVATAR_KEY) || null;
- }
-
- // One GLTFLoader wired with the meshopt decoder only: the default robot rig
- // is uncompressed, but server-baked avatars (the ?avatar= path) emit
- // EXT_meshopt_compression — and crucially, draco/KTX2 are never used by the
- // bake, so we avoid pulling KTX2Loader (keeps the chunk small and dodges a
- // heavier decoder init). Mirrors src/voice/talk-scene.js.
- async _makeLoader() {
- const loader = new GLTFLoader();
- loader.setMeshoptDecoder(await getMeshoptDecoder());
- return loader;
- }
-
- async _loadRobot(rig, camera) {
- const loader = await this._makeLoader();
- const gltf = await loader.loadAsync(ROBOT_URL);
- const model = gltf.scene;
- this._frame(model, rig, camera);
- this.controller = makeMixerController(model, gltf.animations || []);
- }
-
- async _loadAvatar(id, rig, camera) {
- const url = `/api/avatars/${encodeURIComponent(id)}/glb`;
- const loader = await this._makeLoader();
- const gltf = await loader.loadAsync(url);
- const model = gltf.scene;
- this._frame(model, rig, camera);
-
- const manager = new AnimationManager();
- manager.attach(model);
- const manifest = await fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {
- if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`);
- return r.json();
- });
- const wanted = new Set(Object.values(AVATAR_CLIPS));
- const defs = manifest.filter((d) => wanted.has(d.name));
- if (!defs.some((d) => d.name === AVATAR_CLIPS.idle)) {
- throw new Error('animation manifest missing idle clip');
- }
- manager.setAnimationDefs(defs);
- await manager.loadAll();
- const walkName = defs.some((d) => d.name === AVATAR_CLIPS.walk)
- ? AVATAR_CLIPS.walk
- : AVATAR_CLIPS.idle;
- this.controller = makeManagerController(manager, walkName);
- }
-
- // Center the model on X/Z, drop its feet to the floor, and frame the camera
- // to show the full body within the portrait canvas.
- _frame(model, rig, camera) {
- model.traverse((n) => {
- if (n.isMesh) n.frustumCulled = false;
- });
- const box = new Box3().setFromObject(model);
- const size = box.getSize(new Vector3());
- const center = box.getCenter(new Vector3());
- model.position.x -= center.x;
- model.position.z -= center.z;
- model.position.y -= box.min.y;
- rig.add(model);
-
- const height = Math.max(0.6, size.y);
- camera.position.set(0, height * 0.62, height * 2.25);
- camera.lookAt(0, height * 0.52, 0);
- this._height = height;
- }
-
- _teardownScene() {
- try {
- this.controller?.dispose();
- } catch {
- /* non-fatal */
- }
- this.controller = null;
- if (this.scene) {
- this.scene.traverse((n) => {
- if (n.isMesh) {
- n.geometry?.dispose?.();
- const mats = Array.isArray(n.material) ? n.material : [n.material];
- mats.forEach((m) => {
- if (!m) return;
- for (const v of Object.values(m)) {
- if (v && v.isTexture) v.dispose();
- }
- m.dispose?.();
- });
- }
- });
- }
- this.scene = null;
- if (this.renderer) {
- this.renderer.dispose();
- this.renderer.forceContextLoss?.();
- this.renderer = null;
- releaseWebGLContext();
- }
- }
-
- // ── Events ────────────────────────────────────────────────────────────────
- _bindEvents() {
- window.addEventListener('pointermove', this._onPointerMove, { passive: true });
- document.addEventListener('click', this._onLinkClick, true);
- document.addEventListener('visibilitychange', this._onVisibility);
- window.addEventListener('pagehide', this._onPageHide);
- }
-
- _onPointerMove(e) {
- this._cursorX = e.clientX;
- this._cursorMovedAt = performance.now();
- }
-
- // Wave goodbye + flag the next page so the companion waves hello on arrival,
- // giving the cross-navigation continuity. Never blocks the navigation.
- _onLinkClick(e) {
- const a = e.target.closest?.('a[href]');
- if (!a) return;
- if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
- const href = a.getAttribute('href');
- if (!href || href.startsWith('#')) return;
- if (a.target && a.target !== '_self') return;
- let url;
- try {
- url = new URL(href, location.href);
- } catch {
- return;
- }
- if (url.origin !== location.origin) return;
- if (url.pathname === location.pathname) return;
- this.controller?.playWave();
- ssSet(GREET_KEY, '1');
- }
-
- _onVisibility() {
- if (document.hidden) {
- cancelAnimationFrame(this._raf);
- this._raf = 0;
- } else if (this.mounted && !this._raf) {
- this.clock?.update(); // discard the idle gap so dt stays bounded
- this._raf = requestAnimationFrame(this._tick);
- }
- }
-
- _onPageHide() {
- this._persistState();
- }
-
- // ── Greeting / speech bubble ──────────────────────────────────────────────
- _greetForRoute() {
- const arrivedByNav = ssGet(GREET_KEY) === '1';
- ssDel(GREET_KEY);
- if (arrivedByNav) this.controller?.playWave();
- // Orient toward a route-relevant element if there is one.
- this._orientToContext();
- this._say(contextGreeting());
- // Once per session, invite the user to detach into Playground mode.
- if (ssGet(INVITE_KEY) !== '1') {
- ssSet(INVITE_KEY, '1');
- clearTimeout(this._inviteTimer);
- this._inviteTimer = setTimeout(() => {
- if (this.mounted) this._say('Click me to walk the whole page →');
- }, 5600);
- }
- }
-
- _orientToContext() {
- const el = contextTargetEl();
- if (!el) return;
- const rect = el.getBoundingClientRect();
- const elCenterX = rect.left + rect.width / 2;
- const hostRect = this.host.getBoundingClientRect();
- const hostCenterX = hostRect.left + hostRect.width / 2;
- this._targetYaw = clamp((elCenterX - hostCenterX) / window.innerWidth, -0.6, 0.6);
- // Hold the context-facing pose briefly before cursor-follow takes over.
- this._orientLock = true;
- clearTimeout(this._orientTimer);
- this._orientTimer = setTimeout(() => {
- this._orientLock = false;
- }, 4000);
- }
-
- _say(text) {
- if (!this.bubble || !text) return;
- this.bubble.textContent = text;
- this.bubble.hidden = false;
- this.bubble.classList.add('is-in');
- clearTimeout(this._bubbleTimer);
- this._bubbleTimer = setTimeout(() => {
- this.bubble.classList.remove('is-in');
- setTimeout(() => {
- if (this.bubble) this.bubble.hidden = true;
- }, 300);
- }, 5200);
- }
-
- // ── Persistence (Option B: localStorage resume) ───────────────────────────
- _persistState() {
- if (!this.controller) return;
- lsSet(STATE_KEY, JSON.stringify({ yaw: this._yaw }));
- }
-
- _restoreState() {
- try {
- const raw = lsGet(STATE_KEY);
- if (!raw) return;
- const s = JSON.parse(raw);
- if (typeof s.yaw === 'number') {
- this._yaw = s.yaw;
- this._targetYaw = s.yaw;
- }
- } catch {
- /* corrupt state — ignore */
- }
- }
-
- // ── Render loop ───────────────────────────────────────────────────────────
- _tick() {
- if (!this.mounted) return;
- this.clock.update();
- const dt = Math.min(this.clock.getDelta(), 0.05);
-
- // Decide motion: walking while the cursor is in motion and off to one
- // side; idling once it settles. Reduced-motion users get a calm idle.
- const movingRecently = performance.now() - this._cursorMovedAt < CURSOR_IDLE_MS;
- if (!this._reduced && !this._orientLock) {
- const rel = (this._cursorX - window.innerWidth / 2) / (window.innerWidth / 2);
- this._targetYaw = clamp(rel * 0.7, -0.7, 0.7);
- }
- const turning = Math.abs(this._targetYaw - this._yaw) > 0.04;
- const shouldWalk = !this._reduced && (movingRecently || turning);
- this.controller?.setBase(shouldWalk ? 'walk' : 'idle');
-
- // Smoothly turn the rig toward the cursor side.
- this._yaw += (this._targetYaw - this._yaw) * 0.12;
- if (this.rig) this.rig.rotation.y = this._yaw;
-
- this.controller?.update(dt);
- this.renderer.render(this.scene, this.camera);
- this._raf = requestAnimationFrame(this._tick);
- }
-
- _webglSupported() {
- try {
- const c = document.createElement('canvas');
- return !!(
- window.WebGLRenderingContext &&
- (c.getContext('webgl2') || c.getContext('webgl'))
- );
- } catch {
- return false;
- }
- }
-}
-
-function clamp(v, lo, hi) {
- return Math.max(lo, Math.min(hi, v));
-}
-
-// ── Scoped styles (injected once) ───────────────────────────────────────────
-let _stylesInjected = false;
-function ensureStyles() {
- if (_stylesInjected) return;
- _stylesInjected = true;
- const style = document.createElement('style');
- style.id = 'walk-companion-style';
- style.textContent = `
-.walk-companion{position:fixed;right:16px;bottom:16px;width:${CANVAS_W}px;height:${CANVAS_H}px;z-index:2147483000;pointer-events:none;opacity:0;transform:translateY(12px);transition:opacity .35s ease,transform .35s ease;-webkit-user-select:none;user-select:none}
-.walk-companion.is-in{opacity:1;transform:translateY(0)}
-.walk-companion-canvas{position:absolute;inset:0;width:100%;height:100%;z-index:1;pointer-events:auto;cursor:pointer;filter:drop-shadow(0 18px 22px rgba(0,0,0,.32))}
-.walk-companion-close{position:absolute;top:2px;right:2px;z-index:3;width:22px;height:22px;border:none;border-radius:50%;background:rgba(12,14,20,.55);color:#fff;font-size:15px;line-height:1;cursor:pointer;pointer-events:auto;opacity:0;transition:opacity .2s ease,background .2s ease;display:grid;place-items:center;padding:0}
-.walk-companion:hover .walk-companion-close,.walk-companion:focus-within .walk-companion-close{opacity:1}
-.walk-companion-close:hover{background:rgba(220,60,60,.85)}
-.walk-companion-close:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;opacity:1}
-.walk-companion-bubble{position:absolute;left:50%;bottom:calc(100% - 38px);z-index:2;transform:translateX(-50%) translateY(6px);max-width:230px;width:max-content;background:rgba(18,20,28,.94);color:#f2f4f8;font:500 12.5px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;padding:8px 11px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);pointer-events:none;opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
-.walk-companion-bubble.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
-.walk-companion-bubble::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:6px solid transparent;border-top-color:rgba(18,20,28,.94)}
-@media (max-width:520px){.walk-companion{width:148px;height:208px;right:10px;bottom:10px}.walk-companion-bubble{font-size:11.5px;max-width:170px}}
-@media (prefers-reduced-motion:reduce){.walk-companion,.walk-companion-bubble{transition:none}}
-`;
- document.head.appendChild(style);
-}
-
-// ── Public API (driven by public/nav.js) ────────────────────────────────────
-let _instance = null;
-
-function emitChange() {
- try {
- window.dispatchEvent(
- new CustomEvent('walk-companion:change', { detail: { enabled: isEnabled() } }),
- );
- } catch {
- /* non-fatal */
- }
-}
-
-function isEnabled() {
- return lsGet(ENABLED_KEY) === '1';
-}
-
-function enable() {
- lsSet(ENABLED_KEY, '1');
- if (!_instance) _instance = new WalkCompanion();
- _instance.mount();
- emitChange();
-}
-
-function disable() {
- lsSet(ENABLED_KEY, '0');
- if (_instance) _instance.unmount();
- emitChange();
-}
-
-function toggle() {
- if (isEnabled() && _instance && _instance.mounted) disable();
- else enable();
-}
-
-window.__walkCompanion = { enable, disable, toggle, isEnabled };
-
-// ── Playground hand-off ──────────────────────────────────────────────────────
-// The corner companion and the full-screen playground never run at once (one
-// shared WebGL context budget): detaching unmounts the corner instance, then
-// lazy-loads the playground so a normal page never fetches its code.
-let _pgWiring = false;
-function wirePlaygroundReturn() {
- if (_pgWiring) return;
- _pgWiring = true;
- // When the playground exits, bring the corner companion back (if still on).
- window.addEventListener('walk-playground:exit', () => {
- if (isEnabled()) {
- if (!_instance) _instance = new WalkCompanion();
- _instance.mount();
- }
- });
-}
-
-async function detachToPlayground(companion) {
- wirePlaygroundReturn();
- // Where the avatar currently stands, in viewport coords, so it walks out of
- // this exact corner instead of teleporting to the middle of the page.
- let startScreen = null;
- try {
- const r = companion.host.getBoundingClientRect();
- startScreen = { x: r.left + r.width / 2, y: r.top + r.height * 0.86 };
- } catch {
- /* fall back to centered spawn */
- }
- const avatarId = lsGet(AVATAR_KEY) || null;
- if (_instance) _instance.unmount(); // free the corner WebGL context first
- try {
- const mod = await import('./walk-playground.js');
- mod.launchPlayground({ avatarId, startScreen });
- } catch (err) {
- log.warn('[walk-companion] playground failed to load:', err?.message || err);
- // Couldn't enter the playground — restore the corner companion so the
- // click isn't a dead end.
- if (isEnabled()) {
- if (!_instance) _instance = new WalkCompanion();
- _instance.mount();
- }
- }
-}
-
-// Arrived by diving through a link on the previous page → skip the corner
-// companion and drop the character straight into the playground from the top.
-async function tryDropIn() {
- try {
- const mod = await import('./walk-playground.js');
- if (!mod.consumeDropIn()) return false;
- wirePlaygroundReturn();
- mod.launchPlayground({ avatarId: lsGet(AVATAR_KEY) || null, dropIn: true });
- return true;
- } catch (err) {
- log.warn('[walk-companion] drop-in failed:', err?.message || err);
- return false;
- }
-}
-
-// Auto-mount on load when enabled (nav.js only injects this module when the
-// flag is set or the user just toggled it on, so this is the common path).
-const _params = new URLSearchParams(location.search);
-if (_params.get('walk') === '0') {
- disable();
-} else if (_params.get('walk') === 'play') {
- // Deep link straight into the page playground.
- lsSet(ENABLED_KEY, '1');
- import('./walk-playground.js')
- .then((mod) => {
- wirePlaygroundReturn();
- mod.launchPlayground({ avatarId: lsGet(AVATAR_KEY) || null });
- })
- .catch((err) => {
- log.warn('[walk-companion] playground deep-link failed:', err?.message || err);
- enable();
- });
-} else if (_params.get('walk') === '1' || isEnabled()) {
- // If we just dived through a link, resume in the playground; otherwise show
- // the corner companion as usual.
- tryDropIn().then((dropped) => {
- if (!dropped) enable();
- });
-}
+// Delivery is unchanged: Vite emits this module to the stable, unhashed path
+// /walk-companion.js (see vite.config.js → rollupOptions.output.entryFileNames),
+// and public/nav.js injects it with <script type="module"> only when the
+// companion is enabled — so a page that never turns it on pays nothing. We
+// import from companion.js (not the package index) so the playground stays a
+// lazy import() chunk and isn't pulled in until the avatar detaches.
+
+import { createWalkCompanion } from '../walk-sdk/src/companion.js';
+
+const walk = createWalkCompanion({
+ // Static GLBs and the animation manifest are served from this origin.
+ assetBase: '',
+ apiBase: '',
+ manifestUrl: '/animations/manifest.json',
+ // "Make your own" link in the avatar picker → the avatar builder.
+ docsUrl: '/avatar-studio',
+});
+
+// public/nav.js drives the companion through this global (toggle from the nav
+// Walk button, react to ?walk= overrides). Keep the surface it relies on.
+window.__walkCompanion = walk;
+
+walk.bootstrap();
diff --git a/src/walk-playground.js b/src/walk-playground.js
index 7a8019000..c8e7fba0c 100644
--- a/src/walk-playground.js
+++ b/src/walk-playground.js
@@ -1,1468 +1,12 @@
-// Walk Playground — the page becomes a place the companion can roam
-// =================================================================
-// Hands off from the corner Walk Companion (src/walk-companion.js): click the
-// companion and it "detaches" from its spot into a full-page character you steer
-// around the site. The playground ships with TWO movement models and you can
-// switch between them live (the mode button, top-right, or the M key) — the
-// choice is remembered across pages:
+// Walk Playground — three.ws stable entry.
+// ========================================
+// The full-page stroll/platformer engine lives in the SDK (walk-sdk/,
+// @three-ws/walk). This module re-exports it at the stable, unhashed URL
+// /walk-playground.js (a Vite entry) so any page can `import('/walk-playground.js')`
+// and the corner companion's lazy import() resolves to the same singleton —
+// preserving one shared playground instance across the whole site.
//
-// • Stroll — a gentle top-down aerial view. There is no gravity and nothing
-// to fall off: the little guy strolls anywhere across the page.
-// Walk onto a link, pause or press the dive key, and he drops
-// through into the next page.
-// • Platformer — the page's real DOM (headings, cards, buttons, images, links)
-// becomes solid ground. Gravity pulls the character down; he walks
-// and jumps across the layout and can fall off edges. Land on a
-// link and it opens like a trapdoor into the next page.
-//
-// Why this lives in its own module: it is loaded with a dynamic import() the
-// first time you detach, so a normal page never pays for the playground's code
-// or a second WebGL context — exactly the zero-footprint contract the companion
-// already honors. It reuses the companion's shared building blocks: the same
-// RobotExpressive rig + embedded clips, the same meshopt-only GLTFLoader, and
-// the same global WebGL-context budget (reserve/release) so the two never run
-// two contexts at once.
-
-import {
- AmbientLight,
- AnimationMixer,
- Box3,
- CircleGeometry,
- DirectionalLight,
- DoubleSide,
- Group,
- HemisphereLight,
- LoopOnce,
- LoopRepeat,
- Mesh,
- MeshBasicMaterial,
- OrthographicCamera,
- Scene,
- Timer,
- Vector3,
- WebGLRenderer,
-} from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { getMeshoptDecoder } from './viewer/internal.js';
-import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
-import { log } from './shared/log.js';
-
-const ROBOT_URL = '/animations/robotexpressive.glb';
-const RESUME_KEY = 'walk:playground:resume'; // sessionStorage flag: drop in on arrival
-const MODE_KEY = 'walk:playground:mode'; // localStorage: 'stroll' | 'platformer'
-
-// ── Stroll tuning (CSS-pixel units, seconds) ─────────────────────────────────
-const CHAR_PX = 150; // rendered feet-to-head height (pre-foreshorten)
-const MOVE_ACCEL = 3600;
-const MAX_SPEED = 360;
-const RUN_SPEED = 250; // speed above this plays the run clip
-const FRICTION = 3200;
-const EDGE_PAD = 30; // keep the character this far from the page edges
-const CAM_PITCH = 0.5; // radians (~28°) — gentle aerial, "not too dramatic"
-const LINK_DWELL_MS = 700; // stand on a link this long → the doorway opens
-const SPAWN_GUARD_MS = 1100; // no auto-dive until the user has had a beat of control
-const ELEM_PROBE_MS = 90; // throttle for elementFromPoint link hit-testing
-
-// ── Platformer tuning (CSS-pixel units, seconds) ─────────────────────────────
-const PLAT_CHAR_PX = 138; // rendered feet-to-head height
-const GRAVITY = 2600;
-const TERMINAL = 2400;
-const MOVE_SPEED = 330;
-const PLAT_RUN_SPEED = 250; // |vx| above this plays the run clip
-const JUMP_V = 1000; // ≈184px apex
-const GROUND_ACCEL = 2600;
-const AIR_ACCEL = 1400;
-const PLAT_FRICTION = 2400;
-const FOOT_PAD = 26; // horizontal grace so you don't slip off pixel-exact edges
-const LAND_TOL = 14; // vertical tolerance when snapping onto a surface
-const LINK_ARM_MS = 850; // stand still on a link this long → trapdoor opens
-
-// DOM elements that count as solid ground in platformer mode. Filtered further
-// by size/visibility at scan time.
-const SOLID_SELECTOR = [
- 'a[href]',
- 'button',
- 'h1',
- 'h2',
- 'h3',
- 'h4',
- 'p',
- 'li',
- 'img',
- 'figure',
- '.card',
- '[data-platform]',
-].join(',');
-
-function prefersReducedMotion() {
- try {
- return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
- } catch {
- return false;
- }
-}
-function ssSet(key, val) {
- try {
- sessionStorage.setItem(key, val);
- } catch {
- /* non-fatal */
- }
-}
-function ssGet(key) {
- try {
- return sessionStorage.getItem(key);
- } catch {
- return null;
- }
-}
-function ssDel(key) {
- try {
- sessionStorage.removeItem(key);
- } catch {
- /* non-fatal */
- }
-}
-function getMode() {
- try {
- return localStorage.getItem(MODE_KEY) === 'platformer' ? 'platformer' : 'stroll';
- } catch {
- return 'stroll';
- }
-}
-function setMode(m) {
- try {
- localStorage.setItem(MODE_KEY, m === 'platformer' ? 'platformer' : 'stroll');
- } catch {
- /* non-fatal */
- }
-}
-function clamp(v, lo, hi) {
- return Math.max(lo, Math.min(hi, v));
-}
-
-function docWidth() {
- return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
-}
-function docHeight() {
- const el = document.scrollingElement || document.documentElement;
- return Math.max(el.scrollHeight, window.innerHeight || 0);
-}
-function maxScroll() {
- return Math.max(0, docHeight() - window.innerHeight);
-}
-
-// Resolve the same-origin link (if any) sitting under a viewport point, walking
-// up from the topmost element there. Returns its absolute href + element or null.
-function linkHrefAtPoint(sx, sy) {
- let el = document.elementFromPoint(sx, sy);
- if (!el) return null;
- const a = el.closest?.('a[href]');
- if (!a) return null;
- if (a.target && a.target !== '_self') return null;
- const raw = a.getAttribute('href') || '';
- if (!raw || raw.startsWith('#') || raw.startsWith('javascript:')) return null;
- try {
- const u = new URL(raw, location.href);
- if (u.origin !== location.origin) return null;
- return { href: u.href, el: a };
- } catch {
- return null;
- }
-}
-
-// The mode-switch pill, shared by both playgrounds. Shows the live mode and
-// flips to the other one on click (or the M key).
-function modeButtonHTML(mode) {
- const label = mode === 'platformer' ? 'Platformer' : 'Stroll';
- const icon = mode === 'platformer' ? '🎮' : '🚶';
- return `<button type="button" class="walk-pg-mode" aria-label="Switch movement mode (currently ${label})" title="Switch mode (M)"><span class="walk-pg-mode-ic" aria-hidden="true">${icon}</span><span class="walk-pg-mode-tx">${label}</span></button>`;
-}
-
-// ── Animation controller (RobotExpressive clips) ─────────────────────────────
-// States: idle / walk / run / jump. The playground logic never branches on clip
-// names — it calls setState(); missing clips degrade gracefully to idle.
-function makeController(root, clips) {
- const mixer = new AnimationMixer(root);
- const byName = (name) => clips.find((c) => c.name.toLowerCase() === name.toLowerCase());
- const pick = (cands) => {
- for (const n of cands) {
- const c = byName(n);
- if (c) return c;
- }
- return null;
- };
- const map = {
- idle: pick(['Idle', 'idle']),
- walk: pick(['Walking', 'Walk', 'walk']),
- run: pick(['Running', 'Run', 'run', 'Walking', 'walk']),
- jump: pick(['Jump', 'jump', 'WalkJump']),
- };
- const action = {};
- for (const [state, clip] of Object.entries(map)) {
- if (!clip) continue;
- const a = mixer.clipAction(clip);
- a.enabled = true;
- action[state] = a;
- }
-
- let state = 'idle';
- let current = null;
-
- function crossfade(next, dur) {
- const a = action[next] || action.idle;
- if (!a) return;
- const once = next === 'jump';
- a.reset();
- a.setLoop(once ? LoopOnce : LoopRepeat, once ? 1 : Infinity);
- a.clampWhenFinished = once;
- a.fadeIn(dur).play();
- if (current && current !== a) current.fadeOut(dur);
- current = a;
- }
- crossfade('idle', 0);
-
- return {
- setState(next) {
- if (next === state) return;
- state = next;
- crossfade(next, next === 'jump' ? 0.12 : 0.22);
- },
- update(dt) {
- mixer.update(dt);
- },
- dispose() {
- mixer.stopAllAction();
- mixer.uncacheRoot(root);
- },
- };
-}
-
-// ═════════════════════════════════════════════════════════════════════════════
-// Stroll mode — gentle top-down aerial view, no gravity, roam anywhere.
-// ═════════════════════════════════════════════════════════════════════════════
-class StrollPlayground {
- constructor() {
- this.mode = 'stroll';
- this.mounted = false;
- this._reduced = prefersReducedMotion();
- this._raf = 0;
- this._tick = this._tick.bind(this);
- this._onKeyDown = this._onKeyDown.bind(this);
- this._onKeyUp = this._onKeyUp.bind(this);
- this._onResize = this._onResize.bind(this);
-
- // Character state, in document coordinates (feet position on the page).
- this.char = { x: 0, y: 0, vx: 0, vy: 0, facing: 0 };
- this._yaw = 0;
-
- // Input flags (held).
- this.input = { up: false, down: false, left: false, right: false, dive: false };
-
- // Link doorway arming.
- this._armEl = null;
- this._armAt = 0;
- this._armHref = null;
- this._lastProbe = 0;
- this._diving = false;
- this._spawnGuardUntil = 0;
-
- // Scratch vectors reused each frame (no per-frame allocation).
- this._v0 = new Vector3();
- this._v1 = new Vector3();
- }
-
- async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
- if (this.mounted) return;
- if (!this._webglSupported()) {
- log.warn('[walk-playground] WebGL unavailable');
- return;
- }
- this.mounted = true;
- this._avatarId = avatarId;
-
- this._buildDom();
- try {
- await this._buildScene();
- } catch (err) {
- log.warn('[walk-playground] failed to load avatar:', err?.message || err);
- this._teardown();
- return;
- }
-
- this._placeStart(startScreen, dropIn);
- this._spawnGuardUntil = performance.now() + SPAWN_GUARD_MS;
- this._bindEvents();
- if (switched) this._sayModeIntro();
- else this._hintFor(dropIn);
-
- this.clock = new Timer();
- this._raf = requestAnimationFrame(this._tick);
- }
-
- unmount() {
- if (!this.mounted) return;
- this.mounted = false;
- cancelAnimationFrame(this._raf);
- this._raf = 0;
- window.removeEventListener('keydown', this._onKeyDown, true);
- window.removeEventListener('keyup', this._onKeyUp, true);
- window.removeEventListener('resize', this._onResize);
- this._clearArm();
- this._teardown();
- }
-
- // Feet position in viewport coords, for handing off to the other mode.
- currentScreenPos() {
- return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };
- }
-
- // ── DOM scaffold (canvas + d-pad + hint) ──────────────────────────────────
- _buildDom() {
- ensureStyles();
- const host = document.createElement('div');
- host.className = 'walk-pg walk-pg--stroll';
- host.setAttribute('role', 'application');
- host.setAttribute('aria-label', 'Page playground — walk the character with the arrow keys');
- host.innerHTML = `
- <canvas class="walk-pg-canvas"></canvas>
- <div class="walk-pg-hint" aria-live="polite"></div>
- ${modeButtonHTML(this.mode)}
- <button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
- <div class="walk-pg-pad" aria-hidden="true">
- <button type="button" class="walk-pg-btn" data-act="up" aria-label="Walk up">▲</button>
- <div class="walk-pg-pad-row">
- <button type="button" class="walk-pg-btn" data-act="left" aria-label="Walk left">◀</button>
- <button type="button" class="walk-pg-btn walk-pg-dive" data-act="dive" aria-label="Dive into link">⬇</button>
- <button type="button" class="walk-pg-btn" data-act="right" aria-label="Walk right">▶</button>
- </div>
- <button type="button" class="walk-pg-btn" data-act="down" aria-label="Walk down">▼</button>
- </div>
- <div class="walk-pg-flash" aria-hidden="true"></div>
- `;
- document.body.appendChild(host);
- this.host = host;
- this.canvas = host.querySelector('.walk-pg-canvas');
- this.hintEl = host.querySelector('.walk-pg-hint');
- this.flashEl = host.querySelector('.walk-pg-flash');
- host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
- host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
-
- // Touch / pointer d-pad — held while pressed.
- host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
- const act = btn.getAttribute('data-act');
- const on = (e) => {
- e.preventDefault();
- this._setAct(act, true);
- };
- const off = (e) => {
- e.preventDefault();
- this._setAct(act, false);
- };
- btn.addEventListener('pointerdown', on);
- btn.addEventListener('pointerup', off);
- btn.addEventListener('pointerleave', off);
- btn.addEventListener('pointercancel', off);
- });
- requestAnimationFrame(() => host.classList.add('is-in'));
- }
-
- _setAct(act, val) {
- if (act in this.input) this.input[act] = val;
- }
-
- // ── Three.js scene: orthographic, pitched down for a gentle aerial view ────
- async _buildScene() {
- const renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- this.renderer = renderer;
- reserveWebGLContext();
- this._resizeRenderer();
-
- const scene = new Scene();
- this.scene = scene;
- scene.add(new AmbientLight(0xffffff, 0.9));
- const hemi = new HemisphereLight(0xbcd6ff, 0x1a2230, 0.75);
- hemi.position.set(0, 300, 0);
- scene.add(hemi);
- const sun = new DirectionalLight(0xffffff, 1.7);
- sun.position.set(80, 320, 260);
- scene.add(sun);
-
- this._setupCamera();
-
- const rig = new Group();
- scene.add(rig);
- this.rig = rig;
-
- // Soft contact shadow on the page plane (z=0), so the character reads as
- // standing on the page when seen from above.
- const shadow = new Mesh(
- new CircleGeometry(1, 28),
- new MeshBasicMaterial({ color: 0x05070c, transparent: true, opacity: 0.32, side: DoubleSide, depthWrite: false }),
- );
- shadow.renderOrder = -1;
- scene.add(shadow);
- this.shadow = shadow;
-
- const loader = new GLTFLoader();
- loader.setMeshoptDecoder(await getMeshoptDecoder());
- // Detaching from the corner companion means the same default rig walks
- // out of its spot; an explicit ?avatar= is honored when the API serves it.
- const url = this._avatarId ? `/api/avatars/${encodeURIComponent(this._avatarId)}/glb` : ROBOT_URL;
- let gltf;
- try {
- gltf = await loader.loadAsync(url);
- } catch (err) {
- if (this._avatarId) {
- gltf = await loader.loadAsync(ROBOT_URL); // graceful fallback to shared rig
- } else {
- throw err;
- }
- }
- const model = gltf.scene;
- model.traverse((n) => {
- if (n.isMesh) n.frustumCulled = false;
- });
-
- // Scale to a fixed pixel height and drop feet to the rig origin.
- const box = new Box3().setFromObject(model);
- const size = box.getSize(new Vector3());
- const scale = CHAR_PX / Math.max(0.001, size.y);
- model.scale.setScalar(scale);
- const box2 = new Box3().setFromObject(model);
- const center = box2.getCenter(new Vector3());
- model.position.x -= center.x;
- model.position.z -= center.z;
- model.position.y -= box2.min.y;
- this.modelHalfW = (size.x * scale) / 2;
- this._shadowR = Math.max(22, this.modelHalfW * 1.15);
- rig.add(model);
-
- this.controller = makeController(model, gltf.animations || []);
- }
-
- // Orthographic camera looking at the page plane (z=0) from slightly above, so
- // the world maps to screen pixels at a constant scale while we view upright
- // characters from a gentle downward angle. Feet are glued to exact page
- // points each frame via unproject (see _pagePointAtScreen), which stays exact
- // under any camera tilt because orthographic projection has no perspective.
- _setupCamera() {
- const W = window.innerWidth;
- const H = window.innerHeight;
- const cam = new OrthographicCamera(-W / 2, W / 2, H / 2, -H / 2, -4000, 8000);
- const D = 3000;
- cam.position.set(0, Math.sin(CAM_PITCH) * D, Math.cos(CAM_PITCH) * D);
- cam.up.set(0, 1, 0);
- cam.lookAt(0, 0, 0);
- cam.updateProjectionMatrix();
- cam.updateMatrixWorld(true);
- this.camera = cam;
- }
-
- // World point on the page plane (z=0) that projects to a given viewport pixel.
- _pagePointAtScreen(sx, sy, out) {
- const W = window.innerWidth;
- const H = window.innerHeight;
- const ndcX = (sx / W) * 2 - 1;
- const ndcY = -((sy / H) * 2 - 1);
- const p0 = this._v0.set(ndcX, ndcY, -1).unproject(this.camera);
- const p1 = this._v1.set(ndcX, ndcY, 1).unproject(this.camera);
- const dz = p1.z - p0.z;
- const t = Math.abs(dz) < 1e-6 ? 0 : -p0.z / dz;
- return out.set(p0.x + (p1.x - p0.x) * t, p0.y + (p1.y - p0.y) * t, 0);
- }
-
- _placeStart(startScreen, dropIn) {
- const sx = window.scrollX || 0;
- const sy = window.scrollY || 0;
- const w = docWidth();
- if (startScreen) {
- // Detached from the companion's corner (or handed off from platformer)
- // — start from that exact spot.
- this.char.x = clamp(startScreen.x + sx, EDGE_PAD, w - EDGE_PAD);
- this.char.y = clamp(startScreen.y + sy, EDGE_PAD, docHeight() - EDGE_PAD);
- } else {
- // Deep-link or drop-in — start near the middle of the current view.
- this.char.x = clamp(w * 0.5, EDGE_PAD, w - EDGE_PAD);
- this.char.y = clamp(sy + window.innerHeight * (dropIn ? 0.32 : 0.4), EDGE_PAD, docHeight() - EDGE_PAD);
- }
- this.char.vx = 0;
- this.char.vy = 0;
- this._dropIn = dropIn;
- }
-
- // ── Events ────────────────────────────────────────────────────────────────
- _bindEvents() {
- window.addEventListener('keydown', this._onKeyDown, true);
- window.addEventListener('keyup', this._onKeyUp, true);
- window.addEventListener('resize', this._onResize);
- }
-
- _onKeyDown(e) {
- const k = e.key;
- if (k === 'Escape') {
- exitPlayground();
- return;
- }
- if (k === 'm' || k === 'M') {
- e.preventDefault();
- switchPlaygroundMode();
- return;
- }
- let handled = true;
- if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = true;
- else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
- else if (k === 'ArrowUp' || k === 'w' || k === 'W') this.input.up = true;
- else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = true;
- else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E') this.input.dive = true;
- else handled = false;
- if (handled) e.preventDefault();
- }
-
- _onKeyUp(e) {
- const k = e.key;
- if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = false;
- else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = false;
- else if (k === 'ArrowUp' || k === 'w' || k === 'W') this.input.up = false;
- else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = false;
- else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E') this.input.dive = false;
- }
-
- _onResize() {
- this._resizeRenderer();
- this._setupCamera();
- this.char.x = clamp(this.char.x, EDGE_PAD, docWidth() - EDGE_PAD);
- this.char.y = clamp(this.char.y, EDGE_PAD, docHeight() - EDGE_PAD);
- }
-
- _resizeRenderer() {
- this.renderer.setSize(window.innerWidth, window.innerHeight, false);
- }
-
- // ── Hints ─────────────────────────────────────────────────────────────────
- _hintFor(dropIn) {
- const touch = matchMedia('(pointer: coarse)').matches;
- const move = touch ? 'Use the d-pad to walk' : 'Arrow keys / WASD to walk anywhere';
- this._say(dropIn ? `You're in! ${move}. Step on a link to dive deeper.` : `${move}. Step on a link to dive in.`, 5200);
- }
-
- _sayModeIntro() {
- this._say('Stroll mode — free roam, no falling. M to switch back.', 3800);
- }
-
- _say(text, ms = 3200) {
- if (!this.hintEl || !text) return;
- this.hintEl.textContent = text;
- this.hintEl.classList.add('is-in');
- clearTimeout(this._hintTimer);
- this._hintTimer = setTimeout(() => this.hintEl?.classList.remove('is-in'), ms);
- }
-
- // ── Link doorway arming ───────────────────────────────────────────────────
- _armLink(el, href) {
- if (this._armEl === el) return;
- this._clearArm();
- this._armEl = el;
- this._armHref = href;
- this._armAt = performance.now();
- el.classList.add('walk-pg-portal');
- this._say('Pause here or press Space to dive in', 2400);
- }
-
- _clearArm() {
- if (this._armEl) this._armEl.classList.remove('walk-pg-portal');
- this._armEl = null;
- this._armHref = null;
- }
-
- // ── Dive into the next page ───────────────────────────────────────────────
- _dive(href) {
- if (this._diving || !href) return;
- this._diving = true;
- this.controller?.setState('jump');
- if (this._armEl) this._armEl.classList.add('is-open');
- // Flag so the destination relaunches the playground on arrival — the
- // "fall into the next page" payoff.
- ssSet(RESUME_KEY, '1');
- this.flashEl?.classList.add('is-on');
- const go = () => {
- location.href = href;
- };
- if (this._reduced) {
- go();
- return;
- }
- this.char.vx = 0;
- this.char.vy = 0;
- setTimeout(go, 560);
- }
-
- // ── Main loop ─────────────────────────────────────────────────────────────
- _tick() {
- if (!this.mounted) return;
- this.clock.update();
- const dt = Math.min(this.clock.getDelta(), 0.033);
- if (!this._diving) this._step(dt);
- this._follow();
- this._render(dt);
- this._raf = requestAnimationFrame(this._tick);
- }
-
- _step(dt) {
- const c = this.char;
-
- // Build a normalized input vector (so diagonals aren't faster).
- let ix = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
- let iy = (this.input.down ? 1 : 0) - (this.input.up ? 1 : 0);
- if (ix !== 0 && iy !== 0) {
- const inv = 1 / Math.SQRT2;
- ix *= inv;
- iy *= inv;
- }
-
- if (ix !== 0 || iy !== 0) {
- c.vx += ix * MOVE_ACCEL * dt;
- c.vy += iy * MOVE_ACCEL * dt;
- const sp = Math.hypot(c.vx, c.vy);
- if (sp > MAX_SPEED) {
- const k = MAX_SPEED / sp;
- c.vx *= k;
- c.vy *= k;
- }
- } else {
- // Friction to a stop.
- const f = FRICTION * dt;
- const sp = Math.hypot(c.vx, c.vy);
- if (sp <= f) {
- c.vx = 0;
- c.vy = 0;
- } else {
- const k = (sp - f) / sp;
- c.vx *= k;
- c.vy *= k;
- }
- }
-
- c.x = clamp(c.x + c.vx * dt, EDGE_PAD, docWidth() - EDGE_PAD);
- c.y = clamp(c.y + c.vy * dt, EDGE_PAD, docHeight() - EDGE_PAD);
-
- // Facing: turn toward travel direction (model faces +Z at yaw 0).
- const speed = Math.hypot(c.vx, c.vy);
- if (speed > 12) this.char.facing = Math.atan2(c.vx, c.vy);
-
- // Link hit-test under the feet (throttled), then arm / dive.
- const now = performance.now();
- if (now - this._lastProbe > ELEM_PROBE_MS) {
- this._lastProbe = now;
- const feetX = c.x - (window.scrollX || 0);
- const feetY = c.y - (window.scrollY || 0);
- const hit = linkHrefAtPoint(feetX, feetY);
- if (hit) this._armLink(hit.el, hit.href);
- else if (this._armEl) this._clearArm();
- }
-
- // Dive: explicit key, or dwelling still on the doorway past the guard.
- if (this._armHref) {
- if (this.input.dive) {
- this._dive(this._armHref);
- return;
- }
- const pastGuard = now > this._spawnGuardUntil;
- if (pastGuard && speed < 24 && now - this._armAt > LINK_DWELL_MS) {
- this._dive(this._armHref);
- return;
- }
- }
-
- // Animation state.
- let state = 'idle';
- if (speed > RUN_SPEED) state = 'run';
- else if (speed > 12) state = 'walk';
- this.controller?.setState(state);
- }
-
- // Scroll the page so the character stays in a comfortable central band,
- // letting him reach the whole document by walking up or down.
- _follow() {
- const vh = window.innerHeight;
- const cur = window.scrollY || 0;
- const screenY = this.char.y - cur;
- const top = vh * 0.3;
- const bottom = vh * 0.7;
- let next = cur;
- if (screenY < top) next = this.char.y - top;
- else if (screenY > bottom) next = this.char.y - bottom;
- next = clamp(next, 0, maxScroll());
- if (Math.abs(next - cur) > 0.5) window.scrollTo(0, next);
- }
-
- _render(dt) {
- const c = this.char;
- const feetX = c.x - (window.scrollX || 0);
- const feetY = c.y - (window.scrollY || 0);
-
- // Glue the feet to the exact page point beneath them.
- this._pagePointAtScreen(feetX, feetY, this._v0);
- this.rig.position.copy(this._v0);
- if (this.shadow) {
- this.shadow.position.set(this._v0.x, this._v0.y, this._v0.z + 0.5);
- this.shadow.scale.set(this._shadowR, this._shadowR * 0.5, 1);
- }
-
- if (this._diving) {
- this.rig.rotation.y += dt * 10;
- const s = Math.max(0.04, this.rig.scale.x - dt * 1.6);
- this.rig.scale.setScalar(s);
- if (this.shadow) this.shadow.material.opacity = Math.max(0, this.shadow.material.opacity - dt * 0.8);
- } else {
- // Smoothly turn toward the travel direction (shortest way around).
- let d = this.char.facing - this._yaw;
- while (d > Math.PI) d -= Math.PI * 2;
- while (d < -Math.PI) d += Math.PI * 2;
- this._yaw += d * Math.min(1, dt * 11);
- this.rig.rotation.y = this._yaw;
- }
-
- this.controller?.update(dt);
- this.renderer.render(this.scene, this.camera);
- }
-
- _teardown() {
- teardownScene(this);
- }
-
- _webglSupported() {
- return webglSupported();
- }
-}
-
-// ═════════════════════════════════════════════════════════════════════════════
-// Platformer mode — the page's DOM is solid ground; gravity, jumping, falling.
-// ═════════════════════════════════════════════════════════════════════════════
-class PlatformerPlayground {
- constructor() {
- this.mode = 'platformer';
- this.mounted = false;
- this._reduced = prefersReducedMotion();
- this._raf = 0;
- this._tick = this._tick.bind(this);
- this._onKeyDown = this._onKeyDown.bind(this);
- this._onKeyUp = this._onKeyUp.bind(this);
- this._onResize = this._onResize.bind(this);
- this._scheduleRescan = this._scheduleRescan.bind(this);
-
- // Character state, in document coordinates (feet position).
- this.char = { x: 0, y: 0, vx: 0, vy: 0, grounded: false, facing: 1 };
- this.platform = null; // platform currently stood on
- this.platforms = [];
- this._lastScan = 0;
- this._scrollY = 0;
-
- // Input flags.
- this.input = { left: false, right: false, jump: false, down: false };
- this._jumpEdge = false; // jump consumed until released (no auto-bunnyhop)
-
- // Link-trapdoor arming.
- this._armEl = null;
- this._armAt = 0;
- this._armHref = null;
- this._diving = false;
- }
-
- async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
- if (this.mounted) return;
- if (!this._webglSupported()) {
- log.warn('[walk-playground] WebGL unavailable');
- return;
- }
- this.mounted = true;
- this._avatarId = avatarId;
-
- this._buildDom();
- try {
- await this._buildScene();
- } catch (err) {
- log.warn('[walk-playground] failed to load avatar:', err?.message || err);
- this._teardown();
- return;
- }
-
- this._scrollY = window.scrollY || 0;
- this._scan(true);
- this._placeStart(startScreen, dropIn);
- // Grace period so the character can't auto-dive through a link it happens
- // to land on during the initial settle, before the user has any control.
- this._spawnGuardUntil = performance.now() + 1500;
- this._bindEvents();
- if (switched) this._sayModeIntro();
- else this._hintFor(dropIn);
-
- this.clock = new Timer();
- this._raf = requestAnimationFrame(this._tick);
- }
-
- unmount() {
- if (!this.mounted) return;
- this.mounted = false;
- cancelAnimationFrame(this._raf);
- this._raf = 0;
- window.removeEventListener('keydown', this._onKeyDown, true);
- window.removeEventListener('keyup', this._onKeyUp, true);
- window.removeEventListener('resize', this._onResize);
- window.removeEventListener('scroll', this._scheduleRescan, true);
- this._clearArm();
- this._teardown();
- }
-
- // Feet position in viewport coords, for handing off to the other mode.
- currentScreenPos() {
- return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };
- }
-
- // ── DOM scaffold (canvas + controls + hint) ──────────────────────────────
- _buildDom() {
- ensureStyles();
- const host = document.createElement('div');
- host.className = 'walk-pg walk-pg--plat';
- host.setAttribute('role', 'application');
- host.setAttribute('aria-label', 'Page playground — walk and jump the character with arrow keys');
- host.innerHTML = `
- <canvas class="walk-pg-canvas"></canvas>
- <div class="walk-pg-hint" aria-live="polite"></div>
- ${modeButtonHTML(this.mode)}
- <button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
- <div class="walk-pg-pad" aria-hidden="true">
- <button type="button" class="walk-pg-btn" data-act="left" aria-label="Walk left">◀</button>
- <button type="button" class="walk-pg-btn" data-act="right" aria-label="Walk right">▶</button>
- <button type="button" class="walk-pg-btn walk-pg-jump" data-act="jump" aria-label="Jump">⤒</button>
- <button type="button" class="walk-pg-btn" data-act="down" aria-label="Dive into link">⤓</button>
- </div>
- <div class="walk-pg-flash" aria-hidden="true"></div>
- `;
- document.body.appendChild(host);
- this.host = host;
- this.canvas = host.querySelector('.walk-pg-canvas');
- this.hintEl = host.querySelector('.walk-pg-hint');
- this.flashEl = host.querySelector('.walk-pg-flash');
- host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
- host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
-
- // Touch / pointer controls — held while pressed.
- host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
- const act = btn.getAttribute('data-act');
- const on = (e) => {
- e.preventDefault();
- this._setAct(act, true);
- };
- const off = (e) => {
- e.preventDefault();
- this._setAct(act, false);
- };
- btn.addEventListener('pointerdown', on);
- btn.addEventListener('pointerup', off);
- btn.addEventListener('pointerleave', off);
- btn.addEventListener('pointercancel', off);
- });
- requestAnimationFrame(() => host.classList.add('is-in'));
- }
-
- _setAct(act, val) {
- if (act === 'left') this.input.left = val;
- else if (act === 'right') this.input.right = val;
- else if (act === 'jump') {
- this.input.jump = val;
- if (!val) this._jumpEdge = false;
- } else if (act === 'down') this.input.down = val;
- }
-
- // ── Three.js scene: orthographic, 1 unit = 1 CSS pixel ────────────────────
- async _buildScene() {
- const renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
- renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
- this.renderer = renderer;
- reserveWebGLContext();
- this._resizeRenderer();
-
- const scene = new Scene();
- this.scene = scene;
- scene.add(new AmbientLight(0xffffff, 0.9));
- const hemi = new HemisphereLight(0xbcd6ff, 0x1a2230, 0.75);
- hemi.position.set(0, 200, 0);
- scene.add(hemi);
- const sun = new DirectionalLight(0xffffff, 1.7);
- sun.position.set(120, 260, 220);
- scene.add(sun);
-
- // Camera maps screen pixel (px, py) → world (px, -py); +Z toward viewer.
- this.camera = new OrthographicCamera(0, window.innerWidth, 0, -window.innerHeight, -1000, 2000);
- this.camera.position.z = 600;
-
- const rig = new Group();
- scene.add(rig);
- this.rig = rig;
-
- const loader = new GLTFLoader();
- loader.setMeshoptDecoder(await getMeshoptDecoder());
- // Detaching from the corner companion means the same default rig walks
- // out of its spot; an explicit ?avatar= is honored when the API serves it.
- const url = this._avatarId ? `/api/avatars/${encodeURIComponent(this._avatarId)}/glb` : ROBOT_URL;
- let gltf;
- try {
- gltf = await loader.loadAsync(url);
- } catch (err) {
- if (this._avatarId) {
- gltf = await loader.loadAsync(ROBOT_URL); // graceful fallback to shared rig
- } else {
- throw err;
- }
- }
- const model = gltf.scene;
- model.traverse((n) => {
- if (n.isMesh) n.frustumCulled = false;
- });
-
- // Scale to a fixed pixel height and drop feet to the rig origin.
- const box = new Box3().setFromObject(model);
- const size = box.getSize(new Vector3());
- const scale = PLAT_CHAR_PX / Math.max(0.001, size.y);
- model.scale.setScalar(scale);
- const box2 = new Box3().setFromObject(model);
- const center = box2.getCenter(new Vector3());
- model.position.x -= center.x;
- model.position.z -= center.z;
- model.position.y -= box2.min.y;
- this.modelHalfW = (size.x * scale) / 2;
- rig.add(model);
-
- this.controller = makeController(model, gltf.animations || []);
- }
-
- _placeStart(startScreen, dropIn) {
- const sy = window.scrollY || 0;
- if (dropIn) {
- // Arrived by diving through a link on the previous page — fall in from
- // the top, centered, so navigation reads as continuous descent.
- this.char.x = clamp(docWidth() * 0.5, 40, docWidth() - 40);
- this.char.y = sy - PLAT_CHAR_PX;
- this.char.vy = 60;
- this.char.grounded = false;
- } else if (startScreen) {
- // Detached from the companion's corner (or handed off from stroll) —
- // step out from that exact spot and settle under gravity.
- this.char.x = clamp(startScreen.x + (window.scrollX || 0), 40, docWidth() - 40);
- this.char.y = startScreen.y + sy;
- this.char.vy = 40;
- this.char.grounded = false;
- } else {
- this.char.x = clamp(docWidth() * 0.5, 40, docWidth() - 40);
- this.char.y = sy + window.innerHeight * 0.3;
- this.char.vy = 0;
- }
- }
-
- // ── Platform scan from the live DOM ───────────────────────────────────────
- // Only elements within an expanded band around the viewport are considered,
- // so the platform set stays small and follows the user as they descend.
- _scan(force = false) {
- const now = performance.now();
- if (!force && now - this._lastScan < 180) return;
- this._lastScan = now;
-
- const sx = window.scrollX || 0;
- const sy = window.scrollY || 0;
- const bandTop = sy - 1100;
- const bandBottom = sy + window.innerHeight + 1100;
- const out = [];
- const seen = new Set();
-
- const els = document.querySelectorAll(SOLID_SELECTOR);
- for (const el of els) {
- if (out.length >= 360) break;
- if (this.host.contains(el)) continue;
- const r = el.getBoundingClientRect();
- if (r.width < 38 || r.height < 14 || r.height > 520) continue;
- const top = r.top + sy;
- const bottom = r.bottom + sy;
- if (bottom < bandTop || top > bandBottom) continue;
- const style = el.ownerDocument.defaultView.getComputedStyle(el);
- if (style.visibility === 'hidden' || style.display === 'none' || +style.opacity === 0) continue;
- const left = r.left + sx;
- const right = r.right + sx;
- const key = `${Math.round(left)},${Math.round(top)},${Math.round(right)}`;
- if (seen.has(key)) continue;
- seen.add(key);
-
- const link = el.closest('a[href]');
- let href = null;
- if (link) {
- const raw = link.getAttribute('href') || '';
- if (raw && !raw.startsWith('#') && (!link.target || link.target === '_self')) {
- try {
- const u = new URL(raw, location.href);
- if (u.origin === location.origin) href = u.href;
- } catch {
- /* unparseable href — treat as plain platform */
- }
- }
- }
- out.push({ left, right, top, bottom, href, el });
- }
-
- // Always-present floor so the character can never fall out of the page.
- const w = docWidth();
- out.push({ left: -40, right: w + 40, top: docHeight() - 3, bottom: docHeight(), href: null, el: null });
- this.platforms = out;
-
- // Keep standing on a platform that scrolled out of the rescan band.
- if (this.platform && !out.includes(this.platform)) {
- out.push(this.platform);
- }
- }
-
- _scheduleRescan() {
- this._scrollY = window.scrollY || 0;
- this._scan();
- }
-
- // ── Events ────────────────────────────────────────────────────────────────
- _bindEvents() {
- window.addEventListener('keydown', this._onKeyDown, true);
- window.addEventListener('keyup', this._onKeyUp, true);
- window.addEventListener('resize', this._onResize);
- window.addEventListener('scroll', this._scheduleRescan, true);
- }
-
- _onKeyDown(e) {
- const k = e.key;
- if (k === 'Escape') {
- exitPlayground();
- return;
- }
- if (k === 'm' || k === 'M') {
- e.preventDefault();
- switchPlaygroundMode();
- return;
- }
- let handled = true;
- if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = true;
- else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
- else if (k === ' ' || k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'Spacebar') this.input.jump = true;
- else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = true;
- else handled = false;
- if (handled) e.preventDefault();
- }
-
- _onKeyUp(e) {
- const k = e.key;
- if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = false;
- else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = false;
- else if (k === ' ' || k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'Spacebar') {
- this.input.jump = false;
- this._jumpEdge = false;
- } else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = false;
- }
-
- _onResize() {
- this._resizeRenderer();
- if (this.camera) {
- this.camera.right = window.innerWidth;
- this.camera.bottom = -window.innerHeight;
- this.camera.updateProjectionMatrix();
- }
- this._scan(true);
- }
-
- _resizeRenderer() {
- this.renderer.setSize(window.innerWidth, window.innerHeight, false);
- }
-
- // ── Hints ─────────────────────────────────────────────────────────────────
- _hintFor(dropIn) {
- const touch = matchMedia('(pointer: coarse)').matches;
- const move = touch ? 'Use the buttons' : 'Arrow keys / WASD to move, Space to jump';
- this._say(dropIn ? `You fell in! ${move}. Land on a link to dive deeper.` : `${move}. Land on a link to dive in.`, 5200);
- }
-
- _sayModeIntro() {
- const touch = matchMedia('(pointer: coarse)').matches;
- const jump = touch ? 'tap ⤒ to jump' : 'Space to jump';
- this._say(`Platformer mode — gravity on, ${jump}. M to switch back.`, 3800);
- }
-
- _say(text, ms = 3200) {
- if (!this.hintEl || !text) return;
- this.hintEl.textContent = text;
- this.hintEl.classList.add('is-in');
- clearTimeout(this._hintTimer);
- this._hintTimer = setTimeout(() => this.hintEl?.classList.remove('is-in'), ms);
- }
-
- // ── Link-trapdoor arming ──────────────────────────────────────────────────
- _armLink(p) {
- if (this._armEl === p.el) return;
- this._clearArm();
- this._armEl = p.el;
- this._armAt = performance.now();
- this._armHref = p.href;
- p.el.classList.add('walk-pg-portal');
- this._say('↓ to dive in', 2200);
- }
-
- _clearArm() {
- if (this._armEl) this._armEl.classList.remove('walk-pg-portal');
- this._armEl = null;
- this._armHref = null;
- }
-
- // ── Dive into the next page ───────────────────────────────────────────────
- _dive(href) {
- if (this._diving || !href) return;
- this._diving = true;
- this.controller?.setState('jump');
- if (this._armEl) this._armEl.classList.add('is-open');
- // Flag so the destination relaunches the playground and drops the
- // character in from the top — the "fall into the next page" payoff.
- ssSet(RESUME_KEY, '1');
- this.flashEl?.classList.add('is-on');
- const go = () => {
- location.href = href;
- };
- if (this._reduced) {
- go();
- return;
- }
- // Plummet the character, then navigate once the screen has faded.
- this.char.vx = 0;
- this.char.vy = TERMINAL;
- this.char.grounded = false;
- setTimeout(go, 620);
- }
-
- // ── Main loop ───────────────────────────────────────────────────────────────
- _tick() {
- if (!this.mounted) return;
- this.clock.update();
- const dt = Math.min(this.clock.getDelta(), 0.033);
- if (!this._diving) this._step(dt);
- this._follow(dt);
- this._render(dt);
- this._raf = requestAnimationFrame(this._tick);
- }
-
- _step(dt) {
- const c = this.char;
-
- // Horizontal input → acceleration with friction when idle.
- const dir = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
- const accel = c.grounded ? GROUND_ACCEL : AIR_ACCEL;
- if (dir !== 0) {
- c.vx += dir * accel * dt;
- c.vx = clamp(c.vx, -MOVE_SPEED, MOVE_SPEED);
- c.facing = dir;
- } else if (c.grounded) {
- const f = PLAT_FRICTION * dt;
- if (Math.abs(c.vx) <= f) c.vx = 0;
- else c.vx -= Math.sign(c.vx) * f;
- }
-
- // Jump (rising edge only).
- if (this.input.jump && c.grounded && !this._jumpEdge) {
- c.vy = -JUMP_V;
- c.grounded = false;
- this.platform = null;
- this._jumpEdge = true;
- this._clearArm();
- }
-
- // Drop / dive request.
- if (this.input.down && c.grounded) {
- if (this.platform?.href) {
- this._dive(this.platform.href);
- return;
- }
- // Drop through a normal platform to whatever is below.
- c.y += 4;
- c.grounded = false;
- const dropped = this.platform;
- this.platform = null;
- this._dropIgnore = dropped;
- }
-
- // Gravity.
- c.vy = Math.min(c.vy + GRAVITY * dt, TERMINAL);
-
- const prevY = c.y;
- c.x = clamp(c.x + c.vx * dt, this.modelHalfW, docWidth() - this.modelHalfW);
- c.y = c.y + c.vy * dt;
-
- // Land on the highest platform crossed from above this frame.
- if (c.vy >= 0) {
- let best = null;
- for (const p of this.platforms) {
- if (p === this._dropIgnore) continue;
- if (c.x < p.left - FOOT_PAD || c.x > p.right + FOOT_PAD) continue;
- if (prevY <= p.top + LAND_TOL && c.y >= p.top) {
- if (!best || p.top < best.top) best = p;
- }
- }
- if (best) {
- c.y = best.top;
- c.vy = 0;
- c.grounded = true;
- this.platform = best;
- this._dropIgnore = null;
- } else if (c.grounded && this.platform) {
- // Walked off the edge of the current platform?
- const p = this.platform;
- if (c.x < p.left - FOOT_PAD || c.x > p.right + FOOT_PAD) {
- c.grounded = false;
- this.platform = null;
- } else {
- c.y = p.top; // stay snapped
- }
- } else {
- c.grounded = false;
- }
- }
-
- // Trapdoor arming: standing fairly still on a link opens it. Suppressed
- // during the spawn grace period so detaching onto a link isn't an instant
- // teleport — the user gets to take control first.
- const pastGuard = performance.now() > this._spawnGuardUntil;
- if (pastGuard && c.grounded && this.platform?.href && Math.abs(c.vx) < 30 && dir === 0) {
- this._armLink(this.platform);
- if (performance.now() - this._armAt > LINK_ARM_MS) {
- this._dive(this.platform.href);
- return;
- }
- } else if (this._armEl && (!c.grounded || this.platform?.el !== this._armEl || dir !== 0)) {
- this._clearArm();
- }
-
- // Animation state.
- let state = 'idle';
- if (!c.grounded) state = 'jump';
- else if (Math.abs(c.vx) > PLAT_RUN_SPEED) state = 'run';
- else if (Math.abs(c.vx) > 6) state = 'walk';
- this.controller?.setState(state);
- }
-
- // Scroll the page so the character stays comfortably in view.
- _follow(dt) {
- const want = clamp(this.char.y - window.innerHeight * 0.55, 0, maxScroll());
- const cur = window.scrollY || 0;
- const next = this._reduced ? want : cur + (want - cur) * Math.min(1, dt * 6);
- if (Math.abs(next - cur) > 0.5) window.scrollTo(0, next);
- this._scrollY = window.scrollY || 0;
- this._scan();
- }
-
- _render(dt) {
- const c = this.char;
- const sx = window.scrollX || 0;
- const sy = window.scrollY || 0;
- const screenX = c.x - sx;
- const screenY = c.y - sy;
- this.rig.position.set(screenX, -screenY, 0);
-
- // 3/4 hero turn toward travel direction; spin while diving.
- if (this._diving) {
- this.rig.rotation.y += dt * 9;
- const s = Math.max(0.05, this.rig.scale.x - dt * 1.4);
- this.rig.scale.setScalar(s);
- } else {
- const targetYaw = c.facing >= 0 ? 0.6 : -0.6;
- this.rig.rotation.y += (targetYaw - this.rig.rotation.y) * Math.min(1, dt * 10);
- }
-
- this.controller?.update(dt);
- this.renderer.render(this.scene, this.camera);
- }
-
- _teardown() {
- teardownScene(this);
- }
-
- _webglSupported() {
- return webglSupported();
- }
-}
-
-// ── Shared scene teardown / WebGL probe ──────────────────────────────────────
-function teardownScene(pg) {
- try {
- pg.controller?.dispose();
- } catch {
- /* non-fatal */
- }
- pg.controller = null;
- if (pg.scene) {
- pg.scene.traverse((n) => {
- if (n.isMesh) {
- n.geometry?.dispose?.();
- const mats = Array.isArray(n.material) ? n.material : [n.material];
- mats.forEach((m) => {
- if (!m) return;
- for (const v of Object.values(m)) {
- if (v && v.isTexture) v.dispose();
- }
- m.dispose?.();
- });
- }
- });
- }
- pg.scene = null;
- if (pg.renderer) {
- pg.renderer.dispose();
- pg.renderer.forceContextLoss?.();
- pg.renderer = null;
- releaseWebGLContext();
- }
- if (pg.host?.parentNode) pg.host.parentNode.removeChild(pg.host);
- pg.host = null;
-}
-
-function webglSupported() {
- try {
- const c = document.createElement('canvas');
- return !!(window.WebGLRenderingContext && (c.getContext('webgl2') || c.getContext('webgl')));
- } catch {
- return false;
- }
-}
-
-// ── Scoped styles ─────────────────────────────────────────────────────────────
-let _stylesInjected = false;
-function ensureStyles() {
- if (_stylesInjected) return;
- _stylesInjected = true;
- const style = document.createElement('style');
- style.id = 'walk-pg-style';
- style.textContent = `
-.walk-pg{position:fixed;inset:0;z-index:2147483100;pointer-events:none;opacity:0;transition:opacity .3s ease}
-.walk-pg.is-in{opacity:1}
-.walk-pg-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;filter:drop-shadow(0 18px 22px rgba(0,0,0,.3))}
-.walk-pg-exit{position:fixed;top:14px;right:14px;z-index:3;pointer-events:auto;border:1px solid rgba(255,255,255,.16);background:rgba(14,16,22,.72);color:#f2f4f8;font:600 12.5px/1 system-ui,sans-serif;padding:9px 13px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);transition:background .2s ease,transform .15s ease}
-.walk-pg-exit:hover{background:rgba(220,60,60,.85)}
-.walk-pg-exit:active{transform:scale(.96)}
-.walk-pg-exit:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
-.walk-pg-mode{position:fixed;top:14px;right:92px;z-index:3;pointer-events:auto;display:inline-flex;align-items:center;gap:6px;border:1px solid rgba(255,255,255,.16);background:rgba(14,16,22,.72);color:#f2f4f8;font:600 12.5px/1 system-ui,sans-serif;padding:9px 13px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);transition:background .2s ease,transform .15s ease}
-.walk-pg-mode:hover{background:rgba(122,162,255,.55)}
-.walk-pg-mode:active{transform:scale(.96)}
-.walk-pg-mode:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
-.walk-pg-mode-ic{font-size:14px;line-height:1}
-.walk-pg-hint{position:fixed;left:50%;bottom:22px;transform:translateX(-50%) translateY(8px);z-index:3;pointer-events:none;max-width:88vw;width:max-content;background:rgba(18,20,28,.92);color:#f2f4f8;font:500 13px/1.4 system-ui,sans-serif;padding:9px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
-.walk-pg-hint.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
-.walk-pg-btn{pointer-events:auto;border:1px solid rgba(255,255,255,.18);background:rgba(16,18,26,.78);color:#fff;display:grid;place-items:center;backdrop-filter:blur(6px);-webkit-user-select:none;user-select:none;touch-action:none}
-.walk-pg-btn:active{background:rgba(122,162,255,.5)}
-.walk-pg--stroll .walk-pg-pad{position:fixed;left:18px;bottom:18px;z-index:3;display:none;flex-direction:column;align-items:center;gap:8px;pointer-events:none}
-.walk-pg--stroll .walk-pg-pad-row{display:flex;gap:8px;align-items:center}
-.walk-pg--stroll .walk-pg-btn{width:54px;height:54px;border-radius:14px;font-size:20px}
-.walk-pg-dive{border-radius:50%!important;background:rgba(122,162,255,.32)}
-.walk-pg--plat .walk-pg-pad{position:fixed;left:0;right:0;bottom:18px;z-index:3;display:none;justify-content:center;gap:12px;pointer-events:none}
-.walk-pg--plat .walk-pg-btn{width:60px;height:60px;border-radius:50%;font-size:22px}
-.walk-pg-jump{background:rgba(122,162,255,.32)}
-.walk-pg-flash{position:fixed;inset:0;z-index:2;pointer-events:none;background:radial-gradient(circle at 50% 50%,rgba(122,162,255,0) 0%,rgba(8,10,16,0) 60%);opacity:0;transition:opacity .5s ease}
-.walk-pg-flash.is-on{background:radial-gradient(circle at 50% 50%,rgba(122,162,255,.25) 0%,rgba(6,8,14,.96) 70%);opacity:1}
-.walk-pg-portal{outline:2px solid rgba(122,162,255,.9)!important;outline-offset:3px;border-radius:6px;box-shadow:0 0 0 4px rgba(122,162,255,.18),0 0 28px rgba(122,162,255,.45)!important;transition:box-shadow .2s ease,transform .25s ease;animation:walk-pg-pulse 1.1s ease-in-out infinite}
-.walk-pg-portal.is-open{transform:scale(.94);box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 48px rgba(122,162,255,.7)!important}
-@keyframes walk-pg-pulse{0%,100%{box-shadow:0 0 0 4px rgba(122,162,255,.16),0 0 22px rgba(122,162,255,.35)}50%{box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 36px rgba(122,162,255,.6)}}
-@media (pointer: coarse){.walk-pg--stroll .walk-pg-pad,.walk-pg--plat .walk-pg-pad{display:flex}.walk-pg--stroll .walk-pg-hint{bottom:200px}.walk-pg--plat .walk-pg-hint{bottom:110px}.walk-pg-mode .walk-pg-mode-tx{display:none}.walk-pg-mode{right:84px}}
-@media (prefers-reduced-motion:reduce){.walk-pg,.walk-pg-hint,.walk-pg-flash{transition:none}.walk-pg-portal{animation:none}}
-`;
- document.head.appendChild(style);
-}
-
-// ── Public API ────────────────────────────────────────────────────────────────
-let _instance = null;
-
-function modeClass(mode) {
- return mode === 'platformer' ? PlatformerPlayground : StrollPlayground;
-}
-
-export function launchPlayground(opts = {}) {
- if (_instance) return _instance;
- const mode = opts.mode || getMode();
- _instance = new (modeClass(mode))();
- _instance.mount({ ...opts, mode });
- return _instance;
-}
-
-export function exitPlayground() {
- if (_instance) {
- _instance.unmount();
- _instance = null;
- }
- try {
- window.dispatchEvent(new CustomEvent('walk-playground:exit'));
- } catch {
- /* non-fatal */
- }
-}
-
-// Swap the live playground between Stroll and Platformer in place, carrying the
-// character's on-screen position across so it feels like a mode flip, not a
-// relaunch. Does NOT emit walk-playground:exit, so the corner companion stays
-// retired until the user actually exits.
-export function switchPlaygroundMode(forceMode = null) {
- if (!_instance || !_instance.mounted) return null;
- const cur = _instance.mode;
- const next = forceMode || (cur === 'platformer' ? 'stroll' : 'platformer');
- if (next === cur) return _instance;
- setMode(next);
- const startScreen = _instance.currentScreenPos();
- const avatarId = _instance._avatarId || null;
- _instance.unmount();
- _instance = new (modeClass(next))();
- _instance.mount({ avatarId, startScreen, switched: true, mode: next });
- return _instance;
-}
-
-export function getPlaygroundMode() {
- return _instance?.mode || getMode();
-}
-
-export function shouldDropIn() {
- return ssGet(RESUME_KEY) === '1';
-}
-
-export function consumeDropIn() {
- const v = ssGet(RESUME_KEY) === '1';
- if (v) ssDel(RESUME_KEY);
- return v;
-}
-
-// Read-only snapshot of the live character — handy for debugging from the
-// console (e.g. `__walkPlayground.state()`).
-export function playgroundState() {
- if (!_instance || !_instance.mounted) return null;
- const c = _instance.char;
- const base = {
- mode: _instance.mode,
- x: Math.round(c.x),
- y: Math.round(c.y),
- vx: Math.round(c.vx),
- vy: Math.round(c.vy),
- diving: _instance._diving,
- };
- if (_instance.mode === 'platformer') {
- return {
- ...base,
- grounded: c.grounded,
- facing: c.facing,
- platforms: _instance.platforms.length,
- onLink: !!_instance.platform?.href,
- };
- }
- return { ...base, speed: Math.round(Math.hypot(c.vx, c.vy)), onLink: !!_instance._armHref };
-}
+// Importing the SDK module also installs window.__walkPlayground, which the IBM
+// partnership demo and console debugging rely on.
-if (typeof window !== 'undefined') {
- window.__walkPlayground = {
- launch: launchPlayground,
- exit: exitPlayground,
- switchMode: switchPlaygroundMode,
- mode: getPlaygroundMode,
- state: playgroundState,
- };
-}
+export * from '../walk-sdk/src/playground.js';
diff --git a/tests/glb-inspect-partial.test.js b/tests/glb-inspect-partial.test.js
new file mode 100644
index 000000000..aa511a66d
--- /dev/null
+++ b/tests/glb-inspect-partial.test.js
@@ -0,0 +1,58 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { inspectGlb, glbJsonChunkEnd } from '../api/_lib/glb-inspect.js';
+
+const avatar = (name) => resolve(process.cwd(), 'public/avatars', name);
+
+// Real bundled GLBs: rigged humanoids + one static mesh.
+const RIGGED = ['cesium-man.glb', 'fox.glb', 'realistic-female.glb'];
+const STATIC = ['mannequin.glb'];
+
+describe('inspectGlb allowPartial (ranged-read prefix)', () => {
+ for (const name of [...RIGGED, ...STATIC]) {
+ const path = avatar(name);
+ const present = existsSync(path);
+ it.runIf(present)(`prefix inspection matches full inspection — ${name}`, () => {
+ const full = readFileSync(path);
+ const fromFull = inspectGlb(full);
+ expect(fromFull).toBeTruthy();
+
+ // A prefix covering exactly the JSON chunk yields the same rig verdict,
+ // even though declaredLen (the full file size) exceeds the prefix length.
+ const end = glbJsonChunkEnd(full);
+ expect(end).toBeGreaterThan(20);
+ const prefix = full.subarray(0, end);
+ const fromPrefix = inspectGlb(prefix, { allowPartial: true });
+ expect(fromPrefix).toBeTruthy();
+ expect(fromPrefix.isRigged).toBe(fromFull.isRigged);
+ expect(fromPrefix.skeletonJointCount).toBe(fromFull.skeletonJointCount);
+
+ expect(fromFull.isRigged).toBe(RIGGED.includes(name));
+ });
+ }
+
+ it.runIf(existsSync(avatar('cesium-man.glb')))(
+ 'a prefix too short to cover the JSON chunk returns null (refetch signal)',
+ () => {
+ const full = readFileSync(avatar('cesium-man.glb'));
+ const tiny = full.subarray(0, 16);
+ expect(inspectGlb(tiny, { allowPartial: true })).toBeNull();
+ // …and a small (≥20-byte) header prefix is enough for glbJsonChunkEnd to
+ // report how many bytes to refetch — it only reads the chunk-length field.
+ const headerOnly = full.subarray(0, 64);
+ expect(glbJsonChunkEnd(headerOnly)).toBe(glbJsonChunkEnd(full));
+ },
+ );
+
+ it('full-buffer mode still rejects a truncated buffer (declaredLen > length)', () => {
+ const path = avatar('fox.glb');
+ if (!existsSync(path)) return;
+ const full = readFileSync(path);
+ const truncated = full.subarray(0, glbJsonChunkEnd(full)); // missing BIN chunk
+ // Without allowPartial the declaredLen consistency check rejects it.
+ expect(inspectGlb(truncated)).toBeNull();
+ // With allowPartial it parses fine.
+ expect(inspectGlb(truncated, { allowPartial: true })).toBeTruthy();
+ });
+});
diff --git a/walk-sdk/LICENSE b/walk-sdk/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/walk-sdk/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/walk-sdk/build.mjs b/walk-sdk/build.mjs
new file mode 100644
index 000000000..3b48d4542
--- /dev/null
+++ b/walk-sdk/build.mjs
@@ -0,0 +1,51 @@
+#!/usr/bin/env node
+// Build @three-ws/walk into a self-contained, publishable ES module.
+// ==================================================================
+// The source reaches back into the monorepo for the shared retargeting engine
+// (see src/internal/runtime.js). esbuild bundles that — and everything else
+// except `three` — into dist/, so npm consumers install one standalone package
+// that only needs their own copy of Three.js (the peer dependency).
+//
+// Dynamic import('./playground.js') stays a separate chunk (code-splitting) so
+// pages that only use the corner companion never download the playground.
+
+import { build } from 'esbuild';
+import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const outDir = resolve(here, 'dist');
+
+rmSync(outDir, { recursive: true, force: true });
+mkdirSync(outDir, { recursive: true });
+
+const result = await build({
+ entryPoints: [resolve(here, 'src/index.js')],
+ outdir: outDir,
+ bundle: true,
+ format: 'esm',
+ splitting: true,
+ platform: 'browser',
+ target: 'es2020',
+ // Three.js and its addons are the peer dependency — never inline them.
+ external: ['three', 'three/addons/*'],
+ outExtension: { '.js': '.mjs' },
+ entryNames: '[name]',
+ chunkNames: 'chunk-[name]-[hash]',
+ legalComments: 'none',
+ metafile: true,
+ logLevel: 'info',
+});
+
+// Styles are injected at runtime by each module, so the ".css" subpath is a
+// no-op kept for forward-compatibility with side-effect `import` of the stylesheet.
+writeFileSync(
+ resolve(outDir, 'style.css'),
+ '/* @three-ws/walk — styles are injected at runtime by the companion, playground, and picker. */\n',
+);
+
+const out = Object.keys(result.metafile.outputs)
+ .map((p) => p.replace(/^.*walk-sdk\//, ''))
+ .sort();
+console.log('[walk-sdk] built:\n ' + out.join('\n '));
diff --git a/walk-sdk/package.json b/walk-sdk/package.json
new file mode 100644
index 000000000..89567ac5e
--- /dev/null
+++ b/walk-sdk/package.json
@@ -0,0 +1,68 @@
+{
+ "name": "@three-ws/walk",
+ "version": "0.1.0",
+ "description": "A diverse, animated 3D avatar that walks and talks over your web pages — corner companion + full-page playground, with a built-in avatar picker. Powered by Three.js.",
+ "keywords": [
+ "3d",
+ "avatar",
+ "three.js",
+ "webgl",
+ "mascot",
+ "companion",
+ "walking",
+ "playground",
+ "gltf",
+ "glb",
+ "animation",
+ "retargeting",
+ "agent"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/walk",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "walk-sdk"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "type": "module",
+ "main": "./dist/index.mjs",
+ "module": "./dist/index.mjs",
+ "types": "./types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./roster": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./style.css": "./dist/style.css"
+ },
+ "files": [
+ "dist",
+ "src",
+ "types",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "node build.mjs",
+ "prepublishOnly": "npm run build"
+ },
+ "peerDependencies": {
+ "three": ">=0.150.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.js
index 58c2324e1..4263e5b64 100644
--- a/walk-sdk/src/playground.js
+++ b/walk-sdk/src/playground.js
@@ -1155,3 +1155,16 @@ export function playgroundState() {
}
return { ...base, speed: Math.round(Math.hypot(c.vx, c.vy)), onLink: !!_instance._armHref };
}
+
+// Console/debug convenience + the surface a few pages (e.g. the IBM demo)
+// drive directly. Set when this (lazy) module loads, in either host or
+// standalone use.
+if (typeof window !== 'undefined') {
+ window.__walkPlayground = {
+ launch: launchPlayground,
+ exit: exitPlayground,
+ switchMode: switchPlaygroundMode,
+ mode: getPlaygroundMode,
+ state: playgroundState,
+ };
+}
diff --git a/walk-sdk/types/index.d.ts b/walk-sdk/types/index.d.ts
new file mode 100644
index 000000000..870e93996
--- /dev/null
+++ b/walk-sdk/types/index.d.ts
@@ -0,0 +1,164 @@
+// Type definitions for @three-ws/walk
+import type { Object3D } from 'three';
+
+export declare const VERSION: string;
+
+/** How a roster avatar is animated. */
+export type WalkRig = 'embedded' | 'shared';
+
+/** Logical animation states the controller understands. */
+export type WalkState = 'idle' | 'walk' | 'run' | 'jump';
+
+/** Mapping of logical states to clip names (shared rig) or candidate name lists (embedded rig). */
+export interface WalkClipMap {
+ idle?: string | string[];
+ walk?: string | string[];
+ run?: string | string[];
+ wave?: string | string[];
+ jump?: string | string[];
+}
+
+/** A single avatar in the roster. */
+export interface WalkAvatar {
+ id: string;
+ name: string;
+ emoji?: string;
+ blurb?: string;
+ category: string;
+ /** GLB path resolved against `assetBase`; null for API-served avatars. */
+ asset: string | null;
+ source: 'static' | 'api';
+ rig: WalkRig;
+ clips?: WalkClipMap;
+ thumb?: string;
+ accent?: string;
+ tags?: string[];
+}
+
+export declare const WALK_AVATARS: WalkAvatar[];
+export declare const DEFAULT_AVATAR_ID: string;
+export declare const DEFAULT_SHARED_CLIPS: Record<string, string>;
+
+export declare function getAvatar(id: string): WalkAvatar | null;
+export declare function defaultAvatar(): WalkAvatar;
+export declare function listCategories(): string[];
+export declare function makeApiAvatarEntry(
+ id: string,
+ opts?: { name?: string; accent?: string },
+): WalkAvatar;
+export declare function resolveAvatarUrl(
+ entry: WalkAvatar,
+ opts?: { assetBase?: string; apiBase?: string },
+): string | null;
+
+/** Options accepted by `createWalkCompanion`. */
+export interface WalkCompanionOptions {
+ /** Roster shown in the picker and resolvable by id. Defaults to WALK_AVATARS. */
+ avatars?: WalkAvatar[];
+ /** Avatar to load when none is chosen/stored. Defaults to 'robot'. */
+ defaultAvatarId?: string;
+ /** Base prepended to static GLB paths (e.g. a CDN origin). */
+ assetBase?: string;
+ /** Base prepended to the `/api/avatars/<id>/glb` proxy. */
+ apiBase?: string;
+ /** URL of the shared animation manifest. Defaults to '/animations/manifest.json'. */
+ manifestUrl?: string;
+ /** Route prefixes where the companion never mounts. */
+ excludedRoutes?: string[];
+ /** Show the avatar picker button. Defaults to true. */
+ enablePicker?: boolean;
+ /** Override the page-context greeting; return null to fall back to the default. */
+ greeting?: (path: string) => string | null;
+ /** Optional "make your own" link shown in the picker footer. */
+ docsUrl?: string;
+ /** Storage key prefix. Defaults to 'walk'. */
+ storagePrefix?: string;
+}
+
+/** The controller returned by `createWalkCompanion`. */
+export interface WalkCompanionControl {
+ readonly instance: unknown;
+ isEnabled(): boolean;
+ enable(): void;
+ disable(): void;
+ toggle(): void;
+ /** Persist and (if mounted) hot-swap the live avatar. */
+ setAvatar(idOrEntry: string | WalkAvatar): void;
+ openPicker(): void;
+ /** Run the app-style auto-mount + deep-link logic (reads ?walk= and saved state). */
+ bootstrap(): void;
+}
+
+export declare function createWalkCompanion(opts?: WalkCompanionOptions): WalkCompanionControl;
+
+/** A controller exposing setState/playWave for a loaded avatar. */
+export interface WalkController {
+ setState(state: WalkState): void;
+ playWave(): void;
+ update(dt: number): void;
+ dispose(): void;
+}
+
+export declare function loadWalkAvatar(
+ entry: WalkAvatar,
+ opts?: {
+ assetBase?: string;
+ apiBase?: string;
+ manifestUrl?: string;
+ fallbackEntry?: WalkAvatar | null;
+ waveMs?: number;
+ },
+): Promise<{ model: Object3D; controller: WalkController; gltf: unknown; entry: WalkAvatar }>;
+
+export type PlaygroundMode = 'stroll' | 'platformer';
+
+export declare function launchPlayground(opts?: {
+ avatarId?: string | null;
+ startScreen?: { x: number; y: number } | null;
+ dropIn?: boolean;
+ mode?: PlaygroundMode;
+ config?: unknown;
+}): unknown;
+export declare function exitPlayground(): void;
+export declare function switchPlaygroundMode(forceMode?: PlaygroundMode | null): unknown;
+export declare function getPlaygroundMode(): PlaygroundMode;
+export declare function shouldDropIn(config?: unknown): boolean;
+export declare function consumeDropIn(config?: unknown): boolean;
+export declare function playgroundState(): Record<string, unknown> | null;
+
+/** Avatar picker popover. */
+export interface AvatarPicker {
+ el: HTMLElement;
+ show(): void;
+ close(): void;
+ toggle(): void;
+ isOpen(): boolean;
+ setCurrent(id: string): void;
+ destroy(): void;
+}
+
+export declare function createAvatarPicker(opts: {
+ avatars: WalkAvatar[];
+ currentId?: string | null;
+ onSelect: (entry: WalkAvatar) => void;
+ anchor?: { right: number; bottom: number };
+ assetBase?: string;
+ docsUrl?: string;
+}): AvatarPicker;
+
+export interface WalkConfig {
+ avatars: WalkAvatar[];
+ defaultAvatarId: string;
+ assetBase: string;
+ apiBase: string;
+ manifestUrl: string;
+ excludedRoutes: string[];
+ enablePicker: boolean;
+ greeting: ((path: string) => string | null) | null;
+ docsUrl: string | null;
+ keys: Record<string, string>;
+}
+
+export declare function resolveConfig(opts?: WalkCompanionOptions): WalkConfig;
+export declare function resolveAvatarEntry(id: string | null, config: WalkConfig): WalkAvatar;
+export declare const DEFAULT_EXCLUDED_PREFIXES: string[];
diff --git a/x402-modal-sdk/src/global.js b/x402-modal-sdk/src/global.js
new file mode 100644
index 000000000..3cdb9a63c
--- /dev/null
+++ b/x402-modal-sdk/src/global.js
@@ -0,0 +1,64 @@
+// @three-ws/x402-modal — global / CDN entry.
+//
+// This is the side-effectful build that ships as the drop-in <script>. It:
+// 1. reads `data-x402-*` config off its own <script> tag (apiOrigin, brand,
+// builderCode) so a self-hosted deployment can repoint the backend without
+// a line of JS,
+// 2. binds every `[data-x402-endpoint]` element and re-scans the DOM as
+// merchants inject buttons,
+// 3. exposes `window.X402 = { pay, init, configure, version }`.
+//
+// For bundler / npm consumers, import the side-effect-free core instead:
+// import { pay, configure } from '@three-ws/x402-modal';
+
+import { pay, init, configure, version } from './x402-modal.js';
+
+// Pull optional config off the script tag, e.g.
+// <script src=".../x402.global.js"
+// data-x402-api-origin="https://pay.example.com"
+// data-x402-brand-label="Powered by Acme"
+// data-x402-brand-href="https://acme.com"
+// data-x402-builder-wallet="acme"
+// data-x402-builder-service="acme_checkout"></script>
+function readScriptConfig() {
+ if (typeof document === 'undefined') return;
+ const el = document.currentScript || document.querySelector('script[src*="x402.global"], script[src*="/x402.js"]');
+ const ds = el?.dataset;
+ if (!ds) return;
+ const cfg = {};
+ if (ds.x402ApiOrigin !== undefined) cfg.apiOrigin = ds.x402ApiOrigin;
+ if (ds.x402BrandLabel !== undefined || ds.x402BrandHref !== undefined) {
+ cfg.brand = {};
+ if (ds.x402BrandLabel !== undefined) cfg.brand.label = ds.x402BrandLabel;
+ if (ds.x402BrandHref !== undefined) cfg.brand.href = ds.x402BrandHref;
+ }
+ if (ds.x402BuilderDisable === 'true' || ds.x402BuilderDisable === '') {
+ cfg.builderCode = null;
+ } else if (ds.x402BuilderWallet !== undefined || ds.x402BuilderService !== undefined) {
+ cfg.builderCode = {};
+ if (ds.x402BuilderWallet !== undefined) cfg.builderCode.wallet = ds.x402BuilderWallet;
+ if (ds.x402BuilderService !== undefined) cfg.builderCode.service = ds.x402BuilderService;
+ }
+ if (ds.x402SolanaWeb3Url) cfg.solanaWeb3Url = ds.x402SolanaWeb3Url;
+ if (ds.x402NobleHashesUrl) cfg.nobleHashesUrl = ds.x402NobleHashesUrl;
+ if (Object.keys(cfg).length) configure(cfg);
+}
+
+if (typeof document !== 'undefined') {
+ readScriptConfig();
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init, { once: true });
+ } else {
+ init();
+ }
+ // Re-scan when merchants dynamically inject buttons.
+ const mo = new MutationObserver(() => init());
+ mo.observe(document.documentElement, { childList: true, subtree: true });
+}
+
+// Expose to merchants' inline scripts.
+if (typeof window !== 'undefined') {
+ window.X402 = Object.freeze({ pay, init, configure, version });
+}
+
+export { pay, init, configure, version };
diff --git a/x402-modal-sdk/src/x402-modal.js b/x402-modal-sdk/src/x402-modal.js
new file mode 100644
index 000000000..49c356950
--- /dev/null
+++ b/x402-modal-sdk/src/x402-modal.js
@@ -0,0 +1,1577 @@
+// @three-ws/x402-modal — a drop-in payment modal for any x402 paid endpoint.
+//
+// This is the canonical, side-effect-free core. It exports the public API
+// (`pay`, `init`, `configure`, `siwx`, `version`, `CheckoutModal`) but does NOT
+// touch `window` or auto-bind anything on import — that lives in `global.js`,
+// which is what the CDN <script> build ships.
+//
+// Bundler / npm usage:
+//
+// import { pay, configure } from '@three-ws/x402-modal';
+// const out = await pay({ endpoint: '/api/paid/summarize', body: { text: 'hi' } });
+//
+// Drop-in <script> usage (the global build auto-binds `data-x402-endpoint`):
+//
+// <script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script>
+// <button data-x402-endpoint="/api/paid/summarize" data-x402-method="POST">Pay & run</button>
+//
+// The modal drives the full 402 → connect wallet → sign → retry → settle flow,
+// renders price/network/steps/receipt, and resolves with { ok, result, payment,
+// response }. Vanilla JS; the only network deps (Solana web3.js, a keccak for
+// EVM SIWX) are dynamic-imported from a CDN, and only when that path runs.
+
+const VERSION = '0.2.0';
+
+// ─────────────────────────────────────────────────────────── configuration ───
+// Everything the host wants to brand or repoint lives here. Defaults reproduce
+// three.ws's hosted behaviour exactly, so the drop-in script is unchanged; a
+// standalone deployment overrides them with `configure()` (global) or per-call
+// `pay({ ... })` options (which always win over the global config).
+
+const DEFAULTS = {
+ // Origin that serves the Solana `prepare` / `encode` checkout helpers
+ // (POST {origin}/api/x402-checkout?action=prepare|encode). Only the Solana
+ // payment path uses these — the EVM/EIP-3009 path is fully client-side and
+ // needs no backend. `null` ⇒ resolve from the script's own origin at runtime.
+ apiOrigin: null,
+ // Footer attribution shown at the bottom of the modal.
+ brand: { label: 'Powered by three.ws', href: 'https://three.ws' },
+ // ERC-8021 builder-code self-attribution echoed back when the 402 challenge
+ // declares a builder code. `wallet` = your wallet code, `service` = your
+ // integration code. Set to null to disable the echo entirely.
+ builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
+ // CDN modules dynamic-imported on demand. Override to self-host / satisfy a
+ // strict Content-Security-Policy.
+ solanaWeb3Url: 'https://esm.sh/@solana/[email protected]?bundle',
+ nobleHashesUrl: 'https://esm.sh/@noble/[email protected]/sha3?bundle',
+};
+
+const config = {
+ apiOrigin: DEFAULTS.apiOrigin,
+ brand: { ...DEFAULTS.brand },
+ builderCode: DEFAULTS.builderCode ? { ...DEFAULTS.builderCode } : null,
+ solanaWeb3Url: DEFAULTS.solanaWeb3Url,
+ nobleHashesUrl: DEFAULTS.nobleHashesUrl,
+};
+
+// Resolve the origin that hosts this script — used as the default API origin for
+// the Solana prepare/encode helpers. Falls back to the page origin.
+function resolveScriptOrigin() {
+ try {
+ if (typeof document !== 'undefined') {
+ const current = document.currentScript;
+ if (current?.src) return new URL(current.src).origin;
+ const found = document.querySelector('script[src*="x402"]');
+ if (found?.src) return new URL(found.src).origin;
+ }
+ } catch (_) {}
+ return typeof location !== 'undefined' ? location.origin : '';
+}
+
+// Merge user config in. `apiOrigin: ''` is honoured (same-origin); only
+// `undefined` keeps the default. Returns the resolved snapshot for inspection.
+export function configure(opts = {}) {
+ if (!opts || typeof opts !== 'object') return getConfig();
+ if (opts.apiOrigin !== undefined) config.apiOrigin = opts.apiOrigin;
+ if (opts.brand) config.brand = { ...config.brand, ...opts.brand };
+ if (opts.builderCode === null) config.builderCode = null;
+ else if (opts.builderCode) config.builderCode = { ...(config.builderCode || {}), ...opts.builderCode };
+ if (opts.solanaWeb3Url) config.solanaWeb3Url = opts.solanaWeb3Url;
+ if (opts.nobleHashesUrl) config.nobleHashesUrl = opts.nobleHashesUrl;
+ return getConfig();
+}
+
+export function getConfig() {
+ return {
+ apiOrigin: config.apiOrigin,
+ brand: { ...config.brand },
+ builderCode: config.builderCode ? { ...config.builderCode } : null,
+ solanaWeb3Url: config.solanaWeb3Url,
+ nobleHashesUrl: config.nobleHashesUrl,
+ };
+}
+
+// The effective API origin for a given pay() call: explicit per-call > global
+// config > lazily-resolved script origin (cached back into config).
+function apiOriginFor(opts) {
+ if (opts && opts.apiOrigin !== undefined && opts.apiOrigin !== null) return opts.apiOrigin;
+ if (config.apiOrigin !== null && config.apiOrigin !== undefined) return config.apiOrigin;
+ config.apiOrigin = resolveScriptOrigin();
+ return config.apiOrigin;
+}
+
+// SIWX ("Sign-In-With-X" / CAIP-122) lets a wallet that has already paid for
+// an endpoint re-enter it by signing a challenge instead of paying again. The
+// server advertises support by including `extensions['sign-in-with-x']` in the
+// 402 body; clients submit signed proofs via the `SIGN-IN-WITH-X` header.
+const SIWX_HEADER = 'SIGN-IN-WITH-X';
+const SIWX_EXTENSION_KEY = 'sign-in-with-x';
+
+// USDC EIP-3009 typed-data sig works against Base USDC at this address. The
+// domain `version` must match the on-chain `EIP712_DOMAIN_SEPARATOR_VERSION`
+// of the deployed USDC implementation — Base USDC is at version "2".
+const EVM_NETWORKS = {
+ 'eip155:8453': { chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/' },
+ 'eip155:84532': { chainId: 84532, name: 'Base Sepolia', explorer: 'https://sepolia.basescan.org/tx/' },
+ 'eip155:42161': { chainId: 42161, name: 'Arbitrum', explorer: 'https://arbiscan.io/tx/' },
+ 'eip155:10': { chainId: 10, name: 'Optimism', explorer: 'https://optimistic.etherscan.io/tx/' },
+};
+
+// Normalize a single 402 `accept` entry to the shape the modal speaks
+// internally. The x402 spec's canonical atomic-price field is
+// `maxAmountRequired`; some merchants emit `amount`. We read `amount`
+// everywhere downstream, so coerce here once at ingestion. Without this, a
+// spec-compliant merchant yields `accept.amount === undefined` → "NaN USDC".
+function normalizeAccept(accept) {
+ if (!accept || typeof accept !== 'object') return accept;
+ const amount = accept.amount ?? accept.maxAmountRequired;
+ return amount != null && accept.amount == null ? { ...accept, amount: String(amount) } : accept;
+}
+
+function isSolanaNetwork(net) {
+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
+}
+function isEvmNetwork(net) {
+ return typeof net === 'string' && net.startsWith('eip155:');
+}
+// The modal only signs EIP-3009 transferWithAuthorization for EVM. When the
+// server publishes both an EIP-3009 entry and a Permit2 sibling (the
+// gas-sponsoring path used by @x402/evm SDK clients), we must pick the
+// EIP-3009 one. The sibling carries `extra.assetTransferMethod === 'permit2'`.
+function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ const method = accept?.extra?.assetTransferMethod;
+ return !method || method === 'eip3009';
+}
+function networkLabel(net, accept) {
+ if (isSolanaNetwork(net)) return 'Solana';
+ const meta = EVM_NETWORKS[net];
+ return meta?.name || accept?.extra?.name || net;
+}
+function explorerUrl(net, tx) {
+ if (!tx) return null;
+ if (isSolanaNetwork(net)) return `https://solscan.io/tx/${tx}`;
+ const meta = EVM_NETWORKS[net];
+ return meta ? `${meta.explorer}${tx}` : null;
+}
+
+function formatAmount(rawAtomics, decimals = 6) {
+ const n = Number(rawAtomics) / 10 ** decimals;
+ if (n < 0.01) return n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
+ if (n < 1) return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ return n.toFixed(2);
+}
+
+function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+function b64decode(str) {
+ if (!str) return null;
+ try {
+ const bin = typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64').toString('utf8') : decodeURIComponent(escape(atob(str)));
+ return JSON.parse(bin);
+ } catch (_) {
+ return null;
+ }
+}
+
+// ──────────────────────────────────────────────────────── Spending caps ─────
+// Persists per-wallet spend in localStorage so reload-survivable caps work in a
+// pure-browser context. Keys are bucketed by UTC hour and UTC day so the
+// sliding windows reset cleanly at midnight UTC for the daily case. Amounts are
+// stored as base-10 BigInt strings of micro-USD; stablecoin payments flow
+// through as-is since their atomics are already 6-decimal USD-pegged.
+
+const SPEND_LS_PREFIX = 'x402.spend.';
+const STABLE_NAMES = new Set([
+ 'usdc', 'usd coin', 'usdt', 'tether', 'binance-peg usd coin', 'dai',
+]);
+
+function spendBuckets(timestamp = Date.now()) {
+ const hour = Math.floor(timestamp / 3_600_000);
+ const day = Math.floor(timestamp / 86_400_000);
+ return { hour, day };
+}
+
+function spendKey(address, kind, bucket) {
+ return `${SPEND_LS_PREFIX}${kind}.${address.toLowerCase()}.${bucket}`;
+}
+
+function readSpend(address, kind, bucket) {
+ try {
+ const raw = localStorage.getItem(spendKey(address, kind, bucket));
+ if (!raw) return 0n;
+ return BigInt(raw);
+ } catch {
+ return 0n;
+ }
+}
+
+function writeSpend(address, kind, bucket, value) {
+ try {
+ localStorage.setItem(spendKey(address, kind, bucket), value.toString());
+ } catch {
+ // localStorage full / disabled — caps degrade to per-call only.
+ }
+}
+
+function toMicroUsdBrowser(amount, accept) {
+ const atomic = BigInt(amount);
+ const decimals = Number(accept?.extra?.decimals ?? 6);
+ const name = String(accept?.extra?.name || '').toLowerCase();
+ if (STABLE_NAMES.has(name)) {
+ if (decimals === 6) return atomic;
+ if (decimals > 6) return atomic / 10n ** BigInt(decimals - 6);
+ return atomic * 10n ** BigInt(6 - decimals);
+ }
+ // Non-stable in the browser modal: we don't fetch live prices to keep the
+ // drop-in script dependency-free. Cap enforcement for non-stable assets must
+ // be done server-side.
+ return atomic;
+}
+
+// Check the configured caps and, if admitted, reserve the spend in localStorage.
+// Returns { abort, reason?, reservation? }. Reservation carries { address,
+// microUsd, buckets } so a failed payment can roll the reservation back.
+function browserEnforceCap({ accept, caps, address }) {
+ if (!caps || !address) return { abort: false };
+ const microUsd = toMicroUsdBrowser(accept.amount, accept);
+ const maxPerCall = caps.maxPerCall != null ? BigInt(caps.maxPerCall) : null;
+ const maxPerHour = caps.maxPerHour != null ? BigInt(caps.maxPerHour) : null;
+ const maxPerDay = caps.maxPerDay != null ? BigInt(caps.maxPerDay) : null;
+ if (maxPerCall != null && microUsd > maxPerCall) {
+ return { abort: true, reason: `Per-call cap exceeded (${microUsd} > ${maxPerCall} µUSD)` };
+ }
+ const buckets = spendBuckets();
+ const hourTotal = readSpend(address, 'hr', buckets.hour) + microUsd;
+ const dayTotal = readSpend(address, 'day', buckets.day) + microUsd;
+ if (maxPerHour != null && hourTotal > maxPerHour) {
+ return { abort: true, reason: `Hourly cap exceeded (${hourTotal} > ${maxPerHour} µUSD)` };
+ }
+ if (maxPerDay != null && dayTotal > maxPerDay) {
+ return { abort: true, reason: `Daily cap exceeded (${dayTotal} > ${maxPerDay} µUSD)` };
+ }
+ writeSpend(address, 'hr', buckets.hour, hourTotal);
+ writeSpend(address, 'day', buckets.day, dayTotal);
+ return { abort: false, reservation: { address, microUsd, buckets } };
+}
+
+function browserRollbackReservation(reservation) {
+ if (!reservation) return;
+ const { address, microUsd, buckets } = reservation;
+ const hourCurrent = readSpend(address, 'hr', buckets.hour);
+ const dayCurrent = readSpend(address, 'day', buckets.day);
+ const hourNext = hourCurrent - microUsd;
+ const dayNext = dayCurrent - microUsd;
+ writeSpend(address, 'hr', buckets.hour, hourNext < 0n ? 0n : hourNext);
+ writeSpend(address, 'day', buckets.day, dayNext < 0n ? 0n : dayNext);
+}
+
+// ──────────────────────────────────────────── ERC-8021 builder-code echo ────
+// The server enforces that any client-echoed builder-code `a` matches what the
+// 402 challenge declared (anti-tamper). We self-attribute `w` (wallet) and `s`
+// (service) from config; both are validated against the strict code pattern.
+
+const BUILDER_CODE_KEY = 'builder-code';
+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
+
+function buildBuilderCodeEcho(challenge) {
+ const codes = config.builderCode;
+ if (!codes) return null;
+ const ext = challenge?.extensions?.[BUILDER_CODE_KEY];
+ const declaredA = ext?.info?.a;
+ if (!declaredA || !BUILDER_CODE_PATTERN.test(declaredA)) return null;
+ const out = { a: declaredA };
+ if (codes.service && BUILDER_CODE_PATTERN.test(codes.service)) out.s = [codes.service];
+ if (codes.wallet && BUILDER_CODE_PATTERN.test(codes.wallet)) out.w = codes.wallet;
+ return out;
+}
+
+// ─────────────────────────────────────────────────────────── SIWX helpers ────
+
+function extractSiwxExtension(body) {
+ const ext = body?.extensions?.[SIWX_EXTENSION_KEY];
+ if (!ext || !ext.info || !Array.isArray(ext.supportedChains) || !ext.supportedChains.length) return null;
+ return ext;
+}
+
+// Returns { chain, kind: 'evm' | 'solana' } or null. `chain` is the matching
+// entry from `ext.supportedChains` whose signature type matches the wallet kind.
+function pickSiwxChain(ext, walletKind) {
+ for (const chain of ext.supportedChains) {
+ if (walletKind === 'evm' && chain.type === 'eip191') return { chain, kind: 'evm' };
+ if (walletKind === 'solana' && chain.type === 'ed25519') return { chain, kind: 'solana' };
+ }
+ return null;
+}
+
+// Build the CAIP-122 message string. The server rebuilds the same string from
+// payload fields when verifying — any line-by-line drift makes the recovered
+// signer mismatch payload.address and the signature is rejected.
+function buildSiwxMessage(info, chain, address) {
+ const isEvm = chain.type === 'eip191';
+ const accountHeader = isEvm
+ ? `${info.domain} wants you to sign in with your Ethereum account:`
+ : `${info.domain} wants you to sign in with your Solana account:`;
+ const [, chainTail = ''] = String(chain.chainId).split(':');
+ const chainRef = isEvm ? String(parseInt(chainTail, 10)) : chainTail;
+
+ const lines = [accountHeader, address, ''];
+ if (info.statement) {
+ lines.push(info.statement, '');
+ } else if (isEvm) {
+ // siwe's prepareMessage() reserves the statement block even when the
+ // statement is absent, emitting an extra blank line. SIWS does not. The
+ // server rebuilds the EVM message via siwe before recovering the signer,
+ // so omit-statement EVM must carry the same extra blank.
+ lines.push('');
+ }
+ lines.push(`URI: ${info.uri}`);
+ lines.push(`Version: ${info.version || '1'}`);
+ lines.push(`Chain ID: ${chainRef}`);
+ lines.push(`Nonce: ${info.nonce}`);
+ lines.push(`Issued At: ${info.issuedAt}`);
+ if (info.expirationTime) lines.push(`Expiration Time: ${info.expirationTime}`);
+ if (info.notBefore) lines.push(`Not Before: ${info.notBefore}`);
+ if (info.requestId !== undefined && info.requestId !== null) lines.push(`Request ID: ${info.requestId}`);
+ if (Array.isArray(info.resources) && info.resources.length) {
+ lines.push('Resources:');
+ for (const r of info.resources) lines.push(`- ${r}`);
+ }
+ return lines.join('\n');
+}
+
+// Base64-encoded JSON per x402 v2 spec. CAIP-122 fields are all ASCII/Latin-1,
+// so the unescape+encodeURIComponent dance matches what btoa expects.
+function encodeSiwxHeaderValue(payload) {
+ const json = JSON.stringify(payload);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+
+// Base58 (Bitcoin alphabet) — Solana's encoding for both addresses and
+// signatures. Inlined here to avoid pulling in a bundler dependency.
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+function base58encode(bytes) {
+ if (!bytes || bytes.length === 0) return '';
+ let leadingZeros = 0;
+ while (leadingZeros < bytes.length && bytes[leadingZeros] === 0) leadingZeros++;
+ let n = 0n;
+ for (let i = 0; i < bytes.length; i++) n = (n << 8n) | BigInt(bytes[i]);
+ let out = '';
+ while (n > 0n) {
+ out = BASE58_ALPHABET[Number(n % 58n)] + out;
+ n /= 58n;
+ }
+ for (let i = 0; i < leadingZeros; i++) out = BASE58_ALPHABET[0] + out;
+ return out;
+}
+
+// EIP-55 checksum the address before signing. MetaMask returns lowercase
+// addresses, but the server rebuilds the SIWE message with a checksummed
+// address. If we sign a lowercase-address message and send the lowercase
+// address in the payload, the recovered signer differs and verification fails.
+// Keccak-256 is dynamic-imported from a CDN only when SIWX EVM sign-in runs.
+let _evmChecksum = null;
+async function loadEvmChecksum() {
+ if (_evmChecksum) return _evmChecksum;
+ const sha3 = await import(/* @vite-ignore */ config.nobleHashesUrl);
+ const keccak = sha3.keccak_256;
+ _evmChecksum = (addr) => {
+ const a = String(addr).toLowerCase().replace(/^0x/, '');
+ if (!/^[0-9a-f]{40}$/.test(a)) throw new Error(`invalid EVM address: ${addr}`);
+ const hashBytes = keccak(new TextEncoder().encode(a));
+ let hex = '';
+ for (let i = 0; i < hashBytes.length; i++) hex += hashBytes[i].toString(16).padStart(2, '0');
+ let out = '0x';
+ for (let i = 0; i < 40; i++) {
+ out += parseInt(hex[i], 16) >= 8 ? a[i].toUpperCase() : a[i];
+ }
+ return out;
+ };
+ return _evmChecksum;
+}
+
+// ───────────────────────────────────────────────────────────────── styles ────
+
+const STYLE_ID = 'x402-styles';
+const STYLES = `
+:root {
+ --x402-z: 2147483600;
+}
+.x402-overlay {
+ position: fixed; inset: 0;
+ background: rgba(8, 10, 18, 0.55);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ display: flex; align-items: center; justify-content: center;
+ z-index: var(--x402-z);
+ opacity: 0; transition: opacity 0.16s ease-out;
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ color: #0f0f0f;
+}
+.x402-overlay.x402-open { opacity: 1; }
+.x402-overlay * { box-sizing: border-box; }
+.x402-modal {
+ width: calc(100% - 32px); max-width: 420px;
+ background: #ffffff;
+ border-radius: 18px;
+ box-shadow: 0 24px 80px rgba(8, 10, 18, 0.28), 0 4px 16px rgba(8, 10, 18, 0.12);
+ overflow: hidden;
+ transform: translateY(8px) scale(0.985);
+ transition: transform 0.18s ease-out;
+ display: flex; flex-direction: column;
+ max-height: calc(100dvh - 32px);
+}
+.x402-overlay.x402-open .x402-modal { transform: translateY(0) scale(1); }
+.x402-head {
+ padding: 18px 20px 14px;
+ border-bottom: 1px solid #eef0f4;
+ display: flex; align-items: center; gap: 12px;
+}
+.x402-head .x402-merchant {
+ flex: 1; min-width: 0;
+}
+.x402-merchant .x402-name {
+ font-size: 12px; color: #5a6378; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase;
+ margin-bottom: 2px;
+}
+.x402-merchant .x402-action {
+ font-size: 17px; font-weight: 700; color: #0f0f0f;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ letter-spacing: -0.01em;
+}
+.x402-close {
+ width: 32px; height: 32px;
+ border-radius: 8px; border: none; background: #f3f4f7;
+ font-size: 16px; color: #5a6378; cursor: pointer;
+ display: flex; align-items: center; justify-content: center;
+ transition: background 0.12s;
+}
+.x402-close:hover { background: #e7e9ee; color: #0f0f0f; }
+
+.x402-price-row {
+ padding: 18px 20px;
+ display: flex; align-items: baseline; justify-content: space-between;
+ background: linear-gradient(180deg, #fafbfc 0%, #ffffff 100%);
+ border-bottom: 1px solid #eef0f4;
+}
+.x402-price {
+ font-size: 32px; font-weight: 700; letter-spacing: -0.02em; color: #0f0f0f;
+ font-variant-numeric: tabular-nums;
+}
+.x402-price .x402-currency { font-size: 14px; color: #5a6378; font-weight: 600; margin-left: 6px; letter-spacing: 0; }
+.x402-network {
+ font-size: 12px; color: #5a6378; font-weight: 500;
+ background: #f3f4f7; padding: 5px 10px; border-radius: 99px;
+ display: inline-flex; align-items: center; gap: 6px;
+}
+.x402-network::before {
+ content: ''; width: 6px; height: 6px; border-radius: 50%;
+ background: #22c55e;
+}
+
+.x402-body {
+ padding: 16px 20px 18px;
+ flex: 1 1 auto; overflow-y: auto;
+ display: flex; flex-direction: column; gap: 10px;
+}
+.x402-step {
+ display: flex; gap: 12px; align-items: flex-start;
+ padding: 10px 0;
+}
+.x402-step + .x402-step { border-top: 1px solid #f3f4f7; }
+.x402-step-num {
+ width: 22px; height: 22px; flex: 0 0 auto;
+ border-radius: 50%; border: 1.5px solid #d0d4dd; background: #fff;
+ color: #5a6378;
+ font-size: 11px; font-weight: 700;
+ display: flex; align-items: center; justify-content: center;
+}
+.x402-step.x402-active .x402-step-num {
+ border-color: #0a84ff; background: #0a84ff; color: #fff;
+ animation: x402-spin 1.2s linear infinite;
+}
+.x402-step.x402-done .x402-step-num {
+ border-color: #22c55e; background: #22c55e; color: #fff;
+}
+.x402-step.x402-error .x402-step-num {
+ border-color: #ef4444; background: #ef4444; color: #fff;
+}
+@keyframes x402-spin {
+ from { box-shadow: 0 0 0 0 rgba(10, 132, 255, 0.4); }
+ to { box-shadow: 0 0 0 8px rgba(10, 132, 255, 0); }
+}
+.x402-step-body { flex: 1; min-width: 0; }
+.x402-step-label { font-size: 14px; font-weight: 600; color: #0f0f0f; line-height: 1.35; }
+.x402-step-meta { font-size: 12px; color: #5a6378; margin-top: 2px; font-feature-settings: 'tnum' 1; }
+.x402-step.x402-error .x402-step-meta { color: #ef4444; }
+
+.x402-wallet-buttons {
+ display: flex; flex-direction: column; gap: 8px;
+ margin-top: 4px;
+}
+.x402-wallet-btn {
+ width: 100%; padding: 13px 14px;
+ background: #ffffff; border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; color: #0f0f0f;
+ cursor: pointer; font-family: inherit;
+ display: flex; align-items: center; gap: 12px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-wallet-btn:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-wallet-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-wallet-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+.x402-wallet-icon {
+ width: 28px; height: 28px; flex: 0 0 auto;
+ border-radius: 7px;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 16px;
+ background: #f3f4f7;
+}
+.x402-wallet-icon.x402-phantom { background: linear-gradient(135deg, #ab9ff2, #534bb1); color: #fff; }
+.x402-wallet-icon.x402-metamask { background: linear-gradient(135deg, #f6851b, #e2761b); color: #fff; }
+.x402-wallet-name { flex: 1; text-align: left; }
+.x402-wallet-meta { font-size: 11px; color: #8a90a8; font-weight: 500; }
+
+.x402-pay-btn {
+ width: 100%; padding: 14px 16px;
+ background: #0f0f0f; color: #fff; border: none;
+ border-radius: 12px;
+ font-size: 15px; font-weight: 700; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ transition: background 0.12s, transform 0.05s;
+ margin-top: 4px;
+ display: flex; align-items: center; justify-content: center; gap: 8px;
+}
+.x402-pay-btn:hover:not(:disabled) { background: #1d1d1d; }
+.x402-pay-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-pay-btn:disabled { background: #c8ccd4; cursor: not-allowed; }
+
+.x402-pay-secondary {
+ width: 100%; padding: 12px 14px;
+ background: #ffffff; color: #0f0f0f;
+ border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ margin-top: 6px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-pay-secondary:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-pay-secondary:active:not(:disabled) { transform: translateY(1px); }
+
+.x402-siwx-hint {
+ font-size: 11px; color: #5a6378; text-align: center;
+ margin-top: 8px; line-height: 1.4;
+}
+.x402-siwx-fallback {
+ font-size: 12px; color: #b45309; line-height: 1.45;
+ padding: 8px 10px; border-radius: 8px;
+ background: #fffbeb; border: 1px solid #fde68a;
+ margin-bottom: 6px;
+}
+
+.x402-error-box {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
+ font-size: 13px; line-height: 1.45;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ word-break: break-word;
+}
+.x402-error-box strong { font-weight: 700; }
+
+.x402-receipt {
+ padding: 14px 16px; border-radius: 12px;
+ background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
+ border: 1px solid #bbf7d0;
+}
+.x402-receipt-title {
+ font-size: 11px; font-weight: 700; color: #15803d;
+ text-transform: uppercase; letter-spacing: 0.06em;
+ margin-bottom: 8px;
+ display: flex; align-items: center; gap: 6px;
+}
+.x402-receipt-title::before { content: '✓'; font-size: 14px; }
+.x402-receipt-row {
+ display: flex; justify-content: space-between; gap: 12px;
+ font-size: 12px; padding: 2px 0;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+}
+.x402-receipt-row .x402-k { color: #5a6378; }
+.x402-receipt-row .x402-v { color: #0f0f0f; text-align: right; word-break: break-all; }
+.x402-receipt-row a { color: #0a84ff; text-decoration: none; }
+.x402-receipt-row a:hover { text-decoration: underline; }
+
+.x402-result {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fafbfc; border: 1px solid #e2e5ec;
+ max-height: 240px; overflow: auto;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ font-size: 12px; line-height: 1.5; color: #0f0f0f;
+ white-space: pre-wrap; word-break: break-word;
+}
+
+.x402-foot {
+ padding: 10px 20px 14px;
+ border-top: 1px solid #eef0f4;
+ display: flex; align-items: center; justify-content: space-between;
+ font-size: 11px; color: #8a90a8;
+}
+.x402-foot a { color: #5a6378; text-decoration: none; font-weight: 600; }
+.x402-foot a:hover { color: #0f0f0f; }
+.x402-foot .x402-secure { display: flex; align-items: center; gap: 5px; }
+.x402-foot .x402-secure::before { content: '🔒'; font-size: 10px; }
+
+@media (max-width: 480px) {
+ .x402-modal { max-width: none; width: calc(100% - 16px); border-radius: 16px; }
+ .x402-price { font-size: 26px; }
+}
+
+@media (prefers-color-scheme: dark) {
+ .x402-overlay { color: #e6e8f0; }
+ .x402-modal { background: #161616; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6); }
+ .x402-head, .x402-price-row, .x402-foot { border-color: #272727; }
+ .x402-step + .x402-step { border-top-color: #272727; }
+ .x402-merchant .x402-name { color: #8a90a8; }
+ .x402-merchant .x402-action, .x402-price, .x402-step-label { color: #e6e8f0; }
+ .x402-step-meta { color: #8a90a8; }
+ .x402-close { background: #222222; color: #8a90a8; }
+ .x402-close:hover { background: #2e2e2e; color: #e6e8f0; }
+ .x402-price-row { background: linear-gradient(180deg, #1d1d1d 0%, #161616 100%); }
+ .x402-network { background: #222222; color: #b0b6cc; }
+ .x402-wallet-btn { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-wallet-btn:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
+ .x402-wallet-icon { background: #2e2e2e; }
+ .x402-wallet-meta { color: #6b7088; }
+ .x402-pay-btn { background: #ffffff; color: #0f0f0f; }
+ .x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
+ .x402-pay-btn:disabled { background: #2e2e2e; color: #5a6378; }
+ .x402-pay-secondary { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-pay-secondary:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
+ .x402-siwx-hint { color: #8a90a8; }
+ .x402-siwx-fallback { background: #2a1d10; border-color: #78350f; color: #fcd34d; }
+ .x402-step-num { background: #161616; border-color: #2e2e2e; color: #8a90a8; }
+ .x402-result { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-receipt { background: linear-gradient(180deg, #0b1f17 0%, #161616 100%); border-color: #14532d; }
+ .x402-receipt-title { color: #4ade80; }
+ .x402-receipt-row .x402-k { color: #8a90a8; }
+ .x402-receipt-row .x402-v { color: #e6e8f0; }
+ .x402-receipt-row a { color: #60a5fa; }
+ .x402-error-box { background: #1f1416; border-color: #7f1d1d; color: #fca5a5; }
+ .x402-foot a { color: #b0b6cc; }
+ .x402-foot a:hover { color: #ffffff; }
+}
+`;
+
+function injectStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = STYLES;
+ document.head.appendChild(el);
+}
+
+// ───────────────────────────────────────────────────────────── modal class ───
+
+export class CheckoutModal {
+ constructor(opts) {
+ this.opts = opts;
+ this.steps = [
+ { id: 'discover', label: 'Confirming price' },
+ { id: 'connect', label: 'Connect wallet' },
+ { id: 'authorize', label: 'Authorize payment' },
+ { id: 'verify', label: 'Verify & complete' },
+ ];
+ this.activeNetwork = null;
+ this.payerAddress = null;
+ this.accept = null;
+ this.challenge = null;
+ this.disposed = false;
+ // One-shot guard for opts.autoConnect: we only auto-open the wallet on the
+ // first connect render, so an error that drops the user back to this step
+ // shows the manual picker instead of re-launching the wallet in a loop.
+ this.autoConnectTried = false;
+ }
+
+ _apiOrigin() {
+ return apiOriginFor(this.opts);
+ }
+
+ mount() {
+ injectStyles();
+ const brand = this.opts.brand || config.brand || {};
+ const overlay = document.createElement('div');
+ overlay.className = 'x402-overlay';
+ const brandHtml = brand.href
+ ? `<a href="${escapeHtml(brand.href)}" target="_blank" rel="noopener">${escapeHtml(brand.label || brand.href)}</a>`
+ : brand.label
+ ? `<span>${escapeHtml(brand.label)}</span>`
+ : '';
+ overlay.innerHTML = `
+ <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment">
+ <div class="x402-head">
+ <div class="x402-merchant">
+ <div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div>
+ <div class="x402-action" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div>
+ </div>
+ <button class="x402-close" data-close aria-label="Close">✕</button>
+ </div>
+ <div class="x402-price-row">
+ <div class="x402-price" data-price>—<span class="x402-currency"> USDC</span></div>
+ <div class="x402-network" data-network>resolving…</div>
+ </div>
+ <div class="x402-body" data-body></div>
+ <div class="x402-foot">
+ <span class="x402-secure">x402 · onchain settled</span>
+ ${brandHtml}
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+ this.overlay = overlay;
+ this.bodyEl = overlay.querySelector('[data-body]');
+ this.priceEl = overlay.querySelector('[data-price]');
+ this.networkEl = overlay.querySelector('[data-network]');
+ overlay.querySelector('[data-close]').addEventListener('click', () => this.close('cancelled'));
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) this.close('cancelled'); });
+ this.onKey = (e) => { if (e.key === 'Escape') this.close('cancelled'); };
+ document.addEventListener('keydown', this.onKey);
+ requestAnimationFrame(() => overlay.classList.add('x402-open'));
+ return new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ }
+
+ close(reason) {
+ if (this.disposed) return;
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ if (reason === 'cancelled' && this.reject) {
+ const err = new Error('cancelled');
+ err.code = 'cancelled';
+ this.reject(err);
+ }
+ }
+
+ renderSteps(activeId, status = {}) {
+ const html = this.steps
+ .map((s) => {
+ const state = status[s.id] || (s.id === activeId ? 'active' : 'idle');
+ const cls = state === 'active' ? 'x402-active' : state === 'done' ? 'x402-done' : state === 'error' ? 'x402-error' : '';
+ const meta = status[`${s.id}_meta`] || '';
+ const sym = state === 'done' ? '✓' : state === 'error' ? '!' : s.id === activeId && state === 'active' ? ' ' : (this.steps.findIndex((x) => x.id === s.id) + 1);
+ return `<div class="x402-step ${cls}">
+ <div class="x402-step-num">${sym}</div>
+ <div class="x402-step-body">
+ <div class="x402-step-label">${s.label}</div>
+ ${meta ? `<div class="x402-step-meta">${escapeHtml(meta)}</div>` : ''}
+ </div>
+ </div>`;
+ })
+ .join('');
+ return html;
+ }
+
+ setPrice(accept) {
+ const decimals = accept.extra?.decimals ?? 6;
+ const amount = formatAmount(accept.amount, decimals);
+ const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
+ this.networkEl.textContent = networkLabel(accept.network, accept);
+ }
+
+ renderConnect() {
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ const evmDetected = typeof window !== 'undefined' && window.ethereum;
+ const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
+ const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
+
+ // SIWX-first path: when the 402 advertises sign-in-with-x AND we have a
+ // compatible wallet, lead with "Sign in with wallet" (primary) and demote
+ // pay to a secondary action. payFlowOverride is set true when the user
+ // explicitly chooses to pay.
+ if (this.siwx && !this.payFlowOverride) {
+ const siwxSolana = phantomDetected ? pickSiwxChain(this.siwx, 'solana') : null;
+ const siwxEvm = evmDetected ? pickSiwxChain(this.siwx, 'evm') : null;
+ if (siwxSolana || siwxEvm) {
+ this.renderSiwxChoice({ siwxSolana, siwxEvm });
+ return;
+ }
+ }
+
+ // autoConnect (opt-in via opts.autoConnect): when the caller knows the user
+ // is wallet-ready and shouldn't have to pick, skip the picker and go
+ // straight to the signature — but only when exactly one supported wallet is
+ // actually detected. One-shot via autoConnectTried.
+ if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice) {
+ this.autoConnectTried = true;
+ const solanaViable = !!(solanaAccept && phantomDetected);
+ const evmViable = !!(evmAccept && evmDetected);
+ if (solanaViable && !evmViable) { this.runSolana(solanaAccept); return; }
+ if (evmViable && !solanaViable) { this.runEvm(evmAccept); return; }
+ }
+
+ const buttons = [];
+ if (solanaAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-phantom">P</div>
+ <span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span>
+ <span class="x402-wallet-meta">${networkLabel(solanaAccept.network, solanaAccept)}</span>
+ </button>
+ `);
+ }
+ if (evmAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-metamask">M</div>
+ <span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>
+ <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>
+ </button>
+ `);
+ }
+ const fallbackBox = this.siwxFallbackNotice
+ ? `<div class="x402-siwx-fallback">${escapeHtml(this.siwxFallbackNotice)}</div>`
+ : '';
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ ${fallbackBox}
+ <div class="x402-wallet-buttons">${buttons.join('')}</div>
+ `;
+ const onClick = (e) => {
+ const btn = e.target.closest('[data-wallet]');
+ if (!btn || btn.disabled) return;
+ const wallet = btn.dataset.wallet;
+ if (wallet === 'phantom') this.runSolana(solanaAccept);
+ else if (wallet === 'evm') this.runEvm(evmAccept);
+ };
+ this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
+ }
+
+ renderSiwxChoice({ siwxSolana, siwxEvm }) {
+ const priceText = formatAmount(this.accept.amount, this.accept.extra?.decimals ?? 6);
+ const siwxTarget = siwxSolana
+ ? { kind: 'solana', chain: siwxSolana.chain }
+ : { kind: 'evm', chain: siwxEvm.chain };
+ const siwxLabel = siwxTarget.kind === 'solana' ? 'Sign in with Phantom' : 'Sign in with wallet';
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ <button class="x402-pay-btn" data-action="siwx">${siwxLabel}</button>
+ <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
+ <div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
+ `;
+ const siwxBtn = this.bodyEl.querySelector('[data-action="siwx"]');
+ const payBtn = this.bodyEl.querySelector('[data-action="pay"]');
+ siwxBtn.addEventListener('click', () => {
+ if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain);
+ else this.runSiwxEvm(siwxTarget.chain);
+ });
+ payBtn.addEventListener('click', () => {
+ this.payFlowOverride = true;
+ this.renderConnect();
+ });
+ requestAnimationFrame(() => siwxBtn.focus());
+ }
+
+ renderProgress(activeId, meta = {}) {
+ this.bodyEl.innerHTML = this.renderSteps(activeId, {
+ discover: 'done',
+ connect: 'done',
+ ...(activeId === 'verify' ? { authorize: 'done' } : {}),
+ [`${activeId}_meta`]: meta.text || '',
+ ...meta.statuses,
+ });
+ }
+
+ renderError(stepId, message) {
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps(stepId, {
+ ...(stepId !== 'discover' ? { discover: 'done' } : {}),
+ ...(stepId === 'authorize' || stepId === 'verify' ? { connect: 'done' } : {}),
+ ...(stepId === 'verify' ? { authorize: 'done' } : {}),
+ [stepId]: 'error',
+ [`${stepId}_meta`]: 'failed',
+ })}
+ <div class="x402-error-box"><strong>${escapeHtml(stepId)}:</strong> ${escapeHtml(message)}</div>
+ <button class="x402-pay-btn" data-retry>Try again</button>
+ `;
+ this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());
+ }
+
+ renderDone({ result, payment, siwx }) {
+ const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ let receiptHtml;
+ if (siwx) {
+ const addrShort = siwx.address ? `${siwx.address.slice(0, 8)}…${siwx.address.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Welcome back!</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(siwx.network) || siwx.network || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">wallet</span>
+ <span class="x402-v">${escapeHtml(addrShort)}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">paid</span>
+ <span class="x402-v">previously · re-entered free</span>
+ </div>
+ </div>
+ `;
+ } else {
+ const explorer = explorerUrl(payment?.network, payment?.transaction);
+ const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Payment confirmed!</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">payer</span>
+ <span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
+ </div>
+ ${
+ payment?.transaction
+ ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
+ explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ }</span></div>`
+ : ''
+ }
+ </div>
+ `;
+ }
+ this.bodyEl.innerHTML = `
+ ${receiptHtml}
+ <div class="x402-result">${escapeHtml(resultStr).slice(0, 4000)}</div>
+ <button class="x402-pay-btn" data-done>Done</button>
+ `;
+ this.bodyEl.querySelector('[data-done]').addEventListener('click', () => {
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ });
+ }
+
+ async start() {
+ this.bodyEl.innerHTML = this.renderSteps('discover');
+ try {
+ const challenge = await discoverChallenge(this.opts);
+ this.challenge = challenge;
+ this.siwx = extractSiwxExtension(challenge);
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = null;
+ // Prefer Solana when Phantom is present, else first EIP-3009 EVM entry
+ // (skipping Permit2 siblings the modal can't sign for), else first accept.
+ const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));
+ const evm = challenge.accepts.find(isEip3009Accept);
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ this.accept = (phantomDetected && solana) || evm || challenge.accepts[0];
+ this.setPrice(this.accept);
+ this.renderConnect();
+ } catch (err) {
+ this.renderError('discover', err.message || String(err));
+ }
+ }
+
+ async runSolana(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
+ if (!payerAddress) throw new Error('Phantom did not return a public key');
+ this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
+ this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
+
+ const origin = this._apiOrigin();
+ const prep = await postJson(`${origin}/api/x402-checkout?action=prepare`, {
+ accept,
+ buyer: payerAddress,
+ });
+ this.renderProgress('authorize', { text: 'Confirm in Phantom…' });
+ const txBytes = base64ToUint8Array(prep.tx_base64);
+ // Phantom returns a fully-signed VersionedTransaction with the buyer's
+ // signature added. The facilitator's fee-payer signature is added during
+ // /settle.
+ const SolanaWeb3 = await loadSolanaWeb3();
+ const tx = SolanaWeb3.VersionedTransaction.deserialize(txBytes);
+ const signed = await provider.signTransaction(tx);
+ const signedB64 = uint8ArrayToBase64(signed.serialize());
+
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
+ const enc = await postJson(`${origin}/api/x402-checkout?action=encode`, {
+ accept,
+ signed_tx_base64: signedB64,
+ resource_url: new URL(this.opts.endpoint, location.href).href,
+ ...(builderCodeBlock ? { builder_code: builderCodeBlock } : {}),
+ });
+
+ await this.executePaid(enc.x_payment);
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runEvm(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const payerAddress = accounts?.[0];
+ if (!payerAddress) throw new Error('Wallet did not return an account');
+ this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
+
+ const meta = EVM_NETWORKS[accept.network];
+ if (!meta) throw new Error(`Unknown EVM network ${accept.network}`);
+ // Switch chain if needed.
+ const currentChainHex = await eth.request({ method: 'eth_chainId' });
+ const desiredChainHex = '0x' + meta.chainId.toString(16);
+ if (currentChainHex !== desiredChainHex) {
+ this.renderProgress('connect', { text: `Switch wallet to ${meta.name}…` });
+ try {
+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: desiredChainHex }] });
+ } catch (e) {
+ throw new Error(`Wallet is on ${currentChainHex}; please switch to ${meta.name} (${desiredChainHex}) and retry`);
+ }
+ }
+
+ this.renderProgress('authorize', { text: `Authorize ${formatAmount(accept.amount)} USDC…` });
+
+ // EIP-3009 transferWithAuthorization typed-data signature.
+ const validAfter = 0;
+ const validBefore = Math.floor(Date.now() / 1000) + (accept.maxTimeoutSeconds || 600);
+ const nonce = '0x' + randomHex(32);
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId: meta.chainId,
+ verifyingContract: accept.asset,
+ };
+ const types = {
+ EIP712Domain: [
+ { name: 'name', type: 'string' },
+ { name: 'version', type: 'string' },
+ { name: 'chainId', type: 'uint256' },
+ { name: 'verifyingContract', type: 'address' },
+ ],
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const message = {
+ from: payerAddress,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce,
+ };
+ const typedData = {
+ primaryType: 'TransferWithAuthorization',
+ types,
+ domain,
+ message,
+ };
+ const signature = await eth.request({
+ method: 'eth_signTypedData_v4',
+ params: [payerAddress, JSON.stringify(typedData)],
+ });
+
+ const paymentPayload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: this.opts.endpoint, mimeType: 'application/json' },
+ accepted: accept,
+ payload: {
+ signature,
+ // The facilitator /verify requires the EIP-3009 time bounds as
+ // decimal strings, not JSON numbers. The signature is unaffected:
+ // uint256 0 and "0" encode identically.
+ authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter: String(validAfter), validBefore: String(validBefore), nonce },
+ },
+ };
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
+ if (builderCodeBlock) {
+ paymentPayload.extensions = { 'builder-code': builderCodeBlock };
+ }
+ const xPayment = b64encode(paymentPayload);
+ await this.executePaid(xPayment);
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executePaid(xPayment, attempt = 0) {
+ this.renderProgress('verify', {
+ text: attempt ? 'Retrying after upstream throttle…' : 'Calling merchant endpoint…',
+ });
+ try {
+ const res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ 'X-PAYMENT': xPayment,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try {
+ result = JSON.parse(text);
+ } catch {
+ result = text;
+ }
+ } else {
+ result = text;
+ }
+ if (!res.ok) {
+ // A 429 here is a transient upstream throttle. The payment is signed
+ // but NOT yet settled — the merchant runs the work before settling —
+ // so the same X-PAYMENT can be safely re-sent once the window resets,
+ // with no risk of a double charge.
+ if (res.status === 429 && attempt < MAX_THROTTLE_RETRIES) {
+ await this.waitForThrottle(retryAfterSeconds(res, result));
+ return this.executePaid(xPayment, attempt + 1);
+ }
+ const msg = (result && typeof result === 'object' && (result.error_description || result.error)) || `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ const settleHeader = res.headers.get('x-payment-response');
+ const payment = b64decode(settleHeader) || {};
+ this.spendReservation = null;
+ this.renderDone({ result, payment });
+ this.resolve?.({ ok: true, result, payment, response: { status: res.status, headers: headersToObject(res.headers) } });
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError('verify', friendlyError(err));
+ }
+ }
+
+ // Hold the verify step on a live countdown while an upstream throttle resets,
+ // then return so the caller re-sends the same signed payment. The reservation
+ // is deliberately left intact — this is the same payment, not a new one.
+ async waitForThrottle(seconds) {
+ const total = Math.max(1, Math.min(30, Math.round(seconds) || 6));
+ for (let left = total; left > 0; left--) {
+ this.renderProgress('verify', { text: `Service is busy — retrying in ${left}s…` });
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ this.renderProgress('verify', { text: 'Retrying…' });
+ }
+
+ async runSiwxEvm(chain) {
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const rawAddress = accounts?.[0];
+ if (!rawAddress) throw new Error('Wallet did not return an account');
+ const checksum = await loadEvmChecksum();
+ const address = checksum(rawAddress);
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const signature = await eth.request({
+ method: 'personal_sign',
+ params: [message, address],
+ });
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'eip191',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'eip191',
+ signature,
+ };
+ await this.executeSiwx(payload, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runSiwxSolana(chain) {
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const pubkey = conn?.publicKey || provider.publicKey;
+ const address = pubkey?.toString();
+ if (!address) throw new Error('Phantom did not return a public key');
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const encoded = new TextEncoder().encode(message);
+ const signed = await provider.signMessage(encoded, 'utf8');
+ const sigBytes = signed?.signature instanceof Uint8Array ? signed.signature : new Uint8Array(signed?.signature || signed);
+ if (!sigBytes || !sigBytes.length) throw new Error('Phantom did not return a signature');
+ const signature = base58encode(sigBytes);
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'ed25519',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'siws',
+ signature,
+ };
+ await this.executeSiwx(payload, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executeSiwx(payload, chainId) {
+ this.renderProgress('verify', { text: 'Verifying sign-in…' });
+ const headerValue = encodeSiwxHeaderValue(payload);
+ let res;
+ try {
+ res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ [SIWX_HEADER]: headerValue,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ } catch (err) {
+ this.renderError('verify', friendlyError(err));
+ return;
+ }
+
+ if (res.status === 200) {
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try { result = JSON.parse(text); } catch { result = text; }
+ } else {
+ result = text;
+ }
+ const siwx = { address: payload.address, network: chainId };
+ this.renderDone({ result, siwx });
+ this.resolve?.({
+ ok: true,
+ result,
+ siwx,
+ response: { status: res.status, headers: headersToObject(res.headers) },
+ });
+ return;
+ }
+
+ if (res.status === 401 || res.status === 402) {
+ // Most likely: signature verified but this wallet hasn't actually paid
+ // for the resource yet. Drop the SIWX offering and fall back to the
+ // normal payment flow with a one-line notice.
+ let parsed = null;
+ try { parsed = await res.clone().json(); } catch (_) {}
+ const code = parsed?.code || parsed?.error;
+ this.siwx = null;
+ this.payerAddress = null;
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = code === 'siwx_not_paid' || res.status === 402
+ ? "You haven't paid for this yet — pay now to unlock re-entry."
+ : 'Sign-in not accepted — please pay to continue.';
+ if (!this.challenge || !Array.isArray(this.challenge.accepts) || !this.challenge.accepts.length) {
+ this.start();
+ } else {
+ this.renderConnect();
+ }
+ return;
+ }
+
+ const text = await res.text().catch(() => '');
+ this.renderError('verify', `SIWX retry failed: HTTP ${res.status}${text ? ` · ${text.slice(0, 120)}` : ''}`);
+ }
+}
+
+// ───────────────────────────────────────────────────────── helpers ──────────
+
+function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function headersToObject(headers) {
+ const out = {};
+ headers.forEach((v, k) => (out[k] = v));
+ return out;
+}
+
+// How many times executePaid silently re-sends a signed payment after a 429
+// throttle before falling back to the manual "Try again". The payment isn't
+// settled until the merchant call succeeds, so re-sending can't double-charge.
+const MAX_THROTTLE_RETRIES = 2;
+
+// Seconds to wait before re-sending after a 429. Prefers the standard
+// Retry-After header, then the body's `retry_after` hint, then a sane default.
+function retryAfterSeconds(res, result, fallback = 6) {
+ const header = Number.parseInt(res.headers.get('retry-after') || '', 10);
+ if (Number.isFinite(header) && header > 0) return header;
+ const body = result && typeof result === 'object' ? Number(result.retry_after) : NaN;
+ if (Number.isFinite(body) && body > 0) return body;
+ return fallback;
+}
+
+function friendlyError(err) {
+ const msg = err?.shortMessage || err?.message || String(err);
+ if (/user rejected|user denied|reject/i.test(msg)) return 'cancelled in wallet';
+ // Upstream throttles often arrive as raw provider text that names the
+ // merchant's internal billing or credit state. Never relay that to the buyer:
+ // the payment isn't settled until the merchant call succeeds.
+ if (/throttl|rate.?limit|too many requests|less than \$|in credit|\b429\b/i.test(msg)) {
+ return 'The service is briefly busy and your payment was not taken — retry in a few seconds.';
+ }
+ // The Solana and EVM-sign-in paths dynamic-import a library from a CDN. A
+ // strict host Content-Security-Policy (or the CDN being unreachable) blocks
+ // that import. The Base/EIP-3009 payment path has no such dependency.
+ if (/dynamically imported module|esm\.sh|module script failed/i.test(msg)) {
+ return 'A component this wallet path needs (loaded from a CDN) was blocked — often by a strict host security policy. Pay with MetaMask on Base instead; it needs no third-party code.';
+ }
+ return msg.slice(0, 240);
+}
+
+function base64ToUint8Array(b64) {
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
+ const bin = atob(b64);
+ const arr = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
+ return arr;
+}
+function uint8ArrayToBase64(arr) {
+ if (typeof Buffer !== 'undefined') return Buffer.from(arr).toString('base64');
+ let bin = '';
+ for (let i = 0; i < arr.length; i++) bin += String.fromCharCode(arr[i]);
+ return btoa(bin);
+}
+function randomHex(bytes) {
+ const arr = new Uint8Array(bytes);
+ crypto.getRandomValues(arr);
+ return Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+let _solanaWeb3 = null;
+async function loadSolanaWeb3() {
+ if (_solanaWeb3) return _solanaWeb3;
+ // Dynamic import from a CDN keeps the drop-in script tiny — Solana web3.js is
+ // only fetched when a Solana payment is actually attempted.
+ _solanaWeb3 = await import(/* @vite-ignore */ config.solanaWeb3Url);
+ return _solanaWeb3;
+}
+
+async function postJson(url, body) {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { error: 'parse_error', error_description: text.slice(0, 200) };
+ }
+ if (!res.ok) {
+ const err = new Error(data.error_description || data.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.data = data;
+ throw err;
+ }
+ return data;
+}
+
+// Probe the merchant endpoint with a benign request to extract the 402
+// challenge. Accepts HTTP 402 (standard x402) or HTTP 401 with a
+// `payment-required` header (MCP 2025-06-18 spec).
+async function discoverChallenge(opts) {
+ const headers = { ...(opts.headers || {}) };
+ const init = {
+ method: opts.method || 'GET',
+ headers,
+ body: opts.body ? (typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body)) : undefined,
+ };
+ if (init.body && !headers['content-type']) headers['content-type'] = 'application/json';
+ const res = await fetch(opts.endpoint, init);
+
+ // MCP 2025-06-18 endpoints return 401 with the full x402 challenge in the
+ // `payment-required` header (base64-JSON). Accept that alongside standard 402.
+ const prHeader = res.headers.get('payment-required');
+ const is401WithChallenge = res.status === 401 && !!prHeader;
+
+ if (res.status !== 402 && !is401WithChallenge) {
+ // Endpoint isn't paid (200) or isn't an x402 endpoint at all. Surface a
+ // clear error — pointing the modal at a free endpoint should not silently
+ // succeed.
+ const txt = await res.text();
+ throw new Error(`Endpoint did not return 402 (got ${res.status}). Body: ${txt.slice(0, 120)}`);
+ }
+
+ let body = is401WithChallenge ? b64decode(prHeader) : await res.json().catch(() => null);
+ if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
+ // Some servers only emit `{error}` in the body and put the full v2
+ // PaymentRequired envelope in the base64-JSON PAYMENT-REQUIRED header.
+ const decoded = b64decode(prHeader);
+ if (decoded && Array.isArray(decoded.accepts) && decoded.accepts.length) {
+ body = decoded;
+ }
+ }
+ if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
+ throw new Error('Endpoint returned 402 but no `accepts` array could be found in body or header');
+ }
+ // Coerce spec-canonical `maxAmountRequired` → `amount` so downstream price /
+ // caps / signing read one field.
+ body.accepts = body.accepts.map(normalizeAccept);
+ return body;
+}
+
+// ───────────────────────────────────────────────────────── public api ───────
+
+/**
+ * Open the payment modal for an x402 endpoint and resolve when the call
+ * succeeds (after settlement) or reject if the user cancels.
+ * @param {import('../types/index.js').PayOptions} opts
+ * @returns {Promise<import('../types/index.js').PayResult>}
+ */
+export async function pay(opts) {
+ if (!opts?.endpoint) throw new Error('X402.pay: endpoint is required');
+ const modal = new CheckoutModal(opts);
+ const result = modal.mount();
+ // Kick off discovery on the next tick so the modal animates in first.
+ queueMicrotask(() => modal.start());
+ return result;
+}
+
+function readOptsFrom(el) {
+ const ds = el.dataset;
+ let body = ds.x402Body;
+ if (body) {
+ try { body = JSON.parse(body); } catch { /* keep as string */ }
+ }
+ let headers = ds.x402Headers;
+ if (headers) {
+ try { headers = JSON.parse(headers); } catch { headers = undefined; }
+ }
+ let caps = ds.x402Caps;
+ if (caps) {
+ try { caps = JSON.parse(caps); } catch { caps = undefined; }
+ }
+ return {
+ endpoint: ds.x402Endpoint,
+ method: ds.x402Method || (body ? 'POST' : 'GET'),
+ body,
+ headers,
+ caps,
+ apiOrigin: ds.x402ApiOrigin,
+ merchant: ds.x402Merchant,
+ action: ds.x402Action || el.textContent?.trim().slice(0, 60),
+ };
+}
+
+function bindElement(el) {
+ if (el.dataset.x402Bound === '1') return;
+ el.dataset.x402Bound = '1';
+ el.addEventListener('click', async (e) => {
+ e.preventDefault();
+ const opts = readOptsFrom(el);
+ try {
+ const out = await pay(opts);
+ if (out?.siwx) {
+ el.dispatchEvent(new CustomEvent('x402:siwx-signed', { detail: out.siwx, bubbles: true }));
+ }
+ el.dispatchEvent(new CustomEvent('x402:result', { detail: out, bubbles: true }));
+ } catch (err) {
+ if (err?.code === 'cancelled') return;
+ el.dispatchEvent(new CustomEvent('x402:error', { detail: { error: err?.message || String(err) }, bubbles: true }));
+ }
+ });
+}
+
+/** Scan the document and bind every `[data-x402-endpoint]` element. Idempotent. */
+export function init() {
+ if (typeof document === 'undefined') return;
+ document.querySelectorAll('[data-x402-endpoint]').forEach(bindElement);
+}
+
+export { VERSION as version, bindElement, readOptsFrom };
diff --git a/x402-payment-modal/.gitignore b/x402-payment-modal/.gitignore
new file mode 100644
index 000000000..672434e70
--- /dev/null
+++ b/x402-payment-modal/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+*.log
+.DS_Store
+*.tmp.*
diff --git a/x402-payment-modal/LICENSE b/x402-payment-modal/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/x402-payment-modal/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.json
new file mode 100644
index 000000000..bdf4712d7
--- /dev/null
+++ b/x402-payment-modal/package.json
@@ -0,0 +1,114 @@
+{
+ "name": "@three-ws/x402-payment-modal",
+ "version": "1.0.0",
+ "description": "Drop-in x402 payment modal for any paid HTTP endpoint. One ES module, zero runtime dependencies — handles wallet connect (Phantom/Solana + EVM via EIP-3009), the 402 → sign → settle flow, SIWX re-entry, client-side spending caps, and a receipt. Vanilla JS, no bundler required.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./types/index.d.ts",
+ "browser": "./dist/x402.min.js",
+ "unpkg": "./dist/x402.min.js",
+ "jsdelivr": "./dist/x402.min.js",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./min": {
+ "types": "./types/index.d.ts",
+ "default": "./dist/x402.min.js"
+ },
+ "./server": {
+ "types": "./types/server.d.ts",
+ "import": "./server/checkout.js",
+ "default": "./server/checkout.js"
+ },
+ "./server/express": {
+ "import": "./server/express.js",
+ "default": "./server/express.js"
+ },
+ "./server/vercel": {
+ "import": "./server/vercel.js",
+ "default": "./server/vercel.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "src",
+ "dist",
+ "types",
+ "server",
+ "examples",
+ "docs",
+ "README.md",
+ "TUTORIAL.md",
+ "CHANGELOG.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "node build.mjs",
+ "sync:public": "node scripts/sync-public.mjs",
+ "test": "node --test test/",
+ "prepublishOnly": "npm run build"
+ },
+ "keywords": [
+ "x402",
+ "payments",
+ "micropayments",
+ "paywall",
+ "pay-per-call",
+ "usdc",
+ "stablecoin",
+ "solana",
+ "phantom",
+ "evm",
+ "base",
+ "metamask",
+ "eip-3009",
+ "siwx",
+ "wallet",
+ "checkout",
+ "modal",
+ "agentic",
+ "web3",
+ "402",
+ "three-ws"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "x402-payment-modal"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "peerDependencies": {
+ "@solana/web3.js": "^1.95.0",
+ "@solana/spl-token": "^0.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@solana/web3.js": {
+ "optional": true
+ },
+ "@solana/spl-token": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "esbuild": "^0.21.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "sideEffects": [
+ "./src/index.js",
+ "./dist/x402.min.js"
+ ]
+}
diff --git a/x402-modal-sdk/src/index.js b/x402-payment-modal/src/index.js
similarity index 97%
rename from x402-modal-sdk/src/index.js
rename to x402-payment-modal/src/index.js
index 78fc66419..33ab08124 100644
--- a/x402-modal-sdk/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -1,9 +1,9 @@
-// @three-ws/x402-modal — drop-in payment modal for any x402 paid endpoint.
+// @three-ws/x402-payment-modal — drop-in payment modal for any x402 endpoint.
//
// A single, dependency-free ES module. Drop it on any page and any element with
// `data-x402-endpoint` opens a payment modal on click:
//
-// <script type="module" src="https://unpkg.com/@three-ws/x402-modal"></script>
+// <script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>
//
// <button
// data-x402-endpoint="https://example.com/api/paid/summarize"
@@ -742,8 +742,8 @@ class CheckoutModal {
</div>
<div class="x402-body" data-body></div>
<div class="x402-foot">
- <span class="x402-secure">x402 · onchain settled</span>
- <a href="https://three.ws" target="_blank" rel="noopener">Powered by three.ws</a>
+ <span class="x402-secure">${escapeHtml(CONFIG.footerNote)}</span>
+ ${CONFIG.brand?.name ? `<a href="${escapeHtml(CONFIG.brand.url || '#')}" target="_blank" rel="noopener">Powered by ${escapeHtml(CONFIG.brand.name)}</a>` : ''}
</div>
</div>
`;
@@ -1597,8 +1597,45 @@ export function init() {
document.querySelectorAll('[data-x402-endpoint]').forEach(bindElement);
}
+// Read host config from `data-*` attributes on the <script> tag that loaded
+// this module, so script-tag users can configure without an inline module:
+//
+// <script type="module" src=".../x402.js"
+// data-x402-checkout-origin="https://pay.acme.com"
+// data-x402-brand-name="Acme" data-x402-brand-url="https://acme.com"
+// data-x402-footer-note="Acme Pay"
+// data-x402-builder-wallet="acme" data-x402-builder-service="acme_checkout"></script>
+function readScriptConfig() {
+ try {
+ const script =
+ document.currentScript ||
+ document.querySelector('script[src*="x402"][type="module"]') ||
+ document.querySelector('script[data-x402-checkout-origin]');
+ const ds = script?.dataset;
+ if (!ds) return;
+ const next = {};
+ if (ds.x402CheckoutOrigin) next.checkoutOrigin = ds.x402CheckoutOrigin;
+ if (ds.x402CheckoutPath) next.checkoutPath = ds.x402CheckoutPath;
+ if (ds.x402FooterNote) next.footerNote = ds.x402FooterNote;
+ if (ds.x402BrandName || ds.x402BrandUrl) {
+ next.brand = {};
+ if (ds.x402BrandName) next.brand.name = ds.x402BrandName;
+ if (ds.x402BrandUrl) next.brand.url = ds.x402BrandUrl;
+ }
+ if (ds.x402BuilderWallet || ds.x402BuilderService) {
+ next.builderCode = {};
+ if (ds.x402BuilderWallet) next.builderCode.wallet = ds.x402BuilderWallet;
+ if (ds.x402BuilderService) next.builderCode.service = ds.x402BuilderService;
+ }
+ if (Object.keys(next).length) configure(next);
+ } catch (_) {
+ // A missing/odd script tag is non-fatal — defaults still work.
+ }
+}
+
// Auto-init on DOMContentLoaded, plus on demand.
if (typeof document !== 'undefined') {
+ readScriptConfig();
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
} else {
@@ -1611,5 +1648,5 @@ if (typeof document !== 'undefined') {
// Expose to merchants' inline scripts.
if (typeof window !== 'undefined') {
- window.X402 = Object.freeze({ pay, init, version: VERSION });
+ window.X402 = Object.freeze({ pay, init, configure, version: VERSION });
}