Public: anyone can read this; the crew can change it.
An .stl can be exported as an ASCII STL from its page with one link, and the file round-trips #15886
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15856-an-stl-can-be-exported-as-an-ascii-stl-f → main 0 commits fork 2 threads · 2 unresolved
12 files
changed +392
−6
docs/features/file-stl.md +7
| @@ -42,6 +42,13 @@ The first paint carries the triangle count and box, read by the server, so they | ||
| 42 | 42 | STEP still shows its part card, not geometry (that needs a CAD kernel in WebAssembly, a later pull). |
| 43 | 43 | - The header and triangle count are checked against the byte length before any triangle is read. A truncated or |
| 44 | 44 | damaged file, one with no triangles or a coordinate that is not a number, is refused with a sentence and Download. |
| 45 | - **Download as ASCII / binary** (#15856): a link beside the facts saves the other form of the file, `part-ascii.stl` or | |
| 46 | `part-binary.stl`, from `GET /:owner/:name/stl/:ref/*path` (`stlConverted` in `src/web/pages/repo.ts`; same access as raw). | |
| 47 | Binary becomes `solid` text with every coordinate written as the shortest text that reads back to the same float32, so the | |
| 48 | round trip loses nothing; ASCII becomes binary with normals computed from the corners (right-hand rule). The 80-byte header | |
| 49 | and attribute words are not carried; the solid is named `forge`. Over 20 MB, unreadable or empty it answers 422 with a sentence. | |
| 50 | The terminal's file view (`src/tui/screens/workspace.ts`) prints the same address on an `As ASCII:` / `As binary:` line under | |
| 51 | `Download:`. The pure conversion is `src/web/render/stl_convert.ts`; pinned by `test/stl-convert.test.ts` and `test/tui-model3d.test.ts`. | |
| 45 | 52 | - Over 20 MB: refused with a sentence and never fetched; Download still streams it. |
| 46 | 53 | - The server reads the whole file, up to 20 MB, for the first paint, so the facts show with JavaScript off at any size the page opens. |
| 47 | 54 | - Try it: commit a `.stl` to a repository and open its file page. |
src/http/crawl.ts +1 −1
| @@ -66,7 +66,7 @@ const OTHER = "other"; | ||
| 66 | 66 | const CRAWLER = /bot\b|bot[/ ;)-]|crawl|spider|slurp|scrap|archiver|reflection|facebookexternalhit|bingpreview|ia_archiver/i; |
| 67 | 67 | |
| 68 | 68 | /** Paths whose answer costs a git walk or a diff: the ones robots.txt disallows. */ |
| 69 | export const DEEP_SEGMENTS = ["blob", "raw", "commits", "commit", "blame", "compare", "diff", "tree", "history"] as const; | |
| 69 | export const DEEP_SEGMENTS = ["blob", "raw", "stl", "commits", "commit", "blame", "compare", "diff", "tree", "history"] as const; | |
| 70 | 70 | const DEEP = new RegExp(`^/(?:origins/[^/]+/r/)?[^/]+/[^/]+/(?:${DEEP_SEGMENTS.join("|")})(?:/|$)`); |
| 71 | 71 | |
| 72 | 72 | /** Whether `pathname` is a page that costs a git walk or a diff. */ |
src/http/server.ts +2
| @@ -229,6 +229,7 @@ import { | ||
| 229 | 229 | repoHome, |
| 230 | 230 | repoSyncSubmit, |
| 231 | 231 | repoTakeSubmit, |
| 232 | stlConverted, | |
| 232 | 233 | treePage, |
| 233 | 234 | } from "../web/pages/repo.ts"; |
| 234 | 235 | import { mediaBlob } from "../web/pages/media.ts"; |
| @@ -1705,6 +1706,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1705 | 1706 | router.add("GET", "/:owner/:name/tree/:ref/*path", strangerCode(treePage)); |
| 1706 | 1707 | router.add("GET", "/:owner/:name/blob/:ref/*path", strangerCode(blobPage)); |
| 1707 | 1708 | router.add("GET", "/:owner/:name/raw/:ref/*path", strangerCode(rawBlob)); |
| 1709 | router.add("GET", "/:owner/:name/stl/:ref/*path", strangerCode(stlConverted)); | |
| 1708 | 1710 | router.add("GET", "/:owner/:name/archive/:file", strangerCode(sourceArchive)); |
| 1709 | 1711 | router.add("GET", "/:owner/:name/AGENTS.md", strangerCode(agentsMd)); |
| 1710 | 1712 | router.add("GET", "/:owner/:name/media/:ref/*path", strangerCode(mediaBlob)); |
src/tui/screens/workspace.ts +9 −1
| @@ -55,6 +55,8 @@ import { fileKind, isEnvExample, isJsonPath, kindByName, NO_BYTES, RENDER_CAP, s | ||
| 55 | 55 | import { tailOf, tailSentence } from "../../web/log_tail.ts"; |
| 56 | 56 | import { downloadHref } from "../../web/pages/media.ts"; |
| 57 | 57 | import { hexdump, HEX_BYTES } from "../../web/render/hexdump.ts"; |
| 58 | import { STL_LIMIT } from "../../web/render/stl.ts"; | |
| 59 | import { stlForm, stlHref } from "../../web/render/stl_convert.ts"; | |
| 58 | 60 | import { isModelPath, modelFacts } from "../../web/render/model-facts.ts"; |
| 59 | 61 | import { measureTyped, unitFor } from "../../web/render/measure.ts"; |
| 60 | 62 | import type { RepoFacts, RepoSource } from "../../view/source.ts"; |
| @@ -1525,7 +1527,13 @@ export function workspaceScreen( | ||
| 1525 | 1527 | const facts = modelFacts(t.path, bytes, size); |
| 1526 | 1528 | noteTitle = facts.title; |
| 1527 | 1529 | note = facts.facts; |
| 1528 | noteDetail = `${downloadAt(t.path)}\nThe file page turns and measures it; m here measures two points you type; editing a mesh is not built yet.`; | |
| 1530 | // A readable STL under the cap is offered in its other form, as the page's link is. | |
| 1531 | const web = mediaWeb(); | |
| 1532 | const other = | |
| 1533 | web !== undefined && bytes !== null && size <= STL_LIMIT && /\.stl$/i.test(t.path) && /triangle/.test(facts.facts) | |
| 1534 | ? `\nAs ${stlForm(bytes) === "binary" ? "ASCII" : "binary"}: ${stlHref(web, ref, t.path)}` | |
| 1535 | : ""; | |
| 1536 | noteDetail = `${downloadAt(t.path)}${other}\nThe file page turns and measures it; m here measures two points you type; editing a mesh is not built yet.`; | |
| 1529 | 1537 | }; |
| 1530 | 1538 | let raw: Uint8Array | null = null; |
| 1531 | 1539 | let cut = ""; |
src/web/asset.ts +1 −1
| @@ -207,7 +207,7 @@ export function spriteAsset(): FileAsset { | ||
| 207 | 207 | */ |
| 208 | 208 | export const NO_PREFETCH_PATHS = [ |
| 209 | 209 | "/assets/*", "/api/*", "/_plat/*", "/_measure*", "/_script-error", "/mcp*", "/oauth/*", "/sw.js", "/offline", |
| 210 | "/*/*/raw/*", "/*/*/media/*", "/*/*/archive/*", "/*/*/app/*/open", | |
| 210 | "/*/*/raw/*", "/*/*/stl/*", "/*/*/media/*", "/*/*/archive/*", "/*/*/app/*/open", | |
| 211 | 211 | "/logout*", "/signout*", "/sign-out*", "/signin*", "/sign-in*", "/login*", |
| 212 | 212 | "/claim*", "/welcome*", "/first-admin*", "/verify*", "/go/*", "/-/*", "/apps/open*", |
| 213 | 213 | "/settings/*", "/home/*", "/*/-/*", |
src/web/pages/media.ts +1 −1
| @@ -207,7 +207,7 @@ function busy(): Response { | ||
| 207 | 207 | } |
| 208 | 208 | |
| 209 | 209 | /** Saved under its own name, quoted so no byte of it can end the header. */ |
| 210 | function attachment(path: string): string { | |
| 210 | export function attachment(path: string): string { | |
| 211 | 211 | const name = path.slice(path.lastIndexOf("/") + 1); |
| 212 | 212 | const plain = name.replace(/[^\x20-\x7e]|["\\]/g, "_"); |
| 213 | 213 | return `attachment; filename="${plain}"; filename*=UTF-8''${encodeURIComponent(name)}`; |
src/web/pages/repo.ts +54
| @@ -10,6 +10,10 @@ | ||
| 10 | 10 | |
| 11 | 11 | import { DELETING_SAYS } from "../../core/repo_deleting.ts"; |
| 12 | 12 | import { downloadHeaders } from "../../drop/store.ts"; |
| 13 | import type { BlobForRender } from "../../git/read.ts"; | |
| 14 | import { attachment } from "./media.ts"; | |
| 15 | import { convertedPath, convertStl } from "../render/stl_convert.ts"; | |
| 16 | import { STL_LIMIT, STL_TOO_BIG } from "../render/stl.ts"; | |
| 13 | 17 | import { WAVE_CAP } from "../render/waveform.ts"; |
| 14 | 18 | import { repoLine } from "../describe.ts"; |
| 15 | 19 | import { recordLook } from "../../flow/valve_store.ts"; |
| @@ -2152,4 +2156,54 @@ export async function rawBlob(ctx: Ctx): Promise<Response> { | ||
| 2152 | 2156 | }); |
| 2153 | 2157 | } |
| 2154 | 2158 | |
| 2159 | /** | |
| 2160 | * GET /:owner/:name/stl/:ref/*path — an .stl in its other form: binary as | |
| 2161 | * ASCII `solid` text, ASCII as binary. Saved, never shown in place; over 20 MB | |
| 2162 | * it is refused, as the page does not offer it. | |
| 2163 | */ | |
| 2164 | export async function stlConverted(ctx: Ctx): Promise<Response> { | |
| 2165 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 2166 | const repo = loadRepo(ctx); | |
| 2167 | if (!repo) return notFoundPage(ctx); | |
| 2168 | const ref = ctx.params.ref ?? ""; | |
| 2169 | const path = ctx.params.path ?? ""; | |
| 2170 | if (!isSafeRef(ref) || !isSafeTreePath(path) || !/\.stl$/i.test(path)) return notFoundPage(ctx); | |
| 2171 | const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name); | |
| 2172 | const gitAt = performance.now(); | |
| 2173 | let blob: BlobForRender; | |
| 2174 | try { | |
| 2175 | blob = await blobForRender(dir, ref, path, 25_000_000); | |
| 2176 | } finally { | |
| 2177 | notePhase(ctx.request, "git", performance.now() - gitAt); | |
| 2178 | } | |
| 2179 | if (blob.kind === "missing") return notFoundPage(ctx); | |
| 2180 | return stlAnswer(ctx.request, blob, ref, path); | |
| 2181 | } | |
| 2182 | ||
| 2183 | /** The answer for a blob already read: refused with a sentence, or the other form to save. */ | |
| 2184 | export function stlAnswer(request: Request, blob: Exclude<BlobForRender, { kind: "missing" }>, ref: string, path: string): Response { | |
| 2185 | const refuse = (words: string): Response => | |
| 2186 | new Response(words, { | |
| 2187 | status: 422, | |
| 2188 | headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; sandbox", "cache-control": "private, max-age=0" }, | |
| 2189 | }); | |
| 2190 | if (blob.kind === "too_large" || blob.size > STL_LIMIT) return refuse(STL_TOO_BIG); | |
| 2191 | const made = convertStl(blob.body); | |
| 2192 | if ("error" in made) return refuse(made.error); | |
| 2193 | const pinned = FULL_OID.test(ref); | |
| 2194 | const etag = blob.oid ? `"${blob.oid}-${made.form}"` : undefined; | |
| 2195 | const headers: Record<string, string> = { | |
| 2196 | "content-type": made.form === "ascii" ? "model/stl; charset=utf-8" : "model/stl", | |
| 2197 | "content-disposition": attachment(convertedPath(path, made.form)), | |
| 2198 | "x-content-type-options": "nosniff", | |
| 2199 | "content-security-policy": "default-src 'none'; sandbox", | |
| 2200 | "cache-control": pinned && etag ? "private, max-age=31536000, immutable" : "private, max-age=0", | |
| 2201 | }; | |
| 2202 | if (etag) { | |
| 2203 | headers.etag = etag; | |
| 2204 | if (holds(request, etag)) return new Response(null, { status: 304, headers }); | |
| 2205 | } | |
| 2206 | return new Response(made.bytes, { headers }); | |
| 2207 | } | |
| 2208 | ||
| 2155 | 2209 | const FULL_OID = /^[0-9a-f]{40}$/; |
src/web/render/model3d.ts +14
| @@ -26,6 +26,7 @@ import { indexedRows } from "./mesh.ts"; | ||
| 26 | 26 | import { readDae } from "./collada.ts"; |
| 27 | 27 | import { readObj } from "./obj.ts"; |
| 28 | 28 | import { indexedMesh } from "./model-facts.ts"; |
| 29 | import { stlForm, stlHref } from "./stl_convert.ts"; | |
| 29 | 30 | import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts"; |
| 30 | 31 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 31 | 32 | |
| @@ -66,6 +67,18 @@ export function model3d(input: RenderInput): Rendered { | ||
| 66 | 67 | : stl !== undefined && "error" in stl |
| 67 | 68 | ? stl.error |
| 68 | 69 | : "Turning it needs JavaScript and WebGL; Download opens it elsewhere."; |
| 70 | // The other form of a readable STL under 20 MB: one link, never offered over the limit. | |
| 71 | const convertLink = | |
| 72 | stlFacts !== undefined && input.repo !== undefined | |
| 73 | ? btn(`Download as ${stlForm(input.body) === "binary" ? "ASCII" : "binary"}`, { | |
| 74 | href: stlHref(input.repo.base, input.repo.ref, input.path), | |
| 75 | size: "sm", | |
| 76 | variant: "outline", | |
| 77 | icon: "download", | |
| 78 | extra: "stl-convert", | |
| 79 | }) | |
| 80 | : html``; | |
| 81 | ||
| 69 | 82 | // A writer sees the edit form under a readable STL; one over what a commit holds is told why. |
| 70 | 83 | const editable = input.shift !== undefined && stlFacts !== undefined && format === "stl"; |
| 71 | 84 | const axisSelect = (name: string, label: string, none: string): Html => |
| @@ -114,6 +127,7 @@ export function model3d(input: RenderInput): Rendered { | ||
| 114 | 127 | </dl> |
| 115 | 128 | <span class="muted" data-stats aria-live="polite"></span> |
| 116 | 129 | <span class="spacer"></span> |
| 130 | ${convertLink} | |
| 117 | 131 | <span class="model3d-tools" data-tools hidden> |
| 118 | 132 | ${toggle("Wireframe", "wireframe")} ${toggle("Axes", "axes")} ${toggle("Measure", "measure")} |
| 119 | 133 | </span> |
src/web/render/stl_convert.ts added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | /** | |
| 2 | * An STL turned into the other form of STL: binary to ASCII `solid` text and | |
| 3 | * back. Pure: bytes in, bytes out, nothing thrown. The triangles are the same | |
| 4 | * on both sides; every coordinate is a float32 and is written with the | |
| 5 | * shortest text that reads back to that exact float32, so a round trip loses | |
| 6 | * nothing. A binary file's stored normals travel into the text; an ASCII | |
| 7 | * file's normals are not kept, so the binary written from it carries normals | |
| 8 | * computed from the corners (right-hand rule), which is what a slicer does | |
| 9 | * anyway. The 80-byte header and the attribute words are not carried. | |
| 10 | */ | |
| 11 | import { isBinaryStl, parseStl } from "./mesh.ts"; | |
| 12 | import { STL_LIMIT } from "./stl.ts"; | |
| 13 | ||
| 14 | export type StlForm = "ascii" | "binary"; | |
| 15 | ||
| 16 | export type Converted = { | |
| 17 | /** The form the bytes are in now. */ | |
| 18 | readonly form: StlForm; | |
| 19 | readonly bytes: Uint8Array; | |
| 20 | }; | |
| 21 | ||
| 22 | /** The form an STL's bytes are in. */ | |
| 23 | export const stlForm = (bytes: Uint8Array): StlForm => (isBinaryStl(bytes) ? "binary" : "ascii"); | |
| 24 | ||
| 25 | /** The other form of an STL, or the sentence that says why not. */ | |
| 26 | export function convertStl(bytes: Uint8Array): Converted | { readonly error: string } { | |
| 27 | if (bytes.length === 0) return { error: "This file is empty." }; | |
| 28 | if (bytes.length > STL_LIMIT) return { error: "This STL is over 20 MB, more than is converted here." }; | |
| 29 | try { | |
| 30 | const from = stlForm(bytes); | |
| 31 | const mesh = parseStl(bytes); | |
| 32 | if (mesh.triangles === 0) return { error: "This STL holds no triangles." }; | |
| 33 | for (const v of mesh.positions) if (!Number.isFinite(v)) return { error: "This STL holds a coordinate that is not a number." }; | |
| 34 | return from === "binary" ? { form: "ascii", bytes: toAscii(bytes, mesh.positions, mesh.triangles) } : { form: "binary", bytes: toBinary(mesh.positions, mesh.triangles) }; | |
| 35 | } catch (error) { | |
| 36 | return { error: `This is not a readable STL file${error instanceof Error && error.message !== "" ? `: ${error.message}` : ""}.` }; | |
| 37 | } | |
| 38 | } | |
| 39 | ||
| 40 | /** | |
| 41 | * The name the converted file is saved under: `a/part.stl` → `a/part-ascii.stl`; the caller | |
| 42 | * sanitises it. | |
| 43 | */ | |
| 44 | export function convertedPath(path: string, form: StlForm): string { | |
| 45 | return `${path.replace(/\.stl$/i, "")}-${form}.stl`; | |
| 46 | } | |
outdated
This comment says the solid is named from the file's own words, but the value is the constant "forge". Fix the comment, or carry the real name (sanitised) over. |
||
| 47 | ||
| 48 | /** | |
| 49 | * Where the other form is fetched from; every segment encoded, so a space, `#` or `?` stays in the | |
| 50 | * path. | |
| 51 | */ | |
| 52 | export const stlHref = (base: string, ref: string, path: string): string => | |
| 53 | `${base}/stl/${encodeURIComponent(ref)}/${path.split("/").map(encodeURIComponent).join("/")}`; | |
| 54 | ||
| 55 | /** | |
| 56 | * The solid's name in the text: the constant `forge`, not the file's own words (those could hold | |
| 57 | * anything). | |
| 58 | */ | |
| 59 | const SOLID = "forge"; | |
| 60 | ||
| 61 | function toAscii(binary: Uint8Array, positions: Float32Array, triangles: number): Uint8Array { | |
| 62 | const view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength); | |
| 63 | const encoder = new TextEncoder(); | |
| 64 | // One growing buffer, one string per facet: no million-piece join. | |
| 65 | let out = new Uint8Array(Math.min(triangles * 260 + 64, 1 << 24)); | |
| 66 | let at = 0; | |
| 67 | const put = (text: string): void => { | |
| 68 | const room = text.length * 3; | |
| 69 | if (at + room > out.length) { | |
| 70 | const bigger = new Uint8Array(Math.max(out.length * 2, at + room)); | |
| 71 | bigger.set(out.subarray(0, at)); | |
| 72 | out = bigger; | |
| 73 | } | |
| 74 | at += encoder.encodeInto(text, out.subarray(at)).written; | |
| 75 | }; | |
| 76 | put(`solid ${SOLID}\n`); | |
| 77 | for (let t = 0; t < triangles; t++) { | |
| 78 | const n = 84 + t * 50; | |
| 79 | let facet = `facet normal ${num(view.getFloat32(n, true))} ${num(view.getFloat32(n + 4, true))} ${num(view.getFloat32(n + 8, true))}\n outer loop\n`; | |
| 80 | for (let v = 0; v < 3; v++) { | |
| 81 | const p = t * 9 + v * 3; | |
| 82 | facet += ` vertex ${num(positions[p]!)} ${num(positions[p + 1]!)} ${num(positions[p + 2]!)}\n`; | |
| 83 | } | |
| 84 | put(`${facet} endloop\nendfacet\n`); | |
| 85 | } | |
| 86 | put(`endsolid ${SOLID}\n`); | |
| 87 | return out.slice(0, at); | |
| 88 | } | |
| 89 | ||
| 90 | /** `-0` is written `0`; the shortest text otherwise, never exponent-free surprises. */ | |
| 91 | const num = (v: number): string => (v === 0 ? "0" : String(v)); | |
| 92 | ||
| 93 | function toBinary(positions: Float32Array, triangles: number): Uint8Array { | |
| 94 | const out = new Uint8Array(84 + triangles * 50); | |
| 95 | const view = new DataView(out.buffer); | |
| 96 | out.set(new TextEncoder().encode(`binary STL from ${SOLID}`)); | |
| 97 | view.setUint32(80, triangles, true); | |
| 98 | for (let t = 0; t < triangles; t++) { | |
| 99 | const p = t * 9; | |
| 100 | const [ax, ay, az, bx, by, bz, cx, cy, cz] = Array.from(positions.subarray(p, p + 9)) as [number, number, number, number, number, number, number, number, number]; | |
| 101 | const ux = bx - ax, uy = by - ay, uz = bz - az; | |
| 102 | const vx = cx - ax, vy = cy - ay, vz = cz - az; | |
| 103 | let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; | |
| 104 | const len = Math.hypot(nx, ny, nz); | |
| 105 | if (len > 0) { nx /= len; ny /= len; nz /= len; } else { nx = ny = nz = 0; } | |
| 106 | const at = 84 + t * 50; | |
| 107 | view.setFloat32(at, nx, true); | |
| 108 | view.setFloat32(at + 4, ny, true); | |
| 109 | view.setFloat32(at + 8, nz, true); | |
| 110 | for (let i = 0; i < 9; i++) view.setFloat32(at + 12 + i * 4, positions[p + i]!, true); | |
| 111 | } | |
| 112 | return out; | |
| 113 | } |
test/pages-budget.test.ts +1 −1
| @@ -65,7 +65,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = { | ||
| 65 | 65 | }; |
| 66 | 66 | |
| 67 | 67 | /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */ |
| 68 | const MAX_UNFIXTURED = 152; // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) | |
| 68 | const MAX_UNFIXTURED = 153; // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) | |
| 69 | 69 | |
| 70 | 70 | /** Streams and live fragments: no page. */ |
| 71 | 71 | const NOT_PAGES = new Set([ |
test/stl-convert.test.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** #15856: an .stl is offered in its other form, and the file round-trips. */ | |
| 2 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createApp, type App } from "../src/app.ts"; | |
| 7 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 8 | import { getRepo } from "../src/core/repos.ts"; | |
| 9 | import { createUser } from "../src/core/users.ts"; | |
| 10 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 11 | import { model3d } from "../src/web/render/model3d.ts"; | |
| 12 | import { attachment } from "../src/web/pages/media.ts"; | |
| 13 | import { stlAnswer } from "../src/web/pages/repo.ts"; | |
| 14 | import { convertedPath, convertStl, stlForm, stlHref } from "../src/web/render/stl_convert.ts"; | |
| 15 | import { readStl, STL_LIMIT } from "../src/web/render/stl.ts"; | |
| 16 | import { parseStl } from "../src/web/render/mesh.ts"; | |
| 17 | import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts"; | |
| 18 | ||
| 19 | const fixture = async (name: string): Promise<Uint8Array> => | |
| 20 | new Uint8Array(await Bun.file(new URL(`./fixtures/model3d/${name}`, import.meta.url)).arrayBuffer()); | |
| 21 | ||
| 22 | /** A one-triangle binary STL whose corners need float32 digits to survive. */ | |
| 23 | const odd = (): Uint8Array => { | |
| 24 | const out = new Uint8Array(84 + 50); | |
| 25 | const v = new DataView(out.buffer); | |
| 26 | v.setUint32(80, 1, true); | |
| 27 | [0, 0, 1, 0.1, 0.2, 0.3, 1e-7, -2.5e10, 3.14159274, 7, 8, 9].forEach((n, i) => v.setFloat32(84 + i * 4, n, true)); | |
| 28 | return out; | |
| 29 | }; | |
| 30 | ||
| 31 | describe("convertStl", () => { | |
| 32 | test("binary → ASCII → binary keeps every triangle and the Box", async () => { | |
| 33 | const binary = await fixture("cube-binary.stl"); | |
| 34 | const ascii = convertStl(binary); | |
| 35 | if ("error" in ascii) throw new Error(ascii.error); | |
| 36 | expect(ascii.form).toBe("ascii"); | |
| 37 | expect(new TextDecoder().decode(ascii.bytes)).toMatch(/^solid \S+\nfacet normal /); | |
| 38 | expect(stlForm(ascii.bytes)).toBe("ascii"); | |
| 39 | const back = convertStl(ascii.bytes); | |
| 40 | if ("error" in back) throw new Error(back.error); | |
| 41 | expect(back.form).toBe("binary"); | |
| 42 | expect(parseStl(ascii.bytes).positions).toEqual(parseStl(binary).positions); | |
| 43 | expect(parseStl(back.bytes).positions).toEqual(parseStl(binary).positions); | |
| 44 | const [a, b] = [readStl(binary), readStl(back.bytes)]; | |
| 45 | if ("error" in a || "error" in b) throw new Error("must read"); | |
| 46 | expect(b.triangles).toBe(a.triangles); | |
| 47 | expect(b.box).toEqual(a.box); | |
| 48 | expect(b.size).toBe("20 × 20 × 20 units"); | |
| 49 | }); | |
| 50 | ||
| 51 | test("ASCII → binary → ASCII compares the same Box", async () => { | |
| 52 | const ascii = await fixture("cube-ascii.stl"); | |
| 53 | const binary = convertStl(ascii); | |
| 54 | if ("error" in binary) throw new Error(binary.error); | |
| 55 | expect(binary.form).toBe("binary"); | |
| 56 | expect(binary.bytes.length).toBe(84 + 12 * 50); | |
| 57 | const back = convertStl(binary.bytes); | |
| 58 | if ("error" in back) throw new Error(back.error); | |
| 59 | const [a, b] = [readStl(ascii), readStl(back.bytes)]; | |
| 60 | if ("error" in a || "error" in b) throw new Error("must read"); | |
| 61 | expect(b.box).toEqual(a.box); | |
| 62 | expect(b.triangles).toBe(12); | |
| 63 | }); | |
| 64 | ||
| 65 | test("awkward float32 digits survive exactly", () => { | |
| 66 | const binary = odd(); | |
| 67 | const ascii = convertStl(binary); | |
| 68 | if ("error" in ascii) throw new Error(ascii.error); | |
| 69 | const back = convertStl(ascii.bytes); | |
| 70 | if ("error" in back) throw new Error(back.error); | |
| 71 | expect(parseStl(back.bytes).positions).toEqual(parseStl(binary).positions); | |
| 72 | }); | |
| 73 | ||
| 74 | test("a binary file's stored normal travels into the text", () => { | |
| 75 | const ascii = convertStl(odd()); | |
| 76 | if ("error" in ascii) throw new Error(ascii.error); | |
| 77 | expect(new TextDecoder().decode(ascii.bytes)).toContain("facet normal 0 0 1\n"); | |
| 78 | }); | |
| 79 | ||
| 80 | test("garbage and empty files are an error sentence, not a throw", () => { | |
| 81 | expect(convertStl(new Uint8Array(0))).toEqual({ error: expect.any(String) }); | |
| 82 | expect(convertStl(new TextEncoder().encode("solid x\nvertex 1 2\n"))).toEqual({ error: expect.any(String) }); | |
| 83 | expect(convertStl(new Uint8Array(10))).toEqual({ error: expect.any(String) }); | |
| 84 | }); | |
| 85 | ||
| 86 | test("names are the file's own, safe, with the form", () => { | |
| 87 | expect(attachment(convertedPath("a/b/clip.STL", "ascii"))).toContain('filename="clip-ascii.stl"'); | |
| 88 | expect(attachment(convertedPath("we ird\"x.stl", "binary"))).toContain('filename="we ird_x-binary.stl"'); | |
| 89 | }); | |
| 90 | }); | |
| 91 | ||
| 92 | describe("the refusal and the link", () => { | |
| 93 | const req = new Request("https://forge.test/a/b/stl/main/x.stl"); | |
| 94 | test("a blob over 20 MB is a 422 with the sentence, never converted", async () => { | |
| 95 | const res = stlAnswer(req, { kind: "too_large", size: 30_000_000 }, "main", "x.stl"); | |
| 96 | expect(res.status).toBe(422); | |
| 97 | expect(await res.text()).toContain("20 MB"); | |
| 98 | const big = stlAnswer(req, { kind: "binary", body: new Uint8Array(1), size: STL_LIMIT + 1, oid: "a".repeat(40) }, "main", "x.stl"); | |
| 99 | expect(big.status).toBe(422); | |
| 100 | expect(big.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 101 | }); | |
| 102 | ||
| 103 | test("the href encodes each segment", () => { | |
| 104 | expect(stlHref("/a/b", "main", "my parts/a#b?c.stl")).toBe("/a/b/stl/main/my%20parts/a%23b%3Fc.stl"); | |
| 105 | }); | |
| 106 | }); | |
| 107 | ||
| 108 | describe("the link on the page", () => { | |
| 109 | const repo = { base: "/a/b", ref: "main" }; | |
| 110 | const page = (path: string, body: Uint8Array, size = body.length) => | |
| 111 | String(model3d({ path, body, size, media: "/m", download: "/d", repo }).content); | |
| 112 | ||
| 113 | test("a binary STL offers ASCII; an ASCII one offers binary", async () => { | |
| 114 | expect(page("x/c.stl", await fixture("cube-binary.stl"))).toContain('href="/a/b/stl/main/x/c.stl"'); | |
| 115 | expect(page("c.stl", await fixture("cube-binary.stl"))).toContain("Download as ASCII"); | |
| 116 | expect(page("c.stl", await fixture("cube-ascii.stl"))).toContain("Download as binary"); | |
| 117 | }); | |
| 118 | ||
| 119 | test("over 20 MB, or unreadable, the link is not offered", async () => { | |
| 120 | const body = await fixture("cube-binary.stl"); | |
| 121 | expect(page("c.stl", body, STL_LIMIT + 1)).not.toContain("Download as"); | |
| 122 | expect(page("c.stl", new Uint8Array(30))).not.toContain("Download as"); | |
| 123 | }); | |
| 124 | }); | |
| 125 | ||
| 126 | describe("the route", () => { | |
| 127 | let dataDir: string; | |
| 128 | let app: App; | |
| 129 | let servers: Servers; | |
| 130 | let sha = ""; | |
| 131 | const get = (path: string) => fetch(`${servers.url}${path}`); | |
| 132 | ||
| 133 | beforeAll(async () => { | |
| 134 | dataDir = await mkdtemp(join(tmpdir(), "forge-stl-")); | |
| 135 | app = createApp({ dataDir, port: 0, trustedProxies: LOOPBACK_PROXIES }); | |
| 136 | servers = await serve(app); | |
| 137 | const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", isAdmin: true }); | |
| 138 | if (!u.ok) throw new Error(u.error); | |
| 139 | const r = await createRepo(app, u.value, { name: "cad", visibility: "public" }); | |
| 140 | if (!r.ok) throw new Error(String(r.error)); | |
| 141 | const c = await commitToBranch(app, u.value, getRepo(app.db, "alice", "cad")!, { | |
| 142 | message: "Parts", | |
| 143 | files: [ | |
| 144 | { path: "p/cube.stl", content: await fixture("cube-binary.stl") }, | |
| 145 | { path: "cube-a.stl", content: await fixture("cube-ascii.stl") }, | |
| 146 | { path: "a.txt", content: "hi\n" }, | |
| 147 | ], | |
| 148 | }); | |
| 149 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 150 | sha = Bun.spawnSync(["git", "--git-dir", join(dataDir, "repos", "alice", "cad.git"), "rev-parse", "HEAD"]).stdout.toString().trim(); | |
| 151 | }); | |
| 152 | afterAll(async () => { | |
| 153 | servers.stop(); | |
| 154 | app.close(); | |
| 155 | await rm(dataDir, { recursive: true, force: true }); | |
| 156 | }); | |
| 157 | ||
| 158 | test("a binary STL comes back as solid text, saved under a named file", async () => { | |
| 159 | const res = await get("/alice/cad/stl/main/p/cube.stl"); | |
| 160 | expect(res.status).toBe(200); | |
| 161 | expect(res.headers.get("content-type")).toStartWith("model/stl"); | |
| 162 | expect(res.headers.get("content-disposition")).toStartWith('attachment; filename="cube-ascii.stl"'); | |
| 163 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 164 | const text = await res.text(); | |
| 165 | expect(text.startsWith("solid ")).toBe(true); | |
| 166 | expect(text.match(/endfacet/g)?.length).toBe(12); | |
| 167 | }); | |
| 168 | ||
| 169 | test("an ASCII STL comes back as binary", async () => { | |
| 170 | const res = await get("/alice/cad/stl/main/cube-a.stl"); | |
| 171 | expect(res.headers.get("content-disposition")).toStartWith('attachment; filename="cube-a-binary.stl"'); | |
| 172 | expect((await res.arrayBuffer()).byteLength).toBe(84 + 12 * 50); | |
| 173 | }); | |
| 174 | ||
| 175 | test("a full commit id is immutable and revalidates by etag", async () => { | |
| 176 | const res = await get(`/alice/cad/stl/${sha}/p/cube.stl`); | |
| 177 | expect(res.headers.get("cache-control")).toContain("immutable"); | |
| 178 | const etag = res.headers.get("etag")!; | |
| 179 | const again = await fetch(`${servers.url}/alice/cad/stl/${sha}/p/cube.stl`, { headers: { "if-none-match": etag } }); | |
| 180 | expect(again.status).toBe(304); | |
| 181 | }); | |
| 182 | ||
| 183 | test("a non-STL and a missing file are refused", async () => { | |
| 184 | expect((await get("/alice/cad/stl/main/a.txt")).status).toBe(404); | |
| 185 | expect((await get("/alice/cad/stl/main/nope.stl")).status).toBe(404); | |
| 186 | }); | |
| 187 | }); |
test/tui-model3d.test.ts +2 −1
| @@ -49,7 +49,7 @@ test("a binary STL reads as a 3D model with its triangles, its box and where to | ||
| 49 | 49 | const { app } = createForgeApp( |
| 50 | 50 | forge, |
| 51 | 51 | { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, |
| 52 | { terminal: headlessTerminal(140, 40), exitHooks: false }, | |
| 52 | { terminal: headlessTerminal(260, 40), exitHooks: false }, | |
| 53 | 53 | ); |
| 54 | 54 | app.start(); |
| 55 | 55 | const send = (key: string): void => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); |
| @@ -70,6 +70,7 @@ test("a binary STL reads as a 3D model with its triangles, its box and where to | ||
| 70 | 70 | expect(text).toContain("12 triangles · 20 × 20 × 20 units"); |
| 71 | 71 | expect(text).toContain("Download: https://forge.test/alice/tower/media/main/parts/cube.stl?download=1"); |
| 72 | 72 | expect(text).not.toContain("Binary file"); |
| 73 | expect(text).toContain("As ASCII: https://forge.test/alice/tower/stl/main/parts/cube.stl"); | |
| 73 | 74 | } finally { |
| 74 | 75 | app.stop(); |
| 75 | 76 | } |
new above
offline
This duplicates
attachmentin src/web/pages/media.ts (the gate flagged 0.69 similarity). Reuse that helper instead of a second filename sanitiser.