@7365admin1/core 3.110.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,
@@ -4661,7 +4663,8 @@ function useMemberRepo() {
4661
4663
  type,
4662
4664
  status,
4663
4665
  // 3: rows carry roleState (2026-09-25) — older cached pages lack it.
4664
- projectionVersion: 3
4666
+ // 4: roleState "other-site" + roleSiteName.
4667
+ projectionVersion: 4
4665
4668
  };
4666
4669
  if (org) {
4667
4670
  try {
@@ -4719,10 +4722,21 @@ function useMemberRepo() {
4719
4722
  localField: "role",
4720
4723
  foreignField: "_id",
4721
4724
  as: "roles",
4722
- pipeline: [{ $project: { name: 1, org: 1, status: 1 } }]
4725
+ pipeline: [{ $project: { name: 1, org: 1, site: 1, status: 1 } }]
4723
4726
  }
4724
4727
  },
4725
4728
  { $unwind: { path: "$roles", preserveNullAndEmptyArrays: true } },
4729
+ {
4730
+ // The site a site-pinned role belongs to, for the "belongs to
4731
+ // <site>" warning. An org-wide role stores site "" → no match.
4732
+ $lookup: {
4733
+ from: "sites",
4734
+ localField: "roles.site",
4735
+ foreignField: "_id",
4736
+ as: "roleSite",
4737
+ pipeline: [{ $project: { name: 1 } }]
4738
+ }
4739
+ },
4726
4740
  {
4727
4741
  $lookup: {
4728
4742
  from: "users",
@@ -4743,19 +4757,31 @@ function useMemberRepo() {
4743
4757
  // Whether roleName is a role this member can really use, so the
4744
4758
  // Members list never shows a bare name that grants nothing
4745
4759
  // (owner report 2026-09-25). "ok" | "template" (org-less shared
4746
- // role) | "deleted" | "other-org" | "missing" (no role, or an
4747
- // id that resolves to nothing).
4760
+ // role) | "deleted" | "other-org" | "other-site" (the org's role,
4761
+ // pinned to a different site than this membership's — an
4762
+ // org-wide role with no site stays "ok") | "missing" (no role,
4763
+ // or an id that resolves to nothing).
4748
4764
  roleState: {
4749
4765
  $switch: {
4750
4766
  branches: [
4751
4767
  { case: { $not: ["$roles._id"] }, then: "missing" },
4752
4768
  { case: { $ne: [{ $ifNull: ["$roles.status", "active"] }, "active"] }, then: "deleted" },
4753
4769
  { case: { $in: [{ $ifNull: ["$roles.org", ""] }, ["", null]] }, then: "template" },
4754
- { case: { $ne: [{ $toString: "$roles.org" }, { $toString: "$org" }] }, then: "other-org" }
4770
+ { case: { $ne: [{ $toString: "$roles.org" }, { $toString: "$org" }] }, then: "other-org" },
4771
+ {
4772
+ case: {
4773
+ $and: [
4774
+ { $not: [{ $in: [{ $ifNull: ["$roles.site", ""] }, ["", null]] }] },
4775
+ { $ne: [{ $toString: "$roles.site" }, { $toString: { $ifNull: ["$siteId", ""] } }] }
4776
+ ]
4777
+ },
4778
+ then: "other-site"
4779
+ }
4755
4780
  ],
4756
4781
  default: "ok"
4757
4782
  }
4758
4783
  },
4784
+ roleSiteName: { $first: "$roleSite.name" },
4759
4785
  org: 1,
4760
4786
  orgName: 1,
4761
4787
  status: 1,
@@ -10748,12 +10774,12 @@ function planFaultChanges(open, reading) {
10748
10774
  return { open: toOpen, clear };
10749
10775
  }
10750
10776
  function robotFaultSweepConfig(env2 = process.env) {
10751
- const num = (v, def, min, max) => {
10777
+ const num2 = (v, def, min, max) => {
10752
10778
  const n = Math.floor(Number(v));
10753
10779
  return Number.isFinite(n) && String(v ?? "").trim() !== "" ? Math.min(max, Math.max(min, n)) : def;
10754
10780
  };
10755
10781
  const enabled = String(env2.ROBOT_FAULT_SWEEP ?? "on").trim().toLowerCase() !== "off";
10756
- const asked = num(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
10782
+ const asked = num2(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
10757
10783
  const pick = (steps, v) => steps.filter((d) => d <= v).pop() ?? steps[0];
10758
10784
  const subMinute = asked < 60;
10759
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));
@@ -10763,9 +10789,9 @@ function robotFaultSweepConfig(env2 = process.env) {
10763
10789
  enabled,
10764
10790
  seconds,
10765
10791
  cron: cron2,
10766
- concurrency: num(env2.ROBOT_FAULT_SWEEP_CONCURRENCY, 4, 1, 16),
10767
- timeoutMs: num(env2.ROBOT_FAULT_SWEEP_TIMEOUT_MS, 1e4, 1e3, 6e4),
10768
- 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)
10769
10795
  };
10770
10796
  }
10771
10797
  function withTimeout(promise, ms, label2 = "Timed out") {
@@ -55466,8 +55492,8 @@ function encryptPayload(payloadHex) {
55466
55492
  );
55467
55493
  return encrypted.toString("base64");
55468
55494
  }
55469
- function toHex(num, length) {
55470
- return num.toString(16).padStart(length * 2, "0");
55495
+ function toHex(num2, length) {
55496
+ return num2.toString(16).padStart(length * 2, "0");
55471
55497
  }
55472
55498
  function buildPayload(cardNumber, validityMinutes) {
55473
55499
  const randomHex = import_crypto5.default.randomBytes(2).toString("hex");
@@ -55647,8 +55673,8 @@ function UseAccessManagementRepo() {
55647
55673
  }
55648
55674
  }
55649
55675
  function generateCardNo() {
55650
- const num = Math.floor(Math.random() * 65536);
55651
- return num.toString().padStart(10, "0");
55676
+ const num2 = Math.floor(Math.random() * 65536);
55677
+ return num2.toString().padStart(10, "0");
55652
55678
  }
55653
55679
  async function createQrData({
55654
55680
  cardNumber,
@@ -56888,13 +56914,13 @@ function UseAccessManagementRepo() {
56888
56914
  const prevCard = res && res?.[1]?.cardNo || "-1";
56889
56915
  const currentCard = res && res?.[0]?.cardNo || "0";
56890
56916
  let availableCardNo = [];
56891
- let num = parseInt(prevCard, 10) + 1;
56917
+ let num2 = parseInt(prevCard, 10) + 1;
56892
56918
  while (availableCardNo.length < (unit.length > 0 ? unit.length : quantity)) {
56893
- if (num === parseInt(currentCard, 10)) {
56894
- num++;
56919
+ if (num2 === parseInt(currentCard, 10)) {
56920
+ num2++;
56895
56921
  }
56896
- availableCardNo.push(num);
56897
- num++;
56922
+ availableCardNo.push(num2);
56923
+ num2++;
56898
56924
  }
56899
56925
  const cardNumbers = availableCardNo.map(
56900
56926
  (no2) => no2.toString().padStart(10, "0")
@@ -62451,13 +62477,13 @@ function parseRobotCommand(body) {
62451
62477
  if (has2(k))
62452
62478
  return { ok: false, message: `${k} is not valid for a ${kind} command.` };
62453
62479
  }
62454
- const num = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
62455
- if (!num("x") || !num("y"))
62480
+ const num2 = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
62481
+ if (!num2("x") || !num2("y"))
62456
62482
  return { ok: false, message: `${kind} needs x and y (metres).` };
62457
62483
  if (kind === "navigate") {
62458
62484
  if (has2("floorNo"))
62459
62485
  return { ok: false, message: "floorNo is not valid for a navigate command." };
62460
- if (has2("theta") && !num("theta"))
62486
+ if (has2("theta") && !num2("theta"))
62461
62487
  return { ok: false, message: "theta must be a number (radians)." };
62462
62488
  return {
62463
62489
  ok: true,
@@ -62469,7 +62495,7 @@ function parseRobotCommand(body) {
62469
62495
  }
62470
62496
  };
62471
62497
  }
62472
- if (!num("theta"))
62498
+ if (!num2("theta"))
62473
62499
  return { ok: false, message: "relocalize needs theta (radians)." };
62474
62500
  if (!Number.isInteger(b.floorNo))
62475
62501
  return { ok: false, message: "relocalize needs an integer floorNo." };
@@ -63847,7 +63873,25 @@ function buildingInPlanFrame(building) {
63847
63873
  const b = v2 && toPlan2(levels[i].name, v2.x, v2.y);
63848
63874
  return a && b ? [{ start: a, end: b }] : [];
63849
63875
  });
63850
- 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 };
63851
63895
  }),
63852
63896
  doors,
63853
63897
  lifts
@@ -64507,11 +64551,11 @@ function decodeTrackingFrame(data) {
64507
64551
  if (!parsed || typeof parsed !== "object")
64508
64552
  return null;
64509
64553
  const frame2 = parsed;
64510
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
64511
- const x = num(frame2.x);
64512
- const y = num(frame2.y);
64513
- const theta = num(frame2.theta);
64514
- 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);
64515
64559
  if (x === null || y === null || theta === null || statusFlag === null) {
64516
64560
  return null;
64517
64561
  }
@@ -64762,241 +64806,1315 @@ function buildingMapFromRobotMaps(name, maps, floorHeightM = 3) {
64762
64806
  return { name, levels, lifts: [] };
64763
64807
  }
64764
64808
 
64765
- // src/services/robot-tracking.service.ts
64766
- var import_axios4 = __toESM(require("axios"));
64767
- async function openWithAxios(url, body) {
64768
- const response = await import_axios4.default.post(url, body, {
64769
- responseType: "stream",
64770
- // No read timeout: this connection is SUPPOSED to stay open and mostly
64771
- // silent. A request timeout here would sever a healthy stream on a quiet
64772
- // robot. The idle watchdog is what decides a stream is dead, because it can
64773
- // tell silence from a closed socket.
64774
- timeout: 0,
64775
- headers: { "Content-Type": "application/json", Accept: "text/event-stream" }
64776
- });
64777
- 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}`;
64778
64845
  }
64779
- function startRobotTracking(options) {
64780
- const {
64781
- credentials,
64782
- robotSn,
64783
- onEvent,
64784
- baseUrl = ROBOT_CLOUD_BASE_URL,
64785
- idleTimeoutMs = TRACKING_IDLE_TIMEOUT_MS,
64786
- openStream = openWithAxios,
64787
- now = Date.now
64788
- } = options;
64789
- if (!baseUrl)
64790
- throw new Error("Robot cloud: ROBOT_CLOUD_BASE_URL is not configured.");
64791
- let stopped = false;
64792
- let attempt = 0;
64793
- let current = null;
64794
- let watchdog = null;
64795
- let retry = null;
64796
- let lastActivityAt = now();
64797
- let everConnected = false;
64798
- const parser = createSseParser();
64799
- function clearTimers() {
64800
- if (watchdog) {
64801
- clearInterval(watchdog);
64802
- watchdog = null;
64803
- }
64804
- if (retry) {
64805
- clearTimeout(retry);
64806
- retry = null;
64807
- }
64808
- }
64809
- function dropUpstream() {
64810
- if (!current)
64811
- return;
64812
- try {
64813
- current.destroy();
64814
- } 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;
64815
64875
  }
64816
- 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;
64817
64880
  }
64818
- function lose(reason) {
64819
- if (stopped)
64820
- return;
64821
- onEvent({ type: "lost", reason, at: now() });
64822
- dropUpstream();
64823
- 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;
64824
64906
  }
64825
- function scheduleReconnect() {
64826
- if (stopped)
64827
- return;
64828
- clearTimers();
64829
- const delay2 = trackingBackoffMs(attempt++);
64830
- 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);
64831
64932
  }
64832
- async function connect2() {
64833
- if (stopped)
64834
- return;
64835
- const body = robotCloudBody(
64836
- credentials.appid,
64837
- credentials.secret,
64838
- ROBOT_CLOUD_PATHS.tracking,
64839
- { robotSn }
64840
- );
64841
- let stream;
64842
- try {
64843
- stream = await openStream(
64844
- `${baseUrl.replace(/\/+$/, "")}${ROBOT_CLOUD_PATHS.tracking}`,
64845
- body
64846
- );
64847
- } catch (error) {
64848
- lose(error?.message ?? "Could not open the robot's tracking stream.");
64849
- 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) });
64850
64971
  }
64851
- if (stopped) {
64852
- try {
64853
- stream.destroy();
64854
- } catch {
64855
- }
64856
- 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
+ });
64857
64982
  }
64858
- parser.reset();
64859
- current = stream;
64860
- lastActivityAt = now();
64861
- if (everConnected)
64862
- onEvent({ type: "reconnected", at: now() });
64863
- everConnected = true;
64864
- attempt = 0;
64865
- stream.on("data", (chunk2) => {
64866
- if (stopped)
64867
- return;
64868
- const { events, sawActivity } = parser.push(chunk2.toString("utf8"));
64869
- if (sawActivity)
64870
- lastActivityAt = now();
64871
- for (const event of events) {
64872
- const pose = decodeTrackingFrame(event.data);
64873
- if (pose)
64874
- 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));
64875
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
+ });
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
+ };
64876
65025
  });
64877
- stream.on("error", (error) => lose(error?.message ?? "The tracking stream failed."));
64878
- stream.on("end", () => lose("The robot cloud closed the tracking stream."));
64879
- stream.on("close", () => {
64880
- if (!stopped && current === stream)
64881
- 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
64882
65037
  });
64883
- clearTimers();
64884
- watchdog = setInterval(() => {
64885
- if (stopped)
64886
- return;
64887
- if (now() - lastActivityAt >= idleTimeoutMs) {
64888
- lose("The robot stopped reporting.");
64889
- }
64890
- }, Math.max(1e3, Math.floor(idleTimeoutMs / 3)));
64891
65038
  }
64892
- void connect2();
64893
- return {
64894
- stop() {
64895
- if (stopped)
64896
- return;
64897
- stopped = true;
64898
- clearTimers();
64899
- dropUpstream();
64900
- }
64901
- };
65039
+ return rmf;
64902
65040
  }
64903
-
64904
- // src/controllers/robot-fleet.controller.ts
64905
- var import_joi76 = __toESM(require("joi"));
64906
- var import_node_server_utils163 = require("@7365admin1/node-server-utils");
64907
-
64908
- // src/services/robot-fault.service.ts
64909
- var import_node_server_utils162 = require("@7365admin1/node-server-utils");
64910
-
64911
- // src/repositories/robot-fault.repo.ts
64912
- var import_mongodb108 = require("mongodb");
64913
- var import_node_server_utils161 = require("@7365admin1/node-server-utils");
64914
- var toId3 = (v) => v instanceof import_mongodb108.ObjectId ? v : new import_mongodb108.ObjectId(String(v));
64915
- function useRobotFaultRepo() {
64916
- const db2 = import_node_server_utils161.useAtlas.getDb();
64917
- if (!db2)
64918
- throw new import_node_server_utils161.InternalServerError("Unable to connect to server.");
64919
- const collection = db2.collection(ROBOT_FAULTS_COLLECTION);
64920
- async function createIndex() {
64921
- try {
64922
- await collection.createIndexes([
64923
- {
64924
- key: { robotId: 1, code: 1 },
64925
- name: "one_open_fault_per_robot_code",
64926
- unique: true,
64927
- partialFilterExpression: { clearedAt: null }
64928
- },
64929
- { key: { clearedAt: 1, since: 1 }, name: "open_faults_by_since" }
64930
- ]);
64931
- } catch (error) {
64932
- 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 });
64933
65065
  }
64934
65066
  }
64935
- async function getOpenFaults() {
64936
- 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
+ });
64937
65089
  }
64938
- async function getOpenFault(robotId, code) {
64939
- 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 }));
64940
65113
  }
64941
- async function openFault(doc) {
64942
- const now = /* @__PURE__ */ new Date();
64943
- try {
64944
- const res = await collection.insertOne({
64945
- robotId: toId3(doc.robotId),
64946
- orgId: doc.orgId ? toId3(doc.orgId) : null,
64947
- siteId: doc.siteId ? toId3(doc.siteId) : null,
64948
- code: doc.code,
64949
- message: doc.message,
64950
- since: doc.since,
64951
- clearedAt: null,
64952
- notifiedAt: null,
64953
- 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
64954
65140
  });
64955
- return res.insertedId;
64956
- } catch (error) {
64957
- if (error?.code === 11e3)
64958
- return null;
64959
- throw error;
64960
65141
  }
65142
+ pruneVertices(lv);
64961
65143
  }
64962
- async function claimNotify(id) {
64963
- const res = await collection.updateOne(
64964
- { _id: toId3(id), clearedAt: null, notifiedAt: null },
64965
- { $set: { notifiedAt: /* @__PURE__ */ new Date() } }
64966
- );
64967
- return res.modifiedCount === 1;
64968
- }
64969
- async function claimOfflineAlert(id, cutoff) {
64970
- const res = await collection.updateOne(
64971
- { _id: toId3(id), code: "OFFLINE", clearedAt: null, since: { $lte: cutoff }, offlineNotifiedAt: null },
64972
- { $set: { offlineNotifiedAt: /* @__PURE__ */ new Date() } }
64973
- );
64974
- return res.modifiedCount === 1;
64975
- }
64976
- async function claimRecoveryAlert(id) {
64977
- const res = await collection.updateOne(
64978
- { _id: toId3(id), code: "OFFLINE", offlineNotifiedAt: { $ne: null }, recoveryNotifiedAt: null },
64979
- { $set: { recoveryNotifiedAt: /* @__PURE__ */ new Date() } }
64980
- );
64981
- return res.modifiedCount === 1;
64982
- }
64983
- async function findNotifiedOccurrence(robotId, code, since, after) {
64984
- const filter = {
64985
- clearedAt: { $gte: after },
64986
- robotId: toId3(robotId),
64987
- code,
64988
- notifiedAt: { $ne: null }
64989
- };
64990
- if (since)
64991
- filter.since = { $gte: new Date(since.getTime() - 1e3), $lte: new Date(since.getTime() + 1e3) };
64992
- return collection.findOne(filter, { projection: { notifiedAt: 1 } });
64993
- }
64994
- async function markNotified(id, at2) {
64995
- await collection.updateOne({ _id: toId3(id), notifiedAt: null }, { $set: { notifiedAt: at2 } });
64996
- }
64997
- async function clearFault(id) {
64998
- await collection.updateOne(
64999
- { _id: toId3(id), clearedAt: 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 }
66107
+ };
66108
+ if (since)
66109
+ filter.since = { $gte: new Date(since.getTime() - 1e3), $lte: new Date(since.getTime() + 1e3) };
66110
+ return collection.findOne(filter, { projection: { notifiedAt: 1 } });
66111
+ }
66112
+ async function markNotified(id, at2) {
66113
+ await collection.updateOne({ _id: toId3(id), notifiedAt: null }, { $set: { notifiedAt: at2 } });
66114
+ }
66115
+ async function clearFault(id) {
66116
+ await collection.updateOne(
66117
+ { _id: toId3(id), clearedAt: null },
65000
66118
  { $set: { clearedAt: /* @__PURE__ */ new Date() } }
65001
66119
  );
65002
66120
  }
@@ -65373,8 +66491,11 @@ var floorPlanBodySchema = import_joi77.default.object({
65373
66491
  widthPx: import_joi77.default.number().integer().min(1).max(1e4).required(),
65374
66492
  heightPx: import_joi77.default.number().integer().min(1).max(1e4).required(),
65375
66493
  metersPerPixel: import_joi77.default.number().min(1e-4).max(10).required(),
65376
- tx: import_joi77.default.number().min(-1e3).max(1e3).default(0),
65377
- 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")
65378
66499
  });
65379
66500
  var coord = import_joi77.default.number().min(-1e3).max(1e3).required();
65380
66501
  var point = import_joi77.default.object({ x: coord, y: coord });
@@ -65434,11 +66555,24 @@ var rmfLevel = import_joi77.default.object({
65434
66555
  spawn_robot_type: import_joi77.default.string().trim().max(60).allow(""),
65435
66556
  lift_cabin: import_joi77.default.string().trim().max(60).allow(""),
65436
66557
  merge_radius: import_joi77.default.number().min(0).max(100),
65437
- 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("")
65438
66562
  })
65439
66563
  })
65440
66564
  ).max(5e3).default([]),
65441
- 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([]),
65442
66576
  floors: import_joi77.default.array().items(polygon).max(200).default([]),
65443
66577
  holes: import_joi77.default.array().items(polygon).max(200).default([]),
65444
66578
  doors: import_joi77.default.array().items(
@@ -65447,9 +66581,11 @@ var rmfLevel = import_joi77.default.object({
65447
66581
  name: rmfName.required(),
65448
66582
  type: import_joi77.default.string().valid("hinged", "double_hinged", "sliding", "double_sliding").default("hinged"),
65449
66583
  motionAxis: import_joi77.default.string().valid("start", "end"),
65450
- 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),
65451
66586
  motionDirection: import_joi77.default.number().valid(1, -1),
65452
- 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("")
65453
66589
  })
65454
66590
  ).max(500).default([]),
65455
66591
  lanes: import_joi77.default.array().items(
@@ -65459,7 +66595,9 @@ var rmfLevel = import_joi77.default.object({
65459
66595
  bidirectional: import_joi77.default.boolean().default(true),
65460
66596
  orientation: import_joi77.default.string().valid("forward", "backward"),
65461
66597
  speedLimit: import_joi77.default.number().min(0).max(20),
65462
- 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("")
65463
66601
  })
65464
66602
  ).max(5e3).default([]),
65465
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([]),
@@ -65475,10 +66613,13 @@ var rmfLift = import_joi77.default.object({
65475
66613
  depthM: import_joi77.default.number().min(0.3).max(20).required(),
65476
66614
  referenceFloor: import_joi77.default.string().trim().max(60).allow("").default(""),
65477
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(),
65478
66619
  doors: import_joi77.default.array().items(
65479
66620
  import_joi77.default.object({
65480
66621
  name: rmfName.required(),
65481
- 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"),
65482
66623
  x: import_joi77.default.number().min(-20).max(20).required(),
65483
66624
  y: import_joi77.default.number().min(-20).max(20).required(),
65484
66625
  widthM: import_joi77.default.number().min(0.3).max(10).required(),
@@ -65502,6 +66643,11 @@ var rmfBuildingSchema = import_joi77.default.object({
65502
66643
  levels: import_joi77.default.array().items(rmfLevel).max(200).unique("floorNo").default([]),
65503
66644
  lifts: import_joi77.default.array().items(rmfLift).max(50).unique("name").default([])
65504
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
+ });
65505
66651
  var buildingMapBodySchema = import_joi77.default.object({
65506
66652
  name: label.required(),
65507
66653
  levels: import_joi77.default.array().items(level).max(200).unique("floorNo").default([]),
@@ -65647,6 +66793,13 @@ function useRobotBuildingMapRepo() {
65647
66793
  "floorPlans.$.updatedAt": at2,
65648
66794
  "floorPlans.$.updatedBy": plan.updatedBy
65649
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"] = "";
65650
66803
  if (plan.data) {
65651
66804
  fields["floorPlans.$.data"] = new import_mongodb110.Binary(plan.data);
65652
66805
  fields["floorPlans.$.mime"] = plan.mime;
@@ -65654,7 +66807,7 @@ function useRobotBuildingMapRepo() {
65654
66807
  }
65655
66808
  const res = existing ? await collection.updateOne(
65656
66809
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": plan.floorNo },
65657
- { $set: { ...fields, updatedAt: at2 }, $inc: { version: 1 } }
66810
+ { $set: { ...fields, updatedAt: at2 }, ...Object.keys(unset).length ? { $unset: unset } : {}, $inc: { version: 1 } }
65658
66811
  ) : await collection.updateOne(
65659
66812
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": { $ne: plan.floorNo } },
65660
66813
  {
@@ -65668,6 +66821,8 @@ function useRobotBuildingMapRepo() {
65668
66821
  metersPerPixel: plan.metersPerPixel,
65669
66822
  tx: plan.tx,
65670
66823
  ty: plan.ty,
66824
+ yawRad: plan.yawRad ?? 0,
66825
+ ...plan.space === "world" ? { space: "world" } : {},
65671
66826
  data: new import_mongodb110.Binary(plan.data),
65672
66827
  updatedAt: at2,
65673
66828
  updatedBy: plan.updatedBy
@@ -65771,723 +66926,181 @@ function useRobotLiftSessionRepo() {
65771
66926
  await collection.createIndexes([
65772
66927
  // The queue itself: one lift's waiting and active rows, oldest first.
65773
66928
  { key: { liftKey: 1, status: 1, requestedAt: 1 } },
65774
- // One robot in the car at a time, enforced by the database.
65775
- {
65776
- key: { liftKey: 1 },
65777
- name: "one_active_session_per_lift",
65778
- unique: true,
65779
- partialFilterExpression: { status: "active" }
65780
- },
65781
- // One open request per robot - a robot cannot queue for two lifts.
65782
- {
65783
- key: { robotId: 1 },
65784
- name: "one_open_session_per_robot",
65785
- unique: true,
65786
- partialFilterExpression: { open: true }
65787
- },
65788
- { key: { siteId: 1, requestedAt: -1 } }
65789
- ]);
65790
- } catch (error) {
65791
- throw new import_node_server_utils164.InternalServerError("Failed to create index on robot lift sessions.");
65792
- }
65793
- }
65794
- async function advance(liftKey, now = /* @__PURE__ */ new Date()) {
65795
- await collection.updateMany(
65796
- { liftKey, open: true, expiresAt: { $lt: now } },
65797
- {
65798
- $set: {
65799
- status: "expired",
65800
- open: false,
65801
- closedAt: now,
65802
- closedReason: "timed out",
65803
- updatedAt: now
65804
- }
65805
- }
65806
- );
65807
- const holder = await collection.findOne({ liftKey, status: "active" });
65808
- if (holder)
65809
- return;
65810
- const next = await collection.find({ liftKey, status: "queued", open: true }).sort({ requestedAt: 1, _id: 1 }).limit(1).next();
65811
- if (!next)
65812
- return;
65813
- try {
65814
- await collection.updateOne(
65815
- { _id: next._id, status: "queued", open: true },
65816
- {
65817
- $set: {
65818
- status: "active",
65819
- activeAt: now,
65820
- expiresAt: new Date(now.getTime() + LIFT_LEASE_MS),
65821
- updatedAt: now
65822
- }
65823
- }
65824
- );
65825
- } catch (error) {
65826
- if (!isDuplicateKey(error))
65827
- throw error;
65828
- }
65829
- }
65830
- async function enqueue(value) {
65831
- const now = /* @__PURE__ */ new Date();
65832
- const liftKey = liftQueueKey(String(value.mapId), value.liftName);
65833
- await closeExpiredForRobot(value.robotId, now);
65834
- let insertedId;
65835
- try {
65836
- const res = await collection.insertOne({
65837
- ...value,
65838
- liftKey,
65839
- createdBy: new import_mongodb110.ObjectId(value.createdBy),
65840
- status: "queued",
65841
- open: true,
65842
- requestedAt: now,
65843
- activeAt: null,
65844
- expiresAt: new Date(now.getTime() + LIFT_QUEUE_TTL_MS),
65845
- closedAt: null,
65846
- updatedAt: now
65847
- });
65848
- insertedId = res.insertedId;
65849
- } catch (error) {
65850
- if (isDuplicateKey(error)) {
65851
- throw new import_node_server_utils164.AppError("This robot already has a lift request open. Release it first.", 409);
65852
- }
65853
- throw error;
65854
- }
65855
- await advance(liftKey, now);
65856
- return insertedId;
65857
- }
65858
- async function closeExpiredForRobot(robotId, now) {
65859
- const stale = await collection.findOne({ robotId, open: true, expiresAt: { $lt: now } });
65860
- if (stale)
65861
- await advance(stale.liftKey, now);
65862
- }
65863
- async function getSessionById(id) {
65864
- const session = await collection.findOne({ _id: toObjectId16(id, "lift session") });
65865
- if (!session)
65866
- throw new import_node_server_utils164.NotFoundError("Lift session not found.");
65867
- return session;
65868
- }
65869
- async function getQueue(mapId, liftNames) {
65870
- const now = /* @__PURE__ */ new Date();
65871
- const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
65872
- for (const key of keys)
65873
- await advance(key, now);
65874
- return collection.find({ liftKey: { $in: keys }, open: true }).sort({ requestedAt: 1, _id: 1 }).toArray();
65875
- }
65876
- async function getRecent(mapId, liftNames, since) {
65877
- const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
65878
- if (!keys.length)
65879
- return [];
65880
- return collection.find({ liftKey: { $in: keys }, status: { $in: ["released", "expired"] }, closedAt: { $gte: since } }).sort({ closedAt: -1, _id: -1 }).limit(20).toArray();
65881
- }
65882
- async function refresh(id) {
65883
- const now = /* @__PURE__ */ new Date();
65884
- const res = await collection.updateOne(
65885
- { _id: id, status: "active", open: true, expiresAt: { $gte: now } },
65886
- { $set: { expiresAt: new Date(now.getTime() + LIFT_LEASE_MS), updatedAt: now } }
65887
- );
65888
- if (!res.matchedCount) {
65889
- throw new import_node_server_utils164.AppError("This lift session is no longer active.", 409);
65890
- }
65891
- }
65892
- async function release(session, reason = "released") {
65893
- const now = /* @__PURE__ */ new Date();
65894
- await collection.updateOne({ _id: session._id, open: true }, [
65895
- {
65896
- $set: {
65897
- status: { $cond: [{ $eq: ["$status", "active"] }, "released", "cancelled"] },
65898
- open: false,
65899
- closedAt: now,
65900
- closedReason: reason,
65901
- updatedAt: now
65902
- }
65903
- }
65904
- ]);
65905
- await advance(session.liftKey, now);
65906
- }
65907
- async function getOpenForRobot(robotId) {
65908
- const now = /* @__PURE__ */ new Date();
65909
- await closeExpiredForRobot(robotId, now);
65910
- const session = await collection.findOne({ robotId, open: true });
65911
- if (!session)
65912
- return null;
65913
- await advance(session.liftKey, now);
65914
- return collection.findOne({ _id: session._id });
65915
- }
65916
- async function cancelForMap(mapId, keepLiftNames = []) {
65917
- const now = /* @__PURE__ */ new Date();
65918
- await collection.updateMany(
65919
- { mapId, open: true, liftName: { $nin: keepLiftNames } },
65920
- {
65921
- $set: {
65922
- status: "cancelled",
65923
- open: false,
65924
- closedAt: now,
65925
- closedReason: "lift removed from the map",
65926
- updatedAt: now
65927
- }
65928
- }
65929
- );
65930
- }
65931
- return {
65932
- createIndex,
65933
- advance,
65934
- enqueue,
65935
- getSessionById,
65936
- getQueue,
65937
- getRecent,
65938
- refresh,
65939
- release,
65940
- getOpenForRobot,
65941
- cancelForMap
65942
- };
65943
- }
65944
-
65945
- // src/controllers/robot-map.controller.ts
65946
- var import_joi78 = __toESM(require("joi"));
65947
- var import_node_server_utils165 = require("@7365admin1/node-server-utils");
65948
-
65949
- // src/utils/rmf-building.util.ts
65950
- var PLAN_W_M2 = 40;
65951
- var PLAN_H_M2 = 26;
65952
- var DEFAULT_PLAN_FRAME = { minX: 0, maxX: PLAN_W_M2, minY: -PLAN_H_M2, maxY: 0 };
65953
- var WELD_M = 0.01;
65954
- var r3 = (v) => Math.round(v * 1e3) / 1e3;
65955
- var clamp2 = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
65956
- function floorLabel(floorNo2) {
65957
- return floorNo2 < 0 ? `B${-floorNo2}` : floorNo2 === 0 ? "G" : `L${floorNo2}`;
65958
- }
65959
- function floorNoFromName(name) {
65960
- if (typeof name !== "string")
65961
- return null;
65962
- const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
65963
- if (m)
65964
- return m[1].toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
65965
- return /^G$/i.test(name.trim()) ? 0 : null;
65966
- }
65967
- function toPlan(f, p) {
65968
- const w = f.maxX - f.minX || 1;
65969
- const h = f.maxY - f.minY || 1;
65970
- return { x: r3((p.x - f.minX) / w * PLAN_W_M2), y: r3((f.maxY - p.y) / h * PLAN_H_M2) };
65971
- }
65972
- function fromPlan(f, p) {
65973
- 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)) };
65974
- }
65975
- function vertexPool(level2) {
65976
- let next = level2.vertices.reduce((n, v) => Math.max(n, Number(/^v(\d+)$/.exec(v.id)?.[1] ?? 0)), 0) + 1;
65977
- const byId = new Map(level2.vertices.map((v) => [v.id, v]));
65978
- function at2(p, extra) {
65979
- const x = r3(p.x);
65980
- const y = r3(p.y);
65981
- const hit = level2.vertices.find((v2) => Math.abs(v2.x - x) < WELD_M && Math.abs(v2.y - y) < WELD_M);
65982
- if (hit) {
65983
- if (extra?.name && !hit.name)
65984
- hit.name = extra.name;
65985
- if (extra?.params && Object.keys(extra.params).length)
65986
- hit.params = { ...hit.params ?? {}, ...extra.params };
65987
- return hit.id;
65988
- }
65989
- const v = { id: `v${next++}`, x, y, ...extra?.name ? { name: extra.name } : {}, ...extra?.params && Object.keys(extra.params).length ? { params: extra.params } : {} };
65990
- level2.vertices.push(v);
65991
- byId.set(v.id, v);
65992
- return v.id;
65993
- }
65994
- return { at: at2, get: (id) => byId.get(id) };
65995
- }
65996
- function emptyLevel(name, floorNo2, elevationM, planFrame) {
65997
- return { name, floorNo: floorNo2, elevationM, planFrame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [] };
65998
- }
65999
- function emptyRmf(source = "editor") {
66000
- return { formatVersion: 1, coordinateSystem: "cartesian_meters", source, graphs: [], levels: [], lifts: [] };
66001
- }
66002
- var collapseDoor = (t) => t === "sliding" || t === "double_sliding" ? "sliding" : "hinged";
66003
- function pruneVertices(level2) {
66004
- const used = /* @__PURE__ */ new Set();
66005
- const add = (...ids2) => ids2.forEach((i) => used.add(i));
66006
- level2.walls.forEach((e) => add(e.v1, e.v2));
66007
- level2.doors.forEach((e) => add(e.v1, e.v2));
66008
- level2.lanes.forEach((e) => add(e.v1, e.v2));
66009
- level2.measurements.forEach((e) => add(e.v1, e.v2));
66010
- [...level2.floors, ...level2.holes, ...level2.zones].forEach((p) => add(...p.vertices));
66011
- level2.vertices = level2.vertices.filter((v) => used.has(v.id) || v.name || v.params && Object.keys(v.params).length);
66012
- }
66013
- function msgParams(params) {
66014
- const out = {};
66015
- for (const p of params ?? []) {
66016
- if (!p?.name)
66017
- continue;
66018
- 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;
66019
- }
66020
- return out;
66021
- }
66022
- var VERTEX_PARAM_KEYS = [
66023
- "is_charger",
66024
- "is_parking_spot",
66025
- "is_holding_point",
66026
- "is_passthrough_point",
66027
- "is_cleaning_zone",
66028
- "dock_name",
66029
- "spawn_robot_name",
66030
- "spawn_robot_type",
66031
- "lift_cabin",
66032
- "merge_radius",
66033
- "mutex"
66034
- ];
66035
- function vertexParams(raw) {
66036
- const out = {};
66037
- for (const k of VERTEX_PARAM_KEYS) {
66038
- const v = raw[k];
66039
- if (v === void 0 || v === "" || v === false)
66040
- continue;
66041
- out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? Number(v) : String(v).slice(0, 60);
66042
- }
66043
- return out;
66044
- }
66045
- var MSG_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "sliding", 4: "double_sliding", 5: "hinged", 6: "double_hinged" };
66046
- function importFrame(level2) {
66047
- const xs = [];
66048
- const ys = [];
66049
- for (const g of level2.nav_graphs ?? [])
66050
- for (const v of g.vertices ?? [])
66051
- xs.push(v.x), ys.push(v.y);
66052
- for (const d of level2.doors ?? [])
66053
- xs.push(d.v1_x, d.v2_x), ys.push(d.v1_y, d.v2_y);
66054
- if (!xs.length)
66055
- for (const v of level2.wall_graph?.vertices ?? [])
66056
- xs.push(v.x), ys.push(v.y);
66057
- if (!xs.length)
66058
- return { ...DEFAULT_PLAN_FRAME };
66059
- const pad = 3;
66060
- 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) };
66061
- }
66062
- var rot = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
66063
- function rmfFromFleetCore(msg) {
66064
- const rmf = emptyRmf("fleet-core");
66065
- const graphIdx = /* @__PURE__ */ new Map();
66066
- const usedFloors = /* @__PURE__ */ new Set();
66067
- for (const [i, lv] of (msg.levels ?? []).slice(0, 200).entries()) {
66068
- let floorNo2 = floorNoFromName(lv.name) ?? i + 1;
66069
- while (usedFloors.has(floorNo2))
66070
- floorNo2++;
66071
- usedFloors.add(floorNo2);
66072
- const level2 = emptyLevel(String(lv.name).slice(0, 60), floorNo2, Number(lv.elevation ?? 0), importFrame(lv));
66073
- const pool = vertexPool(level2);
66074
- const wg = lv.wall_graph;
66075
- for (const e of (wg?.edges ?? []).slice(0, 5e3)) {
66076
- const a = wg.vertices[e.v1_idx];
66077
- const b = wg.vertices[e.v2_idx];
66078
- if (a && b)
66079
- level2.walls.push({ v1: pool.at(a), v2: pool.at(b) });
66080
- }
66081
- for (const d of (lv.doors ?? []).slice(0, 500)) {
66082
- level2.doors.push({
66083
- name: String(d.name).slice(0, 60),
66084
- v1: pool.at({ x: d.v1_x, y: d.v1_y }),
66085
- v2: pool.at({ x: d.v2_x, y: d.v2_y }),
66086
- type: MSG_DOOR_TYPE[d.door_type] ?? "hinged",
66087
- ...d.motion_range ? { motionDegrees: r3(d.motion_range * 180 / Math.PI) } : {},
66088
- ...d.motion_direction ? { motionDirection: d.motion_direction < 0 ? -1 : 1 } : {}
66089
- });
66929
+ // One robot in the car at a time, enforced by the database.
66930
+ {
66931
+ key: { liftKey: 1 },
66932
+ name: "one_active_session_per_lift",
66933
+ unique: true,
66934
+ partialFilterExpression: { status: "active" }
66935
+ },
66936
+ // One open request per robot - a robot cannot queue for two lifts.
66937
+ {
66938
+ key: { robotId: 1 },
66939
+ name: "one_open_session_per_robot",
66940
+ unique: true,
66941
+ partialFilterExpression: { open: true }
66942
+ },
66943
+ { key: { siteId: 1, requestedAt: -1 } }
66944
+ ]);
66945
+ } catch (error) {
66946
+ throw new import_node_server_utils164.InternalServerError("Failed to create index on robot lift sessions.");
66090
66947
  }
66091
- for (const [gi, g] of (lv.nav_graphs ?? []).entries()) {
66092
- const key = String(g.name ?? gi);
66093
- if (!graphIdx.has(key)) {
66094
- const n = Number(key);
66095
- graphIdx.set(key, Number.isInteger(n) && n >= 0 && n <= 8 ? n : Math.min(8, graphIdx.size));
66096
- }
66097
- const idx = graphIdx.get(key);
66098
- 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)) }));
66099
- for (const e of (g.edges ?? []).slice(0, 5e3)) {
66100
- const a = ids2[e.v1_idx];
66101
- const b = ids2[e.v2_idx];
66102
- if (!a || !b || a === b)
66103
- continue;
66104
- const p = msgParams(e.params);
66105
- level2.lanes.push({
66106
- v1: a,
66107
- v2: b,
66108
- graphIdx: idx,
66109
- bidirectional: (e.edge_type ?? 0) === 0,
66110
- ...Number(p.speed_limit) > 0 ? { speedLimit: Number(p.speed_limit) } : {},
66111
- ...p.mutex ? { mutex: String(p.mutex).slice(0, 60) } : {}
66112
- });
66948
+ }
66949
+ async function advance(liftKey, now = /* @__PURE__ */ new Date()) {
66950
+ await collection.updateMany(
66951
+ { liftKey, open: true, expiresAt: { $lt: now } },
66952
+ {
66953
+ $set: {
66954
+ status: "expired",
66955
+ open: false,
66956
+ closedAt: now,
66957
+ closedReason: "timed out",
66958
+ updatedAt: now
66959
+ }
66113
66960
  }
66961
+ );
66962
+ const holder = await collection.findOne({ liftKey, status: "active" });
66963
+ if (holder)
66964
+ return;
66965
+ const next = await collection.find({ liftKey, status: "queued", open: true }).sort({ requestedAt: 1, _id: 1 }).limit(1).next();
66966
+ if (!next)
66967
+ return;
66968
+ try {
66969
+ await collection.updateOne(
66970
+ { _id: next._id, status: "queued", open: true },
66971
+ {
66972
+ $set: {
66973
+ status: "active",
66974
+ activeAt: now,
66975
+ expiresAt: new Date(now.getTime() + LIFT_LEASE_MS),
66976
+ updatedAt: now
66977
+ }
66978
+ }
66979
+ );
66980
+ } catch (error) {
66981
+ if (!isDuplicateKey(error))
66982
+ throw error;
66114
66983
  }
66115
- rmf.levels.push(level2);
66116
- }
66117
- rmf.graphs = [...new Set(graphIdx.values())].sort((a, b) => a - b).map((idx) => ({ idx, name: `Graph ${idx}`, brands: ["fleet-core"] }));
66118
- rmf.referenceLevel = rmf.levels[0]?.name;
66119
- const levelNames = new Set(rmf.levels.map((l) => l.name));
66120
- for (const l of (msg.lifts ?? []).slice(0, 50)) {
66121
- const yaw = Number(l.ref_yaw ?? 0);
66122
- const doors = (l.doors ?? []).slice(0, 8).map((d) => {
66123
- const a = rot(d.v1_x - l.ref_x, d.v1_y - l.ref_y, -yaw);
66124
- const b = rot(d.v2_x - l.ref_x, d.v2_y - l.ref_y, -yaw);
66125
- return {
66126
- name: String(d.name).slice(0, 60),
66127
- type: d.door_type === 2 || d.door_type === 4 ? "double_sliding" : "sliding",
66128
- x: r3((a.x + b.x) / 2),
66129
- y: r3((a.y + b.y) / 2),
66130
- widthM: r3(Math.hypot(b.x - a.x, b.y - a.y)),
66131
- axisYawRad: r3(Math.atan2(b.y - a.y, b.x - a.x))
66132
- };
66133
- });
66134
- const served = (l.levels ?? []).filter((n) => levelNames.has(n));
66135
- rmf.lifts.push({
66136
- name: String(l.name).slice(0, 60),
66137
- x: r3(l.ref_x),
66138
- y: r3(l.ref_y),
66139
- yawRad: r3(yaw),
66140
- widthM: r3(l.width),
66141
- depthM: r3(l.depth),
66142
- referenceFloor: served[0] ?? rmf.referenceLevel ?? "",
66143
- levelDoors: served.map((level2) => ({ level: level2, doors: doors.map((d) => d.name) })),
66144
- doors
66145
- });
66146
66984
  }
66147
- return rmf;
66148
- }
66149
- function legacyFromRmf(rmf) {
66150
- const levels = [];
66151
- const doors = [];
66152
- for (const lv of rmf.levels) {
66153
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
66154
- const p = (id) => {
66155
- const q = v.get(id);
66156
- return q ? toPlan(lv.planFrame, q) : null;
66157
- };
66158
- const walls = lv.walls.flatMap((w) => {
66159
- const a = p(w.v1);
66160
- const b = p(w.v2);
66161
- return a && b ? [{ start: a, end: b }] : [];
66162
- });
66163
- const zones = lv.zones.flatMap((z5) => {
66164
- const points = z5.vertices.map(p).filter((q) => !!q);
66165
- return points.length >= 3 ? [{ name: z5.name, points: points.slice(0, 200) }] : [];
66166
- });
66167
- levels.push({ floorNo: lv.floorNo, name: lv.name, elevationM: lv.elevationM, walls: walls.slice(0, 2e3), zones: zones.slice(0, 200) });
66168
- for (const d of lv.doors) {
66169
- const a = p(d.v1);
66170
- const b = p(d.v2);
66171
- if (a && b)
66172
- doors.push({ name: d.name, floorNo: lv.floorNo, type: collapseDoor(d.type), start: a, end: b });
66985
+ async function enqueue(value) {
66986
+ const now = /* @__PURE__ */ new Date();
66987
+ const liftKey = liftQueueKey(String(value.mapId), value.liftName);
66988
+ await closeExpiredForRobot(value.robotId, now);
66989
+ let insertedId;
66990
+ try {
66991
+ const res = await collection.insertOne({
66992
+ ...value,
66993
+ liftKey,
66994
+ createdBy: new import_mongodb110.ObjectId(value.createdBy),
66995
+ status: "queued",
66996
+ open: true,
66997
+ requestedAt: now,
66998
+ activeAt: null,
66999
+ expiresAt: new Date(now.getTime() + LIFT_QUEUE_TTL_MS),
67000
+ closedAt: null,
67001
+ updatedAt: now
67002
+ });
67003
+ insertedId = res.insertedId;
67004
+ } catch (error) {
67005
+ if (isDuplicateKey(error)) {
67006
+ throw new import_node_server_utils164.AppError("This robot already has a lift request open. Release it first.", 409);
67007
+ }
67008
+ throw error;
66173
67009
  }
67010
+ await advance(liftKey, now);
67011
+ return insertedId;
66174
67012
  }
66175
- const byName = new Map(rmf.levels.map((l) => [l.name, l]));
66176
- const lifts = [];
66177
- for (const l of rmf.lifts) {
66178
- const withDoors = l.levelDoors.filter((x) => x.doors.length).map((x) => byName.get(x.level)?.floorNo);
66179
- let floors = [...new Set(withDoors.filter((n) => typeof n === "number"))];
66180
- if (floors.length < 2)
66181
- floors = rmf.levels.map((x) => x.floorNo);
66182
- if (floors.length < 2)
66183
- continue;
66184
- const ref = byName.get(l.referenceFloor) ?? rmf.levels[0];
66185
- if (!ref)
66186
- continue;
66187
- const c = toPlan(ref.planFrame, l);
66188
- const f = ref.planFrame;
66189
- lifts.push({
66190
- name: l.name,
66191
- x: c.x,
66192
- y: c.y,
66193
- widthM: r3(clamp2(l.widthM / (f.maxX - f.minX || 1) * PLAN_W_M2, 0.5, 10)),
66194
- depthM: r3(clamp2(l.depthM / (f.maxY - f.minY || 1) * PLAN_H_M2, 0.5, 10)),
66195
- floors: floors.sort((a, b) => a - b)
66196
- });
67013
+ async function closeExpiredForRobot(robotId, now) {
67014
+ const stale = await collection.findOne({ robotId, open: true, expiresAt: { $lt: now } });
67015
+ if (stale)
67016
+ await advance(stale.liftKey, now);
66197
67017
  }
66198
- return { levels, doors: doors.slice(0, 500), lifts };
66199
- }
66200
- var defaultCabinDoor = (l) => ({
66201
- name: "door1",
66202
- type: "double_sliding",
66203
- x: r3(l.widthM / 2),
66204
- y: 0,
66205
- widthM: r3(Math.min(1.2, l.depthM * 0.8)),
66206
- axisYawRad: r3(Math.PI / 2)
66207
- });
66208
- function mergeLegacyIntoRmf(prev, legacy) {
66209
- const base = prev ? structuredClone(prev) : emptyRmf("editor");
66210
- const refFrame = base.levels[0]?.planFrame ?? DEFAULT_PLAN_FRAME;
66211
- const legacyFloors = new Map((legacy.levels ?? []).map((l) => [l.floorNo, l]));
66212
- const allFloors = /* @__PURE__ */ new Set([
66213
- ...legacyFloors.keys(),
66214
- ...(legacy.doors ?? []).map((d) => d.floorNo),
66215
- ...(legacy.lifts ?? []).flatMap((l) => l.floors)
66216
- ]);
66217
- for (const floorNo2 of allFloors) {
66218
- if (base.levels.some((l) => l.floorNo === floorNo2))
66219
- continue;
66220
- base.levels.push(emptyLevel(legacyFloors.get(floorNo2)?.name || floorLabel(floorNo2), floorNo2, legacyFloors.get(floorNo2)?.elevationM ?? 0, { ...refFrame }));
67018
+ async function getSessionById(id) {
67019
+ const session = await collection.findOne({ _id: toObjectId16(id, "lift session") });
67020
+ if (!session)
67021
+ throw new import_node_server_utils164.NotFoundError("Lift session not found.");
67022
+ return session;
66221
67023
  }
66222
- base.levels.sort((a, b) => a.floorNo - b.floorNo);
66223
- for (const lv of base.levels) {
66224
- const src = legacyFloors.get(lv.floorNo);
66225
- if (src?.name)
66226
- lv.name = String(src.name).slice(0, 60);
66227
- if (typeof src?.elevationM === "number")
66228
- lv.elevationM = src.elevationM;
66229
- const prevDoors = new Map(lv.doors.map((d) => [d.name, d]));
66230
- lv.walls = [];
66231
- lv.zones = [];
66232
- lv.doors = [];
66233
- const pool = vertexPool(lv);
66234
- const at2 = (p) => pool.at(fromPlan(lv.planFrame, p));
66235
- for (const w of src?.walls ?? [])
66236
- lv.walls.push({ v1: at2(w.start), v2: at2(w.end) });
66237
- for (const z5 of src?.zones ?? [])
66238
- lv.zones.push({ name: z5.name, vertices: z5.points.map(at2) });
66239
- for (const d of (legacy.doors ?? []).filter((x) => x.floorNo === lv.floorNo)) {
66240
- const was = prevDoors.get(d.name);
66241
- const keep = was && collapseDoor(was.type) === d.type;
66242
- lv.doors.push({
66243
- ...keep ? was : {},
66244
- name: d.name,
66245
- v1: at2(d.start),
66246
- v2: at2(d.end),
66247
- type: keep ? was.type : d.type
66248
- });
66249
- }
66250
- pruneVertices(lv);
67024
+ async function getQueue(mapId, liftNames) {
67025
+ const now = /* @__PURE__ */ new Date();
67026
+ const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
67027
+ for (const key of keys)
67028
+ await advance(key, now);
67029
+ return collection.find({ liftKey: { $in: keys }, open: true }).sort({ requestedAt: 1, _id: 1 }).toArray();
66251
67030
  }
66252
- const prevLifts = new Map(base.lifts.map((l) => [l.name, l]));
66253
- const byFloor = new Map(base.levels.map((l) => [l.floorNo, l]));
66254
- base.lifts = (legacy.lifts ?? []).map((l) => {
66255
- const was = prevLifts.get(l.name);
66256
- const ref = was && base.levels.find((x) => x.name === was.referenceFloor) || byFloor.get(l.floors[0]) || base.levels[0];
66257
- const f = ref.planFrame;
66258
- const c = fromPlan(f, l);
66259
- const widthM = r3(l.widthM / PLAN_W_M2 * (f.maxX - f.minX));
66260
- const depthM = r3(l.depthM / PLAN_H_M2 * (f.maxY - f.minY));
66261
- const doors = was?.doors?.length ? was.doors : [defaultCabinDoor({ widthM, depthM })];
66262
- const served = l.floors.map((n) => byFloor.get(n)?.name).filter((n) => !!n);
66263
- const prevLevelDoors = new Map((was?.levelDoors ?? []).map((x) => [x.level, x.doors]));
66264
- return {
66265
- name: l.name,
66266
- x: c.x,
66267
- y: c.y,
66268
- yawRad: was?.yawRad ?? 0,
66269
- widthM,
66270
- depthM,
66271
- referenceFloor: ref.name,
66272
- ...was?.initialFloor && served.includes(was.initialFloor) ? { initialFloor: was.initialFloor } : {},
66273
- doors,
66274
- levelDoors: served.map((level2) => ({ level: level2, doors: prevLevelDoors.get(level2)?.length ? prevLevelDoors.get(level2) : doors.map((d) => d.name) }))
66275
- };
66276
- });
66277
- base.referenceLevel = base.levels.find((l) => l.name === base.referenceLevel)?.name ?? base.levels[0]?.name;
66278
- return base;
66279
- }
66280
- function rmfProblem(rmf) {
66281
- const levelNames = /* @__PURE__ */ new Set();
66282
- const doorNames = /* @__PURE__ */ new Set();
66283
- const graphIdx = new Set(rmf.graphs.map((g) => g.idx));
66284
- for (const lv of rmf.levels) {
66285
- if (levelNames.has(lv.name))
66286
- return `Two floors are both called "${lv.name}".`;
66287
- levelNames.add(lv.name);
66288
- const f = lv.planFrame;
66289
- if (!(f.maxX > f.minX && f.maxY > f.minY))
66290
- return `Floor ${lv.name}: its plan frame is empty.`;
66291
- const ids2 = /* @__PURE__ */ new Set();
66292
- for (const v of lv.vertices) {
66293
- if (ids2.has(v.id))
66294
- return `Floor ${lv.name}: point id "${v.id}" is used twice.`;
66295
- ids2.add(v.id);
66296
- }
66297
- const missing = (id) => !ids2.has(id);
66298
- const edges = [...lv.walls, ...lv.doors, ...lv.lanes, ...lv.measurements];
66299
- if (edges.some((e) => missing(e.v1) || missing(e.v2)))
66300
- return `Floor ${lv.name}: a line ends at a point that does not exist.`;
66301
- if ([...lv.floors, ...lv.holes, ...lv.zones].some((p) => p.vertices.some(missing)))
66302
- return `Floor ${lv.name}: an area uses a point that does not exist.`;
66303
- for (const d of lv.doors) {
66304
- if (doorNames.has(d.name))
66305
- return `Two doors are both called "${d.name}" - door names must be unique in the building.`;
66306
- doorNames.add(d.name);
66307
- }
66308
- if (lv.lanes.some((l) => !graphIdx.has(l.graphIdx)))
66309
- return `Floor ${lv.name}: a lane belongs to a route graph that is not listed.`;
67031
+ async function getRecent(mapId, liftNames, since) {
67032
+ const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
67033
+ if (!keys.length)
67034
+ return [];
67035
+ return collection.find({ liftKey: { $in: keys }, status: { $in: ["released", "expired"] }, closedAt: { $gte: since } }).sort({ closedAt: -1, _id: -1 }).limit(20).toArray();
66310
67036
  }
66311
- for (const l of rmf.lifts) {
66312
- const cabin = new Set(l.doors.map((d) => d.name));
66313
- if (l.referenceFloor && !levelNames.has(l.referenceFloor))
66314
- return `Lift ${l.name}: its reference floor "${l.referenceFloor}" does not exist.`;
66315
- for (const x of l.levelDoors) {
66316
- if (!levelNames.has(x.level))
66317
- return `Lift ${l.name}: floor "${x.level}" does not exist.`;
66318
- if (x.doors.some((d) => !cabin.has(d)))
66319
- return `Lift ${l.name}: floor ${x.level} opens a cabin door the lift does not have.`;
67037
+ async function refresh(id) {
67038
+ const now = /* @__PURE__ */ new Date();
67039
+ const res = await collection.updateOne(
67040
+ { _id: id, status: "active", open: true, expiresAt: { $gte: now } },
67041
+ { $set: { expiresAt: new Date(now.getTime() + LIFT_LEASE_MS), updatedAt: now } }
67042
+ );
67043
+ if (!res.matchedCount) {
67044
+ throw new import_node_server_utils164.AppError("This lift session is no longer active.", 409);
66320
67045
  }
66321
67046
  }
66322
- return null;
66323
- }
66324
- var P = { str: (v) => [1, v], int: (v) => [2, Math.round(v)], dbl: (v) => [3, v], bool: (v) => [4, v] };
66325
- function toBuildingYaml(name, rmf) {
66326
- const levels = {};
66327
- for (const lv of rmf.levels) {
66328
- const idx = new Map(lv.vertices.map((v, i) => [v.id, i]));
66329
- const edge2 = (v1, v2, params) => [idx.get(v1), idx.get(v2), params];
66330
- levels[lv.name] = {
66331
- elevation: lv.elevationM,
66332
- vertices: lv.vertices.map((v) => {
66333
- const params = {};
66334
- for (const [k, val] of Object.entries(v.params ?? {})) {
66335
- params[k] = typeof val === "boolean" ? P.bool(val) : typeof val === "number" ? P.dbl(val) : P.str(String(val));
67047
+ async function release(session, reason = "released") {
67048
+ const now = /* @__PURE__ */ new Date();
67049
+ await collection.updateOne({ _id: session._id, open: true }, [
67050
+ {
67051
+ $set: {
67052
+ status: { $cond: [{ $eq: ["$status", "active"] }, "released", "cancelled"] },
67053
+ open: false,
67054
+ closedAt: now,
67055
+ closedReason: reason,
67056
+ updatedAt: now
66336
67057
  }
66337
- return [v.x, v.y, 0, v.name ?? "", params];
66338
- }),
66339
- walls: lv.walls.map((w) => edge2(w.v1, w.v2, {})),
66340
- doors: lv.doors.map(
66341
- (d) => edge2(d.v1, d.v2, {
66342
- name: P.str(d.name),
66343
- type: P.str(d.type),
66344
- motion_axis: P.str(d.motionAxis ?? "start"),
66345
- motion_degrees: P.dbl(d.motionDegrees ?? 90),
66346
- motion_direction: P.int(d.motionDirection ?? 1),
66347
- right_left_ratio: P.dbl(d.rightLeftRatio ?? 1)
66348
- })
66349
- ),
66350
- lanes: lv.lanes.map(
66351
- (l) => edge2(l.v1, l.v2, {
66352
- graph_idx: P.int(l.graphIdx),
66353
- bidirectional: P.bool(l.bidirectional),
66354
- orientation: P.str(l.orientation ?? ""),
66355
- ...l.speedLimit ? { speed_limit: P.dbl(l.speedLimit) } : {},
66356
- ...l.mutex ? { mutex: P.str(l.mutex) } : {}
66357
- })
66358
- ),
66359
- measurements: lv.measurements.map((m) => edge2(m.v1, m.v2, { distance: P.dbl(m.distanceM) })),
66360
- floors: lv.floors.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
66361
- holes: lv.holes.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
66362
- fiducials: lv.fiducials.map((f) => [f.x, f.y, f.name]),
66363
- layers: {},
66364
- models: []
66365
- };
67058
+ }
67059
+ ]);
67060
+ await advance(session.liftKey, now);
66366
67061
  }
66367
- const elevation = new Map(rmf.levels.map((l) => [l.name, l.elevationM]));
66368
- const lifts = {};
66369
- for (const l of rmf.lifts) {
66370
- const served = l.levelDoors.map((x) => x.level).sort((a, b) => (elevation.get(a) ?? 0) - (elevation.get(b) ?? 0));
66371
- lifts[l.name] = {
66372
- x: l.x,
66373
- y: l.y,
66374
- yaw: l.yawRad,
66375
- width: l.widthM,
66376
- depth: l.depthM,
66377
- reference_floor_name: l.referenceFloor,
66378
- initial_floor_name: l.initialFloor ?? served[0] ?? l.referenceFloor,
66379
- lowest_floor: served[0] ?? l.referenceFloor,
66380
- highest_floor: served[served.length - 1] ?? l.referenceFloor,
66381
- doors: Object.fromEntries(
66382
- 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 }])
66383
- ),
66384
- level_doors: Object.fromEntries(l.levelDoors.map((x) => [x.level, x.doors])),
66385
- plugins: true
66386
- };
67062
+ async function getOpenForRobot(robotId) {
67063
+ const now = /* @__PURE__ */ new Date();
67064
+ await closeExpiredForRobot(robotId, now);
67065
+ const session = await collection.findOne({ robotId, open: true });
67066
+ if (!session)
67067
+ return null;
67068
+ await advance(session.liftKey, now);
67069
+ return collection.findOne({ _id: session._id });
66387
67070
  }
66388
- return JSON.stringify(
66389
- { name, coordinate_system: "cartesian_meters", reference_level_name: rmf.referenceLevel ?? rmf.levels[0]?.name ?? "", graphs: {}, parameters: {}, levels, lifts },
66390
- null,
66391
- 1
66392
- );
66393
- }
66394
- function segmentsIntersect(a, b, c, d) {
66395
- const det = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
66396
- if (Math.abs(det) < 0.01)
66397
- return false;
66398
- const t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / det;
66399
- const u = -((a.x - b.x) * (a.y - c.y) - (a.y - b.y) * (a.x - c.x)) / det;
66400
- return t >= 0 && t <= 1 && u >= 0 && u <= 1;
66401
- }
66402
- function inLift(p, l) {
66403
- const q = rot(p.x - l.x, p.y - l.y, -l.yawRad);
66404
- return Math.abs(q.x) <= l.widthM / 2 && Math.abs(q.y) <= l.depthM / 2;
66405
- }
66406
- function toNavGraphs(name, rmf) {
66407
- const out = {};
66408
- for (let gi = 0; gi <= 8; gi++) {
66409
- const levels = {};
66410
- const doors = {};
66411
- let empty = true;
66412
- for (const lv of rmf.levels) {
66413
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
66414
- const lanes = lv.lanes.filter((l) => l.graphIdx === gi);
66415
- if (lanes.length)
66416
- empty = false;
66417
- const order = [];
66418
- const mapped = /* @__PURE__ */ new Map();
66419
- for (const l of lanes)
66420
- for (const id of [l.v1, l.v2])
66421
- if (!mapped.has(id))
66422
- mapped.set(id, order.push(id) - 1);
66423
- const lifts2 = rmf.lifts.filter((l) => l.levelDoors.some((x) => x.level === lv.name && x.doors.length));
66424
- const vertices = order.map((id) => {
66425
- const q = v.get(id);
66426
- const lift2 = lifts2.find((l) => inLift(q, l));
66427
- return [q.x, q.y, { name: q.name ?? "", ...q.params ?? {}, ...lift2 ? { lift: lift2.name } : {} }];
66428
- });
66429
- const navLanes = [];
66430
- for (const l of lanes) {
66431
- const a = v.get(l.v1);
66432
- const b = v.get(l.v2);
66433
- const p = {};
66434
- for (const d of lv.doors) {
66435
- const c = v.get(d.v1);
66436
- const e = v.get(d.v2);
66437
- if (c && e && segmentsIntersect(a, b, c, e))
66438
- p.door_name = d.name;
66439
- }
66440
- if (l.orientation)
66441
- p.orientation_constraint = l.orientation;
66442
- if (l.speedLimit && l.speedLimit > 0)
66443
- p.speed_limit = l.speedLimit;
66444
- if (l.mutex)
66445
- p.mutex = l.mutex;
66446
- const endDock = b.params?.dock_name;
66447
- const startDock = a.params?.dock_name;
66448
- const s = mapped.get(l.v1);
66449
- const t = mapped.get(l.v2);
66450
- if (l.bidirectional) {
66451
- const fwd = { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} };
66452
- const back = { ...p, ...endDock ? { undock_name: endDock } : {}, ...startDock ? { dock_name: startDock } : {} };
66453
- if (l.orientation)
66454
- back.orientation_constraint = l.orientation === "forward" ? "backward" : "forward";
66455
- navLanes.push([s, t, fwd], [t, s, back]);
66456
- } else {
66457
- navLanes.push([s, t, { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} }]);
67071
+ async function cancelForMap(mapId, keepLiftNames = []) {
67072
+ const now = /* @__PURE__ */ new Date();
67073
+ await collection.updateMany(
67074
+ { mapId, open: true, liftName: { $nin: keepLiftNames } },
67075
+ {
67076
+ $set: {
67077
+ status: "cancelled",
67078
+ open: false,
67079
+ closedAt: now,
67080
+ closedReason: "lift removed from the map",
67081
+ updatedAt: now
66458
67082
  }
66459
67083
  }
66460
- levels[lv.name] = { vertices, lanes: navLanes };
66461
- for (const d of lv.doors) {
66462
- const c = v.get(d.v1);
66463
- const e = v.get(d.v2);
66464
- if (c && e)
66465
- doors[d.name] = { endpoints: [[c.x, c.y], [e.x, e.y]], map: lv.name };
66466
- }
66467
- }
66468
- if (empty)
66469
- continue;
66470
- const lifts = Object.fromEntries(rmf.lifts.map((l) => [l.name, { position: [l.x, l.y, l.yawRad], dims: [l.widthM, l.depthM] }]));
66471
- out[gi] = JSON.stringify({ building_name: name, levels, lifts, doors }, null, 1);
67084
+ );
66472
67085
  }
66473
- return out;
66474
- }
66475
- function rmfSummary(rmf) {
66476
- if (!rmf)
66477
- return null;
66478
- const sum = (f) => rmf.levels.reduce((n, l) => n + f(l), 0);
66479
67086
  return {
66480
- source: rmf.source ?? "editor",
66481
- levels: rmf.levels.length,
66482
- lanes: sum((l) => l.lanes.length),
66483
- waypoints: sum((l) => l.vertices.filter((v) => v.name).length),
66484
- doors: sum((l) => l.doors.length),
66485
- lifts: rmf.lifts.length,
66486
- graphs: rmf.graphs.length
67087
+ createIndex,
67088
+ advance,
67089
+ enqueue,
67090
+ getSessionById,
67091
+ getQueue,
67092
+ getRecent,
67093
+ refresh,
67094
+ release,
67095
+ getOpenForRobot,
67096
+ cancelForMap
66487
67097
  };
66488
67098
  }
66489
67099
 
66490
67100
  // src/controllers/robot-map.controller.ts
67101
+ var import_joi78 = __toESM(require("joi"));
67102
+ var import_node_server_utils165 = require("@7365admin1/node-server-utils");
67103
+ var import_js_yaml = require("js-yaml");
66491
67104
  function useRobotMapController(deps) {
66492
67105
  const now = () => deps?.now?.() ?? Date.now();
66493
67106
  const robots = () => useRobotRepo();
@@ -66684,6 +67297,32 @@ function useRobotMapController(deps) {
66684
67297
  fail(next, e);
66685
67298
  }
66686
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
+ }
66687
67326
  const floorParam = import_joi78.default.number().integer().min(-20).max(200).required();
66688
67327
  function sniffImage(buf) {
66689
67328
  if (buf.length > 8 && buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
@@ -66719,6 +67358,8 @@ function useRobotMapController(deps) {
66719
67358
  metersPerPixel: value.metersPerPixel,
66720
67359
  tx: value.tx,
66721
67360
  ty: value.ty,
67361
+ yawRad: value.yawRad,
67362
+ space: value.space,
66722
67363
  updatedBy: callerId(req) ?? "",
66723
67364
  ...data ? { data, mime, bytes: data.length } : {}
66724
67365
  });
@@ -66978,6 +67619,7 @@ function useRobotMapController(deps) {
66978
67619
  return {
66979
67620
  getOpenRmfBuilding,
66980
67621
  exportMap,
67622
+ importBuildingFile,
66981
67623
  putFloorPlan,
66982
67624
  getFloorPlan,
66983
67625
  deleteFloorPlan,
@@ -101315,6 +101957,7 @@ function usePersonalEmergencyChainController() {
101315
101957
  attendanceSchema,
101316
101958
  attendanceSettingsSchema,
101317
101959
  buildSelfServiceEmailContext,
101960
+ buildingFileImportSchema,
101318
101961
  buildingFromRmf,
101319
101962
  buildingInPlanFrame,
101320
101963
  buildingMapBodySchema,
@@ -101568,6 +102211,7 @@ function usePersonalEmergencyChainController() {
101568
102211
  resolveInviteActor,
101569
102212
  resolveSiteTimezone,
101570
102213
  resolveStaffRole,
102214
+ rmfBuilding,
101571
102215
  rmfBuildingSchema,
101572
102216
  robotActionsFor,
101573
102217
  robotBrandFor,