Public: anyone can read this; the crew can change it.

A .usdz or .usda scene lists its prims and the files packed beside them #16039

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16021-a-usdz-or-usda-scene-lists-its-prims-and → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16021-a-usdz-or-usda-scene-lists-its-prims-and was merged into main as c308776.

Review

Sign in to review this change.
15 files changed +698 −2
docs/features/file-kinds.md +1
@@ -26,6 +26,7 @@ The forge draws a file on its page when its kind is below and it is within the s
2626 - **Slides**, drawn up to 10 MB: `.pptx`
2727 - **Layered image**, drawn up to 20 MB: `.ora`
2828 - **EPUB book**, drawn up to 20 MB: `.epub`
29 - **USD scene**, drawn up to 20 MB: `.usdz`
2930 - **Font**, drawn up to 20 MB: `.ttf`, `.otf`, `.woff`, `.woff2`
3031 - **Photoshop**, drawn up to 4 GB: `.psd`
3132 - **GIMP**, drawn up to 20 MB: `.xcf`
docs/features/file-usd.md added +21
@@ -0,0 +1,21 @@
1 ---
2 topic: Files in the browser
3 row: A USD scene opens as its prims and packed files
4 ---
5 # USD scenes
6
7 A `.usda` text layer opens as its prim hierarchy: path, schema type and specifier
8 (`def`, `over`, `class`), with the layer's `defaultPrim`, `upAxis` and `metersPerUnit`.
9 A `.usdz` package opens as its packed files with sizes, and the prims of its default
10 layer (the package's first member). Code: `src/web/render/usd.ts`; kind `usd`, up to 20 MB.
11
12 - Nothing is followed: references, payloads and variant contents are not read; a prim
13 inside a variant is not listed. A binary layer (`PXR-USDC`) is named, not read.
14 - Bounded before any loop: 2,000 prims, 64 levels deep, a default layer inflated to 5 MB.
15 Past a bound the page says how many are not listed.
16 - A file over the cap, not a zip, or not opening on `#usda` keeps its source view, with one line why.
17 - The MCP `read_file` tool carries the same facts as `about: { kind: "usd", prims, types, says }`.
18 - The terminal opens the same facts: in a repository's files screen, open a `.usda` or `.usdz`
19 and the pane lists the layer's prims (indented by depth) and the packed files, 200 lines at
20 most. Code: `src/tui/ui/usd-note.ts`, wired in `src/tui/screens/workspace.ts`.
21 - Not done: `.usd` and `.usdc` (a `.usd` may be text or binary), a 3D preview.
scripts/kinds-guide.ts +1 −1
@@ -18,7 +18,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1818 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile",
2020 dockerfile: "Dockerfile", workflow: "GitHub workflow", compose: "Compose file", sql: "SQL", graphql: "GraphQL",
21 epub: "EPUB book", mbox: "Mailbox", bib: "Bibliography", proto: "Protocol Buffers", tfstate: "Terraform state", ini: "INI or properties", rtf: "Rich text", xml: "XML", text: "Other text", binary: "Other binary",
21 epub: "EPUB book", usd: "USD scene", mbox: "Mailbox", bib: "Bibliography", proto: "Protocol Buffers", tfstate: "Terraform state", ini: "INI or properties", rtf: "Rich text", xml: "XML", text: "Other text", binary: "Other binary",
2222 };
2323
2424 /** 1_000_000 as `1 MB`; 4_000_000_000 as `4 GB`; no cap as `none: download only`. */
src/http/mcp/tools/read_file.ts +5
@@ -4,6 +4,7 @@ import { isSafeRef, isSafeTreePath } from "../../../git/guard.ts";
44 import { blobForRender, listTree } from "../../../git/read.ts";
55 import { readStl, sayStl, stlSize, TOO_LARGE } from "../../../text/stl.ts";
66 import { checkConfig, configKind, type ConfigKind } from "../../../text/config_check.ts";
7 import { aboutUsd } from "../../../web/render/usd.ts";
78 import { aboutPcd } from "../../../web/render/pcd.ts";
89 import { describeMedia } from "../../../text/mp4.ts";
910 import { readXcf } from "../../../web/render/xcf-read.ts";
@@ -74,6 +75,10 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7475 const { format, triangles } = stl.value;
outdated

The checklist requires both doors: a USD scene opened on the page must be readable in the terminal too, as a screen in src/tui/ with its entry where AGENTS.md says. The pull has none, and a commit-message 'No door:' line is not an exemption. Add the screen (reuse readUsd) with a test, and say in docs/features/file-usd.md how to reach it.

7576 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7677 }
78 if (/\.(usda|usdz)$/i.test(path)) {
79 const usd = aboutUsd(path, body);
80 if (usd) return usd;
81 }
7782 if (/\.pcd$/i.test(path)) return aboutPcd(body);
7883 if (/\.xcf$/i.test(path)) return aboutXcf(body);
7984 if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text);
src/tui/screens/workspace.ts +8
@@ -135,6 +135,7 @@ import {
135135 import { fill, len, split } from "../ui/layout.ts";
136136 import { renderMarkdown, type Line } from "../ui/markdown.ts";
137137 import { archiveNote } from "../ui/archive-note.ts";
138 import { usdNote } from "../ui/usd-note.ts";
138139 import { holdsExif, readExif } from "../../web/render/exif.ts";
139140 import { psdNote } from "../ui/psd-note.ts";
140141 import { xcfNote } from "../ui/xcf-note.ts";
@@ -1592,6 +1593,7 @@ export function workspaceScreen(
15921593 else {
15931594 const known =
15941595 archiveNote(t.path, read.value.body, read.value.size, formatSize) ??
1596 usdNote(t.path, read.value.body, read.value.size, formatSize) ??
15951597 (kindByName(t.path) === "psd" ? psdNote(read.value.body, read.value.size, formatSize) : undefined) ??
15961598 (kindByName(t.path) === "xcf" ? xcfNote(read.value.body, read.value.size, formatSize) : undefined);
15971599 if (known !== undefined) note = known;
@@ -1606,6 +1608,12 @@ export function workspaceScreen(
16061608 }
16071609 } else {
16081610 raw = read.value.body; // .html included: source here, the page preview is web-only
1611 // A .usda opens as its prims, as the page has it; one that is no scene stays source.
1612 const scene = read.value.partial === true ? undefined : usdNote(t.path, read.value.body, read.value.size, formatSize);
1613 if (scene !== undefined) {
1614 note = scene;
1615 raw = null;
1616 }
16091617 const deps = depsView(t.path, read.value.body);
16101618 if (deps !== null && read.value.partial !== true) sheet = deps;
16111619 // A big JSON file arrives cut: its first level is drawn, as the page draws it.
src/tui/ui/usd-note.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * What the terminal says for a USD scene: the page's facts as lines, read through `readUsd` so
3 * both doors agree. A `.usda` gives its prims (path, type, specifier); a `.usdz` its default
4 * layer's prims and the files packed in it. `undefined` for any other file, and for a file that
5 * is no scene (it keeps its source view).
6 */
7
8 import { count } from "../../web/render/archive.ts";
9 import { printable } from "../../web/render/archive-view.ts";
10 import { DEPTH_CAP, PRIM_CAP, readUsd } from "../../web/render/usd.ts";
11
12 /** Lines kept in the pane; the page lists more. */
13 const SHOWN = 200;
14
15 export function usdNote(
16 path: string,
17 body: Uint8Array,
18 size: number,
19 /** The terminal's own size formatter, so units read as elsewhere. */
20 fmt: (bytes: number) => string,
21 ): string | undefined {
22 if (!/\.(usda|usdz)$/i.test(path)) return undefined;
23 const u = readUsd(path, body);
24 // A `.usda` that is no scene keeps its source; a package that is none says why.
25 if ("error" in u) return /usdz$/i.test(path) ? u.error : undefined;
26 const out: string[] = [`${u.format === "usdz" ? "USDZ" : "USDA"}, ${fmt(size)}`];
27 if (u.note !== "") out.push(u.note);
28 const layer = u.layer;
29 if (layer !== null) {
30 for (const [k, v] of Object.entries(layer.meta)) out.push(`${k}: ${printable(v)}`);
31 if (u.layerName !== "") out.push(`Default layer: ${printable(u.layerName)}`);
32 out.push("", `${count(layer.total)} prims`);
33 for (const p of layer.prims.slice(0, SHOWN))
34 out.push(`${" ".repeat(Math.min(p.depth, 8))}${printable(p.path.slice(p.path.lastIndexOf("/") + 1))} ${printable(p.type)} (${p.specifier})`);
35 const left = layer.total - Math.min(layer.prims.length, SHOWN);
36 if (left > 0)
37 out.push(`${count(left)} more not listed (${count(PRIM_CAP)} kept, to a depth of ${DEPTH_CAP}).`);
38 }
39 if (u.members.length > 0) {
40 out.push("", `${count(u.memberCount)} packed files`);
41 for (const m of u.members.slice(0, SHOWN)) out.push(`${printable(m.path)} ${fmt(m.size)}`);
42 if (u.memberCount > Math.min(u.members.length, SHOWN))
43 out.push(`${count(u.memberCount - Math.min(u.members.length, SHOWN))} more not listed.`);
44 }
45 return out.join("\n");
46 }
src/web/render/archive-view.ts +1 −1
@@ -12,7 +12,7 @@ import type { Rendered, RenderInput } from "./renderers.ts";
1212 const when = (d: Date | null): string => (d === null ? "" : d.toISOString().slice(0, 16).replace("T", " "));
1313
1414 /** Control and bidi-override characters would hide or reorder a name. */
15 const printable = (s: string): string =>
15 export const printable = (s: string): string =>
1616 s.replace(/[\u0000-\u001f\u007f-\u009f‪-‮⁦-⁩]/g, "�");
1717
1818 /** The folder part muted, the name plain; both escaped. */
src/web/render/kinds.ts +11
@@ -38,6 +38,7 @@ export type FileKind =
3838 | "slides"
3939 | "layers"
4040 | "epub"
41 | "usd"
4142 | "font"
4243 | "psd"
4344 | "xcf"
@@ -135,6 +136,9 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
135136 slides: 10 * MB,
136137 layers: 20 * MB,
137138 epub: 20 * MB,
139 // The page reads the whole body; a package's default layer is inflated under its own cap
140 // (`usd.ts`).
141 usd: 20 * MB,
138142 font: 20 * MB,
139143 // Read whole up to 5 MB; above that the header alone gives the facts.
140144 psd: 4_000 * MB,
@@ -446,6 +450,7 @@ const OFFICE: Readonly<Record<string, FileKind>> = {
446450 pptx: "slides",
447451 ora: "layers",
448452 epub: "epub",
453 usdz: "usd",
449454 };
450455 const isOffice = (path: string, head: Uint8Array): FileKind | undefined => {
451456 const kind = OFFICE[extension(path)];
@@ -460,6 +465,10 @@ const isDxfHead = (head: Uint8Array): boolean =>
460465 const isGerberHead = (head: Uint8Array): boolean =>
461466 /%(FS[LT]?[AI]?X\d\dY\d\d|MO(MM|IN))|^\uFEFF?\s*G04/.test(new TextDecoder().decode(head.subarray(0, 1024)));
462467
468 /** A USD text layer opens on `#usda` and a version. */
469 export const isUsdaHead = (head: Uint8Array): boolean =>
470 /^\uFEFF?#usda\s+\d/.test(new TextDecoder().decode(head.subarray(0, 32)));
471
463472 /** A STEP file opens on `ISO-10303-21;`; a `.step` or `.stp` without it stays text. */
464473 const isStepHead = (head: Uint8Array): boolean =>
465474 /^\uFEFF?\s*ISO-10303-21\s*;/.test(new TextDecoder().decode(head.subarray(0, 64)));
@@ -609,6 +618,8 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
609618 if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text";
610619 if (ext === "iges" || ext === "igs") return isIgesHead(head) ? "iges" : "text";
611620 if (ext === "gbr" || ext === "gtl" || ext === "gbl") return isGerberHead(head) ? "gerber" : "text";
621 // A USD text layer opens on `#usda`: a `.usda` that does not is only text.
622 if (ext === "usda") return isUsdaHead(head) ? "usd" : "text";
612623 // RTF opens on `{\rtf`: a `.rtf` whose bytes say otherwise is only text.
613624 if (ext === "rtf") return /^\uFEFF?\s*\{\\rtf/.test(new TextDecoder().decode(head.subarray(0, 16))) ? "rtf" : "text";
614625 return TEXTUAL[ext] ?? (isDxfHead(head) ? "dxf" : "text");
src/web/render/renderers.ts +2
@@ -71,6 +71,7 @@ import { sarif } from "./sarif.ts";
7171 import { sheet } from "./xlsx.ts";
7272 import { docx } from "./docx.ts";
7373 import { epub } from "./epub.ts";
74 import { usd } from "./usd.ts";
7475 import { pptx } from "./pptx.ts";
7576 import { ora } from "./ora.ts";
7677 import { sqlite } from "./sqlite.ts";
@@ -204,6 +205,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
204205 slides: pptx,
205206 layers: ora,
206207 epub,
208 usd,
207209 font,
208210 psd,
209211 xcf,
src/web/render/usd.ts added +286
@@ -0,0 +1,286 @@
1 /**
2 * A USD scene as facts: a `.usda` text layer as its prim hierarchy with types, a `.usdz` package as
3 * its member list with sizes and the prims of its default layer (the package's first member).
4 * Nothing is run or fetched; references, payloads and variants are not followed. One forward pass
5 * over bytes the page already holds under `RENDER_CAP.usd`, with the prims kept, the nesting
6 * followed and the members listed all capped before any of them is stored. A binary layer
7 * (`PXR-USDC`) is named, not read. Never throws: a file that cannot be read is `{ error }`.
8 */
9
10 import { escapeHtml, html, raw } from "../html.ts";
11 import { fileSize } from "../ui.ts";
12 import { count, listArchive, zipEntry, type Entry } from "./archive.ts";
13 import { printable } from "./archive-view.ts";
14 import { isUsdaHead } from "./kinds.ts";
15 import type { Rendered, RenderInput } from "./renderers.ts";
16
17 /** Prims kept for display, whatever the layer holds. */
18 export const PRIM_CAP = 2_000;
19 /** Nesting kept: a prim deeper than this is counted, not listed. */
20 export const DEPTH_CAP = 64;
21 /** The most of the default layer read out of a package, inflated. */
22 export const LAYER_CAP = 5 * 1024 * 1024;
23 /** Brace nesting tracked exactly; deeper is only counted. */
24 const STACK_CAP = 1_000;
25
26 export interface Prim {
27 readonly path: string;
28 readonly specifier: "def" | "over" | "class";
29 /** The schema type (`Mesh`), or "" when the prim names none. */
30 readonly type: string;
31 readonly depth: number;
32 }
33
34 export interface Layer {
35 readonly prims: readonly Prim[];
36 /** Every prim the layer declares at the top of its nesting, shown or not. */
37 readonly total: number;
38 readonly types: ReadonlyMap<string, number>;
39 readonly meta: Readonly<Record<string, string>>;
40 }
41
42 export interface Usd {
43 readonly format: "usda" | "usdz";
44 readonly layer: Layer | null;
45 /** The default layer's name inside a package. */
46 readonly layerName: string;
47 /** Why the layer's prims are not listed, or "". */
48 readonly note: string;
49 readonly members: readonly Entry[];
50 readonly memberCount: number;
51 readonly bytes: number;
52 }
53
54 export interface Unreadable {
55 readonly error: string;
56 }
57
58 const META = new Set(["defaultPrim", "upAxis", "metersPerUnit"]);
59 const HEADER = /\s*(?:([A-Za-z_][\w:]*)\s+)?"([A-Za-z_]\w*)"/y;
60 const VALUE = /\s*=\s*(?:"([^"\n]{0,200})"|([\w.+-]{1,40}))/y;
61 const WORD = /[A-Za-z_][\w:.]*/y;
62
63 const isSpace = (c: number): boolean => c === 32 || c === 10 || c === 13 || c === 9 || c === 44 || c === 59 || c === 61;
64
65 /** The prims of a `.usda` text, in file order. */
66 export function readUsda(text: string): Layer {
67 const prims: Prim[] = [];
68 const types = new Map<string, number>();
69 const meta: Record<string, string> = {};
70 // One entry per open brace: the prim's name, or null for any other brace (a dictionary, a
71 // variant).
72 const stack: (string | null)[] = [];
73 let deep = 0;
74 const names: string[] = [];
75 let paren = 0;
76 let pending: string | null = null;
77 let total = 0;
78 let noTriple = false;
79 let noSingle = false;
80 const n = text.length;
81 let i = 0;
82 while (i < n) {
83 const c = text.charCodeAt(i);
84 if (isSpace(c)) {
85 i++;
86 continue;
87 }
88 if (c === 35) {
89 const nl = text.indexOf("\n", i);
90 i = nl < 0 ? n : nl + 1;
91 continue;
92 }
93 // A token. Anything but `(` or `{` between a prim's header and its body ends the header.
94 if (pending !== null && paren === 0 && c !== 40 && c !== 123) pending = null;
95 if (c === 34 || c === 39) {
96 const q = text.startsWith(text.slice(i, i + 1).repeat(3), i);
97 const close = q ? text.slice(i, i + 1).repeat(3) : text[i]!;
98 let j = i + (q ? 3 : 1);
99 while (j < n) {
100 const d = text.charCodeAt(j);
101 if (d === 92) j += 2;
102 else if (text.startsWith(close, j)) break;
103 else if (!q && d === 10) break;
104 else j++;
105 }
outdated

HIGH (denial of service): an unterminated @@@ makes indexOf(close) scan to the end of the file, then i only advances to the next newline. A 20 MB file of repeated @@@\n lines is millions of full scans, so the render pins the process. Fix: remember when a close was not found (noClose) and skip the rest of the file, or advance i past the whole opener when no close exists; add a test with a large @@@\n repeat that must finish fast.

106 i = Math.min(n, j + close.length);
107 } else if (c === 64) {
108 const close = text.startsWith("@@@", i) ? "@@@" : "@";
109 // A close that was not found once is not there further on either: never scan to the end
110 // twice.
111 const gone = close === "@@@" ? noTriple : noSingle;
112 const end = gone ? -1 : text.indexOf(close, i + close.length);
113 if (end < 0) {
114 if (close === "@@@") noTriple = true;
115 else noSingle = true;
116 }
117 const nl = text.indexOf("\n", i);
118 i = end < 0 || (close === "@" && nl >= 0 && nl < end) ? (nl < 0 ? n : nl + 1) : end + close.length;
119 } else if (c === 123) {
120 if (stack.length >= STACK_CAP) deep++;
121 else {
122 stack.push(pending !== null && paren === 0 ? pending : null);
123 if (pending !== null && paren === 0) names.push(pending);
124 }
125 if (paren === 0) pending = null;
126 i++;
127 } else if (c === 125) {
128 if (deep > 0) deep--;
129 else if (stack.length > 0 && stack.pop() !== null) names.pop();
130 i++;
131 } else if (c === 40 || c === 91) {
132 paren++;
133 i++;
134 } else if (c === 41 || c === 93) {
135 if (paren > 0) paren--;
136 i++;
137 } else if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95) {
138 WORD.lastIndex = i;
139 const word = WORD.exec(text)![0];
140 i += word.length;
141 const top = stack.length === 0 ? null : stack[stack.length - 1];
142 const inPrimBody = deep === 0 && (stack.length === 0 || top !== null);
143 if (paren === 0 && inPrimBody && (word === "def" || word === "over" || word === "class")) {
144 HEADER.lastIndex = i;
145 const h = HEADER.exec(text);
146 if (h !== null) {
147 i = HEADER.lastIndex;
148 total++;
149 const type = h[1] ?? "";
150 types.set(type === "" ? "(untyped)" : type, (types.get(type === "" ? "(untyped)" : type) ?? 0) + 1);
151 if (prims.length < PRIM_CAP && names.length < DEPTH_CAP)
152 prims.push({ path: `/${[...names, h[2]!].join("/")}`, specifier: word, type, depth: names.length });
153 pending = h[2]!;
154 }
155 } else if (stack.length === 0 && paren === 1 && META.has(word) && prims.length === 0 && total === 0) {
156 VALUE.lastIndex = i;
157 const v = VALUE.exec(text);
158 if (v !== null) {
159 meta[word] = v[1] ?? v[2] ?? "";
160 i = VALUE.lastIndex;
161 }
162 }
163 } else i++;
164 }
165 return { prims, total, types, meta };
166 }
167
168 /** The name of the first member of a zip: where a package keeps its default layer. */
169 function firstMember(body: Uint8Array): string | null {
170 if (body.length < 30) return null;
171 const v = new DataView(body.buffer, body.byteOffset, body.byteLength);
172 if (v.getUint32(0, true) !== 0x04034b50) return null;
173 const len = v.getUint16(26, true);
174 if (len === 0 || 30 + len > body.length) return null;
175 return new TextDecoder().decode(body.subarray(30, 30 + len));
176 }
177
178 const isZip = (b: Uint8Array): boolean => b[0] === 0x50 && b[1] === 0x4b && b[2] === 3 && b[3] === 4;
179
180 /** The facts of a `.usda` or `.usdz`, or one sentence on why they cannot be read. */
181 export function readUsd(path: string, body: Uint8Array): Usd | Unreadable {
182 const none = { members: [], memberCount: 0, bytes: 0 } as const;
183 if (/\.usdz$/i.test(path)) {
184 if (!isZip(body)) return { error: "This file is not a zip package, so its scene cannot be read." };
185 const listed = listArchive(body);
186 if ("error" in listed) return { error: listed.error };
187 const members = listed.entries.filter((e) => !e.dir);
188 const name = firstMember(body) ?? "";
189 let layer: Layer | null = null;
190 let note = "";
191 if (name === "") note = "The package's first member could not be read, so its default layer is not listed.";
192 else if (!/\.(usda?|usdc)$/i.test(name)) note = "The package's first member is not a USD layer.";
193 else {
194 const bytes = zipEntry(body, name, LAYER_CAP);
195 if (bytes === null) note = `The default layer ${printable(name)} is too large, packed oddly or damaged, so its prims are not listed.`;
196 else if (isUsdaHead(bytes)) layer = readUsda(new TextDecoder().decode(bytes));
197 else note = `The default layer ${printable(name)} is binary (USDC), so its prims are not listed.`;
198 }
199 return { format: "usdz", layer, layerName: name, note, members, memberCount: listed.count, bytes: listed.bytes };
200 }
201 if (!isUsdaHead(body)) return { error: "This file does not open on #usda, so it is shown as source." };
202 return { format: "usda", layer: readUsda(new TextDecoder().decode(body)), layerName: "", note: "", ...none };
203 }
204
205 const typesLine = (layer: Layer): string =>
206 [...layer.types]
207 .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
208 .slice(0, 8)
209 .map(([t, k]) => `${t} ${count(k)}`)
210 .join(" · ");
211
212 /** The facts as the MCP `read_file` tool words them. */
213 export function aboutUsd(path: string, body: Uint8Array): Record<string, unknown> | undefined {
214 const usd = readUsd(path, body);
215 if ("error" in usd) return { kind: "usd", says: usd.error };
216 const layer = usd.layer;
217 const says =
218 layer === null
219 ? `USDZ, ${count(usd.memberCount)} members. ${usd.note}`
220 : `${usd.format === "usdz" ? "USDZ default layer" : "USDA"}, ${count(layer.total)} prims${layer.total > 0 ? ` (${typesLine(layer)})` : ""}`;
221 return {
222 kind: "usd",
223 format: usd.format,
224 ...(usd.format === "usdz" ? { members: usd.memberCount, layer: usd.layerName } : {}),
225 ...(layer === null
226 ? {}
227 : {
228 prims: layer.total,
229 types: Object.fromEntries(layer.types),
230 ...layer.meta,
231 paths: layer.prims.slice(0, 20).map((p) => `${p.specifier} ${p.type} ${p.path}`.replace(" ", " ")),
232 }),
233 says,
234 };
235 }
236
237 const row = (k: string, v: string): string => `<tr><th scope="row">${k}</th><td>${escapeHtml(printable(v))}</td></tr>`;
238
239 export function usd(input: RenderInput): Rendered {
240 const u = readUsd(input.path, input.body);
241 if ("error" in u) return { content: html``, lines: 0, fallback: u.error };
242 const layer = u.layer;
243 const facts =
244 (layer === null ? "" : Object.entries(layer.meta).map(([k, v]) => row(k, v)).join("")) +
245 (layer === null || layer.total === 0 ? "" : row("Prims", `${count(layer.total)} (${typesLine(layer)})`)) +
246 (u.layerName === "" ? "" : row("Default layer", u.layerName));
247 const primRows =
248 layer === null
249 ? ""
250 : layer.prims
251 .map((p) => {
252 const path = printable(p.path);
253 const cut = path.lastIndexOf("/") + 1;
254 return `<tr><td><span class="muted">${escapeHtml(path.slice(0, cut))}</span>${escapeHtml(path.slice(cut))}</td><td>${escapeHtml(printable(p.type))}</td><td class="muted">${p.specifier}</td></tr>`;
255 })
256 .join("");
257 const left = layer === null ? 0 : layer.total - layer.prims.length;
258 const primCut =
259 left > 0
260 ? `<p class="muted small">${count(left)} more ${left === 1 ? "prim is" : "prims are"} not listed (the page shows the first ${count(PRIM_CAP)}, to a depth of ${DEPTH_CAP}).</p>`
261 : "";
262 const memberRows = u.members
263 .map((e) => {
264 const path = printable(e.path);
265 const cut = path.lastIndexOf("/") + 1;
266 return `<tr><td><span class="muted">${escapeHtml(path.slice(0, cut))}</span>${escapeHtml(path.slice(cut))}</td><td class="num">${fileSize(e.size)}</td></tr>`;
267 })
268 .join("");
269 const memberCut =
270 u.memberCount > u.members.length
271 ? `<p class="muted small">${count(u.memberCount - u.members.length)} more members are not listed.</p>`
272 : "";
273 const label = printable(input.path.slice(input.path.lastIndexOf("/") + 1));
274 const content = html`${raw(u.note === "" ? "" : `<p class="muted small">${escapeHtml(u.note)}</p>`)}
275 ${raw(facts === "" ? "" : `<table class="table" data-dense aria-label="About ${escapeHtml(label)}"><tbody>${facts}</tbody></table>`)}
276 ${raw(primRows === "" ? "" : `<table class="table" data-dense aria-label="Prims of ${escapeHtml(label)}"><thead><tr><th scope="col">Prim</th><th scope="col">Type</th><th scope="col">Specifier</th></tr></thead><tbody>${primRows}</tbody></table>`)}
277 ${raw(primCut)}
278 ${raw(layer !== null && layer.total === 0 ? '<p class="muted small">This layer declares no prims.</p>' : "")}
279 ${raw(memberRows === "" ? "" : `<h3>Packed files</h3><table class="table" data-dense aria-label="Files packed in ${escapeHtml(label)}"><thead><tr><th scope="col">Path</th><th scope="col" class="num">Size</th></tr></thead><tbody>${memberRows}</tbody></table>`)}
280 ${raw(memberCut)}`;
281 const summary =
282 u.format === "usdz"
283 ? `${fileSize(input.size)} · USDZ · ${count(u.memberCount)} files`
284 : `${fileSize(input.size)} · USDA · ${count(layer?.total ?? 0)} prims`;
285 return { content, lines: 0, summary };
286 }
test/fuzz-renderers.test.ts +24
@@ -32,6 +32,25 @@ function igesFile(): string {
3232 ].join("\n") + "\n";
3333 }
3434
35 /**
36 * A small USD layer: hostile text in a value, a prim name no identifier allows, a `javascript:`
37 * one.
38 */
39 const USDA = [
40 "#usda 1.0",
41 "(",
42 ' defaultPrim = "World<b>"',
43 ' upAxis = "Y"',
44 ")",
45 'def Xform "World" (kind = "component")',
46 "{",
47 ' def Mesh "Cube" {}',
48 ' def "<img src=x onerror=alert(1)>" {}',
49 ' over "Lamp" { float3 xformOp:translate = (0, 1, 2) }',
50 "}",
51 "",
52 ].join("\n");
53
3554 /**
3655 * A small valid GIMP file as text, every byte below 0x80 so it survives the fuzzer's round trip.
3756 */
@@ -347,6 +366,11 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
347366 path: "cube.obj",
348367 files: ["# <b>cube</b>\no Cube\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvn 0 0 1\nf 1 2 3\n"],
349368 },
369 usda: { path: "scene.usda", files: [USDA] },
370 usdz: {
371 path: "scene.usdz",
372 files: [storedZip({ "scene.usda": USDA, "tex/<b>.png": "x" })],
373 },
350374 epub: {
351375 path: "book.epub",
352376 files: [
test/render-kinds.test.ts +2
@@ -79,6 +79,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
7979 pptx: [of(0x50, 0x4b, 3, 4, 0), "slides", "application/octet-stream"],
8080 ora: [of(0x50, 0x4b, 3, 4, 0), "layers", "application/octet-stream"],
8181 epub: [of(0x50, 0x4b, 3, 4, 0), "epub", "application/octet-stream"],
82 usdz: [of(0x50, 0x4b, 3, 4, 0), "usd", "application/octet-stream"],
83 usda: [enc("#usda 1.0\n"), "usd", "application/octet-stream"],
8284 ipynb: [enc("{}"), "notebook", "application/octet-stream"],
8385 md: [enc("# a\n"), "markdown", "application/octet-stream"],
8486 markdown: [enc("# a\n"), "markdown", "application/octet-stream"],
test/render-usd.test.ts added +152
@@ -0,0 +1,152 @@
1 /** .usda and .usdz as facts: registry, reader, page, the MCP door, and the hostile cases. */
2 import { describe, expect, test } from "bun:test";
3 import { zip } from "./helpers/zip.ts";
4 import { fileKind, mediaType, RENDER_CAP } from "../src/web/render/kinds.ts";
5 import { RENDERERS, plainReason, rendererFor } from "../src/web/render/renderers.ts";
6 import { aboutUsd, DEPTH_CAP, PRIM_CAP, readUsd, readUsda, usd } from "../src/web/render/usd.ts";
7
8 const enc = (s: string) => new TextEncoder().encode(s);
9 const draw = (path: string, body: Uint8Array) => usd({ path, size: body.length, body, media: "/m", download: "/d" });
10
11 const SCENE = `#usda 1.0
12 (
13 defaultPrim = "World"
14 metersPerUnit = 0.01
15 upAxis = "Y"
16 )
17 def Xform "World" (
18 kind = "assembly"
19 customData = { dictionary d = { string x = "def Fake \\"Nope\\" {" } }
20 )
21 {
22 # def Comment "Hidden" {
23 def Mesh "Cube"
24 {
25 float3[] extent = [(-1, -1, -1), (1, 1, 1)]
26 string note = "def Ghost \\"g\\" {"
27 }
28 over "Tweak" { }
29 class Material "Shared" { }
30 variantSet "v" = { "a" { def Sphere "InVariant" { } } }
31 }
32 def "Loose" { }
33 `;
34
35 describe("usd", () => {
36 test("is its own kind, named by extension and first bytes, and registered", () => {
37 expect(fileKind("a.usda", enc("#usda 1.0\n"))).toBe("usd");
38 expect(fileKind("a.usda", enc("just text"))).toBe("text");
39 const pk = new Uint8Array([0x50, 0x4b, 3, 4, 0]);
40 expect(fileKind("a.usdz", pk)).toBe("usd");
41 expect(fileKind("a.usdz", enc("plain"))).toBe("text");
42 expect(mediaType("a.usdz", pk)).toBe("application/octet-stream");
43 expect(RENDERERS.usd).toBe(usd);
44 expect(rendererFor("a.usda", { kind: "text", body: enc(SCENE), size: SCENE.length })?.render).toBe(usd);
45 });
46
47 test("the hierarchy, with types and specifiers, and no prim from a string, comment, dictionary or variant", () => {
48 const l = readUsda(SCENE);
49 expect(l.prims.map((p) => `${p.specifier} ${p.type} ${p.path}`)).toEqual([
50 "def Xform /World",
51 "def Mesh /World/Cube",
52 "over /World/Tweak",
53 "class Material /World/Shared",
54 "def /Loose",
55 ]);
56 expect(l.total).toBe(5);
57 expect(l.meta).toEqual({ defaultPrim: "World", metersPerUnit: "0.01", upAxis: "Y" });
58 });
59
60 test("a usdz lists its members and the prims of its first member", () => {
61 const body = zip({ "scene.usda": SCENE, "tex/wood.png": "pngbytes" });
62 const u = readUsd("a.usdz", body);
63 if ("error" in u) throw new Error(u.error);
64 expect(u.layerName).toBe("scene.usda");
65 expect(u.layer?.total).toBe(5);
66 expect(u.members.map((m) => m.path)).toEqual(["scene.usda", "tex/wood.png"]);
67 const page = String(draw("a.usdz", body).content);
68 expect(page).toContain("/World/");
69 expect(page).toContain("wood.png");
70 expect(page).toContain("Packed files");
71 });
72
73 test("a usdz whose layer is binary says so and still lists its members", () => {
74 const u = readUsd("a.usdz", zip({ "scene.usdc": "PXR-USDC....", "a.png": "x" }));
75 if ("error" in u) throw new Error(u.error);
76 expect(u.layer).toBeNull();
77 expect(u.note).toContain("binary");
78 expect(u.members.length).toBe(2);
79 });
80
81 test("every value from the file is escaped", () => {
82 const evil = zip({ "<script>alert(1)</script>.usda": SCENE.replace('"Cube"', '"Cube"').replace("def Mesh", "def Mesh<b>"), "<img src=x onerror=1>.png": "x" });
83 const page = String(draw("<i>.usdz", evil).content) + String(draw("a.usda", enc(SCENE.replace('"World"', '"World<script>"'))).content);
84 expect(page).not.toContain("<script>");
85 expect(page).not.toContain("<img");
86 expect(page).not.toContain("<b>");
87 expect(page).toContain("&lt;script&gt;");
88 });
89
90 test("a hostile layer is bounded: prims, depth and braces", () => {
91 const many = "#usda 1.0\n" + 'def Xform "a" {}\n'.repeat(PRIM_CAP + 500);
92 const l = readUsda(many);
93 expect(l.prims.length).toBe(PRIM_CAP);
94 expect(l.total).toBe(PRIM_CAP + 500);
95 expect(String(draw("a.usda", enc(many)).content)).toContain("more prims are not listed");
96 const nest = "#usda 1.0\n" + 'def Xform "n" {'.repeat(5_000) + "}".repeat(5_000);
97 const d = readUsda(nest);
98 expect(d.total).toBeGreaterThan(DEPTH_CAP);
99 expect(d.prims.every((p) => p.depth < DEPTH_CAP)).toBe(true);
100 expect(readUsda("#usda 1.0\n" + "{".repeat(100_000) + "}".repeat(200_000)).total).toBe(0);
101 });
102
103 test("a zip that lies about its lengths or a layer that inflates past its cap keeps the source view", () => {
104 const lie = zip({ "scene.usda": SCENE }, 0x7fffffff);
105 const u = readUsd("a.usdz", lie);
106 if ("error" in u) expect(u.error.length).toBeGreaterThan(0);
107 else expect(u.layer).toBeNull();
108 const bomb = readUsd("a.usdz", zip({ "scene.usda": "#usda 1.0\n" + " ".repeat(6 * 1024 * 1024) }));
109 if ("error" in bomb) throw new Error(bomb.error);
110 expect(bomb.layer).toBeNull();
111 expect(bomb.note).toContain("too large");
112 });
113
114 test("malformed input falls back to the source with one reason", () => {
115 expect(draw("a.usdz", enc("not a zip")).fallback).toContain("not a zip");
116 expect(draw("a.usdz", new Uint8Array([0x50, 0x4b, 3, 4, 1, 2, 3])).fallback).toBeString();
117 expect(draw("a.usda", enc("plain")).fallback).toContain("#usda");
118 });
119
120 test("over the render cap the page keeps the source and says why", () => {
121 const size = RENDER_CAP.usd + 1;
122 expect(plainReason("a.usda", { kind: "too_large", size, head: enc("#usda 1.0\n") })).toContain("too large");
123 });
124
125 test("the MCP file tool's about carries the same facts", () => {
126 const a = aboutUsd("a.usda", enc(SCENE))!;
127 expect(a["kind"]).toBe("usd");
128 expect(a["prims"]).toBe(5);
129 expect(a["types"]).toEqual({ Xform: 1, Mesh: 1, "(untyped)": 2, Material: 1 });
130 expect(String(a["says"])).toContain("5 prims");
131 const z = aboutUsd("a.usdz", zip({ "scene.usda": SCENE }))!;
132 expect(z["members"]).toBe(1);
133 expect(aboutUsd("a.usdz", enc("junk"))!["says"]).toBeString();
134 });
135 });
136
137 describe("asset paths cost one pass, whatever the file repeats", () => {
138 // Each shape is a worry a reviewer raised about `indexOf` for a close; none is quadratic,
139 // and this keeps it so (a rescan per line would take minutes at this size).
140 test.each([
141 ["an @@@ on every line", "@@@\n".repeat(2_000_000)],
142 ["an odd count of @@@ lines", "@@@\n".repeat(2_000_001)],
143 ["a lone @ on every line", "@\n".repeat(4_000_000)],
144 ["@@ on every line", "@@\n".repeat(2_500_000)],
145 ["an @@@ then a lone @, alternating", "@@@\n@\n".repeat(1_000_000)],
146 ])("%s", (_why, body) => {
147 const t0 = performance.now();
148 const layer = readUsda(`#usda 1.0\n${body}`);
149 expect(layer.total).toBe(0);
150 expect(performance.now() - t0).toBeLessThan(3_000);
151 });
152 });
test/tui-usd-screen.test.ts added +86
@@ -0,0 +1,86 @@
1 /** The terminal's door to a USD scene: the file view of a .usda and a .usdz in a repository. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App as Forge } from "../src/app.ts";
9 import { getUserByName } from "../src/core/users.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { headlessTerminal } from "../src/tui/term/terminal.ts";
12 import { seedAdmin } from "./helpers/admin.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14 import { settleApp, settleUntil } from "./helpers/tui.ts";
15 import { zip } from "./helpers/zip.ts";
16
17 quietLogs();
18
19 const LAYER = '#usda 1.0\n( defaultPrim = "World" )\ndef Xform "World"\n{\n def Mesh "Cube" {}\n}\n';
20 let dataDir = "";
21 let forge: Forge;
22
23 beforeAll(async () => {
24 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-usd-"));
25 forge = createApp({ dataDir, port: 0, url: "https://forge.test" });
26 const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
27 if (!a.ok) throw new Error("signup failed");
28 const made = await createRepo(forge, a.value, { name: "scenes", visibility: "public" });
29 if (!made.ok) throw new Error("repo failed");
30 await commitToBranch(forge, a.value, made.value, {
31 message: "scenes",
32 files: [
33 { path: "README.md", content: "# scenes\n" },
34 { path: "stage.usda", content: LAYER },
35 { path: "pack.usdz", content: zip({ "scene.usda": LAYER, "tex/wood.png": "x" }) },
36 ],
37 });
38 });
39
40 afterAll(async () => {
41 forge.close();
42 await rm(dataDir, { recursive: true, force: true });
43 });
44
45 async function open(file: string, waitFor: string): Promise<string> {
46 const user = getUserByName(forge.db, "alice");
47 if (user === undefined) throw new Error("no alice");
48 const { app } = createForgeApp(
49 forge,
50 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
51 { terminal: headlessTerminal(200, 40), exitHooks: false },
52 );
53 app.start();
54 const send = (key: string): void => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
55 try {
56 await settleApp(app);
57 send("/");
58 for (const ch of "scenes") send(ch);
59 send("enter");
60 send("enter");
61 await settleUntil(app, "alice/scenes");
62 send("t");
63 await settleApp(app);
64 for (const ch of file) send(ch);
65 send("enter");
66 await settleUntil(app, waitFor);
67 return app.screen.toText();
68 } finally {
69 app.stop();
70 }
71 }
72
73 test("a .usda opens as its prims", async () => {
74 const text = await open("stageusda", "Cube Mesh");
75 expect(text).toContain("USDA");
76 expect(text).toContain("defaultPrim: World");
77 expect(text).toContain("World Xform (def)");
78 });
79
80 test("a .usdz opens as its prims and its packed files", async () => {
81 const text = await open("packusdz", "tex/wood.png");
82 expect(text).toContain("USDZ");
83 expect(text).toContain("Default layer: scene.usda");
84 expect(text).toContain("2 packed files");
85 expect(text).not.toContain("Binary file");
86 });
test/tui-usd.test.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * A USD scene in the terminal: the file view lists its prims and packed files, as the page does.
3 */
4
5 import { describe, expect, test } from "bun:test";
6 import { usdNote } from "../src/tui/ui/usd-note.ts";
7 import { zip } from "./helpers/zip.ts";
8
9 const fmt = (n: number): string => `${n} B`;
10 const LAYER = `#usda 1.0
11 (
12 defaultPrim = "World"
13 upAxis = "Y"
14 )
15 def Xform "World"
16 {
17 def Mesh "Cube" {}
18 def Sphere "Ball" {}
19 }
20 `;
21 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
22
23 describe("usdNote", () => {
24 test("a .usda lists its prims with type and specifier, indented by depth", () => {
25 const note = usdNote("a.usda", enc(LAYER), LAYER.length, fmt) ?? "";
26 expect(note).toContain("USDA");
27 expect(note).toContain("defaultPrim: World");
28 expect(note).toContain("3 prims");
29 expect(note).toContain("World Xform (def)");
30 expect(note).toContain(" Cube Mesh (def)");
31 });
32
33 test("a .usdz lists its default layer's prims and its packed files", () => {
34 const body = zip({ "scene.usda": LAYER, "tex/wood.png": "x" });
35 const note = usdNote("a.usdz", body, body.length, fmt) ?? "";
36 expect(note).toContain("USDZ");
37 expect(note).toContain("Default layer: scene.usda");
38 expect(note).toContain("2 packed files");
39 expect(note).toContain("tex/wood.png");
40 });
41
42 test("a .usdz that is no zip says why; a .usda that is no scene and other files say nothing", () => {
43 expect(usdNote("a.usdz", enc("nope"), 4, fmt)).toContain("not a zip");
44 expect(usdNote("a.usda", enc("hello"), 5, fmt)).toBeUndefined();
45 expect(usdNote("a.txt", enc(LAYER), 5, fmt)).toBeUndefined();
46 });
47
48 test("a control character in a prim name is not drawn raw", () => {
49 const text = `#usda 1.0\ndef Xform "a" {}\n`;
50 expect(usdNote("a.usda", enc(text), text.length, fmt)).not.toMatch(/[\x00-\x08\x1b]/);
51 });
52 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs