bimdown-cli 0.2.2 → 0.3.0

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/dist/index.js CHANGED
@@ -518,8 +518,8 @@ var hydrate_exports = {};
518
518
  __export(hydrate_exports, {
519
519
  hydrate: () => hydrate
520
520
  });
521
- import { existsSync as existsSync8 } from "fs";
522
- import { join as join9 } from "path";
521
+ import { existsSync as existsSync10 } from "fs";
522
+ import { join as join11 } from "path";
523
523
  async function hydrate(conn, dir) {
524
524
  const registry = buildRegistry(getSpecDir());
525
525
  const layout = discoverLayout(dir);
@@ -531,8 +531,8 @@ async function hydrate(conn, dir) {
531
531
  for (const [tableName, table] of registry) {
532
532
  const csvFiles = [];
533
533
  for (const d of allDirs) {
534
- const csvPath = join9(d.path, `${tableName}.csv`);
535
- if (existsSync8(csvPath)) {
534
+ const csvPath = join11(d.path, `${tableName}.csv`);
535
+ if (existsSync10(csvPath)) {
536
536
  csvFiles.push({ dir: d.name, fullPath: csvPath });
537
537
  }
538
538
  }
@@ -565,8 +565,8 @@ async function injectGeometry(conn, tableName, dirs) {
565
565
  const geometries = /* @__PURE__ */ new Map();
566
566
  for (const d of dirs) {
567
567
  if (d.name === "global") continue;
568
- const svgPath = join9(d.path, `${svgName}.svg`);
569
- if (!existsSync8(svgPath)) continue;
568
+ const svgPath = join11(d.path, `${svgName}.svg`);
569
+ if (!existsSync10(svgPath)) continue;
570
570
  try {
571
571
  const svg = parseSvgFile(svgPath);
572
572
  for (const el of svg.elements) {
@@ -626,8 +626,8 @@ var dehydrate_exports = {};
626
626
  __export(dehydrate_exports, {
627
627
  dehydrate: () => dehydrate
628
628
  });
629
- import { existsSync as existsSync9, mkdirSync } from "fs";
630
- import { join as join10 } from "path";
629
+ import { existsSync as existsSync11, mkdirSync } from "fs";
630
+ import { join as join12 } from "path";
631
631
  async function dehydrate(conn, dir) {
632
632
  const registry = buildRegistry(getSpecDir());
633
633
  for (const [tableName, table] of registry) {
@@ -643,8 +643,8 @@ async function dehydrate(conn, dir) {
643
643
  );
644
644
  for (const partRow of partResult.rows) {
645
645
  const partition = String(partRow._partition);
646
- const outDir = join10(dir, partition);
647
- if (!existsSync9(outDir)) mkdirSync(outDir, { recursive: true });
646
+ const outDir = join12(dir, partition);
647
+ if (!existsSync11(outDir)) mkdirSync(outDir, { recursive: true });
648
648
  const selectCols = csvHeaders.map((h) => `"${h}"`).join(", ");
649
649
  const dataResult = await runQuery(
650
650
  conn,
@@ -661,7 +661,7 @@ async function dehydrate(conn, dir) {
661
661
  return row;
662
662
  })
663
663
  };
664
- writeCsv(join10(outDir, `${tableName}.csv`), data);
664
+ writeCsv(join12(outDir, `${tableName}.csv`), data);
665
665
  }
666
666
  }
667
667
  }
@@ -679,8 +679,8 @@ var render_exports = {};
679
679
  __export(render_exports, {
680
680
  renderLevel: () => renderLevel
681
681
  });
682
- import { existsSync as existsSync10 } from "fs";
683
- import { join as join11 } from "path";
682
+ import { existsSync as existsSync12 } from "fs";
683
+ import { join as join13 } from "path";
684
684
  function elementBounds2(el) {
685
685
  switch (el.tag) {
686
686
  case "path": {
@@ -766,8 +766,8 @@ function escapeXml(s) {
766
766
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
767
767
  }
768
768
  function renderHostedElements(levelDir, tableName, wallElements) {
769
- const csvPath = join11(levelDir.path, `${tableName}.csv`);
770
- if (!existsSync10(csvPath)) return [];
769
+ const csvPath = join13(levelDir.path, `${tableName}.csv`);
770
+ if (!existsSync12(csvPath)) return [];
771
771
  const csv = readCsv(csvPath);
772
772
  const color = COLORS[tableName] ?? DEFAULT_COLOR;
773
773
  const results = [];
@@ -822,8 +822,8 @@ function renderHostedElements(levelDir, tableName, wallElements) {
822
822
  return results;
823
823
  }
824
824
  function renderSpaces(levelDir) {
825
- const csvPath = join11(levelDir.path, "space.csv");
826
- if (!existsSync10(csvPath)) return [];
825
+ const csvPath = join13(levelDir.path, "space.csv");
826
+ if (!existsSync12(csvPath)) return [];
827
827
  const csv = readCsv(csvPath);
828
828
  const color = COLORS.space ?? DEFAULT_COLOR;
829
829
  const results = [];
@@ -831,8 +831,8 @@ function renderSpaces(levelDir) {
831
831
  for (const row of csv.rows) {
832
832
  nameMap.set(row.id, row.name ?? row.id ?? "");
833
833
  }
834
- const svgPath = join11(levelDir.path, "space.svg");
835
- if (existsSync10(svgPath)) {
834
+ const svgPath = join13(levelDir.path, "space.svg");
835
+ if (existsSync12(svgPath)) {
836
836
  try {
837
837
  const svg = parseSvgFile(svgPath);
838
838
  for (const el of svg.elements) {
@@ -899,8 +899,8 @@ function renderLevel(projectDir, levelId) {
899
899
  if (CSV_ONLY_TABLES.has(tableName)) continue;
900
900
  const svgName = SVG_FILE_NAMES[tableName];
901
901
  if (!svgName) continue;
902
- const svgPath = join11(levelDir.path, svgName + ".svg");
903
- if (!existsSync10(svgPath)) continue;
902
+ const svgPath = join13(levelDir.path, svgName + ".svg");
903
+ if (!existsSync12(svgPath)) continue;
904
904
  const svg = parseSvgFile(svgPath);
905
905
  for (const el of svg.elements) {
906
906
  allElements.push({ tableName, el });
@@ -1009,8 +1009,8 @@ var resolve_topology_exports = {};
1009
1009
  __export(resolve_topology_exports, {
1010
1010
  resolveTopology: () => resolveTopology
1011
1011
  });
1012
- import { existsSync as existsSync11, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
1013
- import { join as join12 } from "path";
1012
+ import { existsSync as existsSync13, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
1013
+ import { join as join14 } from "path";
1014
1014
  function dist3d(a, b) {
1015
1015
  const dx = a.x - b.x;
1016
1016
  const dy = a.y - b.y;
@@ -1019,10 +1019,10 @@ function dist3d(a, b) {
1019
1019
  }
1020
1020
  function insideBBox(point, node) {
1021
1021
  const dz = Math.abs(point.z - node.pos.z);
1022
- if (dz > TOLERANCE3) return false;
1022
+ if (dz > TOLERANCE4) return false;
1023
1023
  const dx = Math.abs(point.x - node.pos.x);
1024
1024
  const dy = Math.abs(point.y - node.pos.y);
1025
- return dx <= node.halfW + TOLERANCE3 && dy <= node.halfH + TOLERANCE3;
1025
+ return dx <= node.halfW + TOLERANCE4 && dy <= node.halfH + TOLERANCE4;
1026
1026
  }
1027
1027
  function resolveTopology(dir) {
1028
1028
  buildRegistry(getSpecDir());
@@ -1037,14 +1037,14 @@ function resolveTopology(dir) {
1037
1037
  let skippedStart = 0;
1038
1038
  let skippedEnd = 0;
1039
1039
  for (const d of allDirs) {
1040
- if (!existsSync11(d.path)) continue;
1040
+ if (!existsSync13(d.path)) continue;
1041
1041
  const files = listFiles(d.path);
1042
1042
  for (const tableName of CURVE_TABLES) {
1043
1043
  if (!files.includes(`${tableName}.csv`)) continue;
1044
1044
  const svgName = SVG_FILE_NAMES[tableName];
1045
1045
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1046
- const csvPath = join12(d.path, `${tableName}.csv`);
1047
- const svgPath = join12(d.path, `${svgName}.svg`);
1046
+ const csvPath = join14(d.path, `${tableName}.csv`);
1047
+ const svgPath = join14(d.path, `${svgName}.svg`);
1048
1048
  const csv = readCsv(csvPath);
1049
1049
  const key = `${d.name}/${tableName}`;
1050
1050
  curveData.set(key, { csv, path: csvPath });
@@ -1094,14 +1094,14 @@ function resolveTopology(dir) {
1094
1094
  }
1095
1095
  const nodes = [];
1096
1096
  for (const d of allDirs) {
1097
- if (!existsSync11(d.path)) continue;
1097
+ if (!existsSync13(d.path)) continue;
1098
1098
  const files = listFiles(d.path);
1099
1099
  for (const tableName of NODE_TABLES) {
1100
1100
  if (!files.includes(`${tableName}.csv`)) continue;
1101
1101
  const svgName = SVG_FILE_NAMES[tableName];
1102
1102
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1103
- const csvPath = join12(d.path, `${tableName}.csv`);
1104
- const svgPath = join12(d.path, `${svgName}.svg`);
1103
+ const csvPath = join14(d.path, `${tableName}.csv`);
1104
+ const svgPath = join14(d.path, `${svgName}.svg`);
1105
1105
  const csv = readCsv(csvPath);
1106
1106
  let svgElements;
1107
1107
  try {
@@ -1156,7 +1156,7 @@ function resolveTopology(dir) {
1156
1156
  for (const ep of stillFree) {
1157
1157
  let found = false;
1158
1158
  for (const j of junctions) {
1159
- if (dist3d(ep.point, j.point) < TOLERANCE3) {
1159
+ if (dist3d(ep.point, j.point) < TOLERANCE4) {
1160
1160
  j.endpoints.push(ep);
1161
1161
  found = true;
1162
1162
  break;
@@ -1196,12 +1196,12 @@ function resolveTopology(dir) {
1196
1196
  newNodesByLevel.set(j.levelDir, arr);
1197
1197
  }
1198
1198
  for (const [levelDir, levelJunctions] of newNodesByLevel) {
1199
- const dirPath = levelDir === "global" ? layout.globalDir : join12(dir, levelDir);
1200
- if (!existsSync11(dirPath)) mkdirSync2(dirPath, { recursive: true });
1201
- const csvPath = join12(dirPath, "mep_node.csv");
1202
- const svgPath = join12(dirPath, "mep_node.svg");
1199
+ const dirPath = levelDir === "global" ? layout.globalDir : join14(dir, levelDir);
1200
+ if (!existsSync13(dirPath)) mkdirSync2(dirPath, { recursive: true });
1201
+ const csvPath = join14(dirPath, "mep_node.csv");
1202
+ const svgPath = join14(dirPath, "mep_node.svg");
1203
1203
  let csv;
1204
- if (existsSync11(csvPath)) {
1204
+ if (existsSync13(csvPath)) {
1205
1205
  csv = readCsv(csvPath);
1206
1206
  } else {
1207
1207
  csv = { headers: ["id", "number", "base_offset", "system_type"], rows: [] };
@@ -1210,7 +1210,7 @@ function resolveTopology(dir) {
1210
1210
  if (!csv.headers.includes(h)) csv.headers.push(h);
1211
1211
  }
1212
1212
  let existingSvgElements = [];
1213
- if (existsSync11(svgPath)) {
1213
+ if (existsSync13(svgPath)) {
1214
1214
  try {
1215
1215
  existingSvgElements = parseSvgFile(svgPath).elements;
1216
1216
  } catch {
@@ -1263,7 +1263,7 @@ function resolveTopology(dir) {
1263
1263
  const pad = Math.max(maxX - minX, maxY - minY) * 0.02;
1264
1264
  viewBox = `${(minX - pad).toFixed(3)} ${(-(maxY + pad)).toFixed(3)} ${(maxX - minX + pad * 2).toFixed(3)} ${(maxY - minY + pad * 2).toFixed(3)}`;
1265
1265
  }
1266
- writeFileSync3(svgPath, [
1266
+ writeFileSync4(svgPath, [
1267
1267
  '<?xml version="1.0" encoding="utf-8"?>',
1268
1268
  `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
1269
1269
  ' <g transform="scale(1,-1)">',
@@ -1312,7 +1312,7 @@ function resolveTopology(dir) {
1312
1312
  console.log(`Updated ${updatedRows} curve rows`);
1313
1313
  }
1314
1314
  }
1315
- var TOLERANCE3, CURVE_TABLES, NODE_TABLES;
1315
+ var TOLERANCE4, CURVE_TABLES, NODE_TABLES;
1316
1316
  var init_resolve_topology = __esm({
1317
1317
  "src/commands/resolve-topology.ts"() {
1318
1318
  "use strict";
@@ -1320,7 +1320,7 @@ var init_resolve_topology = __esm({
1320
1320
  init_svg();
1321
1321
  init_fs();
1322
1322
  init_registry();
1323
- TOLERANCE3 = 0.01;
1323
+ TOLERANCE4 = 0.01;
1324
1324
  CURVE_TABLES = ["duct", "pipe", "cable_tray", "conduit"];
1325
1325
  NODE_TABLES = ["equipment", "terminal", "mep_node"];
1326
1326
  }
@@ -1331,8 +1331,8 @@ var merge_exports = {};
1331
1331
  __export(merge_exports, {
1332
1332
  merge: () => merge
1333
1333
  });
1334
- import { existsSync as existsSync12, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
1335
- import { join as join13, basename as basename2 } from "path";
1334
+ import { existsSync as existsSync14, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
1335
+ import { join as join15, basename as basename2 } from "path";
1336
1336
  async function merge(dirs, outputDir) {
1337
1337
  const registry = buildRegistry(getSpecDir());
1338
1338
  console.log(`Scanning ${dirs.length} sources...`);
@@ -1342,10 +1342,10 @@ async function merge(dirs, outputDir) {
1342
1342
  const { canonicalGrids, gridRemaps } = deduplicateGrids(sources);
1343
1343
  console.log(`Merged grids: ${canonicalGrids.rows.length} unique grids`);
1344
1344
  const fullRemaps = buildFullRemaps(sources, levelRemaps, gridRemaps, registry);
1345
- mkdirSync3(join13(outputDir, "global"), { recursive: true });
1346
- writeCsv(join13(outputDir, "global", "level.csv"), canonicalLevels);
1345
+ mkdirSync3(join15(outputDir, "global"), { recursive: true });
1346
+ writeCsv(join15(outputDir, "global", "level.csv"), canonicalLevels);
1347
1347
  if (canonicalGrids.rows.length > 0) {
1348
- writeCsv(join13(outputDir, "global", "grid.csv"), canonicalGrids);
1348
+ writeCsv(join15(outputDir, "global", "grid.csv"), canonicalGrids);
1349
1349
  }
1350
1350
  writeIdMap(outputDir, sources, fullRemaps);
1351
1351
  const levelDirMap = buildLevelDirMap(sources, fullRemaps);
@@ -1356,26 +1356,26 @@ async function merge(dirs, outputDir) {
1356
1356
  function scanSource(dir, registry) {
1357
1357
  const layout = discoverLayout(dir);
1358
1358
  const name = basename2(dir);
1359
- const levelPath = join13(layout.globalDir, "level.csv");
1360
- if (!existsSync12(levelPath)) {
1359
+ const levelPath = join15(layout.globalDir, "level.csv");
1360
+ if (!existsSync14(levelPath)) {
1361
1361
  throw new Error(`Missing level.csv in ${dir}/global/`);
1362
1362
  }
1363
1363
  const levels = readCsv(levelPath);
1364
- const gridPath = join13(layout.globalDir, "grid.csv");
1365
- const grids = existsSync12(gridPath) ? readCsv(gridPath) : null;
1366
- const idMapPath = join13(layout.globalDir, "_IdMap.csv");
1367
- const idMap = existsSync12(idMapPath) ? readCsv(idMapPath) : null;
1364
+ const gridPath = join15(layout.globalDir, "grid.csv");
1365
+ const grids = existsSync14(gridPath) ? readCsv(gridPath) : null;
1366
+ const idMapPath = join15(layout.globalDir, "_IdMap.csv");
1367
+ const idMap = existsSync14(idMapPath) ? readCsv(idMapPath) : null;
1368
1368
  const globalData = /* @__PURE__ */ new Map();
1369
- if (existsSync12(layout.globalDir)) {
1369
+ if (existsSync14(layout.globalDir)) {
1370
1370
  for (const f of listFiles(layout.globalDir)) {
1371
1371
  if (!f.endsWith(".csv")) continue;
1372
1372
  const tableName = f.replace(".csv", "");
1373
1373
  if (tableName === "level" || tableName === "grid" || tableName === "_IdMap") continue;
1374
1374
  if (!registry.has(tableName)) continue;
1375
- const csv = readCsv(join13(layout.globalDir, f));
1375
+ const csv = readCsv(join15(layout.globalDir, f));
1376
1376
  const svgName = SVG_FILE_NAMES[tableName];
1377
- const svgFile = svgName ? join13(layout.globalDir, svgName + ".svg") : null;
1378
- globalData.set(tableName, { csv, svgFile: svgFile && existsSync12(svgFile) ? svgFile : null });
1377
+ const svgFile = svgName ? join15(layout.globalDir, svgName + ".svg") : null;
1378
+ globalData.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1379
1379
  }
1380
1380
  }
1381
1381
  const levelData = /* @__PURE__ */ new Map();
@@ -1385,10 +1385,10 @@ function scanSource(dir, registry) {
1385
1385
  if (!f.endsWith(".csv")) continue;
1386
1386
  const tableName = f.replace(".csv", "");
1387
1387
  if (!registry.has(tableName)) continue;
1388
- const csv = readCsv(join13(ld.path, f));
1388
+ const csv = readCsv(join15(ld.path, f));
1389
1389
  const svgName = SVG_FILE_NAMES[tableName];
1390
- const svgFile = svgName ? join13(ld.path, svgName + ".svg") : null;
1391
- tables.set(tableName, { csv, svgFile: svgFile && existsSync12(svgFile) ? svgFile : null });
1390
+ const svgFile = svgName ? join15(ld.path, svgName + ".svg") : null;
1391
+ tables.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1392
1392
  }
1393
1393
  if (tables.size > 0) {
1394
1394
  levelData.set(ld.name, tables);
@@ -1575,7 +1575,7 @@ function writeIdMap(outputDir, sources, remaps) {
1575
1575
  }
1576
1576
  }
1577
1577
  if (rows.length > 0) {
1578
- writeCsv(join13(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1578
+ writeCsv(join15(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1579
1579
  }
1580
1580
  }
1581
1581
  function buildLevelDirMap(sources, remaps) {
@@ -1616,13 +1616,13 @@ function writeGlobalTables(outputDir, sources, remaps, registry) {
1616
1616
  }
1617
1617
  for (const [tableName, entry] of merged) {
1618
1618
  if (entry.rows.length > 0) {
1619
- writeCsv(join13(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1619
+ writeCsv(join15(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1620
1620
  }
1621
1621
  if (entry.svgInputs.length > 0) {
1622
1622
  const svgName = SVG_FILE_NAMES[tableName];
1623
1623
  if (svgName) {
1624
1624
  const content = writeMergedSvg(entry.svgInputs);
1625
- writeFileSync4(join13(outputDir, "global", svgName + ".svg"), content, "utf-8");
1625
+ writeFileSync5(join15(outputDir, "global", svgName + ".svg"), content, "utf-8");
1626
1626
  }
1627
1627
  }
1628
1628
  }
@@ -1654,17 +1654,17 @@ function writeLevelTables(outputDir, sources, remaps, levelDirMap, registry) {
1654
1654
  }
1655
1655
  }
1656
1656
  for (const [outDirName, tables] of merged) {
1657
- const dirPath = join13(outputDir, outDirName);
1657
+ const dirPath = join15(outputDir, outDirName);
1658
1658
  mkdirSync3(dirPath, { recursive: true });
1659
1659
  for (const [tableName, entry] of tables) {
1660
1660
  if (entry.rows.length > 0) {
1661
- writeCsv(join13(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1661
+ writeCsv(join15(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1662
1662
  }
1663
1663
  if (entry.svgInputs.length > 0) {
1664
1664
  const svgName = SVG_FILE_NAMES[tableName];
1665
1665
  if (svgName) {
1666
1666
  const content = writeMergedSvg(entry.svgInputs);
1667
- writeFileSync4(join13(dirPath, svgName + ".svg"), content, "utf-8");
1667
+ writeFileSync5(join15(dirPath, svgName + ".svg"), content, "utf-8");
1668
1668
  }
1669
1669
  }
1670
1670
  }
@@ -1696,29 +1696,29 @@ var init_exports = {};
1696
1696
  __export(init_exports, {
1697
1697
  initProject: () => initProject
1698
1698
  });
1699
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5, existsSync as existsSync13 } from "fs";
1700
- import { join as join14 } from "path";
1699
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6, existsSync as existsSync15 } from "fs";
1700
+ import { join as join16 } from "path";
1701
1701
  function initProject(absDir) {
1702
- if (!existsSync13(absDir)) {
1702
+ if (!existsSync15(absDir)) {
1703
1703
  mkdirSync4(absDir, { recursive: true });
1704
1704
  }
1705
- writeFileSync5(join14(absDir, ".bimdown"), "", "utf-8");
1706
- const globalDir = join14(absDir, "global");
1707
- if (!existsSync13(globalDir)) {
1705
+ writeFileSync6(join16(absDir, ".bimdown"), "", "utf-8");
1706
+ const globalDir = join16(absDir, "global");
1707
+ if (!existsSync15(globalDir)) {
1708
1708
  mkdirSync4(globalDir, { recursive: true });
1709
1709
  }
1710
- const levelCsvPath = join14(globalDir, "level.csv");
1711
- if (!existsSync13(levelCsvPath)) {
1712
- writeFileSync5(levelCsvPath, "id,name,elevation\nlv-1,Level 1,0.0\n", "utf-8");
1710
+ const levelCsvPath = join16(globalDir, "level.csv");
1711
+ if (!existsSync15(levelCsvPath)) {
1712
+ writeFileSync6(levelCsvPath, "id,name,elevation\nlv-1,Level 1,0.0\n", "utf-8");
1713
1713
  }
1714
- const gridCsvPath = join14(globalDir, "grid.csv");
1715
- if (!existsSync13(gridCsvPath)) {
1714
+ const gridCsvPath = join16(globalDir, "grid.csv");
1715
+ if (!existsSync15(gridCsvPath)) {
1716
1716
  const gridContent = [
1717
1717
  "id,name,role,start_x,start_y,end_x,end_y",
1718
1718
  "gr-1,A,primary,-10000,0,10000,0",
1719
1719
  "gr-2,1,primary,0,-10000,0,10000"
1720
1720
  ].join("\n") + "\n";
1721
- writeFileSync5(gridCsvPath, gridContent, "utf-8");
1721
+ writeFileSync6(gridCsvPath, gridContent, "utf-8");
1722
1722
  }
1723
1723
  console.log(`Initialized empty BimDown project at ${absDir}`);
1724
1724
  console.log("Created:");
@@ -1736,15 +1736,15 @@ var diff_exports = {};
1736
1736
  __export(diff_exports, {
1737
1737
  diffProjects: () => diffProjects
1738
1738
  });
1739
- import { existsSync as existsSync14 } from "fs";
1740
- import { join as join15 } from "path";
1739
+ import { existsSync as existsSync16 } from "fs";
1740
+ import { join as join17 } from "path";
1741
1741
  function diffProjects(dirA, dirB) {
1742
- if (!existsSync14(dirA)) {
1742
+ if (!existsSync16(dirA)) {
1743
1743
  console.error(`Directory not found: ${dirA}`);
1744
1744
  process.exitCode = 1;
1745
1745
  return;
1746
1746
  }
1747
- if (!existsSync14(dirB)) {
1747
+ if (!existsSync16(dirB)) {
1748
1748
  console.error(`Directory not found: ${dirB}`);
1749
1749
  process.exitCode = 1;
1750
1750
  return;
@@ -1763,22 +1763,22 @@ function diffProjects(dirA, dirB) {
1763
1763
  for (const pathName of allPathNames) {
1764
1764
  const dirAAbs = pathsA.find((p) => p.name === pathName)?.abs;
1765
1765
  const dirBAbs = pathsB.find((p) => p.name === pathName)?.abs;
1766
- const filesA = new Set(dirAAbs && existsSync14(dirAAbs) ? listFiles(dirAAbs).filter((f) => f.endsWith(".csv")) : []);
1767
- const filesB = new Set(dirBAbs && existsSync14(dirBAbs) ? listFiles(dirBAbs).filter((f) => f.endsWith(".csv")) : []);
1766
+ const filesA = new Set(dirAAbs && existsSync16(dirAAbs) ? listFiles(dirAAbs).filter((f) => f.endsWith(".csv")) : []);
1767
+ const filesB = new Set(dirBAbs && existsSync16(dirBAbs) ? listFiles(dirBAbs).filter((f) => f.endsWith(".csv")) : []);
1768
1768
  const allFiles = /* @__PURE__ */ new Set([...filesA, ...filesB]);
1769
1769
  let printedPathHeader = false;
1770
1770
  for (const f of allFiles) {
1771
1771
  const tableName = f.replace(".csv", "");
1772
- const pathFileA = dirAAbs ? join15(dirAAbs, f) : null;
1773
- const pathFileB = dirBAbs ? join15(dirBAbs, f) : null;
1772
+ const pathFileA = dirAAbs ? join17(dirAAbs, f) : null;
1773
+ const pathFileB = dirBAbs ? join17(dirBAbs, f) : null;
1774
1774
  const rowsA = {};
1775
1775
  const rowsB = {};
1776
- if (pathFileA && existsSync14(pathFileA)) {
1776
+ if (pathFileA && existsSync16(pathFileA)) {
1777
1777
  for (const row of readCsv(pathFileA).rows) {
1778
1778
  if (row.id) rowsA[String(row.id)] = row;
1779
1779
  }
1780
1780
  }
1781
- if (pathFileB && existsSync14(pathFileB)) {
1781
+ if (pathFileB && existsSync16(pathFileB)) {
1782
1782
  for (const row of readCsv(pathFileB).rows) {
1783
1783
  if (row.id) rowsB[String(row.id)] = row;
1784
1784
  }
@@ -1825,11 +1825,11 @@ __export(publish_exports, {
1825
1825
  publish: () => publish
1826
1826
  });
1827
1827
  import { resolve } from "path";
1828
- import { readFileSync as readFileSync5, existsSync as existsSync15 } from "fs";
1828
+ import { readFileSync as readFileSync6, existsSync as existsSync17 } from "fs";
1829
1829
  import { zipSync } from "fflate";
1830
1830
  async function publish(dir, opts) {
1831
1831
  const absDir = resolve(dir);
1832
- if (!existsSync15(absDir)) {
1832
+ if (!existsSync17(absDir)) {
1833
1833
  console.error(`Directory not found: ${absDir}`);
1834
1834
  process.exitCode = 1;
1835
1835
  return;
@@ -1843,16 +1843,16 @@ async function publish(dir, opts) {
1843
1843
  ];
1844
1844
  const files = {};
1845
1845
  for (const d of allDirs) {
1846
- if (!existsSync15(d.path)) continue;
1846
+ if (!existsSync17(d.path)) continue;
1847
1847
  for (const f of listFiles(d.path)) {
1848
1848
  const filePath = `${d.prefix}/${f}`;
1849
- const content = readFileSync5(resolve(d.path, f));
1849
+ const content = readFileSync6(resolve(d.path, f));
1850
1850
  files[filePath] = new Uint8Array(content);
1851
1851
  }
1852
1852
  }
1853
1853
  const metadataPath = resolve(absDir, "project_metadata.json");
1854
- if (existsSync15(metadataPath)) {
1855
- files["project_metadata.json"] = new Uint8Array(readFileSync5(metadataPath));
1854
+ if (existsSync17(metadataPath)) {
1855
+ files["project_metadata.json"] = new Uint8Array(readFileSync6(metadataPath));
1856
1856
  }
1857
1857
  const fileCount = Object.keys(files).length;
1858
1858
  if (fileCount === 0) {
@@ -1901,258 +1901,13 @@ var init_publish = __esm({
1901
1901
  }
1902
1902
  });
1903
1903
 
1904
- // src/commands/generate-skill.ts
1905
- var generate_skill_exports = {};
1906
- __export(generate_skill_exports, {
1907
- generateSkill: () => generateSkill
1908
- });
1909
- import { existsSync as existsSync16, mkdirSync as mkdirSync5, writeFileSync as writeFileSync6, readFileSync as readFileSync6 } from "fs";
1910
- import { join as join16, resolve as resolve2 } from "path";
1911
- function generateSkill(outputDir) {
1912
- const specDir = getSpecDir();
1913
- const csvSchemaDir = join16(specDir, "csv-schema");
1914
- const registry = buildRegistry(specDir);
1915
- const schemas = loadAllSchemas(csvSchemaDir);
1916
- const sortedNames = [...registry.keys()].sort();
1917
- const allTableNames = sortedNames.map((t) => "`" + t + "`").join(", ");
1918
- const FREEFORM_ID_TABLES = /* @__PURE__ */ new Set(["grid", "level"]);
1919
- const globalOnlyList = [...GLOBAL_ONLY_TABLES].map((t) => `\`${t}.csv\``).join(", ");
1920
- const idExamples = Object.entries(ID_PREFIXES).map(([table, prefix]) => {
1921
- const example = FREEFORM_ID_TABLES.has(table) ? `${table}: \`${prefix}-\` + any string (e.g. \`${prefix}-1\`, \`${prefix}-A\`, \`${prefix}-B2\`)` : `${table} \u2192 \`${prefix}-{n}\``;
1922
- return example;
1923
- });
1924
- const freeformExamples = idExamples.filter((_, i) => FREEFORM_ID_TABLES.has(Object.keys(ID_PREFIXES)[i]));
1925
- const numericExamples = idExamples.filter((_, i) => !FREEFORM_ID_TABLES.has(Object.keys(ID_PREFIXES)[i]));
1926
- const today = /* @__PURE__ */ new Date();
1927
- const publishDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
1928
- const cliVersion = true ? "0.2.2" : "unknown";
1929
- let md = `---
1930
- name: bimdown
1931
- description: Powerful structural and topological manipulation tool for BimDown architectural BIM projects. Use when asked to query building elements, build new structures (CSV+SVG), resolve MEP topologies, or analyze spatial BIM data.
1932
- ---
1933
-
1934
- # BimDown Agent Skill & Schema Rules
1935
-
1936
- > **Version ${cliVersion}** (published ${publishDate}). If this date is more than 1 week ago, run \`npm update -g bimdown-cli\` to update, then re-download this SKILL.md from https://raw.githubusercontent.com/NovaShang/BimDown/main/agent-skill/SKILL.md
1937
-
1938
- You are an AI Coder operating within a BimDown project environment.
1939
- BimDown is an open-source, AI-native building data format using CSV for semantics and SVG for geometry.
1940
-
1941
- ## Core Architecture & Base Concepts
1942
-
1943
- - **Global Unit is METERS**: All coordinates, widths, and structural attributes in CSV/SVG MUST strictly use METERS. BimDown simulates real-world dimensions.
1944
- - **Computed Fields are READ-ONLY**: Any field marked with \`computed: true\` (or listed in \`virtual_fields\`) is automatically calculated by the CLI. **DO NOT** write these fields to CSV files. You can retrieve their values using \`bimdown query\`.
1945
- - **Dual Nature**: Properties live in \`{name}.csv\`. 2D geometry lives in a sibling \`{name}.svg\` file. The \`id\` fields across both must match perfectly.
1946
- - **SVG-derived virtual columns**: When you write geometry in SVG, the CLI automatically computes these fields for \`bimdown query\` \u2014 do NOT write them to CSV:
1947
- - Line elements (wall, beam, pipe, etc.): \`length\`, \`start_x\`, \`start_y\`, \`end_x\`, \`end_y\`
1948
- - Polygon elements (slab, roof, etc.): \`area\`, \`perimeter\`
1949
- - All elements: \`level_id\` (inferred from folder name, e.g. \`lv-1/\` \u2192 \`lv-1\`)
1950
- - **Concrete Example of CSV+SVG Linked State**:
1951
- > \`lv-1/wall.csv\` (note: NO \`level_id\` column \u2014 it is auto-inferred):
1952
- > \`id,thickness,material\`
1953
- > \`w-1,0.2,concrete\`
1954
- >
1955
- > \`lv-1/wall.svg\`:
1956
- > \`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -10 10 10"> <g transform="scale(1,-1)"> <path id="w-1" d="M 0 0 L 10 0" stroke-width="0.2" /> </g> </svg>\`
1957
- >
1958
- > After this, \`bimdown query . "SELECT id, length, level_id FROM wall"\` returns \`w-1, 10.0, lv-1\` \u2014 both \`length\` and \`level_id\` are computed automatically.
1959
-
1960
- ## Project Directory Structure
1961
-
1962
- \`\`\`
1963
- project/
1964
- project_metadata.json # project root marker (format version, name, units)
1965
- global/ # global-only files \u2014 MUST be here, NOT in lv-N/
1966
- ${[...GLOBAL_ONLY_TABLES].sort().map((t) => t + ".csv").join("\n ")}
1967
- lv-1/ # per-level files
1968
- wall.csv + wall.svg # elements with geometry have paired CSV+SVG
1969
- door.csv # hosted elements are CSV-only (parametric position on host wall)
1970
- space.csv # spaces: CSV seed point + space.svg boundary (computed by build)
1971
- ...
1972
- lv-2/
1973
- ...
1974
- \`\`\`
1975
-
1976
- **Key rules**:
1977
- - ${globalOnlyList} MUST live in \`global/\`, never in \`lv-N/\` directories
1978
- - Per-level elements (wall, door, slab, space, etc.) go in \`lv-N/\` directories
1979
- - The folder name (e.g. \`lv-1\`) becomes the element's \`level_id\` \u2014 do NOT write \`level_id\` to CSV
1980
-
1981
- ## Recommended Workflow for Creating/Modifying Buildings
1982
-
1983
- 1. **Plan spatial layout first**: Before writing any files, reason through the spatial relationships \u2014 wall positions, room adjacencies, door/window placements. Sketch coordinates mentally or on paper.
1984
- 2. **Write SVG geometry first**: Create the \`.svg\` files (walls, slabs, columns) with correct coordinates. Geometry determines everything else.
1985
- 3. **Write CSV attributes second**: Create the \`.csv\` files with element properties (material, thickness, etc.). Remember: do NOT include computed fields like \`level_id\`, \`length\`, \`area\`.
1986
- 4. **Render and visually verify**: Run \`bimdown render <dir> -o render.png\` and **view the PNG image** to confirm the layout is correct. Check that walls connect properly, rooms are enclosed, and doors/windows are in the right positions.
1987
- 5. **Build**: Run \`bimdown build <dir>\` to validate schema, check geometry, and compute space boundaries (generates \`space.svg\` from seed points).
1988
- 6. **Iterate**: If the render or build shows problems, fix the SVG geometry and re-render until the layout looks right.
1989
- 7. **Publish**: Run \`bimdown publish <dir>\` to upload the project and get a shareable preview URL for the user to view the 3D model in their browser.
1990
-
1991
- ## CLI Tools & Best Practices
1992
-
1993
- 1. **\`bimdown query <dir> <sql> --json\`**: Runs DuckDB SQL across all tables, including SVG-derived virtual columns.
1994
- - **Example**: \`bimdown query ./proj "SELECT id, length FROM wall WHERE length > 5.0" --json\`
1995
- 2. **\`bimdown render <dir> [-l level] [-o output.png] [-w width]\`**: Renders a level into a PNG blueprint image (default 2048px wide). Use \`.svg\` extension for SVG output. **Always render after modifying geometry and view the PNG to visually verify the result.**
1996
- 3. **\`bimdown build <dir>\`**: Validates the project, checks geometry (wall connectivity, hosted element bounds), and computes space boundaries (generates \`space.svg\`). **Run this EVERY TIME after modifying CSV or SVG files!** Also available as \`bimdown validate\` (alias).
1997
- 4. **\`bimdown schema [table]\`**: Prints the full schema for any element type. Use this to look up fields before creating elements.
1998
- 5. **\`bimdown diff <dirA> <dirB>\`**: Emits a \`+\`, \`-\`, \`~\` structural difference between project snapshots.
1999
- 6. **\`bimdown init <dir>\`**: Creates a new empty BimDown project with the correct directory structure.
2000
- 7. **\`bimdown publish <dir> [--expires 7d]\`**: Publishes the project to BimClaw and returns a shareable preview URL. Use this to let users view the model in a 3D editor. **Always publish after completing a model so users can preview it.**
2001
- 8. **\`bimdown info <dir>\`**: Prints project summary (levels, element counts).
2002
- 9. **\`bimdown resolve-topology <dir>\`**: Auto-detects coincident endpoints for MEP curves, generates \`mep_nodes\`, and fills connectivity fields.
2003
- 10. **\`bimdown merge <dirs...> -o <output>\`**: Merges multiple project directories into one, resolving ID conflicts.
2004
- 11. **\`bimdown sync <dir>\`**: Hydrates into DuckDB and dehydrates back out to CSV/SVG, applying computed defaults.
2005
-
2006
- ## Critical File & Geometry Rules
2007
-
2008
- - **ID format**:
2009
- - **Grid and Level** allow any string after prefix: ${freeformExamples.join("; ")}
2010
- - **All other elements** use \`{prefix}-{number}\` (digits only): ${numericExamples.slice(0, 6).join(", ")}, ...
2011
- - **Always run \`bimdown build\` to confirm your IDs are compliant.**
2012
- - **SVG Coordinate Y-Flip**: All geometry inside \`.svg\` files **MUST** be wrapped in a Y-axis flip group: \`<g transform="scale(1,-1)"> ... </g>\`. This is just a fixed boilerplate \u2014 you do NOT need to do any coordinate conversion. Use normal Cartesian coordinates (X = right, Y = up) directly inside the group.
2013
- - **CSV vs Computed Fields**: Only write fields that are NOT marked as computed. Specifically, \`level_id\`, \`length\`, \`area\`, \`start_x/y\`, \`end_x/y\`, \`perimeter\`, \`volume\`, \`bbox_*\` are all auto-computed \u2014 never write them to CSV.
2014
- - **Vertical positioning** (walls, columns, and other vertical elements):
2015
- - \`level_id\`: auto-inferred from folder name \u2014 do NOT write to CSV
2016
- - \`base_offset\`: vertical offset in meters from the element's level. Default 0. Usually leave empty.
2017
- - \`top_level_id\`: the level where the element's top is constrained. **Leave empty** to default to the next level above. Only set this if the element spans to a non-adjacent level.
2018
- - \`top_offset\`: vertical offset in meters from the top level. Default 0. Usually leave empty.
2019
- - \`height\`: auto-computed from level elevations and offsets \u2014 do NOT write to CSV.
2020
- - **For most single-story walls**: leave \`top_level_id\`, \`top_offset\`, and \`base_offset\` all empty \u2014 the CLI will compute the correct height from level elevations.
2021
-
2022
- ## Generation Tips
2023
-
2024
- ### Typical Values (meters)
2025
- | Element | Field | Typical Range |
2026
- |---------|-------|--------------|
2027
- | Wall (partition) | thickness | 0.1 \u2013 0.15 |
2028
- | Wall (exterior) | thickness | 0.2 \u2013 0.3 |
2029
- | Wall (structural) | thickness | 0.3 \u2013 0.6 |
2030
- | Door (single) | width \xD7 height | 0.9 \xD7 2.1 |
2031
- | Door (double) | width \xD7 height | 1.8 \xD7 2.1 |
2032
- | Window | width \xD7 height | 1.2\u20131.8 \xD7 1.5 |
2033
- | Column | size_x \xD7 size_y | 0.3\u20130.6 \xD7 0.3\u20130.6 |
2034
- | Slab | thickness | 0.15 \u2013 0.25 |
2035
- | Level spacing | elevation diff | 3.0 \u2013 4.0 |
2036
-
2037
- ### Room Boundary Connectivity
2038
- Rooms are enclosed by **walls, curtain walls, columns, and room separators**. For the boundary to close properly:
2039
- - Line element endpoints (walls, curtain walls, room separators) must meet exactly at shared coordinates
2040
- - Example: w-1 ends at (10,0) \u2192 w-2 must start at (10,0) for an L-junction
2041
- - The CLI \`build\` command warns about unconnected endpoints and computes space boundaries from closed loops
2042
-
2043
- ### Door/Window Placement Rules
2044
- - \`position\` = distance in meters from wall **start point** (the M coordinate in SVG path) to the opening **center**
2045
- - Must satisfy: \`position - width/2 >= 0\` AND \`position + width/2 <= wall_length\`
2046
- - Multiple openings on the same wall must not overlap
2047
- - The CLI \`build\` command warns about out-of-bounds and overlapping placements
2048
-
2049
- ### SVG File Template
2050
- Always use this structure for SVG files:
2051
- \`\`\`xml
2052
- <svg xmlns="http://www.w3.org/2000/svg">
2053
- <g transform="scale(1,-1)">
2054
- <!-- elements here, using normal Cartesian coordinates (X=right, Y=up) -->
2055
- </g>
2056
- </svg>
2057
- \`\`\`
2058
-
2059
- ## Base Schema Definitions
2060
-
2061
- These abstract schemas provide common fields for concrete tables below.
2062
-
2063
- `;
2064
- for (const baseName of Array.from(BASE_SCHEMAS).sort()) {
2065
- const filePath = findSchemaFile(csvSchemaDir, baseName);
2066
- if (filePath) {
2067
- md += `### Base: \`${baseName}\`
2068
- \`\`\`yaml
2069
- ${readFileSync6(filePath, "utf-8").trim()}
2070
- \`\`\`
2071
-
2072
- `;
2073
- }
2074
- }
2075
- md += `## Core Schema Topologies (Concrete Tables)
2076
-
2077
- Below is a curated whitelist of the **most commonly used** core architectural elements.
2078
-
2079
- > **IMPORTANT**: The complete list of available elements in this project is:
2080
- > ${allTableNames}
2081
- >
2082
- > If the user asks you to modify or generate elements not listed below, **RUN** \`bimdown schema <table_name>\` to fetch their requirements!
2083
-
2084
- `;
2085
- for (const name of sortedNames) {
2086
- if (!CORE_TABLES.has(name)) continue;
2087
- const table = registry.get(name);
2088
- const hasSVG = TABLES_WITH_SVG.has(name);
2089
- const filePath = findSchemaFile(csvSchemaDir, name);
2090
- if (filePath) {
2091
- md += `### Table: \`${table.name}\` (Prefix: \`${table.prefix}\`)
2092
- `;
2093
- md += `- **Geometry**: ${hasSVG ? "SVG required" : "CSV only"}
2094
- `;
2095
- if (name === "wall") {
2096
- md += `- **IMPORTANT**: A wall MUST be one complete straight line (start to end). Do NOT split a wall into segments for doors/windows. Doors and windows attach to the wall via the \`position\` parameter on the host wall.
2097
- `;
2098
- }
2099
- if (name === "door" || name === "window") {
2100
- md += `- **position**: Distance in meters from the wall's start point to the center of the ${name}. Calculate from the wall's SVG geometry coordinates.
2101
- `;
2102
- }
2103
- md += `\`\`\`yaml
2104
- `;
2105
- md += `id_prefix: ${table.prefix}
2106
- `;
2107
- md += `${readFileSync6(filePath, "utf-8").trim()}
2108
- `;
2109
- const computedFields = table.allFields.filter((f) => f.computed || f.name === "level_id").map((f) => f.name);
2110
- if (computedFields.length > 0) {
2111
- md += `
2112
- virtual_fields: [${computedFields.join(", ")}]
2113
- `;
2114
- }
2115
- md += `\`\`\`
2116
-
2117
- `;
2118
- }
2119
- }
2120
- const rootDir = outputDir ? resolve2(outputDir) : process.cwd();
2121
- const dirPath = join16(rootDir, "agent-skill");
2122
- if (!existsSync16(dirPath)) mkdirSync5(dirPath, { recursive: true });
2123
- const outPath = join16(dirPath, "SKILL.md");
2124
- writeFileSync6(outPath, md, "utf-8");
2125
- console.log(`\u2705 Agent Skill documentation successfully generated at: ${outPath}`);
2126
- }
2127
- function findSchemaFile(baseDir, schemaName) {
2128
- const dirs = [baseDir, join16(baseDir, "architecture"), join16(baseDir, "mep"), join16(baseDir, "structure"), join16(baseDir, "base")];
2129
- for (const d of dirs) {
2130
- if (!existsSync16(d)) continue;
2131
- const p1 = join16(d, `${schemaName}.yaml`);
2132
- if (existsSync16(p1)) return p1;
2133
- const p2 = join16(d, `${schemaName}.yml`);
2134
- if (existsSync16(p2)) return p2;
2135
- }
2136
- return null;
2137
- }
2138
- var CORE_TABLES, BASE_SCHEMAS;
2139
- var init_generate_skill = __esm({
2140
- "src/commands/generate-skill.ts"() {
2141
- "use strict";
2142
- init_registry();
2143
- init_loader();
2144
- CORE_TABLES = /* @__PURE__ */ new Set(["level", "grid", "wall", "door", "window", "space"]);
2145
- BASE_SCHEMAS = /* @__PURE__ */ new Set(["element", "hosted_element", "materialized", "vertical_span", "line_element", "point_element", "polygon_element"]);
2146
- }
2147
- });
2148
-
2149
1904
  // src/index.ts
2150
1905
  import { Command } from "commander";
2151
- import { resolve as resolve3 } from "path";
1906
+ import { resolve as resolve2 } from "path";
2152
1907
 
2153
1908
  // src/build/index.ts
2154
- import { existsSync as existsSync7 } from "fs";
2155
- import { join as join8 } from "path";
1909
+ import { existsSync as existsSync9 } from "fs";
1910
+ import { join as join10 } from "path";
2156
1911
 
2157
1912
  // src/validate/index.ts
2158
1913
  init_registry();
@@ -2197,8 +1952,8 @@ function validateStructure(dir) {
2197
1952
  }
2198
1953
  }
2199
1954
  for (const ld of layout.levelDirs) {
2200
- if (!/^lv-\d+$/.test(ld.name)) {
2201
- issues.push(`${ld.name}/ directory name does not match lv-{n} pattern`);
1955
+ if (!/^lv-.+$/.test(ld.name)) {
1956
+ issues.push(`${ld.name}/ directory name does not match lv-{id} pattern`);
2202
1957
  continue;
2203
1958
  }
2204
1959
  const files = listFiles(ld.path);
@@ -2238,7 +1993,7 @@ function validateStructure(dir) {
2238
1993
  }
2239
1994
  const topEntries = readdirSync3(dir);
2240
1995
  for (const f of topEntries) {
2241
- if (f === "global" || /^lv-\d+$/.test(f)) continue;
1996
+ if (f === "global" || /^lv-.+$/.test(f)) continue;
2242
1997
  if (f === "project_metadata.json") continue;
2243
1998
  if (f.startsWith(".")) continue;
2244
1999
  issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
@@ -2675,7 +2430,8 @@ function computeSpaceBoundaries(levelDir) {
2675
2430
  warnings.push(`${levelDir.name}/ no boundary elements found for space boundary computation`);
2676
2431
  return { warnings, svgWritten: false };
2677
2432
  }
2678
- const { vertices, halfEdges } = buildHalfEdgeStructure(segments);
2433
+ const splitSegments = splitAtTJunctions(segments);
2434
+ const { vertices, halfEdges } = buildHalfEdgeStructure(splitSegments);
2679
2435
  for (const v of vertices) {
2680
2436
  if (v.outgoing.length === 1) {
2681
2437
  const he = v.outgoing[0];
@@ -2735,6 +2491,67 @@ function collectBoundarySegments(levelPath) {
2735
2491
  }
2736
2492
  return segments;
2737
2493
  }
2494
+ function splitAtTJunctions(segments) {
2495
+ const endpoints = [];
2496
+ for (const seg of segments) {
2497
+ endpoints.push({ x: seg.startX, y: seg.startY });
2498
+ endpoints.push({ x: seg.endX, y: seg.endY });
2499
+ }
2500
+ let result = [...segments];
2501
+ let changed = true;
2502
+ while (changed) {
2503
+ changed = false;
2504
+ const nextResult = [];
2505
+ const allEndpoints = [];
2506
+ for (const seg of result) {
2507
+ allEndpoints.push({ x: seg.startX, y: seg.startY });
2508
+ allEndpoints.push({ x: seg.endX, y: seg.endY });
2509
+ }
2510
+ for (const seg of result) {
2511
+ const splitPoints = [];
2512
+ const dx = seg.endX - seg.startX;
2513
+ const dy = seg.endY - seg.startY;
2514
+ const lenSq = dx * dx + dy * dy;
2515
+ if (lenSq < TOLERANCE * TOLERANCE) {
2516
+ nextResult.push(seg);
2517
+ continue;
2518
+ }
2519
+ for (const ep of allEndpoints) {
2520
+ if (Math.abs(ep.x - seg.startX) < TOLERANCE && Math.abs(ep.y - seg.startY) < TOLERANCE) continue;
2521
+ if (Math.abs(ep.x - seg.endX) < TOLERANCE && Math.abs(ep.y - seg.endY) < TOLERANCE) continue;
2522
+ const t = ((ep.x - seg.startX) * dx + (ep.y - seg.startY) * dy) / lenSq;
2523
+ if (t <= TOLERANCE || t >= 1 - TOLERANCE) continue;
2524
+ const closestX = seg.startX + t * dx;
2525
+ const closestY = seg.startY + t * dy;
2526
+ const distSq = (ep.x - closestX) * (ep.x - closestX) + (ep.y - closestY) * (ep.y - closestY);
2527
+ if (distSq < TOLERANCE * TOLERANCE) {
2528
+ splitPoints.push({ x: ep.x, y: ep.y, t });
2529
+ }
2530
+ }
2531
+ if (splitPoints.length === 0) {
2532
+ nextResult.push(seg);
2533
+ } else {
2534
+ changed = true;
2535
+ splitPoints.sort((a, b) => a.t - b.t);
2536
+ const unique = [splitPoints[0]];
2537
+ for (let i = 1; i < splitPoints.length; i++) {
2538
+ if (Math.abs(splitPoints[i].t - unique[unique.length - 1].t) > TOLERANCE) {
2539
+ unique.push(splitPoints[i]);
2540
+ }
2541
+ }
2542
+ let prevX = seg.startX, prevY = seg.startY;
2543
+ for (const sp of unique) {
2544
+ nextResult.push({ startX: prevX, startY: prevY, endX: sp.x, endY: sp.y, id: seg.id });
2545
+ prevX = sp.x;
2546
+ prevY = sp.y;
2547
+ }
2548
+ nextResult.push({ startX: prevX, startY: prevY, endX: seg.endX, endY: seg.endY, id: seg.id });
2549
+ }
2550
+ }
2551
+ result = nextResult;
2552
+ }
2553
+ return result;
2554
+ }
2738
2555
  function buildHalfEdgeStructure(segments) {
2739
2556
  const vertices = [];
2740
2557
  function findOrCreateVertex(x, y) {
@@ -2898,6 +2715,7 @@ function validateGeometry(dir) {
2898
2715
  function validateLineConnectivity(levelDir) {
2899
2716
  const warnings = [];
2900
2717
  const endpoints = [];
2718
+ const segments = [];
2901
2719
  for (const table of BOUNDARY_TABLES2) {
2902
2720
  const svgPath = join7(levelDir.path, `${table}.svg`);
2903
2721
  if (!existsSync6(svgPath)) continue;
@@ -2908,37 +2726,55 @@ function validateLineConnectivity(levelDir) {
2908
2726
  const geo = extractLineGeometry(el);
2909
2727
  endpoints.push({ x: geo.start_x, y: geo.start_y, side: "start", elementId: el.id, table });
2910
2728
  endpoints.push({ x: geo.end_x, y: geo.end_y, side: "end", elementId: el.id, table });
2729
+ segments.push({ start_x: geo.start_x, start_y: geo.start_y, end_x: geo.end_x, end_y: geo.end_y, elementId: el.id, table });
2911
2730
  }
2912
2731
  } catch {
2913
2732
  }
2914
2733
  }
2915
2734
  for (const ep of endpoints) {
2916
- const hasNeighbor = endpoints.some(
2735
+ const hasEndpointNeighbor = endpoints.some(
2917
2736
  (other) => other !== ep && !(other.elementId === ep.elementId && other.table === ep.table) && Math.abs(other.x - ep.x) < TOLERANCE2 && Math.abs(other.y - ep.y) < TOLERANCE2
2918
2737
  );
2919
- if (!hasNeighbor) {
2920
- let nearestDist = Infinity;
2921
- let nearestId = "";
2922
- let nearestSide = "";
2923
- for (const other of endpoints) {
2924
- if (other === ep || other.elementId === ep.elementId && other.table === ep.table) continue;
2925
- const dx = other.x - ep.x;
2926
- const dy = other.y - ep.y;
2927
- const dist = Math.sqrt(dx * dx + dy * dy);
2928
- if (dist < nearestDist) {
2929
- nearestDist = dist;
2930
- nearestId = other.elementId;
2931
- nearestSide = other.side;
2932
- }
2933
- }
2934
- const nearestInfo = nearestDist < Infinity ? ` (nearest: ${nearestId} ${nearestSide}, distance ${nearestDist.toFixed(3)}m)` : "";
2935
- warnings.push(
2936
- `[warn] ${levelDir.name}/${ep.table}.svg ${ep.elementId} ${ep.side} (${ep.x.toFixed(3)}, ${ep.y.toFixed(3)}) has no connected line element${nearestInfo}`
2937
- );
2938
- }
2738
+ if (hasEndpointNeighbor) continue;
2739
+ const hasTJunction = segments.some((seg) => {
2740
+ if (seg.elementId === ep.elementId && seg.table === ep.table) return false;
2741
+ return pointOnSegment(ep.x, ep.y, seg.start_x, seg.start_y, seg.end_x, seg.end_y, TOLERANCE2);
2742
+ });
2743
+ if (hasTJunction) continue;
2744
+ let nearestDist = Infinity;
2745
+ let nearestId = "";
2746
+ let nearestSide = "";
2747
+ for (const other of endpoints) {
2748
+ if (other === ep || other.elementId === ep.elementId && other.table === ep.table) continue;
2749
+ const dx = other.x - ep.x;
2750
+ const dy = other.y - ep.y;
2751
+ const dist2 = Math.sqrt(dx * dx + dy * dy);
2752
+ if (dist2 < nearestDist) {
2753
+ nearestDist = dist2;
2754
+ nearestId = other.elementId;
2755
+ nearestSide = other.side;
2756
+ }
2757
+ }
2758
+ const nearestInfo = nearestDist < Infinity ? ` (nearest: ${nearestId} ${nearestSide}, distance ${nearestDist.toFixed(3)}m)` : "";
2759
+ warnings.push(
2760
+ `[warn] ${levelDir.name}/${ep.table}.svg ${ep.elementId} ${ep.side} (${ep.x.toFixed(3)}, ${ep.y.toFixed(3)}) has no connected line element${nearestInfo}`
2761
+ );
2939
2762
  }
2940
2763
  return warnings;
2941
2764
  }
2765
+ function pointOnSegment(px, py, ax, ay, bx, by, tol) {
2766
+ const dx = bx - ax;
2767
+ const dy = by - ay;
2768
+ const lenSq = dx * dx + dy * dy;
2769
+ if (lenSq < tol * tol) return false;
2770
+ const t = ((px - ax) * dx + (py - ay) * dy) / lenSq;
2771
+ if (t < -tol || t > 1 + tol) return false;
2772
+ const clampedT = Math.max(0, Math.min(1, t));
2773
+ const closestX = ax + clampedT * dx;
2774
+ const closestY = ay + clampedT * dy;
2775
+ const distSq = (px - closestX) * (px - closestX) + (py - closestY) * (py - closestY);
2776
+ return distSq < tol * tol;
2777
+ }
2942
2778
  function validateHostedBounds(levelDir, wallGeometries) {
2943
2779
  const warnings = [];
2944
2780
  for (const tableName of ["door", "window"]) {
@@ -3010,34 +2846,306 @@ function validateHostedOverlap(levelDir) {
3010
2846
  return warnings;
3011
2847
  }
3012
2848
 
2849
+ // src/build/resolve-hosted-coords.ts
2850
+ init_svg();
2851
+ init_csv();
2852
+ init_fs();
2853
+ import { existsSync as existsSync7 } from "fs";
2854
+ import { join as join8 } from "path";
2855
+ var TOLERANCE3 = 0.05;
2856
+ var HOSTED_TABLES = ["door", "window", "opening"];
2857
+ function resolveHostedCoords(dir) {
2858
+ const issues = [];
2859
+ const layout = discoverLayout(dir);
2860
+ const allDirs = [
2861
+ { name: "global", path: layout.globalDir },
2862
+ ...layout.levelDirs
2863
+ ];
2864
+ for (const d of allDirs) {
2865
+ if (!existsSync7(d.path)) continue;
2866
+ const files = listFiles(d.path);
2867
+ const walls = [];
2868
+ for (const table of ["wall", "structure_wall", "curtain_wall"]) {
2869
+ const svgPath = join8(d.path, `${table}.svg`);
2870
+ if (!existsSync7(svgPath)) continue;
2871
+ try {
2872
+ const svg = parseSvgFile(svgPath);
2873
+ for (const el of svg.elements) {
2874
+ if (el.tag !== "path") continue;
2875
+ const geo = extractLineGeometry(el);
2876
+ walls.push({
2877
+ id: el.id,
2878
+ start_x: geo.start_x,
2879
+ start_y: geo.start_y,
2880
+ end_x: geo.end_x,
2881
+ end_y: geo.end_y,
2882
+ length: geo.length
2883
+ });
2884
+ }
2885
+ } catch {
2886
+ }
2887
+ }
2888
+ if (walls.length === 0) continue;
2889
+ for (const table of HOSTED_TABLES) {
2890
+ const csvPath = join8(d.path, `${table}.csv`);
2891
+ if (!files.includes(`${table}.csv`)) continue;
2892
+ const csv = readCsv(csvPath);
2893
+ const hasHostX = csv.headers.includes("host_x");
2894
+ const hasHostY = csv.headers.includes("host_y");
2895
+ if (!hasHostX || !hasHostY) continue;
2896
+ let modified = false;
2897
+ for (let i = 0; i < csv.rows.length; i++) {
2898
+ const row = csv.rows[i];
2899
+ const hostX = parseFloat(row.host_x ?? "");
2900
+ const hostY = parseFloat(row.host_y ?? "");
2901
+ if (isNaN(hostX) || isNaN(hostY)) continue;
2902
+ const existingPosition = parseFloat(row.position ?? "");
2903
+ if (!isNaN(existingPosition) && row.position !== "") continue;
2904
+ const match = findNearestWall(hostX, hostY, walls, row.host_id);
2905
+ if (!match) {
2906
+ issues.push(
2907
+ `${d.name}/${table}.csv:${i + 2} ${row.id} host_x=${hostX}, host_y=${hostY} \u2014 no wall found within ${TOLERANCE3}m`
2908
+ );
2909
+ continue;
2910
+ }
2911
+ row.position = match.position.toFixed(4);
2912
+ if (!row.host_id || row.host_id === "") {
2913
+ row.host_id = match.wallId;
2914
+ }
2915
+ modified = true;
2916
+ }
2917
+ if (modified) {
2918
+ const cleanHeaders = csv.headers.filter((h) => h !== "host_x" && h !== "host_y");
2919
+ if (!cleanHeaders.includes("host_id")) {
2920
+ const idIdx = cleanHeaders.indexOf("id");
2921
+ cleanHeaders.splice(idIdx + 1, 0, "host_id");
2922
+ }
2923
+ if (!cleanHeaders.includes("position")) {
2924
+ const hostIdx = cleanHeaders.indexOf("host_id");
2925
+ cleanHeaders.splice(hostIdx + 1, 0, "position");
2926
+ }
2927
+ const cleanRows = csv.rows.map((row) => {
2928
+ const clean = {};
2929
+ for (const h of cleanHeaders) {
2930
+ if (row[h] !== void 0) clean[h] = row[h];
2931
+ }
2932
+ return clean;
2933
+ });
2934
+ writeCsv(csvPath, { headers: cleanHeaders, rows: cleanRows });
2935
+ }
2936
+ }
2937
+ }
2938
+ return issues;
2939
+ }
2940
+ function findNearestWall(px, py, walls, preferredHostId) {
2941
+ let bestWallId = "";
2942
+ let bestPosition = 0;
2943
+ let bestDist = Infinity;
2944
+ for (const wall of walls) {
2945
+ const dx = wall.end_x - wall.start_x;
2946
+ const dy = wall.end_y - wall.start_y;
2947
+ const lenSq = dx * dx + dy * dy;
2948
+ if (lenSq < 1e-10) continue;
2949
+ const t = ((px - wall.start_x) * dx + (py - wall.start_y) * dy) / lenSq;
2950
+ const clampedT = Math.max(0, Math.min(1, t));
2951
+ const closestX = wall.start_x + clampedT * dx;
2952
+ const closestY = wall.start_y + clampedT * dy;
2953
+ const dist2 = Math.sqrt((px - closestX) ** 2 + (py - closestY) ** 2);
2954
+ if (preferredHostId && preferredHostId !== "") {
2955
+ if (wall.id === preferredHostId) {
2956
+ return { wallId: wall.id, position: clampedT * wall.length };
2957
+ }
2958
+ continue;
2959
+ }
2960
+ if (dist2 < bestDist) {
2961
+ bestDist = dist2;
2962
+ bestWallId = wall.id;
2963
+ bestPosition = clampedT * wall.length;
2964
+ }
2965
+ }
2966
+ if (bestDist > TOLERANCE3 && !preferredHostId) return null;
2967
+ if (!bestWallId) return null;
2968
+ return { wallId: bestWallId, position: bestPosition };
2969
+ }
2970
+
2971
+ // src/build/snap-endpoints.ts
2972
+ init_svg();
2973
+ init_fs();
2974
+ import { existsSync as existsSync8, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
2975
+ import { join as join9 } from "path";
2976
+ var SNAP_TOLERANCE = 0.05;
2977
+ var BOUNDARY_TABLES3 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
2978
+ function snapEndpoints(dir) {
2979
+ const layout = discoverLayout(dir);
2980
+ const allDirs = [
2981
+ { name: "global", path: layout.globalDir },
2982
+ ...layout.levelDirs
2983
+ ];
2984
+ let totalSnapped = 0;
2985
+ for (const d of allDirs) {
2986
+ if (!existsSync8(d.path)) continue;
2987
+ const endpoints = [];
2988
+ for (const table of BOUNDARY_TABLES3) {
2989
+ const svgPath = join9(d.path, `${table}.svg`);
2990
+ if (!existsSync8(svgPath)) continue;
2991
+ try {
2992
+ const svg = parseSvgFile(svgPath);
2993
+ for (const el of svg.elements) {
2994
+ if (el.tag !== "path") continue;
2995
+ const geo = extractLineGeometry(el);
2996
+ endpoints.push({ point: { x: geo.start_x, y: geo.start_y }, table, elementId: el.id, side: "start", levelDir: d.name, levelPath: d.path });
2997
+ endpoints.push({ point: { x: geo.end_x, y: geo.end_y }, table, elementId: el.id, side: "end", levelDir: d.name, levelPath: d.path });
2998
+ }
2999
+ } catch {
3000
+ }
3001
+ }
3002
+ if (endpoints.length === 0) continue;
3003
+ const clusters = clusterEndpoints(endpoints);
3004
+ const snapMap = /* @__PURE__ */ new Map();
3005
+ for (const cluster of clusters) {
3006
+ if (cluster.length <= 1) continue;
3007
+ const canonical = pickCanonical(cluster);
3008
+ for (const ep of cluster) {
3009
+ const dx = Math.abs(ep.point.x - canonical.x);
3010
+ const dy = Math.abs(ep.point.y - canonical.y);
3011
+ if (dx > 1e-6 || dy > 1e-6) {
3012
+ const key = `${ep.table}:${ep.elementId}:${ep.side}`;
3013
+ snapMap.set(key, canonical);
3014
+ totalSnapped++;
3015
+ }
3016
+ }
3017
+ }
3018
+ if (snapMap.size === 0) continue;
3019
+ for (const table of BOUNDARY_TABLES3) {
3020
+ const svgPath = join9(d.path, `${table}.svg`);
3021
+ if (!existsSync8(svgPath)) continue;
3022
+ let svgText = readFileSync5(svgPath, "utf-8");
3023
+ let modified = false;
3024
+ try {
3025
+ const svg = parseSvgFile(svgPath);
3026
+ for (const el of svg.elements) {
3027
+ if (el.tag !== "path") continue;
3028
+ const geo = extractLineGeometry(el);
3029
+ const startKey = `${table}:${el.id}:start`;
3030
+ const endKey = `${table}:${el.id}:end`;
3031
+ const newStart = snapMap.get(startKey);
3032
+ const newEnd = snapMap.get(endKey);
3033
+ if (!newStart && !newEnd) continue;
3034
+ const sx = newStart?.x ?? geo.start_x;
3035
+ const sy = newStart?.y ?? geo.start_y;
3036
+ const ex = newEnd?.x ?? geo.end_x;
3037
+ const ey = newEnd?.y ?? geo.end_y;
3038
+ const oldD = el.attrs.d;
3039
+ const newD = `M ${fmtNum(sx)} ${fmtNum(sy)} L ${fmtNum(ex)} ${fmtNum(ey)}`;
3040
+ if (oldD && oldD !== newD) {
3041
+ svgText = replacePathD(svgText, el.id, oldD, newD);
3042
+ modified = true;
3043
+ }
3044
+ }
3045
+ } catch {
3046
+ continue;
3047
+ }
3048
+ if (modified) {
3049
+ writeFileSync3(svgPath, svgText, "utf-8");
3050
+ }
3051
+ }
3052
+ }
3053
+ return totalSnapped;
3054
+ }
3055
+ function clusterEndpoints(endpoints) {
3056
+ const visited = /* @__PURE__ */ new Set();
3057
+ const clusters = [];
3058
+ for (let i = 0; i < endpoints.length; i++) {
3059
+ if (visited.has(i)) continue;
3060
+ const cluster = [endpoints[i]];
3061
+ visited.add(i);
3062
+ let expanded = true;
3063
+ while (expanded) {
3064
+ expanded = false;
3065
+ for (let j = 0; j < endpoints.length; j++) {
3066
+ if (visited.has(j)) continue;
3067
+ for (const member of cluster) {
3068
+ if (dist(member.point, endpoints[j].point) < SNAP_TOLERANCE) {
3069
+ cluster.push(endpoints[j]);
3070
+ visited.add(j);
3071
+ expanded = true;
3072
+ break;
3073
+ }
3074
+ }
3075
+ }
3076
+ }
3077
+ clusters.push(cluster);
3078
+ }
3079
+ return clusters;
3080
+ }
3081
+ function pickCanonical(cluster) {
3082
+ const counts = /* @__PURE__ */ new Map();
3083
+ for (const ep of cluster) {
3084
+ const key = `${fmtNum(ep.point.x)},${fmtNum(ep.point.y)}`;
3085
+ const entry = counts.get(key);
3086
+ if (entry) {
3087
+ entry.count++;
3088
+ } else {
3089
+ counts.set(key, { point: ep.point, count: 1 });
3090
+ }
3091
+ }
3092
+ let best = { point: cluster[0].point, count: 0 };
3093
+ for (const entry of counts.values()) {
3094
+ if (entry.count > best.count) best = entry;
3095
+ }
3096
+ return best.point;
3097
+ }
3098
+ function dist(a, b) {
3099
+ return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
3100
+ }
3101
+ function fmtNum(n) {
3102
+ const s = n.toFixed(4);
3103
+ return s.replace(/\.?0+$/, "") || "0";
3104
+ }
3105
+ function replacePathD(svgText, id, oldD, newD) {
3106
+ const escaped = oldD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3107
+ const idEscaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3108
+ const pathRegex = new RegExp(`(<path[^>]*\\bid="${idEscaped}"[^>]*\\bd=")${escaped}(")`);
3109
+ if (pathRegex.test(svgText)) {
3110
+ return svgText.replace(pathRegex, `$1${newD}$2`);
3111
+ }
3112
+ const pathRegex2 = new RegExp(`(<path[^>]*\\bd=")${escaped}("[^>]*\\bid="${idEscaped}")`);
3113
+ if (pathRegex2.test(svgText)) {
3114
+ return svgText.replace(pathRegex2, `$1${newD}$2`);
3115
+ }
3116
+ return svgText;
3117
+ }
3118
+
3013
3119
  // src/build/index.ts
3014
3120
  function build(dir) {
3015
- const issues = validate(dir);
3121
+ const snapped = snapEndpoints(dir);
3122
+ const resolveIssues = resolveHostedCoords(dir);
3123
+ const issues = [...resolveIssues, ...validate(dir)];
3016
3124
  const warnings = validateGeometry(dir);
3017
3125
  const artifacts = [];
3018
3126
  const layout = discoverLayout(dir);
3019
3127
  for (const levelDir of layout.levelDirs) {
3020
- const spaceCsvPath = join8(levelDir.path, "space.csv");
3021
- if (!existsSync7(spaceCsvPath)) continue;
3128
+ const spaceCsvPath = join10(levelDir.path, "space.csv");
3129
+ if (!existsSync9(spaceCsvPath)) continue;
3022
3130
  const result = computeSpaceBoundaries(levelDir);
3023
3131
  warnings.push(...result.warnings);
3024
3132
  if (result.svgWritten) {
3025
3133
  artifacts.push(`${levelDir.name}/space.svg`);
3026
3134
  }
3027
3135
  }
3028
- return { issues, warnings, artifacts };
3136
+ return { issues, warnings, artifacts, snappedEndpoints: snapped };
3029
3137
  }
3030
3138
 
3031
3139
  // src/index.ts
3032
3140
  init_registry();
3033
3141
  init_fs();
3034
3142
  init_csv();
3035
- import { existsSync as existsSync17, writeFileSync as writeFileSync7 } from "fs";
3036
- import { join as join17 } from "path";
3143
+ import { existsSync as existsSync18, writeFileSync as writeFileSync7 } from "fs";
3144
+ import { join as join18 } from "path";
3037
3145
  var program = new Command();
3038
- program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.2.2" : "0.0.0");
3146
+ program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.3.0" : "0.0.0");
3039
3147
  function runBuild(dir) {
3040
- const absDir = resolve3(dir);
3148
+ const absDir = resolve2(dir);
3041
3149
  const result = build(absDir);
3042
3150
  if (result.issues.length > 0) {
3043
3151
  for (const issue of result.issues) {
@@ -3054,6 +3162,9 @@ ${result.issues.length} issue(s) found.`);
3054
3162
  console.log(`
3055
3163
  ${result.warnings.length} warning(s).`);
3056
3164
  }
3165
+ if (result.snappedEndpoints > 0) {
3166
+ console.log(`Snapped ${result.snappedEndpoints} endpoint(s) (within 5cm tolerance).`);
3167
+ }
3057
3168
  if (result.artifacts.length > 0) {
3058
3169
  console.log(`
3059
3170
  Generated: ${result.artifacts.join(", ")}`);
@@ -3065,7 +3176,7 @@ Generated: ${result.artifacts.join(", ")}`);
3065
3176
  program.command("build").argument("<dir>", "BimDown project directory").description("Build a BimDown project (validate + compute space boundaries)").action((dir) => runBuild(dir));
3066
3177
  program.command("validate").argument("<dir>", "BimDown project directory").description("Alias for build").action((dir) => runBuild(dir));
3067
3178
  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) => {
3068
- const absDir = resolve3(dir);
3179
+ const absDir = resolve2(dir);
3069
3180
  const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3070
3181
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3071
3182
  const conn = await getConnection2();
@@ -3082,7 +3193,7 @@ program.command("query").argument("<dir>", "BimDown project directory").argument
3082
3193
  }
3083
3194
  });
3084
3195
  program.command("sync").argument("<dir>", "BimDown project directory").description("Hydrate, then dehydrate back (sync DuckDB changes to files)").action(async (dir) => {
3085
- const absDir = resolve3(dir);
3196
+ const absDir = resolve2(dir);
3086
3197
  const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3087
3198
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3088
3199
  const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
@@ -3097,7 +3208,7 @@ program.command("sync").argument("<dir>", "BimDown project directory").descripti
3097
3208
  }
3098
3209
  });
3099
3210
  program.command("render").argument("<dir>", "BimDown project directory").option("-l, --level <id>", "Level to render (defaults to lv-1)", "lv-1").option("-o, --output <file>", "Output file path (defaults to render.png)", "render.png").option("-w, --width <px>", "Image width in pixels", "2048").description("Renders the BimDown project into a visual blueprint (PNG)").action(async (dir, opts) => {
3100
- const absDir = resolve3(dir);
3211
+ const absDir = resolve2(dir);
3101
3212
  const { renderLevel: renderLevel2 } = await Promise.resolve().then(() => (init_render(), render_exports));
3102
3213
  try {
3103
3214
  const svg = renderLevel2(absDir, opts.level);
@@ -3115,11 +3226,11 @@ program.command("render").argument("<dir>", "BimDown project directory").option(
3115
3226
  }
3116
3227
  });
3117
3228
  program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
3118
- const absDir = resolve3(dir);
3229
+ const absDir = resolve2(dir);
3119
3230
  const registry = buildRegistry(getSpecDir());
3120
3231
  const layout = discoverLayout(absDir);
3121
- const levelCsv = join17(layout.globalDir, "level.csv");
3122
- if (existsSync17(levelCsv)) {
3232
+ const levelCsv = join18(layout.globalDir, "level.csv");
3233
+ if (existsSync18(levelCsv)) {
3123
3234
  const levels = readCsv(levelCsv);
3124
3235
  console.log("Levels:");
3125
3236
  for (const row of levels.rows) {
@@ -3133,14 +3244,14 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
3133
3244
  ];
3134
3245
  const totals = {};
3135
3246
  for (const d of allDirs) {
3136
- if (!existsSync17(d.path)) continue;
3247
+ if (!existsSync18(d.path)) continue;
3137
3248
  const files = listFiles(d.path);
3138
3249
  const counts = [];
3139
3250
  for (const f of files) {
3140
3251
  if (!f.endsWith(".csv")) continue;
3141
3252
  const tableName = f.replace(".csv", "");
3142
3253
  if (!registry.has(tableName)) continue;
3143
- const data = readCsv(join17(d.path, f));
3254
+ const data = readCsv(join18(d.path, f));
3144
3255
  counts.push(`${tableName}: ${data.rows.length}`);
3145
3256
  totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
3146
3257
  }
@@ -3158,7 +3269,7 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
3158
3269
  console.log(` TOTAL: ${grand}`);
3159
3270
  });
3160
3271
  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) => {
3161
- const absDir = resolve3(dir);
3272
+ const absDir = resolve2(dir);
3162
3273
  const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
3163
3274
  resolveTopology2(absDir);
3164
3275
  });
@@ -3168,8 +3279,8 @@ program.command("merge").argument("<dirs...>", "Two or more BimDown project dire
3168
3279
  process.exitCode = 1;
3169
3280
  return;
3170
3281
  }
3171
- const absDirs = dirs.map((d) => resolve3(d));
3172
- const absOut = resolve3(opts.output);
3282
+ const absDirs = dirs.map((d) => resolve2(d));
3283
+ const absOut = resolve2(opts.output);
3173
3284
  const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
3174
3285
  await merge2(absDirs, absOut);
3175
3286
  });
@@ -3206,13 +3317,13 @@ program.command("schema").argument("[table]", "Table name (omit for all tables)"
3206
3317
  }
3207
3318
  });
3208
3319
  program.command("init").argument("<dir>", "BimDown project directory").description("Initialize a new BimDown project structure").action(async (dir) => {
3209
- const absDir = resolve3(dir);
3320
+ const absDir = resolve2(dir);
3210
3321
  const { initProject: initProject2 } = await Promise.resolve().then(() => (init_init(), init_exports));
3211
3322
  initProject2(absDir);
3212
3323
  });
3213
3324
  program.command("diff").argument("<dirA>", "First BimDown project directory").argument("<dirB>", "Second BimDown project directory").description("Show differences between two BimDown projects").action(async (dirA, dirB) => {
3214
- const absA = resolve3(dirA);
3215
- const absB = resolve3(dirB);
3325
+ const absA = resolve2(dirA);
3326
+ const absB = resolve2(dirB);
3216
3327
  const { diffProjects: diffProjects2 } = await Promise.resolve().then(() => (init_diff(), diff_exports));
3217
3328
  diffProjects2(absA, absB);
3218
3329
  });
@@ -3220,10 +3331,6 @@ program.command("publish").argument("<dir>", "BimDown project directory").option
3220
3331
  const { publish: publish2 } = await Promise.resolve().then(() => (init_publish(), publish_exports));
3221
3332
  await publish2(dir, opts);
3222
3333
  });
3223
- program.command("generate-skill").description("Generate AI Agent SKILL.md documentation from YAML schemas").action(async () => {
3224
- const { generateSkill: generateSkill2 } = await Promise.resolve().then(() => (init_generate_skill(), generate_skill_exports));
3225
- generateSkill2("..");
3226
- });
3227
3334
  program.parse();
3228
3335
  function printTable(columns, rows) {
3229
3336
  if (rows.length === 0) {