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(docs): live-verified doc steps

nirholas649fa1f5008b
diff --git a/docs/live-docs.md b/docs/live-docs.md
index 2f5e5d08f..3368b92ee 100644
--- a/docs/live-docs.md
+++ b/docs/live-docs.md
@@ -140,11 +140,12 @@ the best reason yet to follow the existing rule that every doc sample uses a liv
three.ws avatar URL and a real endpoint. A sample that 404s now 404s in front of
the reader.
-**Previews follow the reader's origin.** A sample correctly hardcodes
+**Absolute URLs are left exactly as published; relative ones resolve against the
+page you are reading.** A sample correctly hardcodes
`https://three.ws/agent-3d/…` because that is what someone pastes into their own
-site. Inside the preview frame that URL is rewritten to whatever origin the
-reader is on, so a preview on a dev server exercises the local build instead of
-silently loading production.
+site, and the preview loads precisely that. A relative URL such as
+`/avatars/michelle.glb` would otherwise resolve against `about:srcdoc` and load
+nothing, so the frame carries a `<base>` pointing at the reader's own origin.
---
diff --git a/docs/live-steps.md b/docs/live-steps.md
index 349ec1eb9..436acbc94 100644
--- a/docs/live-steps.md
+++ b/docs/live-steps.md
@@ -95,7 +95,25 @@ Add an entry to `STEPS` in [public/live-steps.js](https://github.com/nirholas/th
- `inputs` become editable text fields and are sent as query parameters. Give each one a `value` (the default), a `placeholder`, and a `hint`.
- `exports` maps a variable name to a key in the response body, making it available to later steps on the page.
-### 3. For something that is not a request, add a derivation
+### 3. If the response points at something you can see, render it
+
+Printing JSON proves the API answered. It does not show what the answer *is*. When a response carries the URL of a portrait, a thumbnail, or a GLB, add a `renders` block and the card mounts that asset live underneath the body, so "call the endpoint" and "look at what it returned" collapse into one card:
+
+```js
+renders: {
+ pick: 'agents[0].avatar_thumbnail',
+ kind: 'image',
+ alt: 'The portrait of the first agent in the live public directory',
+}
+```
+
+- `pick` is a dotted path with optional numeric indexes, read from the raw response body. The registry declares it; markdown never supplies one.
+- `kind` is `image`, `model`, or `auto` to infer it from the file extension. A `model` mounts in `model-viewer`, orbitable, and drops its auto-rotate under `prefers-reduced-motion`. A host page that has not registered `model-viewer` gets a real link to the file instead of an empty box.
+- `alt` is required. A step that renders an asset without alt text fails at load.
+
+The URL comes off the network, so it is treated as untrusted: it must be `https:` or a same-origin absolute path before it can become a subresource, and it is applied with `setAttribute` on a fresh element. A `javascript:` or `data:` value in that field renders nothing. When the field is simply absent, the card stays quiet, because a directory whose first entry has no portrait is a normal response rather than an error.
+
+### 4. For something that is not a request, add a derivation
A `derive` step runs a named pure function in the same file and performs no network call. Use it when the thing worth showing is a transform rather than a response, such as assembling the exact message a wallet signs:
@@ -114,7 +132,7 @@ A `derive` step runs a named pure function in the same file and performs no netw
The function itself lives in the `DERIVATIONS` map and receives one object holding every chained variable plus the reader's input values. A derivation named in a step but missing from that map fails at load.
-### 4. Verify
+### 5. Verify
```bash
npx vitest run tests/live-steps.test.js
@@ -134,16 +152,20 @@ The card follows the reader's theme through the canonical tokens in `tokens.css`
## Currently registered steps
-| id | Call | Publishes |
-|---|---|---|
-| `version` | `GET /api/version` | `commit` |
-| `platform-stats` | `GET /api/platform/stats` | |
-| `agents-public` | `GET /api/agents/public` | |
-| `skills-catalog` | `GET /api/skills` | |
-| `three-leaderboard` | `GET /api/leaderboard` | |
-| `auth-me` | `GET /api/auth/me` | |
-| `siws-nonce` | `GET /api/auth/siws/nonce` | `nonce`, `domain`, `uri`, `expiresAt` |
-| `siws-message` | local derivation | |
+| id | Call | Publishes | Renders |
+|---|---|---|---|
+| `version` | `GET /api/version` | `commit` | |
+| `platform-stats` | `GET /api/platform/stats` | | |
+| `agents-public` | `GET /api/agents/public` | | first agent's portrait |
+| `pump-launches` | `GET /api/pump/launches` | | launching agent's portrait |
+| `pump-trending` | `GET /api/pump/trending` | | |
+| `skills-catalog` | `GET /api/skills` | | |
+| `three-leaderboard` | `GET /api/leaderboard` | | |
+| `auth-me` | `GET /api/auth/me` | | |
+| `siws-nonce` | `GET /api/auth/siws/nonce` | `nonce`, `domain`, `uri`, `expiresAt` | |
+| `siws-message` | local derivation | | |
+
+Run `npx vitest run tests/live-steps.test.js` after editing the registry; the suite asserts this table's invariants against the shipped file.
---
diff --git a/public/docs-live-core.js b/public/docs-live-core.js
index 4705bbde7..c96c318f4 100644
--- a/public/docs-live-core.js
+++ b/public/docs-live-core.js
@@ -380,23 +380,25 @@ export function applyPlaceholders(request = {}, values = {}) {
// ── Preview documents ────────────────────────────────────────────────────────
/**
- * Point a snippet's three.ws asset URLs at the origin the reader is actually on.
+ * The `<base>` a sandboxed frame needs so relative URLs in a snippet resolve.
*
- * A doc sample correctly hardcodes `https://three.ws/agent-3d/…` because that is
- * what a reader pastes into their own site. Inside the preview iframe on a dev
- * server or a preview deploy, that URL loads the PRODUCTION component, so the
- * preview stops reflecting the build under test. On three.ws itself this is a
- * no-op.
+ * A frame built from `srcdoc` with no `allow-same-origin` has an opaque origin
+ * and a document URL of `about:srcdoc`, so `body="/avatars/michelle.glb"`
+ * resolves to nothing at all. A base pointing at the reader's own origin makes
+ * relative URLs mean what they mean on the page they were read on.
*
- * @param {string} html
- * @param {string} origin
- * @returns {string}
+ * Absolute `https://three.ws/…` URLs are deliberately left alone. Rewriting
+ * them to the current origin (an earlier version of this did) breaks the frame
+ * on any origin that does not itself serve `/agent-3d/…`, and it is also the
+ * wrong preview: a sample hardcodes the production URL precisely because that is
+ * what the reader will paste into their own site.
+ *
+ * @param {string} [origin]
+ * @returns {string} a `<base>` tag, or '' when no usable origin was supplied
*/
-export function rewriteAssetOrigin(html, origin) {
+export function baseTag(origin) {
const target = normalizeOrigin(origin);
- if (!target) return String(html || '');
- if (/^https:\/\/(www\.)?three\.ws$/.test(target)) return String(html || '');
- return String(html || '').replace(/https:\/\/(?:www\.)?three\.ws(?=\/)/g, target);
+ return target ? `<base href="${target}/">` : '';
}
/**
@@ -413,18 +415,19 @@ export function rewriteAssetOrigin(html, origin) {
*/
export function buildPreviewDoc(snippet, opts = {}) {
const theme = opts.theme === 'light' ? 'light' : 'dark';
- const body = rewriteAssetOrigin(snippet, opts.origin);
+ const body = String(snippet == null ? '' : snippet);
const bg = theme === 'light' ? '#f6f7f9' : '#0e0f13';
const fg = theme === 'light' ? '#16181d' : '#e8eaf0';
- // A snippet that already declares a full document is used verbatim (minus
- // the origin rewrite): wrapping it again would nest <html> inside <body>.
+ // A snippet that already declares a full document is used verbatim: wrapping
+ // it again would nest <html> inside <body>.
if (/^\s*<(!doctype|html)\b/i.test(body)) return body;
return `<!doctype html>
<html lang="en" data-theme="${theme}">
<head>
<meta charset="utf-8">
+${baseTag(opts.origin)}
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root { color-scheme: ${theme}; }
@@ -459,12 +462,12 @@ ${body}
* @returns {string}
*/
export function buildScriptDoc(snippet, opts = {}) {
- const code = rewriteAssetOrigin(snippet, opts.origin);
+ const code = String(snippet == null ? '' : snippet);
// The snippet is injected as a module body. `</script>` inside a string
// literal would otherwise close the tag early and break the document.
const safe = code.replace(/<\/script/gi, '<\\/script');
return `<!doctype html>
-<html lang="en"><head><meta charset="utf-8"></head><body>
+<html lang="en"><head><meta charset="utf-8">${baseTag(opts.origin)}</head><body>
<script type="module">
const send = (level, args) => {
const parts = args.map((a) => {
diff --git a/public/docs-live-verify.js b/public/docs-live-verify.js
new file mode 100644
index 000000000..44de49b98
--- /dev/null
+++ b/public/docs-live-verify.js
@@ -0,0 +1,227 @@
+// Live Docs: the verification layer.
+//
+// Live Docs (docs-live.js) lets a reader press Run on a documentation sample.
+// This module answers the narrower question CI needs: *which* samples can be
+// executed with no human in the loop, and what is each one supposed to answer?
+//
+// It is deliberately built on docs-live-core.js rather than beside it. The
+// runner and the gate share one tokenizer, one curl parser, one placeholder
+// detector and one safety assessment, so a sample the gate proves alive is
+// exactly the sample the reader can run. Duplicating those rules is how the two
+// halves drift apart and the gate starts certifying something nobody sees.
+//
+// Consumed by:
+// • scripts/check-runnable-docs.mjs: executes every verifiable sample in
+// docs/ against the live API and fails the build when one rots
+// • docs-live.js: reads the author directives below so an opt-out written for
+// the gate also suppresses the Run button
+//
+// ── Author directives ────────────────────────────────────────────────────────
+// An HTML comment on the line above a fence controls both halves:
+//
+// <!-- runnable: no the vault id is illustrative --> never run, never probe
+// <!-- runnable: 402 the challenge is the lesson --> probe, expect exactly 402
+// <!-- live: off --> the runner's original
+// opt-out, honoured here too
+//
+// DOM-free and dependency-free: it loads in a plain <script type="module"> and
+// in Node with no build step.
+
+import { classifyBlock, findPlaceholders } from './docs-live-core.js';
+
+/** Hosts a probe is willing to call. Localhost is a runner convenience, not a target CI can verify. */
+export const VERIFIABLE_HOSTS = Object.freeze(['three.ws', 'www.three.ws']);
+
+/**
+ * Paths that are never verifiable even as a bare GET. Some are account-scoped,
+ * so the only thing CI could ever prove is that a logged-out probe gets a 401;
+ * some are plumbing whose response teaches a reader nothing.
+ */
+export const UNVERIFIABLE_PREFIXES = Object.freeze([
+ '/api/admin',
+ '/api/auth',
+ '/api/cron',
+ '/api/credits',
+ '/api/csrf-token',
+ '/api/developer',
+ '/api/keys',
+ '/api/logout',
+ '/api/session',
+ '/api/user',
+ '/api/webhook',
+]);
+
+/**
+ * A value the doc shortened or left blank. `findPlaceholders` covers the slot
+ * syntaxes the runner renders a field for (`$VAR`, `<id>`, `YOUR_KEY`); these
+ * two conventions carry no fillable name, so only the gate needs to reject them.
+ *
+ * an ellipsis, literal or percent-encoded, means the author elided the value
+ * BARE_CAPS_WITH_UNDERSCORES is the docs' shorthand for "your own id here"
+ */
+const ELIDED_VALUE = /\.\.\.|…|%E2%80%A6/i;
+const BARE_CAPS_SLOT = /(^|[^A-Za-z0-9])[A-Z][A-Z0-9]*_[A-Z0-9_]+([^A-Za-z0-9]|$)/;
+
+/**
+ * Request headers that carry a secret, a session, or a device identity. A probe
+ * that sends none of them can only ever see the endpoint's logged-out answer, so
+ * a sample that needs one is not something CI can hold to a contract.
+ */
+const IDENTITY_HEADERS =
+ /^(authorization|cookie|x-api-key|x-payment|x-forge-provider-key|x-admin-|x-cron-|x-signature|x-irl-|x-device|x-session)/i;
+
+/**
+ * Parse an author directive from an HTML comment.
+ *
+ * @param {string|null|undefined} comment the comment's inner text
+ * @returns {{skip: true, note: string} | {expectStatus: number, note: string} | null}
+ */
+export function parseDirective(comment) {
+ if (!comment) return null;
+ const text = String(comment).trim();
+ if (/^live\s*:\s*off\b/i.test(text)) return { skip: true, note: 'the author opted this block out' };
+ const match = text.match(/^runnable:\s*(no|\d{3})\b\s*(.*)$/is);
+ if (!match) return null;
+ const note = match[2].trim();
+ if (/^no$/i.test(match[1])) return { skip: true, note };
+ return { expectStatus: Number(match[1]), note };
+}
+
+/**
+ * Decide whether a documentation code block can be probed without a human.
+ *
+ * @param {string} code raw text of the code block
+ * @param {string} [lang] the fence language
+ * @param {string} [comment] an author directive sitting above the fence
+ * @returns {{verifiable: true, url: string, path: string, accept: string|null,
+ * expectStatus: number|null, note: string}
+ * |{verifiable: false, reason: string}}
+ */
+export function verifiableSample(code, lang, comment) {
+ const directive = parseDirective(comment);
+ if (directive && directive.skip) {
+ return { verifiable: false, reason: directive.note || 'the author opted this block out' };
+ }
+
+ const verdict = classifyBlock({ lang, code });
+ if (!verdict || verdict.kind !== 'request') {
+ return { verifiable: false, reason: 'not a runnable request' };
+ }
+ const request = verdict.request;
+
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
+ return { verifiable: false, reason: `${request.method} is not read-only` };
+ }
+ if (request.body != null) return { verifiable: false, reason: 'sends a body' };
+
+ for (const name of Object.keys(request.headers || {})) {
+ if (IDENTITY_HEADERS.test(name.trim())) {
+ return { verifiable: false, reason: 'needs a credential header' };
+ }
+ }
+ // A slot the reader is expected to fill is exactly what CI cannot fill.
+ if (findPlaceholders(request).length) {
+ return { verifiable: false, reason: 'contains a placeholder the reader fills in' };
+ }
+ if (ELIDED_VALUE.test(request.url)) {
+ return { verifiable: false, reason: 'the URL contains an elided value' };
+ }
+ if (BARE_CAPS_SLOT.test(request.url)) {
+ return { verifiable: false, reason: 'the URL contains a placeholder id' };
+ }
+
+ let parsed;
+ try {
+ parsed = new URL(request.url);
+ } catch {
+ return { verifiable: false, reason: 'not an absolute URL' };
+ }
+ if (parsed.protocol !== 'https:') return { verifiable: false, reason: 'not https' };
+ if (!VERIFIABLE_HOSTS.includes(parsed.hostname)) {
+ return { verifiable: false, reason: 'not a three.ws URL' };
+ }
+ if (UNVERIFIABLE_PREFIXES.some((p) => parsed.pathname === p || parsed.pathname.startsWith(`${p}/`))) {
+ return { verifiable: false, reason: 'account-scoped or privileged path' };
+ }
+ // Verifiable paths are API calls and small JSON manifests. Everything else on
+ // the site is a page or a multi-megabyte binary, and probing those proves
+ // nothing about whether the documented call still works.
+ if (!parsed.pathname.startsWith('/api/') && !parsed.pathname.endsWith('.json')) {
+ return { verifiable: false, reason: 'not an API or JSON path' };
+ }
+
+ const accept = Object.entries(request.headers || {}).find(([k]) => /^accept$/i.test(k));
+ return {
+ verifiable: true,
+ url: parsed.toString(),
+ path: `${parsed.pathname}${parsed.search}`,
+ accept: accept ? accept[1] : null,
+ expectStatus: directive ? directive.expectStatus : null,
+ note: directive ? directive.note : '',
+ };
+}
+
+/**
+ * Pull every fenced code block out of a markdown document, along with any author
+ * directive comment on the line above it.
+ * @returns {Array<{lang: string, code: string, line: number, comment: string|null}>}
+ */
+export function codeBlocks(markdown) {
+ const out = [];
+ const lines = String(markdown || '').split('\n');
+ let fence = null;
+ let lang = '';
+ let start = 0;
+ let comment = null;
+ let buffer = [];
+ let pending = null;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (!fence) {
+ const html = line.match(/^\s*<!--([\s\S]*?)-->\s*$/);
+ if (html) {
+ pending = html[1];
+ continue;
+ }
+ }
+ const open = line.match(/^\s*(`{3,}|~{3,})\s*([A-Za-z0-9_-]*)\s*$/);
+ if (!fence && open) {
+ fence = open[1][0];
+ lang = open[2] || '';
+ start = i + 2;
+ comment = pending;
+ pending = null;
+ buffer = [];
+ continue;
+ }
+ if (fence) {
+ const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);
+ if (close && close[1][0] === fence) {
+ out.push({ lang, code: buffer.join('\n'), line: start, comment });
+ fence = null;
+ comment = null;
+ buffer = [];
+ continue;
+ }
+ buffer.push(line);
+ continue;
+ }
+ // A directive only binds to the fence it immediately precedes.
+ if (line.trim()) pending = null;
+ }
+ return out;
+}
+
+/**
+ * Every verifiable sample in a markdown document, in document order.
+ * @returns {Array<{url: string, path: string, accept: string|null, expectStatus: number|null,
+ * note: string, line: number, code: string}>}
+ */
+export function verifiableSamples(markdown) {
+ const out = [];
+ for (const block of codeBlocks(markdown)) {
+ const verdict = verifiableSample(block.code, block.lang, block.comment);
+ if (verdict.verifiable) out.push({ ...verdict, line: block.line, code: block.code });
+ }
+ return out;
+}
diff --git a/public/live-steps.css b/public/live-steps.css
index 17ae341fa..d2d9fc2e1 100644
--- a/public/live-steps.css
+++ b/public/live-steps.css
@@ -420,6 +420,100 @@
}
}
+/* ── Rendered asset ──────────────────────────────────────────────────────────
+ * When a response carries the URL of a portrait or a GLB, the card mounts it
+ * under the body so "what did the endpoint answer" and "what does that answer
+ * look like" are one glance rather than two tabs. The frame keeps a stable
+ * aspect box so the card does not jump as the asset streams in. */
+
+.ls-asset {
+ margin-top: 0.85rem;
+}
+.ls-asset-head {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ margin-bottom: 0.4rem;
+}
+.ls-asset-label {
+ color: var(--ink-dim, #888);
+ font-size: 0.7rem;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+.ls-asset-src {
+ flex: 1 1 10rem;
+ min-width: 0;
+ color: var(--ink-dim, #888);
+ font-family: var(--font-mono, monospace);
+ font-size: 0.68rem;
+ opacity: 0.7;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.ls-asset-frame {
+ position: relative;
+ display: grid;
+ place-items: center;
+ aspect-ratio: 16 / 9;
+ max-height: 20rem;
+ overflow: hidden;
+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-md, 10px);
+ background:
+ radial-gradient(
+ circle at 50% 38%,
+ color-mix(in srgb, var(--ls-accent) 9%, transparent),
+ transparent 62%
+ ),
+ var(--bg-0, #0a0a0a);
+}
+.ls-asset-img {
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+}
+.ls-asset-model {
+ width: 100%;
+ height: 100%;
+ background: none;
+ --poster-color: transparent;
+}
+.ls-asset-model:focus-visible {
+ outline: 2px solid var(--ls-accent);
+ outline-offset: -2px;
+}
+.ls-asset-hint {
+ position: absolute;
+ right: 0.55rem;
+ bottom: 0.5rem;
+ padding: 0.16rem 0.42rem;
+ border-radius: var(--radius-pill, 999px);
+ background: color-mix(in srgb, var(--bg-0, #0a0a0a) 72%, transparent);
+ color: var(--ink-dim, #888);
+ font-size: 0.64rem;
+ pointer-events: none;
+}
+.ls-asset-fallback {
+ color: var(--ink, #e8e8e8);
+ font-size: 0.8rem;
+ text-decoration: underline;
+ text-underline-offset: 3px;
+}
+.ls-asset-fallback:focus-visible {
+ outline: 2px solid var(--ls-accent);
+ outline-offset: 3px;
+}
+.ls-asset-fail {
+ margin: 0;
+ padding: 0 1rem;
+ color: var(--ink-dim, #888);
+ font-size: 0.78rem;
+ text-align: center;
+}
+
.ls-note {
display: flex;
align-items: flex-start;
@@ -498,6 +592,9 @@
.ls-pre {
font-size: 0.71rem;
}
+ .ls-asset-frame {
+ aspect-ratio: 4 / 3;
+ }
}
/* ── Motion opt-out ──────────────────────────────────────────────────────── */
diff --git a/public/live-steps.js b/public/live-steps.js
index e0b60d975..b9937d8c5 100644
--- a/public/live-steps.js
+++ b/public/live-steps.js
@@ -137,6 +137,58 @@
},
],
exports: {},
+ renders: {
+ pick: 'agents[0].avatar_thumbnail',
+ kind: 'image',
+ alt: 'The portrait of the first agent in the live public directory',
+ },
+ },
+ {
+ id: 'pump-launches',
+ kind: 'request',
+ method: 'GET',
+ path: '/api/pump/launches',
+ title: 'List coins launched through three.ws',
+ summary:
+ 'Every mint launched from the platform, newest first, each joined to the agent that launched it. Public: this is what the launches feed renders from.',
+ docs: '/launches',
+ credentials: 'omit',
+ inputs: [
+ {
+ name: 'limit',
+ label: 'limit',
+ value: '3',
+ placeholder: '3',
+ hint: 'How many launches to return.',
+ },
+ ],
+ exports: {},
+ renders: {
+ pick: 'data.launches[0].agent.avatar_thumbnail_url',
+ kind: 'image',
+ alt: 'The portrait of the agent behind the most recent launch',
+ },
+ },
+ {
+ id: 'pump-trending',
+ kind: 'request',
+ method: 'GET',
+ path: '/api/pump/trending',
+ title: 'Read the trending coin feed',
+ summary:
+ 'Trending mints from the live Pump.fun feed, the same source the market surfaces score against. Values move between one run and the next, which is the point.',
+ docs: '/pumpfun',
+ credentials: 'omit',
+ inputs: [
+ {
+ name: 'limit',
+ label: 'limit',
+ value: '3',
+ placeholder: '3',
+ hint: 'How many coins to return.',
+ },
+ ],
+ exports: {},
},
{
id: 'skills-catalog',
@@ -278,6 +330,20 @@
}
produced.add(name);
}
+ if (step.renders) {
+ if (!parsePickPath(step.renders.pick)) {
+ throw new Error(
+ `live-steps: ${step.id} renders an unreadable path "${step.renders.pick}"`,
+ );
+ }
+ const kind = step.renders.kind || 'auto';
+ if (kind !== 'auto' && kind !== 'model' && kind !== 'image') {
+ throw new Error(`live-steps: ${step.id} renders unknown kind "${kind}"`);
+ }
+ if (!step.renders.alt) {
+ throw new Error(`live-steps: ${step.id} renders without alt text`);
+ }
+ }
} else {
if (typeof DERIVATIONS[step.derive] !== 'function') {
throw new Error(`live-steps: ${step.id} names unknown derivation "${step.derive}"`);
@@ -339,14 +405,21 @@
* ══════════════════════════════════════════════════════════════════════ */
function buildUrl(step, values) {
- const params = new URLSearchParams();
+ /*
+ * encodeURIComponent rather than URLSearchParams, for two reasons. It
+ * percent-encodes the delimiters that matter here (/, ?, #, &) where
+ * URLSearchParams leaves some of them raw and turns spaces into '+', and
+ * it is a language built-in, so this stays pure and testable outside a
+ * browser. Only declared inputs are read, so an undeclared key a caller
+ * passes in can never reach the URL.
+ */
+ const pairs = [];
for (const input of step.inputs || []) {
const raw = values[input.name];
if (raw === undefined || raw === null || String(raw).trim() === '') continue;
- params.set(input.name, String(raw).trim());
+ pairs.push(`${encodeURIComponent(input.name)}=${encodeURIComponent(String(raw).trim())}`);
}
- const qs = params.toString();
- return qs ? `${step.path}?${qs}` : step.path;
+ return pairs.length ? `${step.path}?${pairs.join('&')}` : step.path;
}
/* ══════════════════════════════════════════════════════════════════════
@@ -469,6 +542,145 @@
: 'The API answered with an unexpected status.';
}
+ /* ══════════════════════════════════════════════════════════════════════
+ * The render lane - the part only a 3D platform can do.
+ *
+ * Printing JSON proves the API answered. It does not show what the answer
+ * IS. When a response carries the URL of an avatar, a thumbnail or a GLB,
+ * a step can declare `renders` and the card mounts that asset live under
+ * the body: "call the endpoint" and "look at the thing it returned" become
+ * one card instead of a call, a copy, and a trip to another tab.
+ *
+ * The URL comes off the network, so it is treated as untrusted:
+ * - it is read from the RAW body by a path the registry declares, never
+ * by anything markdown supplies,
+ * - it must be https: or a same-origin absolute path, so a redirected or
+ * poisoned field can never produce a javascript: or data: subresource,
+ * - it is set through setAttribute on a fresh element, never innerHTML.
+ * ══════════════════════════════════════════════════════════════════════ */
+
+ const MODEL_EXT = /\.(glb|gltf)(\?|#|$)/i;
+ const IMAGE_EXT = /\.(png|jpe?g|webp|avif|gif)(\?|#|$)/i;
+
+ /* `agents[0].avatar_thumbnail` -> ['agents', 0, 'avatar_thumbnail']. */
+ function parsePickPath(expr) {
+ if (typeof expr !== 'string' || !expr) return null;
+ /* A trailing separator would otherwise consume cleanly and yield a path
+ * one segment shorter than the author wrote. */
+ if (expr.endsWith('.')) return null;
+ const out = [];
+ const re = /([A-Za-z_$][\w$]*)|\[(\d+)\]/g;
+ let consumed = 0;
+ /* A separator promises another segment; "a." must not parse as ['a']. */
+ let expectSegment = true;
+ let match;
+ while ((match = re.exec(expr)) !== null) {
+ if (match.index !== consumed) return null;
+ consumed = re.lastIndex;
+ out.push(match[1] !== undefined ? match[1] : Number(match[2]));
+ expectSegment = false;
+ if (expr.charAt(consumed) === '.') {
+ consumed += 1;
+ expectSegment = true;
+ }
+ re.lastIndex = consumed;
+ }
+ if (expectSegment || consumed !== expr.length || !out.length) return null;
+ return out;
+ }
+
+ function pickValue(body, path) {
+ let cursor = body;
+ for (const segment of path) {
+ if (cursor === null || cursor === undefined) return undefined;
+ if (typeof segment === 'number') {
+ if (!Array.isArray(cursor)) return undefined;
+ } else if (typeof cursor !== 'object' || Array.isArray(cursor)) {
+ return undefined;
+ }
+ cursor = cursor[segment];
+ }
+ return cursor;
+ }
+
+ function mediaKind(url) {
+ if (typeof url !== 'string') return null;
+ if (MODEL_EXT.test(url)) return 'model';
+ if (IMAGE_EXT.test(url)) return 'image';
+ return null;
+ }
+
+ /*
+ * Only https and same-origin absolute paths may become a subresource. A
+ * scheme-relative or bare-relative value is rejected rather than resolved:
+ * the origin it would pick up depends on the page, and a URL whose host
+ * depends on where the docs are hosted is not a URL worth rendering.
+ */
+ function safeAssetUrl(url) {
+ if (typeof url !== 'string' || !url) return null;
+ if (url.startsWith('//')) return null;
+ if (url.startsWith('/')) return url;
+ return /^https:\/\/[^\s/?#]+/i.test(url) ? url : null;
+ }
+
+ function renderAsset(url, kind, alt) {
+ const wrap = el('div', 'ls-asset');
+ const head = el('div', 'ls-asset-head');
+ head.append(el('span', 'ls-asset-label', 'Rendered from this response'), el('code', 'ls-asset-src', url));
+ wrap.appendChild(head);
+
+ const frame = el('div', 'ls-asset-frame');
+ /*
+ * model-viewer is loaded by the pages that host live steps. If a host
+ * page has not registered it, mounting the element would paint an empty
+ * box, so the reader gets a real link to the file instead.
+ */
+ if (kind === 'model' && !(window.customElements && customElements.get('model-viewer'))) {
+ const link = el('a', 'ls-asset-fallback', 'Open the model file');
+ link.href = url;
+ link.target = '_blank';
+ link.rel = 'noopener noreferrer';
+ frame.appendChild(link);
+ wrap.appendChild(frame);
+ return wrap;
+ }
+
+ if (kind === 'model') {
+ const viewer = document.createElement('model-viewer');
+ viewer.className = 'ls-asset-model';
+ viewer.setAttribute('src', url);
+ viewer.setAttribute('camera-controls', '');
+ viewer.setAttribute('touch-action', 'pan-y');
+ viewer.setAttribute('interaction-prompt', 'none');
+ viewer.setAttribute('shadow-intensity', '0');
+ viewer.setAttribute('exposure', '0.95');
+ viewer.setAttribute('environment-image', 'neutral');
+ viewer.setAttribute('field-of-view', '32deg');
+ viewer.setAttribute('tabindex', '0');
+ viewer.setAttribute('alt', alt || 'The model this response points at');
+ const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ if (!reduce) {
+ viewer.setAttribute('auto-rotate', '');
+ viewer.setAttribute('auto-rotate-delay', '600');
+ viewer.setAttribute('rotation-per-second', '16deg');
+ }
+ frame.append(viewer, el('span', 'ls-asset-hint', 'Drag to orbit'));
+ } else {
+ const img = new Image();
+ img.className = 'ls-asset-img';
+ img.src = url;
+ img.alt = alt || 'The image this response points at';
+ img.loading = 'lazy';
+ img.decoding = 'async';
+ img.addEventListener('error', () => {
+ frame.replaceChildren(el('p', 'ls-asset-fail', 'That URL did not load as an image.'));
+ });
+ frame.appendChild(img);
+ }
+ wrap.appendChild(frame);
+ return wrap;
+ }
+
/* ══════════════════════════════════════════════════════════════════════
* The card.
* ══════════════════════════════════════════════════════════════════════ */
@@ -689,6 +901,19 @@
showNote('is-ok', `Later steps on this page can now use ${exported.join(', ')}.`);
ctx.onExport();
}
+
+ /*
+ * The render lane. Read from the raw body (redaction never hides an
+ * asset URL, but reading raw keeps the two concerns independent), and
+ * stay quiet when the field is absent: a directory whose first entry
+ * has no portrait is a normal response, not an error to shout about.
+ */
+ if (step.renders && parsed) {
+ const raw = pickValue(parsed, parsePickPath(step.renders.pick));
+ const url = safeAssetUrl(raw);
+ const kind = step.renders.kind === 'auto' || !step.renders.kind ? mediaKind(url) : step.renders.kind;
+ if (url && kind) result.appendChild(renderAsset(url, kind, step.renders.alt));
+ }
return true;
}
@@ -812,6 +1037,10 @@
redact,
buildUrl,
explainFailure,
+ parsePickPath,
+ pickValue,
+ safeAssetUrl,
+ mediaKind,
mount,
};
})();
diff --git a/public/runnable-extract.js b/public/runnable-extract.js
deleted file mode 100644
index a06cf7868..000000000
--- a/public/runnable-extract.js
+++ /dev/null
@@ -1,350 +0,0 @@
-// three.ws runnable-sample extractor.
-//
-// One source of truth for the question "is this documentation code block safe to
-// execute for the reader, and if so, what exactly does it call?" It is imported
-// unchanged by two very different callers:
-//
-// • public/runnable-samples.js — the browser, to put a Run button on a block
-// • scripts/check-runnable-docs.mjs — Node, to execute every runnable sample in
-// docs/ against the live API and fail the build when a documented call rots
-//
-// Because both sides share this file, a sample the gate proves alive is exactly
-// the sample the reader can run, and a rule tightened here tightens both at once.
-//
-// The module is deliberately DOM-free and dependency-free so it loads in a plain
-// <script type="module"> and in Node with no build step.
-
-/** Hosts whose URLs we are willing to call on the reader's behalf. */
-export const SAFE_HOSTS = new Set(['three.ws', 'www.three.ws']);
-
-/**
- * Paths that are never runnable even when the request is a bare GET.
- * Some are account-scoped (the reader would only ever see their own 401), some
- * move money or run scheduled work, and some are pure plumbing that teaches the
- * reader nothing. A GET here is not dangerous so much as dishonest: a Run button
- * that always returns 401 is a broken promise.
- */
-export const BLOCKED_PREFIXES = [
- '/api/admin',
- '/api/auth',
- '/api/cron',
- '/api/credits',
- '/api/csrf-token',
- '/api/logout',
- '/api/pay',
- '/api/session',
- '/api/user',
- '/api/wallet',
- '/api/webhook',
-];
-
-/**
- * Request headers that mean the sample only works with a secret, a session, or a
- * device identity the reader does not have. A Run button on one of these can
- * only ever show the reader a 400 or a 401.
- */
-const CREDENTIAL_HEADERS =
- /^(authorization|cookie|x-api-key|x-payment|x-forge-provider-key|x-admin-|x-cron-|x-signature|x-irl-|x-device|x-session)/i;
-
-/** curl flags that take a value we must skip over when scanning for the URL. */
-const VALUE_FLAGS = new Set([
- '-H',
- '--header',
- '-d',
- '--data',
- '--data-raw',
- '--data-binary',
- '--data-urlencode',
- '-F',
- '--form',
- '-X',
- '--request',
- '-o',
- '--output',
- '-u',
- '--user',
- '-b',
- '--cookie',
- '-A',
- '--user-agent',
- '-e',
- '--referer',
- '-T',
- '--upload-file',
- '-w',
- '--write-out',
- '--connect-timeout',
- '--max-time',
- '-m',
- '--retry',
-]);
-
-/** Flags that prove the sample writes, uploads, or authenticates. */
-const DISQUALIFYING_FLAGS = new Set([
- '-d',
- '--data',
- '--data-raw',
- '--data-binary',
- '--data-urlencode',
- '-F',
- '--form',
- '-T',
- '--upload-file',
- '-u',
- '--user',
- '-b',
- '--cookie',
- '-O',
- '--remote-name',
- '-o',
- '--output',
-]);
-
-/**
- * Anything that says "the author left a blank here". A Run button on a URL with
- * a placeholder in it produces a confusing 400 and teaches the reader nothing.
- */
-const PLACEHOLDER_PATTERNS = [
- /[$<>{}]/, // shell vars, angle placeholders, template braces
- /\.\.\./,
- /…/, // ellipsis character
- /[A-Z][A-Z0-9]*_[A-Z0-9_]+/, // JOB_ID, AGENT_ID, YOUR_KEY
- /\byour[-_]/i,
- /\bexample\.(com|org|net)\b/i,
- /\breplace[-_]me\b/i,
-];
-
-/** Split a shell-ish command into tokens, honouring single and double quotes. */
-export function tokenize(command) {
- const tokens = [];
- let current = '';
- let quote = null;
- let started = false;
- for (let i = 0; i < command.length; i++) {
- const ch = command[i];
- if (quote) {
- if (ch === quote) quote = null;
- else current += ch;
- continue;
- }
- if (ch === '"' || ch === "'") {
- quote = ch;
- started = true;
- continue;
- }
- if (/\s/.test(ch)) {
- if (started || current) tokens.push(current);
- current = '';
- started = false;
- continue;
- }
- current += ch;
- }
- if (started || current) tokens.push(current);
- return tokens;
-}
-
-/**
- * Reduce a fenced shell block to the single command it contains, or null.
- * Handles backslash line-continuations, `$`/`>` prompts, and `#` comments. A
- * block holding two commands is not runnable: we will not guess which one the
- * reader meant.
- */
-export function singleCommand(source) {
- const joined = String(source || '')
- .replace(/\\\r?\n[ \t]*/g, ' ')
- .replace(/\r/g, '');
- const lines = joined
- .split('\n')
- .map((line) => line.replace(/^\s*[$>]\s+/, '').trim())
- .filter((line) => line && !line.startsWith('#'));
- if (lines.length !== 1) return null;
- return lines[0];
-}
-
-function hasPlaceholder(value) {
- return PLACEHOLDER_PATTERNS.some((re) => re.test(value));
-}
-
-function blocked(pathname) {
- return BLOCKED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
-}
-
-/**
- * Parse an author directive written as an HTML comment directly above a fence:
- *
- * <!-- runnable: no the vault id is illustrative -->
- * <!-- runnable: 402 the x402 challenge is the lesson -->
- *
- * `no` opts a block out of the Run button and out of the gate. A status code
- * declares what this endpoint is supposed to answer, so the gate can hold a
- * paywalled or deliberately-empty endpoint to its real contract instead of
- * demanding a blanket 200.
- *
- * @param {string|null|undefined} comment the comment's inner text
- * @returns {{skip: true, note: string}|{expectStatus: number, note: string}|null}
- */
-export function parseDirective(comment) {
- if (!comment) return null;
- const match = String(comment)
- .trim()
- .match(/^runnable:\s*(no|\d{3})\b\s*(.*)$/is);
- if (!match) return null;
- const note = match[2].trim();
- if (/^no$/i.test(match[1])) return { skip: true, note };
- return { expectStatus: Number(match[1]), note };
-}
-
-/**
- * Decide whether a documentation code block can be executed for the reader.
- *
- * @param {string} source raw text of the code block
- * @param {string} [lang] the fence language, when the caller knows it
- * @param {string} [comment] an author directive comment sitting above the fence
- * @returns {{runnable: true, method: 'GET', url: string, path: string, accept: string|null,
- * expectStatus: number|null, note: string}
- * |{runnable: false, reason: string}}
- */
-export function extractRunnable(source, lang, comment) {
- const directive = parseDirective(comment);
- if (directive && directive.skip) {
- return { runnable: false, reason: directive.note || 'the author opted this block out' };
- }
- if (lang && !/^(bash|sh|shell|console|zsh|curl)$/i.test(lang)) {
- return { runnable: false, reason: 'not a shell block' };
- }
- const command = singleCommand(source);
- if (!command) return { runnable: false, reason: 'not a single command' };
- if (!/^curl(\s|$)/.test(command)) return { runnable: false, reason: 'not a curl command' };
-
- const tokens = tokenize(command);
- let method = 'GET';
- let accept = null;
- let url = null;
-
- for (let i = 1; i < tokens.length; i++) {
- const token = tokens[i];
-
- if (token === '-X' || token === '--request') {
- method = String(tokens[++i] || '').toUpperCase();
- continue;
- }
- if (token === '-H' || token === '--header') {
- const header = String(tokens[++i] || '');
- if (CREDENTIAL_HEADERS.test(header.trim())) {
- return { runnable: false, reason: 'needs a credential header' };
- }
- const [name, ...rest] = header.split(':');
- if (/^accept$/i.test(name.trim())) accept = rest.join(':').trim();
- continue;
- }
- if (DISQUALIFYING_FLAGS.has(token)) {
- return { runnable: false, reason: 'writes, uploads, or authenticates' };
- }
- if (VALUE_FLAGS.has(token)) {
- i++;
- continue;
- }
- if (token.startsWith('-')) continue; // a bundled boolean flag such as -sL or -i
- if (url) return { runnable: false, reason: 'more than one URL' };
- url = token;
- }
-
- if (method !== 'GET' && method !== 'HEAD') {
- return { runnable: false, reason: `method ${method} is not read-only` };
- }
- if (!url) return { runnable: false, reason: 'no URL in the command' };
- if (hasPlaceholder(url)) return { runnable: false, reason: 'the URL contains a placeholder' };
-
- let parsed;
- try {
- parsed = new URL(url);
- } catch {
- return { runnable: false, reason: 'not an absolute URL' };
- }
- if (parsed.protocol !== 'https:') return { runnable: false, reason: 'not https' };
- if (!SAFE_HOSTS.has(parsed.hostname)) return { runnable: false, reason: 'not a three.ws URL' };
- if (blocked(parsed.pathname)) return { runnable: false, reason: 'account-scoped or privileged path' };
-
- // Runnable paths are API calls and small JSON manifests. Everything else on
- // the site is a page or a multi-megabyte binary; neither belongs in an
- // inline response console.
- const isApi = parsed.pathname.startsWith('/api/');
- const isJson = parsed.pathname.endsWith('.json');
- if (!isApi && !isJson) return { runnable: false, reason: 'not an API or JSON path' };
-
- return {
- runnable: true,
- method: 'GET',
- url: parsed.toString(),
- path: `${parsed.pathname}${parsed.search}`,
- accept,
- expectStatus: directive ? directive.expectStatus : null,
- note: directive ? directive.note : '',
- };
-}
-
-/**
- * Pull every fenced code block out of a markdown document, along with any author
- * directive comment on the line above it.
- * @returns {Array<{lang: string, code: string, line: number, comment: string|null}>}
- */
-export function codeBlocks(markdown) {
- const out = [];
- const lines = String(markdown || '').split('\n');
- let fence = null;
- let lang = '';
- let start = 0;
- let comment = null;
- let buffer = [];
- let lastComment = null;
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (!fence) {
- const html = line.match(/^\s*<!--([\s\S]*?)-->\s*$/);
- if (html) {
- lastComment = html[1];
- continue;
- }
- }
- const open = line.match(/^\s*(`{3,}|~{3,})\s*([A-Za-z0-9_-]*)\s*$/);
- if (!fence && open) {
- fence = open[1][0].repeat(3);
- lang = open[2] || '';
- start = i + 2;
- comment = lastComment;
- lastComment = null;
- buffer = [];
- continue;
- }
- if (fence) {
- const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);
- if (close && close[1][0] === fence[0]) {
- out.push({ lang, code: buffer.join('\n'), line: start, comment });
- fence = null;
- comment = null;
- buffer = [];
- continue;
- }
- buffer.push(line);
- continue;
- }
- // A directive only binds to the fence it immediately precedes.
- if (line.trim()) lastComment = null;
- }
- return out;
-}
-
-/**
- * Every runnable sample in a markdown document, in document order.
- * @returns {Array<{url: string, path: string, accept: string|null, expectStatus: number|null,
- * note: string, line: number, code: string}>}
- */
-export function runnableSamples(markdown) {
- const out = [];
- for (const block of codeBlocks(markdown)) {
- const verdict = extractRunnable(block.code, block.lang, block.comment);
- if (verdict.runnable) out.push({ ...verdict, line: block.line, code: block.code });
- }
- return out;
-}
diff --git a/scripts/check-runnable-docs.mjs b/scripts/check-runnable-docs.mjs
index bc3bceab5..81d801b58 100644
--- a/scripts/check-runnable-docs.mjs
+++ b/scripts/check-runnable-docs.mjs
@@ -8,8 +8,9 @@
* Documentation rots silently. A curl command in a tutorial can point at an
* endpoint that was renamed two quarters ago and nothing notices, because the
* doc still reads fine. This turns that class of rot into a build failure: if
- * the reader can press Run on a sample, CI can press Run on the same sample,
- * using literally the same extractor (public/runnable-extract.js).
+ * the reader can press Run on a sample, CI presses Run on the same sample, over
+ * the same parser and the same safety rules the Live Docs runner uses
+ * (public/docs-live-verify.js on top of public/docs-live-core.js).
*
* A sample passes when the live response status matches its contract:
* • by default, any 2xx
@@ -34,7 +35,7 @@
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve, dirname, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { runnableSamples } from '../public/runnable-extract.js';
+import { verifiableSamples } from '../public/docs-live-verify.js';
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const DOCS = join(ROOT, 'docs');
@@ -50,11 +51,18 @@ const ONLY = flag('only');
const CONCURRENCY = Math.max(1, Math.min(12, Number(flag('concurrency', '6')) || 6));
const TIMEOUT_MS = Math.max(5000, Number(flag('timeout', '30000')) || 30000);
+/**
+ * Generated single-file aggregates hold a copy of every other doc, so probing
+ * them would double every call and report each failure against a file nobody
+ * edits. The same set is skipped by audit-docs and the docs search index.
+ */
+const GENERATED_AGGREGATES = new Set(['ALL.md', 'EVERYTHING.md']);
+
function walk(dir, out = []) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) walk(path, out);
- else if (entry.name.endsWith('.md')) out.push(path);
+ else if (entry.name.endsWith('.md') && !GENERATED_AGGREGATES.has(entry.name)) out.push(path);
}
return out;
}
@@ -63,7 +71,7 @@ function inventory() {
const byUrl = new Map();
for (const file of walk(DOCS)) {
const rel = relative(ROOT, file);
- for (const sample of runnableSamples(readFileSync(file, 'utf8'))) {
+ for (const sample of verifiableSamples(readFileSync(file, 'utf8'))) {
if (ONLY && !sample.url.includes(ONLY)) continue;
const existing = byUrl.get(sample.url);
if (existing) {
@@ -89,28 +97,37 @@ function inventory() {
return [...byUrl.values()].sort((a, b) => a.url.localeCompare(b.url));
}
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
async function probe(sample) {
const url = `${BASE}${sample.path}`;
const started = Date.now();
- try {
- const res = await fetch(url, {
- headers: { accept: sample.accept || 'application/json, */*' },
- redirect: 'follow',
- signal: AbortSignal.timeout(TIMEOUT_MS),
- });
- const expected = sample.expectStatus
- ? res.status === sample.expectStatus
- : res.status >= 200 && res.status < 300;
- return { ...sample, status: res.status, ms: Date.now() - started, ok: expected };
- } catch (err) {
- return {
- ...sample,
- status: 'ERR',
- ms: Date.now() - started,
- ok: false,
- error: String(err.message || err).slice(0, 120),
- };
+ let last = null;
+ // Two attempts, because a shared per-IP budget can throttle a burst of
+ // probes and a 429 says nothing about whether the doc is still true.
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (attempt) await sleep(2500);
+ try {
+ const res = await fetch(url, {
+ headers: { accept: sample.accept || 'application/json, */*' },
+ redirect: 'follow',
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ last = { status: res.status };
+ if (res.status !== 429) break;
+ } catch (err) {
+ last = { status: 'ERR', error: String(err.message || err).slice(0, 120) };
+ break;
+ }
+ }
+ const ms = Date.now() - started;
+ if (sample.expectStatus) {
+ return { ...sample, ...last, ms, ok: last.status === sample.expectStatus };
}
+ // A 429 that survives the retry still proves the route exists and is
+ // enforcing its budget, which is all this gate claims to check.
+ const alive = (last.status >= 200 && last.status < 300) || last.status === 429;
+ return { ...sample, ...last, ms, ok: alive, throttled: last.status === 429 };
}
async function main() {
diff --git a/tests/docs-live-core.test.js b/tests/docs-live-core.test.js
index 01b195299..0a3edde44 100644
--- a/tests/docs-live-core.test.js
+++ b/tests/docs-live-core.test.js
@@ -20,7 +20,7 @@ import {
formatResponseBody,
isSecretName,
parseCurl,
- rewriteAssetOrigin,
+ baseTag,
runLabel,
statusTone,
tokenizeShell,
@@ -261,21 +261,34 @@ describe('applyPlaceholders', () => {
});
});
-describe('rewriteAssetOrigin', () => {
- it('points production asset URLs at a dev origin so the preview tests the local build', () => {
- const out = rewriteAssetOrigin('<script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>', 'http://localhost:3000');
- expect(out).toContain('http://localhost:3000/agent-3d/latest/agent-3d.js');
+describe('baseTag', () => {
+ it('anchors relative URLs to the origin the reader is on', () => {
+ expect(baseTag('http://localhost:3000/docs/')).toBe('<base href="http://localhost:3000/">');
+ expect(baseTag('https://three.ws')).toBe('<base href="https://three.ws/">');
});
- it('is a no-op on three.ws itself', () => {
- const html = '<script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>';
- expect(rewriteAssetOrigin(html, 'https://three.ws')).toBe(html);
- expect(rewriteAssetOrigin(html, 'https://www.three.ws')).toBe(html);
+ it('emits nothing when there is no usable origin', () => {
+ expect(baseTag()).toBe('');
+ expect(baseTag('not a url')).toBe('');
});
+});
- it('leaves other hosts untouched', () => {
- const html = '<img src="https://cdn.example/x.png">';
- expect(rewriteAssetOrigin(html, 'http://localhost:3000')).toBe(html);
+describe('absolute URLs in a snippet', () => {
+ // The first version of this feature rewrote https://three.ws/… to the
+ // current origin so a dev-server preview would exercise the local build.
+ // That broke every preview on any origin not serving /agent-3d/: the
+ // sandboxed frame has an opaque origin, so the rewritten module script was
+ // a cross-origin load with no CORS behind it. Production serves those
+ // assets with `access-control-allow-origin: *`; leaving the URL alone is
+ // both what works and what the reader will actually paste.
+ it('leaves a production asset URL exactly as published', () => {
+ const snippet = '<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>';
+ expect(buildPreviewDoc(snippet, { origin: 'http://localhost:3099' })).toContain(
+ 'https://three.ws/agent-3d/latest/agent-3d.js',
+ );
+ expect(buildScriptDoc('fetch("https://three.ws/api/version")', { origin: 'http://localhost:3099' })).toContain(
+ 'https://three.ws/api/version',
+ );
});
});
diff --git a/tests/live-steps.test.js b/tests/live-steps.test.js
index ad1631926..79b604267 100644
--- a/tests/live-steps.test.js
+++ b/tests/live-steps.test.js
@@ -14,8 +14,20 @@ import vm from 'node:vm';
const ROOT = resolve(__dirname, '..');
const SOURCE = readFileSync(join(ROOT, 'public/live-steps.js'), 'utf8');
+/*
+ * A fresh vm context has no web globals, so hand the script the same small set
+ * a browser would: URL and URLSearchParams for request building, and a location
+ * for resolving relative asset URLs. Anything beyond this (document, fetch) is
+ * only reached from mount(), which the browser pass in
+ * scripts/capture-live-steps-media.mjs exercises for real.
+ */
function load() {
- const sandbox = { window: {} };
+ const sandbox = {
+ window: {},
+ URL,
+ URLSearchParams,
+ location: new URL('https://three.ws/tutorials/wallet-sign-in'),
+ };
vm.createContext(sandbox);
vm.runInContext(SOURCE, sandbox, { filename: 'live-steps.js' });
return sandbox.window.LiveSteps;
@@ -248,6 +260,72 @@ describe('the SIWS message derivation', () => {
});
});
+describe('the rendered-asset lane', () => {
+ it('parses a dotted path with indexes', () => {
+ expect(LiveSteps.parsePickPath('agents[0].avatar_thumbnail')).toEqual([
+ 'agents',
+ 0,
+ 'avatar_thumbnail',
+ ]);
+ expect(LiveSteps.parsePickPath('data.launches[2].agent.avatar_thumbnail_url')).toEqual([
+ 'data',
+ 'launches',
+ 2,
+ 'agent',
+ 'avatar_thumbnail_url',
+ ]);
+ });
+
+ it('rejects anything that is not a plain path', () => {
+ for (const bad of ['', 'a..b', 'a[b]', 'a[]', '.a', 'a.', 'a()', 'a[0', null, 42]) {
+ expect(LiveSteps.parsePickPath(bad)).toBe(null);
+ }
+ });
+
+ it('reads a value, and returns undefined rather than throwing on a miss', () => {
+ const body = { agents: [{ avatar_thumbnail: '/a.png' }] };
+ expect(LiveSteps.pickValue(body, ['agents', 0, 'avatar_thumbnail'])).toBe('/a.png');
+ expect(LiveSteps.pickValue(body, ['agents', 5, 'avatar_thumbnail'])).toBe(undefined);
+ expect(LiveSteps.pickValue(body, ['nope', 'deeper'])).toBe(undefined);
+ // An array where an object key is expected must not be indexed by name.
+ expect(LiveSteps.pickValue(body, ['agents', 'avatar_thumbnail'])).toBe(undefined);
+ });
+
+ it('only lets https and same-origin paths become a subresource', () => {
+ expect(LiveSteps.safeAssetUrl('/avatars/cz.glb')).toBe('/avatars/cz.glb');
+ expect(LiveSteps.safeAssetUrl('https://cdn.example/a.png')).toBe('https://cdn.example/a.png');
+ for (const bad of [
+ 'javascript:alert(1)',
+ 'data:image/svg+xml,<svg onload=alert(1)>',
+ 'http://insecure.example/a.png',
+ '//evil.example/a.png',
+ '',
+ null,
+ {},
+ ]) {
+ expect(LiveSteps.safeAssetUrl(bad)).toBe(null);
+ }
+ });
+
+ it('infers the asset kind from the extension, query string and all', () => {
+ expect(LiveSteps.mediaKind('/a/b.glb')).toBe('model');
+ expect(LiveSteps.mediaKind('/a/b.gltf?v=2')).toBe('model');
+ expect(LiveSteps.mediaKind('/a/b.webp#x')).toBe('image');
+ expect(LiveSteps.mediaKind('/a/b.JPG')).toBe('image');
+ expect(LiveSteps.mediaKind('/a/b.txt')).toBe(null);
+ expect(LiveSteps.mediaKind(null)).toBe(null);
+ });
+
+ it('every registered render declares a readable path, a known kind and alt text', () => {
+ for (const step of LiveSteps.STEPS) {
+ if (!step.renders) continue;
+ expect(LiveSteps.parsePickPath(step.renders.pick)).toBeTruthy();
+ expect(['image', 'model', 'auto', undefined]).toContain(step.renders.kind);
+ expect(String(step.renders.alt).length).toBeGreaterThan(10);
+ }
+ });
+});
+
describe('shipped documentation only references registered steps', () => {
function walk(dir, out = []) {
for (const name of readdirSync(dir)) {