bimdown-cli 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -0
- package/dist/index.js +2028 -0
- package/dist/index.js.map +1 -0
- package/package.json +52 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2028 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// src/schema/loader.ts
|
|
13
|
+
import { readFileSync, readdirSync, statSync } from "fs";
|
|
14
|
+
import { join } from "path";
|
|
15
|
+
import { parse as parseYaml } from "yaml";
|
|
16
|
+
function loadAllSchemas(specDir) {
|
|
17
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
18
|
+
walkYaml(specDir, schemas);
|
|
19
|
+
return schemas;
|
|
20
|
+
}
|
|
21
|
+
function walkYaml(dir, schemas) {
|
|
22
|
+
for (const entry of readdirSync(dir)) {
|
|
23
|
+
const full = join(dir, entry);
|
|
24
|
+
if (statSync(full).isDirectory()) {
|
|
25
|
+
walkYaml(full, schemas);
|
|
26
|
+
} else if (entry.endsWith(".yaml") || entry.endsWith(".yml")) {
|
|
27
|
+
const raw = parseYaml(readFileSync(full, "utf-8"));
|
|
28
|
+
if (raw?.name) schemas.set(raw.name, raw);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function resolveFields(name, schemas, resolved = /* @__PURE__ */ new Map()) {
|
|
33
|
+
if (resolved.has(name)) return resolved.get(name);
|
|
34
|
+
const schema = schemas.get(name);
|
|
35
|
+
if (!schema) throw new Error(`Unknown schema: ${name}`);
|
|
36
|
+
const fields = [];
|
|
37
|
+
const seen = /* @__PURE__ */ new Set();
|
|
38
|
+
for (const baseName of schema.bases ?? []) {
|
|
39
|
+
for (const f of resolveFields(baseName, schemas, resolved)) {
|
|
40
|
+
if (!seen.has(f.name)) {
|
|
41
|
+
seen.add(f.name);
|
|
42
|
+
fields.push(f);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
for (const raw of schema.fields ?? []) {
|
|
47
|
+
const rf = normalizeField(raw);
|
|
48
|
+
const idx = fields.findIndex((f) => f.name === rf.name);
|
|
49
|
+
if (idx >= 0) {
|
|
50
|
+
fields[idx] = rf;
|
|
51
|
+
} else {
|
|
52
|
+
fields.push(rf);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
resolved.set(name, fields);
|
|
56
|
+
return fields;
|
|
57
|
+
}
|
|
58
|
+
function normalizeField(raw) {
|
|
59
|
+
return {
|
|
60
|
+
name: raw.name,
|
|
61
|
+
type: raw.type,
|
|
62
|
+
required: raw.required ?? false,
|
|
63
|
+
computed: raw.computed ?? false,
|
|
64
|
+
reference: raw.reference,
|
|
65
|
+
values: raw.values
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
var init_loader = __esm({
|
|
69
|
+
"src/schema/loader.ts"() {
|
|
70
|
+
"use strict";
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// src/schema/registry.ts
|
|
75
|
+
import { join as join2, dirname } from "path";
|
|
76
|
+
import { fileURLToPath } from "url";
|
|
77
|
+
function buildRegistry(specDir) {
|
|
78
|
+
if (_registry && _specDir === specDir) return _registry;
|
|
79
|
+
const schemas = loadAllSchemas(join2(specDir, "csv-schema"));
|
|
80
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
81
|
+
const registry = /* @__PURE__ */ new Map();
|
|
82
|
+
for (const [name, schema] of schemas) {
|
|
83
|
+
if (schema.abstract) continue;
|
|
84
|
+
const prefix = ID_PREFIXES[name];
|
|
85
|
+
if (!prefix) continue;
|
|
86
|
+
const allFields = resolveFields(name, schemas, resolved);
|
|
87
|
+
const csvFields = allFields.filter((f) => !f.computed);
|
|
88
|
+
const computedFields = allFields.filter((f) => f.computed);
|
|
89
|
+
registry.set(name, {
|
|
90
|
+
name,
|
|
91
|
+
prefix,
|
|
92
|
+
hostType: schema.host_type,
|
|
93
|
+
allFields,
|
|
94
|
+
csvFields,
|
|
95
|
+
computedFields
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
_registry = registry;
|
|
99
|
+
_specDir = specDir;
|
|
100
|
+
return registry;
|
|
101
|
+
}
|
|
102
|
+
function getSpecDir() {
|
|
103
|
+
if (process.env.SPEC_DIR) return process.env.SPEC_DIR;
|
|
104
|
+
const thisFile = fileURLToPath(import.meta.url);
|
|
105
|
+
const thisDir = dirname(thisFile);
|
|
106
|
+
return join2(thisDir, "..", "..", "spec");
|
|
107
|
+
}
|
|
108
|
+
var ID_PREFIXES, GLOBAL_ONLY_TABLES, TABLES_WITHOUT_SVG, SVG_FILE_NAMES, TABLES_WITH_SVG, _registry, _specDir;
|
|
109
|
+
var init_registry = __esm({
|
|
110
|
+
"src/schema/registry.ts"() {
|
|
111
|
+
"use strict";
|
|
112
|
+
init_loader();
|
|
113
|
+
ID_PREFIXES = {
|
|
114
|
+
level: "lv",
|
|
115
|
+
grid: "gr",
|
|
116
|
+
wall: "w",
|
|
117
|
+
column: "c",
|
|
118
|
+
slab: "sl",
|
|
119
|
+
space: "sp",
|
|
120
|
+
door: "d",
|
|
121
|
+
window: "wn",
|
|
122
|
+
stair: "st",
|
|
123
|
+
ramp: "rp",
|
|
124
|
+
railing: "rl",
|
|
125
|
+
room_separator: "rs",
|
|
126
|
+
curtain_wall: "cw",
|
|
127
|
+
roof: "ro",
|
|
128
|
+
ceiling: "cl",
|
|
129
|
+
opening: "op",
|
|
130
|
+
structure_wall: "sw",
|
|
131
|
+
structure_column: "sc",
|
|
132
|
+
structure_slab: "ss",
|
|
133
|
+
beam: "bm",
|
|
134
|
+
brace: "br",
|
|
135
|
+
foundation: "f",
|
|
136
|
+
duct: "du",
|
|
137
|
+
pipe: "pi",
|
|
138
|
+
cable_tray: "ct",
|
|
139
|
+
conduit: "co",
|
|
140
|
+
equipment: "eq",
|
|
141
|
+
terminal: "tm",
|
|
142
|
+
mep_node: "mn",
|
|
143
|
+
mesh: "ms"
|
|
144
|
+
};
|
|
145
|
+
GLOBAL_ONLY_TABLES = /* @__PURE__ */ new Set(["level", "grid", "mesh"]);
|
|
146
|
+
TABLES_WITHOUT_SVG = /* @__PURE__ */ new Set(["level", "grid", "door", "window", "space", "mesh"]);
|
|
147
|
+
SVG_FILE_NAMES = Object.fromEntries(
|
|
148
|
+
Object.keys(ID_PREFIXES).filter((k) => !TABLES_WITHOUT_SVG.has(k)).map((k) => [k, k])
|
|
149
|
+
);
|
|
150
|
+
TABLES_WITH_SVG = new Set(Object.keys(SVG_FILE_NAMES));
|
|
151
|
+
_registry = null;
|
|
152
|
+
_specDir = null;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// src/utils/fs.ts
|
|
157
|
+
import { readdirSync as readdirSync2, statSync as statSync2, existsSync } from "fs";
|
|
158
|
+
import { join as join3 } from "path";
|
|
159
|
+
function discoverLayout(dir) {
|
|
160
|
+
const globalDir = join3(dir, "global");
|
|
161
|
+
const levelDirs = [];
|
|
162
|
+
if (existsSync(dir) && statSync2(dir).isDirectory()) {
|
|
163
|
+
for (const entry of readdirSync2(dir)) {
|
|
164
|
+
if (entry === "global" || entry.startsWith(".")) continue;
|
|
165
|
+
const full = join3(dir, entry);
|
|
166
|
+
if (statSync2(full).isDirectory()) {
|
|
167
|
+
levelDirs.push({ name: entry, path: full });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return { root: dir, globalDir, levelDirs };
|
|
172
|
+
}
|
|
173
|
+
function listFiles(dir) {
|
|
174
|
+
if (!existsSync(dir)) return [];
|
|
175
|
+
return readdirSync2(dir).filter((f) => {
|
|
176
|
+
const full = join3(dir, f);
|
|
177
|
+
return statSync2(full).isFile();
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
var init_fs = __esm({
|
|
181
|
+
"src/utils/fs.ts"() {
|
|
182
|
+
"use strict";
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// src/utils/csv.ts
|
|
187
|
+
import { readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
188
|
+
function readCsv(filePath) {
|
|
189
|
+
let text = readFileSync2(filePath, "utf-8");
|
|
190
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
191
|
+
const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
|
|
192
|
+
if (lines.length === 0) return { headers: [], rows: [] };
|
|
193
|
+
const headers = parseCsvLine(lines[0]);
|
|
194
|
+
const rows = lines.slice(1).map((line) => {
|
|
195
|
+
const values = parseCsvLine(line);
|
|
196
|
+
const row = {};
|
|
197
|
+
for (let i = 0; i < headers.length; i++) {
|
|
198
|
+
row[headers[i]] = values[i] ?? "";
|
|
199
|
+
}
|
|
200
|
+
return row;
|
|
201
|
+
});
|
|
202
|
+
return { headers, rows };
|
|
203
|
+
}
|
|
204
|
+
function parseCsvLine(line) {
|
|
205
|
+
const result = [];
|
|
206
|
+
let current = "";
|
|
207
|
+
let inQuotes = false;
|
|
208
|
+
for (let i = 0; i < line.length; i++) {
|
|
209
|
+
const ch = line[i];
|
|
210
|
+
if (inQuotes) {
|
|
211
|
+
if (ch === '"') {
|
|
212
|
+
if (i + 1 < line.length && line[i + 1] === '"') {
|
|
213
|
+
current += '"';
|
|
214
|
+
i++;
|
|
215
|
+
} else {
|
|
216
|
+
inQuotes = false;
|
|
217
|
+
}
|
|
218
|
+
} else {
|
|
219
|
+
current += ch;
|
|
220
|
+
}
|
|
221
|
+
} else {
|
|
222
|
+
if (ch === '"') {
|
|
223
|
+
inQuotes = true;
|
|
224
|
+
} else if (ch === ",") {
|
|
225
|
+
result.push(current);
|
|
226
|
+
current = "";
|
|
227
|
+
} else {
|
|
228
|
+
current += ch;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
result.push(current);
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
function writeCsv(filePath, data) {
|
|
236
|
+
const lines = [data.headers.join(",")];
|
|
237
|
+
for (const row of data.rows) {
|
|
238
|
+
const values = data.headers.map((h) => escapeCsvValue(row[h] ?? ""));
|
|
239
|
+
lines.push(values.join(","));
|
|
240
|
+
}
|
|
241
|
+
writeFileSync(filePath, lines.join("\n") + "\n", "utf-8");
|
|
242
|
+
}
|
|
243
|
+
function escapeCsvValue(val) {
|
|
244
|
+
if (val.includes(",") || val.includes('"') || val.includes("\n")) {
|
|
245
|
+
return '"' + val.replace(/"/g, '""') + '"';
|
|
246
|
+
}
|
|
247
|
+
return val;
|
|
248
|
+
}
|
|
249
|
+
var init_csv = __esm({
|
|
250
|
+
"src/utils/csv.ts"() {
|
|
251
|
+
"use strict";
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
// src/utils/svg.ts
|
|
256
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
257
|
+
import { XMLParser } from "fast-xml-parser";
|
|
258
|
+
function parseSvgFile(filePath) {
|
|
259
|
+
let text = readFileSync4(filePath, "utf-8");
|
|
260
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
261
|
+
const parsed = parser.parse(text);
|
|
262
|
+
const elements = [];
|
|
263
|
+
const allTags = [];
|
|
264
|
+
let hasYFlip = false;
|
|
265
|
+
function walk(node, tag) {
|
|
266
|
+
if (!node || typeof node !== "object") return;
|
|
267
|
+
if (tag) allTags.push(tag);
|
|
268
|
+
if (tag === "g") {
|
|
269
|
+
const transform = node["@_transform"] ?? "";
|
|
270
|
+
if (typeof transform === "string" && transform.includes("scale(1,-1)")) {
|
|
271
|
+
hasYFlip = true;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const geoTags = ["path", "line", "rect", "polygon", "circle", "text"];
|
|
275
|
+
if (tag && geoTags.includes(tag)) {
|
|
276
|
+
const attrs = {};
|
|
277
|
+
for (const [k, v] of Object.entries(node)) {
|
|
278
|
+
if (k.startsWith("@_")) {
|
|
279
|
+
attrs[k.slice(2)] = String(v);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (attrs.id) {
|
|
283
|
+
elements.push({ tag, id: attrs.id, attrs });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
for (const [key, value] of Object.entries(node)) {
|
|
287
|
+
if (key.startsWith("@_") || key.startsWith("?")) continue;
|
|
288
|
+
if (Array.isArray(value)) {
|
|
289
|
+
for (const item of value) walk(item, key);
|
|
290
|
+
} else if (typeof value === "object" && value !== null) {
|
|
291
|
+
walk(value, key);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
walk(parsed);
|
|
296
|
+
return { elements, allTags, hasYFlip, raw: parsed };
|
|
297
|
+
}
|
|
298
|
+
function extractLineGeometry(el) {
|
|
299
|
+
let x1, y1, x2, y2;
|
|
300
|
+
if (el.tag === "path") {
|
|
301
|
+
const d = el.attrs.d ?? "";
|
|
302
|
+
const m = d.match(/M\s*(-?[\d.]+)[,\s]+(-?[\d.]+)\s*L\s*(-?[\d.]+)[,\s]+(-?[\d.]+)/);
|
|
303
|
+
if (m) {
|
|
304
|
+
x1 = parseFloat(m[1]);
|
|
305
|
+
y1 = parseFloat(m[2]);
|
|
306
|
+
x2 = parseFloat(m[3]);
|
|
307
|
+
y2 = parseFloat(m[4]);
|
|
308
|
+
} else {
|
|
309
|
+
x1 = y1 = x2 = y2 = 0;
|
|
310
|
+
}
|
|
311
|
+
} else {
|
|
312
|
+
x1 = parseFloat(el.attrs.x1 ?? "0");
|
|
313
|
+
y1 = parseFloat(el.attrs.y1 ?? "0");
|
|
314
|
+
x2 = parseFloat(el.attrs.x2 ?? "0");
|
|
315
|
+
y2 = parseFloat(el.attrs.y2 ?? "0");
|
|
316
|
+
}
|
|
317
|
+
const dx = x2 - x1;
|
|
318
|
+
const dy = y2 - y1;
|
|
319
|
+
return {
|
|
320
|
+
start_x: x1,
|
|
321
|
+
start_y: y1,
|
|
322
|
+
end_x: x2,
|
|
323
|
+
end_y: y2,
|
|
324
|
+
length: Math.sqrt(dx * dx + dy * dy),
|
|
325
|
+
thickness: 0
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function extractRectGeometry(el) {
|
|
329
|
+
const x = parseFloat(el.attrs.x ?? "0");
|
|
330
|
+
const y = parseFloat(el.attrs.y ?? "0");
|
|
331
|
+
const w = parseFloat(el.attrs.width ?? "0");
|
|
332
|
+
const h = parseFloat(el.attrs.height ?? "0");
|
|
333
|
+
let rotation = 0;
|
|
334
|
+
const transform = el.attrs.transform;
|
|
335
|
+
if (transform) {
|
|
336
|
+
const m = transform.match(/rotate\(([^,)]+)/);
|
|
337
|
+
if (m) rotation = parseFloat(m[1]);
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
x: x + w / 2,
|
|
341
|
+
y: y + h / 2,
|
|
342
|
+
rotation,
|
|
343
|
+
size_x: w,
|
|
344
|
+
size_y: h
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
function extractPolygonGeometry(el) {
|
|
348
|
+
const pointsStr = el.attrs.points ?? "";
|
|
349
|
+
const coords = pointsStr.trim().split(/\s+/).map((p) => {
|
|
350
|
+
const [x, y] = p.split(",").map(Number);
|
|
351
|
+
return { x: x ?? 0, y: y ?? 0 };
|
|
352
|
+
});
|
|
353
|
+
let area = 0;
|
|
354
|
+
for (let i = 0; i < coords.length; i++) {
|
|
355
|
+
const j = (i + 1) % coords.length;
|
|
356
|
+
area += coords[i].x * coords[j].y;
|
|
357
|
+
area -= coords[j].x * coords[i].y;
|
|
358
|
+
}
|
|
359
|
+
return { points: pointsStr, area: Math.abs(area) / 2 };
|
|
360
|
+
}
|
|
361
|
+
function extractCircleGeometry(el) {
|
|
362
|
+
const cx = parseFloat(el.attrs.cx ?? "0");
|
|
363
|
+
const cy = parseFloat(el.attrs.cy ?? "0");
|
|
364
|
+
const r = parseFloat(el.attrs.r ?? "0");
|
|
365
|
+
return { x: cx, y: cy, size_x: r * 2, size_y: r * 2 };
|
|
366
|
+
}
|
|
367
|
+
function formatSvgAttrs(attrs, idOverride) {
|
|
368
|
+
const parts = [];
|
|
369
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
370
|
+
const val = k === "id" && idOverride ? idOverride : v;
|
|
371
|
+
parts.push(`${k}="${val}"`);
|
|
372
|
+
}
|
|
373
|
+
return parts.join(" ");
|
|
374
|
+
}
|
|
375
|
+
function elementBounds(el) {
|
|
376
|
+
switch (el.tag) {
|
|
377
|
+
case "path": {
|
|
378
|
+
const geo = extractLineGeometry(el);
|
|
379
|
+
return {
|
|
380
|
+
minX: Math.min(geo.start_x, geo.end_x),
|
|
381
|
+
minY: Math.min(geo.start_y, geo.end_y),
|
|
382
|
+
maxX: Math.max(geo.start_x, geo.end_x),
|
|
383
|
+
maxY: Math.max(geo.start_y, geo.end_y)
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
case "line": {
|
|
387
|
+
const x1 = parseFloat(el.attrs.x1 ?? "0"), y1 = parseFloat(el.attrs.y1 ?? "0");
|
|
388
|
+
const x2 = parseFloat(el.attrs.x2 ?? "0"), y2 = parseFloat(el.attrs.y2 ?? "0");
|
|
389
|
+
return { minX: Math.min(x1, x2), minY: Math.min(y1, y2), maxX: Math.max(x1, x2), maxY: Math.max(y1, y2) };
|
|
390
|
+
}
|
|
391
|
+
case "rect": {
|
|
392
|
+
const x = parseFloat(el.attrs.x ?? "0"), y = parseFloat(el.attrs.y ?? "0");
|
|
393
|
+
const w = parseFloat(el.attrs.width ?? "0"), h = parseFloat(el.attrs.height ?? "0");
|
|
394
|
+
return { minX: x, minY: y, maxX: x + w, maxY: y + h };
|
|
395
|
+
}
|
|
396
|
+
case "circle": {
|
|
397
|
+
const cx = parseFloat(el.attrs.cx ?? "0"), cy = parseFloat(el.attrs.cy ?? "0");
|
|
398
|
+
const r = parseFloat(el.attrs.r ?? "0");
|
|
399
|
+
return { minX: cx - r, minY: cy - r, maxX: cx + r, maxY: cy + r };
|
|
400
|
+
}
|
|
401
|
+
case "polygon": {
|
|
402
|
+
const pts = (el.attrs.points ?? "").trim().split(/\s+/).map((p) => {
|
|
403
|
+
const [x, y] = p.split(",").map(Number);
|
|
404
|
+
return { x: x ?? 0, y: y ?? 0 };
|
|
405
|
+
});
|
|
406
|
+
if (pts.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
|
|
407
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
408
|
+
for (const p of pts) {
|
|
409
|
+
minX = Math.min(minX, p.x);
|
|
410
|
+
minY = Math.min(minY, p.y);
|
|
411
|
+
maxX = Math.max(maxX, p.x);
|
|
412
|
+
maxY = Math.max(maxY, p.y);
|
|
413
|
+
}
|
|
414
|
+
return { minX, minY, maxX, maxY };
|
|
415
|
+
}
|
|
416
|
+
default:
|
|
417
|
+
return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
function writeMergedSvg(inputs) {
|
|
421
|
+
const allElements = [];
|
|
422
|
+
for (const input of inputs) {
|
|
423
|
+
for (const el of input.elements) {
|
|
424
|
+
const newId = input.idRemap.get(el.id) ?? el.id;
|
|
425
|
+
allElements.push({ el, newId });
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (allElements.length === 0) {
|
|
429
|
+
return '<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 0 0">\n <g transform="scale(1,-1)">\n </g>\n</svg>';
|
|
430
|
+
}
|
|
431
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
432
|
+
for (const { el } of allElements) {
|
|
433
|
+
const b = elementBounds(el);
|
|
434
|
+
minX = Math.min(minX, b.minX);
|
|
435
|
+
minY = Math.min(minY, b.minY);
|
|
436
|
+
maxX = Math.max(maxX, b.maxX);
|
|
437
|
+
maxY = Math.max(maxY, b.maxY);
|
|
438
|
+
}
|
|
439
|
+
const vbX = minX;
|
|
440
|
+
const vbY = -maxY;
|
|
441
|
+
const vbW = maxX - minX;
|
|
442
|
+
const vbH = maxY - minY;
|
|
443
|
+
const pad = Math.max(vbW, vbH) * 0.02;
|
|
444
|
+
const viewBox = `${(vbX - pad).toFixed(3)} ${(vbY - pad).toFixed(3)} ${(vbW + pad * 2).toFixed(3)} ${(vbH + pad * 2).toFixed(3)}`;
|
|
445
|
+
const lines = [
|
|
446
|
+
'<?xml version="1.0" encoding="utf-8"?>',
|
|
447
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
|
|
448
|
+
' <g transform="scale(1,-1)">'
|
|
449
|
+
];
|
|
450
|
+
for (const { el, newId } of allElements) {
|
|
451
|
+
lines.push(` <${el.tag} ${formatSvgAttrs(el.attrs, newId)} />`);
|
|
452
|
+
}
|
|
453
|
+
lines.push(" </g>");
|
|
454
|
+
lines.push("</svg>");
|
|
455
|
+
return lines.join("\n");
|
|
456
|
+
}
|
|
457
|
+
var parser;
|
|
458
|
+
var init_svg = __esm({
|
|
459
|
+
"src/utils/svg.ts"() {
|
|
460
|
+
"use strict";
|
|
461
|
+
parser = new XMLParser({
|
|
462
|
+
ignoreAttributes: false,
|
|
463
|
+
attributeNamePrefix: "@_",
|
|
464
|
+
allowBooleanAttributes: true,
|
|
465
|
+
parseAttributeValue: false,
|
|
466
|
+
trimValues: true
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
// src/duckdb/engine.ts
|
|
472
|
+
var engine_exports = {};
|
|
473
|
+
__export(engine_exports, {
|
|
474
|
+
closeConnection: () => closeConnection,
|
|
475
|
+
getConnection: () => getConnection,
|
|
476
|
+
runQuery: () => runQuery
|
|
477
|
+
});
|
|
478
|
+
import { DuckDBInstance } from "@duckdb/node-api";
|
|
479
|
+
async function getConnection() {
|
|
480
|
+
if (connection) return connection;
|
|
481
|
+
instance = await DuckDBInstance.create(":memory:");
|
|
482
|
+
connection = await instance.connect();
|
|
483
|
+
return connection;
|
|
484
|
+
}
|
|
485
|
+
async function closeConnection() {
|
|
486
|
+
connection = null;
|
|
487
|
+
instance = null;
|
|
488
|
+
}
|
|
489
|
+
async function runQuery(conn, sql) {
|
|
490
|
+
const reader = await conn.runAndReadAll(sql);
|
|
491
|
+
const columns = reader.columnNames();
|
|
492
|
+
const rows = reader.getRowObjects();
|
|
493
|
+
return { columns, rows };
|
|
494
|
+
}
|
|
495
|
+
var instance, connection;
|
|
496
|
+
var init_engine = __esm({
|
|
497
|
+
"src/duckdb/engine.ts"() {
|
|
498
|
+
"use strict";
|
|
499
|
+
instance = null;
|
|
500
|
+
connection = null;
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
// src/duckdb/hydrate.ts
|
|
505
|
+
var hydrate_exports = {};
|
|
506
|
+
__export(hydrate_exports, {
|
|
507
|
+
hydrate: () => hydrate
|
|
508
|
+
});
|
|
509
|
+
import { existsSync as existsSync4 } from "fs";
|
|
510
|
+
import { join as join6 } from "path";
|
|
511
|
+
async function hydrate(conn, dir) {
|
|
512
|
+
const registry = buildRegistry(getSpecDir());
|
|
513
|
+
const layout = discoverLayout(dir);
|
|
514
|
+
const tables = [];
|
|
515
|
+
const allDirs = [
|
|
516
|
+
{ name: "global", path: layout.globalDir },
|
|
517
|
+
...layout.levelDirs
|
|
518
|
+
];
|
|
519
|
+
for (const [tableName, table] of registry) {
|
|
520
|
+
const csvFiles = [];
|
|
521
|
+
for (const d of allDirs) {
|
|
522
|
+
const csvPath = join6(d.path, `${tableName}.csv`);
|
|
523
|
+
if (existsSync4(csvPath)) {
|
|
524
|
+
csvFiles.push({ dir: d.name, fullPath: csvPath });
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (csvFiles.length === 0) continue;
|
|
528
|
+
const allRows = [];
|
|
529
|
+
let headers = [];
|
|
530
|
+
for (const { dir: dirName, fullPath } of csvFiles) {
|
|
531
|
+
const data = readCsv(fullPath);
|
|
532
|
+
if (headers.length === 0) headers = data.headers;
|
|
533
|
+
for (const row of data.rows) {
|
|
534
|
+
allRows.push({ ...row, _partition: dirName });
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (allRows.length === 0) continue;
|
|
538
|
+
const cols = [...headers, "_partition"];
|
|
539
|
+
const colDefs = cols.map((c) => `"${c}" VARCHAR`).join(", ");
|
|
540
|
+
await runQuery(conn, `CREATE TABLE "${tableName}" (${colDefs})`);
|
|
541
|
+
for (const row of allRows) {
|
|
542
|
+
const values = cols.map((c) => escapeSql(row[c] ?? ""));
|
|
543
|
+
await runQuery(conn, `INSERT INTO "${tableName}" VALUES (${values.join(", ")})`);
|
|
544
|
+
}
|
|
545
|
+
tables.push(tableName);
|
|
546
|
+
await injectGeometry(conn, tableName, allDirs);
|
|
547
|
+
}
|
|
548
|
+
return tables;
|
|
549
|
+
}
|
|
550
|
+
async function injectGeometry(conn, tableName, dirs) {
|
|
551
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
552
|
+
if (!svgName) return;
|
|
553
|
+
const geometries = /* @__PURE__ */ new Map();
|
|
554
|
+
for (const d of dirs) {
|
|
555
|
+
if (d.name === "global") continue;
|
|
556
|
+
const svgPath = join6(d.path, `${svgName}.svg`);
|
|
557
|
+
if (!existsSync4(svgPath)) continue;
|
|
558
|
+
try {
|
|
559
|
+
const svg = parseSvgFile(svgPath);
|
|
560
|
+
for (const el of svg.elements) {
|
|
561
|
+
if (el.tag === "path") {
|
|
562
|
+
const geo = extractLineGeometry(el);
|
|
563
|
+
geometries.set(el.id, geo);
|
|
564
|
+
} else if (el.tag === "rect") {
|
|
565
|
+
const geo = extractRectGeometry(el);
|
|
566
|
+
geometries.set(el.id, geo);
|
|
567
|
+
} else if (el.tag === "polygon") {
|
|
568
|
+
const geo = extractPolygonGeometry(el);
|
|
569
|
+
geometries.set(el.id, geo);
|
|
570
|
+
} else if (el.tag === "circle") {
|
|
571
|
+
const geo = extractCircleGeometry(el);
|
|
572
|
+
geometries.set(el.id, geo);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
} catch {
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (geometries.size === 0) return;
|
|
579
|
+
const allKeys = /* @__PURE__ */ new Set();
|
|
580
|
+
for (const geo of geometries.values()) {
|
|
581
|
+
for (const k of Object.keys(geo)) allKeys.add(k);
|
|
582
|
+
}
|
|
583
|
+
const existingCols = await runQuery(
|
|
584
|
+
conn,
|
|
585
|
+
`SELECT column_name FROM information_schema.columns WHERE table_name = '${tableName}'`
|
|
586
|
+
);
|
|
587
|
+
const existingSet = new Set(existingCols.rows.map((r) => String(r.column_name)));
|
|
588
|
+
for (const col of allKeys) {
|
|
589
|
+
if (existingSet.has(col)) continue;
|
|
590
|
+
const sqlType = col === "points" ? "VARCHAR" : "DOUBLE";
|
|
591
|
+
await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" ${sqlType}`);
|
|
592
|
+
}
|
|
593
|
+
for (const [id, geo] of geometries) {
|
|
594
|
+
const sets = Object.entries(geo).map(([k, v]) => `"${k}" = ${typeof v === "string" ? escapeSql(v) : v}`).join(", ");
|
|
595
|
+
await runQuery(conn, `UPDATE "${tableName}" SET ${sets} WHERE id = ${escapeSql(id)}`);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function escapeSql(val) {
|
|
599
|
+
return "'" + val.replace(/'/g, "''") + "'";
|
|
600
|
+
}
|
|
601
|
+
var init_hydrate = __esm({
|
|
602
|
+
"src/duckdb/hydrate.ts"() {
|
|
603
|
+
"use strict";
|
|
604
|
+
init_registry();
|
|
605
|
+
init_fs();
|
|
606
|
+
init_csv();
|
|
607
|
+
init_svg();
|
|
608
|
+
init_engine();
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// src/duckdb/dehydrate.ts
|
|
613
|
+
var dehydrate_exports = {};
|
|
614
|
+
__export(dehydrate_exports, {
|
|
615
|
+
dehydrate: () => dehydrate
|
|
616
|
+
});
|
|
617
|
+
import { existsSync as existsSync5, mkdirSync } from "fs";
|
|
618
|
+
import { join as join7 } from "path";
|
|
619
|
+
async function dehydrate(conn, dir) {
|
|
620
|
+
const registry = buildRegistry(getSpecDir());
|
|
621
|
+
for (const [tableName, table] of registry) {
|
|
622
|
+
const check = await runQuery(
|
|
623
|
+
conn,
|
|
624
|
+
`SELECT count(*) as cnt FROM information_schema.tables WHERE table_name = '${tableName}'`
|
|
625
|
+
);
|
|
626
|
+
if (!check.rows.length || check.rows[0].cnt === 0n) continue;
|
|
627
|
+
const csvHeaders = table.csvFields.map((f) => f.name);
|
|
628
|
+
const partResult = await runQuery(
|
|
629
|
+
conn,
|
|
630
|
+
`SELECT DISTINCT _partition FROM "${tableName}"`
|
|
631
|
+
);
|
|
632
|
+
for (const partRow of partResult.rows) {
|
|
633
|
+
const partition = String(partRow._partition);
|
|
634
|
+
const outDir = join7(dir, partition);
|
|
635
|
+
if (!existsSync5(outDir)) mkdirSync(outDir, { recursive: true });
|
|
636
|
+
const selectCols = csvHeaders.map((h) => `"${h}"`).join(", ");
|
|
637
|
+
const dataResult = await runQuery(
|
|
638
|
+
conn,
|
|
639
|
+
`SELECT ${selectCols} FROM "${tableName}" WHERE _partition = '${partition}'`
|
|
640
|
+
);
|
|
641
|
+
const data = {
|
|
642
|
+
headers: csvHeaders,
|
|
643
|
+
rows: dataResult.rows.map((r) => {
|
|
644
|
+
const row = {};
|
|
645
|
+
for (const h of csvHeaders) {
|
|
646
|
+
const val = r[h];
|
|
647
|
+
row[h] = val == null ? "" : String(val);
|
|
648
|
+
}
|
|
649
|
+
return row;
|
|
650
|
+
})
|
|
651
|
+
};
|
|
652
|
+
writeCsv(join7(outDir, `${tableName}.csv`), data);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
var init_dehydrate = __esm({
|
|
657
|
+
"src/duckdb/dehydrate.ts"() {
|
|
658
|
+
"use strict";
|
|
659
|
+
init_registry();
|
|
660
|
+
init_csv();
|
|
661
|
+
init_engine();
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
// src/commands/resolve-topology.ts
|
|
666
|
+
var resolve_topology_exports = {};
|
|
667
|
+
__export(resolve_topology_exports, {
|
|
668
|
+
resolveTopology: () => resolveTopology
|
|
669
|
+
});
|
|
670
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
671
|
+
import { join as join8 } from "path";
|
|
672
|
+
function dist3d(a, b) {
|
|
673
|
+
const dx = a.x - b.x;
|
|
674
|
+
const dy = a.y - b.y;
|
|
675
|
+
const dz = a.z - b.z;
|
|
676
|
+
return Math.sqrt(dx * dx + dy * dy + dz * dz);
|
|
677
|
+
}
|
|
678
|
+
function insideBBox(point, node) {
|
|
679
|
+
const dz = Math.abs(point.z - node.pos.z);
|
|
680
|
+
if (dz > TOLERANCE) return false;
|
|
681
|
+
const dx = Math.abs(point.x - node.pos.x);
|
|
682
|
+
const dy = Math.abs(point.y - node.pos.y);
|
|
683
|
+
return dx <= node.halfW + TOLERANCE && dy <= node.halfH + TOLERANCE;
|
|
684
|
+
}
|
|
685
|
+
function resolveTopology(dir) {
|
|
686
|
+
buildRegistry(getSpecDir());
|
|
687
|
+
const layout = discoverLayout(dir);
|
|
688
|
+
const allDirs = [
|
|
689
|
+
{ name: "global", path: layout.globalDir },
|
|
690
|
+
...layout.levelDirs
|
|
691
|
+
];
|
|
692
|
+
const freeEndpoints = [];
|
|
693
|
+
const curveData = /* @__PURE__ */ new Map();
|
|
694
|
+
let totalCurves = 0;
|
|
695
|
+
let skippedStart = 0;
|
|
696
|
+
let skippedEnd = 0;
|
|
697
|
+
for (const d of allDirs) {
|
|
698
|
+
if (!existsSync6(d.path)) continue;
|
|
699
|
+
const files = listFiles(d.path);
|
|
700
|
+
for (const tableName of CURVE_TABLES) {
|
|
701
|
+
if (!files.includes(`${tableName}.csv`)) continue;
|
|
702
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
703
|
+
if (!svgName || !files.includes(`${svgName}.svg`)) continue;
|
|
704
|
+
const csvPath = join8(d.path, `${tableName}.csv`);
|
|
705
|
+
const svgPath = join8(d.path, `${svgName}.svg`);
|
|
706
|
+
const csv = readCsv(csvPath);
|
|
707
|
+
const key = `${d.name}/${tableName}`;
|
|
708
|
+
curveData.set(key, { csv, path: csvPath });
|
|
709
|
+
let svgElements;
|
|
710
|
+
try {
|
|
711
|
+
svgElements = parseSvgFile(svgPath).elements;
|
|
712
|
+
} catch {
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
const geoMap = /* @__PURE__ */ new Map();
|
|
716
|
+
for (const el of svgElements) {
|
|
717
|
+
if (el.tag === "path") {
|
|
718
|
+
const geo = extractLineGeometry(el);
|
|
719
|
+
geoMap.set(el.id, geo);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
for (const row of csv.rows) {
|
|
723
|
+
const geo = geoMap.get(row.id);
|
|
724
|
+
if (!geo) continue;
|
|
725
|
+
totalCurves++;
|
|
726
|
+
const startZ = parseFloat(row.start_z ?? "0");
|
|
727
|
+
const endZ = parseFloat(row.end_z ?? "0");
|
|
728
|
+
if (row.start_node_id) {
|
|
729
|
+
skippedStart++;
|
|
730
|
+
} else {
|
|
731
|
+
freeEndpoints.push({
|
|
732
|
+
curveId: row.id,
|
|
733
|
+
side: "start",
|
|
734
|
+
point: { x: geo.start_x, y: geo.start_y, z: startZ },
|
|
735
|
+
levelDir: d.name,
|
|
736
|
+
systemType: row.system_type ?? ""
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
if (row.end_node_id) {
|
|
740
|
+
skippedEnd++;
|
|
741
|
+
} else {
|
|
742
|
+
freeEndpoints.push({
|
|
743
|
+
curveId: row.id,
|
|
744
|
+
side: "end",
|
|
745
|
+
point: { x: geo.end_x, y: geo.end_y, z: endZ },
|
|
746
|
+
levelDir: d.name,
|
|
747
|
+
systemType: row.system_type ?? ""
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
const nodes = [];
|
|
754
|
+
for (const d of allDirs) {
|
|
755
|
+
if (!existsSync6(d.path)) continue;
|
|
756
|
+
const files = listFiles(d.path);
|
|
757
|
+
for (const tableName of NODE_TABLES) {
|
|
758
|
+
if (!files.includes(`${tableName}.csv`)) continue;
|
|
759
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
760
|
+
if (!svgName || !files.includes(`${svgName}.svg`)) continue;
|
|
761
|
+
const csvPath = join8(d.path, `${tableName}.csv`);
|
|
762
|
+
const svgPath = join8(d.path, `${svgName}.svg`);
|
|
763
|
+
const csv = readCsv(csvPath);
|
|
764
|
+
let svgElements;
|
|
765
|
+
try {
|
|
766
|
+
svgElements = parseSvgFile(svgPath).elements;
|
|
767
|
+
} catch {
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
const posMap = /* @__PURE__ */ new Map();
|
|
771
|
+
for (const el of svgElements) {
|
|
772
|
+
if (el.tag === "rect") {
|
|
773
|
+
const geo = extractRectGeometry(el);
|
|
774
|
+
posMap.set(el.id, { x: geo.x, y: geo.y, halfW: geo.size_x / 2, halfH: geo.size_y / 2 });
|
|
775
|
+
} else if (el.tag === "circle") {
|
|
776
|
+
const geo = extractCircleGeometry(el);
|
|
777
|
+
const r = geo.size_x / 2;
|
|
778
|
+
posMap.set(el.id, { x: geo.x, y: geo.y, halfW: r, halfH: r });
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
for (const row of csv.rows) {
|
|
782
|
+
const p = posMap.get(row.id);
|
|
783
|
+
if (!p) continue;
|
|
784
|
+
const z = parseFloat(row.base_offset ?? "0");
|
|
785
|
+
nodes.push({
|
|
786
|
+
levelDir: d.name,
|
|
787
|
+
tableName,
|
|
788
|
+
id: row.id,
|
|
789
|
+
pos: { x: p.x, y: p.y, z },
|
|
790
|
+
halfW: p.halfW,
|
|
791
|
+
halfH: p.halfH
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
const resolvedIds = /* @__PURE__ */ new Map();
|
|
797
|
+
const stillFree = [];
|
|
798
|
+
for (const ep of freeEndpoints) {
|
|
799
|
+
let matched = null;
|
|
800
|
+
for (const node of nodes) {
|
|
801
|
+
if (insideBBox(ep.point, node)) {
|
|
802
|
+
matched = node;
|
|
803
|
+
break;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
if (matched) {
|
|
807
|
+
resolvedIds.set(`${ep.curveId}:${ep.side}`, matched.id);
|
|
808
|
+
} else {
|
|
809
|
+
stillFree.push(ep);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
const fittingMatches = resolvedIds.size;
|
|
813
|
+
const junctions = [];
|
|
814
|
+
for (const ep of stillFree) {
|
|
815
|
+
let found = false;
|
|
816
|
+
for (const j of junctions) {
|
|
817
|
+
if (dist3d(ep.point, j.point) < TOLERANCE) {
|
|
818
|
+
j.endpoints.push(ep);
|
|
819
|
+
found = true;
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
if (!found) {
|
|
824
|
+
junctions.push({
|
|
825
|
+
point: ep.point,
|
|
826
|
+
endpoints: [ep],
|
|
827
|
+
levelDir: ep.levelDir,
|
|
828
|
+
systemType: ep.systemType,
|
|
829
|
+
nodeId: ""
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
const maxMnId = /* @__PURE__ */ new Map();
|
|
834
|
+
for (const n of nodes) {
|
|
835
|
+
if (n.tableName === "mep_node") {
|
|
836
|
+
const num = parseInt(n.id.replace("mn-", ""), 10);
|
|
837
|
+
const current = maxMnId.get(n.levelDir) ?? 0;
|
|
838
|
+
if (num > current) maxMnId.set(n.levelDir, num);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
for (const j of junctions) {
|
|
842
|
+
const current = maxMnId.get(j.levelDir) ?? 0;
|
|
843
|
+
const nextId = current + 1;
|
|
844
|
+
maxMnId.set(j.levelDir, nextId);
|
|
845
|
+
j.nodeId = `mn-${nextId}`;
|
|
846
|
+
for (const ep of j.endpoints) {
|
|
847
|
+
resolvedIds.set(`${ep.curveId}:${ep.side}`, j.nodeId);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const newNodesByLevel = /* @__PURE__ */ new Map();
|
|
851
|
+
for (const j of junctions) {
|
|
852
|
+
const arr = newNodesByLevel.get(j.levelDir) ?? [];
|
|
853
|
+
arr.push(j);
|
|
854
|
+
newNodesByLevel.set(j.levelDir, arr);
|
|
855
|
+
}
|
|
856
|
+
for (const [levelDir, levelJunctions] of newNodesByLevel) {
|
|
857
|
+
const dirPath = levelDir === "global" ? layout.globalDir : join8(dir, levelDir);
|
|
858
|
+
if (!existsSync6(dirPath)) mkdirSync2(dirPath, { recursive: true });
|
|
859
|
+
const csvPath = join8(dirPath, "mep_node.csv");
|
|
860
|
+
const svgPath = join8(dirPath, "mep_node.svg");
|
|
861
|
+
let csv;
|
|
862
|
+
if (existsSync6(csvPath)) {
|
|
863
|
+
csv = readCsv(csvPath);
|
|
864
|
+
} else {
|
|
865
|
+
csv = { headers: ["id", "number", "base_offset", "system_type"], rows: [] };
|
|
866
|
+
}
|
|
867
|
+
for (const h of ["id", "number", "base_offset", "system_type"]) {
|
|
868
|
+
if (!csv.headers.includes(h)) csv.headers.push(h);
|
|
869
|
+
}
|
|
870
|
+
let existingSvgElements = [];
|
|
871
|
+
if (existsSync6(svgPath)) {
|
|
872
|
+
try {
|
|
873
|
+
existingSvgElements = parseSvgFile(svgPath).elements;
|
|
874
|
+
} catch {
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
const newSvgLines = [];
|
|
878
|
+
const NODE_RADIUS = 0.025;
|
|
879
|
+
for (const j of levelJunctions) {
|
|
880
|
+
csv.rows.push({
|
|
881
|
+
id: j.nodeId,
|
|
882
|
+
number: "",
|
|
883
|
+
base_offset: String(j.point.z),
|
|
884
|
+
system_type: j.systemType
|
|
885
|
+
});
|
|
886
|
+
newSvgLines.push(
|
|
887
|
+
` <circle id="${j.nodeId}" cx="${j.point.x.toFixed(3)}" cy="${j.point.y.toFixed(3)}" r="${NODE_RADIUS}" />`
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
writeCsv(csvPath, csv);
|
|
891
|
+
const existingLines = [];
|
|
892
|
+
for (const el of existingSvgElements) {
|
|
893
|
+
const attrs = Object.entries(el.attrs).map(([k, v]) => `${k}="${v}"`).join(" ");
|
|
894
|
+
existingLines.push(` <${el.tag} ${attrs} />`);
|
|
895
|
+
}
|
|
896
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
897
|
+
for (const el of existingSvgElements) {
|
|
898
|
+
if (el.tag === "rect") {
|
|
899
|
+
const g = extractRectGeometry(el);
|
|
900
|
+
minX = Math.min(minX, g.x - g.size_x / 2);
|
|
901
|
+
minY = Math.min(minY, g.y - g.size_y / 2);
|
|
902
|
+
maxX = Math.max(maxX, g.x + g.size_x / 2);
|
|
903
|
+
maxY = Math.max(maxY, g.y + g.size_y / 2);
|
|
904
|
+
} else if (el.tag === "circle") {
|
|
905
|
+
const g = extractCircleGeometry(el);
|
|
906
|
+
const r = g.size_x / 2;
|
|
907
|
+
minX = Math.min(minX, g.x - r);
|
|
908
|
+
minY = Math.min(minY, g.y - r);
|
|
909
|
+
maxX = Math.max(maxX, g.x + r);
|
|
910
|
+
maxY = Math.max(maxY, g.y + r);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
for (const j of levelJunctions) {
|
|
914
|
+
minX = Math.min(minX, j.point.x - NODE_RADIUS);
|
|
915
|
+
minY = Math.min(minY, j.point.y - NODE_RADIUS);
|
|
916
|
+
maxX = Math.max(maxX, j.point.x + NODE_RADIUS);
|
|
917
|
+
maxY = Math.max(maxY, j.point.y + NODE_RADIUS);
|
|
918
|
+
}
|
|
919
|
+
let viewBox = "0 0 1 1";
|
|
920
|
+
if (minX !== Infinity) {
|
|
921
|
+
const pad = Math.max(maxX - minX, maxY - minY) * 0.02;
|
|
922
|
+
viewBox = `${(minX - pad).toFixed(3)} ${(-(maxY + pad)).toFixed(3)} ${(maxX - minX + pad * 2).toFixed(3)} ${(maxY - minY + pad * 2).toFixed(3)}`;
|
|
923
|
+
}
|
|
924
|
+
writeFileSync2(svgPath, [
|
|
925
|
+
'<?xml version="1.0" encoding="utf-8"?>',
|
|
926
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
|
|
927
|
+
' <g transform="scale(1,-1)">',
|
|
928
|
+
...existingLines,
|
|
929
|
+
...newSvgLines,
|
|
930
|
+
" </g>",
|
|
931
|
+
"</svg>"
|
|
932
|
+
].join("\n"), "utf-8");
|
|
933
|
+
}
|
|
934
|
+
let updatedRows = 0;
|
|
935
|
+
for (const [, entry] of curveData) {
|
|
936
|
+
let modified = false;
|
|
937
|
+
const csv = entry.csv;
|
|
938
|
+
if (!csv.headers.includes("start_node_id")) csv.headers.push("start_node_id");
|
|
939
|
+
if (!csv.headers.includes("end_node_id")) csv.headers.push("end_node_id");
|
|
940
|
+
for (const row of csv.rows) {
|
|
941
|
+
if (!row.start_node_id) {
|
|
942
|
+
const id = resolvedIds.get(`${row.id}:start`);
|
|
943
|
+
if (id) {
|
|
944
|
+
row.start_node_id = id;
|
|
945
|
+
modified = true;
|
|
946
|
+
updatedRows++;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
if (!row.end_node_id) {
|
|
950
|
+
const id = resolvedIds.get(`${row.id}:end`);
|
|
951
|
+
if (id) {
|
|
952
|
+
row.end_node_id = id;
|
|
953
|
+
modified = true;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (modified) {
|
|
958
|
+
writeCsv(entry.path, csv);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
const totalEndpoints = totalCurves * 2;
|
|
962
|
+
const alreadyResolved = skippedStart + skippedEnd;
|
|
963
|
+
console.log(`Scanned ${totalCurves} MEP curves (${totalEndpoints} endpoints)`);
|
|
964
|
+
console.log(` Already connected: ${alreadyResolved} (from Revit export)`);
|
|
965
|
+
console.log(` Free endpoints: ${freeEndpoints.length}`);
|
|
966
|
+
console.log(` Matched to existing fittings (bbox): ${fittingMatches}`);
|
|
967
|
+
console.log(` New mep_nodes created: ${junctions.length}`);
|
|
968
|
+
console.log(` Unresolved: ${stillFree.length - junctions.reduce((s, j) => s + j.endpoints.length, 0)}`);
|
|
969
|
+
if (updatedRows > 0) {
|
|
970
|
+
console.log(`Updated ${updatedRows} curve rows`);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
var TOLERANCE, CURVE_TABLES, NODE_TABLES;
|
|
974
|
+
var init_resolve_topology = __esm({
|
|
975
|
+
"src/commands/resolve-topology.ts"() {
|
|
976
|
+
"use strict";
|
|
977
|
+
init_csv();
|
|
978
|
+
init_svg();
|
|
979
|
+
init_fs();
|
|
980
|
+
init_registry();
|
|
981
|
+
TOLERANCE = 0.01;
|
|
982
|
+
CURVE_TABLES = ["duct", "pipe", "cable_tray", "conduit"];
|
|
983
|
+
NODE_TABLES = ["equipment", "terminal", "mep_node"];
|
|
984
|
+
}
|
|
985
|
+
});
|
|
986
|
+
|
|
987
|
+
// src/commands/merge.ts
|
|
988
|
+
var merge_exports = {};
|
|
989
|
+
__export(merge_exports, {
|
|
990
|
+
merge: () => merge
|
|
991
|
+
});
|
|
992
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
993
|
+
import { join as join9, basename as basename2 } from "path";
|
|
994
|
+
async function merge(dirs, outputDir) {
|
|
995
|
+
const registry = buildRegistry(getSpecDir());
|
|
996
|
+
console.log(`Scanning ${dirs.length} sources...`);
|
|
997
|
+
const sources = dirs.map((dir) => scanSource(dir, registry));
|
|
998
|
+
const { canonicalLevels, levelRemaps } = deduplicateLevels(sources);
|
|
999
|
+
console.log(`Merged levels: ${canonicalLevels.rows.length} unique levels`);
|
|
1000
|
+
const { canonicalGrids, gridRemaps } = deduplicateGrids(sources);
|
|
1001
|
+
console.log(`Merged grids: ${canonicalGrids.rows.length} unique grids`);
|
|
1002
|
+
const fullRemaps = buildFullRemaps(sources, levelRemaps, gridRemaps, registry);
|
|
1003
|
+
mkdirSync3(join9(outputDir, "global"), { recursive: true });
|
|
1004
|
+
writeCsv(join9(outputDir, "global", "level.csv"), canonicalLevels);
|
|
1005
|
+
if (canonicalGrids.rows.length > 0) {
|
|
1006
|
+
writeCsv(join9(outputDir, "global", "grid.csv"), canonicalGrids);
|
|
1007
|
+
}
|
|
1008
|
+
writeIdMap(outputDir, sources, fullRemaps);
|
|
1009
|
+
const levelDirMap = buildLevelDirMap(sources, fullRemaps);
|
|
1010
|
+
writeGlobalTables(outputDir, sources, fullRemaps, registry);
|
|
1011
|
+
writeLevelTables(outputDir, sources, fullRemaps, levelDirMap, registry);
|
|
1012
|
+
console.log(`Merge complete \u2192 ${outputDir}`);
|
|
1013
|
+
}
|
|
1014
|
+
function scanSource(dir, registry) {
|
|
1015
|
+
const layout = discoverLayout(dir);
|
|
1016
|
+
const name = basename2(dir);
|
|
1017
|
+
const levelPath = join9(layout.globalDir, "level.csv");
|
|
1018
|
+
if (!existsSync7(levelPath)) {
|
|
1019
|
+
throw new Error(`Missing level.csv in ${dir}/global/`);
|
|
1020
|
+
}
|
|
1021
|
+
const levels = readCsv(levelPath);
|
|
1022
|
+
const gridPath = join9(layout.globalDir, "grid.csv");
|
|
1023
|
+
const grids = existsSync7(gridPath) ? readCsv(gridPath) : null;
|
|
1024
|
+
const idMapPath = join9(layout.globalDir, "_IdMap.csv");
|
|
1025
|
+
const idMap = existsSync7(idMapPath) ? readCsv(idMapPath) : null;
|
|
1026
|
+
const globalData = /* @__PURE__ */ new Map();
|
|
1027
|
+
if (existsSync7(layout.globalDir)) {
|
|
1028
|
+
for (const f of listFiles(layout.globalDir)) {
|
|
1029
|
+
if (!f.endsWith(".csv")) continue;
|
|
1030
|
+
const tableName = f.replace(".csv", "");
|
|
1031
|
+
if (tableName === "level" || tableName === "grid" || tableName === "_IdMap") continue;
|
|
1032
|
+
if (!registry.has(tableName)) continue;
|
|
1033
|
+
const csv = readCsv(join9(layout.globalDir, f));
|
|
1034
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
1035
|
+
const svgFile = svgName ? join9(layout.globalDir, svgName + ".svg") : null;
|
|
1036
|
+
globalData.set(tableName, { csv, svgFile: svgFile && existsSync7(svgFile) ? svgFile : null });
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
const levelData = /* @__PURE__ */ new Map();
|
|
1040
|
+
for (const ld of layout.levelDirs) {
|
|
1041
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1042
|
+
for (const f of listFiles(ld.path)) {
|
|
1043
|
+
if (!f.endsWith(".csv")) continue;
|
|
1044
|
+
const tableName = f.replace(".csv", "");
|
|
1045
|
+
if (!registry.has(tableName)) continue;
|
|
1046
|
+
const csv = readCsv(join9(ld.path, f));
|
|
1047
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
1048
|
+
const svgFile = svgName ? join9(ld.path, svgName + ".svg") : null;
|
|
1049
|
+
tables.set(tableName, { csv, svgFile: svgFile && existsSync7(svgFile) ? svgFile : null });
|
|
1050
|
+
}
|
|
1051
|
+
if (tables.size > 0) {
|
|
1052
|
+
levelData.set(ld.name, tables);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return { name, layout, levels, grids, idMap, levelData, globalData };
|
|
1056
|
+
}
|
|
1057
|
+
function deduplicateLevels(sources) {
|
|
1058
|
+
const allLevels = [];
|
|
1059
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1060
|
+
for (const row of sources[si].levels.rows) {
|
|
1061
|
+
allLevels.push({
|
|
1062
|
+
sourceIdx: si,
|
|
1063
|
+
id: row.id,
|
|
1064
|
+
name: row.name ?? "",
|
|
1065
|
+
number: row.number ?? "",
|
|
1066
|
+
elevation: parseFloat(row.elevation ?? "0")
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
allLevels.sort((a, b) => a.elevation - b.elevation);
|
|
1071
|
+
const groups = [];
|
|
1072
|
+
for (const lv of allLevels) {
|
|
1073
|
+
const last = groups[groups.length - 1];
|
|
1074
|
+
if (last && Math.abs(last[0].elevation - lv.elevation) <= ELEVATION_TOLERANCE) {
|
|
1075
|
+
last.push(lv);
|
|
1076
|
+
} else {
|
|
1077
|
+
groups.push([lv]);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
const canonicalRows = [];
|
|
1081
|
+
const remaps = sources.map(() => /* @__PURE__ */ new Map());
|
|
1082
|
+
for (let gi = 0; gi < groups.length; gi++) {
|
|
1083
|
+
const canonId = `lv-${gi + 1}`;
|
|
1084
|
+
const rep = groups[gi][0];
|
|
1085
|
+
canonicalRows.push({
|
|
1086
|
+
id: canonId,
|
|
1087
|
+
number: rep.number,
|
|
1088
|
+
name: rep.name,
|
|
1089
|
+
elevation: String(rep.elevation)
|
|
1090
|
+
});
|
|
1091
|
+
for (const entry of groups[gi]) {
|
|
1092
|
+
remaps[entry.sourceIdx].set(entry.id, canonId);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
return {
|
|
1096
|
+
canonicalLevels: { headers: ["id", "number", "name", "elevation"], rows: canonicalRows },
|
|
1097
|
+
levelRemaps: remaps
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
function deduplicateGrids(sources) {
|
|
1101
|
+
const allGrids = [];
|
|
1102
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1103
|
+
if (!sources[si].grids) continue;
|
|
1104
|
+
for (const row of sources[si].grids.rows) {
|
|
1105
|
+
allGrids.push({
|
|
1106
|
+
sourceIdx: si,
|
|
1107
|
+
id: row.id,
|
|
1108
|
+
number: row.number ?? "",
|
|
1109
|
+
start_x: parseFloat(row.start_x ?? "0"),
|
|
1110
|
+
start_y: parseFloat(row.start_y ?? "0"),
|
|
1111
|
+
end_x: parseFloat(row.end_x ?? "0"),
|
|
1112
|
+
end_y: parseFloat(row.end_y ?? "0")
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
const remaps = sources.map(() => /* @__PURE__ */ new Map());
|
|
1117
|
+
if (allGrids.length === 0) {
|
|
1118
|
+
return { canonicalGrids: { headers: ["id", "number", "start_x", "start_y", "end_x", "end_y"], rows: [] }, gridRemaps: remaps };
|
|
1119
|
+
}
|
|
1120
|
+
const matched = [];
|
|
1121
|
+
for (const g of allGrids) {
|
|
1122
|
+
let found = false;
|
|
1123
|
+
for (const group of matched) {
|
|
1124
|
+
const rep = group[0];
|
|
1125
|
+
if (Math.abs(rep.start_x - g.start_x) <= GRID_COORD_TOLERANCE && Math.abs(rep.start_y - g.start_y) <= GRID_COORD_TOLERANCE && Math.abs(rep.end_x - g.end_x) <= GRID_COORD_TOLERANCE && Math.abs(rep.end_y - g.end_y) <= GRID_COORD_TOLERANCE) {
|
|
1126
|
+
group.push(g);
|
|
1127
|
+
found = true;
|
|
1128
|
+
break;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
if (!found) {
|
|
1132
|
+
matched.push([g]);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
const canonicalRows = [];
|
|
1136
|
+
for (let gi = 0; gi < matched.length; gi++) {
|
|
1137
|
+
const canonId = `gr-${gi + 1}`;
|
|
1138
|
+
const rep = matched[gi][0];
|
|
1139
|
+
canonicalRows.push({
|
|
1140
|
+
id: canonId,
|
|
1141
|
+
number: rep.number,
|
|
1142
|
+
start_x: String(rep.start_x),
|
|
1143
|
+
start_y: String(rep.start_y),
|
|
1144
|
+
end_x: String(rep.end_x),
|
|
1145
|
+
end_y: String(rep.end_y)
|
|
1146
|
+
});
|
|
1147
|
+
for (const entry of matched[gi]) {
|
|
1148
|
+
remaps[entry.sourceIdx].set(entry.id, canonId);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
return {
|
|
1152
|
+
canonicalGrids: { headers: ["id", "number", "start_x", "start_y", "end_x", "end_y"], rows: canonicalRows },
|
|
1153
|
+
gridRemaps: remaps
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
function buildFullRemaps(sources, levelRemaps, gridRemaps, registry) {
|
|
1157
|
+
const remaps = sources.map((_, i) => {
|
|
1158
|
+
const m = /* @__PURE__ */ new Map();
|
|
1159
|
+
for (const [old, nw] of levelRemaps[i]) m.set(old, nw);
|
|
1160
|
+
for (const [old, nw] of gridRemaps[i]) m.set(old, nw);
|
|
1161
|
+
return m;
|
|
1162
|
+
});
|
|
1163
|
+
const prefixCounters = /* @__PURE__ */ new Map();
|
|
1164
|
+
const prefixGroups = /* @__PURE__ */ new Map();
|
|
1165
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1166
|
+
const collectIds = (csv) => {
|
|
1167
|
+
for (const row of csv.rows) {
|
|
1168
|
+
if (!row.id) continue;
|
|
1169
|
+
const dash = row.id.indexOf("-");
|
|
1170
|
+
if (dash < 0) continue;
|
|
1171
|
+
const prefix = row.id.substring(0, dash);
|
|
1172
|
+
if (prefix === "lv" || prefix === "gr") continue;
|
|
1173
|
+
let group = prefixGroups.get(prefix);
|
|
1174
|
+
if (!group) {
|
|
1175
|
+
group = [];
|
|
1176
|
+
prefixGroups.set(prefix, group);
|
|
1177
|
+
}
|
|
1178
|
+
group.push({ sourceIdx: si, oldId: row.id });
|
|
1179
|
+
}
|
|
1180
|
+
};
|
|
1181
|
+
for (const [, data] of sources[si].globalData) {
|
|
1182
|
+
collectIds(data.csv);
|
|
1183
|
+
}
|
|
1184
|
+
for (const [, tables] of sources[si].levelData) {
|
|
1185
|
+
for (const [, data] of tables) {
|
|
1186
|
+
collectIds(data.csv);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
for (const [prefix, group] of prefixGroups) {
|
|
1191
|
+
let counter = 1;
|
|
1192
|
+
for (const { sourceIdx, oldId } of group) {
|
|
1193
|
+
const newId = `${prefix}-${counter}`;
|
|
1194
|
+
remaps[sourceIdx].set(oldId, newId);
|
|
1195
|
+
counter++;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
return remaps;
|
|
1199
|
+
}
|
|
1200
|
+
function remapRow(row, remap, refFieldNames) {
|
|
1201
|
+
const out = {};
|
|
1202
|
+
for (const [key, val] of Object.entries(row)) {
|
|
1203
|
+
if (val && (refFieldNames.has(key) || KNOWN_ID_FIELDS.has(key))) {
|
|
1204
|
+
out[key] = remap.get(val) ?? val;
|
|
1205
|
+
} else {
|
|
1206
|
+
out[key] = val;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
return out;
|
|
1210
|
+
}
|
|
1211
|
+
function getRefFieldNames(registry) {
|
|
1212
|
+
const names = /* @__PURE__ */ new Set();
|
|
1213
|
+
for (const [, table] of registry) {
|
|
1214
|
+
for (const f of table.csvFields) {
|
|
1215
|
+
if (f.type === "reference") names.add(f.name);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
for (const f of KNOWN_ID_FIELDS) names.add(f);
|
|
1219
|
+
return names;
|
|
1220
|
+
}
|
|
1221
|
+
function writeIdMap(outputDir, sources, remaps) {
|
|
1222
|
+
const seenUuid = /* @__PURE__ */ new Map();
|
|
1223
|
+
const rows = [];
|
|
1224
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1225
|
+
if (!sources[si].idMap) continue;
|
|
1226
|
+
for (const row of sources[si].idMap.rows) {
|
|
1227
|
+
const oldId = row.id;
|
|
1228
|
+
const uuid = row.uuid;
|
|
1229
|
+
const newId = remaps[si].get(oldId) ?? oldId;
|
|
1230
|
+
if (seenUuid.has(uuid)) continue;
|
|
1231
|
+
seenUuid.set(uuid, newId);
|
|
1232
|
+
rows.push({ id: newId, uuid });
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
if (rows.length > 0) {
|
|
1236
|
+
writeCsv(join9(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
function buildLevelDirMap(sources, remaps) {
|
|
1240
|
+
const result = /* @__PURE__ */ new Map();
|
|
1241
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1242
|
+
const dirMap = /* @__PURE__ */ new Map();
|
|
1243
|
+
const src = sources[si];
|
|
1244
|
+
for (const ld of src.layout.levelDirs) {
|
|
1245
|
+
const oldLevelId = ld.name;
|
|
1246
|
+
const newLevelId = remaps[si].get(oldLevelId);
|
|
1247
|
+
if (newLevelId) {
|
|
1248
|
+
dirMap.set(ld.name, newLevelId);
|
|
1249
|
+
} else {
|
|
1250
|
+
dirMap.set(ld.name, ld.name);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
result.set(String(si), dirMap);
|
|
1254
|
+
}
|
|
1255
|
+
return result;
|
|
1256
|
+
}
|
|
1257
|
+
function writeGlobalTables(outputDir, sources, remaps, registry) {
|
|
1258
|
+
const refFields = getRefFieldNames(registry);
|
|
1259
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1260
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1261
|
+
for (const [tableName, data] of sources[si].globalData) {
|
|
1262
|
+
if (!merged.has(tableName)) {
|
|
1263
|
+
merged.set(tableName, { rows: [], headers: data.csv.headers, svgInputs: [] });
|
|
1264
|
+
}
|
|
1265
|
+
const entry = merged.get(tableName);
|
|
1266
|
+
for (const row of data.csv.rows) {
|
|
1267
|
+
entry.rows.push(remapRow(row, remaps[si], refFields));
|
|
1268
|
+
}
|
|
1269
|
+
if (data.svgFile) {
|
|
1270
|
+
const svg = parseSvgFile(data.svgFile);
|
|
1271
|
+
entry.svgInputs.push({ elements: svg.elements, idRemap: remaps[si] });
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
for (const [tableName, entry] of merged) {
|
|
1276
|
+
if (entry.rows.length > 0) {
|
|
1277
|
+
writeCsv(join9(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
|
|
1278
|
+
}
|
|
1279
|
+
if (entry.svgInputs.length > 0) {
|
|
1280
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
1281
|
+
if (svgName) {
|
|
1282
|
+
const content = writeMergedSvg(entry.svgInputs);
|
|
1283
|
+
writeFileSync3(join9(outputDir, "global", svgName + ".svg"), content, "utf-8");
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
function writeLevelTables(outputDir, sources, remaps, levelDirMap, registry) {
|
|
1289
|
+
const refFields = getRefFieldNames(registry);
|
|
1290
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1291
|
+
for (let si = 0; si < sources.length; si++) {
|
|
1292
|
+
const dirMap = levelDirMap.get(String(si));
|
|
1293
|
+
for (const [srcDirName, tables] of sources[si].levelData) {
|
|
1294
|
+
const outDirName = dirMap.get(srcDirName) ?? srcDirName;
|
|
1295
|
+
if (!merged.has(outDirName)) {
|
|
1296
|
+
merged.set(outDirName, /* @__PURE__ */ new Map());
|
|
1297
|
+
}
|
|
1298
|
+
const levelMerged = merged.get(outDirName);
|
|
1299
|
+
for (const [tableName, data] of tables) {
|
|
1300
|
+
if (!levelMerged.has(tableName)) {
|
|
1301
|
+
levelMerged.set(tableName, { rows: [], headers: data.csv.headers, svgInputs: [] });
|
|
1302
|
+
}
|
|
1303
|
+
const entry = levelMerged.get(tableName);
|
|
1304
|
+
for (const row of data.csv.rows) {
|
|
1305
|
+
entry.rows.push(remapRow(row, remaps[si], refFields));
|
|
1306
|
+
}
|
|
1307
|
+
if (data.svgFile) {
|
|
1308
|
+
const svg = parseSvgFile(data.svgFile);
|
|
1309
|
+
entry.svgInputs.push({ elements: svg.elements, idRemap: remaps[si] });
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
for (const [outDirName, tables] of merged) {
|
|
1315
|
+
const dirPath = join9(outputDir, outDirName);
|
|
1316
|
+
mkdirSync3(dirPath, { recursive: true });
|
|
1317
|
+
for (const [tableName, entry] of tables) {
|
|
1318
|
+
if (entry.rows.length > 0) {
|
|
1319
|
+
writeCsv(join9(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
|
|
1320
|
+
}
|
|
1321
|
+
if (entry.svgInputs.length > 0) {
|
|
1322
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
1323
|
+
if (svgName) {
|
|
1324
|
+
const content = writeMergedSvg(entry.svgInputs);
|
|
1325
|
+
writeFileSync3(join9(dirPath, svgName + ".svg"), content, "utf-8");
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
var ELEVATION_TOLERANCE, GRID_COORD_TOLERANCE, KNOWN_ID_FIELDS;
|
|
1332
|
+
var init_merge = __esm({
|
|
1333
|
+
"src/commands/merge.ts"() {
|
|
1334
|
+
"use strict";
|
|
1335
|
+
init_csv();
|
|
1336
|
+
init_svg();
|
|
1337
|
+
init_fs();
|
|
1338
|
+
init_registry();
|
|
1339
|
+
ELEVATION_TOLERANCE = 1e-3;
|
|
1340
|
+
GRID_COORD_TOLERANCE = 0.01;
|
|
1341
|
+
KNOWN_ID_FIELDS = /* @__PURE__ */ new Set([
|
|
1342
|
+
"id",
|
|
1343
|
+
"host_id",
|
|
1344
|
+
"top_level_id",
|
|
1345
|
+
"level_id",
|
|
1346
|
+
"start_node_id",
|
|
1347
|
+
"end_node_id"
|
|
1348
|
+
]);
|
|
1349
|
+
}
|
|
1350
|
+
});
|
|
1351
|
+
|
|
1352
|
+
// src/index.ts
|
|
1353
|
+
import { Command } from "commander";
|
|
1354
|
+
import { resolve } from "path";
|
|
1355
|
+
|
|
1356
|
+
// src/validate/index.ts
|
|
1357
|
+
init_registry();
|
|
1358
|
+
init_fs();
|
|
1359
|
+
init_csv();
|
|
1360
|
+
import { existsSync as existsSync3 } from "fs";
|
|
1361
|
+
import { join as join5 } from "path";
|
|
1362
|
+
|
|
1363
|
+
// src/validate/structure.ts
|
|
1364
|
+
init_fs();
|
|
1365
|
+
init_registry();
|
|
1366
|
+
import { existsSync as existsSync2, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
1367
|
+
import { join as join4, extname } from "path";
|
|
1368
|
+
var OPTIONAL_SVG_TABLES = /* @__PURE__ */ new Set(["opening"]);
|
|
1369
|
+
var KNOWN_CSV_NAMES = new Set(Object.keys(ID_PREFIXES).map((t) => `${t}.csv`));
|
|
1370
|
+
var KNOWN_SVG_NAMES = new Set(Object.values(SVG_FILE_NAMES).map((s) => `${s}.svg`));
|
|
1371
|
+
var KNOWN_GLOBAL_EXTRAS = /* @__PURE__ */ new Set(["_IdMap.csv"]);
|
|
1372
|
+
function validateStructure(dir) {
|
|
1373
|
+
const issues = [];
|
|
1374
|
+
const layout = discoverLayout(dir);
|
|
1375
|
+
if (!existsSync2(layout.globalDir)) {
|
|
1376
|
+
issues.push("global/ missing global/ directory");
|
|
1377
|
+
return issues;
|
|
1378
|
+
}
|
|
1379
|
+
const globalFiles = listFiles(layout.globalDir);
|
|
1380
|
+
if (!globalFiles.includes("level.csv")) {
|
|
1381
|
+
issues.push("global/ missing level.csv");
|
|
1382
|
+
}
|
|
1383
|
+
if (!globalFiles.includes("grid.csv")) {
|
|
1384
|
+
issues.push("global/ missing grid.csv");
|
|
1385
|
+
}
|
|
1386
|
+
for (const f of globalFiles) {
|
|
1387
|
+
const ext = extname(f);
|
|
1388
|
+
if (ext === ".svg") {
|
|
1389
|
+
issues.push(`global/${f} SVG files are not allowed in global/`);
|
|
1390
|
+
} else if (ext === ".csv") {
|
|
1391
|
+
if (!KNOWN_CSV_NAMES.has(f) && !KNOWN_GLOBAL_EXTRAS.has(f)) {
|
|
1392
|
+
issues.push(`global/${f} unknown file \u2014 only known table CSVs are allowed`);
|
|
1393
|
+
}
|
|
1394
|
+
} else {
|
|
1395
|
+
issues.push(`global/${f} unexpected file \u2014 only CSV files are allowed in global/`);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
for (const ld of layout.levelDirs) {
|
|
1399
|
+
if (!/^lv-\d+$/.test(ld.name)) {
|
|
1400
|
+
issues.push(`${ld.name}/ directory name does not match lv-{n} pattern`);
|
|
1401
|
+
continue;
|
|
1402
|
+
}
|
|
1403
|
+
const files = listFiles(ld.path);
|
|
1404
|
+
for (const f of files) {
|
|
1405
|
+
const ext = extname(f);
|
|
1406
|
+
if (ext === ".csv") {
|
|
1407
|
+
if (!KNOWN_CSV_NAMES.has(f)) {
|
|
1408
|
+
issues.push(`${ld.name}/${f} unknown file \u2014 not a recognized BimDown table`);
|
|
1409
|
+
}
|
|
1410
|
+
const tableName = f.replace(".csv", "");
|
|
1411
|
+
if (GLOBAL_ONLY_TABLES.has(tableName)) {
|
|
1412
|
+
issues.push(`${ld.name}/${f} ${tableName} belongs in global/ only`);
|
|
1413
|
+
}
|
|
1414
|
+
} else if (ext === ".svg") {
|
|
1415
|
+
if (!KNOWN_SVG_NAMES.has(f)) {
|
|
1416
|
+
issues.push(`${ld.name}/${f} unknown SVG file \u2014 not a recognized BimDown table name`);
|
|
1417
|
+
}
|
|
1418
|
+
const svgBase = f.replace(".svg", "");
|
|
1419
|
+
const tableName = Object.entries(SVG_FILE_NAMES).find(
|
|
1420
|
+
([, v]) => v === svgBase
|
|
1421
|
+
)?.[0];
|
|
1422
|
+
if (tableName && !files.includes(`${tableName}.csv`)) {
|
|
1423
|
+
issues.push(`${ld.name}/${f} orphaned SVG \u2014 no matching ${tableName}.csv`);
|
|
1424
|
+
}
|
|
1425
|
+
} else {
|
|
1426
|
+
issues.push(`${ld.name}/${f} unexpected file \u2014 only CSV and SVG files are allowed`);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
for (const f of files) {
|
|
1430
|
+
if (extname(f) !== ".csv") continue;
|
|
1431
|
+
const tableName = f.replace(".csv", "");
|
|
1432
|
+
const svgName = SVG_FILE_NAMES[tableName];
|
|
1433
|
+
if (svgName && !files.includes(`${svgName}.svg`) && !OPTIONAL_SVG_TABLES.has(tableName)) {
|
|
1434
|
+
issues.push(`${ld.name}/${f} missing paired SVG file "${svgName}.svg"`);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
const topEntries = readdirSync3(dir);
|
|
1439
|
+
for (const f of topEntries) {
|
|
1440
|
+
if (f === "global" || /^lv-\d+$/.test(f)) continue;
|
|
1441
|
+
if (f === "project_metadata.json") continue;
|
|
1442
|
+
if (f.startsWith(".")) continue;
|
|
1443
|
+
issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
|
|
1444
|
+
}
|
|
1445
|
+
const metadataPath = join4(dir, "project_metadata.json");
|
|
1446
|
+
if (existsSync2(metadataPath)) {
|
|
1447
|
+
try {
|
|
1448
|
+
const raw = readFileSync3(metadataPath, "utf-8");
|
|
1449
|
+
const metadata = JSON.parse(raw);
|
|
1450
|
+
if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
|
|
1451
|
+
issues.push("project_metadata.json must be a JSON object");
|
|
1452
|
+
} else {
|
|
1453
|
+
if (!metadata.format_version || typeof metadata.format_version !== "string") {
|
|
1454
|
+
issues.push('project_metadata.json missing or invalid "format_version" (required string)');
|
|
1455
|
+
}
|
|
1456
|
+
for (const key of Object.keys(metadata)) {
|
|
1457
|
+
if (!["format_version", "project_name", "units", "source"].includes(key)) {
|
|
1458
|
+
issues.push(`project_metadata.json unknown field "${key}"`);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
} catch (e) {
|
|
1463
|
+
issues.push(`project_metadata.json failed to parse: ${e.message}`);
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
return issues;
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// src/validate/csv.ts
|
|
1470
|
+
function validateCsvHeaders(path, table, data) {
|
|
1471
|
+
const issues = [];
|
|
1472
|
+
const expected = new Set(table.csvFields.map((f) => f.name));
|
|
1473
|
+
const actual = new Set(data.headers);
|
|
1474
|
+
for (const h of data.headers) {
|
|
1475
|
+
if (!expected.has(h)) {
|
|
1476
|
+
issues.push(`${path} unexpected column "${h}"`);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
for (const f of table.csvFields) {
|
|
1480
|
+
if (f.required && !actual.has(f.name)) {
|
|
1481
|
+
issues.push(`${path} missing required column "${f.name}"`);
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
return issues;
|
|
1485
|
+
}
|
|
1486
|
+
function validateCsvRequired(path, table, data) {
|
|
1487
|
+
const issues = [];
|
|
1488
|
+
const requiredFields = table.csvFields.filter((f) => f.required);
|
|
1489
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1490
|
+
const row = data.rows[i];
|
|
1491
|
+
for (const f of requiredFields) {
|
|
1492
|
+
const val = row[f.name];
|
|
1493
|
+
if (val === void 0 || val === "") {
|
|
1494
|
+
issues.push(`${path}:${i + 2} required field "${f.name}" is empty`);
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
return issues;
|
|
1499
|
+
}
|
|
1500
|
+
function validateCsvEnums(path, table, data) {
|
|
1501
|
+
const issues = [];
|
|
1502
|
+
const enumFields = table.csvFields.filter((f) => f.type === "enum" && f.values);
|
|
1503
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1504
|
+
const row = data.rows[i];
|
|
1505
|
+
for (const f of enumFields) {
|
|
1506
|
+
const val = row[f.name];
|
|
1507
|
+
if (val !== void 0 && val !== "" && !f.values.includes(val)) {
|
|
1508
|
+
issues.push(
|
|
1509
|
+
`${path}:${i + 2} field "${f.name}" value "${val}" is not a valid enum (${f.values.join(", ")})`
|
|
1510
|
+
);
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return issues;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// src/validate/ids.ts
|
|
1518
|
+
function validateIdFormat(path, table, data) {
|
|
1519
|
+
const issues = [];
|
|
1520
|
+
const prefix = table.prefix;
|
|
1521
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1522
|
+
const id = data.rows[i].id;
|
|
1523
|
+
if (!id) continue;
|
|
1524
|
+
const regex = new RegExp(`^${prefix}-\\d+$`);
|
|
1525
|
+
if (!regex.test(id)) {
|
|
1526
|
+
issues.push(`${path}:${i + 2} id "${id}" has wrong format, expected "${prefix}-{n}"`);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
return issues;
|
|
1530
|
+
}
|
|
1531
|
+
function createIdRegistry() {
|
|
1532
|
+
return { ids: /* @__PURE__ */ new Map(), allIds: /* @__PURE__ */ new Map(), issues: [] };
|
|
1533
|
+
}
|
|
1534
|
+
function registerIds(registry, path, tableName, data) {
|
|
1535
|
+
const level = path.split("/")[0];
|
|
1536
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1537
|
+
const id = data.rows[i].id;
|
|
1538
|
+
if (!id) continue;
|
|
1539
|
+
const scopedKey = `${level}/${id}`;
|
|
1540
|
+
const existing = registry.ids.get(scopedKey);
|
|
1541
|
+
if (existing) {
|
|
1542
|
+
if (existing.table === tableName) {
|
|
1543
|
+
registry.issues.push(
|
|
1544
|
+
`${path}:${i + 2} duplicate id "${id}" (first seen in ${existing.path}:${existing.row})`
|
|
1545
|
+
);
|
|
1546
|
+
} else {
|
|
1547
|
+
registry.issues.push(
|
|
1548
|
+
`${path}:${i + 2} id "${id}" conflicts with ${existing.table} in ${existing.path}:${existing.row}`
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
} else {
|
|
1552
|
+
registry.ids.set(scopedKey, { table: tableName, path, row: i + 2 });
|
|
1553
|
+
}
|
|
1554
|
+
registry.allIds.set(id, { table: tableName, path, row: i + 2 });
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
// src/validate/references.ts
|
|
1559
|
+
init_registry();
|
|
1560
|
+
function validateReferences(path, table, data, idRegistry) {
|
|
1561
|
+
const issues = [];
|
|
1562
|
+
const refFields = table.csvFields.filter((f) => f.type === "reference");
|
|
1563
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1564
|
+
const row = data.rows[i];
|
|
1565
|
+
for (const f of refFields) {
|
|
1566
|
+
const val = row[f.name];
|
|
1567
|
+
if (!val) continue;
|
|
1568
|
+
const entry = idRegistry.allIds.get(val);
|
|
1569
|
+
if (!entry) {
|
|
1570
|
+
issues.push(`${path}:${i + 2} ${f.name} "${val}" references non-existent id`);
|
|
1571
|
+
continue;
|
|
1572
|
+
}
|
|
1573
|
+
if (f.reference && f.reference !== "element") {
|
|
1574
|
+
const expectedPrefix = ID_PREFIXES[f.reference];
|
|
1575
|
+
if (expectedPrefix && !val.startsWith(expectedPrefix + "-")) {
|
|
1576
|
+
issues.push(
|
|
1577
|
+
`${path}:${i + 2} ${f.name} "${val}" should reference ${f.reference} (prefix "${expectedPrefix}-")`
|
|
1578
|
+
);
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
return issues;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
// src/validate/ranges.ts
|
|
1587
|
+
var FIELD_MAX = {
|
|
1588
|
+
elevation: 500,
|
|
1589
|
+
// tallest buildings ~500m
|
|
1590
|
+
base_offset: 100,
|
|
1591
|
+
top_offset: 100,
|
|
1592
|
+
thickness: 2,
|
|
1593
|
+
width: 30,
|
|
1594
|
+
height: 20,
|
|
1595
|
+
size_x: 10,
|
|
1596
|
+
size_y: 10,
|
|
1597
|
+
length: 100,
|
|
1598
|
+
position: 1,
|
|
1599
|
+
// parametric 0-1
|
|
1600
|
+
start_x: 1e4,
|
|
1601
|
+
// site coordinates can be large
|
|
1602
|
+
start_y: 1e4,
|
|
1603
|
+
end_x: 1e4,
|
|
1604
|
+
end_y: 1e4,
|
|
1605
|
+
start_z: 500,
|
|
1606
|
+
end_z: 500,
|
|
1607
|
+
step_count: 200
|
|
1608
|
+
// not meters, but still bounded
|
|
1609
|
+
};
|
|
1610
|
+
var DEFAULT_MAX = 1e3;
|
|
1611
|
+
function validateRanges(path, table, data) {
|
|
1612
|
+
const issues = [];
|
|
1613
|
+
const floatFields = table.csvFields.filter(
|
|
1614
|
+
(f) => (f.type === "float" || f.type === "int") && f.name !== "id"
|
|
1615
|
+
);
|
|
1616
|
+
for (let i = 0; i < data.rows.length; i++) {
|
|
1617
|
+
const row = data.rows[i];
|
|
1618
|
+
const rowNum = i + 2;
|
|
1619
|
+
for (const field of floatFields) {
|
|
1620
|
+
const raw = row[field.name];
|
|
1621
|
+
if (raw === void 0 || raw === "") continue;
|
|
1622
|
+
const val = Number(raw);
|
|
1623
|
+
if (isNaN(val)) continue;
|
|
1624
|
+
const max = FIELD_MAX[field.name] ?? DEFAULT_MAX;
|
|
1625
|
+
if (Math.abs(val) > max) {
|
|
1626
|
+
issues.push(
|
|
1627
|
+
`${path}:${rowNum} ${field.name}=${raw} looks like millimeters \u2014 all values must be in meters (max reasonable: ${max})`
|
|
1628
|
+
);
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return issues;
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// src/validate/svg.ts
|
|
1636
|
+
init_svg();
|
|
1637
|
+
var ALLOWED_TAGS = /* @__PURE__ */ new Set(["svg", "g", "path", "rect", "polygon", "circle", "text"]);
|
|
1638
|
+
var FORBIDDEN_TAGS = /* @__PURE__ */ new Set(["line", "defs", "use", "script", "linearGradient", "radialGradient", "filter"]);
|
|
1639
|
+
var EXPECTED_TAGS = {
|
|
1640
|
+
// Line elements → <path>
|
|
1641
|
+
wall: /* @__PURE__ */ new Set(["path"]),
|
|
1642
|
+
structure_wall: /* @__PURE__ */ new Set(["path"]),
|
|
1643
|
+
curtain_wall: /* @__PURE__ */ new Set(["path"]),
|
|
1644
|
+
room_separator: /* @__PURE__ */ new Set(["path"]),
|
|
1645
|
+
stair: /* @__PURE__ */ new Set(["path"]),
|
|
1646
|
+
ramp: /* @__PURE__ */ new Set(["path"]),
|
|
1647
|
+
railing: /* @__PURE__ */ new Set(["path"]),
|
|
1648
|
+
beam: /* @__PURE__ */ new Set(["path"]),
|
|
1649
|
+
brace: /* @__PURE__ */ new Set(["path"]),
|
|
1650
|
+
duct: /* @__PURE__ */ new Set(["path"]),
|
|
1651
|
+
pipe: /* @__PURE__ */ new Set(["path"]),
|
|
1652
|
+
cable_tray: /* @__PURE__ */ new Set(["path"]),
|
|
1653
|
+
conduit: /* @__PURE__ */ new Set(["path"]),
|
|
1654
|
+
// Point elements → <rect> | <circle>
|
|
1655
|
+
column: /* @__PURE__ */ new Set(["rect", "circle"]),
|
|
1656
|
+
structure_column: /* @__PURE__ */ new Set(["rect", "circle"]),
|
|
1657
|
+
equipment: /* @__PURE__ */ new Set(["rect", "circle"]),
|
|
1658
|
+
terminal: /* @__PURE__ */ new Set(["rect", "circle"]),
|
|
1659
|
+
mep_node: /* @__PURE__ */ new Set(["rect", "circle"]),
|
|
1660
|
+
// Polygon elements → <polygon>
|
|
1661
|
+
slab: /* @__PURE__ */ new Set(["polygon"]),
|
|
1662
|
+
roof: /* @__PURE__ */ new Set(["polygon"]),
|
|
1663
|
+
ceiling: /* @__PURE__ */ new Set(["polygon"]),
|
|
1664
|
+
structure_slab: /* @__PURE__ */ new Set(["polygon"]),
|
|
1665
|
+
// Mixed geometry
|
|
1666
|
+
foundation: /* @__PURE__ */ new Set(["rect", "circle", "path", "polygon"]),
|
|
1667
|
+
opening: /* @__PURE__ */ new Set(["rect", "polygon"])
|
|
1668
|
+
};
|
|
1669
|
+
function extractPathCoords(d) {
|
|
1670
|
+
const coords = [];
|
|
1671
|
+
const nums = d.match(/-?[\d.]+/g);
|
|
1672
|
+
if (nums) {
|
|
1673
|
+
for (const n of nums) {
|
|
1674
|
+
const val = parseFloat(n);
|
|
1675
|
+
if (!isNaN(val)) coords.push(val);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
return coords;
|
|
1679
|
+
}
|
|
1680
|
+
function validateSvgFile(displayPath, fullPath, csvIds, isHosted, tableName) {
|
|
1681
|
+
const issues = [];
|
|
1682
|
+
let svg;
|
|
1683
|
+
try {
|
|
1684
|
+
svg = parseSvgFile(fullPath);
|
|
1685
|
+
} catch (e) {
|
|
1686
|
+
issues.push(`${displayPath} failed to parse SVG: ${e.message}`);
|
|
1687
|
+
return issues;
|
|
1688
|
+
}
|
|
1689
|
+
if (!svg.hasYFlip) {
|
|
1690
|
+
issues.push(`${displayPath} missing required <g transform="scale(1,-1)"> for Y-axis flip`);
|
|
1691
|
+
}
|
|
1692
|
+
for (const tag of svg.allTags) {
|
|
1693
|
+
if (FORBIDDEN_TAGS.has(tag)) {
|
|
1694
|
+
issues.push(`${displayPath} forbidden tag <${tag}> found`);
|
|
1695
|
+
}
|
|
1696
|
+
if (!ALLOWED_TAGS.has(tag) && !FORBIDDEN_TAGS.has(tag) && !tag.startsWith("?")) {
|
|
1697
|
+
issues.push(`${displayPath} unknown tag <${tag}>`);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
const svgIds = /* @__PURE__ */ new Set();
|
|
1701
|
+
for (const el of svg.elements) {
|
|
1702
|
+
if (svgIds.has(el.id)) {
|
|
1703
|
+
issues.push(`${displayPath} duplicate SVG element id "${el.id}"`);
|
|
1704
|
+
}
|
|
1705
|
+
svgIds.add(el.id);
|
|
1706
|
+
if (!csvIds.has(el.id)) {
|
|
1707
|
+
issues.push(`${displayPath} SVG element "${el.id}" has no matching CSV row`);
|
|
1708
|
+
}
|
|
1709
|
+
if (tableName && EXPECTED_TAGS[tableName] && !EXPECTED_TAGS[tableName].has(el.tag)) {
|
|
1710
|
+
const expected = [...EXPECTED_TAGS[tableName]].join(" or ");
|
|
1711
|
+
issues.push(`${displayPath} element "${el.id}" uses <${el.tag}> but ${tableName} requires <${expected}>`);
|
|
1712
|
+
}
|
|
1713
|
+
if (isHosted && !el.attrs["data-host"]) {
|
|
1714
|
+
issues.push(`${displayPath} hosted element "${el.id}" missing data-host attribute`);
|
|
1715
|
+
}
|
|
1716
|
+
if (el.tag === "path" && el.attrs.d) {
|
|
1717
|
+
const coords = extractPathCoords(el.attrs.d);
|
|
1718
|
+
for (const val of coords) {
|
|
1719
|
+
if (Math.abs(val) > 1e3) {
|
|
1720
|
+
issues.push(
|
|
1721
|
+
`${displayPath} element "${el.id}" path coordinates look like millimeters \u2014 SVG coordinates must be in meters`
|
|
1722
|
+
);
|
|
1723
|
+
break;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
const coordAttrs = ["x", "y", "cx", "cy", "r", "width", "height"];
|
|
1728
|
+
for (const attr of coordAttrs) {
|
|
1729
|
+
const raw = el.attrs[attr];
|
|
1730
|
+
if (raw === void 0) continue;
|
|
1731
|
+
const val = Number(raw);
|
|
1732
|
+
if (!isNaN(val) && Math.abs(val) > 1e3) {
|
|
1733
|
+
issues.push(
|
|
1734
|
+
`${displayPath} element "${el.id}" ${attr}=${raw} looks like millimeters \u2014 SVG coordinates must be in meters`
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
if (el.attrs["points"]) {
|
|
1739
|
+
const points = el.attrs["points"].trim().split(/\s+/);
|
|
1740
|
+
for (const pt of points) {
|
|
1741
|
+
const [px, py] = pt.split(",").map(Number);
|
|
1742
|
+
if (!isNaN(px) && Math.abs(px) > 1e3 || !isNaN(py) && Math.abs(py) > 1e3) {
|
|
1743
|
+
issues.push(
|
|
1744
|
+
`${displayPath} element "${el.id}" polygon point ${pt} looks like millimeters \u2014 coordinates must be in meters`
|
|
1745
|
+
);
|
|
1746
|
+
break;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
return issues;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
// src/validate/index.ts
|
|
1755
|
+
function validate(dir) {
|
|
1756
|
+
const issues = [];
|
|
1757
|
+
issues.push(...validateStructure(dir));
|
|
1758
|
+
const registry = buildRegistry(getSpecDir());
|
|
1759
|
+
const layout = discoverLayout(dir);
|
|
1760
|
+
const csvEntries = [];
|
|
1761
|
+
const allDirs = [
|
|
1762
|
+
{ name: "global", path: layout.globalDir },
|
|
1763
|
+
...layout.levelDirs
|
|
1764
|
+
];
|
|
1765
|
+
for (const d of allDirs) {
|
|
1766
|
+
if (!existsSync3(d.path)) continue;
|
|
1767
|
+
const files = listFiles(d.path);
|
|
1768
|
+
for (const f of files) {
|
|
1769
|
+
if (!f.endsWith(".csv")) continue;
|
|
1770
|
+
const tableName = f.replace(".csv", "");
|
|
1771
|
+
const table = registry.get(tableName);
|
|
1772
|
+
if (!table) continue;
|
|
1773
|
+
const fullPath = join5(d.path, f);
|
|
1774
|
+
const relPath = `${d.name}/${f}`;
|
|
1775
|
+
let data;
|
|
1776
|
+
try {
|
|
1777
|
+
data = readCsv(fullPath);
|
|
1778
|
+
} catch (e) {
|
|
1779
|
+
issues.push(`${relPath} failed to read CSV: ${e.message}`);
|
|
1780
|
+
continue;
|
|
1781
|
+
}
|
|
1782
|
+
csvEntries.push({ path: relPath, fullPath, tableName, table, data });
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
for (const entry of csvEntries) {
|
|
1786
|
+
issues.push(...validateCsvHeaders(entry.path, entry.table, entry.data));
|
|
1787
|
+
issues.push(...validateCsvRequired(entry.path, entry.table, entry.data));
|
|
1788
|
+
}
|
|
1789
|
+
for (const entry of csvEntries) {
|
|
1790
|
+
issues.push(...validateIdFormat(entry.path, entry.table, entry.data));
|
|
1791
|
+
}
|
|
1792
|
+
const idRegistry = createIdRegistry();
|
|
1793
|
+
for (const entry of csvEntries) {
|
|
1794
|
+
registerIds(idRegistry, entry.path, entry.tableName, entry.data);
|
|
1795
|
+
}
|
|
1796
|
+
issues.push(...idRegistry.issues);
|
|
1797
|
+
for (const entry of csvEntries) {
|
|
1798
|
+
issues.push(...validateCsvEnums(entry.path, entry.table, entry.data));
|
|
1799
|
+
}
|
|
1800
|
+
for (const entry of csvEntries) {
|
|
1801
|
+
issues.push(...validateReferences(entry.path, entry.table, entry.data, idRegistry));
|
|
1802
|
+
}
|
|
1803
|
+
for (const entry of csvEntries) {
|
|
1804
|
+
issues.push(...validateRanges(entry.path, entry.table, entry.data));
|
|
1805
|
+
}
|
|
1806
|
+
for (const entry of csvEntries) {
|
|
1807
|
+
if (!entry.table.hostType) continue;
|
|
1808
|
+
for (let i = 0; i < entry.data.rows.length; i++) {
|
|
1809
|
+
const row = entry.data.rows[i];
|
|
1810
|
+
const pos = row.position;
|
|
1811
|
+
if (pos === void 0 || pos === "") continue;
|
|
1812
|
+
const val = Number(pos);
|
|
1813
|
+
if (isNaN(val) || val < 0 || val > 1) {
|
|
1814
|
+
issues.push(
|
|
1815
|
+
`${entry.path}:${i + 2} position=${pos} must be between 0.0 and 1.0`
|
|
1816
|
+
);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
for (const d of allDirs) {
|
|
1821
|
+
if (!existsSync3(d.path) || d.name === "global") continue;
|
|
1822
|
+
const files = listFiles(d.path);
|
|
1823
|
+
for (const f of files) {
|
|
1824
|
+
if (!f.endsWith(".svg")) continue;
|
|
1825
|
+
const svgBase = f.replace(".svg", "");
|
|
1826
|
+
const tableEntry = Object.entries(SVG_FILE_NAMES).find(([, v]) => v === svgBase);
|
|
1827
|
+
if (!tableEntry) continue;
|
|
1828
|
+
const [tableName] = tableEntry;
|
|
1829
|
+
const table = registry.get(tableName);
|
|
1830
|
+
if (!table) continue;
|
|
1831
|
+
const csvIds = /* @__PURE__ */ new Set();
|
|
1832
|
+
for (const entry of csvEntries) {
|
|
1833
|
+
if (entry.tableName === tableName) {
|
|
1834
|
+
const entryDir = entry.path.split("/")[0];
|
|
1835
|
+
if (entryDir === d.name) {
|
|
1836
|
+
for (const row of entry.data.rows) {
|
|
1837
|
+
if (row.id) csvIds.add(row.id);
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
const svgFullPath = join5(d.path, f);
|
|
1843
|
+
const relPath = `${d.name}/${f}`;
|
|
1844
|
+
const isHosted = !!table.hostType;
|
|
1845
|
+
issues.push(...validateSvgFile(relPath, svgFullPath, csvIds, isHosted, tableName));
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return issues;
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
// src/index.ts
|
|
1852
|
+
init_registry();
|
|
1853
|
+
init_fs();
|
|
1854
|
+
init_csv();
|
|
1855
|
+
import { existsSync as existsSync8 } from "fs";
|
|
1856
|
+
import { join as join10 } from "path";
|
|
1857
|
+
var program = new Command();
|
|
1858
|
+
program.name("bimdown").description("BimDown CLI \u2014 validate, query, and manage BimDown projects").version("0.1.0");
|
|
1859
|
+
program.command("validate").argument("<dir>", "BimDown project directory").description("Validate a BimDown project directory").action((dir) => {
|
|
1860
|
+
const absDir = resolve(dir);
|
|
1861
|
+
const issues = validate(absDir);
|
|
1862
|
+
if (issues.length === 0) {
|
|
1863
|
+
console.log("No issues found.");
|
|
1864
|
+
} else {
|
|
1865
|
+
for (const issue of issues) {
|
|
1866
|
+
console.log(issue);
|
|
1867
|
+
}
|
|
1868
|
+
console.log(`
|
|
1869
|
+
${issues.length} issue(s) found.`);
|
|
1870
|
+
process.exitCode = 1;
|
|
1871
|
+
}
|
|
1872
|
+
});
|
|
1873
|
+
program.command("query").argument("<dir>", "BimDown project directory").argument("<sql>", "SQL query to execute").option("--json", "Output results as JSON").description("Hydrate into DuckDB and execute a SQL query").action(async (dir, sql, opts) => {
|
|
1874
|
+
const absDir = resolve(dir);
|
|
1875
|
+
const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
|
|
1876
|
+
const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
|
|
1877
|
+
const conn = await getConnection2();
|
|
1878
|
+
try {
|
|
1879
|
+
await hydrate2(conn, absDir);
|
|
1880
|
+
const result = await runQuery2(conn, sql);
|
|
1881
|
+
if (opts.json) {
|
|
1882
|
+
console.log(JSON.stringify(result.rows, jsonReplacer, 2));
|
|
1883
|
+
} else {
|
|
1884
|
+
printTable(result.columns, result.rows);
|
|
1885
|
+
}
|
|
1886
|
+
} finally {
|
|
1887
|
+
await closeConnection2();
|
|
1888
|
+
}
|
|
1889
|
+
});
|
|
1890
|
+
program.command("sync").argument("<dir>", "BimDown project directory").description("Hydrate, then dehydrate back (sync DuckDB changes to files)").action(async (dir) => {
|
|
1891
|
+
const absDir = resolve(dir);
|
|
1892
|
+
const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
|
|
1893
|
+
const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
|
|
1894
|
+
const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
|
|
1895
|
+
const conn = await getConnection2();
|
|
1896
|
+
try {
|
|
1897
|
+
const tables = await hydrate2(conn, absDir);
|
|
1898
|
+
console.log(`Hydrated ${tables.length} tables: ${tables.join(", ")}`);
|
|
1899
|
+
await dehydrate2(conn, absDir);
|
|
1900
|
+
console.log("Sync complete \u2014 files updated.");
|
|
1901
|
+
} finally {
|
|
1902
|
+
await closeConnection2();
|
|
1903
|
+
}
|
|
1904
|
+
});
|
|
1905
|
+
program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
|
|
1906
|
+
const absDir = resolve(dir);
|
|
1907
|
+
const registry = buildRegistry(getSpecDir());
|
|
1908
|
+
const layout = discoverLayout(absDir);
|
|
1909
|
+
const levelCsv = join10(layout.globalDir, "level.csv");
|
|
1910
|
+
if (existsSync8(levelCsv)) {
|
|
1911
|
+
const levels = readCsv(levelCsv);
|
|
1912
|
+
console.log("Levels:");
|
|
1913
|
+
for (const row of levels.rows) {
|
|
1914
|
+
console.log(` ${row.id} ${row.name || row.number || ""} elevation=${row.elevation}`);
|
|
1915
|
+
}
|
|
1916
|
+
console.log();
|
|
1917
|
+
}
|
|
1918
|
+
const allDirs = [
|
|
1919
|
+
{ name: "global", path: layout.globalDir },
|
|
1920
|
+
...layout.levelDirs
|
|
1921
|
+
];
|
|
1922
|
+
const totals = {};
|
|
1923
|
+
for (const d of allDirs) {
|
|
1924
|
+
if (!existsSync8(d.path)) continue;
|
|
1925
|
+
const files = listFiles(d.path);
|
|
1926
|
+
const counts = [];
|
|
1927
|
+
for (const f of files) {
|
|
1928
|
+
if (!f.endsWith(".csv")) continue;
|
|
1929
|
+
const tableName = f.replace(".csv", "");
|
|
1930
|
+
if (!registry.has(tableName)) continue;
|
|
1931
|
+
const data = readCsv(join10(d.path, f));
|
|
1932
|
+
counts.push(`${tableName}: ${data.rows.length}`);
|
|
1933
|
+
totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
|
|
1934
|
+
}
|
|
1935
|
+
if (counts.length > 0) {
|
|
1936
|
+
console.log(`${d.name}/ ${counts.join(", ")}`);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
console.log();
|
|
1940
|
+
console.log("Totals:");
|
|
1941
|
+
let grand = 0;
|
|
1942
|
+
for (const [table, count] of Object.entries(totals).sort(([a], [b]) => a.localeCompare(b))) {
|
|
1943
|
+
console.log(` ${table}: ${count}`);
|
|
1944
|
+
grand += count;
|
|
1945
|
+
}
|
|
1946
|
+
console.log(` TOTAL: ${grand}`);
|
|
1947
|
+
});
|
|
1948
|
+
program.command("resolve-topology").argument("<dir>", "BimDown project directory").description("Auto-resolve MEP topology: detect coincident endpoints, generate mep_nodes, fill connectivity").action(async (dir) => {
|
|
1949
|
+
const absDir = resolve(dir);
|
|
1950
|
+
const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
|
|
1951
|
+
resolveTopology2(absDir);
|
|
1952
|
+
});
|
|
1953
|
+
program.command("merge").argument("<dirs...>", "Two or more BimDown project directories to merge").requiredOption("-o, --output <dir>", "Output directory for merged project").description("Merge multiple BimDown project directories into one, resolving ID conflicts").action(async (dirs, opts) => {
|
|
1954
|
+
if (dirs.length < 2) {
|
|
1955
|
+
console.error("At least 2 source directories are required.");
|
|
1956
|
+
process.exitCode = 1;
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
1959
|
+
const absDirs = dirs.map((d) => resolve(d));
|
|
1960
|
+
const absOut = resolve(opts.output);
|
|
1961
|
+
const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
|
|
1962
|
+
await merge2(absDirs, absOut);
|
|
1963
|
+
});
|
|
1964
|
+
program.command("schema").argument("[table]", "Table name (omit for all tables)").description("Print resolved schema for a table or all tables").action((table) => {
|
|
1965
|
+
const registry = buildRegistry(getSpecDir());
|
|
1966
|
+
const tables = table ? [table] : [...registry.keys()].sort();
|
|
1967
|
+
for (const t of tables) {
|
|
1968
|
+
const resolved = registry.get(t);
|
|
1969
|
+
if (!resolved) {
|
|
1970
|
+
console.error(`Unknown table: ${t}`);
|
|
1971
|
+
process.exitCode = 1;
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
console.log(`\u2500\u2500 ${resolved.name} (prefix: ${resolved.prefix}) \u2500\u2500`);
|
|
1975
|
+
if (resolved.hostType) {
|
|
1976
|
+
console.log(` host_type: ${resolved.hostType}`);
|
|
1977
|
+
}
|
|
1978
|
+
console.log(" CSV fields:");
|
|
1979
|
+
for (const f of resolved.csvFields) {
|
|
1980
|
+
const tags = [];
|
|
1981
|
+
if (f.required) tags.push("required");
|
|
1982
|
+
if (f.type === "reference") tags.push(`ref:${f.reference}`);
|
|
1983
|
+
if (f.type === "enum") tags.push(`enum:[${f.values?.join("|")}]`);
|
|
1984
|
+
const tagStr = tags.length > 0 ? ` (${tags.join(", ")})` : "";
|
|
1985
|
+
console.log(` ${f.name}: ${f.type}${tagStr}`);
|
|
1986
|
+
}
|
|
1987
|
+
if (resolved.computedFields.length > 0) {
|
|
1988
|
+
console.log(" Computed fields:");
|
|
1989
|
+
for (const f of resolved.computedFields) {
|
|
1990
|
+
console.log(` ${f.name}: ${f.type}`);
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
console.log();
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
program.parse();
|
|
1997
|
+
function printTable(columns, rows) {
|
|
1998
|
+
if (rows.length === 0) {
|
|
1999
|
+
console.log("(empty result)");
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
const widths = columns.map((c) => c.length);
|
|
2003
|
+
for (const row of rows) {
|
|
2004
|
+
for (let i = 0; i < columns.length; i++) {
|
|
2005
|
+
const val = formatValue(row[columns[i]]);
|
|
2006
|
+
widths[i] = Math.max(widths[i], val.length);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
const header = columns.map((c, i) => c.padEnd(widths[i])).join(" | ");
|
|
2010
|
+
console.log(header);
|
|
2011
|
+
console.log(widths.map((w) => "-".repeat(w)).join("-+-"));
|
|
2012
|
+
for (const row of rows) {
|
|
2013
|
+
const line = columns.map((c, i) => formatValue(row[c]).padEnd(widths[i])).join(" | ");
|
|
2014
|
+
console.log(line);
|
|
2015
|
+
}
|
|
2016
|
+
console.log(`
|
|
2017
|
+
(${rows.length} row(s))`);
|
|
2018
|
+
}
|
|
2019
|
+
function formatValue(val) {
|
|
2020
|
+
if (val == null) return "";
|
|
2021
|
+
if (typeof val === "bigint") return val.toString();
|
|
2022
|
+
return String(val);
|
|
2023
|
+
}
|
|
2024
|
+
function jsonReplacer(_key, value) {
|
|
2025
|
+
if (typeof value === "bigint") return Number(value);
|
|
2026
|
+
return value;
|
|
2027
|
+
}
|
|
2028
|
+
//# sourceMappingURL=index.js.map
|