Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(assets-cli): add a three.ws asset to a project in one command
nirholasd3ba098e22d2
diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 4b0f70c4e..94e7201dc 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -46,6 +46,118 @@ Rate-limited responses return HTTP 429 with `{ "error": "...", "code": "RATE_LIM---+## Asset Catalog API++One search across every ready-made asset three.ws publishes: the CC0 object/prop library, the ready-made character library, and the motion-clip library. **No authentication, no API key, no payment.** Open CORS, cached at the edge for 5 minutes.++The same join and the same code generation back the free MCP tools (`search_catalog`, `get_catalog_item`, `get_item_source`) and the `@three-ws/assets` CLI, so all three surfaces answer identically.++### Search the catalog++```+GET /api/catalog?q=wooden+chair&kind=object&limit=12&offset=0+```++| Parameter | Notes |+| --- | --- |+| `q` | Free text over titles, names, tags, and categories |+| `kind` | `object`, `character`, or `animation` |+| `category` | Exact category, from a previous response's `facets.categories` |+| `tag` | Exact tag, from `facets.tags` |+| `limit` | 1 to 50 (default 12) |+| `offset` | Page offset; use `next_offset` from the previous response |++Every word of `q` must match somewhere, which keeps a two-word query precise. If nothing matches all of them, the search retries on any of them and sets `relaxed: true`, so a phrase never dead-ends silently.++**Response**++```json+{+ "ok": true,+ "items": [+ {+ "id": "object:painted_wooden_chair_01",+ "kind": "object",+ "name": "painted_wooden_chair_01",+ "title": "Painted Wooden Chair 01",+ "categories": ["furniture", "seating"],+ "tags": ["chair", "wood", "painted"],+ "license": "CC0",+ "format": "glb",+ "url": "https://cdn.three.ws/objects/polyhaven/glb/painted_wooden_chair_01.glb",+ "thumb": "https://cdn.three.ws/objects/polyhaven/thumbs/painted_wooden_chair_01.png",+ "bytes": 491572+ }+ ],+ "matched": 10,+ "relaxed": false,+ "total": 3492,+ "offset": 0,+ "next_offset": 12,+ "facets": {+ "kinds": { "object": 10 },+ "categories": [{ "value": "furniture", "count": 8 }],+ "tags": [{ "value": "chair", "count": 6 }]+ },+ "generated_at": { "object": "2026-07-21T13:16:14.305Z" }+}+```++`total` is the whole catalog; `matched` is how many the query hit. A character adds `rigged`, `skins`, `baked_animations`, and `source`; a motion clip adds `duration_seconds`, `loop`, and `format: "three-animation-clip-json"`.++**Errors:** `400 validation_error` for an unknown `kind` or a non-integer/out-of-range `limit` or `offset`, validated before any storage read.++---++### Get one item with its source++```+GET /api/catalog?id=object:painted_wooden_chair_01+```++Returns the item, the site links that browse/preview/edit it, up to six related items of the same kind, and paste-ready source in every framework that applies.++**Response**++```json+{+ "ok": true,+ "item": { "id": "object:painted_wooden_chair_01", "kind": "object" },+ "links": {+ "browse": "https://three.ws/objects",+ "preview": "https://three.ws/app#model=...&kind=object",+ "ar": "https://three.ws/ar/studio?src=...",+ "download": "https://cdn.three.ws/objects/..."+ },+ "related": [{ "id": "object:bar_chair_round_01", "title": "Bar Chair Round 01" }],+ "frameworks": ["model-viewer", "three", "agent-3d", "react"],+ "snippets": {+ "model-viewer": {+ "language": "html",+ "code": "<model-viewer src=\"https://cdn.three.ws/...\" ...></model-viewer>",+ "notes": ["This is the exact renderer and build the three.ws browse grids use."]+ }+ }+}+```++`frameworks[0]` is the recommended one for that kind: `model-viewer` for a prop, `agent-3d` for a rigged character, `three` for a motion clip. The `agent-3d` snippet is pinned to the exact published component version with its Subresource Integrity hash, never `latest`.++A bare name (`painted_wooden_chair_01`) also resolves. An unknown id returns `404 not_found` with a `hint` naming the search call to make instead.++---++### From the command line++```bash+npx @three-ws/assets search wooden chair --kind object+npx @three-ws/assets add object:painted_wooden_chair_01+```++`add` downloads the asset into `public/three-ws/` and prints the snippet rewritten to point at the local copy. See [packages/assets-cli/README.md](../packages/assets-cli/README.md).++---+## Agents API### List agentsdiff --git a/package.json b/package.jsonindex 55f7dcc3e..9a0cf069f 100644--- a/package.json+++ b/package.json@@ -77,6 +77,7 @@"services/liquidation-collector","packages/avatar-schema","packages/avatar-cli",+ "packages/assets-cli","packages/defi-utils","packages/viewer-presets","packages/avatar-agent-mcp",@@ -380,6 +381,7 @@"feedback:repro": "node --env-file-if-exists=.env.local scripts/feedback-repro.mjs","test:agent-vitals": "node --test packages/agent-vitals/test/*.test.js","test:witness": "node --test packages/witness/test/*.test.js",+ "test:assets-cli": "node --test packages/assets-cli/test/*.test.js","build:info": "node scripts/write-build-info.mjs","build:info:snapshot": "node scripts/write-build-info.mjs --snapshot","build:gcp": "npm run check:conflicts && npm run check:browser-graph && npm run check:tdz-bootstrap && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:lib:full && npm run build:avatar-sdk && npm run build:chat && npm run build && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",diff --git a/packages/assets-cli/LICENSE b/packages/assets-cli/LICENSEnew file mode 100644index 000000000..b5ae2a4e1--- /dev/null+++ b/packages/assets-cli/LICENSE@@ -0,0 +1,201 @@+ 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, whether in Source or+ Object form, 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 modifications+ 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 any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to 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 otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated 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 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 a Contribution incorporated 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, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, 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 as an addendum 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 copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 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 redistributing 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 consequential 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 any and 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 act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ 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/packages/assets-cli/README.md b/packages/assets-cli/README.mdnew file mode 100644index 000000000..406d687e9--- /dev/null+++ b/packages/assets-cli/README.md@@ -0,0 +1,173 @@+# @three-ws/assets++Find a ready-made 3D prop, rigged character, or motion clip on [three.ws](https://three.ws)+and put it in your project, with the code that renders it.++Free and public. No account, no API key, no payment, nothing to sign up for. The catalog it+searches is the platform's published CC0 object library, ready-made character library, and+motion-clip library: **3,492 assets** as of September 2026.++```bash+npx @three-ws/assets search wooden chair --kind object+npx @three-ws/assets add object:painted_wooden_chair_01+```++The second command downloads the GLB into `public/three-ws/` and prints this, ready to paste:++```html+<script+ type="module"+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"+ integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"+ crossorigin="anonymous"+></script>++<model-viewer+ src="/three-ws/painted_wooden_chair_01.glb"+ alt="Painted Wooden Chair 01"+ camera-controls+ auto-rotate+ ar+ shadow-intensity="1"+ style="width:100%;height:420px"+></model-viewer>+```++Note the `src`: the snippet points at the copy on your disk, not at our CDN. Your site keeps+working if we are down.++## Install++Nothing to install. `npx @three-ws/assets <command>` runs the current version. To pin it:++```bash+npm install --save-dev @three-ws/assets+```++Requires Node 18 or newer (it uses the built-in `fetch`).++## Commands++### `search <terms…>`++Search all three libraries at once.++```bash+three-ws-assets search industrial lamp+three-ws-assets search wave --kind animation --limit 5+three-ws-assets search --kind character --json+```++| Flag | Meaning |+| --- | --- |+| `--kind <k>` | `object` (CC0 props), `character` (rigged humanoids), `animation` (motion clips) |+| `--category <c>` | Exact category, from the `categories:` line of a previous result |+| `--tag <t>` | Exact tag |+| `--limit <n>` | 1 to 50, default 12 |+| `--offset <n>` | Page offset, printed as `more:` when there are more results |+| `--json` | Raw JSON on stdout |++Every word of the query has to match something (title, name, tag, or category), which is what+keeps a two-word search precise. If nothing matches all of the words, you get the partial+matches with a warning on stderr rather than an empty list.++Exits `1` when nothing matches, so a script can branch on it.++### `show <id>`++Print one item's facts plus paste-ready source, without downloading anything.++```bash+three-ws-assets show object:painted_wooden_chair_01+three-ws-assets show character:abe --framework three+three-ws-assets show animation:mx-wave-abc123 --json+```++With no `--framework` you get the one that fits the item and the names of the others. With+one, you get only that snippet, so `three-ws-assets show <id> --framework three > model.js`+produces a usable file.++### `add <id>`++Download the asset into your project and print the snippet rewritten to point at the local+copy.++```bash+three-ws-assets add object:painted_wooden_chair_01+three-ws-assets add character:abe --dir src/models --framework agent-3d+three-ws-assets add animation:mx-wave-abc123 --thumb+```++| Flag | Meaning |+| --- | --- |+| `--dir <path>` | Where to write. Defaults to `public/three-ws/` when the project has a `public/` directory, otherwise `three-ws-assets/` |+| `--framework <f>` | `agent-3d`, `model-viewer`, `three`, or `react` |+| `--thumb` | Download the thumbnail alongside the asset |+| `--force` | Overwrite a file whose contents changed since it was added |+| `--json` | Written paths, the local url, and the snippet, as JSON |++`add` is safe to put in a setup script:++- a re-run that would write identical bytes reports the file as already up to date and+ changes nothing;+- a file you edited after adding it is **never** overwritten without `--force`, and the+ command exits `1` instead;+- parent directories are created as needed.++When the target directory is not under a `public/` directory we cannot prove the file will be+served, so the snippet uses a project-relative path and the command says so on stderr.++## Frameworks++| Framework | What you get |+| --- | --- |+| `model-viewer` | The `<model-viewer>` tag, build, and integrity hash the three.ws browse grids themselves render with. The default for props. |+| `agent-3d` | The `<agent-3d>` web component, pinned to the exact published version with its Subresource Integrity hash. Never `latest`. The default for rigged characters. |+| `three` | Plain three.js: `GLTFLoader` for a model, `THREE.AnimationClip.parse` for a motion clip. The default for clips. |+| `react` | The same wrapped as a React component, or a hook for a clip. |++## Licensing++Every object in the CC0 library is public domain: use it commercially, modify it, no+attribution required. Characters and motion clips carry their own `license` field, printed by+`show` and `add` and present in `--json` output. Check it before shipping.++## Configuration++| Variable | Purpose |+| --- | --- |+| `THREE_WS_API` | Catalog origin. Defaults to `https://three.ws`. Also settable per call with `--api <origin>`. |+| `NO_COLOR` | Disable colored output (also `--no-color`). |+| `FORCE_COLOR` | Force color when stdout is not a TTY. |++## Programmatic use++The catalog client is exported, so a build script can skip the CLI:++```js+import { resolveApi, searchCatalog, fetchItem, downloadAsset } from '@three-ws/assets/api';++const origin = resolveApi();+const { items } = await searchCatalog(origin, { q: 'desk lamp', kind: 'object', limit: 5 });+const { item, snippets } = await fetchItem(origin, items[0].id);+const bytes = await downloadAsset(item.url);+```++Or talk to the endpoint directly: `GET https://three.ws/api/catalog?q=desk+lamp&kind=object`.++## The same catalog from an AI client++Every three.ws MCP client gets the same data through three free tools, `search_catalog`,+`get_catalog_item`, and `get_item_source`. Add the server and ask for a chair in plain+language:++```json+{ "mcpServers": { "three-ws": { "type": "http", "url": "https://three.ws/api/mcp" } } }+```++See [docs/mcp.md](https://three.ws/docs/mcp) for the tool schemas.++## License++Apache-2.0. The tool is Apache-2.0; the assets it downloads carry their own licenses, as+above.diff --git a/packages/assets-cli/package.json b/packages/assets-cli/package.jsonnew file mode 100644index 000000000..d4aa801f3--- /dev/null+++ b/packages/assets-cli/package.json@@ -0,0 +1,53 @@+{+ "name": "@three-ws/assets",+ "version": "0.1.0",+ "description": "Find a ready-made 3D prop, rigged character, or motion clip on three.ws and add it to your project with the code that renders it. Free and public: no account, no API key, no payment.",+ "keywords": [+ "three.ws",+ "3d",+ "glb",+ "gltf",+ "cc0",+ "assets",+ "cli",+ "three.js",+ "model-viewer",+ "animation",+ "avatar",+ "props"+ ],+ "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": "packages/assets-cli"+ },+ "type": "module",+ "bin": {+ "three-ws-assets": "./src/cli.js"+ },+ "main": "./src/cli.js",+ "exports": {+ ".": "./src/cli.js",+ "./api": "./src/api.js"+ },+ "files": [+ "src",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "test": "node --test test/*.test.js"+ },+ "engines": {+ "node": ">=18"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/assets-cli/src/api.js b/packages/assets-cli/src/api.jsnew file mode 100644index 000000000..a0f9f2458--- /dev/null+++ b/packages/assets-cli/src/api.js@@ -0,0 +1,92 @@+// The one place this CLI talks to three.ws.+//+// Everything goes through GET /api/catalog, the public asset catalog: no API+// key, no account, no payment. The base origin is overridable so the same CLI+// drives a local dev server (`--api http://localhost:3000`) or a preview+// deployment without a rebuild.++export const DEFAULT_API = 'https://three.ws';++/** Resolve the API origin from a flag, then the environment, then the default. */+export function resolveApi(flags = {}) {+ const raw = typeof flags.api === 'string' ? flags.api : process.env.THREE_WS_API;+ const origin = String(raw || DEFAULT_API).trim().replace(/\/+$/, '');+ if (!/^https?:\/\//.test(origin)) {+ throw new Error(`--api must be an http(s) origin, got "${origin}"`);+ }+ return origin;+}++// A network hiccup on a 15 KB JSON read is worth one retry; a 404 or a 400 is+// the caller's answer and is returned as-is for the command to explain.+async function getJson(url, { timeoutMs = 15_000, attempts = 2 } = {}) {+ let lastErr;+ for (let attempt = 1; attempt <= attempts; attempt++) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetch(url, {+ headers: { accept: 'application/json' },+ signal: controller.signal,+ });+ const body = await res.json().catch(() => null);+ return { ok: res.ok, status: res.status, body };+ } catch (err) {+ lastErr = err;+ } finally {+ clearTimeout(timer);+ }+ }+ throw new Error(`could not reach the catalog: ${lastErr?.message || lastErr}`);+}++/** Search the catalog. Returns the parsed response body. */+export async function searchCatalog(origin, { q, kind, category, tag, limit, offset } = {}) {+ const url = new URL('/api/catalog', origin);+ if (q) url.searchParams.set('q', q);+ if (kind) url.searchParams.set('kind', kind);+ if (category) url.searchParams.set('category', category);+ if (tag) url.searchParams.set('tag', tag);+ if (limit) url.searchParams.set('limit', String(limit));+ if (offset) url.searchParams.set('offset', String(offset));+ const { ok, status, body } = await getJson(url.href);+ if (!ok) throw new Error(body?.message || `catalog search failed (HTTP ${status})`);+ return body;+}++/** One item plus its links, related items, and every source snippet. */+export async function fetchItem(origin, id) {+ const url = new URL('/api/catalog', origin);+ url.searchParams.set('id', id);+ const { ok, status, body } = await getJson(url.href);+ if (status === 404) {+ const err = new Error(`no catalog item with id "${id}"`);+ err.notFound = true;+ throw err;+ }+ if (!ok) throw new Error(body?.message || `catalog lookup failed (HTTP ${status})`);+ return body;+}++/**+ * Download one asset's bytes. Assets are served straight off the CDN with open+ * CORS, so this never proxies through the API.+ *+ * @returns {Promise<Buffer>}+ */+export async function downloadAsset(url, { timeoutMs = 120_000 } = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetch(url, { signal: controller.signal });+ if (!res.ok) throw new Error(`download failed (HTTP ${res.status}) for ${url}`);+ return Buffer.from(await res.arrayBuffer());+ } catch (err) {+ if (err.name === 'AbortError') {+ throw new Error(`download timed out after ${timeoutMs}ms`, { cause: err });+ }+ throw err;+ } finally {+ clearTimeout(timer);+ }+}diff --git a/packages/assets-cli/src/cli.js b/packages/assets-cli/src/cli.jsnew file mode 100755index 000000000..a5378cc48--- /dev/null+++ b/packages/assets-cli/src/cli.js@@ -0,0 +1,229 @@+#!/usr/bin/env node+// three-ws-assets: find a ready-made 3D asset on three.ws and put it in your+// project, with the code that renders it.+//+// Everything this CLI reads is free and public. There is no login, no API key,+// and no payment: the catalog it searches is the platform's published CC0 prop+// library, ready-made character library, and motion-clip library.++import { add } from './commands/add.js';+import { search } from './commands/search.js';+import { show } from './commands/show.js';+import { style, symbols, failure, hint } from './style.js';++const COMMANDS = {+ search: {+ run: search,+ summary: 'Search the three.ws asset catalog',+ usage: `${style.bold('three-ws-assets search')} ${style.dim('<terms…> [options]')}++ Search every ready-made asset three.ws publishes: CC0 props, rigged+ characters, and retargetable motion clips. Every word has to match, so a+ two-word query stays precise; if nothing matches all of them you get the+ partial matches with a warning rather than an empty list.++ ${style.bold('options')}+ --kind <k> object | character | animation+ --category <c> Exact category from a previous result+ --tag <t> Exact tag from a previous result+ --limit <n> 1..50 (default: 12)+ --offset <n> Page offset (see "more:" in the output)+ --json Raw JSON on stdout+ --api <origin> Catalog origin (default: https://three.ws)++ ${style.dim('example')}+ three-ws-assets search wooden chair --kind object`,+ },+ show: {+ run: show,+ summary: 'Print one item and the code that renders it',+ usage: `${style.bold('three-ws-assets show')} ${style.dim('<id> [options]')}++ Print an item's facts plus paste-ready source. Without --framework you get+ the one that fits the item (model-viewer for a prop, agent-3d for a rigged+ character, three for a motion clip) and the names of the others.++ ${style.bold('options')}+ --framework <f> agent-3d | model-viewer | three | react+ --json Raw JSON, including every framework's snippet+ --api <origin> Catalog origin (default: https://three.ws)++ ${style.dim('example')}+ three-ws-assets show object:painted_wooden_chair_01 --framework three`,+ },+ add: {+ run: add,+ summary: 'Download an asset into your project and print its snippet',+ usage: `${style.bold('three-ws-assets add')} ${style.dim('<id> [options]')}++ Download the GLB (or clip JSON) into your project and print the snippet+ rewritten to point at the local copy. Files land in ${style.cyan('public/three-ws/')} when+ the project has a public directory, otherwise ${style.cyan('three-ws-assets/')}.++ A re-run that would write identical bytes reports the file as already up to+ date. A file whose contents changed since it was added is never overwritten+ without ${style.cyan('--force')}.++ ${style.bold('options')}+ --dir <path> Where to write (default: public/three-ws)+ --framework <f> agent-3d | model-viewer | three | react+ --thumb Download the thumbnail too+ --force Overwrite a file whose contents differ+ --json Raw JSON: written paths, the local url, the snippet+ --api <origin> Catalog origin (default: https://three.ws)++ ${style.dim('example')}+ three-ws-assets add object:painted_wooden_chair_01 --thumb`,+ },+};++function topHelp() {+ const rows = Object.entries(COMMANDS)+ .map(([name, c]) => ` ${style.cyan(name.padEnd(8))} ${c.summary}`)+ .join('\n');+ return `+${style.bold('three-ws-assets')} ${style.dim('<command> [options]')}++ Ready-made 3D props, rigged characters, and motion clips from three.ws.+ Free and public: no account, no API key, no payment.++${style.bold('commands')}+${rows}++${style.bold('global')}+ --help, -h Show help (use ${style.cyan('<command> --help')} for command details)+ --version, -V Print the CLI version+ --no-color Disable colored output+ --api <origin> Catalog origin, or set ${style.cyan('THREE_WS_API')}++${style.dim('quick start')}+ ${style.dim('three-ws-assets search wooden chair --kind object')}+ ${style.dim('three-ws-assets add object:painted_wooden_chair_01')}++${style.dim(`${symbols.arrow} docs: https://three.ws/docs/mcp ${symbols.bullet} issues: https://github.com/nirholas/three.ws/issues`)}+`;+}++export function parseArgs(argv) {+ const args = { _: [], flags: {} };+ for (let i = 0; i < argv.length; i++) {+ const tok = argv[i];+ if (tok === '--no-color') {+ args.flags['no-color'] = true;+ } else if (tok.startsWith('--')) {+ const key = tok.slice(2);+ const next = argv[i + 1];+ if (next === undefined || next.startsWith('-')) {+ args.flags[key] = true;+ } else {+ args.flags[key] = next;+ i++;+ }+ } else if (tok.startsWith('-') && tok.length > 1) {+ args.flags[tok.slice(1)] = true;+ } else {+ args._.push(tok);+ }+ }+ return args;+}++/** Closest command name within edit distance 2, for "did you mean" hints. */+function suggestCommand(input) {+ let best = null;+ let bestDist = Infinity;+ for (const name of Object.keys(COMMANDS)) {+ const d = levenshtein(input, name);+ if (d < bestDist) {+ bestDist = d;+ best = name;+ }+ }+ return bestDist <= 2 ? best : null;+}++function levenshtein(a, b) {+ const m = a.length;+ const n = b.length;+ const row = Array.from({ length: n + 1 }, (_, i) => i);+ for (let i = 1; i <= m; i++) {+ let prev = row[0];+ row[0] = i;+ for (let j = 1; j <= n; j++) {+ const tmp = row[j];+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));+ prev = tmp;+ }+ }+ return row[n];+}++async function readVersion() {+ const { readFileSync } = await import('node:fs');+ const { fileURLToPath } = await import('node:url');+ const { dirname, resolve } = await import('node:path');+ const here = dirname(fileURLToPath(import.meta.url));+ return JSON.parse(readFileSync(resolve(here, '../package.json'), 'utf8')).version;+}++export async function main(argv) {+ const args = parseArgs(argv);++ if (args.flags.version || args.flags.V) {+ process.stdout.write(`${await readVersion()}\n`);+ return 0;+ }++ const [command, ...rest] = args._;+ const wantsHelp = args.flags.help || args.flags.h;++ if (!command) {+ process.stdout.write(topHelp());+ return wantsHelp ? 0 : 1;+ }++ const entry = COMMANDS[command];+ if (!entry) {+ failure(`unknown command: ${style.bold(command)}`);+ const guess = suggestCommand(command);+ if (guess) hint(`did you mean "${guess}"?`);+ hint('run "three-ws-assets --help" to see all commands');+ return 1;+ }++ if (wantsHelp) {+ process.stdout.write(`${entry.usage}\n`);+ return 0;+ }++ return entry.run({ positional: rest, flags: args.flags });+}++/** Turn low-level Node errors into a one-line, human message. */+function describeError(err) {+ switch (err?.code) {+ case 'ENOENT':+ return `file not found: ${err.path ?? err.message}`;+ case 'EACCES':+ return `permission denied: ${err.path ?? err.message}`;+ case 'EISDIR':+ return `expected a file but got a directory: ${err.path ?? err.message}`;+ default:+ return err?.message ?? String(err);+ }+}++const isDirectInvocation = (() => {+ if (typeof process === 'undefined' || !process.argv[1]) return false;+ const entry = process.argv[1];+ return entry.endsWith('cli.js') || entry.endsWith('three-ws-assets');+})();++if (isDirectInvocation) {+ main(process.argv.slice(2))+ .then((code) => process.exit(code ?? 0))+ .catch((err) => {+ failure(describeError(err));+ process.exit(1);+ });+}diff --git a/packages/assets-cli/src/commands/add.js b/packages/assets-cli/src/commands/add.jsnew file mode 100644index 000000000..22ccfcac5--- /dev/null+++ b/packages/assets-cli/src/commands/add.js@@ -0,0 +1,179 @@+import { createHash } from 'node:crypto';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';++import { resolveApi, fetchItem, downloadAsset } from '../api.js';+import { style, symbols, success, failure, hint, warn, heading } from '../style.js';++/**+ * Where a downloaded asset lands when `--dir` is not given.+ *+ * A project with a `public/` directory is almost always serving it at the web+ * root, so an asset written under it is reachable at `/three-ws/<file>` with no+ * build config. Without one, we do not guess a serving convention: the files go+ * in a plainly named directory and the snippet uses the path relative to the+ * project, which the caller then wires up themselves.+ */+export function defaultDir(cwd) {+ return existsSync(join(cwd, 'public'))+ ? join(cwd, 'public', 'three-ws')+ : join(cwd, 'three-ws-assets');+}++/**+ * The URL the snippet should reference for a file on disk.+ *+ * Returns `{ url, served }`. `served: false` means we could not prove the file+ * will be reachable at that path, and the caller warns instead of implying it+ * works.+ */+export function webPathFor(cwd, filePath) {+ const rel = relative(cwd, filePath);+ const segments = rel.split(sep);+ const publicIndex = segments.indexOf('public');+ if (publicIndex !== -1) {+ return { url: `/${segments.slice(publicIndex + 1).join('/')}`, served: true };+ }+ return { url: `./${segments.join('/')}`, served: false };+}++function extensionFor(item) {+ const fromUrl = extname(new URL(item.url).pathname);+ if (fromUrl) return fromUrl;+ return item.format === 'glb' ? '.glb' : '.json';+}++function sha256(buf) {+ return createHash('sha256').update(buf).digest('hex');+}++/**+ * Write `bytes` to `target`, refusing to clobber a file whose contents differ.+ *+ * A re-run that would write identical bytes is reported as unchanged rather+ * than as a write, so `add` is safe to put in a setup script. A file that was+ * edited after it was added is never silently replaced: that is someone's work.+ *+ * @returns {Promise<'written'|'unchanged'|'conflict'>}+ */+export async function writeAsset(target, bytes, { force = false } = {}) {+ if (existsSync(target)) {+ const existing = await readFile(target);+ if (sha256(existing) === sha256(bytes)) return 'unchanged';+ if (!force) return 'conflict';+ }+ await mkdir(resolve(target, '..'), { recursive: true });+ await writeFile(target, bytes);+ return 'written';+}++export async function add({ positional, flags }) {+ const id = positional[0];+ if (!id) {+ failure('add needs a catalog id');+ hint('find one with: three-ws-assets search <term>');+ return 1;+ }++ const cwd = process.cwd();+ const dirFlag = typeof flags.dir === 'string' ? flags.dir : null;+ const dir = dirFlag ? (isAbsolute(dirFlag) ? dirFlag : resolve(cwd, dirFlag)) : defaultDir(cwd);++ const origin = resolveApi(flags);+ let payload;+ try {+ payload = await fetchItem(origin, id);+ } catch (err) {+ failure(err.message);+ if (err.notFound) hint('search first: three-ws-assets search <term>');+ return 1;+ }++ const { item, snippets, frameworks, links } = payload;+ if (!item.url) {+ failure(`${item.id} has no downloadable file`);+ return 1;+ }++ const wanted = typeof flags.framework === 'string' ? flags.framework : null;+ if (wanted && !snippets[wanted]) {+ failure(`no "${wanted}" source for a ${item.kind}`);+ hint(`available: ${frameworks.join(', ')}`);+ return 1;+ }++ const targets = [{ label: 'asset', url: item.url, path: join(dir, `${item.name}${extensionFor(item)}`) }];+ if (flags.thumb && item.thumb) {+ targets.push({+ label: 'thumbnail',+ url: item.thumb,+ path: join(dir, basename(new URL(item.thumb).pathname)),+ });+ }++ const written = [];+ for (const target of targets) {+ const bytes = await downloadAsset(target.url);+ const outcome = await writeAsset(target.path, bytes, { force: Boolean(flags.force) });+ if (outcome === 'conflict') {+ failure(`${relative(cwd, target.path)} exists with different contents`);+ hint('pass --force to overwrite it');+ return 1;+ }+ written.push({ ...target, bytes: bytes.length, outcome });+ }++ // The snippet the API returned points at the CDN. Now that the bytes are on+ // disk, rewrite it to the local copy: that is the whole point of `add` as+ // opposed to `show`.+ const assetFile = written[0];+ const web = webPathFor(cwd, assetFile.path);+ const chosen = wanted || frameworks[0];+ const code = snippets[chosen].code.split(item.url).join(web.url);++ if (flags.json) {+ process.stdout.write(+ `${JSON.stringify(+ {+ ok: true,+ id: item.id,+ files: written.map((w) => ({+ path: relative(cwd, w.path),+ bytes: w.bytes,+ outcome: w.outcome,+ })),+ url: web.url,+ served: web.served,+ framework: chosen,+ snippet: code,+ license: item.license,+ },+ null,+ 2,+ )}\n`,+ );+ return 0;+ }++ for (const w of written) {+ const path = relative(cwd, w.path);+ if (w.outcome === 'unchanged') {+ process.stdout.write(`${style.dim(`${symbols.bullet} ${path} already up to date`)}\n`);+ } else {+ success(`${path} ${style.dim(`(${(w.bytes / 1024).toFixed(0)} KB ${w.label})`)}`);+ }+ }+ if (item.license) process.stdout.write(`${style.dim(`license: ${item.license}`)}\n`);+ if (!web.served) {+ warn(`${relative(cwd, dir)} is not under a public/ directory`);+ hint('the snippet uses a project-relative path; serve that directory or pass --dir');+ }++ process.stdout.write(`\n${heading(chosen)}\n${code}\n`);+ for (const note of snippets[chosen].notes || []) {+ process.stdout.write(`${style.dim(` ${symbols.bullet} ${note}`)}\n`);+ }+ if (links?.preview) process.stdout.write(`\n${style.dim(`preview: ${links.preview}`)}\n`);+ return 0;+}diff --git a/packages/assets-cli/src/commands/search.js b/packages/assets-cli/src/commands/search.jsnew file mode 100644index 000000000..1a536a23e--- /dev/null+++ b/packages/assets-cli/src/commands/search.js@@ -0,0 +1,78 @@+import { resolveApi, searchCatalog } from '../api.js';+import { style, symbols, failure, hint, heading } from '../style.js';++const KINDS = ['object', 'character', 'animation'];++function formatBytes(n) {+ if (!n) return '';+ const mb = n / 1024 / 1024;+ return mb >= 1 ? `${mb.toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;+}++function describe(item) {+ if (item.kind === 'animation') {+ const secs = item.duration_seconds ? `${item.duration_seconds.toFixed(1)}s` : 'clip';+ return `${secs}${item.loop ? ' loop' : ''}`;+ }+ return [formatBytes(item.bytes), item.license].filter(Boolean).join(', ');+}++export async function search({ positional, flags }) {+ const query = positional.join(' ').trim();+ const kind = typeof flags.kind === 'string' ? flags.kind : null;+ if (kind && !KINDS.includes(kind)) {+ failure(`--kind must be one of: ${KINDS.join(', ')}`);+ return 1;+ }+ const limit = flags.limit ? Number(flags.limit) : 12;+ if (!Number.isInteger(limit) || limit < 1 || limit > 50) {+ failure('--limit must be a whole number from 1 to 50');+ return 1;+ }++ const origin = resolveApi(flags);+ const result = await searchCatalog(origin, {+ q: query || undefined,+ kind: kind || undefined,+ category: typeof flags.category === 'string' ? flags.category : undefined,+ tag: typeof flags.tag === 'string' ? flags.tag : undefined,+ limit,+ offset: flags.offset ? Number(flags.offset) : undefined,+ });++ if (flags.json) {+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ return result.items.length ? 0 : 1;+ }++ if (!result.items.length) {+ failure(`nothing in the catalog matches ${query ? `"${query}"` : 'that filter'}`);+ hint(`the catalog holds ${result.total} items; try a broader term or drop --kind`);+ return 1;+ }++ if (result.relaxed) {+ process.stderr.write(+ `${style.yellow(symbols.warn)} nothing matches every word of "${query}"; showing partial matches, best first\n`,+ );+ }++ const width = Math.max(...result.items.map((i) => i.id.length));+ process.stdout.write(`${heading(`${result.matched} match${result.matched === 1 ? '' : 'es'}`)}\n`);+ for (const item of result.items) {+ const meta = describe(item);+ process.stdout.write(+ ` ${style.cyan(item.id.padEnd(width))} ${item.title}${meta ? style.dim(` (${meta})`) : ''}\n`,+ );+ }++ const cats = (result.facets?.categories || []).slice(0, 6).map((c) => c.value);+ if (cats.length) process.stdout.write(`\n${style.dim(`categories: ${cats.join(', ')}`)}\n`);+ if (result.next_offset != null) {+ process.stdout.write(`${style.dim(`more: --offset ${result.next_offset}`)}\n`);+ }+ process.stdout.write(+ `${style.dim(`${symbols.arrow} add one: three-ws-assets add ${result.items[0].id}`)}\n`,+ );+ return 0;+}diff --git a/packages/assets-cli/src/commands/show.js b/packages/assets-cli/src/commands/show.jsnew file mode 100644index 000000000..f36ef7647--- /dev/null+++ b/packages/assets-cli/src/commands/show.js@@ -0,0 +1,68 @@+import { resolveApi, fetchItem } from '../api.js';+import { style, symbols, failure, hint, heading } from '../style.js';++export async function show({ positional, flags }) {+ const id = positional[0];+ if (!id) {+ failure('show needs a catalog id');+ hint('find one with: three-ws-assets search <term>');+ return 1;+ }++ const origin = resolveApi(flags);+ let payload;+ try {+ payload = await fetchItem(origin, id);+ } catch (err) {+ failure(err.message);+ if (err.notFound) hint('search first: three-ws-assets search <term>');+ return 1;+ }++ if (flags.json) {+ process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);+ return 0;+ }++ const { item, links, related, frameworks, snippets } = payload;+ process.stdout.write(`${style.bold(item.title)} ${style.dim(item.id)}\n`);+ const facts = [+ item.kind === 'animation' ? 'motion clip' : item.kind === 'object' ? 'prop' : 'rigged character',+ item.license,+ item.kind === 'animation'+ ? item.duration_seconds && `${item.duration_seconds.toFixed(2)}s ${item.loop ? 'loop' : 'one-shot'}`+ : item.bytes && `${(item.bytes / 1024 / 1024).toFixed(1)} MB`,+ ].filter(Boolean);+ process.stdout.write(`${style.dim(facts.join(' · '))}\n`);+ if (item.tags?.length) process.stdout.write(`${style.dim(`tags: ${item.tags.join(', ')}`)}\n`);++ // A specific framework prints only its snippet, so the output pipes cleanly+ // into a file. With no --framework, the recommended one is shown and the rest+ // are named.+ const wanted = typeof flags.framework === 'string' ? flags.framework : null;+ if (wanted && !snippets[wanted]) {+ failure(`no "${wanted}" source for a ${item.kind}`);+ hint(`available: ${frameworks.join(', ')}`);+ return 1;+ }+ const chosen = wanted || frameworks[0];+ process.stdout.write(`\n${heading(chosen)}\n`);+ process.stdout.write(`${snippets[chosen].code}\n`);+ for (const note of snippets[chosen].notes || []) {+ process.stdout.write(`${style.dim(` ${symbols.bullet} ${note}`)}\n`);+ }++ if (!wanted) {+ const others = frameworks.filter((f) => f !== chosen);+ if (others.length) {+ process.stdout.write(`\n${style.dim(`other frameworks: ${others.join(', ')}`)}\n`);+ }+ if (links?.preview) process.stdout.write(`${style.dim(`preview: ${links.preview}`)}\n`);+ if (related?.length) {+ process.stdout.write(+ `${style.dim(`related: ${related.slice(0, 4).map((r) => r.id).join(', ')}`)}\n`,+ );+ }+ }+ return 0;+}diff --git a/packages/assets-cli/src/style.js b/packages/assets-cli/src/style.jsnew file mode 100644index 000000000..6f6496b84--- /dev/null+++ b/packages/assets-cli/src/style.js@@ -0,0 +1,78 @@+// Zero-dependency terminal styling for the three-ws-assets CLI.+//+// Decoration is applied only to human-facing framing (messages, headers, help).+// Machine payloads (`--json` output, embed snippets, file paths) are always+// emitted uncolored so they stay pipe- and paste-safe.+//+// Color is honored unless disabled by the NO_COLOR convention+// (https://no-color.org), a `--no-color` flag, or a non-TTY stdout, and is+// forced on by FORCE_COLOR.++const noColorEnv = process.env.NO_COLOR != null && process.env.NO_COLOR !== '';+const noColorFlag = process.argv.includes('--no-color');+const forceColor = ['1', '2', '3', 'true'].includes(process.env.FORCE_COLOR ?? '');++export const colorEnabled =+ !noColorFlag &&+ !noColorEnv &&+ (forceColor || Boolean(process.stdout.isTTY) || Boolean(process.stderr.isTTY));++const CODES = {+ bold: 1,+ dim: 2,+ red: 31,+ green: 32,+ yellow: 33,+ cyan: 36,+ gray: 90,+};++function paint(code, text) {+ if (!colorEnabled) return text;+ return `\x1b[${code}m${text}\x1b[0m`;+}++export const style = {+ bold: (t) => paint(CODES.bold, t),+ dim: (t) => paint(CODES.dim, t),+ red: (t) => paint(CODES.red, t),+ green: (t) => paint(CODES.green, t),+ yellow: (t) => paint(CODES.yellow, t),+ cyan: (t) => paint(CODES.cyan, t),+ gray: (t) => paint(CODES.gray, t),+};++// Glyphs degrade to ASCII when stdout is not a TTY (CI logs, pipes).+const unicode = Boolean(process.stdout.isTTY) || forceColor;+export const symbols = {+ tick: unicode ? '✔' : 'ok',+ cross: unicode ? '✖' : 'x',+ warn: unicode ? '⚠' : '!',+ arrow: unicode ? '›' : '>',+ bullet: unicode ? '•' : '-',+};++/** Success line to stdout (human framing only). */+export function success(message) {+ process.stdout.write(`${style.green(symbols.tick)} ${message}\n`);+}++/** Failure line to stderr. */+export function failure(message) {+ process.stderr.write(`${style.red(symbols.cross)} ${message}\n`);+}++/** Warning line to stderr. */+export function warn(message) {+ process.stderr.write(`${style.yellow(symbols.warn)} ${message}\n`);+}++/** Dim hint line to stderr, indented under a preceding message. */+export function hint(message) {+ process.stderr.write(` ${style.dim(message)}\n`);+}++/** Section header for human-readable stdout blocks. */+export function heading(text) {+ return style.dim(`${symbols.arrow} ${text}`);+}diff --git a/packages/assets-cli/test/cli.test.js b/packages/assets-cli/test/cli.test.jsnew file mode 100644index 000000000..3c610f9d2--- /dev/null+++ b/packages/assets-cli/test/cli.test.js@@ -0,0 +1,316 @@+// three-ws-assets CLI tests.+//+// A local HTTP server stands in for three.ws: it answers /api/catalog with the+// same response shape the real endpoint returns and serves asset bytes from a+// CDN-shaped path. Nothing here reaches the network, and every command runs+// through main() exactly as the shell invokes it.++import assert from 'node:assert/strict';+import http from 'node:http';+import { after, before, beforeEach, describe, it } from 'node:test';+import { mkdtemp, readFile, writeFile, mkdir } from 'node:fs/promises';+import { existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { main, parseArgs } from '../src/cli.js';+import { defaultDir, webPathFor, writeAsset } from '../src/commands/add.js';++const CHAIR_BYTES = Buffer.from('glTF-pretend-chair-bytes');+const THUMB_BYTES = Buffer.from('png-pretend-thumb');++function chair(origin) {+ return {+ id: 'object:wooden_chair',+ kind: 'object',+ name: 'wooden_chair',+ title: 'Wooden Chair',+ categories: ['furniture'],+ tags: ['wood', 'seating'],+ license: 'CC0',+ format: 'glb',+ url: `${origin}/cdn/wooden_chair.glb`,+ thumb: `${origin}/cdn/wooden_chair.png`,+ bytes: CHAIR_BYTES.length,+ };+}++function detail(origin) {+ const item = chair(origin);+ return {+ ok: true,+ item,+ links: { browse: 'https://three.ws/objects', preview: 'https://three.ws/app#model=x' },+ related: [{ id: 'object:bar_stool', title: 'Bar Stool' }],+ frameworks: ['model-viewer', 'three', 'agent-3d', 'react'],+ snippets: {+ 'model-viewer': {+ language: 'html',+ code: `<model-viewer src="${item.url}"></model-viewer>`,+ notes: ['This is the renderer the browse grids use.'],+ },+ three: { language: 'javascript', code: `loadAsync("${item.url}")`, notes: [] },+ 'agent-3d': { language: 'html', code: `<agent-3d body="${item.url}"></agent-3d>`, notes: [] },+ react: { language: 'jsx', code: `const url = "${item.url}";`, notes: [] },+ },+ };+}++let server;+let origin;+let cwd;+let out;+let err;++/** Run the CLI with stdout/stderr captured, returning { code, out, err }. */+async function run(...argv) {+ out = '';+ err = '';+ const realOut = process.stdout.write.bind(process.stdout);+ const realErr = process.stderr.write.bind(process.stderr);+ process.stdout.write = (chunk) => {+ out += chunk;+ return true;+ };+ process.stderr.write = (chunk) => {+ err += chunk;+ return true;+ };+ try {+ const code = await main([...argv, '--api', origin, '--no-color']);+ return { code, out, err };+ } finally {+ process.stdout.write = realOut;+ process.stderr.write = realErr;+ }+}++before(async () => {+ server = http.createServer((req, res) => {+ const url = new URL(req.url, 'http://x');+ if (url.pathname === '/cdn/wooden_chair.glb') {+ res.writeHead(200, { 'content-type': 'model/gltf-binary' }).end(CHAIR_BYTES);+ return;+ }+ if (url.pathname === '/cdn/wooden_chair.png') {+ res.writeHead(200, { 'content-type': 'image/png' }).end(THUMB_BYTES);+ return;+ }+ if (url.pathname !== '/api/catalog') {+ res.writeHead(404).end('{}');+ return;+ }+ const id = url.searchParams.get('id');+ if (id) {+ if (id !== 'object:wooden_chair') {+ res+ .writeHead(404, { 'content-type': 'application/json' })+ .end(JSON.stringify({ error: 'not_found', message: `no catalog item with id "${id}"` }));+ return;+ }+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(detail(origin)));+ return;+ }+ const q = url.searchParams.get('q') || '';+ const matches = q.includes('nothing') ? [] : [chair(origin)];+ res.writeHead(200, { 'content-type': 'application/json' }).end(+ JSON.stringify({+ ok: true,+ items: matches,+ matched: matches.length,+ relaxed: q.includes('partial'),+ total: 3492,+ offset: 0,+ next_offset: matches.length ? 1 : null,+ facets: { kinds: { object: matches.length }, categories: [{ value: 'furniture', count: 1 }], tags: [] },+ }),+ );+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ origin = `http://127.0.0.1:${server.address().port}`;+});++after(() => server.close());++beforeEach(async () => {+ cwd = await mkdtemp(join(tmpdir(), 'three-ws-assets-'));+ process.chdir(cwd);+});++describe('argument parsing', () => {+ it('separates positionals from flags and value flags from booleans', () => {+ const args = parseArgs(['add', 'object:x', '--dir', 'assets', '--force', '--json']);+ assert.deepEqual(args._, ['add', 'object:x']);+ assert.equal(args.flags.dir, 'assets');+ assert.equal(args.flags.force, true);+ assert.equal(args.flags.json, true);+ });+});++describe('help and unknown commands', () => {+ it('prints help and exits non-zero when called with no command', async () => {+ const r = await run();+ assert.equal(r.code, 1);+ assert.match(r.out, /three-ws-assets <command>/);+ });++ it('exits 0 for an explicit --help', async () => {+ const r = await run('--help');+ assert.equal(r.code, 0);+ });++ it('suggests the closest command for a typo', async () => {+ const r = await run('serach', 'chair');+ assert.equal(r.code, 1);+ assert.match(r.err, /did you mean "search"/);+ });+});++describe('search', () => {+ it('lists ids and points at the next step', async () => {+ const r = await run('search', 'wooden', 'chair');+ assert.equal(r.code, 0);+ assert.match(r.out, /object:wooden_chair/);+ assert.match(r.out, /three-ws-assets add object:wooden_chair/);+ });++ it('exits non-zero and says what to try when nothing matches', async () => {+ const r = await run('search', 'nothing');+ assert.equal(r.code, 1);+ assert.match(r.err, /nothing in the catalog matches/);+ });++ it('warns when the catalog fell back to a partial match', async () => {+ const r = await run('search', 'partial', 'match');+ assert.equal(r.code, 0);+ assert.match(r.err, /nothing matches every word/);+ });++ it('rejects an unknown --kind before making a request', async () => {+ const r = await run('search', 'chair', '--kind', 'furniture');+ assert.equal(r.code, 1);+ assert.match(r.err, /--kind must be one of/);+ });++ it('emits raw JSON with --json', async () => {+ const r = await run('search', 'chair', '--json');+ assert.equal(JSON.parse(r.out).items[0].id, 'object:wooden_chair');+ });+});++describe('show', () => {+ it('prints the recommended framework and names the others', async () => {+ const r = await run('show', 'object:wooden_chair');+ assert.equal(r.code, 0);+ assert.match(r.out, /<model-viewer/);+ assert.match(r.out, /other frameworks: three, agent-3d, react/);+ });++ it('prints only the requested framework so the output pipes cleanly', async () => {+ const r = await run('show', 'object:wooden_chair', '--framework', 'three');+ assert.match(r.out, /loadAsync/);+ assert.doesNotMatch(r.out, /other frameworks/);+ });++ it('rejects a framework the item does not have', async () => {+ const r = await run('show', 'object:wooden_chair', '--framework', 'svelte');+ assert.equal(r.code, 1);+ assert.match(r.err, /available: model-viewer/);+ });++ it('explains an unknown id instead of throwing', async () => {+ const r = await run('show', 'object:missing');+ assert.equal(r.code, 1);+ assert.match(r.err, /no catalog item/);+ });+});++describe('add', () => {+ it('writes the asset under public/ and rewrites the snippet to the local path', async () => {+ await mkdir(join(cwd, 'public'), { recursive: true });+ const r = await run('add', 'object:wooden_chair');+ assert.equal(r.code, 0);+ const written = await readFile(join(cwd, 'public', 'three-ws', 'wooden_chair.glb'));+ assert.deepEqual(written, CHAIR_BYTES);+ assert.match(r.out, /src="\/three-ws\/wooden_chair\.glb"/);+ assert.doesNotMatch(r.out, /cdn\/wooden_chair\.glb"/);+ });++ it('falls back to a plain directory and warns that it is not served', async () => {+ const r = await run('add', 'object:wooden_chair');+ assert.equal(r.code, 0);+ assert.ok(existsSync(join(cwd, 'three-ws-assets', 'wooden_chair.glb')));+ assert.match(r.err, /not under a public\/ directory/);+ assert.match(r.out, /\.\/three-ws-assets\/wooden_chair\.glb/);+ });++ it('takes the thumbnail only when asked', async () => {+ await run('add', 'object:wooden_chair');+ assert.ok(!existsSync(join(cwd, 'three-ws-assets', 'wooden_chair.png')));+ await run('add', 'object:wooden_chair', '--thumb');+ assert.ok(existsSync(join(cwd, 'three-ws-assets', 'wooden_chair.png')));+ });++ it('reports an unchanged file on a re-run instead of rewriting it', async () => {+ await run('add', 'object:wooden_chair');+ const r = await run('add', 'object:wooden_chair');+ assert.equal(r.code, 0);+ assert.match(r.out, /already up to date/);+ });++ it('refuses to clobber an edited file, and obeys --force', async () => {+ await run('add', 'object:wooden_chair');+ const target = join(cwd, 'three-ws-assets', 'wooden_chair.glb');+ await writeFile(target, 'edited by hand');+ const refused = await run('add', 'object:wooden_chair');+ assert.equal(refused.code, 1);+ assert.match(refused.err, /exists with different contents/);+ assert.equal(await readFile(target, 'utf8'), 'edited by hand');++ const forced = await run('add', 'object:wooden_chair', '--force');+ assert.equal(forced.code, 0);+ assert.deepEqual(await readFile(target), CHAIR_BYTES);+ });++ it('honors --dir', async () => {+ await run('add', 'object:wooden_chair', '--dir', 'src/models');+ assert.ok(existsSync(join(cwd, 'src', 'models', 'wooden_chair.glb')));+ });++ it('reports written paths, the local url, and the snippet with --json', async () => {+ await mkdir(join(cwd, 'public'), { recursive: true });+ const r = await run('add', 'object:wooden_chair', '--json');+ const payload = JSON.parse(r.out);+ assert.equal(payload.files[0].path, join('public', 'three-ws', 'wooden_chair.glb'));+ assert.equal(payload.url, '/three-ws/wooden_chair.glb');+ assert.equal(payload.served, true);+ assert.match(payload.snippet, /\/three-ws\/wooden_chair\.glb/);+ });+});++describe('path helpers', () => {+ it('prefers public/three-ws when the project has a public directory', async () => {+ assert.equal(defaultDir(cwd), join(cwd, 'three-ws-assets'));+ await mkdir(join(cwd, 'public'), { recursive: true });+ assert.equal(defaultDir(cwd), join(cwd, 'public', 'three-ws'));+ });++ it('maps a path under public/ to a served root url', () => {+ assert.deepEqual(webPathFor('/proj', '/proj/public/three-ws/a.glb'), {+ url: '/three-ws/a.glb',+ served: true,+ });+ assert.deepEqual(webPathFor('/proj', '/proj/assets/a.glb'), {+ url: './assets/a.glb',+ served: false,+ });+ });++ it('creates missing parent directories on write', async () => {+ const target = join(cwd, 'deep', 'nested', 'a.glb');+ assert.equal(await writeAsset(target, CHAIR_BYTES), 'written');+ assert.equal(await writeAsset(target, CHAIR_BYTES), 'unchanged');+ assert.equal(await writeAsset(target, Buffer.from('other')), 'conflict');+ assert.equal(await writeAsset(target, Buffer.from('other'), { force: true }), 'written');+ });+});diff --git a/tests/api/catalog-endpoint.test.js b/tests/api/catalog-endpoint.test.jsnew file mode 100644index 000000000..b47d8b81e--- /dev/null+++ b/tests/api/catalog-endpoint.test.js@@ -0,0 +1,146 @@+// GET /api/catalog: the public asset-catalog endpoint.+//+// R2 is stubbed with manifests shaped like the published ones, so the suite+// exercises the real join, the real validation, and the real snippet payload+// without a network call. The endpoint is the CLI's only server dependency+// (@three-ws/assets), so its response shape is a contract, not an internal.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const MANIFESTS = {+ 'objects/library/manifest.json': {+ objects: [+ {+ name: 'wooden_chair',+ label: 'Wooden Chair',+ url: 'https://cdn.test/objects/wooden_chair.glb',+ thumb: 'https://cdn.test/objects/wooden_chair.png',+ bytes: 1048576,+ categories: ['furniture'],+ tags: ['wood', 'seating'],+ license: 'CC0',+ },+ ],+ },+ 'avatars/library/manifest.json': {+ avatars: [+ {+ name: 'abe',+ label: 'Abe',+ url: 'https://cdn.test/avatars/abe.glb',+ bytes: 35947032,+ source: 'mixamo',+ license: 'Mixamo',+ },+ ],+ },+ 'animations/library/manifest.json': { clips: [] },+ 'animations/library/generated/manifest.json': null,+};++vi.mock('../../api/_lib/r2.js', () => ({+ getObjectBuffer: vi.fn(async (key) => {+ const value = MANIFESTS[key];+ if (value == null) {+ const err = new Error('NoSuchKey');+ err.name = 'NoSuchKey';+ throw err;+ }+ return Buffer.from(JSON.stringify(value), 'utf8');+ }),+}));++vi.mock('../../api/_lib/rate-limit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ limits: { ...actual.limits, publicIp: async () => ({ success: true, limit: 240, remaining: 239, reset: Date.now() + 60_000 }) },+ };+});++const { resetCatalogCache } = await import('../../api/_lib/asset-catalog.js');+const handler = (await import('../../api/catalog.js')).default;++function invoke(url) {+ const req = { method: 'GET', url, headers: { host: 'three.ws' } };+ let status = 0;+ let body = null;+ const headers = {};+ const res = {+ setHeader: (k, v) => {+ headers[k.toLowerCase()] = v;+ },+ getHeader: (k) => headers[k.toLowerCase()],+ removeHeader: (k) => delete headers[k.toLowerCase()],+ writeHead(code, hdrs) {+ status = code;+ Object.assign(headers, hdrs || {});+ return this;+ },+ end(payload) {+ if (!status) status = 200;+ try {+ body = payload ? JSON.parse(payload) : null;+ } catch {+ body = payload;+ }+ return this;+ },+ set statusCode(v) {+ status = v;+ },+ get statusCode() {+ return status;+ },+ };+ return handler(req, res).then(() => ({ status, body, headers }));+}++beforeEach(() => resetCatalogCache());++describe('GET /api/catalog', () => {+ it('searches across every library', async () => {+ const { status, body } = await invoke('/api/catalog?q=chair');+ expect(status).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.items[0].id).toBe('object:wooden_chair');+ expect(body.total).toBe(2);+ });++ it('filters by kind', async () => {+ const { body } = await invoke('/api/catalog?kind=character');+ expect(body.items.map((i) => i.id)).toEqual(['character:abe']);+ });++ it('returns an item with links, related, frameworks, and every snippet', async () => {+ const { status, body } = await invoke('/api/catalog?id=object:wooden_chair');+ expect(status).toBe(200);+ expect(body.item.id).toBe('object:wooden_chair');+ expect(body.frameworks[0]).toBe('model-viewer');+ expect(Object.keys(body.snippets).sort()).toEqual(+ ['agent-3d', 'model-viewer', 'react', 'three'].sort(),+ );+ expect(body.snippets['model-viewer'].code).toContain(body.item.url);+ expect(body.links.browse).toBe('https://three.ws/objects');+ });++ it('404s an unknown id with a hint that names the next call', async () => {+ const { status, body } = await invoke('/api/catalog?id=object:nope');+ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ expect(body.hint).toMatch(/\/api\/catalog\?q=/);+ });++ it('rejects a bad kind, limit, and offset before reading storage', async () => {+ expect((await invoke('/api/catalog?kind=furniture')).status).toBe(400);+ expect((await invoke('/api/catalog?limit=0')).status).toBe(400);+ expect((await invoke('/api/catalog?limit=2.5')).status).toBe(400);+ expect((await invoke('/api/catalog?limit=999')).status).toBe(400);+ expect((await invoke('/api/catalog?offset=abc')).status).toBe(400);+ });++ it('is cacheable at the edge', async () => {+ const { headers } = await invoke('/api/catalog?q=chair');+ expect(headers['cache-control']).toContain('s-maxage=300');+ });+});