bimdown-cli 0.2.3 → 0.4.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.
@@ -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);
@@ -528,11 +528,12 @@ async function hydrate(conn, dir) {
528
528
  { name: "global", path: layout.globalDir },
529
529
  ...layout.levelDirs
530
530
  ];
531
+ const hydrated = [];
531
532
  for (const [tableName, table] of registry) {
532
533
  const csvFiles = [];
533
534
  for (const d of allDirs) {
534
- const csvPath = join9(d.path, `${tableName}.csv`);
535
- if (existsSync8(csvPath)) {
535
+ const csvPath = join11(d.path, `${tableName}.csv`);
536
+ if (existsSync10(csvPath)) {
536
537
  csvFiles.push({ dir: d.name, fullPath: csvPath });
537
538
  }
538
539
  }
@@ -550,38 +551,96 @@ async function hydrate(conn, dir) {
550
551
  const cols = [...headers, "_partition"];
551
552
  const colDefs = cols.map((c) => `"${c}" VARCHAR`).join(", ");
552
553
  await runQuery(conn, `CREATE TABLE "${tableName}" (${colDefs})`);
553
- for (const row of allRows) {
554
- const values = cols.map((c) => escapeSql(row[c] ?? ""));
555
- await runQuery(conn, `INSERT INTO "${tableName}" VALUES (${values.join(", ")})`);
554
+ for (let i = 0; i < allRows.length; i += INSERT_BATCH_SIZE) {
555
+ const batch = allRows.slice(i, i + INSERT_BATCH_SIZE);
556
+ const valuesSql = batch.map((row) => `(${cols.map((c) => escapeSql(row[c] ?? "")).join(", ")})`).join(", ");
557
+ await runQuery(conn, `INSERT INTO "${tableName}" VALUES ${valuesSql}`);
556
558
  }
557
559
  tables.push(tableName);
558
- await injectGeometry(conn, tableName, allDirs);
560
+ hydrated.push({ name: tableName, table });
561
+ }
562
+ const levelsReady = await tryCreateLevelsTemp(conn);
563
+ for (const { name, table } of hydrated) {
564
+ await injectGeometry(conn, name, allDirs);
565
+ if (levelsReady && table.computedFields.some((f) => f.name === "height")) {
566
+ await injectHeight(conn, name);
567
+ }
559
568
  }
560
569
  return tables;
561
570
  }
571
+ async function tryCreateLevelsTemp(conn) {
572
+ const check = await runQuery(
573
+ conn,
574
+ `SELECT table_name FROM information_schema.tables WHERE table_name = 'level'`
575
+ );
576
+ if (check.rows.length === 0) return false;
577
+ await runQuery(
578
+ conn,
579
+ `CREATE TEMP TABLE _levels AS
580
+ SELECT
581
+ id,
582
+ CAST(elevation AS DOUBLE) AS elevation,
583
+ ROW_NUMBER() OVER (ORDER BY CAST(elevation AS DOUBLE)) AS rank
584
+ FROM level
585
+ WHERE elevation IS NOT NULL AND elevation <> ''`
586
+ );
587
+ return true;
588
+ }
589
+ async function injectHeight(conn, tableName) {
590
+ const colsResult = await runQuery(
591
+ conn,
592
+ `SELECT column_name FROM information_schema.columns WHERE table_name = '${tableName}'`
593
+ );
594
+ const existing = new Set(colsResult.rows.map((r) => String(r.column_name)));
595
+ const ensureVarchar = async (col) => {
596
+ if (!existing.has(col)) {
597
+ await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" VARCHAR`);
598
+ }
599
+ };
600
+ await ensureVarchar("base_level_id");
601
+ await ensureVarchar("top_level_id");
602
+ await ensureVarchar("base_offset");
603
+ await ensureVarchar("top_offset");
604
+ if (!existing.has("height")) {
605
+ await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "height" DOUBLE`);
606
+ }
607
+ await runQuery(
608
+ conn,
609
+ `UPDATE "${tableName}" AS t
610
+ SET height = (lv_top.elevation + COALESCE(CAST(NULLIF(t.top_offset, '') AS DOUBLE), 0))
611
+ - (lv_base.elevation + COALESCE(CAST(NULLIF(t.base_offset, '') AS DOUBLE), 0))
612
+ FROM _levels AS lv_base, _levels AS lv_top
613
+ WHERE lv_base.id = COALESCE(
614
+ NULLIF(t.base_level_id, ''),
615
+ CASE WHEN t._partition <> 'global'
616
+ THEN t._partition
617
+ ELSE (SELECT id FROM _levels ORDER BY rank LIMIT 1)
618
+ END
619
+ )
620
+ AND lv_top.id = COALESCE(
621
+ NULLIF(t.top_level_id, ''),
622
+ (SELECT id FROM _levels WHERE rank = lv_base.rank + 1)
623
+ )`
624
+ );
625
+ }
562
626
  async function injectGeometry(conn, tableName, dirs) {
563
627
  const svgName = SVG_FILE_NAMES[tableName];
564
628
  if (!svgName) return;
565
629
  const geometries = /* @__PURE__ */ new Map();
566
630
  for (const d of dirs) {
567
- if (d.name === "global") continue;
568
- const svgPath = join9(d.path, `${svgName}.svg`);
569
- if (!existsSync8(svgPath)) continue;
631
+ const svgPath = join11(d.path, `${svgName}.svg`);
632
+ if (!existsSync10(svgPath)) continue;
570
633
  try {
571
634
  const svg = parseSvgFile(svgPath);
572
635
  for (const el of svg.elements) {
573
636
  if (el.tag === "path") {
574
- const geo = extractLineGeometry(el);
575
- geometries.set(el.id, geo);
637
+ geometries.set(el.id, extractLineGeometry(el));
576
638
  } else if (el.tag === "rect") {
577
- const geo = extractRectGeometry(el);
578
- geometries.set(el.id, geo);
639
+ geometries.set(el.id, extractRectGeometry(el));
579
640
  } else if (el.tag === "polygon") {
580
- const geo = extractPolygonGeometry(el);
581
- geometries.set(el.id, geo);
641
+ geometries.set(el.id, extractPolygonGeometry(el));
582
642
  } else if (el.tag === "circle") {
583
- const geo = extractCircleGeometry(el);
584
- geometries.set(el.id, geo);
643
+ geometries.set(el.id, extractCircleGeometry(el));
585
644
  }
586
645
  }
587
646
  } catch {
@@ -592,24 +651,50 @@ async function injectGeometry(conn, tableName, dirs) {
592
651
  for (const geo of geometries.values()) {
593
652
  for (const k of Object.keys(geo)) allKeys.add(k);
594
653
  }
654
+ const geoCols = Array.from(allKeys);
655
+ const typeOf = (col) => col === "points" ? "VARCHAR" : "DOUBLE";
595
656
  const existingCols = await runQuery(
596
657
  conn,
597
658
  `SELECT column_name FROM information_schema.columns WHERE table_name = '${tableName}'`
598
659
  );
599
660
  const existingSet = new Set(existingCols.rows.map((r) => String(r.column_name)));
600
- for (const col of allKeys) {
661
+ for (const col of geoCols) {
601
662
  if (existingSet.has(col)) continue;
602
- const sqlType = col === "points" ? "VARCHAR" : "DOUBLE";
603
- await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" ${sqlType}`);
604
- }
605
- for (const [id, geo] of geometries) {
606
- const sets = Object.entries(geo).map(([k, v]) => `"${k}" = ${typeof v === "string" ? escapeSql(v) : v}`).join(", ");
607
- await runQuery(conn, `UPDATE "${tableName}" SET ${sets} WHERE id = ${escapeSql(id)}`);
663
+ await runQuery(conn, `ALTER TABLE "${tableName}" ADD COLUMN "${col}" ${typeOf(col)}`);
664
+ }
665
+ const stagingName = `_geo_${tableName}`;
666
+ const stagingColDefs = ['"id" VARCHAR', ...geoCols.map((c) => `"${c}" ${typeOf(c)}`)].join(", ");
667
+ await runQuery(conn, `CREATE TEMP TABLE "${stagingName}" (${stagingColDefs})`);
668
+ const entries = Array.from(geometries.entries());
669
+ for (let i = 0; i < entries.length; i += INSERT_BATCH_SIZE) {
670
+ const batch = entries.slice(i, i + INSERT_BATCH_SIZE);
671
+ const valuesSql = batch.map(([id, geo]) => {
672
+ const vals = [escapeSql(id)];
673
+ for (const col of geoCols) {
674
+ const v = geo[col];
675
+ if (v === void 0 || v === null) {
676
+ vals.push("NULL");
677
+ } else if (typeof v === "string") {
678
+ vals.push(escapeSql(v));
679
+ } else {
680
+ vals.push(String(v));
681
+ }
682
+ }
683
+ return `(${vals.join(", ")})`;
684
+ }).join(", ");
685
+ await runQuery(conn, `INSERT INTO "${stagingName}" VALUES ${valuesSql}`);
608
686
  }
687
+ const setClause = geoCols.map((c) => `"${c}" = g."${c}"`).join(", ");
688
+ await runQuery(
689
+ conn,
690
+ `UPDATE "${tableName}" SET ${setClause} FROM "${stagingName}" g WHERE "${tableName}".id = g.id`
691
+ );
692
+ await runQuery(conn, `DROP TABLE "${stagingName}"`);
609
693
  }
610
694
  function escapeSql(val) {
611
695
  return "'" + val.replace(/'/g, "''") + "'";
612
696
  }
697
+ var INSERT_BATCH_SIZE;
613
698
  var init_hydrate = __esm({
614
699
  "src/duckdb/hydrate.ts"() {
615
700
  "use strict";
@@ -618,6 +703,7 @@ var init_hydrate = __esm({
618
703
  init_csv();
619
704
  init_svg();
620
705
  init_engine();
706
+ INSERT_BATCH_SIZE = 500;
621
707
  }
622
708
  });
623
709
 
@@ -626,8 +712,8 @@ var dehydrate_exports = {};
626
712
  __export(dehydrate_exports, {
627
713
  dehydrate: () => dehydrate
628
714
  });
629
- import { existsSync as existsSync9, mkdirSync } from "fs";
630
- import { join as join10 } from "path";
715
+ import { existsSync as existsSync11, mkdirSync } from "fs";
716
+ import { join as join12 } from "path";
631
717
  async function dehydrate(conn, dir) {
632
718
  const registry = buildRegistry(getSpecDir());
633
719
  for (const [tableName, table] of registry) {
@@ -643,8 +729,8 @@ async function dehydrate(conn, dir) {
643
729
  );
644
730
  for (const partRow of partResult.rows) {
645
731
  const partition = String(partRow._partition);
646
- const outDir = join10(dir, partition);
647
- if (!existsSync9(outDir)) mkdirSync(outDir, { recursive: true });
732
+ const outDir = join12(dir, partition);
733
+ if (!existsSync11(outDir)) mkdirSync(outDir, { recursive: true });
648
734
  const selectCols = csvHeaders.map((h) => `"${h}"`).join(", ");
649
735
  const dataResult = await runQuery(
650
736
  conn,
@@ -661,7 +747,7 @@ async function dehydrate(conn, dir) {
661
747
  return row;
662
748
  })
663
749
  };
664
- writeCsv(join10(outDir, `${tableName}.csv`), data);
750
+ writeCsv(join12(outDir, `${tableName}.csv`), data);
665
751
  }
666
752
  }
667
753
  }
@@ -679,8 +765,8 @@ var render_exports = {};
679
765
  __export(render_exports, {
680
766
  renderLevel: () => renderLevel
681
767
  });
682
- import { existsSync as existsSync10 } from "fs";
683
- import { join as join11 } from "path";
768
+ import { existsSync as existsSync12 } from "fs";
769
+ import { join as join13 } from "path";
684
770
  function elementBounds2(el) {
685
771
  switch (el.tag) {
686
772
  case "path": {
@@ -766,8 +852,8 @@ function escapeXml(s) {
766
852
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
767
853
  }
768
854
  function renderHostedElements(levelDir, tableName, wallElements) {
769
- const csvPath = join11(levelDir.path, `${tableName}.csv`);
770
- if (!existsSync10(csvPath)) return [];
855
+ const csvPath = join13(levelDir.path, `${tableName}.csv`);
856
+ if (!existsSync12(csvPath)) return [];
771
857
  const csv = readCsv(csvPath);
772
858
  const color = COLORS[tableName] ?? DEFAULT_COLOR;
773
859
  const results = [];
@@ -806,7 +892,7 @@ function renderHostedElements(levelDir, tableName, wallElements) {
806
892
  const y1 = cy - uy * halfW;
807
893
  const x2 = cx + ux * halfW;
808
894
  const y2 = cy + uy * halfW;
809
- const sw = tableName === "door" ? "0.08" : "0.06";
895
+ const sw = tableName === "door" ? "0.22" : "0.18";
810
896
  const markup = ` <line id="${row.id}" x1="${x1.toFixed(3)}" y1="${y1.toFixed(3)}" x2="${x2.toFixed(3)}" y2="${y2.toFixed(3)}" stroke="${color.stroke}" stroke-width="${sw}" />`;
811
897
  results.push({
812
898
  tableName,
@@ -822,8 +908,8 @@ function renderHostedElements(levelDir, tableName, wallElements) {
822
908
  return results;
823
909
  }
824
910
  function renderSpaces(levelDir) {
825
- const csvPath = join11(levelDir.path, "space.csv");
826
- if (!existsSync10(csvPath)) return [];
911
+ const csvPath = join13(levelDir.path, "space.csv");
912
+ if (!existsSync12(csvPath)) return [];
827
913
  const csv = readCsv(csvPath);
828
914
  const color = COLORS.space ?? DEFAULT_COLOR;
829
915
  const results = [];
@@ -831,8 +917,8 @@ function renderSpaces(levelDir) {
831
917
  for (const row of csv.rows) {
832
918
  nameMap.set(row.id, row.name ?? row.id ?? "");
833
919
  }
834
- const svgPath = join11(levelDir.path, "space.svg");
835
- if (existsSync10(svgPath)) {
920
+ const svgPath = join13(levelDir.path, "space.svg");
921
+ if (existsSync12(svgPath)) {
836
922
  try {
837
923
  const svg = parseSvgFile(svgPath);
838
924
  for (const el of svg.elements) {
@@ -895,22 +981,28 @@ function renderLevel(projectDir, levelId) {
895
981
  const csvOnlyElements = [];
896
982
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
897
983
  const wallElements = /* @__PURE__ */ new Map();
984
+ const renderSources = [
985
+ { path: layout.globalDir },
986
+ { path: levelDir.path }
987
+ ];
898
988
  for (const tableName of RENDER_ORDER) {
899
989
  if (CSV_ONLY_TABLES.has(tableName)) continue;
900
990
  const svgName = SVG_FILE_NAMES[tableName];
901
991
  if (!svgName) continue;
902
- const svgPath = join11(levelDir.path, svgName + ".svg");
903
- if (!existsSync10(svgPath)) continue;
904
- const svg = parseSvgFile(svgPath);
905
- for (const el of svg.elements) {
906
- allElements.push({ tableName, el });
907
- if (tableName === "wall") wallElements.set(el.id, el);
908
- const b = elementBounds2(el);
909
- if (b) {
910
- minX = Math.min(minX, b.minX);
911
- minY = Math.min(minY, b.minY);
912
- maxX = Math.max(maxX, b.maxX);
913
- maxY = Math.max(maxY, b.maxY);
992
+ for (const src of renderSources) {
993
+ const svgPath = join13(src.path, svgName + ".svg");
994
+ if (!existsSync12(svgPath)) continue;
995
+ const svg = parseSvgFile(svgPath);
996
+ for (const el of svg.elements) {
997
+ allElements.push({ tableName, el });
998
+ if (tableName === "wall") wallElements.set(el.id, el);
999
+ const b = elementBounds2(el);
1000
+ if (b) {
1001
+ minX = Math.min(minX, b.minX);
1002
+ minY = Math.min(minY, b.minY);
1003
+ maxX = Math.max(maxX, b.maxX);
1004
+ maxY = Math.max(maxY, b.maxY);
1005
+ }
914
1006
  }
915
1007
  }
916
1008
  }
@@ -1009,8 +1101,8 @@ var resolve_topology_exports = {};
1009
1101
  __export(resolve_topology_exports, {
1010
1102
  resolveTopology: () => resolveTopology
1011
1103
  });
1012
- import { existsSync as existsSync11, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
1013
- import { join as join12 } from "path";
1104
+ import { existsSync as existsSync13, mkdirSync as mkdirSync2, writeFileSync as writeFileSync4 } from "fs";
1105
+ import { join as join14 } from "path";
1014
1106
  function dist3d(a, b) {
1015
1107
  const dx = a.x - b.x;
1016
1108
  const dy = a.y - b.y;
@@ -1019,10 +1111,10 @@ function dist3d(a, b) {
1019
1111
  }
1020
1112
  function insideBBox(point, node) {
1021
1113
  const dz = Math.abs(point.z - node.pos.z);
1022
- if (dz > TOLERANCE3) return false;
1114
+ if (dz > TOLERANCE4) return false;
1023
1115
  const dx = Math.abs(point.x - node.pos.x);
1024
1116
  const dy = Math.abs(point.y - node.pos.y);
1025
- return dx <= node.halfW + TOLERANCE3 && dy <= node.halfH + TOLERANCE3;
1117
+ return dx <= node.halfW + TOLERANCE4 && dy <= node.halfH + TOLERANCE4;
1026
1118
  }
1027
1119
  function resolveTopology(dir) {
1028
1120
  buildRegistry(getSpecDir());
@@ -1037,14 +1129,14 @@ function resolveTopology(dir) {
1037
1129
  let skippedStart = 0;
1038
1130
  let skippedEnd = 0;
1039
1131
  for (const d of allDirs) {
1040
- if (!existsSync11(d.path)) continue;
1132
+ if (!existsSync13(d.path)) continue;
1041
1133
  const files = listFiles(d.path);
1042
1134
  for (const tableName of CURVE_TABLES) {
1043
1135
  if (!files.includes(`${tableName}.csv`)) continue;
1044
1136
  const svgName = SVG_FILE_NAMES[tableName];
1045
1137
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1046
- const csvPath = join12(d.path, `${tableName}.csv`);
1047
- const svgPath = join12(d.path, `${svgName}.svg`);
1138
+ const csvPath = join14(d.path, `${tableName}.csv`);
1139
+ const svgPath = join14(d.path, `${svgName}.svg`);
1048
1140
  const csv = readCsv(csvPath);
1049
1141
  const key = `${d.name}/${tableName}`;
1050
1142
  curveData.set(key, { csv, path: csvPath });
@@ -1094,14 +1186,14 @@ function resolveTopology(dir) {
1094
1186
  }
1095
1187
  const nodes = [];
1096
1188
  for (const d of allDirs) {
1097
- if (!existsSync11(d.path)) continue;
1189
+ if (!existsSync13(d.path)) continue;
1098
1190
  const files = listFiles(d.path);
1099
1191
  for (const tableName of NODE_TABLES) {
1100
1192
  if (!files.includes(`${tableName}.csv`)) continue;
1101
1193
  const svgName = SVG_FILE_NAMES[tableName];
1102
1194
  if (!svgName || !files.includes(`${svgName}.svg`)) continue;
1103
- const csvPath = join12(d.path, `${tableName}.csv`);
1104
- const svgPath = join12(d.path, `${svgName}.svg`);
1195
+ const csvPath = join14(d.path, `${tableName}.csv`);
1196
+ const svgPath = join14(d.path, `${svgName}.svg`);
1105
1197
  const csv = readCsv(csvPath);
1106
1198
  let svgElements;
1107
1199
  try {
@@ -1156,7 +1248,7 @@ function resolveTopology(dir) {
1156
1248
  for (const ep of stillFree) {
1157
1249
  let found = false;
1158
1250
  for (const j of junctions) {
1159
- if (dist3d(ep.point, j.point) < TOLERANCE3) {
1251
+ if (dist3d(ep.point, j.point) < TOLERANCE4) {
1160
1252
  j.endpoints.push(ep);
1161
1253
  found = true;
1162
1254
  break;
@@ -1196,12 +1288,12 @@ function resolveTopology(dir) {
1196
1288
  newNodesByLevel.set(j.levelDir, arr);
1197
1289
  }
1198
1290
  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");
1291
+ const dirPath = levelDir === "global" ? layout.globalDir : join14(dir, levelDir);
1292
+ if (!existsSync13(dirPath)) mkdirSync2(dirPath, { recursive: true });
1293
+ const csvPath = join14(dirPath, "mep_node.csv");
1294
+ const svgPath = join14(dirPath, "mep_node.svg");
1203
1295
  let csv;
1204
- if (existsSync11(csvPath)) {
1296
+ if (existsSync13(csvPath)) {
1205
1297
  csv = readCsv(csvPath);
1206
1298
  } else {
1207
1299
  csv = { headers: ["id", "number", "base_offset", "system_type"], rows: [] };
@@ -1210,7 +1302,7 @@ function resolveTopology(dir) {
1210
1302
  if (!csv.headers.includes(h)) csv.headers.push(h);
1211
1303
  }
1212
1304
  let existingSvgElements = [];
1213
- if (existsSync11(svgPath)) {
1305
+ if (existsSync13(svgPath)) {
1214
1306
  try {
1215
1307
  existingSvgElements = parseSvgFile(svgPath).elements;
1216
1308
  } catch {
@@ -1263,7 +1355,7 @@ function resolveTopology(dir) {
1263
1355
  const pad = Math.max(maxX - minX, maxY - minY) * 0.02;
1264
1356
  viewBox = `${(minX - pad).toFixed(3)} ${(-(maxY + pad)).toFixed(3)} ${(maxX - minX + pad * 2).toFixed(3)} ${(maxY - minY + pad * 2).toFixed(3)}`;
1265
1357
  }
1266
- writeFileSync3(svgPath, [
1358
+ writeFileSync4(svgPath, [
1267
1359
  '<?xml version="1.0" encoding="utf-8"?>',
1268
1360
  `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}">`,
1269
1361
  ' <g transform="scale(1,-1)">',
@@ -1312,7 +1404,7 @@ function resolveTopology(dir) {
1312
1404
  console.log(`Updated ${updatedRows} curve rows`);
1313
1405
  }
1314
1406
  }
1315
- var TOLERANCE3, CURVE_TABLES, NODE_TABLES;
1407
+ var TOLERANCE4, CURVE_TABLES, NODE_TABLES;
1316
1408
  var init_resolve_topology = __esm({
1317
1409
  "src/commands/resolve-topology.ts"() {
1318
1410
  "use strict";
@@ -1320,7 +1412,7 @@ var init_resolve_topology = __esm({
1320
1412
  init_svg();
1321
1413
  init_fs();
1322
1414
  init_registry();
1323
- TOLERANCE3 = 0.01;
1415
+ TOLERANCE4 = 0.01;
1324
1416
  CURVE_TABLES = ["duct", "pipe", "cable_tray", "conduit"];
1325
1417
  NODE_TABLES = ["equipment", "terminal", "mep_node"];
1326
1418
  }
@@ -1331,8 +1423,8 @@ var merge_exports = {};
1331
1423
  __export(merge_exports, {
1332
1424
  merge: () => merge
1333
1425
  });
1334
- import { existsSync as existsSync12, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
1335
- import { join as join13, basename as basename2 } from "path";
1426
+ import { existsSync as existsSync14, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
1427
+ import { join as join15, basename as basename2 } from "path";
1336
1428
  async function merge(dirs, outputDir) {
1337
1429
  const registry = buildRegistry(getSpecDir());
1338
1430
  console.log(`Scanning ${dirs.length} sources...`);
@@ -1342,10 +1434,10 @@ async function merge(dirs, outputDir) {
1342
1434
  const { canonicalGrids, gridRemaps } = deduplicateGrids(sources);
1343
1435
  console.log(`Merged grids: ${canonicalGrids.rows.length} unique grids`);
1344
1436
  const fullRemaps = buildFullRemaps(sources, levelRemaps, gridRemaps, registry);
1345
- mkdirSync3(join13(outputDir, "global"), { recursive: true });
1346
- writeCsv(join13(outputDir, "global", "level.csv"), canonicalLevels);
1437
+ mkdirSync3(join15(outputDir, "global"), { recursive: true });
1438
+ writeCsv(join15(outputDir, "global", "level.csv"), canonicalLevels);
1347
1439
  if (canonicalGrids.rows.length > 0) {
1348
- writeCsv(join13(outputDir, "global", "grid.csv"), canonicalGrids);
1440
+ writeCsv(join15(outputDir, "global", "grid.csv"), canonicalGrids);
1349
1441
  }
1350
1442
  writeIdMap(outputDir, sources, fullRemaps);
1351
1443
  const levelDirMap = buildLevelDirMap(sources, fullRemaps);
@@ -1356,26 +1448,26 @@ async function merge(dirs, outputDir) {
1356
1448
  function scanSource(dir, registry) {
1357
1449
  const layout = discoverLayout(dir);
1358
1450
  const name = basename2(dir);
1359
- const levelPath = join13(layout.globalDir, "level.csv");
1360
- if (!existsSync12(levelPath)) {
1451
+ const levelPath = join15(layout.globalDir, "level.csv");
1452
+ if (!existsSync14(levelPath)) {
1361
1453
  throw new Error(`Missing level.csv in ${dir}/global/`);
1362
1454
  }
1363
1455
  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;
1456
+ const gridPath = join15(layout.globalDir, "grid.csv");
1457
+ const grids = existsSync14(gridPath) ? readCsv(gridPath) : null;
1458
+ const idMapPath = join15(layout.globalDir, "_IdMap.csv");
1459
+ const idMap = existsSync14(idMapPath) ? readCsv(idMapPath) : null;
1368
1460
  const globalData = /* @__PURE__ */ new Map();
1369
- if (existsSync12(layout.globalDir)) {
1461
+ if (existsSync14(layout.globalDir)) {
1370
1462
  for (const f of listFiles(layout.globalDir)) {
1371
1463
  if (!f.endsWith(".csv")) continue;
1372
1464
  const tableName = f.replace(".csv", "");
1373
1465
  if (tableName === "level" || tableName === "grid" || tableName === "_IdMap") continue;
1374
1466
  if (!registry.has(tableName)) continue;
1375
- const csv = readCsv(join13(layout.globalDir, f));
1467
+ const csv = readCsv(join15(layout.globalDir, f));
1376
1468
  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 });
1469
+ const svgFile = svgName ? join15(layout.globalDir, svgName + ".svg") : null;
1470
+ globalData.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1379
1471
  }
1380
1472
  }
1381
1473
  const levelData = /* @__PURE__ */ new Map();
@@ -1385,10 +1477,10 @@ function scanSource(dir, registry) {
1385
1477
  if (!f.endsWith(".csv")) continue;
1386
1478
  const tableName = f.replace(".csv", "");
1387
1479
  if (!registry.has(tableName)) continue;
1388
- const csv = readCsv(join13(ld.path, f));
1480
+ const csv = readCsv(join15(ld.path, f));
1389
1481
  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 });
1482
+ const svgFile = svgName ? join15(ld.path, svgName + ".svg") : null;
1483
+ tables.set(tableName, { csv, svgFile: svgFile && existsSync14(svgFile) ? svgFile : null });
1392
1484
  }
1393
1485
  if (tables.size > 0) {
1394
1486
  levelData.set(ld.name, tables);
@@ -1575,7 +1667,7 @@ function writeIdMap(outputDir, sources, remaps) {
1575
1667
  }
1576
1668
  }
1577
1669
  if (rows.length > 0) {
1578
- writeCsv(join13(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1670
+ writeCsv(join15(outputDir, "global", "_IdMap.csv"), { headers: ["id", "uuid"], rows });
1579
1671
  }
1580
1672
  }
1581
1673
  function buildLevelDirMap(sources, remaps) {
@@ -1616,13 +1708,13 @@ function writeGlobalTables(outputDir, sources, remaps, registry) {
1616
1708
  }
1617
1709
  for (const [tableName, entry] of merged) {
1618
1710
  if (entry.rows.length > 0) {
1619
- writeCsv(join13(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1711
+ writeCsv(join15(outputDir, "global", tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1620
1712
  }
1621
1713
  if (entry.svgInputs.length > 0) {
1622
1714
  const svgName = SVG_FILE_NAMES[tableName];
1623
1715
  if (svgName) {
1624
1716
  const content = writeMergedSvg(entry.svgInputs);
1625
- writeFileSync4(join13(outputDir, "global", svgName + ".svg"), content, "utf-8");
1717
+ writeFileSync5(join15(outputDir, "global", svgName + ".svg"), content, "utf-8");
1626
1718
  }
1627
1719
  }
1628
1720
  }
@@ -1654,17 +1746,17 @@ function writeLevelTables(outputDir, sources, remaps, levelDirMap, registry) {
1654
1746
  }
1655
1747
  }
1656
1748
  for (const [outDirName, tables] of merged) {
1657
- const dirPath = join13(outputDir, outDirName);
1749
+ const dirPath = join15(outputDir, outDirName);
1658
1750
  mkdirSync3(dirPath, { recursive: true });
1659
1751
  for (const [tableName, entry] of tables) {
1660
1752
  if (entry.rows.length > 0) {
1661
- writeCsv(join13(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1753
+ writeCsv(join15(dirPath, tableName + ".csv"), { headers: entry.headers, rows: entry.rows });
1662
1754
  }
1663
1755
  if (entry.svgInputs.length > 0) {
1664
1756
  const svgName = SVG_FILE_NAMES[tableName];
1665
1757
  if (svgName) {
1666
1758
  const content = writeMergedSvg(entry.svgInputs);
1667
- writeFileSync4(join13(dirPath, svgName + ".svg"), content, "utf-8");
1759
+ writeFileSync5(join15(dirPath, svgName + ".svg"), content, "utf-8");
1668
1760
  }
1669
1761
  }
1670
1762
  }
@@ -1696,29 +1788,29 @@ var init_exports = {};
1696
1788
  __export(init_exports, {
1697
1789
  initProject: () => initProject
1698
1790
  });
1699
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5, existsSync as existsSync13 } from "fs";
1700
- import { join as join14 } from "path";
1791
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6, existsSync as existsSync15 } from "fs";
1792
+ import { join as join16 } from "path";
1701
1793
  function initProject(absDir) {
1702
- if (!existsSync13(absDir)) {
1794
+ if (!existsSync15(absDir)) {
1703
1795
  mkdirSync4(absDir, { recursive: true });
1704
1796
  }
1705
- writeFileSync5(join14(absDir, ".bimdown"), "", "utf-8");
1706
- const globalDir = join14(absDir, "global");
1707
- if (!existsSync13(globalDir)) {
1797
+ writeFileSync6(join16(absDir, ".bimdown"), "", "utf-8");
1798
+ const globalDir = join16(absDir, "global");
1799
+ if (!existsSync15(globalDir)) {
1708
1800
  mkdirSync4(globalDir, { recursive: true });
1709
1801
  }
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");
1802
+ const levelCsvPath = join16(globalDir, "level.csv");
1803
+ if (!existsSync15(levelCsvPath)) {
1804
+ writeFileSync6(levelCsvPath, "id,name,elevation\nlv-1,Level 1,0.0\n", "utf-8");
1713
1805
  }
1714
- const gridCsvPath = join14(globalDir, "grid.csv");
1715
- if (!existsSync13(gridCsvPath)) {
1806
+ const gridCsvPath = join16(globalDir, "grid.csv");
1807
+ if (!existsSync15(gridCsvPath)) {
1716
1808
  const gridContent = [
1717
1809
  "id,name,role,start_x,start_y,end_x,end_y",
1718
1810
  "gr-1,A,primary,-10000,0,10000,0",
1719
1811
  "gr-2,1,primary,0,-10000,0,10000"
1720
1812
  ].join("\n") + "\n";
1721
- writeFileSync5(gridCsvPath, gridContent, "utf-8");
1813
+ writeFileSync6(gridCsvPath, gridContent, "utf-8");
1722
1814
  }
1723
1815
  console.log(`Initialized empty BimDown project at ${absDir}`);
1724
1816
  console.log("Created:");
@@ -1736,15 +1828,15 @@ var diff_exports = {};
1736
1828
  __export(diff_exports, {
1737
1829
  diffProjects: () => diffProjects
1738
1830
  });
1739
- import { existsSync as existsSync14 } from "fs";
1740
- import { join as join15 } from "path";
1831
+ import { existsSync as existsSync16 } from "fs";
1832
+ import { join as join17 } from "path";
1741
1833
  function diffProjects(dirA, dirB) {
1742
- if (!existsSync14(dirA)) {
1834
+ if (!existsSync16(dirA)) {
1743
1835
  console.error(`Directory not found: ${dirA}`);
1744
1836
  process.exitCode = 1;
1745
1837
  return;
1746
1838
  }
1747
- if (!existsSync14(dirB)) {
1839
+ if (!existsSync16(dirB)) {
1748
1840
  console.error(`Directory not found: ${dirB}`);
1749
1841
  process.exitCode = 1;
1750
1842
  return;
@@ -1763,22 +1855,22 @@ function diffProjects(dirA, dirB) {
1763
1855
  for (const pathName of allPathNames) {
1764
1856
  const dirAAbs = pathsA.find((p) => p.name === pathName)?.abs;
1765
1857
  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")) : []);
1858
+ const filesA = new Set(dirAAbs && existsSync16(dirAAbs) ? listFiles(dirAAbs).filter((f) => f.endsWith(".csv")) : []);
1859
+ const filesB = new Set(dirBAbs && existsSync16(dirBAbs) ? listFiles(dirBAbs).filter((f) => f.endsWith(".csv")) : []);
1768
1860
  const allFiles = /* @__PURE__ */ new Set([...filesA, ...filesB]);
1769
1861
  let printedPathHeader = false;
1770
1862
  for (const f of allFiles) {
1771
1863
  const tableName = f.replace(".csv", "");
1772
- const pathFileA = dirAAbs ? join15(dirAAbs, f) : null;
1773
- const pathFileB = dirBAbs ? join15(dirBAbs, f) : null;
1864
+ const pathFileA = dirAAbs ? join17(dirAAbs, f) : null;
1865
+ const pathFileB = dirBAbs ? join17(dirBAbs, f) : null;
1774
1866
  const rowsA = {};
1775
1867
  const rowsB = {};
1776
- if (pathFileA && existsSync14(pathFileA)) {
1868
+ if (pathFileA && existsSync16(pathFileA)) {
1777
1869
  for (const row of readCsv(pathFileA).rows) {
1778
1870
  if (row.id) rowsA[String(row.id)] = row;
1779
1871
  }
1780
1872
  }
1781
- if (pathFileB && existsSync14(pathFileB)) {
1873
+ if (pathFileB && existsSync16(pathFileB)) {
1782
1874
  for (const row of readCsv(pathFileB).rows) {
1783
1875
  if (row.id) rowsB[String(row.id)] = row;
1784
1876
  }
@@ -1825,11 +1917,11 @@ __export(publish_exports, {
1825
1917
  publish: () => publish
1826
1918
  });
1827
1919
  import { resolve } from "path";
1828
- import { readFileSync as readFileSync5, existsSync as existsSync15 } from "fs";
1920
+ import { readFileSync as readFileSync6, existsSync as existsSync17 } from "fs";
1829
1921
  import { zipSync } from "fflate";
1830
1922
  async function publish(dir, opts) {
1831
1923
  const absDir = resolve(dir);
1832
- if (!existsSync15(absDir)) {
1924
+ if (!existsSync17(absDir)) {
1833
1925
  console.error(`Directory not found: ${absDir}`);
1834
1926
  process.exitCode = 1;
1835
1927
  return;
@@ -1843,16 +1935,16 @@ async function publish(dir, opts) {
1843
1935
  ];
1844
1936
  const files = {};
1845
1937
  for (const d of allDirs) {
1846
- if (!existsSync15(d.path)) continue;
1938
+ if (!existsSync17(d.path)) continue;
1847
1939
  for (const f of listFiles(d.path)) {
1848
1940
  const filePath = `${d.prefix}/${f}`;
1849
- const content = readFileSync5(resolve(d.path, f));
1941
+ const content = readFileSync6(resolve(d.path, f));
1850
1942
  files[filePath] = new Uint8Array(content);
1851
1943
  }
1852
1944
  }
1853
1945
  const metadataPath = resolve(absDir, "project_metadata.json");
1854
- if (existsSync15(metadataPath)) {
1855
- files["project_metadata.json"] = new Uint8Array(readFileSync5(metadataPath));
1946
+ if (existsSync17(metadataPath)) {
1947
+ files["project_metadata.json"] = new Uint8Array(readFileSync6(metadataPath));
1856
1948
  }
1857
1949
  const fileCount = Object.keys(files).length;
1858
1950
  if (fileCount === 0) {
@@ -1901,258 +1993,13 @@ var init_publish = __esm({
1901
1993
  }
1902
1994
  });
1903
1995
 
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.3" : "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
1996
  // src/index.ts
2150
1997
  import { Command } from "commander";
2151
- import { resolve as resolve3 } from "path";
1998
+ import { resolve as resolve2 } from "path";
2152
1999
 
2153
2000
  // src/build/index.ts
2154
- import { existsSync as existsSync7 } from "fs";
2155
- import { join as join8 } from "path";
2001
+ import { existsSync as existsSync9 } from "fs";
2002
+ import { join as join10 } from "path";
2156
2003
 
2157
2004
  // src/validate/index.ts
2158
2005
  init_registry();
@@ -2197,8 +2044,8 @@ function validateStructure(dir) {
2197
2044
  }
2198
2045
  }
2199
2046
  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`);
2047
+ if (!/^lv-.+$/.test(ld.name)) {
2048
+ issues.push(`${ld.name}/ directory name does not match lv-{id} pattern`);
2202
2049
  continue;
2203
2050
  }
2204
2051
  const files = listFiles(ld.path);
@@ -2238,7 +2085,7 @@ function validateStructure(dir) {
2238
2085
  }
2239
2086
  const topEntries = readdirSync3(dir);
2240
2087
  for (const f of topEntries) {
2241
- if (f === "global" || /^lv-\d+$/.test(f)) continue;
2088
+ if (f === "global" || /^lv-.+$/.test(f)) continue;
2242
2089
  if (f === "project_metadata.json") continue;
2243
2090
  if (f.startsWith(".")) continue;
2244
2091
  issues.push(`${f} unexpected entry in project root \u2014 only global/ and lv-{n}/ directories are allowed`);
@@ -2664,18 +2511,22 @@ import { join as join6 } from "path";
2664
2511
  var TOLERANCE = 0.01;
2665
2512
  var MAX_FACE_EDGES = 1e4;
2666
2513
  var BOUNDARY_TABLES = ["wall", "structure_wall", "curtain_wall", "room_separator"];
2667
- function computeSpaceBoundaries(levelDir) {
2514
+ function computeSpaceBoundaries(levelDir, globalDir) {
2668
2515
  const warnings = [];
2669
2516
  const spaceCsvPath = join6(levelDir.path, "space.csv");
2670
2517
  if (!existsSync5(spaceCsvPath)) return { warnings, svgWritten: false };
2671
2518
  const spaceCsv = readCsv(spaceCsvPath);
2672
2519
  if (spaceCsv.rows.length === 0) return { warnings, svgWritten: false };
2673
2520
  const segments = collectBoundarySegments(levelDir.path);
2521
+ if (globalDir) {
2522
+ segments.push(...collectBoundarySegments(globalDir));
2523
+ }
2674
2524
  if (segments.length === 0) {
2675
2525
  warnings.push(`${levelDir.name}/ no boundary elements found for space boundary computation`);
2676
2526
  return { warnings, svgWritten: false };
2677
2527
  }
2678
- const { vertices, halfEdges } = buildHalfEdgeStructure(segments);
2528
+ const splitSegments = splitAtIntersections(segments);
2529
+ const { vertices, halfEdges } = buildHalfEdgeStructure(splitSegments);
2679
2530
  for (const v of vertices) {
2680
2531
  if (v.outgoing.length === 1) {
2681
2532
  const he = v.outgoing[0];
@@ -2735,6 +2586,82 @@ function collectBoundarySegments(levelPath) {
2735
2586
  }
2736
2587
  return segments;
2737
2588
  }
2589
+ function splitAtIntersections(segments) {
2590
+ let result = [...segments];
2591
+ let changed = true;
2592
+ while (changed) {
2593
+ changed = false;
2594
+ const allEndpoints = [];
2595
+ for (const seg of result) {
2596
+ allEndpoints.push({ x: seg.startX, y: seg.startY });
2597
+ allEndpoints.push({ x: seg.endX, y: seg.endY });
2598
+ }
2599
+ const nextResult = [];
2600
+ for (let i = 0; i < result.length; i++) {
2601
+ const seg = result[i];
2602
+ const dx = seg.endX - seg.startX;
2603
+ const dy = seg.endY - seg.startY;
2604
+ const lenSq = dx * dx + dy * dy;
2605
+ if (lenSq < TOLERANCE * TOLERANCE) {
2606
+ nextResult.push(seg);
2607
+ continue;
2608
+ }
2609
+ const splitPoints = [];
2610
+ for (const ep of allEndpoints) {
2611
+ if (Math.abs(ep.x - seg.startX) < TOLERANCE && Math.abs(ep.y - seg.startY) < TOLERANCE) continue;
2612
+ if (Math.abs(ep.x - seg.endX) < TOLERANCE && Math.abs(ep.y - seg.endY) < TOLERANCE) continue;
2613
+ const t = ((ep.x - seg.startX) * dx + (ep.y - seg.startY) * dy) / lenSq;
2614
+ if (t <= TOLERANCE || t >= 1 - TOLERANCE) continue;
2615
+ const closestX = seg.startX + t * dx;
2616
+ const closestY = seg.startY + t * dy;
2617
+ const distSq = (ep.x - closestX) * (ep.x - closestX) + (ep.y - closestY) * (ep.y - closestY);
2618
+ if (distSq < TOLERANCE * TOLERANCE) {
2619
+ splitPoints.push({ x: ep.x, y: ep.y, t });
2620
+ }
2621
+ }
2622
+ for (let j = 0; j < result.length; j++) {
2623
+ if (j === i) continue;
2624
+ const other = result[j];
2625
+ const ox = other.endX - other.startX;
2626
+ const oy = other.endY - other.startY;
2627
+ const det = dx * oy - dy * ox;
2628
+ if (Math.abs(det) < 1e-12) continue;
2629
+ const rx = other.startX - seg.startX;
2630
+ const ry = other.startY - seg.startY;
2631
+ const t = (rx * oy - ry * ox) / det;
2632
+ const s = (rx * dy - ry * dx) / det;
2633
+ if (t <= TOLERANCE || t >= 1 - TOLERANCE) continue;
2634
+ if (s <= TOLERANCE || s >= 1 - TOLERANCE) continue;
2635
+ splitPoints.push({
2636
+ x: seg.startX + t * dx,
2637
+ y: seg.startY + t * dy,
2638
+ t
2639
+ });
2640
+ }
2641
+ if (splitPoints.length === 0) {
2642
+ nextResult.push(seg);
2643
+ } else {
2644
+ changed = true;
2645
+ splitPoints.sort((a, b) => a.t - b.t);
2646
+ const unique = [splitPoints[0]];
2647
+ for (let k = 1; k < splitPoints.length; k++) {
2648
+ if (Math.abs(splitPoints[k].t - unique[unique.length - 1].t) > TOLERANCE) {
2649
+ unique.push(splitPoints[k]);
2650
+ }
2651
+ }
2652
+ let prevX = seg.startX, prevY = seg.startY;
2653
+ for (const sp of unique) {
2654
+ nextResult.push({ startX: prevX, startY: prevY, endX: sp.x, endY: sp.y, id: seg.id });
2655
+ prevX = sp.x;
2656
+ prevY = sp.y;
2657
+ }
2658
+ nextResult.push({ startX: prevX, startY: prevY, endX: seg.endX, endY: seg.endY, id: seg.id });
2659
+ }
2660
+ }
2661
+ result = nextResult;
2662
+ }
2663
+ return result;
2664
+ }
2738
2665
  function buildHalfEdgeStructure(segments) {
2739
2666
  const vertices = [];
2740
2667
  function findOrCreateVertex(x, y) {
@@ -2898,6 +2825,7 @@ function validateGeometry(dir) {
2898
2825
  function validateLineConnectivity(levelDir) {
2899
2826
  const warnings = [];
2900
2827
  const endpoints = [];
2828
+ const segments = [];
2901
2829
  for (const table of BOUNDARY_TABLES2) {
2902
2830
  const svgPath = join7(levelDir.path, `${table}.svg`);
2903
2831
  if (!existsSync6(svgPath)) continue;
@@ -2908,37 +2836,55 @@ function validateLineConnectivity(levelDir) {
2908
2836
  const geo = extractLineGeometry(el);
2909
2837
  endpoints.push({ x: geo.start_x, y: geo.start_y, side: "start", elementId: el.id, table });
2910
2838
  endpoints.push({ x: geo.end_x, y: geo.end_y, side: "end", elementId: el.id, table });
2839
+ 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
2840
  }
2912
2841
  } catch {
2913
2842
  }
2914
2843
  }
2915
2844
  for (const ep of endpoints) {
2916
- const hasNeighbor = endpoints.some(
2845
+ const hasEndpointNeighbor = endpoints.some(
2917
2846
  (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
2847
  );
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
- }
2848
+ if (hasEndpointNeighbor) continue;
2849
+ const hasTJunction = segments.some((seg) => {
2850
+ if (seg.elementId === ep.elementId && seg.table === ep.table) return false;
2851
+ return pointOnSegment(ep.x, ep.y, seg.start_x, seg.start_y, seg.end_x, seg.end_y, TOLERANCE2);
2852
+ });
2853
+ if (hasTJunction) continue;
2854
+ let nearestDist = Infinity;
2855
+ let nearestId = "";
2856
+ let nearestSide = "";
2857
+ for (const other of endpoints) {
2858
+ if (other === ep || other.elementId === ep.elementId && other.table === ep.table) continue;
2859
+ const dx = other.x - ep.x;
2860
+ const dy = other.y - ep.y;
2861
+ const dist2 = Math.sqrt(dx * dx + dy * dy);
2862
+ if (dist2 < nearestDist) {
2863
+ nearestDist = dist2;
2864
+ nearestId = other.elementId;
2865
+ nearestSide = other.side;
2866
+ }
2867
+ }
2868
+ const nearestInfo = nearestDist < Infinity ? ` (nearest: ${nearestId} ${nearestSide}, distance ${nearestDist.toFixed(3)}m)` : "";
2869
+ warnings.push(
2870
+ `[warn] ${levelDir.name}/${ep.table}.svg ${ep.elementId} ${ep.side} (${ep.x.toFixed(3)}, ${ep.y.toFixed(3)}) has no connected line element${nearestInfo}`
2871
+ );
2939
2872
  }
2940
2873
  return warnings;
2941
2874
  }
2875
+ function pointOnSegment(px, py, ax, ay, bx, by, tol) {
2876
+ const dx = bx - ax;
2877
+ const dy = by - ay;
2878
+ const lenSq = dx * dx + dy * dy;
2879
+ if (lenSq < tol * tol) return false;
2880
+ const t = ((px - ax) * dx + (py - ay) * dy) / lenSq;
2881
+ if (t < -tol || t > 1 + tol) return false;
2882
+ const clampedT = Math.max(0, Math.min(1, t));
2883
+ const closestX = ax + clampedT * dx;
2884
+ const closestY = ay + clampedT * dy;
2885
+ const distSq = (px - closestX) * (px - closestX) + (py - closestY) * (py - closestY);
2886
+ return distSq < tol * tol;
2887
+ }
2942
2888
  function validateHostedBounds(levelDir, wallGeometries) {
2943
2889
  const warnings = [];
2944
2890
  for (const tableName of ["door", "window"]) {
@@ -3010,34 +2956,332 @@ function validateHostedOverlap(levelDir) {
3010
2956
  return warnings;
3011
2957
  }
3012
2958
 
2959
+ // src/build/resolve-hosted-coords.ts
2960
+ init_svg();
2961
+ init_csv();
2962
+ init_fs();
2963
+ import { existsSync as existsSync7 } from "fs";
2964
+ import { join as join8 } from "path";
2965
+ var TOLERANCE3 = 0.05;
2966
+ var HOSTED_TABLES = ["door", "window", "opening"];
2967
+ function resolveHostedCoords(dir) {
2968
+ const issues = [];
2969
+ const layout = discoverLayout(dir);
2970
+ const allDirs = [
2971
+ { name: "global", path: layout.globalDir },
2972
+ ...layout.levelDirs
2973
+ ];
2974
+ for (const d of allDirs) {
2975
+ if (!existsSync7(d.path)) continue;
2976
+ const files = listFiles(d.path);
2977
+ const walls = [];
2978
+ for (const table of ["wall", "structure_wall", "curtain_wall"]) {
2979
+ const svgPath = join8(d.path, `${table}.svg`);
2980
+ if (!existsSync7(svgPath)) continue;
2981
+ try {
2982
+ const svg = parseSvgFile(svgPath);
2983
+ for (const el of svg.elements) {
2984
+ if (el.tag !== "path") continue;
2985
+ const geo = extractLineGeometry(el);
2986
+ walls.push({
2987
+ id: el.id,
2988
+ start_x: geo.start_x,
2989
+ start_y: geo.start_y,
2990
+ end_x: geo.end_x,
2991
+ end_y: geo.end_y,
2992
+ length: geo.length
2993
+ });
2994
+ }
2995
+ } catch {
2996
+ }
2997
+ }
2998
+ if (walls.length === 0) continue;
2999
+ for (const table of HOSTED_TABLES) {
3000
+ const csvPath = join8(d.path, `${table}.csv`);
3001
+ if (!files.includes(`${table}.csv`)) continue;
3002
+ const csv = readCsv(csvPath);
3003
+ const hasHostX = csv.headers.includes("host_x");
3004
+ const hasHostY = csv.headers.includes("host_y");
3005
+ if (!hasHostX || !hasHostY) continue;
3006
+ let modified = false;
3007
+ for (let i = 0; i < csv.rows.length; i++) {
3008
+ const row = csv.rows[i];
3009
+ const hostX = parseFloat(row.host_x ?? "");
3010
+ const hostY = parseFloat(row.host_y ?? "");
3011
+ if (isNaN(hostX) || isNaN(hostY)) continue;
3012
+ const existingPosition = parseFloat(row.position ?? "");
3013
+ if (!isNaN(existingPosition) && row.position !== "") continue;
3014
+ const match = findNearestWall(hostX, hostY, walls, row.host_id);
3015
+ if (!match) {
3016
+ issues.push(
3017
+ `${d.name}/${table}.csv:${i + 2} ${row.id} host_x=${hostX}, host_y=${hostY} \u2014 no wall found within ${TOLERANCE3}m`
3018
+ );
3019
+ continue;
3020
+ }
3021
+ row.position = match.position.toFixed(4);
3022
+ if (!row.host_id || row.host_id === "") {
3023
+ row.host_id = match.wallId;
3024
+ }
3025
+ modified = true;
3026
+ }
3027
+ if (modified) {
3028
+ const cleanHeaders = csv.headers.filter((h) => h !== "host_x" && h !== "host_y");
3029
+ if (!cleanHeaders.includes("host_id")) {
3030
+ const idIdx = cleanHeaders.indexOf("id");
3031
+ cleanHeaders.splice(idIdx + 1, 0, "host_id");
3032
+ }
3033
+ if (!cleanHeaders.includes("position")) {
3034
+ const hostIdx = cleanHeaders.indexOf("host_id");
3035
+ cleanHeaders.splice(hostIdx + 1, 0, "position");
3036
+ }
3037
+ const cleanRows = csv.rows.map((row) => {
3038
+ const clean = {};
3039
+ for (const h of cleanHeaders) {
3040
+ if (row[h] !== void 0) clean[h] = row[h];
3041
+ }
3042
+ return clean;
3043
+ });
3044
+ writeCsv(csvPath, { headers: cleanHeaders, rows: cleanRows });
3045
+ }
3046
+ }
3047
+ }
3048
+ return issues;
3049
+ }
3050
+ function findNearestWall(px, py, walls, preferredHostId) {
3051
+ let bestWallId = "";
3052
+ let bestPosition = 0;
3053
+ let bestDist = Infinity;
3054
+ for (const wall of walls) {
3055
+ const dx = wall.end_x - wall.start_x;
3056
+ const dy = wall.end_y - wall.start_y;
3057
+ const lenSq = dx * dx + dy * dy;
3058
+ if (lenSq < 1e-10) continue;
3059
+ const t = ((px - wall.start_x) * dx + (py - wall.start_y) * dy) / lenSq;
3060
+ const clampedT = Math.max(0, Math.min(1, t));
3061
+ const closestX = wall.start_x + clampedT * dx;
3062
+ const closestY = wall.start_y + clampedT * dy;
3063
+ const dist2 = Math.sqrt((px - closestX) ** 2 + (py - closestY) ** 2);
3064
+ if (preferredHostId && preferredHostId !== "") {
3065
+ if (wall.id === preferredHostId) {
3066
+ return { wallId: wall.id, position: clampedT * wall.length };
3067
+ }
3068
+ continue;
3069
+ }
3070
+ if (dist2 < bestDist) {
3071
+ bestDist = dist2;
3072
+ bestWallId = wall.id;
3073
+ bestPosition = clampedT * wall.length;
3074
+ }
3075
+ }
3076
+ if (bestDist > TOLERANCE3 && !preferredHostId) return null;
3077
+ if (!bestWallId) return null;
3078
+ return { wallId: bestWallId, position: bestPosition };
3079
+ }
3080
+
3081
+ // src/build/snap-endpoints.ts
3082
+ init_svg();
3083
+ init_csv();
3084
+ init_fs();
3085
+ import { existsSync as existsSync8, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
3086
+ import { join as join9 } from "path";
3087
+ var MIN_SNAP_TOLERANCE = 0.1;
3088
+ var BOUNDARY_TABLES3 = ["wall", "structure_wall", "curtain_wall", "room_separator"];
3089
+ var WALL_TABLES_WITH_THICKNESS = ["wall", "structure_wall", "curtain_wall"];
3090
+ function snapEndpoints(dir) {
3091
+ const layout = discoverLayout(dir);
3092
+ const allDirs = [
3093
+ { name: "global", path: layout.globalDir },
3094
+ ...layout.levelDirs
3095
+ ];
3096
+ let totalSnapped = 0;
3097
+ const snapTolerance = computeSnapTolerance(allDirs);
3098
+ const allEndpoints = [];
3099
+ for (const d of allDirs) {
3100
+ if (!existsSync8(d.path)) continue;
3101
+ for (const table of BOUNDARY_TABLES3) {
3102
+ const svgPath = join9(d.path, `${table}.svg`);
3103
+ if (!existsSync8(svgPath)) continue;
3104
+ try {
3105
+ const svg = parseSvgFile(svgPath);
3106
+ for (const el of svg.elements) {
3107
+ if (el.tag !== "path") continue;
3108
+ const geo = extractLineGeometry(el);
3109
+ allEndpoints.push({ point: { x: geo.start_x, y: geo.start_y }, table, elementId: el.id, side: "start", levelDir: d.name, levelPath: d.path });
3110
+ allEndpoints.push({ point: { x: geo.end_x, y: geo.end_y }, table, elementId: el.id, side: "end", levelDir: d.name, levelPath: d.path });
3111
+ }
3112
+ } catch {
3113
+ }
3114
+ }
3115
+ }
3116
+ if (allEndpoints.length === 0) return 0;
3117
+ const clusters = clusterEndpoints(allEndpoints, snapTolerance);
3118
+ const snapMap = /* @__PURE__ */ new Map();
3119
+ for (const cluster of clusters) {
3120
+ if (cluster.length <= 1) continue;
3121
+ const canonical = pickCanonical(cluster);
3122
+ for (const ep of cluster) {
3123
+ const dx = Math.abs(ep.point.x - canonical.x);
3124
+ const dy = Math.abs(ep.point.y - canonical.y);
3125
+ if (dx > 1e-6 || dy > 1e-6) {
3126
+ const key = `${ep.levelPath}:${ep.table}:${ep.elementId}:${ep.side}`;
3127
+ snapMap.set(key, canonical);
3128
+ totalSnapped++;
3129
+ }
3130
+ }
3131
+ }
3132
+ if (snapMap.size === 0) return 0;
3133
+ for (const d of allDirs) {
3134
+ if (!existsSync8(d.path)) continue;
3135
+ for (const table of BOUNDARY_TABLES3) {
3136
+ const svgPath = join9(d.path, `${table}.svg`);
3137
+ if (!existsSync8(svgPath)) continue;
3138
+ let svgText = readFileSync5(svgPath, "utf-8");
3139
+ let modified = false;
3140
+ try {
3141
+ const svg = parseSvgFile(svgPath);
3142
+ for (const el of svg.elements) {
3143
+ if (el.tag !== "path") continue;
3144
+ const geo = extractLineGeometry(el);
3145
+ const startKey = `${d.path}:${table}:${el.id}:start`;
3146
+ const endKey = `${d.path}:${table}:${el.id}:end`;
3147
+ const newStart = snapMap.get(startKey);
3148
+ const newEnd = snapMap.get(endKey);
3149
+ if (!newStart && !newEnd) continue;
3150
+ const sx = newStart?.x ?? geo.start_x;
3151
+ const sy = newStart?.y ?? geo.start_y;
3152
+ const ex = newEnd?.x ?? geo.end_x;
3153
+ const ey = newEnd?.y ?? geo.end_y;
3154
+ const oldD = el.attrs.d;
3155
+ const newD = `M ${fmtNum(sx)} ${fmtNum(sy)} L ${fmtNum(ex)} ${fmtNum(ey)}`;
3156
+ if (oldD && oldD !== newD) {
3157
+ svgText = replacePathD(svgText, el.id, oldD, newD);
3158
+ modified = true;
3159
+ }
3160
+ }
3161
+ } catch {
3162
+ continue;
3163
+ }
3164
+ if (modified) {
3165
+ writeFileSync3(svgPath, svgText, "utf-8");
3166
+ }
3167
+ }
3168
+ }
3169
+ return totalSnapped;
3170
+ }
3171
+ function computeSnapTolerance(dirs) {
3172
+ let maxThickness = 0;
3173
+ for (const d of dirs) {
3174
+ if (!existsSync8(d.path)) continue;
3175
+ for (const table of WALL_TABLES_WITH_THICKNESS) {
3176
+ const csvPath = join9(d.path, `${table}.csv`);
3177
+ if (!existsSync8(csvPath)) continue;
3178
+ try {
3179
+ const csv = readCsv(csvPath);
3180
+ for (const row of csv.rows) {
3181
+ const t = parseFloat(row.thickness ?? "0");
3182
+ if (t > maxThickness) maxThickness = t;
3183
+ }
3184
+ } catch {
3185
+ }
3186
+ }
3187
+ }
3188
+ const tolerance = Math.max(MIN_SNAP_TOLERANCE, maxThickness);
3189
+ return tolerance;
3190
+ }
3191
+ function clusterEndpoints(endpoints, tolerance) {
3192
+ const visited = /* @__PURE__ */ new Set();
3193
+ const clusters = [];
3194
+ for (let i = 0; i < endpoints.length; i++) {
3195
+ if (visited.has(i)) continue;
3196
+ const cluster = [endpoints[i]];
3197
+ visited.add(i);
3198
+ let expanded = true;
3199
+ while (expanded) {
3200
+ expanded = false;
3201
+ for (let j = 0; j < endpoints.length; j++) {
3202
+ if (visited.has(j)) continue;
3203
+ for (const member of cluster) {
3204
+ if (dist(member.point, endpoints[j].point) < tolerance) {
3205
+ cluster.push(endpoints[j]);
3206
+ visited.add(j);
3207
+ expanded = true;
3208
+ break;
3209
+ }
3210
+ }
3211
+ }
3212
+ }
3213
+ clusters.push(cluster);
3214
+ }
3215
+ return clusters;
3216
+ }
3217
+ function pickCanonical(cluster) {
3218
+ const counts = /* @__PURE__ */ new Map();
3219
+ for (const ep of cluster) {
3220
+ const key = `${fmtNum(ep.point.x)},${fmtNum(ep.point.y)}`;
3221
+ const entry = counts.get(key);
3222
+ if (entry) {
3223
+ entry.count++;
3224
+ } else {
3225
+ counts.set(key, { point: ep.point, count: 1 });
3226
+ }
3227
+ }
3228
+ let best = { point: cluster[0].point, count: 0 };
3229
+ for (const entry of counts.values()) {
3230
+ if (entry.count > best.count) best = entry;
3231
+ }
3232
+ return best.point;
3233
+ }
3234
+ function dist(a, b) {
3235
+ return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
3236
+ }
3237
+ function fmtNum(n) {
3238
+ const s = n.toFixed(4);
3239
+ return s.replace(/\.?0+$/, "") || "0";
3240
+ }
3241
+ function replacePathD(svgText, id, oldD, newD) {
3242
+ const escaped = oldD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3243
+ const idEscaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3244
+ const pathRegex = new RegExp(`(<path[^>]*\\bid="${idEscaped}"[^>]*\\bd=")${escaped}(")`);
3245
+ if (pathRegex.test(svgText)) {
3246
+ return svgText.replace(pathRegex, `$1${newD}$2`);
3247
+ }
3248
+ const pathRegex2 = new RegExp(`(<path[^>]*\\bd=")${escaped}("[^>]*\\bid="${idEscaped}")`);
3249
+ if (pathRegex2.test(svgText)) {
3250
+ return svgText.replace(pathRegex2, `$1${newD}$2`);
3251
+ }
3252
+ return svgText;
3253
+ }
3254
+
3013
3255
  // src/build/index.ts
3014
3256
  function build(dir) {
3015
- const issues = validate(dir);
3257
+ const snapped = snapEndpoints(dir);
3258
+ const resolveIssues = resolveHostedCoords(dir);
3259
+ const issues = [...resolveIssues, ...validate(dir)];
3016
3260
  const warnings = validateGeometry(dir);
3017
3261
  const artifacts = [];
3018
3262
  const layout = discoverLayout(dir);
3019
3263
  for (const levelDir of layout.levelDirs) {
3020
- const spaceCsvPath = join8(levelDir.path, "space.csv");
3021
- if (!existsSync7(spaceCsvPath)) continue;
3022
- const result = computeSpaceBoundaries(levelDir);
3264
+ const spaceCsvPath = join10(levelDir.path, "space.csv");
3265
+ if (!existsSync9(spaceCsvPath)) continue;
3266
+ const result = computeSpaceBoundaries(levelDir, layout.globalDir);
3023
3267
  warnings.push(...result.warnings);
3024
3268
  if (result.svgWritten) {
3025
3269
  artifacts.push(`${levelDir.name}/space.svg`);
3026
3270
  }
3027
3271
  }
3028
- return { issues, warnings, artifacts };
3272
+ return { issues, warnings, artifacts, snappedEndpoints: snapped };
3029
3273
  }
3030
3274
 
3031
3275
  // src/index.ts
3032
3276
  init_registry();
3033
3277
  init_fs();
3034
3278
  init_csv();
3035
- import { existsSync as existsSync17, writeFileSync as writeFileSync7 } from "fs";
3036
- import { join as join17 } from "path";
3279
+ import { existsSync as existsSync18, writeFileSync as writeFileSync7 } from "fs";
3280
+ import { join as join18 } from "path";
3037
3281
  var program = new Command();
3038
- program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.2.3" : "0.0.0");
3282
+ program.name("bimdown").description("BimDown CLI \u2014 build, query, and manage BimDown projects").version(true ? "0.4.0" : "0.0.0");
3039
3283
  function runBuild(dir) {
3040
- const absDir = resolve3(dir);
3284
+ const absDir = resolve2(dir);
3041
3285
  const result = build(absDir);
3042
3286
  if (result.issues.length > 0) {
3043
3287
  for (const issue of result.issues) {
@@ -3054,6 +3298,9 @@ ${result.issues.length} issue(s) found.`);
3054
3298
  console.log(`
3055
3299
  ${result.warnings.length} warning(s).`);
3056
3300
  }
3301
+ if (result.snappedEndpoints > 0) {
3302
+ console.log(`Snapped ${result.snappedEndpoints} endpoint(s).`);
3303
+ }
3057
3304
  if (result.artifacts.length > 0) {
3058
3305
  console.log(`
3059
3306
  Generated: ${result.artifacts.join(", ")}`);
@@ -3065,7 +3312,7 @@ Generated: ${result.artifacts.join(", ")}`);
3065
3312
  program.command("build").argument("<dir>", "BimDown project directory").description("Build a BimDown project (validate + compute space boundaries)").action((dir) => runBuild(dir));
3066
3313
  program.command("validate").argument("<dir>", "BimDown project directory").description("Alias for build").action((dir) => runBuild(dir));
3067
3314
  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);
3315
+ const absDir = resolve2(dir);
3069
3316
  const { getConnection: getConnection2, runQuery: runQuery2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3070
3317
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3071
3318
  const conn = await getConnection2();
@@ -3082,7 +3329,7 @@ program.command("query").argument("<dir>", "BimDown project directory").argument
3082
3329
  }
3083
3330
  });
3084
3331
  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);
3332
+ const absDir = resolve2(dir);
3086
3333
  const { getConnection: getConnection2, closeConnection: closeConnection2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
3087
3334
  const { hydrate: hydrate2 } = await Promise.resolve().then(() => (init_hydrate(), hydrate_exports));
3088
3335
  const { dehydrate: dehydrate2 } = await Promise.resolve().then(() => (init_dehydrate(), dehydrate_exports));
@@ -3096,8 +3343,8 @@ program.command("sync").argument("<dir>", "BimDown project directory").descripti
3096
3343
  await closeConnection2();
3097
3344
  }
3098
3345
  });
3099
- 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);
3346
+ 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). Color legend: walls=dark navy, structural walls=slate, columns=dark filled, slabs=light grey translucent, spaces=blue translucent, stairs=orange, beams=purple. DOORS render as BOLD RED (#e63946) lines and WINDOWS as BOLD TEAL (#2a9d8f) lines cutting across their host walls. MEP: ducts=cyan, pipes=light blue, cable tray=green, conduit=teal, equipment=red fill, terminals=orange fill.").action(async (dir, opts) => {
3347
+ const absDir = resolve2(dir);
3101
3348
  const { renderLevel: renderLevel2 } = await Promise.resolve().then(() => (init_render(), render_exports));
3102
3349
  try {
3103
3350
  const svg = renderLevel2(absDir, opts.level);
@@ -3115,11 +3362,11 @@ program.command("render").argument("<dir>", "BimDown project directory").option(
3115
3362
  }
3116
3363
  });
3117
3364
  program.command("info").argument("<dir>", "BimDown project directory").description("Print project summary").action((dir) => {
3118
- const absDir = resolve3(dir);
3365
+ const absDir = resolve2(dir);
3119
3366
  const registry = buildRegistry(getSpecDir());
3120
3367
  const layout = discoverLayout(absDir);
3121
- const levelCsv = join17(layout.globalDir, "level.csv");
3122
- if (existsSync17(levelCsv)) {
3368
+ const levelCsv = join18(layout.globalDir, "level.csv");
3369
+ if (existsSync18(levelCsv)) {
3123
3370
  const levels = readCsv(levelCsv);
3124
3371
  console.log("Levels:");
3125
3372
  for (const row of levels.rows) {
@@ -3133,14 +3380,14 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
3133
3380
  ];
3134
3381
  const totals = {};
3135
3382
  for (const d of allDirs) {
3136
- if (!existsSync17(d.path)) continue;
3383
+ if (!existsSync18(d.path)) continue;
3137
3384
  const files = listFiles(d.path);
3138
3385
  const counts = [];
3139
3386
  for (const f of files) {
3140
3387
  if (!f.endsWith(".csv")) continue;
3141
3388
  const tableName = f.replace(".csv", "");
3142
3389
  if (!registry.has(tableName)) continue;
3143
- const data = readCsv(join17(d.path, f));
3390
+ const data = readCsv(join18(d.path, f));
3144
3391
  counts.push(`${tableName}: ${data.rows.length}`);
3145
3392
  totals[tableName] = (totals[tableName] ?? 0) + data.rows.length;
3146
3393
  }
@@ -3158,7 +3405,7 @@ program.command("info").argument("<dir>", "BimDown project directory").descripti
3158
3405
  console.log(` TOTAL: ${grand}`);
3159
3406
  });
3160
3407
  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);
3408
+ const absDir = resolve2(dir);
3162
3409
  const { resolveTopology: resolveTopology2 } = await Promise.resolve().then(() => (init_resolve_topology(), resolve_topology_exports));
3163
3410
  resolveTopology2(absDir);
3164
3411
  });
@@ -3168,8 +3415,8 @@ program.command("merge").argument("<dirs...>", "Two or more BimDown project dire
3168
3415
  process.exitCode = 1;
3169
3416
  return;
3170
3417
  }
3171
- const absDirs = dirs.map((d) => resolve3(d));
3172
- const absOut = resolve3(opts.output);
3418
+ const absDirs = dirs.map((d) => resolve2(d));
3419
+ const absOut = resolve2(opts.output);
3173
3420
  const { merge: merge2 } = await Promise.resolve().then(() => (init_merge(), merge_exports));
3174
3421
  await merge2(absDirs, absOut);
3175
3422
  });
@@ -3206,13 +3453,13 @@ program.command("schema").argument("[table]", "Table name (omit for all tables)"
3206
3453
  }
3207
3454
  });
3208
3455
  program.command("init").argument("<dir>", "BimDown project directory").description("Initialize a new BimDown project structure").action(async (dir) => {
3209
- const absDir = resolve3(dir);
3456
+ const absDir = resolve2(dir);
3210
3457
  const { initProject: initProject2 } = await Promise.resolve().then(() => (init_init(), init_exports));
3211
3458
  initProject2(absDir);
3212
3459
  });
3213
3460
  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);
3461
+ const absA = resolve2(dirA);
3462
+ const absB = resolve2(dirB);
3216
3463
  const { diffProjects: diffProjects2 } = await Promise.resolve().then(() => (init_diff(), diff_exports));
3217
3464
  diffProjects2(absA, absB);
3218
3465
  });
@@ -3220,10 +3467,6 @@ program.command("publish").argument("<dir>", "BimDown project directory").option
3220
3467
  const { publish: publish2 } = await Promise.resolve().then(() => (init_publish(), publish_exports));
3221
3468
  await publish2(dir, opts);
3222
3469
  });
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
3470
  program.parse();
3228
3471
  function printTable(columns, rows) {
3229
3472
  if (rows.length === 0) {
@@ -3256,4 +3499,4 @@ function jsonReplacer(_key, value) {
3256
3499
  if (typeof value === "bigint") return Number(value);
3257
3500
  return value;
3258
3501
  }
3259
- //# sourceMappingURL=index.js.map
3502
+ //# sourceMappingURL=cli.js.map