@7365admin1/core 3.111.0 → 3.112.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
@@ -347,6 +347,7 @@ __export(src_exports, {
347
347
  attendanceSchema: () => attendanceSchema,
348
348
  attendanceSettingsSchema: () => attendanceSettingsSchema,
349
349
  buildSelfServiceEmailContext: () => buildSelfServiceEmailContext,
350
+ buildingFileImportSchema: () => buildingFileImportSchema,
350
351
  buildingFromRmf: () => buildingFromRmf,
351
352
  buildingInPlanFrame: () => buildingInPlanFrame,
352
353
  buildingMapBodySchema: () => buildingMapBodySchema,
@@ -600,6 +601,7 @@ __export(src_exports, {
600
601
  resolveInviteActor: () => resolveInviteActor,
601
602
  resolveSiteTimezone: () => resolveSiteTimezone,
602
603
  resolveStaffRole: () => resolveStaffRole,
604
+ rmfBuilding: () => rmf_building_util_exports,
603
605
  rmfBuildingSchema: () => rmfBuildingSchema,
604
606
  robotActionsFor: () => robotActionsFor,
605
607
  robotBrandFor: () => robotBrandFor,
@@ -10772,12 +10774,12 @@ function planFaultChanges(open, reading) {
10772
10774
  return { open: toOpen, clear };
10773
10775
  }
10774
10776
  function robotFaultSweepConfig(env2 = process.env) {
10775
- const num = (v, def, min, max) => {
10777
+ const num2 = (v, def, min, max) => {
10776
10778
  const n = Math.floor(Number(v));
10777
10779
  return Number.isFinite(n) && String(v ?? "").trim() !== "" ? Math.min(max, Math.max(min, n)) : def;
10778
10780
  };
10779
10781
  const enabled = String(env2.ROBOT_FAULT_SWEEP ?? "on").trim().toLowerCase() !== "off";
10780
- const asked = num(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
10782
+ const asked = num2(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
10781
10783
  const pick = (steps, v) => steps.filter((d) => d <= v).pop() ?? steps[0];
10782
10784
  const subMinute = asked < 60;
10783
10785
  const step = subMinute ? pick([10, 12, 15, 20, 30], asked) : pick([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60], Math.floor(asked / 60));
@@ -10787,9 +10789,9 @@ function robotFaultSweepConfig(env2 = process.env) {
10787
10789
  enabled,
10788
10790
  seconds,
10789
10791
  cron: cron2,
10790
- concurrency: num(env2.ROBOT_FAULT_SWEEP_CONCURRENCY, 4, 1, 16),
10791
- timeoutMs: num(env2.ROBOT_FAULT_SWEEP_TIMEOUT_MS, 1e4, 1e3, 6e4),
10792
- offlineAlertMinutes: num(env2.ROBOT_OFFLINE_ALERT_MINUTES, 10, 1, 1440)
10792
+ concurrency: num2(env2.ROBOT_FAULT_SWEEP_CONCURRENCY, 4, 1, 16),
10793
+ timeoutMs: num2(env2.ROBOT_FAULT_SWEEP_TIMEOUT_MS, 1e4, 1e3, 6e4),
10794
+ offlineAlertMinutes: num2(env2.ROBOT_OFFLINE_ALERT_MINUTES, 10, 1, 1440)
10793
10795
  };
10794
10796
  }
10795
10797
  function withTimeout(promise, ms, label2 = "Timed out") {
@@ -55490,8 +55492,8 @@ function encryptPayload(payloadHex) {
55490
55492
  );
55491
55493
  return encrypted.toString("base64");
55492
55494
  }
55493
- function toHex(num, length) {
55494
- return num.toString(16).padStart(length * 2, "0");
55495
+ function toHex(num2, length) {
55496
+ return num2.toString(16).padStart(length * 2, "0");
55495
55497
  }
55496
55498
  function buildPayload(cardNumber, validityMinutes) {
55497
55499
  const randomHex = import_crypto5.default.randomBytes(2).toString("hex");
@@ -55671,8 +55673,8 @@ function UseAccessManagementRepo() {
55671
55673
  }
55672
55674
  }
55673
55675
  function generateCardNo() {
55674
- const num = Math.floor(Math.random() * 65536);
55675
- return num.toString().padStart(10, "0");
55676
+ const num2 = Math.floor(Math.random() * 65536);
55677
+ return num2.toString().padStart(10, "0");
55676
55678
  }
55677
55679
  async function createQrData({
55678
55680
  cardNumber,
@@ -56912,13 +56914,13 @@ function UseAccessManagementRepo() {
56912
56914
  const prevCard = res && res?.[1]?.cardNo || "-1";
56913
56915
  const currentCard = res && res?.[0]?.cardNo || "0";
56914
56916
  let availableCardNo = [];
56915
- let num = parseInt(prevCard, 10) + 1;
56917
+ let num2 = parseInt(prevCard, 10) + 1;
56916
56918
  while (availableCardNo.length < (unit.length > 0 ? unit.length : quantity)) {
56917
- if (num === parseInt(currentCard, 10)) {
56918
- num++;
56919
+ if (num2 === parseInt(currentCard, 10)) {
56920
+ num2++;
56919
56921
  }
56920
- availableCardNo.push(num);
56921
- num++;
56922
+ availableCardNo.push(num2);
56923
+ num2++;
56922
56924
  }
56923
56925
  const cardNumbers = availableCardNo.map(
56924
56926
  (no2) => no2.toString().padStart(10, "0")
@@ -62475,13 +62477,13 @@ function parseRobotCommand(body) {
62475
62477
  if (has2(k))
62476
62478
  return { ok: false, message: `${k} is not valid for a ${kind} command.` };
62477
62479
  }
62478
- const num = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
62479
- if (!num("x") || !num("y"))
62480
+ const num2 = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
62481
+ if (!num2("x") || !num2("y"))
62480
62482
  return { ok: false, message: `${kind} needs x and y (metres).` };
62481
62483
  if (kind === "navigate") {
62482
62484
  if (has2("floorNo"))
62483
62485
  return { ok: false, message: "floorNo is not valid for a navigate command." };
62484
- if (has2("theta") && !num("theta"))
62486
+ if (has2("theta") && !num2("theta"))
62485
62487
  return { ok: false, message: "theta must be a number (radians)." };
62486
62488
  return {
62487
62489
  ok: true,
@@ -62493,7 +62495,7 @@ function parseRobotCommand(body) {
62493
62495
  }
62494
62496
  };
62495
62497
  }
62496
- if (!num("theta"))
62498
+ if (!num2("theta"))
62497
62499
  return { ok: false, message: "relocalize needs theta (radians)." };
62498
62500
  if (!Number.isInteger(b.floorNo))
62499
62501
  return { ok: false, message: "relocalize needs an integer floorNo." };
@@ -63871,7 +63873,25 @@ function buildingInPlanFrame(building) {
63871
63873
  const b = v2 && toPlan2(levels[i].name, v2.x, v2.y);
63872
63874
  return a && b ? [{ start: a, end: b }] : [];
63873
63875
  });
63874
- return { ...lv, walls };
63876
+ const lanes = [];
63877
+ const waypoints = [];
63878
+ for (const graph of levels[i].nav_graphs ?? []) {
63879
+ const pts = (graph.vertices ?? []).map((v) => toPlan2(levels[i].name, v.x, v.y));
63880
+ for (const e of (graph.edges ?? []).slice(0, 5e3)) {
63881
+ const a = pts[e.v1_idx];
63882
+ const b = pts[e.v2_idx];
63883
+ if (a && b && lanes.length < 5e3)
63884
+ lanes.push({ start: a, end: b, oneWay: (e.edge_type ?? 0) !== 0, graph: String(graph.name) });
63885
+ }
63886
+ (graph.vertices ?? []).forEach((v, k) => {
63887
+ const at2 = pts[k];
63888
+ const flags = new Set((v.params ?? []).map((p) => p.name));
63889
+ if (at2 && v.name && waypoints.length < 2e3) {
63890
+ waypoints.push({ ...at2, name: String(v.name).slice(0, 60), charger: flags.has("is_charger"), holding: flags.has("is_holding_point"), parking: flags.has("is_parking_spot") });
63891
+ }
63892
+ });
63893
+ }
63894
+ return { ...lv, walls, lanes, waypoints };
63875
63895
  }),
63876
63896
  doors,
63877
63897
  lifts
@@ -64531,11 +64551,11 @@ function decodeTrackingFrame(data) {
64531
64551
  if (!parsed || typeof parsed !== "object")
64532
64552
  return null;
64533
64553
  const frame2 = parsed;
64534
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
64535
- const x = num(frame2.x);
64536
- const y = num(frame2.y);
64537
- const theta = num(frame2.theta);
64538
- const statusFlag = num(frame2.status);
64554
+ const num2 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
64555
+ const x = num2(frame2.x);
64556
+ const y = num2(frame2.y);
64557
+ const theta = num2(frame2.theta);
64558
+ const statusFlag = num2(frame2.status);
64539
64559
  if (x === null || y === null || theta === null || statusFlag === null) {
64540
64560
  return null;
64541
64561
  }
@@ -64786,230 +64806,1304 @@ function buildingMapFromRobotMaps(name, maps, floorHeightM = 3) {
64786
64806
  return { name, levels, lifts: [] };
64787
64807
  }
64788
64808
 
64789
- // src/services/robot-tracking.service.ts
64790
- var import_axios4 = __toESM(require("axios"));
64791
- async function openWithAxios(url, body) {
64792
- const response = await import_axios4.default.post(url, body, {
64793
- responseType: "stream",
64794
- // No read timeout: this connection is SUPPOSED to stay open and mostly
64795
- // silent. A request timeout here would sever a healthy stream on a quiet
64796
- // robot. The idle watchdog is what decides a stream is dead, because it can
64797
- // tell silence from a closed socket.
64798
- timeout: 0,
64799
- headers: { "Content-Type": "application/json", Accept: "text/event-stream" }
64800
- });
64801
- return response.data;
64809
+ // src/utils/rmf-building.util.ts
64810
+ var rmf_building_util_exports = {};
64811
+ __export(rmf_building_util_exports, {
64812
+ DEFAULT_PLAN_FRAME: () => DEFAULT_PLAN_FRAME,
64813
+ LIFT_DOOR_TYPE_INT: () => LIFT_DOOR_TYPE_INT,
64814
+ PLAN_H_M: () => PLAN_H_M2,
64815
+ PLAN_W_M: () => PLAN_W_M2,
64816
+ RmfImportError: () => RmfImportError,
64817
+ applyXform: () => applyXform,
64818
+ buildingFrame: () => buildingFrame,
64819
+ emptyRmf: () => emptyRmf,
64820
+ fiducialTransform: () => fiducialTransform,
64821
+ floorLabel: () => floorLabel,
64822
+ floorNoFromName: () => floorNoFromName,
64823
+ fromBuildingYaml: () => fromBuildingYaml,
64824
+ fromNavGraph: () => fromNavGraph,
64825
+ fromPlan: () => fromPlan,
64826
+ legacyFromRmf: () => legacyFromRmf,
64827
+ liftShaft: () => liftShaft,
64828
+ mergeLegacyIntoRmf: () => mergeLegacyIntoRmf,
64829
+ rmfFromFleetCore: () => rmfFromFleetCore,
64830
+ rmfProblem: () => rmfProblem,
64831
+ rmfSummary: () => rmfSummary,
64832
+ toBuildingYaml: () => toBuildingYaml,
64833
+ toNavGraphs: () => toNavGraphs,
64834
+ toPlan: () => toPlan
64835
+ });
64836
+ var LIFT_DOOR_TYPE_INT = { sliding: 1, double_sliding: 2, telescope: 3, double_telescope: 4 };
64837
+ var PLAN_W_M2 = 40;
64838
+ var PLAN_H_M2 = 26;
64839
+ var DEFAULT_PLAN_FRAME = { minX: 0, maxX: PLAN_W_M2, minY: -PLAN_H_M2, maxY: 0 };
64840
+ var WELD_M = 0.01;
64841
+ var r3 = (v) => Math.round(v * 1e3) / 1e3;
64842
+ var clamp2 = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
64843
+ function floorLabel(floorNo2) {
64844
+ return floorNo2 < 0 ? `B${-floorNo2}` : floorNo2 === 0 ? "G" : `L${floorNo2}`;
64802
64845
  }
64803
- function startRobotTracking(options) {
64804
- const {
64805
- credentials,
64806
- robotSn,
64807
- onEvent,
64808
- baseUrl = ROBOT_CLOUD_BASE_URL,
64809
- idleTimeoutMs = TRACKING_IDLE_TIMEOUT_MS,
64810
- openStream = openWithAxios,
64811
- now = Date.now
64812
- } = options;
64813
- if (!baseUrl)
64814
- throw new Error("Robot cloud: ROBOT_CLOUD_BASE_URL is not configured.");
64815
- let stopped = false;
64816
- let attempt = 0;
64817
- let current = null;
64818
- let watchdog = null;
64819
- let retry = null;
64820
- let lastActivityAt = now();
64821
- let everConnected = false;
64822
- const parser = createSseParser();
64823
- function clearTimers() {
64824
- if (watchdog) {
64825
- clearInterval(watchdog);
64826
- watchdog = null;
64827
- }
64828
- if (retry) {
64829
- clearTimeout(retry);
64830
- retry = null;
64831
- }
64832
- }
64833
- function dropUpstream() {
64834
- if (!current)
64835
- return;
64836
- try {
64837
- current.destroy();
64838
- } catch {
64846
+ function floorNoFromName(name) {
64847
+ if (typeof name !== "string")
64848
+ return null;
64849
+ const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
64850
+ if (m)
64851
+ return m[1].toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
64852
+ return /^G$/i.test(name.trim()) ? 0 : null;
64853
+ }
64854
+ function toPlan(f, p) {
64855
+ const w = f.maxX - f.minX || 1;
64856
+ const h = f.maxY - f.minY || 1;
64857
+ return { x: r3((p.x - f.minX) / w * PLAN_W_M2), y: r3((f.maxY - p.y) / h * PLAN_H_M2) };
64858
+ }
64859
+ function fromPlan(f, p) {
64860
+ return { x: r3(f.minX + p.x / PLAN_W_M2 * (f.maxX - f.minX)), y: r3(f.maxY - p.y / PLAN_H_M2 * (f.maxY - f.minY)) };
64861
+ }
64862
+ function vertexPool(level2) {
64863
+ let next = level2.vertices.reduce((n, v) => Math.max(n, Number(/^v(\d+)$/.exec(v.id)?.[1] ?? 0)), 0) + 1;
64864
+ const byId = new Map(level2.vertices.map((v) => [v.id, v]));
64865
+ function at2(p, extra) {
64866
+ const x = r3(p.x);
64867
+ const y = r3(p.y);
64868
+ const hit = level2.vertices.find((v2) => Math.abs(v2.x - x) < WELD_M && Math.abs(v2.y - y) < WELD_M);
64869
+ if (hit) {
64870
+ if (extra?.name && !hit.name)
64871
+ hit.name = extra.name;
64872
+ if (extra?.params && Object.keys(extra.params).length)
64873
+ hit.params = { ...hit.params ?? {}, ...extra.params };
64874
+ return hit.id;
64839
64875
  }
64840
- current = null;
64876
+ const v = { id: `v${next++}`, x, y, ...extra?.name ? { name: extra.name } : {}, ...extra?.params && Object.keys(extra.params).length ? { params: extra.params } : {} };
64877
+ level2.vertices.push(v);
64878
+ byId.set(v.id, v);
64879
+ return v.id;
64841
64880
  }
64842
- function lose(reason) {
64843
- if (stopped)
64844
- return;
64845
- onEvent({ type: "lost", reason, at: now() });
64846
- dropUpstream();
64847
- scheduleReconnect();
64881
+ return { at: at2, get: (id) => byId.get(id) };
64882
+ }
64883
+ function emptyLevel(name, floorNo2, elevationM, planFrame) {
64884
+ return { name, floorNo: floorNo2, elevationM, planFrame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [] };
64885
+ }
64886
+ function emptyRmf(source = "editor") {
64887
+ return { formatVersion: 1, coordinateSystem: "cartesian_meters", source, graphs: [], levels: [], lifts: [] };
64888
+ }
64889
+ var collapseDoor = (t) => t === "sliding" || t === "double_sliding" ? "sliding" : "hinged";
64890
+ function pruneVertices(level2) {
64891
+ const used = /* @__PURE__ */ new Set();
64892
+ const add = (...ids2) => ids2.forEach((i) => used.add(i));
64893
+ level2.walls.forEach((e) => add(e.v1, e.v2));
64894
+ level2.doors.forEach((e) => add(e.v1, e.v2));
64895
+ level2.lanes.forEach((e) => add(e.v1, e.v2));
64896
+ level2.measurements.forEach((e) => add(e.v1, e.v2));
64897
+ [...level2.floors, ...level2.holes, ...level2.zones].forEach((p) => add(...p.vertices));
64898
+ level2.vertices = level2.vertices.filter((v) => used.has(v.id) || v.name || v.params && Object.keys(v.params).length);
64899
+ }
64900
+ function msgParams(params) {
64901
+ const out = {};
64902
+ for (const p of params ?? []) {
64903
+ if (!p?.name)
64904
+ continue;
64905
+ out[p.name] = p.type === 1 ? String(p.value_string ?? "") : p.type === 2 ? Number(p.value_int ?? 0) : p.type === 3 ? Number(p.value_float ?? 0) : p.type === 4 ? Boolean(p.value_bool) : true;
64848
64906
  }
64849
- function scheduleReconnect() {
64850
- if (stopped)
64851
- return;
64852
- clearTimers();
64853
- const delay2 = trackingBackoffMs(attempt++);
64854
- retry = setTimeout(connect2, delay2);
64907
+ return out;
64908
+ }
64909
+ var VERTEX_PARAM_KEYS = [
64910
+ "is_charger",
64911
+ "is_parking_spot",
64912
+ "is_holding_point",
64913
+ "is_passthrough_point",
64914
+ "is_cleaning_zone",
64915
+ "dock_name",
64916
+ "spawn_robot_name",
64917
+ "spawn_robot_type",
64918
+ "lift_cabin",
64919
+ "merge_radius",
64920
+ "mutex",
64921
+ "pickup_dispenser",
64922
+ "dropoff_ingestor",
64923
+ "human_goal_set_name"
64924
+ ];
64925
+ function vertexParams(raw) {
64926
+ const out = {};
64927
+ for (const k of VERTEX_PARAM_KEYS) {
64928
+ const v = raw[k];
64929
+ if (v === void 0 || v === "" || v === false)
64930
+ continue;
64931
+ out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? Number(v) : String(v).slice(0, 60);
64855
64932
  }
64856
- async function connect2() {
64857
- if (stopped)
64858
- return;
64859
- const body = robotCloudBody(
64860
- credentials.appid,
64861
- credentials.secret,
64862
- ROBOT_CLOUD_PATHS.tracking,
64863
- { robotSn }
64864
- );
64865
- let stream;
64866
- try {
64867
- stream = await openStream(
64868
- `${baseUrl.replace(/\/+$/, "")}${ROBOT_CLOUD_PATHS.tracking}`,
64869
- body
64870
- );
64871
- } catch (error) {
64872
- lose(error?.message ?? "Could not open the robot's tracking stream.");
64873
- return;
64933
+ return out;
64934
+ }
64935
+ var MSG_LIFT_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "telescope", 4: "double_telescope" };
64936
+ var MSG_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "sliding", 4: "double_sliding", 5: "hinged", 6: "double_hinged" };
64937
+ function importFrame(level2) {
64938
+ const xs = [];
64939
+ const ys = [];
64940
+ for (const g of level2.nav_graphs ?? [])
64941
+ for (const v of g.vertices ?? [])
64942
+ xs.push(v.x), ys.push(v.y);
64943
+ for (const d of level2.doors ?? [])
64944
+ xs.push(d.v1_x, d.v2_x), ys.push(d.v1_y, d.v2_y);
64945
+ if (!xs.length)
64946
+ for (const v of level2.wall_graph?.vertices ?? [])
64947
+ xs.push(v.x), ys.push(v.y);
64948
+ if (!xs.length)
64949
+ return { ...DEFAULT_PLAN_FRAME };
64950
+ const pad = 3;
64951
+ return { minX: r3(Math.min(...xs) - pad), maxX: r3(Math.max(...xs) + pad), minY: r3(Math.min(...ys) - pad), maxY: r3(Math.max(...ys) + pad) };
64952
+ }
64953
+ var rot = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
64954
+ function rmfFromFleetCore(msg) {
64955
+ const rmf = emptyRmf("fleet-core");
64956
+ const graphIdx = /* @__PURE__ */ new Map();
64957
+ const usedFloors = /* @__PURE__ */ new Set();
64958
+ for (const [i, lv] of (msg.levels ?? []).slice(0, 200).entries()) {
64959
+ let floorNo2 = floorNoFromName(lv.name) ?? i + 1;
64960
+ while (usedFloors.has(floorNo2))
64961
+ floorNo2++;
64962
+ usedFloors.add(floorNo2);
64963
+ const level2 = emptyLevel(String(lv.name).slice(0, 60), floorNo2, Number(lv.elevation ?? 0), importFrame(lv));
64964
+ const pool = vertexPool(level2);
64965
+ const wg = lv.wall_graph;
64966
+ for (const e of (wg?.edges ?? []).slice(0, 5e3)) {
64967
+ const a = wg.vertices[e.v1_idx];
64968
+ const b = wg.vertices[e.v2_idx];
64969
+ if (a && b)
64970
+ level2.walls.push({ v1: pool.at(a), v2: pool.at(b) });
64874
64971
  }
64875
- if (stopped) {
64876
- try {
64877
- stream.destroy();
64878
- } catch {
64879
- }
64880
- return;
64972
+ for (const d of (lv.doors ?? []).slice(0, 500)) {
64973
+ level2.doors.push({
64974
+ name: String(d.name).slice(0, 60),
64975
+ v1: pool.at({ x: d.v1_x, y: d.v1_y }),
64976
+ v2: pool.at({ x: d.v2_x, y: d.v2_y }),
64977
+ type: MSG_DOOR_TYPE[d.door_type] ?? "hinged",
64978
+ // Kept only where they differ from traffic-editor's defaults (90 degrees, direction 1) - the same as a file import.
64979
+ ...d.motion_range && r3(d.motion_range * 180 / Math.PI) !== 90 ? { motionDegrees: r3(d.motion_range * 180 / Math.PI) } : {},
64980
+ ...d.motion_direction && d.motion_direction < 0 ? { motionDirection: -1 } : {}
64981
+ });
64881
64982
  }
64882
- parser.reset();
64883
- current = stream;
64884
- lastActivityAt = now();
64885
- if (everConnected)
64886
- onEvent({ type: "reconnected", at: now() });
64887
- everConnected = true;
64888
- attempt = 0;
64889
- stream.on("data", (chunk2) => {
64890
- if (stopped)
64891
- return;
64892
- const { events, sawActivity } = parser.push(chunk2.toString("utf8"));
64893
- if (sawActivity)
64894
- lastActivityAt = now();
64895
- for (const event of events) {
64896
- const pose = decodeTrackingFrame(event.data);
64897
- if (pose)
64898
- onEvent({ type: "pose", pose, at: now() });
64983
+ for (const [gi, g] of (lv.nav_graphs ?? []).entries()) {
64984
+ const key = String(g.name ?? gi);
64985
+ if (!graphIdx.has(key)) {
64986
+ const n = Number(key);
64987
+ graphIdx.set(key, Number.isInteger(n) && n >= 0 && n <= 8 ? n : Math.min(8, graphIdx.size));
64988
+ }
64989
+ const idx = graphIdx.get(key);
64990
+ const ids2 = (g.vertices ?? []).map((v) => pool.at(v, { name: v.name ? String(v.name).slice(0, 60) : void 0, params: vertexParams(msgParams(v.params)) }));
64991
+ for (const e of (g.edges ?? []).slice(0, 5e3)) {
64992
+ const a = ids2[e.v1_idx];
64993
+ const b = ids2[e.v2_idx];
64994
+ if (!a || !b || a === b)
64995
+ continue;
64996
+ const p = msgParams(e.params);
64997
+ level2.lanes.push({
64998
+ v1: a,
64999
+ v2: b,
65000
+ graphIdx: idx,
65001
+ bidirectional: (e.edge_type ?? 0) === 0,
65002
+ ...Number(p.speed_limit) > 0 ? { speedLimit: Number(p.speed_limit) } : {},
65003
+ ...p.mutex ? { mutex: String(p.mutex).slice(0, 60) } : {}
65004
+ });
64899
65005
  }
65006
+ }
65007
+ rmf.levels.push(level2);
65008
+ }
65009
+ rmf.graphs = [...new Set(graphIdx.values())].sort((a, b) => a - b).map((idx) => ({ idx, name: `Graph ${idx}`, brands: ["fleet-core"] }));
65010
+ rmf.referenceLevel = rmf.levels[0]?.name;
65011
+ const levelNames = new Set(rmf.levels.map((l) => l.name));
65012
+ for (const l of (msg.lifts ?? []).slice(0, 50)) {
65013
+ const yaw = Number(l.ref_yaw ?? 0);
65014
+ const doors = (l.doors ?? []).slice(0, 8).map((d) => {
65015
+ const a = rot(d.v1_x - l.ref_x, d.v1_y - l.ref_y, -yaw);
65016
+ const b = rot(d.v2_x - l.ref_x, d.v2_y - l.ref_y, -yaw);
65017
+ return {
65018
+ name: String(d.name).slice(0, 60),
65019
+ type: MSG_LIFT_DOOR_TYPE[d.door_type] ?? "sliding",
65020
+ x: r3((a.x + b.x) / 2),
65021
+ y: r3((a.y + b.y) / 2),
65022
+ widthM: r3(Math.hypot(b.x - a.x, b.y - a.y)),
65023
+ axisYawRad: r3(Math.atan2(b.y - a.y, b.x - a.x))
65024
+ };
64900
65025
  });
64901
- stream.on("error", (error) => lose(error?.message ?? "The tracking stream failed."));
64902
- stream.on("end", () => lose("The robot cloud closed the tracking stream."));
64903
- stream.on("close", () => {
64904
- if (!stopped && current === stream)
64905
- lose("The tracking stream closed.");
65026
+ const served = (l.levels ?? []).filter((n) => levelNames.has(n));
65027
+ rmf.lifts.push({
65028
+ name: String(l.name).slice(0, 60),
65029
+ x: r3(l.ref_x),
65030
+ y: r3(l.ref_y),
65031
+ yawRad: r3(yaw),
65032
+ widthM: r3(l.width),
65033
+ depthM: r3(l.depth),
65034
+ referenceFloor: served[0] ?? rmf.referenceLevel ?? "",
65035
+ levelDoors: served.map((level2) => ({ level: level2, doors: doors.map((d) => d.name) })),
65036
+ doors
64906
65037
  });
64907
- clearTimers();
64908
- watchdog = setInterval(() => {
64909
- if (stopped)
64910
- return;
64911
- if (now() - lastActivityAt >= idleTimeoutMs) {
64912
- lose("The robot stopped reporting.");
64913
- }
64914
- }, Math.max(1e3, Math.floor(idleTimeoutMs / 3)));
64915
65038
  }
64916
- void connect2();
64917
- return {
64918
- stop() {
64919
- if (stopped)
64920
- return;
64921
- stopped = true;
64922
- clearTimers();
64923
- dropUpstream();
64924
- }
64925
- };
65039
+ return rmf;
64926
65040
  }
64927
-
64928
- // src/controllers/robot-fleet.controller.ts
64929
- var import_joi76 = __toESM(require("joi"));
64930
- var import_node_server_utils163 = require("@7365admin1/node-server-utils");
64931
-
64932
- // src/services/robot-fault.service.ts
64933
- var import_node_server_utils162 = require("@7365admin1/node-server-utils");
64934
-
64935
- // src/repositories/robot-fault.repo.ts
64936
- var import_mongodb108 = require("mongodb");
64937
- var import_node_server_utils161 = require("@7365admin1/node-server-utils");
64938
- var toId3 = (v) => v instanceof import_mongodb108.ObjectId ? v : new import_mongodb108.ObjectId(String(v));
64939
- function useRobotFaultRepo() {
64940
- const db2 = import_node_server_utils161.useAtlas.getDb();
64941
- if (!db2)
64942
- throw new import_node_server_utils161.InternalServerError("Unable to connect to server.");
64943
- const collection = db2.collection(ROBOT_FAULTS_COLLECTION);
64944
- async function createIndex() {
64945
- try {
64946
- await collection.createIndexes([
64947
- {
64948
- key: { robotId: 1, code: 1 },
64949
- name: "one_open_fault_per_robot_code",
64950
- unique: true,
64951
- partialFilterExpression: { clearedAt: null }
64952
- },
64953
- { key: { clearedAt: 1, since: 1 }, name: "open_faults_by_since" }
64954
- ]);
64955
- } catch (error) {
64956
- throw new import_node_server_utils161.InternalServerError("Failed to create index on robot faults.");
65041
+ function legacyFromRmf(rmf) {
65042
+ const levels = [];
65043
+ const doors = [];
65044
+ for (const lv of rmf.levels) {
65045
+ const v = new Map(lv.vertices.map((x) => [x.id, x]));
65046
+ const p = (id) => {
65047
+ const q = v.get(id);
65048
+ return q ? toPlan(lv.planFrame, q) : null;
65049
+ };
65050
+ const walls = lv.walls.flatMap((w) => {
65051
+ const a = p(w.v1);
65052
+ const b = p(w.v2);
65053
+ return a && b ? [{ start: a, end: b }] : [];
65054
+ });
65055
+ const zones = lv.zones.flatMap((z5) => {
65056
+ const points = z5.vertices.map(p).filter((q) => !!q);
65057
+ return points.length >= 3 ? [{ name: z5.name, points: points.slice(0, 200) }] : [];
65058
+ });
65059
+ levels.push({ floorNo: lv.floorNo, name: lv.name, elevationM: lv.elevationM, walls: walls.slice(0, 2e3), zones: zones.slice(0, 200) });
65060
+ for (const d of lv.doors) {
65061
+ const a = p(d.v1);
65062
+ const b = p(d.v2);
65063
+ if (a && b)
65064
+ doors.push({ name: d.name, floorNo: lv.floorNo, type: collapseDoor(d.type), start: a, end: b });
64957
65065
  }
64958
65066
  }
64959
- async function getOpenFaults() {
64960
- return collection.find({ clearedAt: null }, { projection: { robotId: 1, code: 1, since: 1 } }).toArray();
65067
+ const byName = new Map(rmf.levels.map((l) => [l.name, l]));
65068
+ const lifts = [];
65069
+ for (const l of rmf.lifts) {
65070
+ const withDoors = l.levelDoors.filter((x) => x.doors.length).map((x) => byName.get(x.level)?.floorNo);
65071
+ let floors = [...new Set(withDoors.filter((n) => typeof n === "number"))];
65072
+ if (floors.length < 2)
65073
+ floors = rmf.levels.map((x) => x.floorNo);
65074
+ if (floors.length < 2)
65075
+ continue;
65076
+ const ref = byName.get(l.referenceFloor) ?? rmf.levels[0];
65077
+ if (!ref)
65078
+ continue;
65079
+ const c = toPlan(ref.planFrame, l);
65080
+ const f = ref.planFrame;
65081
+ lifts.push({
65082
+ name: l.name,
65083
+ x: c.x,
65084
+ y: c.y,
65085
+ widthM: r3(clamp2(l.widthM / (f.maxX - f.minX || 1) * PLAN_W_M2, 0.5, 10)),
65086
+ depthM: r3(clamp2(l.depthM / (f.maxY - f.minY || 1) * PLAN_H_M2, 0.5, 10)),
65087
+ floors: floors.sort((a, b) => a - b)
65088
+ });
64961
65089
  }
64962
- async function getOpenFault(robotId, code) {
64963
- return collection.findOne({ robotId: toId3(robotId), code, clearedAt: null });
65090
+ return { levels, doors: doors.slice(0, 500), lifts };
65091
+ }
65092
+ var defaultCabinDoor = (l) => ({
65093
+ name: "door1",
65094
+ type: "double_sliding",
65095
+ x: r3(l.widthM / 2),
65096
+ y: 0,
65097
+ widthM: r3(Math.min(1.2, l.depthM * 0.8)),
65098
+ axisYawRad: r3(Math.PI / 2)
65099
+ });
65100
+ function mergeLegacyIntoRmf(prev, legacy) {
65101
+ const base = prev ? structuredClone(prev) : emptyRmf("editor");
65102
+ const refFrame = base.levels[0]?.planFrame ?? DEFAULT_PLAN_FRAME;
65103
+ const legacyFloors = new Map((legacy.levels ?? []).map((l) => [l.floorNo, l]));
65104
+ const allFloors = /* @__PURE__ */ new Set([
65105
+ ...legacyFloors.keys(),
65106
+ ...(legacy.doors ?? []).map((d) => d.floorNo),
65107
+ ...(legacy.lifts ?? []).flatMap((l) => l.floors)
65108
+ ]);
65109
+ for (const floorNo2 of allFloors) {
65110
+ if (base.levels.some((l) => l.floorNo === floorNo2))
65111
+ continue;
65112
+ base.levels.push(emptyLevel(legacyFloors.get(floorNo2)?.name || floorLabel(floorNo2), floorNo2, legacyFloors.get(floorNo2)?.elevationM ?? 0, { ...refFrame }));
64964
65113
  }
64965
- async function openFault(doc) {
64966
- const now = /* @__PURE__ */ new Date();
64967
- try {
64968
- const res = await collection.insertOne({
64969
- robotId: toId3(doc.robotId),
64970
- orgId: doc.orgId ? toId3(doc.orgId) : null,
64971
- siteId: doc.siteId ? toId3(doc.siteId) : null,
64972
- code: doc.code,
64973
- message: doc.message,
64974
- since: doc.since,
64975
- clearedAt: null,
64976
- notifiedAt: null,
64977
- createdAt: now
65114
+ base.levels.sort((a, b) => a.floorNo - b.floorNo);
65115
+ for (const lv of base.levels) {
65116
+ const src = legacyFloors.get(lv.floorNo);
65117
+ if (src?.name)
65118
+ lv.name = String(src.name).slice(0, 60);
65119
+ if (typeof src?.elevationM === "number")
65120
+ lv.elevationM = src.elevationM;
65121
+ const prevDoors = new Map(lv.doors.map((d) => [d.name, d]));
65122
+ lv.walls = [];
65123
+ lv.zones = [];
65124
+ lv.doors = [];
65125
+ const pool = vertexPool(lv);
65126
+ const at2 = (p) => pool.at(fromPlan(lv.planFrame, p));
65127
+ for (const w of src?.walls ?? [])
65128
+ lv.walls.push({ v1: at2(w.start), v2: at2(w.end) });
65129
+ for (const z5 of src?.zones ?? [])
65130
+ lv.zones.push({ name: z5.name, vertices: z5.points.map(at2) });
65131
+ for (const d of (legacy.doors ?? []).filter((x) => x.floorNo === lv.floorNo)) {
65132
+ const was = prevDoors.get(d.name);
65133
+ const keep = was && collapseDoor(was.type) === d.type;
65134
+ lv.doors.push({
65135
+ ...keep ? was : {},
65136
+ name: d.name,
65137
+ v1: at2(d.start),
65138
+ v2: at2(d.end),
65139
+ type: keep ? was.type : d.type
64978
65140
  });
64979
- return res.insertedId;
64980
- } catch (error) {
64981
- if (error?.code === 11e3)
64982
- return null;
64983
- throw error;
64984
65141
  }
65142
+ pruneVertices(lv);
64985
65143
  }
64986
- async function claimNotify(id) {
64987
- const res = await collection.updateOne(
64988
- { _id: toId3(id), clearedAt: null, notifiedAt: null },
64989
- { $set: { notifiedAt: /* @__PURE__ */ new Date() } }
64990
- );
64991
- return res.modifiedCount === 1;
64992
- }
64993
- async function claimOfflineAlert(id, cutoff) {
64994
- const res = await collection.updateOne(
64995
- { _id: toId3(id), code: "OFFLINE", clearedAt: null, since: { $lte: cutoff }, offlineNotifiedAt: null },
64996
- { $set: { offlineNotifiedAt: /* @__PURE__ */ new Date() } }
64997
- );
64998
- return res.modifiedCount === 1;
64999
- }
65000
- async function claimRecoveryAlert(id) {
65001
- const res = await collection.updateOne(
65002
- { _id: toId3(id), code: "OFFLINE", offlineNotifiedAt: { $ne: null }, recoveryNotifiedAt: null },
65003
- { $set: { recoveryNotifiedAt: /* @__PURE__ */ new Date() } }
65004
- );
65005
- return res.modifiedCount === 1;
65006
- }
65007
- async function findNotifiedOccurrence(robotId, code, since, after) {
65008
- const filter = {
65009
- clearedAt: { $gte: after },
65010
- robotId: toId3(robotId),
65011
- code,
65012
- notifiedAt: { $ne: null }
65144
+ const prevLifts = new Map(base.lifts.map((l) => [l.name, l]));
65145
+ const byFloor = new Map(base.levels.map((l) => [l.floorNo, l]));
65146
+ base.lifts = (legacy.lifts ?? []).map((l) => {
65147
+ const was = prevLifts.get(l.name);
65148
+ const ref = was && base.levels.find((x) => x.name === was.referenceFloor) || byFloor.get(l.floors[0]) || base.levels[0];
65149
+ const f = ref.planFrame;
65150
+ const c = fromPlan(f, l);
65151
+ const widthM = r3(l.widthM / PLAN_W_M2 * (f.maxX - f.minX));
65152
+ const depthM = r3(l.depthM / PLAN_H_M2 * (f.maxY - f.minY));
65153
+ const doors = was?.doors?.length ? was.doors : [defaultCabinDoor({ widthM, depthM })];
65154
+ const served = l.floors.map((n) => byFloor.get(n)?.name).filter((n) => !!n);
65155
+ const prevLevelDoors = new Map((was?.levelDoors ?? []).map((x) => [x.level, x.doors]));
65156
+ return {
65157
+ name: l.name,
65158
+ x: c.x,
65159
+ y: c.y,
65160
+ yawRad: was?.yawRad ?? 0,
65161
+ widthM,
65162
+ depthM,
65163
+ referenceFloor: ref.name,
65164
+ ...was?.initialFloor && served.includes(was.initialFloor) ? { initialFloor: was.initialFloor } : {},
65165
+ doors,
65166
+ levelDoors: served.map((level2) => ({ level: level2, doors: prevLevelDoors.get(level2)?.length ? prevLevelDoors.get(level2) : doors.map((d) => d.name) }))
65167
+ };
65168
+ });
65169
+ base.referenceLevel = base.levels.find((l) => l.name === base.referenceLevel)?.name ?? base.levels[0]?.name;
65170
+ return base;
65171
+ }
65172
+ function rmfProblem(rmf) {
65173
+ const levelNames = /* @__PURE__ */ new Set();
65174
+ const doorNames = /* @__PURE__ */ new Set();
65175
+ const graphIdx = new Set(rmf.graphs.map((g) => g.idx));
65176
+ for (const lv of rmf.levels) {
65177
+ if (levelNames.has(lv.name))
65178
+ return `Two floors are both called "${lv.name}".`;
65179
+ levelNames.add(lv.name);
65180
+ const f = lv.planFrame;
65181
+ if (!(f.maxX > f.minX && f.maxY > f.minY))
65182
+ return `Floor ${lv.name}: its plan frame is empty.`;
65183
+ const ids2 = /* @__PURE__ */ new Set();
65184
+ for (const v of lv.vertices) {
65185
+ if (ids2.has(v.id))
65186
+ return `Floor ${lv.name}: point id "${v.id}" is used twice.`;
65187
+ ids2.add(v.id);
65188
+ }
65189
+ const missing = (id) => !ids2.has(id);
65190
+ const edges = [...lv.walls, ...lv.doors, ...lv.lanes, ...lv.measurements];
65191
+ if (edges.some((e) => missing(e.v1) || missing(e.v2)))
65192
+ return `Floor ${lv.name}: a line ends at a point that does not exist.`;
65193
+ if ([...lv.floors, ...lv.holes, ...lv.zones].some((p) => p.vertices.some(missing)))
65194
+ return `Floor ${lv.name}: an area uses a point that does not exist.`;
65195
+ for (const d of lv.doors) {
65196
+ if (doorNames.has(d.name))
65197
+ return `Two doors are both called "${d.name}" - door names must be unique in the building.`;
65198
+ doorNames.add(d.name);
65199
+ }
65200
+ if (lv.lanes.some((l) => !graphIdx.has(l.graphIdx)))
65201
+ return `Floor ${lv.name}: a lane belongs to a route graph that is not listed.`;
65202
+ }
65203
+ for (const l of rmf.lifts) {
65204
+ const cabin = new Set(l.doors.map((d) => d.name));
65205
+ if (l.referenceFloor && !levelNames.has(l.referenceFloor))
65206
+ return `Lift ${l.name}: its reference floor "${l.referenceFloor}" does not exist.`;
65207
+ for (const [what, floor] of [["lowest", l.lowestFloor], ["highest", l.highestFloor], ["first", l.initialFloor]]) {
65208
+ if (floor && !levelNames.has(floor))
65209
+ return `Lift ${l.name}: its ${what} floor "${floor}" does not exist.`;
65210
+ }
65211
+ for (const x of l.levelDoors) {
65212
+ if (!levelNames.has(x.level))
65213
+ return `Lift ${l.name}: floor "${x.level}" does not exist.`;
65214
+ if (x.doors.some((d) => !cabin.has(d)))
65215
+ return `Lift ${l.name}: floor ${x.level} opens a cabin door the lift does not have.`;
65216
+ }
65217
+ }
65218
+ return null;
65219
+ }
65220
+ var P = { str: (v) => [1, v], int: (v) => [2, Math.round(v)], dbl: (v) => [3, v], bool: (v) => [4, v] };
65221
+ function vertexParamYaml(k, val) {
65222
+ if (k === "merge_radius")
65223
+ return P.dbl(Number(val));
65224
+ if (typeof val === "boolean")
65225
+ return P.bool(val);
65226
+ return P.str(String(val ?? ""));
65227
+ }
65228
+ function liftFloorRange(l, levels) {
65229
+ const elevation = new Map(levels.map((x) => [x.name, x.elevationM]));
65230
+ const served = l.levelDoors.map((x) => x.level).sort((a, b) => (elevation.get(a) ?? 0) - (elevation.get(b) ?? 0));
65231
+ return {
65232
+ lowest: l.lowestFloor || served[0] || l.referenceFloor,
65233
+ highest: l.highestFloor || served[served.length - 1] || l.referenceFloor,
65234
+ initial: l.initialFloor || served[0] || l.referenceFloor
65235
+ };
65236
+ }
65237
+ function toBuildingYaml(name, rmf) {
65238
+ const levels = {};
65239
+ for (const lv of rmf.levels) {
65240
+ const idx = new Map(lv.vertices.map((v, i) => [v.id, i]));
65241
+ const edge2 = (v1, v2, params) => [idx.get(v1), idx.get(v2), params];
65242
+ const f = lv.planFrame;
65243
+ levels[lv.name] = {
65244
+ elevation: lv.elevationM,
65245
+ hero_floor_no: lv.floorNo,
65246
+ hero_plan_frame: [f.minX, f.minY, f.maxX, f.maxY],
65247
+ vertices: lv.vertices.map((v) => {
65248
+ const params = {};
65249
+ for (const [k, val] of Object.entries(v.params ?? {}))
65250
+ if (val !== void 0)
65251
+ params[k] = vertexParamYaml(k, val);
65252
+ return [v.x, v.y, 0, v.name ?? "", params];
65253
+ }),
65254
+ walls: lv.walls.map(
65255
+ (w) => edge2(w.v1, w.v2, {
65256
+ alpha: P.dbl(w.alpha ?? 1),
65257
+ texture_height: P.dbl(w.textureHeight ?? 2.5),
65258
+ texture_name: P.str(w.textureName ?? "default"),
65259
+ texture_scale: P.dbl(w.textureScale ?? 1),
65260
+ texture_width: P.dbl(w.textureWidth ?? 1)
65261
+ })
65262
+ ),
65263
+ doors: lv.doors.map(
65264
+ (d) => edge2(d.v1, d.v2, {
65265
+ motion_axis: P.str(d.motionAxis ?? "start"),
65266
+ motion_degrees: P.dbl(d.motionDegrees ?? 90),
65267
+ motion_direction: P.int(d.motionDirection ?? 1),
65268
+ name: P.str(d.name),
65269
+ plugin: P.str(d.plugin ?? "normal"),
65270
+ right_left_ratio: P.dbl(d.rightLeftRatio ?? 1),
65271
+ type: P.str(d.type)
65272
+ })
65273
+ ),
65274
+ lanes: lv.lanes.map(
65275
+ (l) => edge2(l.v1, l.v2, {
65276
+ bidirectional: P.bool(l.bidirectional),
65277
+ demo_mock_floor_name: P.str(l.demoMockFloorName ?? ""),
65278
+ demo_mock_lift_name: P.str(l.demoMockLiftName ?? ""),
65279
+ graph_idx: P.int(l.graphIdx),
65280
+ mutex: P.str(l.mutex ?? ""),
65281
+ orientation: P.str(l.orientation ?? ""),
65282
+ speed_limit: P.dbl(l.speedLimit ?? 0)
65283
+ })
65284
+ ),
65285
+ measurements: lv.measurements.map((m) => edge2(m.v1, m.v2, { distance: P.dbl(m.distanceM) })),
65286
+ floors: lv.floors.map((p) => ({ vertices: p.vertices.map((id) => idx.get(id)), parameters: {} })),
65287
+ holes: lv.holes.map((p) => ({ vertices: p.vertices.map((id) => idx.get(id)), parameters: {} })),
65288
+ fiducials: lv.fiducials.map((p) => [p.x, p.y, p.name]),
65289
+ ...lv.zones.length ? { hero_zones: lv.zones.map((z5) => ({ name: z5.name, vertices: z5.vertices.map((id) => idx.get(id)) })) } : {},
65290
+ layers: {},
65291
+ models: []
65292
+ };
65293
+ }
65294
+ const lifts = {};
65295
+ for (const l of rmf.lifts) {
65296
+ const range = liftFloorRange(l, rmf.levels);
65297
+ lifts[l.name] = {
65298
+ x: l.x,
65299
+ y: l.y,
65300
+ yaw: l.yawRad,
65301
+ width: l.widthM,
65302
+ depth: l.depthM,
65303
+ reference_floor_name: l.referenceFloor,
65304
+ initial_floor_name: range.initial,
65305
+ lowest_floor: range.lowest,
65306
+ highest_floor: range.highest,
65307
+ doors: Object.fromEntries(
65308
+ l.doors.map((d) => [d.name, { door_type: LIFT_DOOR_TYPE_INT[d.type] ?? 2, x: d.x, y: d.y, width: d.widthM, motion_axis_orientation: d.axisYawRad }])
65309
+ ),
65310
+ level_doors: Object.fromEntries(l.levelDoors.map((x) => [x.level, x.doors])),
65311
+ plugins: l.plugins ?? true
65312
+ };
65313
+ }
65314
+ const graphs = Object.fromEntries(
65315
+ rmf.graphs.map((g) => [String(g.idx), { name: g.name, default_lane_width: 1, ...g.brands.length ? { hero_brands: g.brands } : {} }])
65316
+ );
65317
+ return JSON.stringify(
65318
+ { name, coordinate_system: "cartesian_meters", reference_level_name: rmf.referenceLevel ?? rmf.levels[0]?.name ?? "", graphs, parameters: {}, levels, lifts },
65319
+ null,
65320
+ 1
65321
+ );
65322
+ }
65323
+ function segmentsIntersect(a, b, c, d) {
65324
+ const det = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
65325
+ if (Math.abs(det) < 0.01)
65326
+ return false;
65327
+ const t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / det;
65328
+ const u = -((a.x - b.x) * (a.y - c.y) - (a.y - b.y) * (a.x - c.x)) / det;
65329
+ return t >= 0 && t <= 1 && u >= 0 && u <= 1;
65330
+ }
65331
+ function liftShaft(l) {
65332
+ const d = l.depthM / 2 + 0.05;
65333
+ const w = l.widthM / 2 + 0.05;
65334
+ const s = Math.sin(l.yawRad);
65335
+ const c = Math.cos(l.yawRad);
65336
+ return [
65337
+ { x: l.x - d * s - w * c, y: l.y + d * c - w * s },
65338
+ { x: l.x + d * s - w * c, y: l.y - d * c - w * s },
65339
+ { x: l.x + d * s + w * c, y: l.y - d * c + w * s },
65340
+ { x: l.x - d * s + w * c, y: l.y + d * c + w * s }
65341
+ ];
65342
+ }
65343
+ function inShaft(p, verts) {
65344
+ const cross = verts.map((v, i) => {
65345
+ const prev = verts[(i + 3) % 4];
65346
+ const a = { x: v.x - p.x, y: v.y - p.y };
65347
+ const b = { x: prev.x - v.x, y: prev.y - v.y };
65348
+ return a.x * b.y - a.y * b.x;
65349
+ });
65350
+ return cross.every((c) => c >= 0) || cross.every((c) => c <= 0);
65351
+ }
65352
+ function toNavGraphs(name, rmf) {
65353
+ const out = {};
65354
+ const elevation = new Map(rmf.levels.map((l) => [l.name, l.elevationM]));
65355
+ const shafts = rmf.lifts.map((l) => {
65356
+ const range = liftFloorRange(l, rmf.levels);
65357
+ return {
65358
+ lift: l,
65359
+ verts: liftShaft(l),
65360
+ // lift.py: no lowest / highest floor = no bound; a lift with no level_doors marks nothing.
65361
+ lo: elevation.get(range.lowest) ?? -Infinity,
65362
+ hi: elevation.get(range.highest) ?? Infinity,
65363
+ hasDoors: l.levelDoors.length > 0
65364
+ };
65365
+ });
65366
+ for (let gi = 0; gi <= 8; gi++) {
65367
+ const levels = {};
65368
+ const doors = {};
65369
+ let empty = true;
65370
+ for (const lv of rmf.levels) {
65371
+ const v = new Map(lv.vertices.map((x) => [x.id, x]));
65372
+ const lanes = lv.lanes.filter((l) => l.graphIdx === gi && v.has(l.v1) && v.has(l.v2));
65373
+ if (lanes.length)
65374
+ empty = false;
65375
+ const order = [];
65376
+ const mapped = /* @__PURE__ */ new Map();
65377
+ for (const l of lanes)
65378
+ for (const id of [l.v1, l.v2])
65379
+ if (!mapped.has(id))
65380
+ mapped.set(id, order.push(id) - 1);
65381
+ const here = shafts.filter((s) => s.hasDoors && lv.elevationM >= s.lo && lv.elevationM <= s.hi);
65382
+ const vertices = order.map((id) => {
65383
+ const q = v.get(id);
65384
+ const lift2 = here.find((s) => inShaft(q, s.verts))?.lift;
65385
+ return [q.x, q.y, { name: q.name ?? "", ...q.params ?? {}, ...lift2 ? { lift: lift2.name } : {} }];
65386
+ });
65387
+ const navLanes = [];
65388
+ for (const l of lanes) {
65389
+ const a = v.get(l.v1);
65390
+ const b = v.get(l.v2);
65391
+ const p = {};
65392
+ for (const d of lv.doors) {
65393
+ const c = v.get(d.v1);
65394
+ const e = v.get(d.v2);
65395
+ if (c && e && segmentsIntersect(a, b, c, e))
65396
+ p.door_name = d.name;
65397
+ }
65398
+ if (l.orientation)
65399
+ p.orientation_constraint = l.orientation;
65400
+ if (l.speedLimit && l.speedLimit > 0)
65401
+ p.speed_limit = l.speedLimit;
65402
+ if (l.mutex)
65403
+ p.mutex = l.mutex;
65404
+ if (l.demoMockFloorName)
65405
+ p.demo_mock_floor_name = l.demoMockFloorName;
65406
+ if (l.demoMockLiftName)
65407
+ p.demo_mock_lift_name = l.demoMockLiftName;
65408
+ const endDock = b.params?.dock_name;
65409
+ const startDock = a.params?.dock_name;
65410
+ const s = mapped.get(l.v1);
65411
+ const t = mapped.get(l.v2);
65412
+ if (l.bidirectional) {
65413
+ const fwd = { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} };
65414
+ const back = { ...p, ...endDock ? { undock_name: endDock } : {}, ...startDock ? { dock_name: startDock } : {} };
65415
+ if (l.orientation)
65416
+ back.orientation_constraint = l.orientation === "forward" ? "backward" : "forward";
65417
+ navLanes.push([s, t, fwd], [t, s, back]);
65418
+ } else {
65419
+ navLanes.push([s, t, { ...p, is_bidirectional: false, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} }]);
65420
+ }
65421
+ }
65422
+ levels[lv.name] = { vertices, lanes: navLanes };
65423
+ for (const d of lv.doors) {
65424
+ const c = v.get(d.v1);
65425
+ const e = v.get(d.v2);
65426
+ if (c && e)
65427
+ doors[d.name] = { endpoints: [[c.x, c.y], [e.x, e.y]], map: lv.name };
65428
+ }
65429
+ }
65430
+ if (empty)
65431
+ continue;
65432
+ const lifts = Object.fromEntries(rmf.lifts.map((l) => [l.name, { position: [l.x, l.y, l.yawRad], dims: [l.widthM, l.depthM] }]));
65433
+ out[gi] = JSON.stringify({ building_name: name, levels, lifts, doors, offset: [0, 0] }, null, 1);
65434
+ }
65435
+ return out;
65436
+ }
65437
+ var RmfImportError = class extends Error {
65438
+ };
65439
+ var IDENTITY = { scale: 1, rot: 0, tx: 0, ty: 0 };
65440
+ function applyXform(t, p) {
65441
+ const q = rot(p.x, p.y, t.rot);
65442
+ return { x: q.x * t.scale + t.tx, y: q.y * t.scale + t.ty };
65443
+ }
65444
+ function fiducialTransform(pairs, refScale) {
65445
+ const bearing = (a, b) => Math.atan2(b.y - a.y, b.x - a.x);
65446
+ const dist = (a, b) => Math.hypot(b.x - a.x, b.y - a.y);
65447
+ const bearings = [];
65448
+ const distances = [];
65449
+ for (let i = 0; i < pairs.length; i++) {
65450
+ for (let j = i + 1; j < pairs.length; j++) {
65451
+ bearings.push([bearing(pairs[i][0], pairs[j][0]), bearing(pairs[i][1], pairs[j][1])]);
65452
+ distances.push([dist(pairs[i][0], pairs[j][0]), dist(pairs[i][1], pairs[j][1])]);
65453
+ }
65454
+ }
65455
+ if (!bearings.length)
65456
+ return null;
65457
+ let sinSum = 0;
65458
+ let cosSum = 0;
65459
+ for (const [ref, target] of bearings) {
65460
+ sinSum += Math.sin(target - ref);
65461
+ cosSum += Math.cos(target - ref);
65462
+ }
65463
+ const rotation = -Math.atan2(sinSum, cosSum);
65464
+ const rel = distances.reduce((n, [ref, target]) => n + target / (ref || 1e-9), 0) / distances.length;
65465
+ if (!(rel > 0) || !Number.isFinite(rel))
65466
+ return null;
65467
+ let tx = 0;
65468
+ let ty = 0;
65469
+ for (const [f0, f1] of pairs) {
65470
+ const q = rot(f1.x / rel, f1.y / rel, rotation);
65471
+ tx += q.x - f0.x;
65472
+ ty += q.y - f0.y;
65473
+ }
65474
+ return { scale: refScale / rel, rot: rotation, tx: tx * -refScale / pairs.length, ty: ty * -refScale / pairs.length };
65475
+ }
65476
+ function measurementScale(vertices, meas) {
65477
+ const est = meas.flatMap(([a, b, d]) => {
65478
+ const p = vertices[a];
65479
+ const q = vertices[b];
65480
+ const len = p && q ? Math.hypot(q.x - p.x, q.y - p.y) : 0;
65481
+ return len > 0 && d > 0 ? [d / len] : [];
65482
+ });
65483
+ return est.length ? est.reduce((n, v) => n + v, 0) / est.length : null;
65484
+ }
65485
+ var pval = (p) => Array.isArray(p) ? p[1] : p;
65486
+ var num = (v, fallback = 0) => v !== null && v !== "" && Number.isFinite(Number(v)) ? Number(v) : fallback;
65487
+ var str60 = (v) => String(v ?? "").slice(0, 60);
65488
+ function decodeParams(raw) {
65489
+ const out = {};
65490
+ if (raw && typeof raw === "object" && !Array.isArray(raw))
65491
+ for (const [k, v] of Object.entries(raw))
65492
+ out[k] = pval(v);
65493
+ return out;
65494
+ }
65495
+ function edgeList(raw) {
65496
+ return (Array.isArray(raw) ? raw : []).flatMap(
65497
+ (e) => Array.isArray(e) && Number.isInteger(Number(e[0])) && Number.isInteger(Number(e[1])) ? [{ a: Number(e[0]), b: Number(e[1]), p: decodeParams(e[2]) }] : []
65498
+ );
65499
+ }
65500
+ function fileVertexParams(raw) {
65501
+ const out = {};
65502
+ for (const k of VERTEX_PARAM_KEYS) {
65503
+ const v = raw[k];
65504
+ if (v === void 0 || v === null)
65505
+ continue;
65506
+ out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? clamp2(num(v), 0, 100) : str60(v);
65507
+ }
65508
+ return out;
65509
+ }
65510
+ function canonicalVertices(level2) {
65511
+ pruneVertices(level2);
65512
+ const map = new Map(level2.vertices.map((v, i) => [v.id, `v${i + 1}`]));
65513
+ const id = (x) => map.get(x) ?? x;
65514
+ level2.vertices = level2.vertices.map((v) => ({ ...v, id: id(v.id) }));
65515
+ for (const list of [level2.walls, level2.doors, level2.lanes, level2.measurements]) {
65516
+ for (const e of list) {
65517
+ e.v1 = id(e.v1);
65518
+ e.v2 = id(e.v2);
65519
+ }
65520
+ }
65521
+ for (const poly of [...level2.floors, ...level2.holes, ...level2.zones])
65522
+ poly.vertices = poly.vertices.map(id);
65523
+ }
65524
+ function buildingFrame(rmf, pad = 2) {
65525
+ const xs = [];
65526
+ const ys = [];
65527
+ for (const lv of rmf.levels) {
65528
+ for (const v of lv.vertices)
65529
+ xs.push(v.x), ys.push(v.y);
65530
+ for (const f of lv.fiducials)
65531
+ xs.push(f.x), ys.push(f.y);
65532
+ }
65533
+ for (const l of rmf.lifts)
65534
+ for (const c of liftShaft(l))
65535
+ xs.push(c.x), ys.push(c.y);
65536
+ if (!xs.length)
65537
+ return { ...DEFAULT_PLAN_FRAME };
65538
+ const grow = (lo, hi) => hi - lo < 10 ? [(lo + hi) / 2 - 5, (lo + hi) / 2 + 5] : [lo, hi];
65539
+ const [minX, maxX] = grow(Math.min(...xs) - pad, Math.max(...xs) + pad);
65540
+ const [minY, maxY] = grow(Math.min(...ys) - pad, Math.max(...ys) + pad);
65541
+ return { minX: r3(minX), maxX: r3(maxX), minY: r3(minY), maxY: r3(maxY) };
65542
+ }
65543
+ var frameOf = (raw) => {
65544
+ if (!Array.isArray(raw) || raw.length !== 4 || raw.some((v) => !Number.isFinite(Number(v))))
65545
+ return null;
65546
+ const [minX, minY, maxX, maxY] = raw.map(Number);
65547
+ return maxX > minX && maxY > minY ? { minX, maxX, minY, maxY } : null;
65548
+ };
65549
+ function fromBuildingYaml(doc) {
65550
+ if (!doc || typeof doc !== "object" || !doc.levels || typeof doc.levels !== "object" || Array.isArray(doc.levels)) {
65551
+ throw new RmfImportError("This is not a building file: it has no floors (levels).");
65552
+ }
65553
+ const cs = String(doc.coordinate_system ?? "reference_image");
65554
+ if (cs === "wgs84" || cs === "web_mercator") {
65555
+ throw new RmfImportError("This building file is laid out on map (GPS) coordinates. Save it in metres or as an image-based plan in the traffic editor, then import it.");
65556
+ }
65557
+ if (cs !== "reference_image" && cs !== "cartesian_meters")
65558
+ throw new RmfImportError(`This building file uses an unknown coordinate system ("${cs.slice(0, 30)}").`);
65559
+ const flip = cs === "reference_image" ? -1 : 1;
65560
+ const warnings = [];
65561
+ const names = Object.keys(doc.levels);
65562
+ if (!names.length)
65563
+ throw new RmfImportError("This building file has no floors.");
65564
+ if (names.length > 200)
65565
+ throw new RmfImportError("This building file has more than 200 floors.");
65566
+ const LIMITS = [["vertices", 5e3], ["walls", 5e3], ["lanes", 5e3], ["doors", 500], ["measurements", 200], ["fiducials", 200], ["floors", 200], ["holes", 200], ["hero_zones", 200]];
65567
+ for (const name of names) {
65568
+ const y = doc.levels[name] ?? {};
65569
+ for (const [key, max] of LIMITS) {
65570
+ if (Array.isArray(y[key]) && y[key].length > max)
65571
+ throw new RmfImportError(`Floor ${str60(name)} has more than ${max} ${key.replace("hero_", "")} - more than a building map can hold.`);
65572
+ }
65573
+ }
65574
+ if (doc.lifts && typeof doc.lifts === "object" && Object.keys(doc.lifts).length > 50)
65575
+ throw new RmfImportError("This building file has more than 50 lifts.");
65576
+ const raw = names.map((name) => {
65577
+ const y = doc.levels[name] ?? {};
65578
+ const vertices = (Array.isArray(y.vertices) ? y.vertices : []).map((v) => ({
65579
+ x: num(v?.[0]),
65580
+ y: num(v?.[1]) * flip,
65581
+ name: str60(v?.[3]),
65582
+ params: fileVertexParams(decodeParams(v?.[4]))
65583
+ }));
65584
+ const fiducials = (Array.isArray(y.fiducials) ? y.fiducials : []).map((f) => ({ x: num(f?.[0]), y: num(f?.[1]) * flip, name: str60(f?.[2]) }));
65585
+ const meas = edgeList(y.measurements).map((e) => [e.a, e.b, num(e.p.distance)]);
65586
+ return { name: str60(name), y, vertices, fiducials, meas, elevation: num(y.elevation) };
65587
+ });
65588
+ const refName = raw.some((l) => l.name === doc.reference_level_name) ? String(doc.reference_level_name) : raw[0].name;
65589
+ const ref = raw.find((l) => l.name === refName);
65590
+ const xforms = /* @__PURE__ */ new Map();
65591
+ if (cs === "reference_image") {
65592
+ let refScale = measurementScale(ref.vertices, ref.meas);
65593
+ if (refScale === null) {
65594
+ refScale = 1;
65595
+ warnings.push(`Floor ${ref.name} has no measurement, so its size is unknown - sizes are in pixels. Measure a known length on that floor, then save.`);
65596
+ }
65597
+ xforms.set(ref.name, { ...IDENTITY, scale: refScale });
65598
+ for (const lv of raw) {
65599
+ if (lv === ref)
65600
+ continue;
65601
+ const pairs = [];
65602
+ const mine = /* @__PURE__ */ new Map();
65603
+ for (const b of lv.fiducials)
65604
+ if (b.name && !mine.has(b.name))
65605
+ mine.set(b.name, b);
65606
+ const seen2 = /* @__PURE__ */ new Set();
65607
+ for (const a of ref.fiducials) {
65608
+ const b = a.name && !seen2.has(a.name) ? mine.get(a.name) : void 0;
65609
+ if (b) {
65610
+ seen2.add(a.name);
65611
+ pairs.push([a, b]);
65612
+ }
65613
+ }
65614
+ const t = fiducialTransform(pairs, refScale);
65615
+ if (t)
65616
+ xforms.set(lv.name, t);
65617
+ else {
65618
+ xforms.set(lv.name, { ...IDENTITY, scale: measurementScale(lv.vertices, lv.meas) ?? refScale });
65619
+ warnings.push(`Floor ${lv.name} shares fewer than two fiducials with ${ref.name}, so it could not be lined up with it - check its position.`);
65620
+ }
65621
+ }
65622
+ }
65623
+ const xf = (level2) => xforms.get(level2) ?? IDENTITY;
65624
+ const floorNos = /* @__PURE__ */ new Map();
65625
+ const used = /* @__PURE__ */ new Set();
65626
+ for (const lv of raw) {
65627
+ const hero = Number(lv.y.hero_floor_no);
65628
+ const n = Number.isInteger(hero) && hero >= -20 && hero <= 200 ? hero : floorNoFromName(lv.name);
65629
+ if (n !== null && !used.has(n)) {
65630
+ floorNos.set(lv.name, n);
65631
+ used.add(n);
65632
+ }
65633
+ }
65634
+ let next = Math.max(0, ...used) + 1;
65635
+ for (const lv of [...raw].sort((a, b) => a.elevation - b.elevation)) {
65636
+ if (floorNos.has(lv.name))
65637
+ continue;
65638
+ while (used.has(next))
65639
+ next++;
65640
+ if (next > 200)
65641
+ throw new RmfImportError("This building file has too many floors to number.");
65642
+ floorNos.set(lv.name, next);
65643
+ used.add(next);
65644
+ }
65645
+ const rmf = emptyRmf("file");
65646
+ const graphIdx = /* @__PURE__ */ new Set();
65647
+ for (const lv of raw) {
65648
+ const t = xf(lv.name);
65649
+ const level2 = emptyLevel(lv.name, floorNos.get(lv.name), lv.elevation, { ...DEFAULT_PLAN_FRAME });
65650
+ const ids2 = lv.vertices.map((_, i) => `v${i + 1}`);
65651
+ level2.vertices = lv.vertices.map((v, i) => {
65652
+ const w = applyXform(t, v);
65653
+ return { id: ids2[i], x: r3(w.x), y: r3(w.y), ...v.name ? { name: v.name } : {}, ...Object.keys(v.params).length ? { params: v.params } : {} };
65654
+ });
65655
+ const ok = (e) => !!ids2[e.a] && !!ids2[e.b] && e.a !== e.b;
65656
+ for (const e of edgeList(lv.y.walls).filter(ok)) {
65657
+ const extra = {};
65658
+ if (e.p.texture_name !== void 0 && e.p.texture_name !== "default")
65659
+ extra.textureName = str60(e.p.texture_name);
65660
+ if (e.p.alpha !== void 0 && num(e.p.alpha, 1) !== 1)
65661
+ extra.alpha = clamp2(num(e.p.alpha, 1), 0, 1);
65662
+ if (e.p.texture_height !== void 0 && num(e.p.texture_height, 2.5) !== 2.5)
65663
+ extra.textureHeight = clamp2(num(e.p.texture_height, 2.5), 0, 100);
65664
+ if (e.p.texture_width !== void 0 && num(e.p.texture_width, 1) !== 1)
65665
+ extra.textureWidth = clamp2(num(e.p.texture_width, 1), 0, 100);
65666
+ if (e.p.texture_scale !== void 0 && num(e.p.texture_scale, 1) !== 1)
65667
+ extra.textureScale = clamp2(num(e.p.texture_scale, 1), 0, 100);
65668
+ level2.walls.push({ v1: ids2[e.a], v2: ids2[e.b], ...extra });
65669
+ }
65670
+ for (const e of edgeList(lv.y.doors).filter(ok)) {
65671
+ const type = String(e.p.type ?? "hinged");
65672
+ const degrees = clamp2(num(e.p.motion_degrees, 90), -360, 360);
65673
+ const ratio = clamp2(num(e.p.right_left_ratio, 1), 0, 10);
65674
+ const plugin = str60(e.p.plugin ?? "normal");
65675
+ level2.doors.push({
65676
+ name: str60(e.p.name ?? "").trim() || `door_${level2.doors.length + 1}`,
65677
+ v1: ids2[e.a],
65678
+ v2: ids2[e.b],
65679
+ type: ["hinged", "double_hinged", "sliding", "double_sliding"].includes(type) ? type : "hinged",
65680
+ ...e.p.motion_axis === "end" ? { motionAxis: "end" } : {},
65681
+ ...degrees !== 90 ? { motionDegrees: degrees } : {},
65682
+ ...num(e.p.motion_direction, 1) < 0 ? { motionDirection: -1 } : {},
65683
+ ...ratio !== 1 ? { rightLeftRatio: ratio } : {},
65684
+ ...plugin !== "normal" ? { plugin } : {}
65685
+ });
65686
+ }
65687
+ for (const e of edgeList(lv.y.lanes).filter(ok)) {
65688
+ const gi = Math.round(num(e.p.graph_idx, 0));
65689
+ if (gi < 0 || gi > 8) {
65690
+ warnings.push(`Floor ${lv.name}: a lane on graph ${gi} was skipped (graphs 0-8 only).`);
65691
+ continue;
65692
+ }
65693
+ graphIdx.add(gi);
65694
+ const orientation = e.p.orientation === "forward" || e.p.orientation === "backward" ? e.p.orientation : void 0;
65695
+ level2.lanes.push({
65696
+ v1: ids2[e.a],
65697
+ v2: ids2[e.b],
65698
+ graphIdx: gi,
65699
+ bidirectional: e.p.bidirectional === true,
65700
+ ...orientation ? { orientation } : {},
65701
+ ...num(e.p.speed_limit) > 0 ? { speedLimit: clamp2(num(e.p.speed_limit), 0, 20) } : {},
65702
+ ...e.p.mutex ? { mutex: str60(e.p.mutex) } : {},
65703
+ ...e.p.demo_mock_floor_name ? { demoMockFloorName: str60(e.p.demo_mock_floor_name) } : {},
65704
+ ...e.p.demo_mock_lift_name ? { demoMockLiftName: str60(e.p.demo_mock_lift_name) } : {}
65705
+ });
65706
+ }
65707
+ for (const e of edgeList(lv.y.measurements).filter(ok)) {
65708
+ const d = num(e.p.distance);
65709
+ if (d >= 0.01)
65710
+ level2.measurements.push({ v1: ids2[e.a], v2: ids2[e.b], distanceM: Math.min(d, 1e4) });
65711
+ }
65712
+ const polyIds = (p) => (Array.isArray(p?.vertices) ? p.vertices : []).map((i) => ids2[Number(i)]).filter((x) => !!x);
65713
+ const polys = (list) => (Array.isArray(list) ? list : []).flatMap((p) => {
65714
+ const vs = polyIds(p);
65715
+ return vs.length >= 3 ? [{ vertices: vs }] : [];
65716
+ });
65717
+ level2.floors = polys(lv.y.floors);
65718
+ level2.holes = polys(lv.y.holes);
65719
+ level2.zones = (Array.isArray(lv.y.hero_zones) ? lv.y.hero_zones : []).flatMap((z5) => {
65720
+ const vs = polyIds(z5);
65721
+ return vs.length >= 3 && str60(z5?.name).trim() ? [{ name: str60(z5.name).trim(), vertices: vs }] : [];
65722
+ });
65723
+ level2.fiducials = lv.fiducials.map((f) => {
65724
+ const w = applyXform(t, f);
65725
+ return { name: f.name || "fiducial", x: r3(w.x), y: r3(w.y) };
65726
+ });
65727
+ canonicalVertices(level2);
65728
+ rmf.levels.push(level2);
65729
+ }
65730
+ rmf.levels.sort((a, b) => a.floorNo - b.floorNo);
65731
+ rmf.referenceLevel = refName;
65732
+ const levelNames = new Set(rmf.levels.map((l) => l.name));
65733
+ const lifts = doc.lifts && typeof doc.lifts === "object" ? Object.entries(doc.lifts) : [];
65734
+ for (const [liftName, ly] of lifts.slice(0, 50)) {
65735
+ const refFloor = levelNames.has(ly?.reference_floor_name) ? String(ly.reference_floor_name) : refName;
65736
+ if (ly?.reference_floor_name && !levelNames.has(ly.reference_floor_name)) {
65737
+ warnings.push(`Lift ${str60(liftName)}: its reference floor "${str60(ly.reference_floor_name)}" is not in the file; ${refName} was used.`);
65738
+ }
65739
+ const c = applyXform(xf(refFloor), { x: num(ly?.x), y: num(ly?.y) * flip });
65740
+ const doors = Object.entries(ly?.doors ?? {}).slice(0, 8).map(([dn, d]) => ({
65741
+ name: str60(dn),
65742
+ type: MSG_LIFT_DOOR_TYPE[Math.round(num(d?.door_type, 2))] ?? "double_sliding",
65743
+ x: r3(clamp2(num(d?.x), -20, 20)),
65744
+ y: r3(clamp2(num(d?.y), -20, 20)),
65745
+ widthM: r3(clamp2(num(d?.width, 1), 0.3, 10)),
65746
+ axisYawRad: clamp2(num(d?.motion_axis_orientation), -10, 10)
65747
+ }));
65748
+ const doorNames = new Set(doors.map((d) => d.name));
65749
+ const levelDoors = Object.entries(ly?.level_doors ?? {}).filter(([level2]) => levelNames.has(level2)).map(([level2, list]) => ({ level: level2, doors: (Array.isArray(list) ? list : []).map(str60).filter((d) => doorNames.has(d)) }));
65750
+ const floorName = (v) => typeof v === "string" && levelNames.has(v) ? v : void 0;
65751
+ const lift2 = {
65752
+ name: str60(liftName),
65753
+ x: r3(c.x),
65754
+ y: r3(c.y),
65755
+ yawRad: clamp2(num(ly?.yaw), -10, 10),
65756
+ widthM: r3(clamp2(num(ly?.width, 2), 0.3, 20)),
65757
+ depthM: r3(clamp2(num(ly?.depth, 2), 0.3, 20)),
65758
+ referenceFloor: refFloor,
65759
+ ...floorName(ly?.initial_floor_name) ? { initialFloor: floorName(ly.initial_floor_name) } : {},
65760
+ ...floorName(ly?.lowest_floor) ? { lowestFloor: floorName(ly.lowest_floor) } : {},
65761
+ ...floorName(ly?.highest_floor) ? { highestFloor: floorName(ly.highest_floor) } : {},
65762
+ ...ly?.plugins === false ? { plugins: false } : {},
65763
+ doors,
65764
+ levelDoors
65765
+ };
65766
+ const derived = liftFloorRange({ ...lift2, lowestFloor: void 0, highestFloor: void 0, initialFloor: void 0 }, rmf.levels);
65767
+ if (lift2.lowestFloor === derived.lowest)
65768
+ delete lift2.lowestFloor;
65769
+ if (lift2.highestFloor === derived.highest)
65770
+ delete lift2.highestFloor;
65771
+ if (lift2.initialFloor === derived.initial)
65772
+ delete lift2.initialFloor;
65773
+ rmf.lifts.push(lift2);
65774
+ }
65775
+ const graphsYaml = doc.graphs && typeof doc.graphs === "object" ? doc.graphs : {};
65776
+ const declared = Object.keys(graphsYaml).map(Number).filter((n) => Number.isInteger(n) && n >= 0 && n <= 8);
65777
+ rmf.graphs = [.../* @__PURE__ */ new Set([...graphIdx, ...declared])].sort((a, b) => a - b).map((idx) => {
65778
+ const g = graphsYaml[String(idx)] ?? {};
65779
+ return { idx, name: str60(g.name).trim() || `Graph ${idx}`, brands: (Array.isArray(g.hero_brands) ? g.hero_brands : []).map(str60).slice(0, 20) };
65780
+ });
65781
+ const frames = new Map(raw.map((lv) => [lv.name, frameOf(lv.y.hero_plan_frame)]));
65782
+ if ([...frames.values()].every(Boolean))
65783
+ rmf.levels.forEach((l) => l.planFrame = frames.get(l.name));
65784
+ else {
65785
+ const f = buildingFrame(rmf);
65786
+ rmf.levels.forEach((l) => l.planFrame = { ...f });
65787
+ }
65788
+ return { rmf, name: str60(doc.name ?? doc.building_name ?? "").trim(), warnings };
65789
+ }
65790
+ function fromNavGraph(doc, graphIdx) {
65791
+ if (!doc || typeof doc !== "object" || !doc.levels || typeof doc.levels !== "object")
65792
+ throw new RmfImportError("This is not a route map file: it has no floors (levels).");
65793
+ if (!Number.isInteger(graphIdx) || graphIdx < 0 || graphIdx > 8)
65794
+ throw new RmfImportError("Choose a route graph from 0 to 8.");
65795
+ const rmf = emptyRmf("file");
65796
+ const warnings = [];
65797
+ const shared = (p) => JSON.stringify([p.door_name ?? null, p.speed_limit ?? null, p.mutex ?? null, p.demo_mock_floor_name ?? null, p.demo_mock_lift_name ?? null]);
65798
+ const flipOrientation = (o) => o === "forward" ? "backward" : o === "backward" ? "forward" : o;
65799
+ const usedFloors = /* @__PURE__ */ new Set();
65800
+ let seq = 0;
65801
+ for (const [name, ly] of Object.entries(doc.levels).slice(0, 200)) {
65802
+ let floorNo2 = floorNoFromName(name) ?? ++seq;
65803
+ while (usedFloors.has(floorNo2))
65804
+ floorNo2++;
65805
+ usedFloors.add(floorNo2);
65806
+ const level2 = emptyLevel(str60(name), floorNo2, 0, { ...DEFAULT_PLAN_FRAME });
65807
+ const verts = (Array.isArray(ly?.vertices) ? ly.vertices : []).slice(0, 5e3);
65808
+ level2.vertices = verts.map((v, k) => {
65809
+ const p = v?.[2] && typeof v[2] === "object" ? v[2] : {};
65810
+ const params = fileVertexParams(p);
65811
+ return { id: `v${k + 1}`, x: r3(num(v?.[0])), y: r3(num(v?.[1])), ...p.name ? { name: str60(p.name) } : {}, ...Object.keys(params).length ? { params } : {} };
65812
+ });
65813
+ if (Array.isArray(ly?.lanes) && ly.lanes.length > 1e4)
65814
+ throw new RmfImportError(`Floor ${str60(name)} has more than 10000 one-way lanes - more than a building map can hold.`);
65815
+ const lanes = (Array.isArray(ly?.lanes) ? ly.lanes : []).filter(
65816
+ (l) => Array.isArray(l) && level2.vertices[Number(l[0])] && level2.vertices[Number(l[1])] && Number(l[0]) !== Number(l[1])
65817
+ );
65818
+ const used = /* @__PURE__ */ new Set();
65819
+ const byEnds = /* @__PURE__ */ new Map();
65820
+ lanes.forEach((l, k) => {
65821
+ const key = `${Number(l[0])},${Number(l[1])}`;
65822
+ byEnds.set(key, [...byEnds.get(key) ?? [], k]);
65823
+ });
65824
+ lanes.forEach((l, k) => {
65825
+ if (used.has(k))
65826
+ return;
65827
+ used.add(k);
65828
+ const a = Number(l[0]);
65829
+ const b = Number(l[1]);
65830
+ const p = l[2] ?? {};
65831
+ let bidirectional = p.is_bidirectional === true;
65832
+ if (!bidirectional && p.is_bidirectional === void 0) {
65833
+ const back = (byEnds.get(`${b},${a}`) ?? []).find((j) => {
65834
+ if (used.has(j))
65835
+ return false;
65836
+ const q = lanes[j][2] ?? {};
65837
+ return shared(q) === shared(p) && (q.orientation_constraint ?? null) === (flipOrientation(p.orientation_constraint) ?? null);
65838
+ });
65839
+ if (back !== void 0) {
65840
+ used.add(back);
65841
+ bidirectional = true;
65842
+ }
65843
+ }
65844
+ const o = p.orientation_constraint;
65845
+ level2.lanes.push({
65846
+ v1: level2.vertices[a].id,
65847
+ v2: level2.vertices[b].id,
65848
+ graphIdx,
65849
+ bidirectional,
65850
+ ...o === "forward" || o === "backward" ? { orientation: o } : {},
65851
+ ...num(p.speed_limit) > 0 ? { speedLimit: clamp2(num(p.speed_limit), 0, 20) } : {},
65852
+ ...p.mutex ? { mutex: str60(p.mutex) } : {},
65853
+ ...p.demo_mock_floor_name ? { demoMockFloorName: str60(p.demo_mock_floor_name) } : {},
65854
+ ...p.demo_mock_lift_name ? { demoMockLiftName: str60(p.demo_mock_lift_name) } : {}
65855
+ });
65856
+ });
65857
+ canonicalVertices(level2);
65858
+ rmf.levels.push(level2);
65859
+ }
65860
+ if (!rmf.levels.some((l) => l.lanes.length))
65861
+ warnings.push("The route map has no lanes.");
65862
+ rmf.graphs = [{ idx: graphIdx, name: `Graph ${graphIdx}`, brands: [] }];
65863
+ const f = buildingFrame(rmf);
65864
+ rmf.levels.forEach((l) => l.planFrame = { ...f });
65865
+ rmf.referenceLevel = rmf.levels[0]?.name;
65866
+ return { rmf, warnings };
65867
+ }
65868
+ function rmfSummary(rmf) {
65869
+ if (!rmf)
65870
+ return null;
65871
+ const sum = (f) => rmf.levels.reduce((n, l) => n + f(l), 0);
65872
+ return {
65873
+ source: rmf.source ?? "editor",
65874
+ levels: rmf.levels.length,
65875
+ lanes: sum((l) => l.lanes.length),
65876
+ waypoints: sum((l) => l.vertices.filter((v) => v.name).length),
65877
+ doors: sum((l) => l.doors.length),
65878
+ lifts: rmf.lifts.length,
65879
+ graphs: rmf.graphs.length
65880
+ };
65881
+ }
65882
+
65883
+ // src/services/robot-tracking.service.ts
65884
+ var import_axios4 = __toESM(require("axios"));
65885
+ async function openWithAxios(url, body) {
65886
+ const response = await import_axios4.default.post(url, body, {
65887
+ responseType: "stream",
65888
+ // No read timeout: this connection is SUPPOSED to stay open and mostly
65889
+ // silent. A request timeout here would sever a healthy stream on a quiet
65890
+ // robot. The idle watchdog is what decides a stream is dead, because it can
65891
+ // tell silence from a closed socket.
65892
+ timeout: 0,
65893
+ headers: { "Content-Type": "application/json", Accept: "text/event-stream" }
65894
+ });
65895
+ return response.data;
65896
+ }
65897
+ function startRobotTracking(options) {
65898
+ const {
65899
+ credentials,
65900
+ robotSn,
65901
+ onEvent,
65902
+ baseUrl = ROBOT_CLOUD_BASE_URL,
65903
+ idleTimeoutMs = TRACKING_IDLE_TIMEOUT_MS,
65904
+ openStream = openWithAxios,
65905
+ now = Date.now
65906
+ } = options;
65907
+ if (!baseUrl)
65908
+ throw new Error("Robot cloud: ROBOT_CLOUD_BASE_URL is not configured.");
65909
+ let stopped = false;
65910
+ let attempt = 0;
65911
+ let current = null;
65912
+ let watchdog = null;
65913
+ let retry = null;
65914
+ let lastActivityAt = now();
65915
+ let everConnected = false;
65916
+ const parser = createSseParser();
65917
+ function clearTimers() {
65918
+ if (watchdog) {
65919
+ clearInterval(watchdog);
65920
+ watchdog = null;
65921
+ }
65922
+ if (retry) {
65923
+ clearTimeout(retry);
65924
+ retry = null;
65925
+ }
65926
+ }
65927
+ function dropUpstream() {
65928
+ if (!current)
65929
+ return;
65930
+ try {
65931
+ current.destroy();
65932
+ } catch {
65933
+ }
65934
+ current = null;
65935
+ }
65936
+ function lose(reason) {
65937
+ if (stopped)
65938
+ return;
65939
+ onEvent({ type: "lost", reason, at: now() });
65940
+ dropUpstream();
65941
+ scheduleReconnect();
65942
+ }
65943
+ function scheduleReconnect() {
65944
+ if (stopped)
65945
+ return;
65946
+ clearTimers();
65947
+ const delay2 = trackingBackoffMs(attempt++);
65948
+ retry = setTimeout(connect2, delay2);
65949
+ }
65950
+ async function connect2() {
65951
+ if (stopped)
65952
+ return;
65953
+ const body = robotCloudBody(
65954
+ credentials.appid,
65955
+ credentials.secret,
65956
+ ROBOT_CLOUD_PATHS.tracking,
65957
+ { robotSn }
65958
+ );
65959
+ let stream;
65960
+ try {
65961
+ stream = await openStream(
65962
+ `${baseUrl.replace(/\/+$/, "")}${ROBOT_CLOUD_PATHS.tracking}`,
65963
+ body
65964
+ );
65965
+ } catch (error) {
65966
+ lose(error?.message ?? "Could not open the robot's tracking stream.");
65967
+ return;
65968
+ }
65969
+ if (stopped) {
65970
+ try {
65971
+ stream.destroy();
65972
+ } catch {
65973
+ }
65974
+ return;
65975
+ }
65976
+ parser.reset();
65977
+ current = stream;
65978
+ lastActivityAt = now();
65979
+ if (everConnected)
65980
+ onEvent({ type: "reconnected", at: now() });
65981
+ everConnected = true;
65982
+ attempt = 0;
65983
+ stream.on("data", (chunk2) => {
65984
+ if (stopped)
65985
+ return;
65986
+ const { events, sawActivity } = parser.push(chunk2.toString("utf8"));
65987
+ if (sawActivity)
65988
+ lastActivityAt = now();
65989
+ for (const event of events) {
65990
+ const pose = decodeTrackingFrame(event.data);
65991
+ if (pose)
65992
+ onEvent({ type: "pose", pose, at: now() });
65993
+ }
65994
+ });
65995
+ stream.on("error", (error) => lose(error?.message ?? "The tracking stream failed."));
65996
+ stream.on("end", () => lose("The robot cloud closed the tracking stream."));
65997
+ stream.on("close", () => {
65998
+ if (!stopped && current === stream)
65999
+ lose("The tracking stream closed.");
66000
+ });
66001
+ clearTimers();
66002
+ watchdog = setInterval(() => {
66003
+ if (stopped)
66004
+ return;
66005
+ if (now() - lastActivityAt >= idleTimeoutMs) {
66006
+ lose("The robot stopped reporting.");
66007
+ }
66008
+ }, Math.max(1e3, Math.floor(idleTimeoutMs / 3)));
66009
+ }
66010
+ void connect2();
66011
+ return {
66012
+ stop() {
66013
+ if (stopped)
66014
+ return;
66015
+ stopped = true;
66016
+ clearTimers();
66017
+ dropUpstream();
66018
+ }
66019
+ };
66020
+ }
66021
+
66022
+ // src/controllers/robot-fleet.controller.ts
66023
+ var import_joi76 = __toESM(require("joi"));
66024
+ var import_node_server_utils163 = require("@7365admin1/node-server-utils");
66025
+
66026
+ // src/services/robot-fault.service.ts
66027
+ var import_node_server_utils162 = require("@7365admin1/node-server-utils");
66028
+
66029
+ // src/repositories/robot-fault.repo.ts
66030
+ var import_mongodb108 = require("mongodb");
66031
+ var import_node_server_utils161 = require("@7365admin1/node-server-utils");
66032
+ var toId3 = (v) => v instanceof import_mongodb108.ObjectId ? v : new import_mongodb108.ObjectId(String(v));
66033
+ function useRobotFaultRepo() {
66034
+ const db2 = import_node_server_utils161.useAtlas.getDb();
66035
+ if (!db2)
66036
+ throw new import_node_server_utils161.InternalServerError("Unable to connect to server.");
66037
+ const collection = db2.collection(ROBOT_FAULTS_COLLECTION);
66038
+ async function createIndex() {
66039
+ try {
66040
+ await collection.createIndexes([
66041
+ {
66042
+ key: { robotId: 1, code: 1 },
66043
+ name: "one_open_fault_per_robot_code",
66044
+ unique: true,
66045
+ partialFilterExpression: { clearedAt: null }
66046
+ },
66047
+ { key: { clearedAt: 1, since: 1 }, name: "open_faults_by_since" }
66048
+ ]);
66049
+ } catch (error) {
66050
+ throw new import_node_server_utils161.InternalServerError("Failed to create index on robot faults.");
66051
+ }
66052
+ }
66053
+ async function getOpenFaults() {
66054
+ return collection.find({ clearedAt: null }, { projection: { robotId: 1, code: 1, since: 1 } }).toArray();
66055
+ }
66056
+ async function getOpenFault(robotId, code) {
66057
+ return collection.findOne({ robotId: toId3(robotId), code, clearedAt: null });
66058
+ }
66059
+ async function openFault(doc) {
66060
+ const now = /* @__PURE__ */ new Date();
66061
+ try {
66062
+ const res = await collection.insertOne({
66063
+ robotId: toId3(doc.robotId),
66064
+ orgId: doc.orgId ? toId3(doc.orgId) : null,
66065
+ siteId: doc.siteId ? toId3(doc.siteId) : null,
66066
+ code: doc.code,
66067
+ message: doc.message,
66068
+ since: doc.since,
66069
+ clearedAt: null,
66070
+ notifiedAt: null,
66071
+ createdAt: now
66072
+ });
66073
+ return res.insertedId;
66074
+ } catch (error) {
66075
+ if (error?.code === 11e3)
66076
+ return null;
66077
+ throw error;
66078
+ }
66079
+ }
66080
+ async function claimNotify(id) {
66081
+ const res = await collection.updateOne(
66082
+ { _id: toId3(id), clearedAt: null, notifiedAt: null },
66083
+ { $set: { notifiedAt: /* @__PURE__ */ new Date() } }
66084
+ );
66085
+ return res.modifiedCount === 1;
66086
+ }
66087
+ async function claimOfflineAlert(id, cutoff) {
66088
+ const res = await collection.updateOne(
66089
+ { _id: toId3(id), code: "OFFLINE", clearedAt: null, since: { $lte: cutoff }, offlineNotifiedAt: null },
66090
+ { $set: { offlineNotifiedAt: /* @__PURE__ */ new Date() } }
66091
+ );
66092
+ return res.modifiedCount === 1;
66093
+ }
66094
+ async function claimRecoveryAlert(id) {
66095
+ const res = await collection.updateOne(
66096
+ { _id: toId3(id), code: "OFFLINE", offlineNotifiedAt: { $ne: null }, recoveryNotifiedAt: null },
66097
+ { $set: { recoveryNotifiedAt: /* @__PURE__ */ new Date() } }
66098
+ );
66099
+ return res.modifiedCount === 1;
66100
+ }
66101
+ async function findNotifiedOccurrence(robotId, code, since, after) {
66102
+ const filter = {
66103
+ clearedAt: { $gte: after },
66104
+ robotId: toId3(robotId),
66105
+ code,
66106
+ notifiedAt: { $ne: null }
65013
66107
  };
65014
66108
  if (since)
65015
66109
  filter.since = { $gte: new Date(since.getTime() - 1e3), $lte: new Date(since.getTime() + 1e3) };
@@ -65397,8 +66491,11 @@ var floorPlanBodySchema = import_joi77.default.object({
65397
66491
  widthPx: import_joi77.default.number().integer().min(1).max(1e4).required(),
65398
66492
  heightPx: import_joi77.default.number().integer().min(1).max(1e4).required(),
65399
66493
  metersPerPixel: import_joi77.default.number().min(1e-4).max(10).required(),
65400
- tx: import_joi77.default.number().min(-1e3).max(1e3).default(0),
65401
- ty: import_joi77.default.number().min(-1e3).max(1e3).default(0)
66494
+ tx: import_joi77.default.number().min(-1e5).max(1e5).default(0),
66495
+ ty: import_joi77.default.number().min(-1e5).max(1e5).default(0),
66496
+ // No default: an older app re-scaling a plan sends neither, and must not reset a turn it cannot see.
66497
+ yawRad: import_joi77.default.number().min(-10).max(10),
66498
+ space: import_joi77.default.string().valid("world")
65402
66499
  });
65403
66500
  var coord = import_joi77.default.number().min(-1e3).max(1e3).required();
65404
66501
  var point = import_joi77.default.object({ x: coord, y: coord });
@@ -65458,11 +66555,24 @@ var rmfLevel = import_joi77.default.object({
65458
66555
  spawn_robot_type: import_joi77.default.string().trim().max(60).allow(""),
65459
66556
  lift_cabin: import_joi77.default.string().trim().max(60).allow(""),
65460
66557
  merge_radius: import_joi77.default.number().min(0).max(100),
65461
- mutex: import_joi77.default.string().trim().max(60).allow("")
66558
+ mutex: import_joi77.default.string().trim().max(60).allow(""),
66559
+ pickup_dispenser: import_joi77.default.string().trim().max(60).allow(""),
66560
+ dropoff_ingestor: import_joi77.default.string().trim().max(60).allow(""),
66561
+ human_goal_set_name: import_joi77.default.string().trim().max(60).allow("")
65462
66562
  })
65463
66563
  })
65464
66564
  ).max(5e3).default([]),
65465
- walls: import_joi77.default.array().items(import_joi77.default.object(edge)).max(5e3).default([]),
66565
+ walls: import_joi77.default.array().items(
66566
+ import_joi77.default.object({
66567
+ ...edge,
66568
+ // traffic-editor wall look (simulation only); absent = its defaults.
66569
+ textureName: import_joi77.default.string().trim().max(60).allow(""),
66570
+ alpha: import_joi77.default.number().min(0).max(1),
66571
+ textureHeight: import_joi77.default.number().min(0).max(100),
66572
+ textureWidth: import_joi77.default.number().min(0).max(100),
66573
+ textureScale: import_joi77.default.number().min(0).max(100)
66574
+ })
66575
+ ).max(5e3).default([]),
65466
66576
  floors: import_joi77.default.array().items(polygon).max(200).default([]),
65467
66577
  holes: import_joi77.default.array().items(polygon).max(200).default([]),
65468
66578
  doors: import_joi77.default.array().items(
@@ -65471,9 +66581,11 @@ var rmfLevel = import_joi77.default.object({
65471
66581
  name: rmfName.required(),
65472
66582
  type: import_joi77.default.string().valid("hinged", "double_hinged", "sliding", "double_sliding").default("hinged"),
65473
66583
  motionAxis: import_joi77.default.string().valid("start", "end"),
65474
- motionDegrees: import_joi77.default.number().min(0).max(360),
66584
+ // traffic-editor draws |degrees|; files in the wild carry negative ones (rmf_demos hotel).
66585
+ motionDegrees: import_joi77.default.number().min(-360).max(360),
65475
66586
  motionDirection: import_joi77.default.number().valid(1, -1),
65476
- rightLeftRatio: import_joi77.default.number().min(0).max(10)
66587
+ rightLeftRatio: import_joi77.default.number().min(0).max(10),
66588
+ plugin: import_joi77.default.string().trim().max(60).allow("")
65477
66589
  })
65478
66590
  ).max(500).default([]),
65479
66591
  lanes: import_joi77.default.array().items(
@@ -65483,7 +66595,9 @@ var rmfLevel = import_joi77.default.object({
65483
66595
  bidirectional: import_joi77.default.boolean().default(true),
65484
66596
  orientation: import_joi77.default.string().valid("forward", "backward"),
65485
66597
  speedLimit: import_joi77.default.number().min(0).max(20),
65486
- mutex: import_joi77.default.string().trim().max(60).allow("")
66598
+ mutex: import_joi77.default.string().trim().max(60).allow(""),
66599
+ demoMockFloorName: import_joi77.default.string().trim().max(60).allow(""),
66600
+ demoMockLiftName: import_joi77.default.string().trim().max(60).allow("")
65487
66601
  })
65488
66602
  ).max(5e3).default([]),
65489
66603
  measurements: import_joi77.default.array().items(import_joi77.default.object({ ...edge, distanceM: import_joi77.default.number().min(0.01).max(1e4).required() })).max(200).default([]),
@@ -65499,10 +66613,13 @@ var rmfLift = import_joi77.default.object({
65499
66613
  depthM: import_joi77.default.number().min(0.3).max(20).required(),
65500
66614
  referenceFloor: import_joi77.default.string().trim().max(60).allow("").default(""),
65501
66615
  initialFloor: import_joi77.default.string().trim().max(60).allow(""),
66616
+ lowestFloor: import_joi77.default.string().trim().max(60).allow(""),
66617
+ highestFloor: import_joi77.default.string().trim().max(60).allow(""),
66618
+ plugins: import_joi77.default.boolean(),
65502
66619
  doors: import_joi77.default.array().items(
65503
66620
  import_joi77.default.object({
65504
66621
  name: rmfName.required(),
65505
- type: import_joi77.default.string().valid("sliding", "double_sliding").default("double_sliding"),
66622
+ type: import_joi77.default.string().valid("sliding", "double_sliding", "telescope", "double_telescope").default("double_sliding"),
65506
66623
  x: import_joi77.default.number().min(-20).max(20).required(),
65507
66624
  y: import_joi77.default.number().min(-20).max(20).required(),
65508
66625
  widthM: import_joi77.default.number().min(0.3).max(10).required(),
@@ -65526,6 +66643,11 @@ var rmfBuildingSchema = import_joi77.default.object({
65526
66643
  levels: import_joi77.default.array().items(rmfLevel).max(200).unique("floorNo").default([]),
65527
66644
  lifts: import_joi77.default.array().items(rmfLift).max(50).unique("name").default([])
65528
66645
  });
66646
+ var buildingFileImportSchema = import_joi77.default.object({
66647
+ format: import_joi77.default.string().valid("building", "nav").default("building"),
66648
+ text: import_joi77.default.string().min(1).max(19e5).required(),
66649
+ graph: import_joi77.default.number().integer().min(0).max(8).when("format", { is: "nav", then: import_joi77.default.required(), otherwise: import_joi77.default.forbidden() })
66650
+ });
65529
66651
  var buildingMapBodySchema = import_joi77.default.object({
65530
66652
  name: label.required(),
65531
66653
  levels: import_joi77.default.array().items(level).max(200).unique("floorNo").default([]),
@@ -65671,6 +66793,13 @@ function useRobotBuildingMapRepo() {
65671
66793
  "floorPlans.$.updatedAt": at2,
65672
66794
  "floorPlans.$.updatedBy": plan.updatedBy
65673
66795
  };
66796
+ if (plan.yawRad !== void 0)
66797
+ fields["floorPlans.$.yawRad"] = plan.yawRad;
66798
+ const unset = {};
66799
+ if (plan.space === "world")
66800
+ fields["floorPlans.$.space"] = "world";
66801
+ else
66802
+ unset["floorPlans.$.space"] = "";
65674
66803
  if (plan.data) {
65675
66804
  fields["floorPlans.$.data"] = new import_mongodb110.Binary(plan.data);
65676
66805
  fields["floorPlans.$.mime"] = plan.mime;
@@ -65678,7 +66807,7 @@ function useRobotBuildingMapRepo() {
65678
66807
  }
65679
66808
  const res = existing ? await collection.updateOne(
65680
66809
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": plan.floorNo },
65681
- { $set: { ...fields, updatedAt: at2 }, $inc: { version: 1 } }
66810
+ { $set: { ...fields, updatedAt: at2 }, ...Object.keys(unset).length ? { $unset: unset } : {}, $inc: { version: 1 } }
65682
66811
  ) : await collection.updateOne(
65683
66812
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": { $ne: plan.floorNo } },
65684
66813
  {
@@ -65692,6 +66821,8 @@ function useRobotBuildingMapRepo() {
65692
66821
  metersPerPixel: plan.metersPerPixel,
65693
66822
  tx: plan.tx,
65694
66823
  ty: plan.ty,
66824
+ yawRad: plan.yawRad ?? 0,
66825
+ ...plan.space === "world" ? { space: "world" } : {},
65695
66826
  data: new import_mongodb110.Binary(plan.data),
65696
66827
  updatedAt: at2,
65697
66828
  updatedBy: plan.updatedBy
@@ -65969,549 +67100,7 @@ function useRobotLiftSessionRepo() {
65969
67100
  // src/controllers/robot-map.controller.ts
65970
67101
  var import_joi78 = __toESM(require("joi"));
65971
67102
  var import_node_server_utils165 = require("@7365admin1/node-server-utils");
65972
-
65973
- // src/utils/rmf-building.util.ts
65974
- var PLAN_W_M2 = 40;
65975
- var PLAN_H_M2 = 26;
65976
- var DEFAULT_PLAN_FRAME = { minX: 0, maxX: PLAN_W_M2, minY: -PLAN_H_M2, maxY: 0 };
65977
- var WELD_M = 0.01;
65978
- var r3 = (v) => Math.round(v * 1e3) / 1e3;
65979
- var clamp2 = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
65980
- function floorLabel(floorNo2) {
65981
- return floorNo2 < 0 ? `B${-floorNo2}` : floorNo2 === 0 ? "G" : `L${floorNo2}`;
65982
- }
65983
- function floorNoFromName(name) {
65984
- if (typeof name !== "string")
65985
- return null;
65986
- const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
65987
- if (m)
65988
- return m[1].toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
65989
- return /^G$/i.test(name.trim()) ? 0 : null;
65990
- }
65991
- function toPlan(f, p) {
65992
- const w = f.maxX - f.minX || 1;
65993
- const h = f.maxY - f.minY || 1;
65994
- return { x: r3((p.x - f.minX) / w * PLAN_W_M2), y: r3((f.maxY - p.y) / h * PLAN_H_M2) };
65995
- }
65996
- function fromPlan(f, p) {
65997
- return { x: r3(f.minX + p.x / PLAN_W_M2 * (f.maxX - f.minX)), y: r3(f.maxY - p.y / PLAN_H_M2 * (f.maxY - f.minY)) };
65998
- }
65999
- function vertexPool(level2) {
66000
- let next = level2.vertices.reduce((n, v) => Math.max(n, Number(/^v(\d+)$/.exec(v.id)?.[1] ?? 0)), 0) + 1;
66001
- const byId = new Map(level2.vertices.map((v) => [v.id, v]));
66002
- function at2(p, extra) {
66003
- const x = r3(p.x);
66004
- const y = r3(p.y);
66005
- const hit = level2.vertices.find((v2) => Math.abs(v2.x - x) < WELD_M && Math.abs(v2.y - y) < WELD_M);
66006
- if (hit) {
66007
- if (extra?.name && !hit.name)
66008
- hit.name = extra.name;
66009
- if (extra?.params && Object.keys(extra.params).length)
66010
- hit.params = { ...hit.params ?? {}, ...extra.params };
66011
- return hit.id;
66012
- }
66013
- const v = { id: `v${next++}`, x, y, ...extra?.name ? { name: extra.name } : {}, ...extra?.params && Object.keys(extra.params).length ? { params: extra.params } : {} };
66014
- level2.vertices.push(v);
66015
- byId.set(v.id, v);
66016
- return v.id;
66017
- }
66018
- return { at: at2, get: (id) => byId.get(id) };
66019
- }
66020
- function emptyLevel(name, floorNo2, elevationM, planFrame) {
66021
- return { name, floorNo: floorNo2, elevationM, planFrame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [] };
66022
- }
66023
- function emptyRmf(source = "editor") {
66024
- return { formatVersion: 1, coordinateSystem: "cartesian_meters", source, graphs: [], levels: [], lifts: [] };
66025
- }
66026
- var collapseDoor = (t) => t === "sliding" || t === "double_sliding" ? "sliding" : "hinged";
66027
- function pruneVertices(level2) {
66028
- const used = /* @__PURE__ */ new Set();
66029
- const add = (...ids2) => ids2.forEach((i) => used.add(i));
66030
- level2.walls.forEach((e) => add(e.v1, e.v2));
66031
- level2.doors.forEach((e) => add(e.v1, e.v2));
66032
- level2.lanes.forEach((e) => add(e.v1, e.v2));
66033
- level2.measurements.forEach((e) => add(e.v1, e.v2));
66034
- [...level2.floors, ...level2.holes, ...level2.zones].forEach((p) => add(...p.vertices));
66035
- level2.vertices = level2.vertices.filter((v) => used.has(v.id) || v.name || v.params && Object.keys(v.params).length);
66036
- }
66037
- function msgParams(params) {
66038
- const out = {};
66039
- for (const p of params ?? []) {
66040
- if (!p?.name)
66041
- continue;
66042
- out[p.name] = p.type === 1 ? String(p.value_string ?? "") : p.type === 2 ? Number(p.value_int ?? 0) : p.type === 3 ? Number(p.value_float ?? 0) : p.type === 4 ? Boolean(p.value_bool) : true;
66043
- }
66044
- return out;
66045
- }
66046
- var VERTEX_PARAM_KEYS = [
66047
- "is_charger",
66048
- "is_parking_spot",
66049
- "is_holding_point",
66050
- "is_passthrough_point",
66051
- "is_cleaning_zone",
66052
- "dock_name",
66053
- "spawn_robot_name",
66054
- "spawn_robot_type",
66055
- "lift_cabin",
66056
- "merge_radius",
66057
- "mutex"
66058
- ];
66059
- function vertexParams(raw) {
66060
- const out = {};
66061
- for (const k of VERTEX_PARAM_KEYS) {
66062
- const v = raw[k];
66063
- if (v === void 0 || v === "" || v === false)
66064
- continue;
66065
- out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? Number(v) : String(v).slice(0, 60);
66066
- }
66067
- return out;
66068
- }
66069
- var MSG_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "sliding", 4: "double_sliding", 5: "hinged", 6: "double_hinged" };
66070
- function importFrame(level2) {
66071
- const xs = [];
66072
- const ys = [];
66073
- for (const g of level2.nav_graphs ?? [])
66074
- for (const v of g.vertices ?? [])
66075
- xs.push(v.x), ys.push(v.y);
66076
- for (const d of level2.doors ?? [])
66077
- xs.push(d.v1_x, d.v2_x), ys.push(d.v1_y, d.v2_y);
66078
- if (!xs.length)
66079
- for (const v of level2.wall_graph?.vertices ?? [])
66080
- xs.push(v.x), ys.push(v.y);
66081
- if (!xs.length)
66082
- return { ...DEFAULT_PLAN_FRAME };
66083
- const pad = 3;
66084
- return { minX: r3(Math.min(...xs) - pad), maxX: r3(Math.max(...xs) + pad), minY: r3(Math.min(...ys) - pad), maxY: r3(Math.max(...ys) + pad) };
66085
- }
66086
- var rot = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
66087
- function rmfFromFleetCore(msg) {
66088
- const rmf = emptyRmf("fleet-core");
66089
- const graphIdx = /* @__PURE__ */ new Map();
66090
- const usedFloors = /* @__PURE__ */ new Set();
66091
- for (const [i, lv] of (msg.levels ?? []).slice(0, 200).entries()) {
66092
- let floorNo2 = floorNoFromName(lv.name) ?? i + 1;
66093
- while (usedFloors.has(floorNo2))
66094
- floorNo2++;
66095
- usedFloors.add(floorNo2);
66096
- const level2 = emptyLevel(String(lv.name).slice(0, 60), floorNo2, Number(lv.elevation ?? 0), importFrame(lv));
66097
- const pool = vertexPool(level2);
66098
- const wg = lv.wall_graph;
66099
- for (const e of (wg?.edges ?? []).slice(0, 5e3)) {
66100
- const a = wg.vertices[e.v1_idx];
66101
- const b = wg.vertices[e.v2_idx];
66102
- if (a && b)
66103
- level2.walls.push({ v1: pool.at(a), v2: pool.at(b) });
66104
- }
66105
- for (const d of (lv.doors ?? []).slice(0, 500)) {
66106
- level2.doors.push({
66107
- name: String(d.name).slice(0, 60),
66108
- v1: pool.at({ x: d.v1_x, y: d.v1_y }),
66109
- v2: pool.at({ x: d.v2_x, y: d.v2_y }),
66110
- type: MSG_DOOR_TYPE[d.door_type] ?? "hinged",
66111
- ...d.motion_range ? { motionDegrees: r3(d.motion_range * 180 / Math.PI) } : {},
66112
- ...d.motion_direction ? { motionDirection: d.motion_direction < 0 ? -1 : 1 } : {}
66113
- });
66114
- }
66115
- for (const [gi, g] of (lv.nav_graphs ?? []).entries()) {
66116
- const key = String(g.name ?? gi);
66117
- if (!graphIdx.has(key)) {
66118
- const n = Number(key);
66119
- graphIdx.set(key, Number.isInteger(n) && n >= 0 && n <= 8 ? n : Math.min(8, graphIdx.size));
66120
- }
66121
- const idx = graphIdx.get(key);
66122
- const ids2 = (g.vertices ?? []).map((v) => pool.at(v, { name: v.name ? String(v.name).slice(0, 60) : void 0, params: vertexParams(msgParams(v.params)) }));
66123
- for (const e of (g.edges ?? []).slice(0, 5e3)) {
66124
- const a = ids2[e.v1_idx];
66125
- const b = ids2[e.v2_idx];
66126
- if (!a || !b || a === b)
66127
- continue;
66128
- const p = msgParams(e.params);
66129
- level2.lanes.push({
66130
- v1: a,
66131
- v2: b,
66132
- graphIdx: idx,
66133
- bidirectional: (e.edge_type ?? 0) === 0,
66134
- ...Number(p.speed_limit) > 0 ? { speedLimit: Number(p.speed_limit) } : {},
66135
- ...p.mutex ? { mutex: String(p.mutex).slice(0, 60) } : {}
66136
- });
66137
- }
66138
- }
66139
- rmf.levels.push(level2);
66140
- }
66141
- rmf.graphs = [...new Set(graphIdx.values())].sort((a, b) => a - b).map((idx) => ({ idx, name: `Graph ${idx}`, brands: ["fleet-core"] }));
66142
- rmf.referenceLevel = rmf.levels[0]?.name;
66143
- const levelNames = new Set(rmf.levels.map((l) => l.name));
66144
- for (const l of (msg.lifts ?? []).slice(0, 50)) {
66145
- const yaw = Number(l.ref_yaw ?? 0);
66146
- const doors = (l.doors ?? []).slice(0, 8).map((d) => {
66147
- const a = rot(d.v1_x - l.ref_x, d.v1_y - l.ref_y, -yaw);
66148
- const b = rot(d.v2_x - l.ref_x, d.v2_y - l.ref_y, -yaw);
66149
- return {
66150
- name: String(d.name).slice(0, 60),
66151
- type: d.door_type === 2 || d.door_type === 4 ? "double_sliding" : "sliding",
66152
- x: r3((a.x + b.x) / 2),
66153
- y: r3((a.y + b.y) / 2),
66154
- widthM: r3(Math.hypot(b.x - a.x, b.y - a.y)),
66155
- axisYawRad: r3(Math.atan2(b.y - a.y, b.x - a.x))
66156
- };
66157
- });
66158
- const served = (l.levels ?? []).filter((n) => levelNames.has(n));
66159
- rmf.lifts.push({
66160
- name: String(l.name).slice(0, 60),
66161
- x: r3(l.ref_x),
66162
- y: r3(l.ref_y),
66163
- yawRad: r3(yaw),
66164
- widthM: r3(l.width),
66165
- depthM: r3(l.depth),
66166
- referenceFloor: served[0] ?? rmf.referenceLevel ?? "",
66167
- levelDoors: served.map((level2) => ({ level: level2, doors: doors.map((d) => d.name) })),
66168
- doors
66169
- });
66170
- }
66171
- return rmf;
66172
- }
66173
- function legacyFromRmf(rmf) {
66174
- const levels = [];
66175
- const doors = [];
66176
- for (const lv of rmf.levels) {
66177
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
66178
- const p = (id) => {
66179
- const q = v.get(id);
66180
- return q ? toPlan(lv.planFrame, q) : null;
66181
- };
66182
- const walls = lv.walls.flatMap((w) => {
66183
- const a = p(w.v1);
66184
- const b = p(w.v2);
66185
- return a && b ? [{ start: a, end: b }] : [];
66186
- });
66187
- const zones = lv.zones.flatMap((z5) => {
66188
- const points = z5.vertices.map(p).filter((q) => !!q);
66189
- return points.length >= 3 ? [{ name: z5.name, points: points.slice(0, 200) }] : [];
66190
- });
66191
- levels.push({ floorNo: lv.floorNo, name: lv.name, elevationM: lv.elevationM, walls: walls.slice(0, 2e3), zones: zones.slice(0, 200) });
66192
- for (const d of lv.doors) {
66193
- const a = p(d.v1);
66194
- const b = p(d.v2);
66195
- if (a && b)
66196
- doors.push({ name: d.name, floorNo: lv.floorNo, type: collapseDoor(d.type), start: a, end: b });
66197
- }
66198
- }
66199
- const byName = new Map(rmf.levels.map((l) => [l.name, l]));
66200
- const lifts = [];
66201
- for (const l of rmf.lifts) {
66202
- const withDoors = l.levelDoors.filter((x) => x.doors.length).map((x) => byName.get(x.level)?.floorNo);
66203
- let floors = [...new Set(withDoors.filter((n) => typeof n === "number"))];
66204
- if (floors.length < 2)
66205
- floors = rmf.levels.map((x) => x.floorNo);
66206
- if (floors.length < 2)
66207
- continue;
66208
- const ref = byName.get(l.referenceFloor) ?? rmf.levels[0];
66209
- if (!ref)
66210
- continue;
66211
- const c = toPlan(ref.planFrame, l);
66212
- const f = ref.planFrame;
66213
- lifts.push({
66214
- name: l.name,
66215
- x: c.x,
66216
- y: c.y,
66217
- widthM: r3(clamp2(l.widthM / (f.maxX - f.minX || 1) * PLAN_W_M2, 0.5, 10)),
66218
- depthM: r3(clamp2(l.depthM / (f.maxY - f.minY || 1) * PLAN_H_M2, 0.5, 10)),
66219
- floors: floors.sort((a, b) => a - b)
66220
- });
66221
- }
66222
- return { levels, doors: doors.slice(0, 500), lifts };
66223
- }
66224
- var defaultCabinDoor = (l) => ({
66225
- name: "door1",
66226
- type: "double_sliding",
66227
- x: r3(l.widthM / 2),
66228
- y: 0,
66229
- widthM: r3(Math.min(1.2, l.depthM * 0.8)),
66230
- axisYawRad: r3(Math.PI / 2)
66231
- });
66232
- function mergeLegacyIntoRmf(prev, legacy) {
66233
- const base = prev ? structuredClone(prev) : emptyRmf("editor");
66234
- const refFrame = base.levels[0]?.planFrame ?? DEFAULT_PLAN_FRAME;
66235
- const legacyFloors = new Map((legacy.levels ?? []).map((l) => [l.floorNo, l]));
66236
- const allFloors = /* @__PURE__ */ new Set([
66237
- ...legacyFloors.keys(),
66238
- ...(legacy.doors ?? []).map((d) => d.floorNo),
66239
- ...(legacy.lifts ?? []).flatMap((l) => l.floors)
66240
- ]);
66241
- for (const floorNo2 of allFloors) {
66242
- if (base.levels.some((l) => l.floorNo === floorNo2))
66243
- continue;
66244
- base.levels.push(emptyLevel(legacyFloors.get(floorNo2)?.name || floorLabel(floorNo2), floorNo2, legacyFloors.get(floorNo2)?.elevationM ?? 0, { ...refFrame }));
66245
- }
66246
- base.levels.sort((a, b) => a.floorNo - b.floorNo);
66247
- for (const lv of base.levels) {
66248
- const src = legacyFloors.get(lv.floorNo);
66249
- if (src?.name)
66250
- lv.name = String(src.name).slice(0, 60);
66251
- if (typeof src?.elevationM === "number")
66252
- lv.elevationM = src.elevationM;
66253
- const prevDoors = new Map(lv.doors.map((d) => [d.name, d]));
66254
- lv.walls = [];
66255
- lv.zones = [];
66256
- lv.doors = [];
66257
- const pool = vertexPool(lv);
66258
- const at2 = (p) => pool.at(fromPlan(lv.planFrame, p));
66259
- for (const w of src?.walls ?? [])
66260
- lv.walls.push({ v1: at2(w.start), v2: at2(w.end) });
66261
- for (const z5 of src?.zones ?? [])
66262
- lv.zones.push({ name: z5.name, vertices: z5.points.map(at2) });
66263
- for (const d of (legacy.doors ?? []).filter((x) => x.floorNo === lv.floorNo)) {
66264
- const was = prevDoors.get(d.name);
66265
- const keep = was && collapseDoor(was.type) === d.type;
66266
- lv.doors.push({
66267
- ...keep ? was : {},
66268
- name: d.name,
66269
- v1: at2(d.start),
66270
- v2: at2(d.end),
66271
- type: keep ? was.type : d.type
66272
- });
66273
- }
66274
- pruneVertices(lv);
66275
- }
66276
- const prevLifts = new Map(base.lifts.map((l) => [l.name, l]));
66277
- const byFloor = new Map(base.levels.map((l) => [l.floorNo, l]));
66278
- base.lifts = (legacy.lifts ?? []).map((l) => {
66279
- const was = prevLifts.get(l.name);
66280
- const ref = was && base.levels.find((x) => x.name === was.referenceFloor) || byFloor.get(l.floors[0]) || base.levels[0];
66281
- const f = ref.planFrame;
66282
- const c = fromPlan(f, l);
66283
- const widthM = r3(l.widthM / PLAN_W_M2 * (f.maxX - f.minX));
66284
- const depthM = r3(l.depthM / PLAN_H_M2 * (f.maxY - f.minY));
66285
- const doors = was?.doors?.length ? was.doors : [defaultCabinDoor({ widthM, depthM })];
66286
- const served = l.floors.map((n) => byFloor.get(n)?.name).filter((n) => !!n);
66287
- const prevLevelDoors = new Map((was?.levelDoors ?? []).map((x) => [x.level, x.doors]));
66288
- return {
66289
- name: l.name,
66290
- x: c.x,
66291
- y: c.y,
66292
- yawRad: was?.yawRad ?? 0,
66293
- widthM,
66294
- depthM,
66295
- referenceFloor: ref.name,
66296
- ...was?.initialFloor && served.includes(was.initialFloor) ? { initialFloor: was.initialFloor } : {},
66297
- doors,
66298
- levelDoors: served.map((level2) => ({ level: level2, doors: prevLevelDoors.get(level2)?.length ? prevLevelDoors.get(level2) : doors.map((d) => d.name) }))
66299
- };
66300
- });
66301
- base.referenceLevel = base.levels.find((l) => l.name === base.referenceLevel)?.name ?? base.levels[0]?.name;
66302
- return base;
66303
- }
66304
- function rmfProblem(rmf) {
66305
- const levelNames = /* @__PURE__ */ new Set();
66306
- const doorNames = /* @__PURE__ */ new Set();
66307
- const graphIdx = new Set(rmf.graphs.map((g) => g.idx));
66308
- for (const lv of rmf.levels) {
66309
- if (levelNames.has(lv.name))
66310
- return `Two floors are both called "${lv.name}".`;
66311
- levelNames.add(lv.name);
66312
- const f = lv.planFrame;
66313
- if (!(f.maxX > f.minX && f.maxY > f.minY))
66314
- return `Floor ${lv.name}: its plan frame is empty.`;
66315
- const ids2 = /* @__PURE__ */ new Set();
66316
- for (const v of lv.vertices) {
66317
- if (ids2.has(v.id))
66318
- return `Floor ${lv.name}: point id "${v.id}" is used twice.`;
66319
- ids2.add(v.id);
66320
- }
66321
- const missing = (id) => !ids2.has(id);
66322
- const edges = [...lv.walls, ...lv.doors, ...lv.lanes, ...lv.measurements];
66323
- if (edges.some((e) => missing(e.v1) || missing(e.v2)))
66324
- return `Floor ${lv.name}: a line ends at a point that does not exist.`;
66325
- if ([...lv.floors, ...lv.holes, ...lv.zones].some((p) => p.vertices.some(missing)))
66326
- return `Floor ${lv.name}: an area uses a point that does not exist.`;
66327
- for (const d of lv.doors) {
66328
- if (doorNames.has(d.name))
66329
- return `Two doors are both called "${d.name}" - door names must be unique in the building.`;
66330
- doorNames.add(d.name);
66331
- }
66332
- if (lv.lanes.some((l) => !graphIdx.has(l.graphIdx)))
66333
- return `Floor ${lv.name}: a lane belongs to a route graph that is not listed.`;
66334
- }
66335
- for (const l of rmf.lifts) {
66336
- const cabin = new Set(l.doors.map((d) => d.name));
66337
- if (l.referenceFloor && !levelNames.has(l.referenceFloor))
66338
- return `Lift ${l.name}: its reference floor "${l.referenceFloor}" does not exist.`;
66339
- for (const x of l.levelDoors) {
66340
- if (!levelNames.has(x.level))
66341
- return `Lift ${l.name}: floor "${x.level}" does not exist.`;
66342
- if (x.doors.some((d) => !cabin.has(d)))
66343
- return `Lift ${l.name}: floor ${x.level} opens a cabin door the lift does not have.`;
66344
- }
66345
- }
66346
- return null;
66347
- }
66348
- var P = { str: (v) => [1, v], int: (v) => [2, Math.round(v)], dbl: (v) => [3, v], bool: (v) => [4, v] };
66349
- function toBuildingYaml(name, rmf) {
66350
- const levels = {};
66351
- for (const lv of rmf.levels) {
66352
- const idx = new Map(lv.vertices.map((v, i) => [v.id, i]));
66353
- const edge2 = (v1, v2, params) => [idx.get(v1), idx.get(v2), params];
66354
- levels[lv.name] = {
66355
- elevation: lv.elevationM,
66356
- vertices: lv.vertices.map((v) => {
66357
- const params = {};
66358
- for (const [k, val] of Object.entries(v.params ?? {})) {
66359
- params[k] = typeof val === "boolean" ? P.bool(val) : typeof val === "number" ? P.dbl(val) : P.str(String(val));
66360
- }
66361
- return [v.x, v.y, 0, v.name ?? "", params];
66362
- }),
66363
- walls: lv.walls.map((w) => edge2(w.v1, w.v2, {})),
66364
- doors: lv.doors.map(
66365
- (d) => edge2(d.v1, d.v2, {
66366
- name: P.str(d.name),
66367
- type: P.str(d.type),
66368
- motion_axis: P.str(d.motionAxis ?? "start"),
66369
- motion_degrees: P.dbl(d.motionDegrees ?? 90),
66370
- motion_direction: P.int(d.motionDirection ?? 1),
66371
- right_left_ratio: P.dbl(d.rightLeftRatio ?? 1)
66372
- })
66373
- ),
66374
- lanes: lv.lanes.map(
66375
- (l) => edge2(l.v1, l.v2, {
66376
- graph_idx: P.int(l.graphIdx),
66377
- bidirectional: P.bool(l.bidirectional),
66378
- orientation: P.str(l.orientation ?? ""),
66379
- ...l.speedLimit ? { speed_limit: P.dbl(l.speedLimit) } : {},
66380
- ...l.mutex ? { mutex: P.str(l.mutex) } : {}
66381
- })
66382
- ),
66383
- measurements: lv.measurements.map((m) => edge2(m.v1, m.v2, { distance: P.dbl(m.distanceM) })),
66384
- floors: lv.floors.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
66385
- holes: lv.holes.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
66386
- fiducials: lv.fiducials.map((f) => [f.x, f.y, f.name]),
66387
- layers: {},
66388
- models: []
66389
- };
66390
- }
66391
- const elevation = new Map(rmf.levels.map((l) => [l.name, l.elevationM]));
66392
- const lifts = {};
66393
- for (const l of rmf.lifts) {
66394
- const served = l.levelDoors.map((x) => x.level).sort((a, b) => (elevation.get(a) ?? 0) - (elevation.get(b) ?? 0));
66395
- lifts[l.name] = {
66396
- x: l.x,
66397
- y: l.y,
66398
- yaw: l.yawRad,
66399
- width: l.widthM,
66400
- depth: l.depthM,
66401
- reference_floor_name: l.referenceFloor,
66402
- initial_floor_name: l.initialFloor ?? served[0] ?? l.referenceFloor,
66403
- lowest_floor: served[0] ?? l.referenceFloor,
66404
- highest_floor: served[served.length - 1] ?? l.referenceFloor,
66405
- doors: Object.fromEntries(
66406
- l.doors.map((d) => [d.name, { door_type: d.type === "double_sliding" ? 2 : 1, x: d.x, y: d.y, width: d.widthM, motion_axis_orientation: d.axisYawRad }])
66407
- ),
66408
- level_doors: Object.fromEntries(l.levelDoors.map((x) => [x.level, x.doors])),
66409
- plugins: true
66410
- };
66411
- }
66412
- return JSON.stringify(
66413
- { name, coordinate_system: "cartesian_meters", reference_level_name: rmf.referenceLevel ?? rmf.levels[0]?.name ?? "", graphs: {}, parameters: {}, levels, lifts },
66414
- null,
66415
- 1
66416
- );
66417
- }
66418
- function segmentsIntersect(a, b, c, d) {
66419
- const det = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
66420
- if (Math.abs(det) < 0.01)
66421
- return false;
66422
- const t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / det;
66423
- const u = -((a.x - b.x) * (a.y - c.y) - (a.y - b.y) * (a.x - c.x)) / det;
66424
- return t >= 0 && t <= 1 && u >= 0 && u <= 1;
66425
- }
66426
- function inLift(p, l) {
66427
- const q = rot(p.x - l.x, p.y - l.y, -l.yawRad);
66428
- return Math.abs(q.x) <= l.widthM / 2 && Math.abs(q.y) <= l.depthM / 2;
66429
- }
66430
- function toNavGraphs(name, rmf) {
66431
- const out = {};
66432
- for (let gi = 0; gi <= 8; gi++) {
66433
- const levels = {};
66434
- const doors = {};
66435
- let empty = true;
66436
- for (const lv of rmf.levels) {
66437
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
66438
- const lanes = lv.lanes.filter((l) => l.graphIdx === gi);
66439
- if (lanes.length)
66440
- empty = false;
66441
- const order = [];
66442
- const mapped = /* @__PURE__ */ new Map();
66443
- for (const l of lanes)
66444
- for (const id of [l.v1, l.v2])
66445
- if (!mapped.has(id))
66446
- mapped.set(id, order.push(id) - 1);
66447
- const lifts2 = rmf.lifts.filter((l) => l.levelDoors.some((x) => x.level === lv.name && x.doors.length));
66448
- const vertices = order.map((id) => {
66449
- const q = v.get(id);
66450
- const lift2 = lifts2.find((l) => inLift(q, l));
66451
- return [q.x, q.y, { name: q.name ?? "", ...q.params ?? {}, ...lift2 ? { lift: lift2.name } : {} }];
66452
- });
66453
- const navLanes = [];
66454
- for (const l of lanes) {
66455
- const a = v.get(l.v1);
66456
- const b = v.get(l.v2);
66457
- const p = {};
66458
- for (const d of lv.doors) {
66459
- const c = v.get(d.v1);
66460
- const e = v.get(d.v2);
66461
- if (c && e && segmentsIntersect(a, b, c, e))
66462
- p.door_name = d.name;
66463
- }
66464
- if (l.orientation)
66465
- p.orientation_constraint = l.orientation;
66466
- if (l.speedLimit && l.speedLimit > 0)
66467
- p.speed_limit = l.speedLimit;
66468
- if (l.mutex)
66469
- p.mutex = l.mutex;
66470
- const endDock = b.params?.dock_name;
66471
- const startDock = a.params?.dock_name;
66472
- const s = mapped.get(l.v1);
66473
- const t = mapped.get(l.v2);
66474
- if (l.bidirectional) {
66475
- const fwd = { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} };
66476
- const back = { ...p, ...endDock ? { undock_name: endDock } : {}, ...startDock ? { dock_name: startDock } : {} };
66477
- if (l.orientation)
66478
- back.orientation_constraint = l.orientation === "forward" ? "backward" : "forward";
66479
- navLanes.push([s, t, fwd], [t, s, back]);
66480
- } else {
66481
- navLanes.push([s, t, { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} }]);
66482
- }
66483
- }
66484
- levels[lv.name] = { vertices, lanes: navLanes };
66485
- for (const d of lv.doors) {
66486
- const c = v.get(d.v1);
66487
- const e = v.get(d.v2);
66488
- if (c && e)
66489
- doors[d.name] = { endpoints: [[c.x, c.y], [e.x, e.y]], map: lv.name };
66490
- }
66491
- }
66492
- if (empty)
66493
- continue;
66494
- const lifts = Object.fromEntries(rmf.lifts.map((l) => [l.name, { position: [l.x, l.y, l.yawRad], dims: [l.widthM, l.depthM] }]));
66495
- out[gi] = JSON.stringify({ building_name: name, levels, lifts, doors }, null, 1);
66496
- }
66497
- return out;
66498
- }
66499
- function rmfSummary(rmf) {
66500
- if (!rmf)
66501
- return null;
66502
- const sum = (f) => rmf.levels.reduce((n, l) => n + f(l), 0);
66503
- return {
66504
- source: rmf.source ?? "editor",
66505
- levels: rmf.levels.length,
66506
- lanes: sum((l) => l.lanes.length),
66507
- waypoints: sum((l) => l.vertices.filter((v) => v.name).length),
66508
- doors: sum((l) => l.doors.length),
66509
- lifts: rmf.lifts.length,
66510
- graphs: rmf.graphs.length
66511
- };
66512
- }
66513
-
66514
- // src/controllers/robot-map.controller.ts
67103
+ var import_js_yaml = require("js-yaml");
66515
67104
  function useRobotMapController(deps) {
66516
67105
  const now = () => deps?.now?.() ?? Date.now();
66517
67106
  const robots = () => useRobotRepo();
@@ -66708,6 +67297,32 @@ function useRobotMapController(deps) {
66708
67297
  fail(next, e);
66709
67298
  }
66710
67299
  }
67300
+ async function importBuildingFile(req, res, next) {
67301
+ const { error, value } = buildingFileImportSchema.validate(req.body ?? {});
67302
+ if (error)
67303
+ return fail(next, new import_node_server_utils165.BadRequestError(error.message));
67304
+ try {
67305
+ if (/(^|[\s[{,:-])[&*][A-Za-z0-9_-]+/m.test(value.text.replace(/'[^'\n]*'|"[^"\n]*"/g, "''"))) {
67306
+ throw new import_node_server_utils165.BadRequestError("This file uses YAML anchors or aliases, which building files never contain. Export it again from the traffic editor.");
67307
+ }
67308
+ let doc;
67309
+ try {
67310
+ doc = (0, import_js_yaml.load)(value.text, { schema: import_js_yaml.CORE_SCHEMA, json: true });
67311
+ } catch (e) {
67312
+ throw new import_node_server_utils165.BadRequestError(`This file is not valid YAML: ${String(e?.reason ?? e?.message ?? "unreadable").slice(0, 120)}.`);
67313
+ }
67314
+ const out = value.format === "nav" ? { name: "", ...fromNavGraph(doc, value.graph) } : fromBuildingYaml(doc);
67315
+ const checked = rmfBuildingSchema.validate(out.rmf);
67316
+ if (checked.error)
67317
+ throw new import_node_server_utils165.BadRequestError(`This file cannot be used: ${checked.error.message}`);
67318
+ const problem = rmfProblem(checked.value);
67319
+ if (problem)
67320
+ throw new import_node_server_utils165.BadRequestError(`This file cannot be used: ${problem}`);
67321
+ res.json({ format: value.format, name: out.name, rmf: checked.value, summary: rmfSummary(checked.value), warnings: out.warnings });
67322
+ } catch (e) {
67323
+ fail(next, e instanceof RmfImportError ? new import_node_server_utils165.BadRequestError(e.message) : e);
67324
+ }
67325
+ }
66711
67326
  const floorParam = import_joi78.default.number().integer().min(-20).max(200).required();
66712
67327
  function sniffImage(buf) {
66713
67328
  if (buf.length > 8 && buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
@@ -66743,6 +67358,8 @@ function useRobotMapController(deps) {
66743
67358
  metersPerPixel: value.metersPerPixel,
66744
67359
  tx: value.tx,
66745
67360
  ty: value.ty,
67361
+ yawRad: value.yawRad,
67362
+ space: value.space,
66746
67363
  updatedBy: callerId(req) ?? "",
66747
67364
  ...data ? { data, mime, bytes: data.length } : {}
66748
67365
  });
@@ -67002,6 +67619,7 @@ function useRobotMapController(deps) {
67002
67619
  return {
67003
67620
  getOpenRmfBuilding,
67004
67621
  exportMap,
67622
+ importBuildingFile,
67005
67623
  putFloorPlan,
67006
67624
  getFloorPlan,
67007
67625
  deleteFloorPlan,
@@ -101339,6 +101957,7 @@ function usePersonalEmergencyChainController() {
101339
101957
  attendanceSchema,
101340
101958
  attendanceSettingsSchema,
101341
101959
  buildSelfServiceEmailContext,
101960
+ buildingFileImportSchema,
101342
101961
  buildingFromRmf,
101343
101962
  buildingInPlanFrame,
101344
101963
  buildingMapBodySchema,
@@ -101592,6 +102211,7 @@ function usePersonalEmergencyChainController() {
101592
102211
  resolveInviteActor,
101593
102212
  resolveSiteTimezone,
101594
102213
  resolveStaffRole,
102214
+ rmfBuilding,
101595
102215
  rmfBuildingSchema,
101596
102216
  robotActionsFor,
101597
102217
  robotBrandFor,