Public: anyone can read this; the crew can change it.
A .wasm module lists its sections, imports and exports #14467
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14453-a-wasm-module-lists-its-sections-imports → main 7 commits fork 2 threads · 2 unresolved
12 files
changed +412
−2
docs/features/file-kinds.md +1
| @@ -17,6 +17,7 @@ The forge draws a file on its page when its kind is below and it is within the s | ||
| 17 | 17 | - **Table (CSV, TSV, JSON lines)**, drawn up to 10 MB: `.csv`, `.tsv`, `.jsonl`, `.ndjson` |
| 18 | 18 | - **SQLite database**, drawn up to 5 MB: `.db`, `.sqlite`, `.sqlite3` |
| 19 | 19 | - **Parquet**, drawn up to 5 MB: `.parquet` |
| 20 | - **WebAssembly module**, drawn up to 5 MB: `.wasm` | |
| 20 | 21 | - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj`, `.dae` |
| 21 | 22 | - **Archive**, drawn up to 50 MB: `.zip`, `.tar`, `.tgz`, `.tar.gz` |
| 22 | 23 | - **Spreadsheet**, drawn up to 10 MB: `.xlsx` |
docs/features/wasm-modules.md added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | --- | |
| 2 | topic: Files in the browser | |
| 3 | row: A .wasm module as its sections, imports and exports | |
| 4 | --- | |
| 5 | # A WebAssembly module | |
| 6 | ||
| 7 | Open a `.wasm` file (up to 5 MB, and only when it starts with the `\0asm` signature) and the file page lists what the binary says: its version, its section table (id, name, size), and the names it imports and exports with their kinds. Only the section headers and the import and export sections are read; no code is decoded and nothing runs. Each table shows its first 500 rows and counts the rest. | |
| 8 | ||
| 9 | A section that cannot be read in full (a Memory64 or unknown import kind, a name running past its section, a file cut short) does not hide the rest: the section table and everything read before it stay, and a line under them names the section that failed. A file without the signature, or over 5 MB, shows as source or a download, as any binary does. | |
| 10 | ||
| 11 | Terminal door: in the workspace, open the same file and it is one table of rows: the headline, a `note` row for each section that could not be read, then each `section`, `import` and `export`. `src/tui/screens/workspace_wasm.ts` reuses the page's `readWasm` (`src/web/render/wasm.ts`) and its size gate. |
scripts/kinds-guide.ts +1 −1
| @@ -10,7 +10,7 @@ export const END = "<!-- file-kinds:end -->"; | ||
| 10 | 10 | /** The name a person says for each kind. A new kind without one fails the type check. */ |
| 11 | 11 | export const NAMES: Readonly<Record<FileKind, string>> = { |
| 12 | 12 | image: "Image", svg: "SVG", pdf: "PDF", html: "HTML page", audio: "Audio", video: "Video", csv: "Table (CSV, TSV, JSON lines)", |
| 13 | sqlite: "SQLite database", parquet: "Parquet", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", | |
| 13 | sqlite: "SQLite database", parquet: "Parquet", wasm: "WebAssembly module", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document", | |
| 14 | 14 | slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", config: "Config", markdown: "Markdown", |
| 15 | 15 | notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive", |
| 16 | 16 | geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", |
src/tui/screens/workspace.ts +2 −1
| @@ -95,6 +95,7 @@ import { sheetView } from "./workspace_sheet.ts"; | ||
| 95 | 95 | import { sqliteStep, sqliteView, type SqliteAt } from "./workspace_sqlite.ts"; |
| 96 | 96 | import { officeView } from "./workspace_office.ts"; |
| 97 | 97 | import { parquetView } from "./workspace_parquet.ts"; |
| 98 | import { wasmView } from "./workspace_wasm.ts"; | |
| 98 | 99 | import { layoutTable, type Grid } from "../ui/grid.ts"; |
| 99 | 100 | import type { Ctx, Screen } from "../app/app.ts"; |
| 100 | 101 | import { stripAnsi } from "../term/ansi.ts"; |
| @@ -1549,7 +1550,7 @@ export function workspaceScreen( | ||
| 1549 | 1550 | // bytes as text is how a terminal ends up beeping at you. |
| 1550 | 1551 | const base = looksLikeImage(t.path) ? null : sqliteView(t.path, read.value.body, { table: 0, page: 1 }); |
| 1551 | 1552 | if (base !== null && typeof base !== "string") db = read.value.body; |
| 1552 | const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body)); | |
| 1553 | const book = looksLikeImage(t.path) ? null : (base ?? sheetView(t.path, read.value.body) ?? officeView(t.path, read.value.body) ?? parquetView(t.path, read.value.body) ?? wasmView(t.path, read.value.body)); | |
| 1553 | 1554 | if (looksLikeImage(t.path)) picture = read.value.body; |
| 1554 | 1555 | else if (book !== null && typeof book !== "string") sheet = book; |
| 1555 | 1556 | else if (typeof book === "string") note = book; |
src/tui/screens/workspace_wasm.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** | |
| 2 | * A .wasm module in the terminal workspace, read the way the page reads it: the same `readWasm`, | |
| 3 | * drawn as one table of its sections, imports and exports. The same gate too: the name and the | |
| 4 | * bytes must say so (`fileKind`), under the page's cap. A section that cannot be read is a `note` | |
| 5 | * row and the rest stands; only a file without the signature answers a sentence. | |
| 6 | * | |
| 7 | * `wasmView(path, body)` answers a table, a sentence (the workspace shows it as its note), or | |
| 8 | * `null` for a file that is not WebAssembly. | |
| 9 | */ | |
| 10 | ||
| 11 | import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts"; | |
| 12 | import { readWasm } from "../../web/render/wasm.ts"; | |
| 13 | import { fileSize } from "../../web/ui.ts"; | |
| 14 | import type { Table } from "../../text/csv.ts"; | |
| 15 | ||
| 16 | /** A name from the file, for a terminal: control characters become a replacement mark. */ | |
| 17 | const plain = (s: string): string => s.replace(/[\u0000-\u001f\u007f-\u009f]/g, "�").slice(0, 200); | |
| 18 | ||
| 19 | export function wasmView(path: string, body: Uint8Array): Table | string | null { | |
| 20 | if (fileKind(path, body.subarray(0, HEAD_BYTES)) !== "wasm") return null; | |
| 21 | if (body.length > RENDER_CAP.wasm) | |
| 22 | return `This file is over ${RENDER_CAP.wasm / 1_000_000} MB, too large to open here. Download it instead.`; | |
| 23 | let w; | |
| 24 | try { | |
| 25 | w = readWasm(body); | |
| 26 | } catch { | |
| 27 | return "This WebAssembly module cannot be shown as sections: it does not start with the WebAssembly signature."; | |
| 28 | } | |
| 29 | const header = ["Part", "Name", "Detail"]; | |
| 30 | const n = (k: number, one: string): string => `${k.toLocaleString()} ${one}${k === 1 ? "" : "s"}`; | |
| 31 | const rows = [ | |
| 32 | [`WebAssembly v${w.version}`, `${n(w.sectionCount, "section")} · ${n(w.importCount, "import")} · ${n(w.exportCount, "export")}`, fileSize(body.length)], | |
| 33 | ...w.problems.map((p) => ["note", plain(p), ""]), | |
| 34 | ...w.sections.map((s) => ["section", plain(s.name), fileSize(s.size)]), | |
| 35 | ...w.imports.map((i) => ["import", plain(`${i.module}.${i.name}`), i.kind]), | |
| 36 | ...w.exports.map((x) => ["export", plain(x.name), `${x.kind} #${x.index}`]), | |
| 37 | ]; | |
| 38 | const more = | |
| 39 | Math.max(0, w.sectionCount - w.sections.length) + | |
| 40 | Math.max(0, w.importCount - w.imports.length) + | |
| 41 | Math.max(0, w.exportCount - w.exports.length); | |
| 42 | return { header, rows, more, delimiter: ",", columns: header.length }; | |
| 43 | } |
src/web/render/kinds.ts +11
| @@ -23,6 +23,7 @@ export type FileKind = | ||
| 23 | 23 | | "csv" |
| 24 | 24 | | "sqlite" |
| 25 | 25 | | "parquet" |
| 26 | | "wasm" | |
| 26 | 27 | | "model3d" |
| 27 | 28 | | "archive" |
| 28 | 29 | | "sheet" |
| @@ -104,6 +105,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = { | ||
| 104 | 105 | sqlite: 5 * MB, |
| 105 | 106 | // Only the footer is read, but the page reads the whole body: under its 5 MB ceiling. |
| 106 | 107 | parquet: 5 * MB, |
| 108 | // Only section headers, imports and exports are read; the page reads the whole body. | |
| 109 | wasm: 5 * MB, | |
| 107 | 110 | model3d: 100 * MB, |
| 108 | 111 | archive: 50 * MB, |
| 109 | 112 | sheet: 10 * MB, |
| @@ -390,6 +393,10 @@ const isDxfHead = (head: Uint8Array): boolean => | ||
| 390 | 393 | const isStepHead = (head: Uint8Array): boolean => |
| 391 | 394 | /^\uFEFF?\s*ISO-10303-21\s*;/.test(new TextDecoder().decode(head.subarray(0, 64))); |
| 392 | 395 | |
| 396 | /** A WebAssembly module opens on `\0asm`; its type is never served as `application/wasm`. */ | |
| 397 | const isWasm = (path: string, head: Uint8Array): boolean => | |
| 398 | extension(path) === "wasm" && bytes(0x00, 0x61, 0x73, 0x6d)(head); | |
| 399 | ||
| 393 | 400 | /** For a caller that has only a name: the kind its extension gives. */ |
| 394 | 401 | export const NO_BYTES: Uint8Array = new Uint8Array(0); |
| 395 | 402 | |
| @@ -469,6 +476,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind { | ||
| 469 | 476 | const office = isOffice(path, head); |
| 470 | 477 | if (office !== undefined) return office; |
| 471 | 478 | if (isArchive(path, head)) return "archive"; |
| 479 | if (isWasm(path, head)) return "wasm"; | |
| 472 | 480 | if (looksBinary(head)) return "binary"; |
| 473 | 481 | if (isLcovName(path)) return "lcov"; |
| 474 | 482 | if (isEnvExample(path)) return "env"; |
| @@ -512,6 +520,7 @@ export function kindByName(path: string): FileKind { | ||
| 512 | 520 | if (isWorkflowName(path)) return "workflow"; |
| 513 | 521 | if (isComposeName(path)) return "compose"; |
| 514 | 522 | if (ext === "xlsx") return "sheet"; |
| 523 | if (ext === "wasm") return "wasm"; | |
| 515 | 524 | if (OFFICE[ext] !== undefined) return OFFICE[ext]!; |
| 516 | 525 | return MEDIA[ext]?.kind ?? TEXTUAL[ext] ?? "text"; |
| 517 | 526 | } |
| @@ -544,6 +553,7 @@ export const KNOWN_EXTENSIONS: readonly string[] = [ | ||
| 544 | 553 | "tar", |
| 545 | 554 | "tgz", |
| 546 | 555 | "xlsx", |
| 556 | "wasm", | |
| 547 | 557 | ...Object.keys(OFFICE), |
| 548 | 558 | ]; |
| 549 | 559 | |
| @@ -613,6 +623,7 @@ const BY_CONTENT: Readonly<Partial<Record<FileKind, string>>> = { | ||
| 613 | 623 | const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>> = { |
| 614 | 624 | sheet: ["xlsx"], |
| 615 | 625 | archive: ["zip", "tar", "tgz"], |
| 626 | wasm: ["wasm"], | |
| 616 | 627 | }; |
| 617 | 628 | |
| 618 | 629 | /** What names a kind, for the guide: extensions and file names, each once, to show as code. */ |
src/web/render/renderers.ts +2
| @@ -61,6 +61,7 @@ import { pptx } from "./pptx.ts"; | ||
| 61 | 61 | import { ora } from "./ora.ts"; |
| 62 | 62 | import { sqlite } from "./sqlite.ts"; |
| 63 | 63 | import { parquet } from "./parquet.ts"; |
| 64 | import { wasm } from "./wasm.ts"; | |
| 64 | 65 | import { subtitles } from "./subtitles.ts"; |
| 65 | 66 | import { video } from "./video.ts"; |
| 66 | 67 | |
| @@ -131,6 +132,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = { | ||
| 131 | 132 | csv, |
| 132 | 133 | sqlite, |
| 133 | 134 | parquet, |
| 135 | wasm, | |
| 134 | 136 | audio, |
| 135 | 137 | video, |
| 136 | 138 | model3d, |
src/web/render/wasm.ts added +195
| @@ -0,0 +1,195 @@ | ||
| 1 | /** | |
| 2 | * A WebAssembly module as what its binary says: the version, the section table, and the names it | |
| 3 | * imports and exports with their kinds. Only the section headers and the import and export | |
| 4 | * sections are read; no code is decoded and nothing runs. Every read is checked against the | |
| 5 | * file's length (the file is capped by `RENDER_CAP.wasm` before it gets here), and every loop is | |
| 6 | * bounded by the bytes left, so a hostile count cannot spin it. A file without the signature falls | |
| 7 | * back to the plain file view with one sentence; a section that cannot be read (a Memory64 or | |
| 8 | * unknown import kind, a name past its section, a cut-off file) keeps what was read before it and | |
| 9 | * is named in `problems`. | |
| 10 | */ | |
| 11 | ||
| 12 | import { escapeHtml, html, raw } from "../html.ts"; | |
| 13 | import { fileSize } from "../ui.ts"; | |
| 14 | import type { Rendered, RenderInput } from "./renderers.ts"; | |
outdated
A malformed import/export/custom section throws away the whole file; keep the section table and note the failing section, and test it. |
||
| 15 | ||
| 16 | /** Rows drawn per table; the rest are counted. */ | |
| 17 | export const ROW_CAP = 500; | |
| 18 | const NAME_CAP = 200; | |
| 19 | ||
| 20 | class Bad extends Error {} | |
| 21 | ||
| 22 | const SECTIONS: Readonly<Record<number, string>> = { | |
| 23 | 0: "custom", 1: "type", 2: "import", 3: "function", 4: "table", 5: "memory", 6: "global", 7: "export", | |
| 24 | 8: "start", 9: "element", 10: "code", 11: "data", 12: "data count", 13: "tag", | |
| 25 | }; | |
| 26 | const KINDS = ["function", "table", "memory", "global", "tag"]; | |
| 27 | ||
| 28 | export interface Section { readonly id: number; readonly name: string; readonly size: number } | |
| 29 | export interface Import { readonly module: string; readonly name: string; readonly kind: string } | |
| 30 | export interface Export { readonly name: string; readonly kind: string; readonly index: number } | |
| 31 | export interface Wasm { | |
| 32 | readonly version: number; | |
| 33 | readonly sections: readonly Section[]; | |
| 34 | readonly sectionCount: number; | |
| 35 | readonly imports: readonly Import[]; | |
| 36 | readonly importCount: number; | |
| 37 | readonly exports: readonly Export[]; | |
| 38 | readonly exportCount: number; | |
| 39 | /** One sentence per section that could not be read in full; the rest of the table stands. */ | |
| 40 | readonly problems: readonly string[]; | |
| 41 | } | |
| 42 | ||
| 43 | /** A bounds-checked cursor over `b[pos, end)`. */ | |
| 44 | class Cursor { | |
| 45 | constructor(private readonly b: Uint8Array, public pos: number, readonly end: number) {} | |
| 46 | ||
| 47 | byte(): number { | |
| 48 | if (this.pos >= this.end) throw new Bad("it ends early"); | |
| 49 | return this.b[this.pos++]!; | |
| 50 | } | |
| 51 | ||
| 52 | /** An unsigned LEB128 of at most ten bytes; larger than 2^53 is refused. */ | |
| 53 | leb(): number { | |
| 54 | let n = 0; | |
| 55 | let scale = 1; | |
| 56 | for (let i = 0; i < 10; i++) { | |
| 57 | const x = this.byte(); | |
| 58 | n += (x & 0x7f) * scale; | |
| 59 | if (n > Number.MAX_SAFE_INTEGER) throw new Bad("it holds a number too large"); | |
| 60 | if ((x & 0x80) === 0) return n; | |
| 61 | scale *= 128; | |
| 62 | } | |
| 63 | throw new Bad("it holds a malformed number"); | |
| 64 | } | |
| 65 | ||
| 66 | name(): string { | |
| 67 | const len = this.leb(); | |
| 68 | if (len > this.end - this.pos) throw new Bad("a name runs past its section"); | |
| 69 | const s = new TextDecoder().decode(this.b.subarray(this.pos, this.pos + len)); | |
| 70 | this.pos += len; | |
| 71 | return s; | |
| 72 | } | |
| 73 | ||
| 74 | /** A count of entries that each take at least one byte: refused when more than the bytes left. */ | |
| 75 | count(): number { | |
| 76 | const n = this.leb(); | |
| 77 | if (n > this.end - this.pos) throw new Bad("a count is larger than its section"); | |
| 78 | return n; | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | function limits(c: Cursor): void { | |
| 83 | const flag = c.byte(); | |
| 84 | c.leb(); | |
| 85 | if ((flag & 1) !== 0) c.leb(); | |
| 86 | } | |
| 87 | ||
| 88 | function readImports(c: Cursor, out: Import[], tally: { n: number }): void { | |
| 89 | const n = c.count(); | |
| 90 | for (let i = 0; i < n; i++) { | |
| 91 | const module = c.name(); | |
| 92 | const name = c.name(); | |
| 93 | const k = c.byte(); | |
| 94 | if (k > 4) throw new Bad("an import has an unknown kind"); | |
| 95 | if (k === 0) c.leb(); | |
| 96 | else if (k === 1) { c.byte(); limits(c); } | |
| 97 | else if (k === 2) limits(c); | |
| 98 | else if (k === 3) { c.byte(); c.byte(); } | |
| 99 | else { c.byte(); c.leb(); } | |
| 100 | tally.n++; | |
| 101 | if (out.length < ROW_CAP) out.push({ module, name, kind: KINDS[k]! }); | |
| 102 | } | |
| 103 | } | |
| 104 | ||
| 105 | function readExports(c: Cursor, out: Export[], tally: { n: number }): void { | |
| 106 | const n = c.count(); | |
| 107 | for (let i = 0; i < n; i++) { | |
| 108 | const name = c.name(); | |
| 109 | const k = c.byte(); | |
| 110 | if (k > 4) throw new Bad("an export has an unknown kind"); | |
| 111 | const index = c.leb(); | |
| 112 | tally.n++; | |
| 113 | if (out.length < ROW_CAP) out.push({ name, kind: KINDS[k]!, index }); | |
| 114 | } | |
| 115 | } | |
| 116 | ||
| 117 | /** The module as plain data; throws a sentence-sized reason when it cannot be read. */ | |
| 118 | export function readWasm(body: Uint8Array): Wasm { | |
| 119 | if (body.length < 8 || body[0] !== 0 || body[1] !== 0x61 || body[2] !== 0x73 || body[3] !== 0x6d) | |
| 120 | throw new Bad("it does not start with the WebAssembly signature"); | |
| 121 | const version = new DataView(body.buffer, body.byteOffset, body.byteLength).getUint32(4, true); | |
| 122 | const top = new Cursor(body, 8, body.length); | |
| 123 | const sections: Section[] = []; | |
| 124 | const imports: Import[] = []; | |
| 125 | const exports: Export[] = []; | |
| 126 | const problems: string[] = []; | |
| 127 | const imported = { n: 0 }; | |
| 128 | const exported = { n: 0 }; | |
| 129 | let sectionCount = 0; | |
| 130 | while (top.pos < top.end) { | |
| 131 | let id = 0; | |
| 132 | let size = 0; | |
| 133 | try { | |
| 134 | id = top.byte(); | |
| 135 | size = top.leb(); | |
| 136 | if (size > top.end - top.pos) throw new Bad("a section runs past the end of the file, so it is cut short"); | |
| 137 | } catch (e) { | |
| 138 | problems.push(`After ${plural(sectionCount, "section")}: ${e instanceof Bad ? e.message : "it could not be read"}.`); | |
| 139 | break; | |
| 140 | } | |
| 141 | const start = top.pos; | |
| 142 | const inner = new Cursor(body, start, start + size); | |
| 143 | let label = SECTIONS[id] ?? `unknown (${id})`; | |
| 144 | try { | |
| 145 | if (id === 0) label = `custom: ${inner.name().slice(0, NAME_CAP)}`; | |
| 146 | else if (id === 2) readImports(inner, imports, imported); | |
| 147 | else if (id === 7) readExports(inner, exports, exported); | |
| 148 | } catch (e) { | |
| 149 | problems.push(`The ${label} section was read only in part: ${e instanceof Bad ? e.message : "it could not be read"}.`); | |
| 150 | if (id === 0) label = "custom"; | |
| 151 | } | |
| 152 | sectionCount++; | |
| 153 | if (sections.length < ROW_CAP) sections.push({ id, name: label, size }); | |
| 154 | top.pos = start + size; | |
| 155 | } | |
| 156 | return { version, sections, sectionCount, imports, importCount: imported.n, exports, exportCount: exported.n, problems }; | |
| 157 | } | |
| 158 | ||
| 159 | const plural = (n: number, one: string): string => `${n.toLocaleString()} ${one}${n === 1 ? "" : "s"}`; | |
| 160 | ||
| 161 | /** Names come from the file: control characters are dropped, the length capped, then escaped. */ | |
| 162 | const clean = (s: string): string => escapeHtml(s.replace(/[\u0000-\u001f\u007f]/g, "�").slice(0, NAME_CAP)); | |
| 163 | ||
| 164 | export function wasm(input: RenderInput): Rendered { | |
| 165 | let w: Wasm; | |
| 166 | try { | |
| 167 | w = readWasm(input.body); | |
| 168 | } catch (e) { | |
| 169 | const why = e instanceof Bad ? e.message : "it could not be read"; | |
| 170 | return { content: html``, lines: 0, fallback: `This WebAssembly module cannot be shown as sections: ${why}.` }; | |
| 171 | } | |
| 172 | const summary = `WebAssembly v${w.version} · ${plural(w.sectionCount, "section")} · ${plural(w.importCount, "import")} · ${plural(w.exportCount, "export")} · ${fileSize(input.size)}`; | |
| 173 | const more = (shown: number, total: number, what: string): string => | |
| 174 | total > shown ? `<p class="muted small">Showing the first ${shown.toLocaleString()} of ${total.toLocaleString()} ${what}.</p>` : ""; | |
| 175 | const sec = w.sections | |
| 176 | .map((s) => `<tr><td class="num">${s.id}</td><td>${clean(s.name)}</td><td class="num">${escapeHtml(fileSize(s.size))}</td></tr>`) | |
| 177 | .join(""); | |
| 178 | const imp = w.imports | |
| 179 | .map((i) => `<tr><td>${clean(i.module)}</td><td>${clean(i.name)}</td><td class="muted">${escapeHtml(i.kind)}</td></tr>`) | |
| 180 | .join(""); | |
| 181 | const exp = w.exports | |
| 182 | .map((x) => `<tr><td>${clean(x.name)}</td><td class="muted">${escapeHtml(x.kind)}</td><td class="num">${x.index}</td></tr>`) | |
| 183 | .join(""); | |
| 184 | const notes = w.problems.map((p) => `<p class="muted small">${clean(p)}</p>`).join(""); | |
| 185 | const table = (label: string, head: string, rows: string): string => | |
| 186 | `<div class="csv-scroll"><table class="table" data-dense aria-label="${label}"><thead><tr>${head}</tr></thead><tbody>${rows}</tbody></table></div>`; | |
| 187 | const content = [ | |
| 188 | notes, | |
| 189 | table("Sections", '<th class="num">Id</th><th>Section</th><th class="num">Size</th>', sec), | |
| 190 | more(w.sections.length, w.sectionCount, "sections"), | |
| 191 | w.importCount > 0 ? table("Imports", "<th>Module</th><th>Name</th><th>Kind</th>", imp) + more(w.imports.length, w.importCount, "imports") : "", | |
| 192 | w.exportCount > 0 ? table("Exports", '<th>Name</th><th>Kind</th><th class="num">Index</th>', exp) + more(w.exports.length, w.exportCount, "exports") : "", | |
| 193 | ].join("\n"); | |
| 194 | return { content: html`${raw(content)}`, lines: 0, summary }; | |
| 195 | } |
test/fuzz-renderers.test.ts +1
| @@ -320,6 +320,7 @@ export const EXCLUDED: Readonly<Record<string, string>> = { | ||
| 320 | 320 | video: "a <video> pointing at the media route; binary, needs a fixture", |
| 321 | 321 | sqlite: "binary database pages; needs a fixture to splice into", |
| 322 | 322 | parquet: "binary columnar file; needs a fixture to splice into", |
| 323 | wasm: "binary module; needs a fixture to splice into", | |
| 323 | 324 | archive: "zip/tar bytes; needs a fixture to splice into", |
| 324 | 325 | sheet: "a zip of XML (xlsx); needs a fixture to splice into", |
| 325 | 326 | document: "a zip of XML (docx); needs a fixture to splice into", |
test/render-kinds.test.ts +1
| @@ -45,6 +45,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = { | ||
| 45 | 45 | sqlite: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"], |
| 46 | 46 | sqlite3: [enc("SQLite format 3\0"), "sqlite", "application/vnd.sqlite3"], |
| 47 | 47 | parquet: [enc("PAR1"), "parquet", "application/vnd.apache.parquet"], |
| 48 | wasm: [of(0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0), "wasm", "application/octet-stream"], | |
| 48 | 49 | csv: [enc("a,b\n1,2\n"), "csv", "application/octet-stream"], |
| 49 | 50 | tsv: [enc("a\tb\n"), "csv", "application/octet-stream"], |
| 50 | 51 | jsonl: [enc("{\"a\":1}\n"), "csv", "application/octet-stream"], |
test/render-wasm.test.ts added +96
| @@ -0,0 +1,96 @@ | ||
| 1 | /** A WebAssembly module (built here) as its section table, imports and exports. */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import type { Blob } from "../src/view/source.ts"; | |
| 4 | import { fileKind } from "../src/web/render/kinds.ts"; | |
| 5 | import { RENDERERS, rendererFor } from "../src/web/render/renderers.ts"; | |
| 6 | import { readWasm, ROW_CAP, wasm } from "../src/web/render/wasm.ts"; | |
| 7 | ||
| 8 | const enc = (s: string): number[] => [...new TextEncoder().encode(s)]; | |
| 9 | const str = (s: string): number[] => [enc(s).length, ...enc(s)]; | |
| 10 | const leb = (n: number): number[] => (n < 128 ? [n] : [(n & 0x7f) | 0x80, ...leb(n >> 7)]); | |
| 11 | const section = (id: number, body: number[]): number[] => [id, ...leb(body.length), ...body]; | |
| 12 | const HEAD = [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]; | |
| 13 | ||
| 14 | function module(evil = "env"): Uint8Array { | |
| 15 | const imports = [2, ...str(evil), ...str("log"), 0, 0, ...str("env"), ...str("mem"), 2, 0, 1]; | |
| 16 | const exports = [2, ...str("main"), 0, 3, ...str("memory"), 2, 0]; | |
| 17 | return Uint8Array.from([ | |
| 18 | ...HEAD, | |
| 19 | ...section(1, [0]), | |
| 20 | ...section(2, imports), | |
| 21 | ...section(7, exports), | |
| 22 | ...section(0, str("name")), | |
| 23 | ]); | |
| 24 | } | |
| 25 | const draw = (body: Uint8Array) => wasm({ path: "a.wasm", size: body.length, body, media: "", download: "" }); | |
| 26 | const text = (r: ReturnType<typeof draw>) => String(r.content); | |
| 27 | ||
| 28 | describe("a .wasm module", () => { | |
| 29 | test("is a kind of its own, by name and signature", () => { | |
| 30 | expect(fileKind("a.wasm", module())).toBe("wasm"); | |
| 31 | expect(fileKind("a.wasm", Uint8Array.from([1, 0, 3, 4]))).toBe("binary"); | |
| 32 | expect(RENDERERS.wasm).toBe(wasm); | |
| 33 | }); | |
| 34 | ||
| 35 | test("lists sections, imports and exports with their kinds", () => { | |
| 36 | const w = readWasm(module()); | |
| 37 | expect(w.version).toBe(1); | |
| 38 | expect(w.sections.map((s) => s.name)).toEqual(["type", "import", "export", "custom: name"]); | |
| 39 | expect(w.imports).toEqual([ | |
| 40 | { module: "env", name: "log", kind: "function" }, | |
| 41 | { module: "env", name: "mem", kind: "memory" }, | |
| 42 | ]); | |
| 43 | expect(w.exports).toEqual([ | |
| 44 | { name: "main", kind: "function", index: 3 }, | |
| 45 | { name: "memory", kind: "memory", index: 0 }, | |
| 46 | ]); | |
| 47 | const r = draw(module()); | |
| 48 | expect(r.summary).toContain("WebAssembly v1 · 4 sections · 2 imports · 2 exports"); | |
| 49 | expect(text(r)).toContain("<td>main</td>"); | |
| 50 | expect(r.fallback).toBeUndefined(); | |
| 51 | }); | |
| 52 | ||
| 53 | test("escapes names from the file", () => { | |
| 54 | const out = text(draw(module("<script>alert(1)</script>"))); | |
| 55 | expect(out).not.toContain("<script>"); | |
| 56 | expect(out).toContain("<script>"); | |
| 57 | }); | |
| 58 | ||
| 59 | test("a file without the signature falls back and never throws", () => { | |
| 60 | for (const bad of [module().subarray(0, 5), Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8, 9])]) { | |
| 61 | expect(draw(bad).fallback).toContain("cannot be shown"); | |
| 62 | } | |
| 63 | }); | |
| 64 | ||
| 65 | test("a section that cannot be read keeps the section table and says which", () => { | |
| 66 | for (const [body, said] of [ | |
| 67 | [Uint8Array.from([...HEAD, ...section(1, [0]), ...section(2, [1, ...str("a"), ...str("b"), 9, 0])]), "import section was read only in part"], | |
| 68 | [Uint8Array.from([...HEAD, ...section(1, [0]), ...section(7, [1, 1, 0x61, 9, 0])]), "export section was read only in part"], | |
| 69 | [Uint8Array.from([...HEAD, ...section(1, [0]), ...section(0, [9, 1])]), "custom section was read only in part"], | |
| 70 | [Uint8Array.from([...HEAD, ...section(1, [0]), ...section(2, [0xff, 0xff, 0x7f])]), "import section was read only in part"], | |
| 71 | [module().subarray(0, module().length - 3), "cut short"], | |
| 72 | ] as const) { | |
| 73 | const r = draw(body); | |
| 74 | expect(r.fallback).toBeUndefined(); | |
| 75 | expect(text(r)).toContain("<td>type</td>"); | |
| 76 | expect(text(r)).toContain(said); | |
| 77 | } | |
| 78 | const w = readWasm(Uint8Array.from([...HEAD, ...section(2, [2, ...str("a"), ...str("b"), 0, 0, ...str("c"), ...str("d"), 9])])); | |
| 79 | expect(w.imports).toEqual([{ module: "a", name: "b", kind: "function" }]); | |
| 80 | expect(w.importCount).toBe(1); | |
| 81 | }); | |
| 82 | ||
| 83 | test("a huge count is bounded by the bytes, and rows by the cap", () => { | |
| 84 | const entries = Array.from({ length: 600 }, () => [1, 0x61, 0, 0]).flat(); | |
| 85 | const body = Uint8Array.from([...HEAD, ...section(7, [0xd8, 0x04, ...entries])]); | |
| 86 | const r = draw(body); | |
| 87 | expect(r.fallback).toBeUndefined(); | |
| 88 | expect(readWasm(body).exports.length).toBe(ROW_CAP); | |
| 89 | expect(r.summary).toContain("600 exports"); | |
| 90 | }); | |
| 91 | ||
| 92 | test("an oversized file keeps its source view", () => { | |
| 93 | const blob: Blob = { kind: "too_large", size: 6_000_000, head: module() }; | |
| 94 | expect(rendererFor("a.wasm", blob)).toBeUndefined(); | |
| 95 | }); | |
| 96 | }); |
test/tui-workspace-wasm.test.ts added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | /** A .wasm module in the terminal workspace: the page's reader, one table, the page's gate. */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { wasmView } from "../src/tui/screens/workspace_wasm.ts"; | |
| 4 | import { RENDER_CAP } from "../src/web/render/kinds.ts"; | |
| 5 | ||
| 6 | const enc = (s: string): number[] => [...new TextEncoder().encode(s)]; | |
| 7 | const str = (s: string): number[] => [enc(s).length, ...enc(s)]; | |
| 8 | const section = (id: number, body: number[]): number[] => [id, body.length, ...body]; | |
| 9 | const HEAD = [0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]; | |
| 10 | const good = Uint8Array.from([ | |
| 11 | ...HEAD, | |
| 12 | ...section(1, [0]), | |
| 13 | ...section(2, [1, ...str("env"), ...str("log"), 0, 0]), | |
| 14 | ...section(7, [1, ...str("main"), 0, 3]), | |
| 15 | ]); | |
| 16 | ||
| 17 | describe("wasmView", () => { | |
| 18 | test("is null for what is not WebAssembly by name and bytes", () => { | |
| 19 | expect(wasmView("a.txt", good)).toBeNull(); | |
| 20 | expect(wasmView("a.wasm", Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]))).toBeNull(); | |
| 21 | }); | |
| 22 | ||
| 23 | test("draws the sections, imports and exports as rows", () => { | |
| 24 | const t = wasmView("a.wasm", good); | |
| 25 | if (t === null || typeof t === "string") throw new Error("expected a table"); | |
| 26 | expect(t.rows[0]![0]).toBe("WebAssembly v1"); | |
| 27 | expect(t.rows[0]![1]).toBe("3 sections · 1 import · 1 export"); | |
| 28 | expect(t.rows.slice(1).map((r) => r.slice(0, 2).join(" "))).toEqual([ | |
| 29 | "section type", "section import", "section export", "import env.log", "export main", | |
| 30 | ]); | |
| 31 | expect(t.rows.at(-1)![2]).toBe("function #3"); | |
| 32 | }); | |
| 33 | ||
| 34 | test("an unreadable section is a note row and the table stands; a control character is replaced", () => { | |
| 35 | const body = Uint8Array.from([...HEAD, ...section(1, [0]), ...section(2, [1, ...str("a\u0007"), ...str("b"), 9, 0])]); | |
| 36 | const t = wasmView("a.wasm", body); | |
| 37 | if (t === null || typeof t === "string") throw new Error("expected a table"); | |
| 38 | expect(t.rows.some((r) => r[0] === "note" && r[1]!.includes("import section was read only in part"))).toBe(true); | |
| 39 | expect(t.rows.some((r) => r[0] === "section" && r[1] === "type")).toBe(true); | |
| 40 | expect(JSON.stringify(t.rows)).not.toContain("\\u0007"); | |
| 41 | }); | |
| 42 | ||
| 43 | test("a module over the page's cap answers a sentence", () => { | |
| 44 | const big = new Uint8Array(RENDER_CAP.wasm + 1); | |
| 45 | big.set(HEAD); | |
| 46 | expect(wasmView("a.wasm", big)).toContain("too large to open here"); | |
| 47 | }); | |
| 48 | }); |
new above
offline
No terminal door: add a src/tui screen that reuses readWasm (both doors rule), with a test.