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

A building model in IFC opens as its project tree and element counts #16036

Merged opened this

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

Merged

scout/forge:scout/16020-a-building-model-in-ifc-opens-as-its-pro → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16020-a-building-model-in-ifc-opens-as-its-pro was merged into main as 6fbf6e6.

Review

Sign in to review this change.
21 files changed +579 −33
docs/design/areas/ifc.md added +5
@@ -0,0 +1,5 @@
1 # IFC building model
2
3 The blob page's view for an `.ifc` file (`src/web/render/ifc.ts`, the reading in `src/text/ifc.ts`). Facts, the spatial tree and the element counts are `status-rows` (label as `dt`, value as `dd`) under the plain `h3` the other file renderers use.
4
5 - `.ifc-depth-1` … `.ifc-depth-6` (`src/web/render/ifc-css.ts`) — a tree row's depth, as indent on its `dt` only, in steps of 1.5ch. The label is the level (Project, Site, Building, Storey), so a screen reader hears words, not glyphs. A row with no name says "no name"; an element type is words ("Wall standard case"), not the file's upper-case name.
docs/features/file-kinds.md +1
@@ -61,6 +61,7 @@ The forge draws a file on its page when its kind is below and it is within the s
6161 - **Excalidraw**, drawn up to 1 MB: `.excalidraw`
6262 - **STEP model**, drawn up to 5 MB: `.step`, `.stp`
6363 - **IGES drawing**, drawn up to 5 MB: `.iges`, `.igs`
64 - **IFC building model**, drawn up to 5 MB: `.ifc`
6465 - **Premiere project**, drawn up to 10 MB: `.prproj`
6566 - **SARIF report**, drawn up to 5 MB: `.sarif`
6667 - **Coverage (lcov)**, drawn up to 5 MB: `.lcov`, `lcov.info`
scripts/kinds-guide.ts +1 −1
@@ -15,7 +15,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
1616 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
1717 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", kicad: "KiCad board", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
18 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
18 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", ifc: "IFC building model", 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",
2121 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",
src/core/empty_words.ts +2
@@ -110,6 +110,8 @@ export const NOTE_WORDS = {
110110 noRepositoryRunsOnItsOwn: "No repository runs on its own.",
111111 nothingOfferedYet: "Nothing offered yet.",
112112 noFlagIsDeclaredYet: "No flag is declared yet.",
113 noProjectInThisFile: "No project in this file.",
114 noElementsPlacedInAStorey: "No elements are placed in a storey.",
113115 nothingProposedToTheParentForgeYet: "Nothing proposed to the parent forge yet.",
114116 noProcessesWereRead: "No processes were read.",
115117 noSamplesYet: "No samples yet.",
src/http/mcp/tools/read_file.ts +7 −1
@@ -4,6 +4,8 @@ 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 { readIfc, ifcAbout } from "../../../text/ifc.ts";
8 import { RENDER_CAP } from "../../../web/render/kinds.ts";
79 import { kicadFacts, parseKicad } from "../../../web/render/kicad.ts";
810 import { aboutUsd } from "../../../web/render/usd.ts";
911 import { readMidi, Unreadable } from "../../../web/render/midi.ts";
@@ -15,7 +17,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"
1517
1618 export const tool: Tool = {
1719 name: "read_file",
18 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}",
20 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}",
1921 description:
2022 "No shell? Read a file or list a directory at a ref (default branch); over 5 MB answers tooLarge.",
2123 inputSchema: {
@@ -77,6 +79,10 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7779 const { format, triangles } = stl.value;
7880 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7981 }
82 if (/\.ifc$/i.test(path) && body.length <= RENDER_CAP.ifc) {
83 const model = readIfc(new TextDecoder().decode(body));
84 return "error" in model ? { kind: "ifc", says: `IFC, unreadable: ${model.error}` } : ifcAbout(model);
85 }
8086 if (/\.kicad_pcb$/i.test(path) && text !== undefined) {
8187 const board = parseKicad(text);
8288 return "error" in board ? { kind: "kicad_pcb", parses: false, message: board.error } : kicadFacts(board);
src/text/ifc.ts added +257
@@ -0,0 +1,257 @@
1 /**
2 * An IFC building model (`.ifc`, STEP text) read for its header, its spatial tree (project, site,
3 * building, storey) and a count of the elements placed in storeys. No geometry is kept. The caller
4 * caps the size first; comments are stripped in one pass, DATA is walked once, and a statement is
5 * only parsed when it is a spatial object or one of the two relationships that place things; each
6 * such scan resumes after its own end, and a relation's parts are appended to one list per parent,
7 * so a hostile file is linear. The tree is walked with a visited set and a depth and node limit, so
8 * a cycle or a huge file ends. A `#n=IFC…(` inside a quoted string of an ordinary statement is
9 * counted as an entity: the counts are a summary, not a validator. Pure; shared by the blob page,
10 * the MCP file tool and the terminal workspace.
11 */
12
13 import { slots, statement, strings } from "./step_text.ts";
14
15 export const TREE_NODES = 200;
16 export const TREE_DEPTH = 6;
17 export const ELEMENT_TYPES = 40;
18 const NAME_CHARS = 200;
19 const SPATIAL = ["IFCPROJECT", "IFCSITE", "IFCBUILDING", "IFCBUILDINGSTOREY"] as const;
20 const LABEL: Readonly<Record<string, string>> = {
21 IFCPROJECT: "Project", IFCSITE: "Site", IFCBUILDING: "Building", IFCBUILDINGSTOREY: "Storey",
22 };
23
24 export interface TreeNode {
25 readonly type: string;
26 readonly name: string;
27 readonly children: TreeNode[];
28 }
29
30 export interface Model {
31 readonly schema: string[];
32 readonly name: string;
33 readonly description: string;
34 readonly written: string;
35 readonly authors: string[];
36 readonly application: string;
37 readonly tree: TreeNode[];
38 readonly treeMore: number;
39 /** Contained elements by IFC type, most first, at most ELEMENT_TYPES. */
40 readonly elements: [string, number][];
41 readonly elementTotal: number;
42 readonly elementKinds: number;
43 readonly entities: number;
44 }
45
46 /** One statement's text from `from` to the `;` outside quotes; the end index is past the `;`. */
47 function statementEnd(body: string, from: number): number {
48 let inStr = false;
49 for (let i = from; i < body.length; i++) {
50 const c = body[i];
51 if (c === "'") inStr = !inStr;
52 else if (!inStr && c === ";") return i + 1;
53 }
54 return body.length;
55 }
56
57 const refs = (slot: string): number[] => [...slot.matchAll(/#(\d+)/g)].map((m) => Number(m[1]));
58 const text = (slot: string | undefined): string => strings(slot ?? "")[0]?.slice(0, NAME_CHARS) ?? "";
59
60
61 /**
62 * Add `ids` to the list under `key`, in place; the number of ids written (never a copy of the
63 * list).
64 */
65 export function append(map: Map<number, number[]>, key: number, ids: readonly number[]): number {
66 let list = map.get(key);
67 if (list === undefined) map.set(key, (list = []));
68 for (const id of ids) list.push(id);
69 return ids.length;
70 }
71
72 /**
73 * `src` without its block comments, in one pass; an unclosed one stays. `work` counts the
74 * characters looked at.
75 */
76 export function stripComments(src: string, work?: { steps: number }): string {
77 const out: string[] = [];
78 let at = 0;
79 let from = 0;
80 for (;;) {
81 const open = src.indexOf("/*", from);
82 const close = open < 0 ? -1 : src.indexOf("*/", open + 2);
83 if (close < 0) break;
84 if (work) work.steps += close + 2 - from;
85 out.push(src.slice(at, open));
86 at = from = close + 2;
87 }
88 if (work) work.steps += src.length - from;
89 out.push(src.slice(at));
90 return out.join("");
91 }
92
93 /** Read an IFC file's text. Pure. An error string when it is no IFC model. */
94 export function readIfc(source: string): Model | { error: string } {
95 const src = stripComments(source.replace(/^/, ""));
96 if (!/^\s*ISO-10303-21\s*;/.test(src)) return { error: "it does not open with ISO-10303-21" };
97 const start = /\bHEADER\s*;/i.exec(src);
98 if (start === null) return { error: "it has no HEADER section" };
99 const rest = src.slice(start.index + start[0].length);
100 const end = /\bENDSEC\s*;/i.exec(rest);
101 if (end === null) return { error: "its HEADER section never ends" };
102 const header = rest.slice(0, end.index);
103 const afterHeader = rest.slice(end.index + end[0].length);
104 const data = /\bDATA\s*;/i.exec(afterHeader);
105 if (data === null) return { error: "it has no DATA section" };
106 const body = afterHeader.slice(data.index + data[0].length);
107
108 const types = new Map<number, string>();
109 const nodes = new Map<number, { type: string; name: string }>();
110 const children = new Map<number, number[]>();
111 const contained: number[] = [];
112 const head = /#(\d+)\s*=\s*([A-Za-z][A-Za-z0-9_]*)\s*\(/g;
113 let entities = 0;
114 for (let m = head.exec(body); m !== null; m = head.exec(body)) {
115 const id = Number(m[1]);
116 const type = (m[2] ?? "").toUpperCase();
117 entities++;
118 types.set(id, type);
119 const spatial = (SPATIAL as readonly string[]).includes(type);
120 if (!spatial && type !== "IFCRELAGGREGATES" && type !== "IFCRELCONTAINEDINSPATIALSTRUCTURE") continue;
121 const to = statementEnd(body, head.lastIndex);
122 const args = slots(body.slice(head.lastIndex, Math.max(head.lastIndex, to - 2)));
123 head.lastIndex = to;
124 // IfcRoot: GlobalId, OwnerHistory, Name, Description; a relationship then names the parent and
125 // the parts.
126 if (spatial) nodes.set(id, { type, name: text(args[2]) });
127 else if (type === "IFCRELAGGREGATES") {
128 const parent = refs(args[4] ?? "")[0];
129 if (parent !== undefined) append(children, parent, refs(args[5] ?? ""));
130 } else for (const id of refs(args[4] ?? "")) contained.push(id);
131 }
132
133 const seen = new Set<number>();
134 let shown = 0;
135 let more = 0;
136 const walk = (id: number, depth: number): TreeNode | undefined => {
137 const node = nodes.get(id);
138 if (node === undefined || seen.has(id)) return undefined;
139 if (shown >= TREE_NODES || depth > TREE_DEPTH) {
140 more++;
141 return undefined;
142 }
143 seen.add(id);
144 shown++;
145 const out: TreeNode = { ...node, children: [] };
146 for (const c of children.get(id) ?? []) {
147 const kid = walk(c, depth + 1);
148 if (kid !== undefined) out.children.push(kid);
149 }
150 return out;
151 };
152 const tree: TreeNode[] = [];
153 for (const [id, node] of nodes) {
154 if (node.type !== "IFCPROJECT") continue;
155 const root = walk(id, 0);
156 if (root !== undefined) tree.push(root);
157 }
158
159 const counts = new Map<string, number>();
160 const once = new Set<number>();
161 for (const id of contained) {
162 const type = types.get(id);
163 if (type === undefined || once.has(id)) continue;
164 once.add(id);
165 counts.set(type, (counts.get(type) ?? 0) + 1);
166 }
167 const elements = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
168 const fileName = slots(statement(header, "FILE_NAME"));
169 // FILE_NAME: name, time stamp, authors, organisations, preprocessor, originating system,
170 // authorisation.
171 return {
172 schema: strings(statement(header, "FILE_SCHEMA")),
173 name: text(fileName[0]),
174 description: strings(statement(header, "FILE_DESCRIPTION")).join(" · "),
175 written: text(fileName[1]),
176 authors: [...strings(fileName[2] ?? ""), ...strings(fileName[3] ?? "")],
177 application: [text(fileName[5]), text(fileName[4])].filter((s) => s !== "").join(" · "),
178 tree,
179 treeMore: more,
180 elements: elements.slice(0, ELEMENT_TYPES),
181 elementTotal: once.size,
182 elementKinds: elements.length,
183 entities,
184 };
185 }
186
187 export const n = (x: number): string => x.toLocaleString("en");
188 const WORDS = [
189 "air", "annotation", "beam", "boiler", "building", "cable", "carrier", "case", "chimney", "column", "covering",
190 "curtain", "damper", "distribution", "door", "duct", "element", "elementary", "energy", "equipment", "fan",
191 "fastener", "filter", "fitting", "flow", "footing", "furnishing", "furniture", "grid", "heat", "lamp", "light",
192 "member", "mechanical", "opening", "pile", "pipe", "plate", "proxy", "railing", "ramp", "reinforcing", "roof",
193 "segment", "sensor", "shading", "device", "site", "slab", "space", "stair", "standard", "storey", "system",
194 "tank", "terminal", "transport", "valve", "wall", "window", "bar", "mesh", "flight", "stud", "type", "fixture",
195 "sanitary", "geographic", "civil", "port", "pump", "unit", "slab", "way",
196 ].sort((a, b) => b.length - a.length);
197
198 /**
199 * `IFCWALLSTANDARDCASE` as "Wall standard case"; a name it cannot split is its lower-case
200 * remainder.
201 */
202 export function typeWords(type: string): string {
203 const rest = type.toLowerCase().replace(/^ifc/, "");
204 const cut = (at: number, left: number): string[] | undefined => {
205 if (at === rest.length) return [];
206 if (left === 0) return undefined;
207 for (const w of WORDS) {
208 if (!rest.startsWith(w, at)) continue;
209 const tail = cut(at + w.length, left - 1);
210 if (tail !== undefined) return [w, ...tail];
211 }
212 return undefined;
213 };
214 const words = cut(0, 5) ?? [rest];
215 const line = words.join(" ");
216 return line.charAt(0).toUpperCase() + line.slice(1);
217 }
218
219 /** The header facts as label and value, for both doors. */
220 export function ifcFacts(m: Model): [string, string][] {
221 const facts: [string, string][] = [
222 ["Schema", m.schema.join(", ")],
223 ["Name", m.name],
224 ["Description", m.description],
225 ["Written", m.written],
226 ["Author", m.authors.join(" · ")],
227 ["Application", m.application],
228 ];
229 return [...facts.filter(([, v]) => v !== ""), ["Entities", n(m.entities)]];
230 }
231
232 /** The tree flattened, depth first, as `[depth, "Storey", name]`. */
233 export function ifcTreeRows(m: Model): [number, string, string][] {
234 const out: [number, string, string][] = [];
235 const go = (t: TreeNode, d: number): void => {
236 out.push([d, LABEL[t.type] ?? t.type, t.name]);
237 for (const c of t.children) go(c, d + 1);
238 };
239 for (const t of m.tree) go(t, 0);
240 return out;
241 }
242
243 /** The facts the MCP file tool carries beside the content. */
244 export function ifcAbout(m: Model): Record<string, unknown> {
245 const rows = ifcTreeRows(m);
246 const named = (label: string) => rows.filter((r) => r[1] === label).map((r) => r[2]);
247 return {
248 kind: "ifc",
249 schema: m.schema,
250 project: named("Project")[0] ?? "",
251 storeys: named("Storey"),
252 elements: m.elementTotal,
253 elementTypes: Object.fromEntries(m.elements),
254 says: `IFC ${m.schema.join(", ")} · ${n(m.entities)} entities · ${n(named("Storey").length)} storeys · ${n(m.elementTotal)} elements`,
255 };
256 }
257
src/text/step_text.ts added +31
@@ -0,0 +1,31 @@
1 /** The pure reading of STEP (ISO 10303-21) HEADER text, shared by the STEP and IFC readers. */
2
3 const TEXT_CHARS = 200;
4
5 /** The quoted strings of one HEADER statement, `''` read as an apostrophe. */
6 export const strings = (statement: string): string[] =>
7 [...statement.matchAll(/'((?:[^']|'')*)'/g)]
8 .map((m) => (m[1] ?? "").replaceAll("''", "'").trim().slice(0, TEXT_CHARS))
9 .filter((s) => s !== "");
10
11 export const statement = (header: string, name: string): string =>
12 new RegExp(`${name}\\s*\\(([\\s\\S]*?)\\)\\s*;`, "i").exec(header)?.[1] ?? "";
13
14 /** FILE_NAME's slots, split at the commas outside quotes and brackets. */
15 export function slots(args: string): string[] {
16 const out: string[] = [];
17 let depth = 0;
18 let inStr = false;
19 let cur = "";
20 for (const c of args) {
21 if (c === "'") inStr = !inStr;
22 if (!inStr && c === "(") depth++;
23 if (!inStr && c === ")") depth--;
24 if (!inStr && depth === 0 && c === ",") {
25 out.push(cur);
26 cur = "";
27 } else cur += c;
28 }
29 out.push(cur);
30 return out;
31 }
src/tui/screens/workspace.ts +26
@@ -68,6 +68,7 @@ import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts";
6868 import { isKmlPath, kmlTable } from "./kml.ts";
6969 import { pcdFacts } from "../../web/render/pcd.ts";
7070 import { gcodeFacts, parseGcode } from "../../web/render/gcode.ts";
71 import { ifcFacts, ifcTreeRows, readIfc, typeWords } from "../../text/ifc.ts";
7172 import { readStep, stepFacts } from "../../web/render/step.ts";
7273 import { parseOtio } from "../../web/render/otio.ts";
7374 import { parseEdl } from "../../web/render/edl.ts";
@@ -853,6 +854,26 @@ function stepTable(source: string): Table | string {
853854 return { header: ["Fact", "Value"], rows, more: card.moreProducts, delimiter: ",", columns: 2 };
854855 }
855856
857 /**
858 * `.ifc`: a building model, drawn as its header facts, spatial tree and element counts. Shares the
859 * reader.
860 */
861 function isIfcPath(path: string): boolean {
862 return /\.ifc$/i.test(path);
863 }
864
865 function ifcTable(source: Uint8Array): Table | string {
866 if (source.length > RENDER_CAP.ifc) return "not drawn as a building model: it is too large to summarise";
867 const m = readIfc(new TextDecoder().decode(source));
868 if ("error" in m) return `not drawn as a building model: ${m.error}`;
869 const rows: string[][] = [
870 ...ifcFacts(m).map(([k, v]) => [k, v]),
871 ...ifcTreeRows(m).map(([d, level, name]) => [`${" ".repeat(d)}${level}`, name === "" ? "no name" : name]),
872 ...m.elements.map(([t, c]) => [typeWords(t), c.toLocaleString("en")]),
873 ];
874 return { header: ["Fact", "Value"], rows, more: m.treeMore, delimiter: ",", columns: 2 };
875 }
876
856877 /** `.geojson`: features, drawn as a table of their geometry type and properties. */
857878 function isGeoJsonPath(path: string): boolean {
858879 return /\.geojson$/i.test(path);
@@ -1197,6 +1218,11 @@ class Tab {
11971218 this.table = typeof part === "string" ? null : part;
11981219 this.fault = typeof part === "string" ? part : "";
11991220 if (this.table !== null) this.grid = layoutTable(this.table);
1221 } else if (isIfcPath(this.path)) {
1222 const model = ifcTable(source);
1223 this.table = typeof model === "string" ? null : model;
1224 this.fault = typeof model === "string" ? model : "";
1225 if (this.table !== null) this.grid = layoutTable(this.table);
12001226 } else if (isGeoJsonPath(this.path)) {
12011227 this.table = geoJsonTable(new TextDecoder().decode(source));
12021228 if (this.table !== null) this.grid = layoutTable(this.table);
src/web/render/ifc-css.ts added +4
@@ -0,0 +1,4 @@
1 /** The IFC spatial tree's indent, apart from `ifc.ts` so `style.ts` imports no renderer. */
2
3 /** One step of indent per level of the tree (`TREE_DEPTH` is 6), on the label only. */
4 export const ifcCss = /* css */ `@layer content{${[1, 2, 3, 4, 5, 6].map((d) => `.ifc-depth-${d}>dt{padding-inline-start:${d * 1.5}ch}`).join("")}}`;
src/web/render/ifc.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * An IFC building model (`.ifc`) as its header, its spatial tree and a table of the element types
3 * with counts. The reading is `src/text/ifc.ts`; this only draws it. Every value is escaped by
4 * `html`.
5 */
6
7 import { html } from "../html.ts";
8 import type { Rendered, RenderInput } from "./renderers.ts";
9 import { RENDER_CAP } from "./kinds.ts";
10 import { fileSize } from "../ui.ts";
11 import { emptyNote } from "../empty_words.ts";
12 import { ifcFacts, ifcTreeRows, n, readIfc, typeWords } from "../../text/ifc.ts";
13
14 const rows = (list: [string, string][]) =>
15 html`${list.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}`;
16
17 /**
18 * A tree row: the level is the label, the depth is the row's class (`ifc-depth-N`, `ifc-css.ts`).
19 */
20 const treeRows = (list: [number, string, string][]) =>
21 html`${list.map(([d, level, name]) => html`<div class="status-row ifc-depth-${String(d)}"><dt>${level}</dt><dd>${name === "" ? "no name" : name}</dd></div>`)}`;
22
23 export function ifc(input: RenderInput): Rendered {
24 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
25 if (input.size > RENDER_CAP.ifc || input.body.length > RENDER_CAP.ifc) return fall("it is too large to summarise");
26 const m = readIfc(new TextDecoder().decode(input.body));
27 if ("error" in m) return fall(m.error);
28 const content = html`<section>
29 <dl class="status-rows">${rows(ifcFacts(m))}</dl>
30 <h3>Spatial tree</h3>
31 ${m.tree.length > 0
32 ? html`<dl class="status-rows" aria-label="Spatial tree">${treeRows(ifcTreeRows(m))}</dl>${m.treeMore > 0 ? html`<p class="muted small">${n(m.treeMore)} more not shown</p>` : html``}`
33 : emptyNote("noProjectInThisFile")}
34 <h3>Elements</h3>
35 ${m.elements.length > 0
36 ? html`<dl class="status-rows" aria-label="Elements">${rows(m.elements.map(([t, c]) => [typeWords(t), n(c)]))}</dl>${m.elementKinds > m.elements.length ? html`<p class="muted small">${n(m.elementKinds - m.elements.length)} more types</p>` : html``}`
37 : emptyNote("noElementsPlacedInAStorey")}
38 </section>`;
39 return { content, lines: 0, summary: `${n(m.elementTotal)} elements · ${fileSize(input.size)}` };
40 }
src/web/render/kinds.ts +8 −1
@@ -73,6 +73,7 @@ export type FileKind =
7373 | "excalidraw"
7474 | "step"
7575 | "iges"
76 | "ifc"
7677 | "prproj"
7778 | "sarif"
7879 | "lcov"
@@ -183,6 +184,7 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
183184 excalidraw: 1 * MB,
184185 step: 5 * MB,
185186 iges: 5 * MB,
187 ifc: 5 * MB,
186188 // The compressed size; the inflated text is capped again in `prproj.ts`.
187189 prproj: 10 * MB,
188190 sarif: 5 * MB,
@@ -357,6 +359,7 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
357359 stp: "step",
358360 iges: "iges",
359361 igs: "iges",
362 ifc: "ifc",
360363 sarif: "sarif",
361364 opml: "opml",
362365 rss: "feed",
@@ -477,7 +480,10 @@ const isKicadHead = (head: Uint8Array): boolean => /^\uFEFF?\s*\(\s*kicad_pcb[\s
477480 export const isUsdaHead = (head: Uint8Array): boolean =>
478481 /^\uFEFF?#usda\s+\d/.test(new TextDecoder().decode(head.subarray(0, 32)));
479482
480 /** A STEP file opens on `ISO-10303-21;`; a `.step` or `.stp` without it stays text. */
483 /**
484 * A STEP file (and an IFC model, which is one) opens on `ISO-10303-21;`; a `.step` or `.stp`
485 * without it stays text.
486 */
481487 const isStepHead = (head: Uint8Array): boolean =>
482488 /^\uFEFF?\s*ISO-10303-21\s*;/.test(new TextDecoder().decode(head.subarray(0, 64)));
483489
@@ -628,6 +634,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
628634 // A Kdenlive project is MLT XML: a `.kdenlive` whose root is not `<mlt>` is only text.
629635 if (ext === "kdenlive") return isMltHead(head) ? "kdenlive" : "text";
630636 if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text";
637 if (ext === "ifc") return isStepHead(head) ? "ifc" : "text";
631638 if (ext === "iges" || ext === "igs") return isIgesHead(head) ? "iges" : "text";
632639 if (ext === "gbr" || ext === "gtl" || ext === "gbl") return isGerberHead(head) ? "gerber" : "text";
633640 if (ext === "kicad_pcb") return isKicadHead(head) ? "kicad" : "text";
src/web/render/renderers.ts +2
@@ -34,6 +34,7 @@ import { kicad } from "./kicad.ts";
3434 import { drawio, excalidraw, mermaid } from "./diagram.ts";
3535 import { step } from "./step.ts";
3636 import { iges } from "./iges.ts";
37 import { ifc } from "./ifc.ts";
3738 import { prproj } from "./prproj.ts";
3839 import { gcode } from "./gcode.ts";
3940 import { gpx } from "./gpx.ts";
@@ -171,6 +172,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
171172 excalidraw,
172173 step,
173174 iges,
175 ifc,
174176 prproj,
175177 geojson,
176178 kml,
src/web/render/step.ts +3 −28
@@ -13,6 +13,9 @@ import { html } from "../html.ts";
1313 import type { Rendered, RenderInput } from "./renderers.ts";
1414 import { RENDER_CAP } from "./kinds.ts";
1515 import { fileSize } from "../ui.ts";
16 import { slots, statement, strings } from "../../text/step_text.ts";
17
18 export { slots, statement, strings };
1619
1720 export const TOP_TYPES = 20;
1821 export const PRODUCT_CAP = 50;
@@ -38,34 +41,6 @@ export interface Card {
3841 readonly unit: string;
3942 }
4043
41 /** The quoted strings of one HEADER statement, `''` read as an apostrophe. */
42 const strings = (statement: string): string[] =>
43 [...statement.matchAll(/'((?:[^']|'')*)'/g)]
44 .map((m) => (m[1] ?? "").replaceAll("''", "'").trim().slice(0, TEXT_CHARS))
45 .filter((s) => s !== "");
46
47 const statement = (header: string, name: string): string =>
48 new RegExp(`${name}\\s*\\(([\\s\\S]*?)\\)\\s*;`, "i").exec(header)?.[1] ?? "";
49
50 /** FILE_NAME's slots, split at the commas outside quotes and brackets. */
51 function slots(args: string): string[] {
52 const out: string[] = [];
53 let depth = 0;
54 let inStr = false;
55 let cur = "";
56 for (const c of args) {
57 if (c === "'") inStr = !inStr;
58 if (!inStr && c === "(") depth++;
59 if (!inStr && c === ")") depth--;
60 if (!inStr && depth === 0 && c === ",") {
61 out.push(cur);
62 cur = "";
63 } else cur += c;
64 }
65 out.push(cur);
66 return out;
67 }
68
6944 const SI_PREFIX: Readonly<Record<string, string>> = {
7045 MILLI: "milli", CENTI: "centi", KILO: "kilo", MICRO: "micro", DECI: "deci",
7146 };
src/web/style.ts +2
@@ -28,6 +28,7 @@ import { homeFlowCss } from "./pages/home_flow_style.ts";
2828 import { base, layers, reset, utilities } from "./style/base.ts";
2929 import { components } from "./style/components.ts";
3030 import { content } from "./style/content.ts";
31 import { ifcCss } from "./render/ifc-css.ts";
3132 import { gcodeCss } from "./render/gcode-css.ts";
3233 import { pcdCss } from "./render/pcd-css.ts";
3334 import { model3dCss } from "./render/model3d-css.ts";
@@ -47,6 +48,7 @@ export const css = [
4748 content,
4849 model3dCss,
4950 gcodeCss,
51 ifcCss,
5052 pcdCss,
5153 utilities,
5254 pickCss,
test/fuzz-renderers.test.ts +5
@@ -7,6 +7,7 @@
77 * (`FUZZ_SEED`, `FUZZ_RUNS`): a failure prints the seed and the shrunk case,
88 * to be kept in test/fuzz-found.test.ts.
99 */
10 import { IFC } from "./helpers/ifc.ts";
1011 import { describe, expect, test } from "bun:test";
1112 import { RENDERERS, type Renderer } from "../src/web/render/renderers.ts";
1213 import { fuzz, int, mix, pick, rng, SEED, type Rand } from "./helpers/fuzz.ts";
@@ -366,6 +367,10 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
366367 path: "part.igs",
367368 files: [igesFile()],
368369 },
370 ifc: {
371 path: "house.ifc",
372 files: [IFC],
373 },
369374 step: {
370375 path: "part.step",
371376 files: [
test/helpers/ifc.ts added +26
@@ -0,0 +1,26 @@
1 /** A small valid IFC file: one project, site, building, two storeys, and three placed elements. */
2 export const IFC = [
3 "ISO-10303-21;",
4 "HEADER;",
5 "FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1');",
6 "FILE_NAME('house.ifc','2026-01-02T03:04:05',('Ada <b>L</b>'),('Acme'),'Preproc 1','Revit 2026','');",
7 "FILE_SCHEMA(('IFC4'));",
8 "ENDSEC;",
9 "DATA;",
10 "#1=IFCPROJECT('0a',$,'Demo <script>x</script>',$,$,$,$,$,$);",
11 "#2=IFCSITE('0b',$,'Site; one',$,$,$,$,$,.ELEMENT.,$,$,$,$,$);",
12 "#3=IFCBUILDING('0c',$,'Main',$,$,$,$,$,.ELEMENT.,$,$,$);",
13 "#4=IFCBUILDINGSTOREY('0d',$,'Ground',$,$,$,$,$,.ELEMENT.,0.);",
14 "#5=IFCBUILDINGSTOREY('0e',$,'First',$,$,$,$,$,.ELEMENT.,3000.);",
15 "#6=IFCRELAGGREGATES('1a',$,$,$,#1,(#2));",
16 "#7=IFCRELAGGREGATES('1b',$,$,$,#2,(#3));",
17 "#8=IFCRELAGGREGATES('1c',$,$,$,#3,(#4,#5));",
18 "#10=IFCWALL('2a',$,'W1',$,$,$,$,$,$);",
19 "#11=IFCWALL('2b',$,'W2',$,$,$,$,$,$);",
20 "#12=IFCDOOR('2c',$,'D1',$,$,$,$,$,$,$,$);",
21 "#13=IFCCARTESIANPOINT((0.,0.,0.));",
22 "#14=IFCRELCONTAINEDINSPATIALSTRUCTURE('3a',$,$,$,(#10,#11,#12),#4);",
23 "ENDSEC;",
24 "END-ISO-10303-21;",
25 "",
26 ].join("\n");
test/llms-budget.test.ts +4 −2
@@ -51,9 +51,11 @@ const get = async (token?: string): Promise<string> =>
5151 * `stopped`; main had grown to within 22 bytes of the admin ceiling. Raised at #15866: main (the
5252 * route catalogue after #15676 and #15782, the fork routes) measured anonymous 9,114, signed-in
5353 * 82,445 and admin past 94,100, over the ceilings with no pull at fault; anonymous 9,250,
54 * signed-in 83,300, admin 95,300 are those sizes plus about a percent.
54 * signed-in 83,300, admin 95,300 are those sizes plus about a percent. Raised at #16020: main
55 * measured signed-in 83,283 and admin 95,000, within 17 bytes of the ceiling before the pull's
56 * `.ifc` note on read_file; signed-in 84,100 and admin 96,000 (anonymous unchanged).
5557 */
56 const BUDGET = { anonymous: 9_250, signedIn: 83_300, admin: 95_300 } as const;
58 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 96_000 } as const;
5759
5860 /** Sections are cut at "## " headings; the lead before the first one is its own. */
5961 function sections(text: string): { name: string; bytes: number }[] {
test/mcp-read-file.test.ts +13
@@ -11,6 +11,7 @@ import { createUser } from "../src/core/users.ts";
1111 import { serve, type Servers } from "../src/http/server.ts";
1212 import { quietLogs } from "./helpers/globals.ts";
1313 import { box, concat, ftyp, mvhd0, tkhd } from "./helpers/mp4-boxes.ts";
14 import { IFC } from "./helpers/ifc.ts";
1415 import { make as xcfFile } from "./helpers/xcf.ts";
1516 import { asciiBox, binaryBox } from "./helpers/stl.ts";
1617
@@ -65,6 +66,8 @@ beforeAll(async () => {
6566 for (const r of [pub, priv])
6667 ok(await commitToBranch(app, owner, r, { message: "seed", files: [
6768 { path: "src/a.txt", content: "hello\n" },
69 { path: "house.ifc", content: IFC },
70 { path: "broken.ifc", content: "not a model" },
6871 { path: "bad.json", content: '{\n "a": }' },
6972 { path: "good.json", content: "{}" },
7073 ] }));
@@ -169,6 +172,16 @@ test("a config file says whether it parses; other files carry no about", async (
169172 expect((await read(t, { repo: "ada/pub", path: "src/a.txt" })).value.about).toBeUndefined();
170173 });
171174
175 test("an IFC file that is no model says why, in its about", async () => {
176 const f = (await read(tok["stranger"]!, { repo: "ada/pub", path: "broken.ifc" })).value;
177 expect(f.about).toEqual({ kind: "ifc", says: "IFC, unreadable: it does not open with ISO-10303-21" });
178 });
179
180 test("an IFC file carries its schema, storeys and element counts", async () => {
181 const f = (await read(tok["stranger"]!, { repo: "ada/pub", path: "house.ifc" })).value;
182 expect(f.about).toMatchObject({ kind: "ifc", storeys: ["Ground", "First"], elements: 3 });
183 });
184
172185 test("a .xcf file carries its canvas and layers as about, or says it is unreadable", async () => {
173186 const file = (await read(tok["stranger"]!, { repo: "ada/pub", path: "art.xcf" })).value;
174187 expect(file.about).toMatchObject({ kind: "xcf", width: 64, height: 48, mode: "RGB", layerCount: 1 });
test/render-ifc.test.ts added +122
@@ -0,0 +1,122 @@
1 /** IFC building models as header, spatial tree and element counts. */
2 import { describe, expect, test } from "bun:test";
3 import { ifc } from "../src/web/render/ifc.ts";
4 import { append, ifcAbout, readIfc, stripComments, TREE_NODES, typeWords } from "../src/text/ifc.ts";
5 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
6 import { RENDERERS } from "../src/web/render/renderers.ts";
7 import { IFC } from "./helpers/ifc.ts";
8
9 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
10 const draw = (text: string, size = text.length) => ifc({ path: "a.ifc", size, body: enc(text), media: "/m", download: "/d" });
11 const model = (text: string) => {
12 const m = readIfc(text);
13 if ("error" in m) throw new Error(m.error);
14 return m;
15 };
16
17 describe("ifc", () => {
18 test("registered, by extension and by its first bytes", () => {
19 expect(fileKind("a.ifc", enc(IFC))).toBe("ifc");
20 expect(fileKind("a.IFC", enc(IFC))).toBe("ifc");
21 expect(fileKind("a.ifc", enc("hello\n"))).toBe("text");
22 expect(fileKind("a.txt", enc(IFC))).toBe("text");
23 expect(RENDERERS.ifc).toBe(ifc);
24 expect(RENDER_CAP.ifc).toBeGreaterThan(0);
25 });
26
27 test("parse: header, tree and element counts", () => {
28 const m = model(IFC);
29 expect(m.schema).toEqual(["IFC4"]);
30 expect(m.application).toBe("Revit 2026 · Preproc 1");
31 expect(m.elements).toEqual([["IFCWALL", 2], ["IFCDOOR", 1]]);
32 const out = String(draw(IFC).content);
33 expect(out).toContain("IFC4");
34 expect(out).toContain("Site; one");
35 expect(out).toContain('<div class="status-row ifc-depth-2"><dt>Building</dt><dd>Main</dd></div>');
36 expect(out).toContain("<dt>Wall</dt><dd>2</dd>");
37 expect(out).not.toContain("›");
38 expect(String(draw(IFC).summary)).toContain("3 elements");
39 });
40
41 test("escape: every value from the file is escaped", () => {
42 const out = String(draw(IFC).content);
43 expect(out).not.toContain("<script");
44 expect(out).not.toContain("<b>L");
45 expect(out).toContain("&lt;script&gt;");
46 });
47
48 test("cap: a file over the cap keeps the source and says why", () => {
49 const r = draw(IFC, RENDER_CAP.ifc + 1);
50 expect(r.fallback).toContain("too large");
51 });
52
53 test("malformed: no header, or no data, keeps the source and says why", () => {
54 expect(draw("hello").fallback).toContain("ISO-10303-21");
55 expect(draw("ISO-10303-21;\nDATA;\n").fallback).toContain("HEADER");
56 expect(draw("ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('IFC4'));\n").fallback).toContain("never ends");
57 expect(draw("ISO-10303-21;\nHEADER;\nENDSEC;\n").fallback).toContain("no DATA");
58 });
59
60 test("hostile: a cycle ends, and a huge tree is cut", () => {
61 const cyc = IFC.replace("#8=", "#9=IFCRELAGGREGATES('1d',$,$,$,#5,(#1));\n#8=");
62 expect(model(cyc).tree.length).toBe(1);
63 const parts = Array.from({ length: TREE_NODES + 50 }, (_, i) => `#${100 + i}=IFCBUILDINGSTOREY('x',$,'S${i}',$);`).join("\n");
64 const rel = `#99=IFCRELAGGREGATES('r',$,$,$,#3,(${Array.from({ length: TREE_NODES + 50 }, (_, i) => `#${100 + i}`).join(",")}));`;
65 const m = model(IFC.replace("ENDSEC;\nEND", `${parts}\n${rel}\nENDSEC;\nEND`));
66 const count = (t: { children: unknown[] }): number => 1 + (t.children as { children: unknown[] }[]).reduce((a, c) => a + count(c), 0);
67 expect(count(m.tree[0]!)).toBeLessThanOrEqual(TREE_NODES);
68 expect(m.treeMore).toBeGreaterThan(0);
69 });
70
71 test("hostile: unterminated statements stay linear", () => {
72 const body = "#1=IFCRELAGGREGATES('x',$,$,$,#2,(#3".repeat(20000);
73 expect("error" in readIfc(`ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n${body}`)).toBe(false);
74 });
75
76 test("hostile: unclosed comment openers are one pass, by work counted", () => {
77 const src = "/* ".repeat(100_000);
78 const work = { steps: 0 };
79 expect(stripComments(src, work)).toBe(src);
80 expect(work.steps).toBeLessThanOrEqual(src.length);
81 const mixed = "a/* c */b/*x*/c".repeat(1000);
82 const w2 = { steps: 0 };
83 expect(stripComments(mixed, w2)).toBe("abc".repeat(1000));
84 expect(w2.steps).toBeLessThanOrEqual(mixed.length);
85 expect("error" in readIfc(`${src}ISO-10303-21;`)).toBe(true);
86 });
87
88 test("hostile: many relations on one parent append to one list, never copy it", () => {
89 const map = new Map<number, number[]>();
90 let written = 0;
91 for (let i = 0; i < 50_000; i++) written += append(map, 1, [i, i + 1]);
92 expect(written).toBe(100_000);
93 expect(map.get(1)!.length).toBe(100_000);
94 const first = map.get(1);
95 append(map, 1, [7]);
96 expect(map.get(1)).toBe(first);
97 const rels = Array.from({ length: 5000 }, (_, i) => `#${i + 100}=IFCRELAGGREGATES('r',$,$,$,#3,(#${i + 20000}));`).join("\n");
98 const m = model(IFC.replace("ENDSEC;\nEND", `${rels}\nENDSEC;\nEND`));
99 expect(m.entities).toBeGreaterThan(5000);
100 const big = `(${Array.from({ length: 300_000 }, (_, i) => `#${i + 900000}`).join(",")})`;
101 expect(model(IFC.replace("(#10,#11,#12)", big)).elementTotal).toBe(0);
102 });
103
104 test("words: a type name is split into plain words", () => {
105 expect(typeWords("IFCWALLSTANDARDCASE")).toBe("Wall standard case");
106 expect(typeWords("IFCDOOR")).toBe("Door");
107 expect(typeWords("IFCQQQ")).toBe("Qqq");
108 });
109
110 test("tree: the level is the label and the depth a class", () => {
111 const out = String(draw(IFC).content);
112 expect(out).toContain('<div class="status-row ifc-depth-0"><dt>Project</dt>');
113 expect(out).toContain('<dt>Storey</dt><dd>Ground</dd>');
114 expect(out).not.toContain("(unnamed)");
115 });
116
117 test("about: the facts for the MCP file tool", () => {
118 const about = ifcAbout(model(IFC));
119 expect(about).toMatchObject({ kind: "ifc", schema: ["IFC4"], storeys: ["Ground", "First"], elements: 3, elementTypes: { IFCWALL: 2, IFCDOOR: 1 } });
120 expect(about["says"]).toContain("2 storeys");
121 });
122 });
test/render-kinds.test.ts +1
@@ -116,6 +116,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
116116 drawio: [enc("<mxfile/>"), "drawio", "application/octet-stream"],
117117 excalidraw: [enc("{}"), "excalidraw", "application/octet-stream"],
118118 step: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
119 ifc: [enc("ISO-10303-21;\nHEADER;\n"), "ifc", "application/octet-stream"],
119120 iges: [igesHead, "iges", "application/octet-stream"],
120121 igs: [igesHead, "iges", "application/octet-stream"],
121122 stp: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
test/tui-workspace-formats-more.test.ts +19
@@ -11,6 +11,7 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1111 import type { App as Forge } from "../src/app.ts";
1212 import type { User } from "../src/core/users.ts";
1313 import { zip } from "./helpers/zip.ts";
14 import { IFC } from "./helpers/ifc.ts";
1415 import { quietLogs } from "./helpers/globals.ts";
1516 import { workspaceFixture, type Fixture } from "./helpers/tui-workspace.ts";
1617
@@ -279,6 +280,24 @@ describe("the terminal workspace, by file type", () => {
279280 }
280281 });
281282
283 test("an .ifc opens as its facts, tree and element counts, sharing the reader", async () => {
284 const made = await createRepo(forge, alice, { name: "houses", visibility: "public", description: "bim" });
285 if (!made.ok) throw new Error("repo failed");
286 await commitToBranch(forge, alice, made.value, { message: "seed", files: [{ path: "h.ifc", content: IFC }] });
287 const h = boot();
288 try {
289 await h.settle();
290 await open(h, "houses");
291 await openFile(h, "h.ifc");
292 expect(h.text()).toContain("IFC4");
293 expect(h.text()).toContain("Storey");
294 expect(h.text()).toContain("Ground");
295 expect(h.text()).toContain("Wall");
296 } finally {
297 h.stop();
298 }
299 });
300
282301 test("a .geojson opens as its features table, sharing the web parser, and s flips to the source", async () => {
283302 const made = await createRepo(forge, alice, { name: "places", visibility: "public", description: "geo" });
284303 if (!made.ok) throw new Error("repo failed");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs