@7365admin1/core 3.111.0 → 3.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/models/base.model.ts
2
8
  var AppServiceType = /* @__PURE__ */ ((AppServiceType2) => {
3
9
  AppServiceType2["REAL_ESTATE_DEVELOPER"] = "real_estate_developer";
@@ -9841,12 +9847,12 @@ function planFaultChanges(open, reading) {
9841
9847
  return { open: toOpen, clear };
9842
9848
  }
9843
9849
  function robotFaultSweepConfig(env2 = process.env) {
9844
- const num = (v, def, min, max) => {
9850
+ const num2 = (v, def, min, max) => {
9845
9851
  const n = Math.floor(Number(v));
9846
9852
  return Number.isFinite(n) && String(v ?? "").trim() !== "" ? Math.min(max, Math.max(min, n)) : def;
9847
9853
  };
9848
9854
  const enabled = String(env2.ROBOT_FAULT_SWEEP ?? "on").trim().toLowerCase() !== "off";
9849
- const asked = num(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
9855
+ const asked = num2(env2.ROBOT_FAULT_SWEEP_SECONDS, 60, 10, 3600);
9850
9856
  const pick = (steps, v) => steps.filter((d) => d <= v).pop() ?? steps[0];
9851
9857
  const subMinute = asked < 60;
9852
9858
  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));
@@ -9856,9 +9862,9 @@ function robotFaultSweepConfig(env2 = process.env) {
9856
9862
  enabled,
9857
9863
  seconds,
9858
9864
  cron: cron2,
9859
- concurrency: num(env2.ROBOT_FAULT_SWEEP_CONCURRENCY, 4, 1, 16),
9860
- timeoutMs: num(env2.ROBOT_FAULT_SWEEP_TIMEOUT_MS, 1e4, 1e3, 6e4),
9861
- offlineAlertMinutes: num(env2.ROBOT_OFFLINE_ALERT_MINUTES, 10, 1, 1440)
9865
+ concurrency: num2(env2.ROBOT_FAULT_SWEEP_CONCURRENCY, 4, 1, 16),
9866
+ timeoutMs: num2(env2.ROBOT_FAULT_SWEEP_TIMEOUT_MS, 1e4, 1e3, 6e4),
9867
+ offlineAlertMinutes: num2(env2.ROBOT_OFFLINE_ALERT_MINUTES, 10, 1, 1440)
9862
9868
  };
9863
9869
  }
9864
9870
  function withTimeout(promise, ms, label2 = "Timed out") {
@@ -54911,8 +54917,8 @@ function encryptPayload(payloadHex) {
54911
54917
  );
54912
54918
  return encrypted.toString("base64");
54913
54919
  }
54914
- function toHex(num, length) {
54915
- return num.toString(16).padStart(length * 2, "0");
54920
+ function toHex(num2, length) {
54921
+ return num2.toString(16).padStart(length * 2, "0");
54916
54922
  }
54917
54923
  function buildPayload(cardNumber, validityMinutes) {
54918
54924
  const randomHex = crypto7.randomBytes(2).toString("hex");
@@ -55092,8 +55098,8 @@ function UseAccessManagementRepo() {
55092
55098
  }
55093
55099
  }
55094
55100
  function generateCardNo() {
55095
- const num = Math.floor(Math.random() * 65536);
55096
- return num.toString().padStart(10, "0");
55101
+ const num2 = Math.floor(Math.random() * 65536);
55102
+ return num2.toString().padStart(10, "0");
55097
55103
  }
55098
55104
  async function createQrData({
55099
55105
  cardNumber,
@@ -56333,13 +56339,13 @@ function UseAccessManagementRepo() {
56333
56339
  const prevCard = res && res?.[1]?.cardNo || "-1";
56334
56340
  const currentCard = res && res?.[0]?.cardNo || "0";
56335
56341
  let availableCardNo = [];
56336
- let num = parseInt(prevCard, 10) + 1;
56342
+ let num2 = parseInt(prevCard, 10) + 1;
56337
56343
  while (availableCardNo.length < (unit.length > 0 ? unit.length : quantity)) {
56338
- if (num === parseInt(currentCard, 10)) {
56339
- num++;
56344
+ if (num2 === parseInt(currentCard, 10)) {
56345
+ num2++;
56340
56346
  }
56341
- availableCardNo.push(num);
56342
- num++;
56347
+ availableCardNo.push(num2);
56348
+ num2++;
56343
56349
  }
56344
56350
  const cardNumbers = availableCardNo.map(
56345
56351
  (no2) => no2.toString().padStart(10, "0")
@@ -61913,13 +61919,13 @@ function parseRobotCommand(body) {
61913
61919
  if (has2(k))
61914
61920
  return { ok: false, message: `${k} is not valid for a ${kind} command.` };
61915
61921
  }
61916
- const num = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
61917
- if (!num("x") || !num("y"))
61922
+ const num2 = (k) => typeof b[k] === "number" && Number.isFinite(b[k]);
61923
+ if (!num2("x") || !num2("y"))
61918
61924
  return { ok: false, message: `${kind} needs x and y (metres).` };
61919
61925
  if (kind === "navigate") {
61920
61926
  if (has2("floorNo"))
61921
61927
  return { ok: false, message: "floorNo is not valid for a navigate command." };
61922
- if (has2("theta") && !num("theta"))
61928
+ if (has2("theta") && !num2("theta"))
61923
61929
  return { ok: false, message: "theta must be a number (radians)." };
61924
61930
  return {
61925
61931
  ok: true,
@@ -61931,7 +61937,7 @@ function parseRobotCommand(body) {
61931
61937
  }
61932
61938
  };
61933
61939
  }
61934
- if (!num("theta"))
61940
+ if (!num2("theta"))
61935
61941
  return { ok: false, message: "relocalize needs theta (radians)." };
61936
61942
  if (!Number.isInteger(b.floorNo))
61937
61943
  return { ok: false, message: "relocalize needs an integer floorNo." };
@@ -63309,7 +63315,25 @@ function buildingInPlanFrame(building) {
63309
63315
  const b = v2 && toPlan2(levels[i].name, v2.x, v2.y);
63310
63316
  return a && b ? [{ start: a, end: b }] : [];
63311
63317
  });
63312
- return { ...lv, walls };
63318
+ const lanes = [];
63319
+ const waypoints = [];
63320
+ for (const graph of levels[i].nav_graphs ?? []) {
63321
+ const pts = (graph.vertices ?? []).map((v) => toPlan2(levels[i].name, v.x, v.y));
63322
+ for (const e of (graph.edges ?? []).slice(0, 5e3)) {
63323
+ const a = pts[e.v1_idx];
63324
+ const b = pts[e.v2_idx];
63325
+ if (a && b && lanes.length < 5e3)
63326
+ lanes.push({ start: a, end: b, oneWay: (e.edge_type ?? 0) !== 0, graph: String(graph.name) });
63327
+ }
63328
+ (graph.vertices ?? []).forEach((v, k) => {
63329
+ const at2 = pts[k];
63330
+ const flags = new Set((v.params ?? []).map((p) => p.name));
63331
+ if (at2 && v.name && waypoints.length < 2e3) {
63332
+ 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") });
63333
+ }
63334
+ });
63335
+ }
63336
+ return { ...lv, walls, lanes, waypoints };
63313
63337
  }),
63314
63338
  doors,
63315
63339
  lifts
@@ -63969,11 +63993,11 @@ function decodeTrackingFrame(data) {
63969
63993
  if (!parsed || typeof parsed !== "object")
63970
63994
  return null;
63971
63995
  const frame2 = parsed;
63972
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
63973
- const x = num(frame2.x);
63974
- const y = num(frame2.y);
63975
- const theta = num(frame2.theta);
63976
- const statusFlag = num(frame2.status);
63996
+ const num2 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
63997
+ const x = num2(frame2.x);
63998
+ const y = num2(frame2.y);
63999
+ const theta = num2(frame2.theta);
64000
+ const statusFlag = num2(frame2.status);
63977
64001
  if (x === null || y === null || theta === null || statusFlag === null) {
63978
64002
  return null;
63979
64003
  }
@@ -64224,251 +64248,1325 @@ function buildingMapFromRobotMaps(name, maps, floorHeightM = 3) {
64224
64248
  return { name, levels, lifts: [] };
64225
64249
  }
64226
64250
 
64227
- // src/services/robot-tracking.service.ts
64228
- import axios4 from "axios";
64229
- async function openWithAxios(url, body) {
64230
- const response = await axios4.post(url, body, {
64231
- responseType: "stream",
64232
- // No read timeout: this connection is SUPPOSED to stay open and mostly
64233
- // silent. A request timeout here would sever a healthy stream on a quiet
64234
- // robot. The idle watchdog is what decides a stream is dead, because it can
64235
- // tell silence from a closed socket.
64236
- timeout: 0,
64237
- headers: { "Content-Type": "application/json", Accept: "text/event-stream" }
64238
- });
64239
- return response.data;
64251
+ // src/utils/rmf-building.util.ts
64252
+ var rmf_building_util_exports = {};
64253
+ __export(rmf_building_util_exports, {
64254
+ DEFAULT_PLAN_FRAME: () => DEFAULT_PLAN_FRAME,
64255
+ LIFT_DOOR_TYPE_INT: () => LIFT_DOOR_TYPE_INT,
64256
+ PLAN_H_M: () => PLAN_H_M2,
64257
+ PLAN_W_M: () => PLAN_W_M2,
64258
+ RmfImportError: () => RmfImportError,
64259
+ applyXform: () => applyXform,
64260
+ buildingFrame: () => buildingFrame,
64261
+ emptyRmf: () => emptyRmf,
64262
+ fiducialTransform: () => fiducialTransform,
64263
+ floorLabel: () => floorLabel,
64264
+ floorNoFromName: () => floorNoFromName,
64265
+ fromBuildingYaml: () => fromBuildingYaml,
64266
+ fromNavGraph: () => fromNavGraph,
64267
+ fromPlan: () => fromPlan,
64268
+ legacyFromRmf: () => legacyFromRmf,
64269
+ liftShaft: () => liftShaft,
64270
+ mergeLegacyIntoRmf: () => mergeLegacyIntoRmf,
64271
+ rmfFromFleetCore: () => rmfFromFleetCore,
64272
+ rmfProblem: () => rmfProblem,
64273
+ rmfSummary: () => rmfSummary,
64274
+ toBuildingYaml: () => toBuildingYaml,
64275
+ toNavGraphs: () => toNavGraphs,
64276
+ toPlan: () => toPlan
64277
+ });
64278
+ var LIFT_DOOR_TYPE_INT = { sliding: 1, double_sliding: 2, telescope: 3, double_telescope: 4 };
64279
+ var PLAN_W_M2 = 40;
64280
+ var PLAN_H_M2 = 26;
64281
+ var DEFAULT_PLAN_FRAME = { minX: 0, maxX: PLAN_W_M2, minY: -PLAN_H_M2, maxY: 0 };
64282
+ var WELD_M = 0.01;
64283
+ var r3 = (v) => Math.round(v * 1e3) / 1e3;
64284
+ var clamp2 = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
64285
+ function floorLabel(floorNo2) {
64286
+ return floorNo2 < 0 ? `B${-floorNo2}` : floorNo2 === 0 ? "G" : `L${floorNo2}`;
64240
64287
  }
64241
- function startRobotTracking(options) {
64242
- const {
64243
- credentials,
64244
- robotSn,
64245
- onEvent,
64246
- baseUrl = ROBOT_CLOUD_BASE_URL,
64247
- idleTimeoutMs = TRACKING_IDLE_TIMEOUT_MS,
64248
- openStream = openWithAxios,
64249
- now = Date.now
64250
- } = options;
64251
- if (!baseUrl)
64252
- throw new Error("Robot cloud: ROBOT_CLOUD_BASE_URL is not configured.");
64253
- let stopped = false;
64254
- let attempt = 0;
64255
- let current = null;
64256
- let watchdog = null;
64257
- let retry = null;
64258
- let lastActivityAt = now();
64259
- let everConnected = false;
64260
- const parser = createSseParser();
64261
- function clearTimers() {
64262
- if (watchdog) {
64263
- clearInterval(watchdog);
64264
- watchdog = null;
64265
- }
64266
- if (retry) {
64267
- clearTimeout(retry);
64268
- retry = null;
64269
- }
64270
- }
64271
- function dropUpstream() {
64272
- if (!current)
64273
- return;
64274
- try {
64275
- current.destroy();
64276
- } catch {
64288
+ function floorNoFromName(name) {
64289
+ if (typeof name !== "string")
64290
+ return null;
64291
+ const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
64292
+ if (m)
64293
+ return m[1].toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
64294
+ return /^G$/i.test(name.trim()) ? 0 : null;
64295
+ }
64296
+ function toPlan(f, p) {
64297
+ const w = f.maxX - f.minX || 1;
64298
+ const h = f.maxY - f.minY || 1;
64299
+ return { x: r3((p.x - f.minX) / w * PLAN_W_M2), y: r3((f.maxY - p.y) / h * PLAN_H_M2) };
64300
+ }
64301
+ function fromPlan(f, p) {
64302
+ 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)) };
64303
+ }
64304
+ function vertexPool(level2) {
64305
+ let next = level2.vertices.reduce((n, v) => Math.max(n, Number(/^v(\d+)$/.exec(v.id)?.[1] ?? 0)), 0) + 1;
64306
+ const byId = new Map(level2.vertices.map((v) => [v.id, v]));
64307
+ function at2(p, extra) {
64308
+ const x = r3(p.x);
64309
+ const y = r3(p.y);
64310
+ const hit = level2.vertices.find((v2) => Math.abs(v2.x - x) < WELD_M && Math.abs(v2.y - y) < WELD_M);
64311
+ if (hit) {
64312
+ if (extra?.name && !hit.name)
64313
+ hit.name = extra.name;
64314
+ if (extra?.params && Object.keys(extra.params).length)
64315
+ hit.params = { ...hit.params ?? {}, ...extra.params };
64316
+ return hit.id;
64277
64317
  }
64278
- current = null;
64318
+ const v = { id: `v${next++}`, x, y, ...extra?.name ? { name: extra.name } : {}, ...extra?.params && Object.keys(extra.params).length ? { params: extra.params } : {} };
64319
+ level2.vertices.push(v);
64320
+ byId.set(v.id, v);
64321
+ return v.id;
64279
64322
  }
64280
- function lose(reason) {
64281
- if (stopped)
64282
- return;
64283
- onEvent({ type: "lost", reason, at: now() });
64284
- dropUpstream();
64285
- scheduleReconnect();
64323
+ return { at: at2, get: (id) => byId.get(id) };
64324
+ }
64325
+ function emptyLevel(name, floorNo2, elevationM, planFrame) {
64326
+ return { name, floorNo: floorNo2, elevationM, planFrame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [] };
64327
+ }
64328
+ function emptyRmf(source = "editor") {
64329
+ return { formatVersion: 1, coordinateSystem: "cartesian_meters", source, graphs: [], levels: [], lifts: [] };
64330
+ }
64331
+ var collapseDoor = (t) => t === "sliding" || t === "double_sliding" ? "sliding" : "hinged";
64332
+ function pruneVertices(level2) {
64333
+ const used = /* @__PURE__ */ new Set();
64334
+ const add = (...ids2) => ids2.forEach((i) => used.add(i));
64335
+ level2.walls.forEach((e) => add(e.v1, e.v2));
64336
+ level2.doors.forEach((e) => add(e.v1, e.v2));
64337
+ level2.lanes.forEach((e) => add(e.v1, e.v2));
64338
+ level2.measurements.forEach((e) => add(e.v1, e.v2));
64339
+ [...level2.floors, ...level2.holes, ...level2.zones].forEach((p) => add(...p.vertices));
64340
+ level2.vertices = level2.vertices.filter((v) => used.has(v.id) || v.name || v.params && Object.keys(v.params).length);
64341
+ }
64342
+ function msgParams(params) {
64343
+ const out = {};
64344
+ for (const p of params ?? []) {
64345
+ if (!p?.name)
64346
+ continue;
64347
+ 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;
64286
64348
  }
64287
- function scheduleReconnect() {
64288
- if (stopped)
64289
- return;
64290
- clearTimers();
64291
- const delay2 = trackingBackoffMs(attempt++);
64292
- retry = setTimeout(connect2, delay2);
64349
+ return out;
64350
+ }
64351
+ var VERTEX_PARAM_KEYS = [
64352
+ "is_charger",
64353
+ "is_parking_spot",
64354
+ "is_holding_point",
64355
+ "is_passthrough_point",
64356
+ "is_cleaning_zone",
64357
+ "dock_name",
64358
+ "spawn_robot_name",
64359
+ "spawn_robot_type",
64360
+ "lift_cabin",
64361
+ "merge_radius",
64362
+ "mutex",
64363
+ "pickup_dispenser",
64364
+ "dropoff_ingestor",
64365
+ "human_goal_set_name"
64366
+ ];
64367
+ function vertexParams(raw) {
64368
+ const out = {};
64369
+ for (const k of VERTEX_PARAM_KEYS) {
64370
+ const v = raw[k];
64371
+ if (v === void 0 || v === "" || v === false)
64372
+ continue;
64373
+ out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? Number(v) : String(v).slice(0, 60);
64293
64374
  }
64294
- async function connect2() {
64295
- if (stopped)
64296
- return;
64297
- const body = robotCloudBody(
64298
- credentials.appid,
64299
- credentials.secret,
64300
- ROBOT_CLOUD_PATHS.tracking,
64301
- { robotSn }
64302
- );
64303
- let stream;
64304
- try {
64305
- stream = await openStream(
64306
- `${baseUrl.replace(/\/+$/, "")}${ROBOT_CLOUD_PATHS.tracking}`,
64307
- body
64308
- );
64309
- } catch (error) {
64310
- lose(error?.message ?? "Could not open the robot's tracking stream.");
64311
- return;
64375
+ return out;
64376
+ }
64377
+ var MSG_LIFT_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "telescope", 4: "double_telescope" };
64378
+ var MSG_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "sliding", 4: "double_sliding", 5: "hinged", 6: "double_hinged" };
64379
+ function importFrame(level2) {
64380
+ const xs = [];
64381
+ const ys = [];
64382
+ for (const g of level2.nav_graphs ?? [])
64383
+ for (const v of g.vertices ?? [])
64384
+ xs.push(v.x), ys.push(v.y);
64385
+ for (const d of level2.doors ?? [])
64386
+ xs.push(d.v1_x, d.v2_x), ys.push(d.v1_y, d.v2_y);
64387
+ if (!xs.length)
64388
+ for (const v of level2.wall_graph?.vertices ?? [])
64389
+ xs.push(v.x), ys.push(v.y);
64390
+ if (!xs.length)
64391
+ return { ...DEFAULT_PLAN_FRAME };
64392
+ const pad = 3;
64393
+ 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) };
64394
+ }
64395
+ var rot = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
64396
+ function rmfFromFleetCore(msg) {
64397
+ const rmf = emptyRmf("fleet-core");
64398
+ const graphIdx = /* @__PURE__ */ new Map();
64399
+ const usedFloors = /* @__PURE__ */ new Set();
64400
+ for (const [i, lv] of (msg.levels ?? []).slice(0, 200).entries()) {
64401
+ let floorNo2 = floorNoFromName(lv.name) ?? i + 1;
64402
+ while (usedFloors.has(floorNo2))
64403
+ floorNo2++;
64404
+ usedFloors.add(floorNo2);
64405
+ const level2 = emptyLevel(String(lv.name).slice(0, 60), floorNo2, Number(lv.elevation ?? 0), importFrame(lv));
64406
+ const pool = vertexPool(level2);
64407
+ const wg = lv.wall_graph;
64408
+ for (const e of (wg?.edges ?? []).slice(0, 5e3)) {
64409
+ const a = wg.vertices[e.v1_idx];
64410
+ const b = wg.vertices[e.v2_idx];
64411
+ if (a && b)
64412
+ level2.walls.push({ v1: pool.at(a), v2: pool.at(b) });
64312
64413
  }
64313
- if (stopped) {
64314
- try {
64315
- stream.destroy();
64316
- } catch {
64317
- }
64318
- return;
64414
+ for (const d of (lv.doors ?? []).slice(0, 500)) {
64415
+ level2.doors.push({
64416
+ name: String(d.name).slice(0, 60),
64417
+ v1: pool.at({ x: d.v1_x, y: d.v1_y }),
64418
+ v2: pool.at({ x: d.v2_x, y: d.v2_y }),
64419
+ type: MSG_DOOR_TYPE[d.door_type] ?? "hinged",
64420
+ // Kept only where they differ from traffic-editor's defaults (90 degrees, direction 1) - the same as a file import.
64421
+ ...d.motion_range && r3(d.motion_range * 180 / Math.PI) !== 90 ? { motionDegrees: r3(d.motion_range * 180 / Math.PI) } : {},
64422
+ ...d.motion_direction && d.motion_direction < 0 ? { motionDirection: -1 } : {}
64423
+ });
64319
64424
  }
64320
- parser.reset();
64321
- current = stream;
64322
- lastActivityAt = now();
64323
- if (everConnected)
64324
- onEvent({ type: "reconnected", at: now() });
64325
- everConnected = true;
64326
- attempt = 0;
64327
- stream.on("data", (chunk2) => {
64328
- if (stopped)
64329
- return;
64330
- const { events, sawActivity } = parser.push(chunk2.toString("utf8"));
64331
- if (sawActivity)
64332
- lastActivityAt = now();
64333
- for (const event of events) {
64334
- const pose = decodeTrackingFrame(event.data);
64335
- if (pose)
64336
- onEvent({ type: "pose", pose, at: now() });
64425
+ for (const [gi, g] of (lv.nav_graphs ?? []).entries()) {
64426
+ const key = String(g.name ?? gi);
64427
+ if (!graphIdx.has(key)) {
64428
+ const n = Number(key);
64429
+ graphIdx.set(key, Number.isInteger(n) && n >= 0 && n <= 8 ? n : Math.min(8, graphIdx.size));
64430
+ }
64431
+ const idx = graphIdx.get(key);
64432
+ 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)) }));
64433
+ for (const e of (g.edges ?? []).slice(0, 5e3)) {
64434
+ const a = ids2[e.v1_idx];
64435
+ const b = ids2[e.v2_idx];
64436
+ if (!a || !b || a === b)
64437
+ continue;
64438
+ const p = msgParams(e.params);
64439
+ level2.lanes.push({
64440
+ v1: a,
64441
+ v2: b,
64442
+ graphIdx: idx,
64443
+ bidirectional: (e.edge_type ?? 0) === 0,
64444
+ ...Number(p.speed_limit) > 0 ? { speedLimit: Number(p.speed_limit) } : {},
64445
+ ...p.mutex ? { mutex: String(p.mutex).slice(0, 60) } : {}
64446
+ });
64337
64447
  }
64448
+ }
64449
+ rmf.levels.push(level2);
64450
+ }
64451
+ rmf.graphs = [...new Set(graphIdx.values())].sort((a, b) => a - b).map((idx) => ({ idx, name: `Graph ${idx}`, brands: ["fleet-core"] }));
64452
+ rmf.referenceLevel = rmf.levels[0]?.name;
64453
+ const levelNames = new Set(rmf.levels.map((l) => l.name));
64454
+ for (const l of (msg.lifts ?? []).slice(0, 50)) {
64455
+ const yaw = Number(l.ref_yaw ?? 0);
64456
+ const doors = (l.doors ?? []).slice(0, 8).map((d) => {
64457
+ const a = rot(d.v1_x - l.ref_x, d.v1_y - l.ref_y, -yaw);
64458
+ const b = rot(d.v2_x - l.ref_x, d.v2_y - l.ref_y, -yaw);
64459
+ return {
64460
+ name: String(d.name).slice(0, 60),
64461
+ type: MSG_LIFT_DOOR_TYPE[d.door_type] ?? "sliding",
64462
+ x: r3((a.x + b.x) / 2),
64463
+ y: r3((a.y + b.y) / 2),
64464
+ widthM: r3(Math.hypot(b.x - a.x, b.y - a.y)),
64465
+ axisYawRad: r3(Math.atan2(b.y - a.y, b.x - a.x))
64466
+ };
64338
64467
  });
64339
- stream.on("error", (error) => lose(error?.message ?? "The tracking stream failed."));
64340
- stream.on("end", () => lose("The robot cloud closed the tracking stream."));
64341
- stream.on("close", () => {
64342
- if (!stopped && current === stream)
64343
- lose("The tracking stream closed.");
64468
+ const served = (l.levels ?? []).filter((n) => levelNames.has(n));
64469
+ rmf.lifts.push({
64470
+ name: String(l.name).slice(0, 60),
64471
+ x: r3(l.ref_x),
64472
+ y: r3(l.ref_y),
64473
+ yawRad: r3(yaw),
64474
+ widthM: r3(l.width),
64475
+ depthM: r3(l.depth),
64476
+ referenceFloor: served[0] ?? rmf.referenceLevel ?? "",
64477
+ levelDoors: served.map((level2) => ({ level: level2, doors: doors.map((d) => d.name) })),
64478
+ doors
64344
64479
  });
64345
- clearTimers();
64346
- watchdog = setInterval(() => {
64347
- if (stopped)
64348
- return;
64349
- if (now() - lastActivityAt >= idleTimeoutMs) {
64350
- lose("The robot stopped reporting.");
64351
- }
64352
- }, Math.max(1e3, Math.floor(idleTimeoutMs / 3)));
64353
64480
  }
64354
- void connect2();
64355
- return {
64356
- stop() {
64357
- if (stopped)
64358
- return;
64359
- stopped = true;
64360
- clearTimers();
64361
- dropUpstream();
64362
- }
64363
- };
64481
+ return rmf;
64364
64482
  }
64365
-
64366
- // src/controllers/robot-fleet.controller.ts
64367
- import Joi76 from "joi";
64368
- import { BadRequestError as BadRequestError135, logger as logger108 } from "@7365admin1/node-server-utils";
64369
-
64370
- // src/services/robot-fault.service.ts
64371
- import { logger as logger107 } from "@7365admin1/node-server-utils";
64372
-
64373
- // src/repositories/robot-fault.repo.ts
64374
- import { ObjectId as ObjectId108 } from "mongodb";
64375
- import { InternalServerError as InternalServerError50, useAtlas as useAtlas80 } from "@7365admin1/node-server-utils";
64376
- var toId3 = (v) => v instanceof ObjectId108 ? v : new ObjectId108(String(v));
64377
- function useRobotFaultRepo() {
64378
- const db2 = useAtlas80.getDb();
64379
- if (!db2)
64380
- throw new InternalServerError50("Unable to connect to server.");
64381
- const collection = db2.collection(ROBOT_FAULTS_COLLECTION);
64382
- async function createIndex() {
64383
- try {
64384
- await collection.createIndexes([
64385
- {
64386
- key: { robotId: 1, code: 1 },
64387
- name: "one_open_fault_per_robot_code",
64388
- unique: true,
64389
- partialFilterExpression: { clearedAt: null }
64390
- },
64391
- { key: { clearedAt: 1, since: 1 }, name: "open_faults_by_since" }
64392
- ]);
64393
- } catch (error) {
64394
- throw new InternalServerError50("Failed to create index on robot faults.");
64483
+ function legacyFromRmf(rmf) {
64484
+ const levels = [];
64485
+ const doors = [];
64486
+ for (const lv of rmf.levels) {
64487
+ const v = new Map(lv.vertices.map((x) => [x.id, x]));
64488
+ const p = (id) => {
64489
+ const q = v.get(id);
64490
+ return q ? toPlan(lv.planFrame, q) : null;
64491
+ };
64492
+ const walls = lv.walls.flatMap((w) => {
64493
+ const a = p(w.v1);
64494
+ const b = p(w.v2);
64495
+ return a && b ? [{ start: a, end: b }] : [];
64496
+ });
64497
+ const zones = lv.zones.flatMap((z5) => {
64498
+ const points = z5.vertices.map(p).filter((q) => !!q);
64499
+ return points.length >= 3 ? [{ name: z5.name, points: points.slice(0, 200) }] : [];
64500
+ });
64501
+ levels.push({ floorNo: lv.floorNo, name: lv.name, elevationM: lv.elevationM, walls: walls.slice(0, 2e3), zones: zones.slice(0, 200) });
64502
+ for (const d of lv.doors) {
64503
+ const a = p(d.v1);
64504
+ const b = p(d.v2);
64505
+ if (a && b)
64506
+ doors.push({ name: d.name, floorNo: lv.floorNo, type: collapseDoor(d.type), start: a, end: b });
64395
64507
  }
64396
64508
  }
64397
- async function getOpenFaults() {
64398
- return collection.find({ clearedAt: null }, { projection: { robotId: 1, code: 1, since: 1 } }).toArray();
64509
+ const byName = new Map(rmf.levels.map((l) => [l.name, l]));
64510
+ const lifts = [];
64511
+ for (const l of rmf.lifts) {
64512
+ const withDoors = l.levelDoors.filter((x) => x.doors.length).map((x) => byName.get(x.level)?.floorNo);
64513
+ let floors = [...new Set(withDoors.filter((n) => typeof n === "number"))];
64514
+ if (floors.length < 2)
64515
+ floors = rmf.levels.map((x) => x.floorNo);
64516
+ if (floors.length < 2)
64517
+ continue;
64518
+ const ref = byName.get(l.referenceFloor) ?? rmf.levels[0];
64519
+ if (!ref)
64520
+ continue;
64521
+ const c = toPlan(ref.planFrame, l);
64522
+ const f = ref.planFrame;
64523
+ lifts.push({
64524
+ name: l.name,
64525
+ x: c.x,
64526
+ y: c.y,
64527
+ widthM: r3(clamp2(l.widthM / (f.maxX - f.minX || 1) * PLAN_W_M2, 0.5, 10)),
64528
+ depthM: r3(clamp2(l.depthM / (f.maxY - f.minY || 1) * PLAN_H_M2, 0.5, 10)),
64529
+ floors: floors.sort((a, b) => a - b)
64530
+ });
64399
64531
  }
64400
- async function getOpenFault(robotId, code) {
64401
- return collection.findOne({ robotId: toId3(robotId), code, clearedAt: null });
64532
+ return { levels, doors: doors.slice(0, 500), lifts };
64533
+ }
64534
+ var defaultCabinDoor = (l) => ({
64535
+ name: "door1",
64536
+ type: "double_sliding",
64537
+ x: r3(l.widthM / 2),
64538
+ y: 0,
64539
+ widthM: r3(Math.min(1.2, l.depthM * 0.8)),
64540
+ axisYawRad: r3(Math.PI / 2)
64541
+ });
64542
+ function mergeLegacyIntoRmf(prev, legacy) {
64543
+ const base = prev ? structuredClone(prev) : emptyRmf("editor");
64544
+ const refFrame = base.levels[0]?.planFrame ?? DEFAULT_PLAN_FRAME;
64545
+ const legacyFloors = new Map((legacy.levels ?? []).map((l) => [l.floorNo, l]));
64546
+ const allFloors = /* @__PURE__ */ new Set([
64547
+ ...legacyFloors.keys(),
64548
+ ...(legacy.doors ?? []).map((d) => d.floorNo),
64549
+ ...(legacy.lifts ?? []).flatMap((l) => l.floors)
64550
+ ]);
64551
+ for (const floorNo2 of allFloors) {
64552
+ if (base.levels.some((l) => l.floorNo === floorNo2))
64553
+ continue;
64554
+ base.levels.push(emptyLevel(legacyFloors.get(floorNo2)?.name || floorLabel(floorNo2), floorNo2, legacyFloors.get(floorNo2)?.elevationM ?? 0, { ...refFrame }));
64402
64555
  }
64403
- async function openFault(doc) {
64404
- const now = /* @__PURE__ */ new Date();
64405
- try {
64406
- const res = await collection.insertOne({
64407
- robotId: toId3(doc.robotId),
64408
- orgId: doc.orgId ? toId3(doc.orgId) : null,
64409
- siteId: doc.siteId ? toId3(doc.siteId) : null,
64410
- code: doc.code,
64411
- message: doc.message,
64412
- since: doc.since,
64413
- clearedAt: null,
64414
- notifiedAt: null,
64415
- createdAt: now
64556
+ base.levels.sort((a, b) => a.floorNo - b.floorNo);
64557
+ for (const lv of base.levels) {
64558
+ const src = legacyFloors.get(lv.floorNo);
64559
+ if (src?.name)
64560
+ lv.name = String(src.name).slice(0, 60);
64561
+ if (typeof src?.elevationM === "number")
64562
+ lv.elevationM = src.elevationM;
64563
+ const prevDoors = new Map(lv.doors.map((d) => [d.name, d]));
64564
+ lv.walls = [];
64565
+ lv.zones = [];
64566
+ lv.doors = [];
64567
+ const pool = vertexPool(lv);
64568
+ const at2 = (p) => pool.at(fromPlan(lv.planFrame, p));
64569
+ for (const w of src?.walls ?? [])
64570
+ lv.walls.push({ v1: at2(w.start), v2: at2(w.end) });
64571
+ for (const z5 of src?.zones ?? [])
64572
+ lv.zones.push({ name: z5.name, vertices: z5.points.map(at2) });
64573
+ for (const d of (legacy.doors ?? []).filter((x) => x.floorNo === lv.floorNo)) {
64574
+ const was = prevDoors.get(d.name);
64575
+ const keep = was && collapseDoor(was.type) === d.type;
64576
+ lv.doors.push({
64577
+ ...keep ? was : {},
64578
+ name: d.name,
64579
+ v1: at2(d.start),
64580
+ v2: at2(d.end),
64581
+ type: keep ? was.type : d.type
64416
64582
  });
64417
- return res.insertedId;
64418
- } catch (error) {
64419
- if (error?.code === 11e3)
64420
- return null;
64421
- throw error;
64422
64583
  }
64584
+ pruneVertices(lv);
64423
64585
  }
64424
- async function claimNotify(id) {
64425
- const res = await collection.updateOne(
64426
- { _id: toId3(id), clearedAt: null, notifiedAt: null },
64427
- { $set: { notifiedAt: /* @__PURE__ */ new Date() } }
64428
- );
64429
- return res.modifiedCount === 1;
64430
- }
64431
- async function claimOfflineAlert(id, cutoff) {
64432
- const res = await collection.updateOne(
64433
- { _id: toId3(id), code: "OFFLINE", clearedAt: null, since: { $lte: cutoff }, offlineNotifiedAt: null },
64434
- { $set: { offlineNotifiedAt: /* @__PURE__ */ new Date() } }
64435
- );
64436
- return res.modifiedCount === 1;
64437
- }
64438
- async function claimRecoveryAlert(id) {
64439
- const res = await collection.updateOne(
64440
- { _id: toId3(id), code: "OFFLINE", offlineNotifiedAt: { $ne: null }, recoveryNotifiedAt: null },
64441
- { $set: { recoveryNotifiedAt: /* @__PURE__ */ new Date() } }
64442
- );
64443
- return res.modifiedCount === 1;
64444
- }
64445
- async function findNotifiedOccurrence(robotId, code, since, after) {
64446
- const filter = {
64447
- clearedAt: { $gte: after },
64448
- robotId: toId3(robotId),
64449
- code,
64450
- notifiedAt: { $ne: null }
64451
- };
64452
- if (since)
64453
- filter.since = { $gte: new Date(since.getTime() - 1e3), $lte: new Date(since.getTime() + 1e3) };
64454
- return collection.findOne(filter, { projection: { notifiedAt: 1 } });
64455
- }
64456
- async function markNotified(id, at2) {
64457
- await collection.updateOne({ _id: toId3(id), notifiedAt: null }, { $set: { notifiedAt: at2 } });
64458
- }
64459
- async function clearFault(id) {
64460
- await collection.updateOne(
64461
- { _id: toId3(id), clearedAt: null },
64462
- { $set: { clearedAt: /* @__PURE__ */ new Date() } }
64463
- );
64464
- }
64465
- async function listNetworkFaults(q) {
64466
- const page = Math.max(1, Math.floor(q.page || 1));
64467
- const limit = Math.min(100, Math.max(1, Math.floor(q.limit || 25)));
64468
- const [res] = await collection.aggregate(networkFaultsPipeline({ ...q, page, limit })).toArray();
64469
- const total = res?.total?.[0]?.n ?? 0;
64470
- const faults = res?.faults?.[0]?.n ?? 0;
64471
- return { items: res?.items ?? [], page, limit, pages: Math.ceil(total / limit), total, faults };
64586
+ const prevLifts = new Map(base.lifts.map((l) => [l.name, l]));
64587
+ const byFloor = new Map(base.levels.map((l) => [l.floorNo, l]));
64588
+ base.lifts = (legacy.lifts ?? []).map((l) => {
64589
+ const was = prevLifts.get(l.name);
64590
+ const ref = was && base.levels.find((x) => x.name === was.referenceFloor) || byFloor.get(l.floors[0]) || base.levels[0];
64591
+ const f = ref.planFrame;
64592
+ const c = fromPlan(f, l);
64593
+ const widthM = r3(l.widthM / PLAN_W_M2 * (f.maxX - f.minX));
64594
+ const depthM = r3(l.depthM / PLAN_H_M2 * (f.maxY - f.minY));
64595
+ const doors = was?.doors?.length ? was.doors : [defaultCabinDoor({ widthM, depthM })];
64596
+ const served = l.floors.map((n) => byFloor.get(n)?.name).filter((n) => !!n);
64597
+ const prevLevelDoors = new Map((was?.levelDoors ?? []).map((x) => [x.level, x.doors]));
64598
+ return {
64599
+ name: l.name,
64600
+ x: c.x,
64601
+ y: c.y,
64602
+ yawRad: was?.yawRad ?? 0,
64603
+ widthM,
64604
+ depthM,
64605
+ referenceFloor: ref.name,
64606
+ ...was?.initialFloor && served.includes(was.initialFloor) ? { initialFloor: was.initialFloor } : {},
64607
+ doors,
64608
+ levelDoors: served.map((level2) => ({ level: level2, doors: prevLevelDoors.get(level2)?.length ? prevLevelDoors.get(level2) : doors.map((d) => d.name) }))
64609
+ };
64610
+ });
64611
+ base.referenceLevel = base.levels.find((l) => l.name === base.referenceLevel)?.name ?? base.levels[0]?.name;
64612
+ return base;
64613
+ }
64614
+ function rmfProblem(rmf) {
64615
+ const levelNames = /* @__PURE__ */ new Set();
64616
+ const doorNames = /* @__PURE__ */ new Set();
64617
+ const graphIdx = new Set(rmf.graphs.map((g) => g.idx));
64618
+ for (const lv of rmf.levels) {
64619
+ if (levelNames.has(lv.name))
64620
+ return `Two floors are both called "${lv.name}".`;
64621
+ levelNames.add(lv.name);
64622
+ const f = lv.planFrame;
64623
+ if (!(f.maxX > f.minX && f.maxY > f.minY))
64624
+ return `Floor ${lv.name}: its plan frame is empty.`;
64625
+ const ids2 = /* @__PURE__ */ new Set();
64626
+ for (const v of lv.vertices) {
64627
+ if (ids2.has(v.id))
64628
+ return `Floor ${lv.name}: point id "${v.id}" is used twice.`;
64629
+ ids2.add(v.id);
64630
+ }
64631
+ const missing = (id) => !ids2.has(id);
64632
+ const edges = [...lv.walls, ...lv.doors, ...lv.lanes, ...lv.measurements];
64633
+ if (edges.some((e) => missing(e.v1) || missing(e.v2)))
64634
+ return `Floor ${lv.name}: a line ends at a point that does not exist.`;
64635
+ if ([...lv.floors, ...lv.holes, ...lv.zones].some((p) => p.vertices.some(missing)))
64636
+ return `Floor ${lv.name}: an area uses a point that does not exist.`;
64637
+ for (const d of lv.doors) {
64638
+ if (doorNames.has(d.name))
64639
+ return `Two doors are both called "${d.name}" - door names must be unique in the building.`;
64640
+ doorNames.add(d.name);
64641
+ }
64642
+ if (lv.lanes.some((l) => !graphIdx.has(l.graphIdx)))
64643
+ return `Floor ${lv.name}: a lane belongs to a route graph that is not listed.`;
64644
+ }
64645
+ for (const l of rmf.lifts) {
64646
+ const cabin = new Set(l.doors.map((d) => d.name));
64647
+ if (l.referenceFloor && !levelNames.has(l.referenceFloor))
64648
+ return `Lift ${l.name}: its reference floor "${l.referenceFloor}" does not exist.`;
64649
+ for (const [what, floor] of [["lowest", l.lowestFloor], ["highest", l.highestFloor], ["first", l.initialFloor]]) {
64650
+ if (floor && !levelNames.has(floor))
64651
+ return `Lift ${l.name}: its ${what} floor "${floor}" does not exist.`;
64652
+ }
64653
+ for (const x of l.levelDoors) {
64654
+ if (!levelNames.has(x.level))
64655
+ return `Lift ${l.name}: floor "${x.level}" does not exist.`;
64656
+ if (x.doors.some((d) => !cabin.has(d)))
64657
+ return `Lift ${l.name}: floor ${x.level} opens a cabin door the lift does not have.`;
64658
+ }
64659
+ }
64660
+ return null;
64661
+ }
64662
+ var P = { str: (v) => [1, v], int: (v) => [2, Math.round(v)], dbl: (v) => [3, v], bool: (v) => [4, v] };
64663
+ function vertexParamYaml(k, val) {
64664
+ if (k === "merge_radius")
64665
+ return P.dbl(Number(val));
64666
+ if (typeof val === "boolean")
64667
+ return P.bool(val);
64668
+ return P.str(String(val ?? ""));
64669
+ }
64670
+ function liftFloorRange(l, levels) {
64671
+ const elevation = new Map(levels.map((x) => [x.name, x.elevationM]));
64672
+ const served = l.levelDoors.map((x) => x.level).sort((a, b) => (elevation.get(a) ?? 0) - (elevation.get(b) ?? 0));
64673
+ return {
64674
+ lowest: l.lowestFloor || served[0] || l.referenceFloor,
64675
+ highest: l.highestFloor || served[served.length - 1] || l.referenceFloor,
64676
+ initial: l.initialFloor || served[0] || l.referenceFloor
64677
+ };
64678
+ }
64679
+ function toBuildingYaml(name, rmf) {
64680
+ const levels = {};
64681
+ for (const lv of rmf.levels) {
64682
+ const idx = new Map(lv.vertices.map((v, i) => [v.id, i]));
64683
+ const edge2 = (v1, v2, params) => [idx.get(v1), idx.get(v2), params];
64684
+ const f = lv.planFrame;
64685
+ levels[lv.name] = {
64686
+ elevation: lv.elevationM,
64687
+ hero_floor_no: lv.floorNo,
64688
+ hero_plan_frame: [f.minX, f.minY, f.maxX, f.maxY],
64689
+ vertices: lv.vertices.map((v) => {
64690
+ const params = {};
64691
+ for (const [k, val] of Object.entries(v.params ?? {}))
64692
+ if (val !== void 0)
64693
+ params[k] = vertexParamYaml(k, val);
64694
+ return [v.x, v.y, 0, v.name ?? "", params];
64695
+ }),
64696
+ walls: lv.walls.map(
64697
+ (w) => edge2(w.v1, w.v2, {
64698
+ alpha: P.dbl(w.alpha ?? 1),
64699
+ texture_height: P.dbl(w.textureHeight ?? 2.5),
64700
+ texture_name: P.str(w.textureName ?? "default"),
64701
+ texture_scale: P.dbl(w.textureScale ?? 1),
64702
+ texture_width: P.dbl(w.textureWidth ?? 1)
64703
+ })
64704
+ ),
64705
+ doors: lv.doors.map(
64706
+ (d) => edge2(d.v1, d.v2, {
64707
+ motion_axis: P.str(d.motionAxis ?? "start"),
64708
+ motion_degrees: P.dbl(d.motionDegrees ?? 90),
64709
+ motion_direction: P.int(d.motionDirection ?? 1),
64710
+ name: P.str(d.name),
64711
+ plugin: P.str(d.plugin ?? "normal"),
64712
+ right_left_ratio: P.dbl(d.rightLeftRatio ?? 1),
64713
+ type: P.str(d.type)
64714
+ })
64715
+ ),
64716
+ lanes: lv.lanes.map(
64717
+ (l) => edge2(l.v1, l.v2, {
64718
+ bidirectional: P.bool(l.bidirectional),
64719
+ demo_mock_floor_name: P.str(l.demoMockFloorName ?? ""),
64720
+ demo_mock_lift_name: P.str(l.demoMockLiftName ?? ""),
64721
+ graph_idx: P.int(l.graphIdx),
64722
+ mutex: P.str(l.mutex ?? ""),
64723
+ orientation: P.str(l.orientation ?? ""),
64724
+ speed_limit: P.dbl(l.speedLimit ?? 0)
64725
+ })
64726
+ ),
64727
+ measurements: lv.measurements.map((m) => edge2(m.v1, m.v2, { distance: P.dbl(m.distanceM) })),
64728
+ floors: lv.floors.map((p) => ({ vertices: p.vertices.map((id) => idx.get(id)), parameters: {} })),
64729
+ holes: lv.holes.map((p) => ({ vertices: p.vertices.map((id) => idx.get(id)), parameters: {} })),
64730
+ fiducials: lv.fiducials.map((p) => [p.x, p.y, p.name]),
64731
+ ...lv.zones.length ? { hero_zones: lv.zones.map((z5) => ({ name: z5.name, vertices: z5.vertices.map((id) => idx.get(id)) })) } : {},
64732
+ layers: {},
64733
+ models: []
64734
+ };
64735
+ }
64736
+ const lifts = {};
64737
+ for (const l of rmf.lifts) {
64738
+ const range = liftFloorRange(l, rmf.levels);
64739
+ lifts[l.name] = {
64740
+ x: l.x,
64741
+ y: l.y,
64742
+ yaw: l.yawRad,
64743
+ width: l.widthM,
64744
+ depth: l.depthM,
64745
+ reference_floor_name: l.referenceFloor,
64746
+ initial_floor_name: range.initial,
64747
+ lowest_floor: range.lowest,
64748
+ highest_floor: range.highest,
64749
+ doors: Object.fromEntries(
64750
+ 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 }])
64751
+ ),
64752
+ level_doors: Object.fromEntries(l.levelDoors.map((x) => [x.level, x.doors])),
64753
+ plugins: l.plugins ?? true
64754
+ };
64755
+ }
64756
+ const graphs = Object.fromEntries(
64757
+ rmf.graphs.map((g) => [String(g.idx), { name: g.name, default_lane_width: 1, ...g.brands.length ? { hero_brands: g.brands } : {} }])
64758
+ );
64759
+ return JSON.stringify(
64760
+ { name, coordinate_system: "cartesian_meters", reference_level_name: rmf.referenceLevel ?? rmf.levels[0]?.name ?? "", graphs, parameters: {}, levels, lifts },
64761
+ null,
64762
+ 1
64763
+ );
64764
+ }
64765
+ function segmentsIntersect(a, b, c, d) {
64766
+ const det = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
64767
+ if (Math.abs(det) < 0.01)
64768
+ return false;
64769
+ const t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / det;
64770
+ const u = -((a.x - b.x) * (a.y - c.y) - (a.y - b.y) * (a.x - c.x)) / det;
64771
+ return t >= 0 && t <= 1 && u >= 0 && u <= 1;
64772
+ }
64773
+ function liftShaft(l) {
64774
+ const d = l.depthM / 2 + 0.05;
64775
+ const w = l.widthM / 2 + 0.05;
64776
+ const s = Math.sin(l.yawRad);
64777
+ const c = Math.cos(l.yawRad);
64778
+ return [
64779
+ { x: l.x - d * s - w * c, y: l.y + d * c - w * s },
64780
+ { x: l.x + d * s - w * c, y: l.y - d * c - w * s },
64781
+ { x: l.x + d * s + w * c, y: l.y - d * c + w * s },
64782
+ { x: l.x - d * s + w * c, y: l.y + d * c + w * s }
64783
+ ];
64784
+ }
64785
+ function inShaft(p, verts) {
64786
+ const cross = verts.map((v, i) => {
64787
+ const prev = verts[(i + 3) % 4];
64788
+ const a = { x: v.x - p.x, y: v.y - p.y };
64789
+ const b = { x: prev.x - v.x, y: prev.y - v.y };
64790
+ return a.x * b.y - a.y * b.x;
64791
+ });
64792
+ return cross.every((c) => c >= 0) || cross.every((c) => c <= 0);
64793
+ }
64794
+ function toNavGraphs(name, rmf) {
64795
+ const out = {};
64796
+ const elevation = new Map(rmf.levels.map((l) => [l.name, l.elevationM]));
64797
+ const shafts = rmf.lifts.map((l) => {
64798
+ const range = liftFloorRange(l, rmf.levels);
64799
+ return {
64800
+ lift: l,
64801
+ verts: liftShaft(l),
64802
+ // lift.py: no lowest / highest floor = no bound; a lift with no level_doors marks nothing.
64803
+ lo: elevation.get(range.lowest) ?? -Infinity,
64804
+ hi: elevation.get(range.highest) ?? Infinity,
64805
+ hasDoors: l.levelDoors.length > 0
64806
+ };
64807
+ });
64808
+ for (let gi = 0; gi <= 8; gi++) {
64809
+ const levels = {};
64810
+ const doors = {};
64811
+ let empty = true;
64812
+ for (const lv of rmf.levels) {
64813
+ const v = new Map(lv.vertices.map((x) => [x.id, x]));
64814
+ const lanes = lv.lanes.filter((l) => l.graphIdx === gi && v.has(l.v1) && v.has(l.v2));
64815
+ if (lanes.length)
64816
+ empty = false;
64817
+ const order = [];
64818
+ const mapped = /* @__PURE__ */ new Map();
64819
+ for (const l of lanes)
64820
+ for (const id of [l.v1, l.v2])
64821
+ if (!mapped.has(id))
64822
+ mapped.set(id, order.push(id) - 1);
64823
+ const here = shafts.filter((s) => s.hasDoors && lv.elevationM >= s.lo && lv.elevationM <= s.hi);
64824
+ const vertices = order.map((id) => {
64825
+ const q = v.get(id);
64826
+ const lift2 = here.find((s) => inShaft(q, s.verts))?.lift;
64827
+ return [q.x, q.y, { name: q.name ?? "", ...q.params ?? {}, ...lift2 ? { lift: lift2.name } : {} }];
64828
+ });
64829
+ const navLanes = [];
64830
+ for (const l of lanes) {
64831
+ const a = v.get(l.v1);
64832
+ const b = v.get(l.v2);
64833
+ const p = {};
64834
+ for (const d of lv.doors) {
64835
+ const c = v.get(d.v1);
64836
+ const e = v.get(d.v2);
64837
+ if (c && e && segmentsIntersect(a, b, c, e))
64838
+ p.door_name = d.name;
64839
+ }
64840
+ if (l.orientation)
64841
+ p.orientation_constraint = l.orientation;
64842
+ if (l.speedLimit && l.speedLimit > 0)
64843
+ p.speed_limit = l.speedLimit;
64844
+ if (l.mutex)
64845
+ p.mutex = l.mutex;
64846
+ if (l.demoMockFloorName)
64847
+ p.demo_mock_floor_name = l.demoMockFloorName;
64848
+ if (l.demoMockLiftName)
64849
+ p.demo_mock_lift_name = l.demoMockLiftName;
64850
+ const endDock = b.params?.dock_name;
64851
+ const startDock = a.params?.dock_name;
64852
+ const s = mapped.get(l.v1);
64853
+ const t = mapped.get(l.v2);
64854
+ if (l.bidirectional) {
64855
+ const fwd = { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} };
64856
+ const back = { ...p, ...endDock ? { undock_name: endDock } : {}, ...startDock ? { dock_name: startDock } : {} };
64857
+ if (l.orientation)
64858
+ back.orientation_constraint = l.orientation === "forward" ? "backward" : "forward";
64859
+ navLanes.push([s, t, fwd], [t, s, back]);
64860
+ } else {
64861
+ navLanes.push([s, t, { ...p, is_bidirectional: false, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} }]);
64862
+ }
64863
+ }
64864
+ levels[lv.name] = { vertices, lanes: navLanes };
64865
+ for (const d of lv.doors) {
64866
+ const c = v.get(d.v1);
64867
+ const e = v.get(d.v2);
64868
+ if (c && e)
64869
+ doors[d.name] = { endpoints: [[c.x, c.y], [e.x, e.y]], map: lv.name };
64870
+ }
64871
+ }
64872
+ if (empty)
64873
+ continue;
64874
+ const lifts = Object.fromEntries(rmf.lifts.map((l) => [l.name, { position: [l.x, l.y, l.yawRad], dims: [l.widthM, l.depthM] }]));
64875
+ out[gi] = JSON.stringify({ building_name: name, levels, lifts, doors, offset: [0, 0] }, null, 1);
64876
+ }
64877
+ return out;
64878
+ }
64879
+ var RmfImportError = class extends Error {
64880
+ };
64881
+ var IDENTITY = { scale: 1, rot: 0, tx: 0, ty: 0 };
64882
+ function applyXform(t, p) {
64883
+ const q = rot(p.x, p.y, t.rot);
64884
+ return { x: q.x * t.scale + t.tx, y: q.y * t.scale + t.ty };
64885
+ }
64886
+ function fiducialTransform(pairs, refScale) {
64887
+ const bearing = (a, b) => Math.atan2(b.y - a.y, b.x - a.x);
64888
+ const dist = (a, b) => Math.hypot(b.x - a.x, b.y - a.y);
64889
+ const bearings = [];
64890
+ const distances = [];
64891
+ for (let i = 0; i < pairs.length; i++) {
64892
+ for (let j = i + 1; j < pairs.length; j++) {
64893
+ bearings.push([bearing(pairs[i][0], pairs[j][0]), bearing(pairs[i][1], pairs[j][1])]);
64894
+ distances.push([dist(pairs[i][0], pairs[j][0]), dist(pairs[i][1], pairs[j][1])]);
64895
+ }
64896
+ }
64897
+ if (!bearings.length)
64898
+ return null;
64899
+ let sinSum = 0;
64900
+ let cosSum = 0;
64901
+ for (const [ref, target] of bearings) {
64902
+ sinSum += Math.sin(target - ref);
64903
+ cosSum += Math.cos(target - ref);
64904
+ }
64905
+ const rotation = -Math.atan2(sinSum, cosSum);
64906
+ const rel = distances.reduce((n, [ref, target]) => n + target / (ref || 1e-9), 0) / distances.length;
64907
+ if (!(rel > 0) || !Number.isFinite(rel))
64908
+ return null;
64909
+ let tx = 0;
64910
+ let ty = 0;
64911
+ for (const [f0, f1] of pairs) {
64912
+ const q = rot(f1.x / rel, f1.y / rel, rotation);
64913
+ tx += q.x - f0.x;
64914
+ ty += q.y - f0.y;
64915
+ }
64916
+ return { scale: refScale / rel, rot: rotation, tx: tx * -refScale / pairs.length, ty: ty * -refScale / pairs.length };
64917
+ }
64918
+ function measurementScale(vertices, meas) {
64919
+ const est = meas.flatMap(([a, b, d]) => {
64920
+ const p = vertices[a];
64921
+ const q = vertices[b];
64922
+ const len = p && q ? Math.hypot(q.x - p.x, q.y - p.y) : 0;
64923
+ return len > 0 && d > 0 ? [d / len] : [];
64924
+ });
64925
+ return est.length ? est.reduce((n, v) => n + v, 0) / est.length : null;
64926
+ }
64927
+ var pval = (p) => Array.isArray(p) ? p[1] : p;
64928
+ var num = (v, fallback = 0) => v !== null && v !== "" && Number.isFinite(Number(v)) ? Number(v) : fallback;
64929
+ var str60 = (v) => String(v ?? "").slice(0, 60);
64930
+ function decodeParams(raw) {
64931
+ const out = {};
64932
+ if (raw && typeof raw === "object" && !Array.isArray(raw))
64933
+ for (const [k, v] of Object.entries(raw))
64934
+ out[k] = pval(v);
64935
+ return out;
64936
+ }
64937
+ function edgeList(raw) {
64938
+ return (Array.isArray(raw) ? raw : []).flatMap(
64939
+ (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]) }] : []
64940
+ );
64941
+ }
64942
+ function fileVertexParams(raw) {
64943
+ const out = {};
64944
+ for (const k of VERTEX_PARAM_KEYS) {
64945
+ const v = raw[k];
64946
+ if (v === void 0 || v === null)
64947
+ continue;
64948
+ out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? clamp2(num(v), 0, 100) : str60(v);
64949
+ }
64950
+ return out;
64951
+ }
64952
+ function canonicalVertices(level2) {
64953
+ pruneVertices(level2);
64954
+ const map = new Map(level2.vertices.map((v, i) => [v.id, `v${i + 1}`]));
64955
+ const id = (x) => map.get(x) ?? x;
64956
+ level2.vertices = level2.vertices.map((v) => ({ ...v, id: id(v.id) }));
64957
+ for (const list of [level2.walls, level2.doors, level2.lanes, level2.measurements]) {
64958
+ for (const e of list) {
64959
+ e.v1 = id(e.v1);
64960
+ e.v2 = id(e.v2);
64961
+ }
64962
+ }
64963
+ for (const poly of [...level2.floors, ...level2.holes, ...level2.zones])
64964
+ poly.vertices = poly.vertices.map(id);
64965
+ }
64966
+ function buildingFrame(rmf, pad = 2) {
64967
+ const xs = [];
64968
+ const ys = [];
64969
+ for (const lv of rmf.levels) {
64970
+ for (const v of lv.vertices)
64971
+ xs.push(v.x), ys.push(v.y);
64972
+ for (const f of lv.fiducials)
64973
+ xs.push(f.x), ys.push(f.y);
64974
+ }
64975
+ for (const l of rmf.lifts)
64976
+ for (const c of liftShaft(l))
64977
+ xs.push(c.x), ys.push(c.y);
64978
+ if (!xs.length)
64979
+ return { ...DEFAULT_PLAN_FRAME };
64980
+ const grow = (lo, hi) => hi - lo < 10 ? [(lo + hi) / 2 - 5, (lo + hi) / 2 + 5] : [lo, hi];
64981
+ const [minX, maxX] = grow(Math.min(...xs) - pad, Math.max(...xs) + pad);
64982
+ const [minY, maxY] = grow(Math.min(...ys) - pad, Math.max(...ys) + pad);
64983
+ return { minX: r3(minX), maxX: r3(maxX), minY: r3(minY), maxY: r3(maxY) };
64984
+ }
64985
+ var frameOf = (raw) => {
64986
+ if (!Array.isArray(raw) || raw.length !== 4 || raw.some((v) => !Number.isFinite(Number(v))))
64987
+ return null;
64988
+ const [minX, minY, maxX, maxY] = raw.map(Number);
64989
+ return maxX > minX && maxY > minY ? { minX, maxX, minY, maxY } : null;
64990
+ };
64991
+ function fromBuildingYaml(doc) {
64992
+ if (!doc || typeof doc !== "object" || !doc.levels || typeof doc.levels !== "object" || Array.isArray(doc.levels)) {
64993
+ throw new RmfImportError("This is not a building file: it has no floors (levels).");
64994
+ }
64995
+ const cs = String(doc.coordinate_system ?? "reference_image");
64996
+ if (cs === "wgs84" || cs === "web_mercator") {
64997
+ 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.");
64998
+ }
64999
+ if (cs !== "reference_image" && cs !== "cartesian_meters")
65000
+ throw new RmfImportError(`This building file uses an unknown coordinate system ("${cs.slice(0, 30)}").`);
65001
+ const flip = cs === "reference_image" ? -1 : 1;
65002
+ const warnings = [];
65003
+ const names = Object.keys(doc.levels);
65004
+ if (!names.length)
65005
+ throw new RmfImportError("This building file has no floors.");
65006
+ if (names.length > 200)
65007
+ throw new RmfImportError("This building file has more than 200 floors.");
65008
+ const LIMITS = [["vertices", 5e3], ["walls", 5e3], ["lanes", 5e3], ["doors", 500], ["measurements", 200], ["fiducials", 200], ["floors", 200], ["holes", 200], ["hero_zones", 200]];
65009
+ for (const name of names) {
65010
+ const y = doc.levels[name] ?? {};
65011
+ for (const [key, max] of LIMITS) {
65012
+ if (Array.isArray(y[key]) && y[key].length > max)
65013
+ throw new RmfImportError(`Floor ${str60(name)} has more than ${max} ${key.replace("hero_", "")} - more than a building map can hold.`);
65014
+ }
65015
+ }
65016
+ if (doc.lifts && typeof doc.lifts === "object" && Object.keys(doc.lifts).length > 50)
65017
+ throw new RmfImportError("This building file has more than 50 lifts.");
65018
+ const raw = names.map((name) => {
65019
+ const y = doc.levels[name] ?? {};
65020
+ const vertices = (Array.isArray(y.vertices) ? y.vertices : []).map((v) => ({
65021
+ x: num(v?.[0]),
65022
+ y: num(v?.[1]) * flip,
65023
+ name: str60(v?.[3]),
65024
+ params: fileVertexParams(decodeParams(v?.[4]))
65025
+ }));
65026
+ const fiducials = (Array.isArray(y.fiducials) ? y.fiducials : []).map((f) => ({ x: num(f?.[0]), y: num(f?.[1]) * flip, name: str60(f?.[2]) }));
65027
+ const meas = edgeList(y.measurements).map((e) => [e.a, e.b, num(e.p.distance)]);
65028
+ return { name: str60(name), y, vertices, fiducials, meas, elevation: num(y.elevation) };
65029
+ });
65030
+ const refName = raw.some((l) => l.name === doc.reference_level_name) ? String(doc.reference_level_name) : raw[0].name;
65031
+ const ref = raw.find((l) => l.name === refName);
65032
+ const xforms = /* @__PURE__ */ new Map();
65033
+ if (cs === "reference_image") {
65034
+ let refScale = measurementScale(ref.vertices, ref.meas);
65035
+ if (refScale === null) {
65036
+ refScale = 1;
65037
+ 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.`);
65038
+ }
65039
+ xforms.set(ref.name, { ...IDENTITY, scale: refScale });
65040
+ for (const lv of raw) {
65041
+ if (lv === ref)
65042
+ continue;
65043
+ const pairs = [];
65044
+ const mine = /* @__PURE__ */ new Map();
65045
+ for (const b of lv.fiducials)
65046
+ if (b.name && !mine.has(b.name))
65047
+ mine.set(b.name, b);
65048
+ const seen2 = /* @__PURE__ */ new Set();
65049
+ for (const a of ref.fiducials) {
65050
+ const b = a.name && !seen2.has(a.name) ? mine.get(a.name) : void 0;
65051
+ if (b) {
65052
+ seen2.add(a.name);
65053
+ pairs.push([a, b]);
65054
+ }
65055
+ }
65056
+ const t = fiducialTransform(pairs, refScale);
65057
+ if (t)
65058
+ xforms.set(lv.name, t);
65059
+ else {
65060
+ xforms.set(lv.name, { ...IDENTITY, scale: measurementScale(lv.vertices, lv.meas) ?? refScale });
65061
+ 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.`);
65062
+ }
65063
+ }
65064
+ }
65065
+ const xf = (level2) => xforms.get(level2) ?? IDENTITY;
65066
+ const floorNos = /* @__PURE__ */ new Map();
65067
+ const used = /* @__PURE__ */ new Set();
65068
+ for (const lv of raw) {
65069
+ const hero = Number(lv.y.hero_floor_no);
65070
+ const n = Number.isInteger(hero) && hero >= -20 && hero <= 200 ? hero : floorNoFromName(lv.name);
65071
+ if (n !== null && !used.has(n)) {
65072
+ floorNos.set(lv.name, n);
65073
+ used.add(n);
65074
+ }
65075
+ }
65076
+ let next = Math.max(0, ...used) + 1;
65077
+ for (const lv of [...raw].sort((a, b) => a.elevation - b.elevation)) {
65078
+ if (floorNos.has(lv.name))
65079
+ continue;
65080
+ while (used.has(next))
65081
+ next++;
65082
+ if (next > 200)
65083
+ throw new RmfImportError("This building file has too many floors to number.");
65084
+ floorNos.set(lv.name, next);
65085
+ used.add(next);
65086
+ }
65087
+ const rmf = emptyRmf("file");
65088
+ const graphIdx = /* @__PURE__ */ new Set();
65089
+ for (const lv of raw) {
65090
+ const t = xf(lv.name);
65091
+ const level2 = emptyLevel(lv.name, floorNos.get(lv.name), lv.elevation, { ...DEFAULT_PLAN_FRAME });
65092
+ const ids2 = lv.vertices.map((_, i) => `v${i + 1}`);
65093
+ level2.vertices = lv.vertices.map((v, i) => {
65094
+ const w = applyXform(t, v);
65095
+ 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 } : {} };
65096
+ });
65097
+ const ok = (e) => !!ids2[e.a] && !!ids2[e.b] && e.a !== e.b;
65098
+ for (const e of edgeList(lv.y.walls).filter(ok)) {
65099
+ const extra = {};
65100
+ if (e.p.texture_name !== void 0 && e.p.texture_name !== "default")
65101
+ extra.textureName = str60(e.p.texture_name);
65102
+ if (e.p.alpha !== void 0 && num(e.p.alpha, 1) !== 1)
65103
+ extra.alpha = clamp2(num(e.p.alpha, 1), 0, 1);
65104
+ if (e.p.texture_height !== void 0 && num(e.p.texture_height, 2.5) !== 2.5)
65105
+ extra.textureHeight = clamp2(num(e.p.texture_height, 2.5), 0, 100);
65106
+ if (e.p.texture_width !== void 0 && num(e.p.texture_width, 1) !== 1)
65107
+ extra.textureWidth = clamp2(num(e.p.texture_width, 1), 0, 100);
65108
+ if (e.p.texture_scale !== void 0 && num(e.p.texture_scale, 1) !== 1)
65109
+ extra.textureScale = clamp2(num(e.p.texture_scale, 1), 0, 100);
65110
+ level2.walls.push({ v1: ids2[e.a], v2: ids2[e.b], ...extra });
65111
+ }
65112
+ for (const e of edgeList(lv.y.doors).filter(ok)) {
65113
+ const type = String(e.p.type ?? "hinged");
65114
+ const degrees = clamp2(num(e.p.motion_degrees, 90), -360, 360);
65115
+ const ratio = clamp2(num(e.p.right_left_ratio, 1), 0, 10);
65116
+ const plugin = str60(e.p.plugin ?? "normal");
65117
+ level2.doors.push({
65118
+ name: str60(e.p.name ?? "").trim() || `door_${level2.doors.length + 1}`,
65119
+ v1: ids2[e.a],
65120
+ v2: ids2[e.b],
65121
+ type: ["hinged", "double_hinged", "sliding", "double_sliding"].includes(type) ? type : "hinged",
65122
+ ...e.p.motion_axis === "end" ? { motionAxis: "end" } : {},
65123
+ ...degrees !== 90 ? { motionDegrees: degrees } : {},
65124
+ ...num(e.p.motion_direction, 1) < 0 ? { motionDirection: -1 } : {},
65125
+ ...ratio !== 1 ? { rightLeftRatio: ratio } : {},
65126
+ ...plugin !== "normal" ? { plugin } : {}
65127
+ });
65128
+ }
65129
+ for (const e of edgeList(lv.y.lanes).filter(ok)) {
65130
+ const gi = Math.round(num(e.p.graph_idx, 0));
65131
+ if (gi < 0 || gi > 8) {
65132
+ warnings.push(`Floor ${lv.name}: a lane on graph ${gi} was skipped (graphs 0-8 only).`);
65133
+ continue;
65134
+ }
65135
+ graphIdx.add(gi);
65136
+ const orientation = e.p.orientation === "forward" || e.p.orientation === "backward" ? e.p.orientation : void 0;
65137
+ level2.lanes.push({
65138
+ v1: ids2[e.a],
65139
+ v2: ids2[e.b],
65140
+ graphIdx: gi,
65141
+ bidirectional: e.p.bidirectional === true,
65142
+ ...orientation ? { orientation } : {},
65143
+ ...num(e.p.speed_limit) > 0 ? { speedLimit: clamp2(num(e.p.speed_limit), 0, 20) } : {},
65144
+ ...e.p.mutex ? { mutex: str60(e.p.mutex) } : {},
65145
+ ...e.p.demo_mock_floor_name ? { demoMockFloorName: str60(e.p.demo_mock_floor_name) } : {},
65146
+ ...e.p.demo_mock_lift_name ? { demoMockLiftName: str60(e.p.demo_mock_lift_name) } : {}
65147
+ });
65148
+ }
65149
+ for (const e of edgeList(lv.y.measurements).filter(ok)) {
65150
+ const d = num(e.p.distance);
65151
+ if (d >= 0.01)
65152
+ level2.measurements.push({ v1: ids2[e.a], v2: ids2[e.b], distanceM: Math.min(d, 1e4) });
65153
+ }
65154
+ const polyIds = (p) => (Array.isArray(p?.vertices) ? p.vertices : []).map((i) => ids2[Number(i)]).filter((x) => !!x);
65155
+ const polys = (list) => (Array.isArray(list) ? list : []).flatMap((p) => {
65156
+ const vs = polyIds(p);
65157
+ return vs.length >= 3 ? [{ vertices: vs }] : [];
65158
+ });
65159
+ level2.floors = polys(lv.y.floors);
65160
+ level2.holes = polys(lv.y.holes);
65161
+ level2.zones = (Array.isArray(lv.y.hero_zones) ? lv.y.hero_zones : []).flatMap((z5) => {
65162
+ const vs = polyIds(z5);
65163
+ return vs.length >= 3 && str60(z5?.name).trim() ? [{ name: str60(z5.name).trim(), vertices: vs }] : [];
65164
+ });
65165
+ level2.fiducials = lv.fiducials.map((f) => {
65166
+ const w = applyXform(t, f);
65167
+ return { name: f.name || "fiducial", x: r3(w.x), y: r3(w.y) };
65168
+ });
65169
+ canonicalVertices(level2);
65170
+ rmf.levels.push(level2);
65171
+ }
65172
+ rmf.levels.sort((a, b) => a.floorNo - b.floorNo);
65173
+ rmf.referenceLevel = refName;
65174
+ const levelNames = new Set(rmf.levels.map((l) => l.name));
65175
+ const lifts = doc.lifts && typeof doc.lifts === "object" ? Object.entries(doc.lifts) : [];
65176
+ for (const [liftName, ly] of lifts.slice(0, 50)) {
65177
+ const refFloor = levelNames.has(ly?.reference_floor_name) ? String(ly.reference_floor_name) : refName;
65178
+ if (ly?.reference_floor_name && !levelNames.has(ly.reference_floor_name)) {
65179
+ warnings.push(`Lift ${str60(liftName)}: its reference floor "${str60(ly.reference_floor_name)}" is not in the file; ${refName} was used.`);
65180
+ }
65181
+ const c = applyXform(xf(refFloor), { x: num(ly?.x), y: num(ly?.y) * flip });
65182
+ const doors = Object.entries(ly?.doors ?? {}).slice(0, 8).map(([dn, d]) => ({
65183
+ name: str60(dn),
65184
+ type: MSG_LIFT_DOOR_TYPE[Math.round(num(d?.door_type, 2))] ?? "double_sliding",
65185
+ x: r3(clamp2(num(d?.x), -20, 20)),
65186
+ y: r3(clamp2(num(d?.y), -20, 20)),
65187
+ widthM: r3(clamp2(num(d?.width, 1), 0.3, 10)),
65188
+ axisYawRad: clamp2(num(d?.motion_axis_orientation), -10, 10)
65189
+ }));
65190
+ const doorNames = new Set(doors.map((d) => d.name));
65191
+ 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)) }));
65192
+ const floorName = (v) => typeof v === "string" && levelNames.has(v) ? v : void 0;
65193
+ const lift2 = {
65194
+ name: str60(liftName),
65195
+ x: r3(c.x),
65196
+ y: r3(c.y),
65197
+ yawRad: clamp2(num(ly?.yaw), -10, 10),
65198
+ widthM: r3(clamp2(num(ly?.width, 2), 0.3, 20)),
65199
+ depthM: r3(clamp2(num(ly?.depth, 2), 0.3, 20)),
65200
+ referenceFloor: refFloor,
65201
+ ...floorName(ly?.initial_floor_name) ? { initialFloor: floorName(ly.initial_floor_name) } : {},
65202
+ ...floorName(ly?.lowest_floor) ? { lowestFloor: floorName(ly.lowest_floor) } : {},
65203
+ ...floorName(ly?.highest_floor) ? { highestFloor: floorName(ly.highest_floor) } : {},
65204
+ ...ly?.plugins === false ? { plugins: false } : {},
65205
+ doors,
65206
+ levelDoors
65207
+ };
65208
+ const derived = liftFloorRange({ ...lift2, lowestFloor: void 0, highestFloor: void 0, initialFloor: void 0 }, rmf.levels);
65209
+ if (lift2.lowestFloor === derived.lowest)
65210
+ delete lift2.lowestFloor;
65211
+ if (lift2.highestFloor === derived.highest)
65212
+ delete lift2.highestFloor;
65213
+ if (lift2.initialFloor === derived.initial)
65214
+ delete lift2.initialFloor;
65215
+ rmf.lifts.push(lift2);
65216
+ }
65217
+ const graphsYaml = doc.graphs && typeof doc.graphs === "object" ? doc.graphs : {};
65218
+ const declared = Object.keys(graphsYaml).map(Number).filter((n) => Number.isInteger(n) && n >= 0 && n <= 8);
65219
+ rmf.graphs = [.../* @__PURE__ */ new Set([...graphIdx, ...declared])].sort((a, b) => a - b).map((idx) => {
65220
+ const g = graphsYaml[String(idx)] ?? {};
65221
+ return { idx, name: str60(g.name).trim() || `Graph ${idx}`, brands: (Array.isArray(g.hero_brands) ? g.hero_brands : []).map(str60).slice(0, 20) };
65222
+ });
65223
+ const frames = new Map(raw.map((lv) => [lv.name, frameOf(lv.y.hero_plan_frame)]));
65224
+ if ([...frames.values()].every(Boolean))
65225
+ rmf.levels.forEach((l) => l.planFrame = frames.get(l.name));
65226
+ else {
65227
+ const f = buildingFrame(rmf);
65228
+ rmf.levels.forEach((l) => l.planFrame = { ...f });
65229
+ }
65230
+ return { rmf, name: str60(doc.name ?? doc.building_name ?? "").trim(), warnings };
65231
+ }
65232
+ function fromNavGraph(doc, graphIdx) {
65233
+ if (!doc || typeof doc !== "object" || !doc.levels || typeof doc.levels !== "object")
65234
+ throw new RmfImportError("This is not a route map file: it has no floors (levels).");
65235
+ if (!Number.isInteger(graphIdx) || graphIdx < 0 || graphIdx > 8)
65236
+ throw new RmfImportError("Choose a route graph from 0 to 8.");
65237
+ const rmf = emptyRmf("file");
65238
+ const warnings = [];
65239
+ 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]);
65240
+ const flipOrientation = (o) => o === "forward" ? "backward" : o === "backward" ? "forward" : o;
65241
+ const usedFloors = /* @__PURE__ */ new Set();
65242
+ let seq = 0;
65243
+ for (const [name, ly] of Object.entries(doc.levels).slice(0, 200)) {
65244
+ let floorNo2 = floorNoFromName(name) ?? ++seq;
65245
+ while (usedFloors.has(floorNo2))
65246
+ floorNo2++;
65247
+ usedFloors.add(floorNo2);
65248
+ const level2 = emptyLevel(str60(name), floorNo2, 0, { ...DEFAULT_PLAN_FRAME });
65249
+ const verts = (Array.isArray(ly?.vertices) ? ly.vertices : []).slice(0, 5e3);
65250
+ level2.vertices = verts.map((v, k) => {
65251
+ const p = v?.[2] && typeof v[2] === "object" ? v[2] : {};
65252
+ const params = fileVertexParams(p);
65253
+ 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 } : {} };
65254
+ });
65255
+ if (Array.isArray(ly?.lanes) && ly.lanes.length > 1e4)
65256
+ throw new RmfImportError(`Floor ${str60(name)} has more than 10000 one-way lanes - more than a building map can hold.`);
65257
+ const lanes = (Array.isArray(ly?.lanes) ? ly.lanes : []).filter(
65258
+ (l) => Array.isArray(l) && level2.vertices[Number(l[0])] && level2.vertices[Number(l[1])] && Number(l[0]) !== Number(l[1])
65259
+ );
65260
+ const used = /* @__PURE__ */ new Set();
65261
+ const byEnds = /* @__PURE__ */ new Map();
65262
+ lanes.forEach((l, k) => {
65263
+ const key = `${Number(l[0])},${Number(l[1])}`;
65264
+ byEnds.set(key, [...byEnds.get(key) ?? [], k]);
65265
+ });
65266
+ lanes.forEach((l, k) => {
65267
+ if (used.has(k))
65268
+ return;
65269
+ used.add(k);
65270
+ const a = Number(l[0]);
65271
+ const b = Number(l[1]);
65272
+ const p = l[2] ?? {};
65273
+ let bidirectional = p.is_bidirectional === true;
65274
+ if (!bidirectional && p.is_bidirectional === void 0) {
65275
+ const back = (byEnds.get(`${b},${a}`) ?? []).find((j) => {
65276
+ if (used.has(j))
65277
+ return false;
65278
+ const q = lanes[j][2] ?? {};
65279
+ return shared(q) === shared(p) && (q.orientation_constraint ?? null) === (flipOrientation(p.orientation_constraint) ?? null);
65280
+ });
65281
+ if (back !== void 0) {
65282
+ used.add(back);
65283
+ bidirectional = true;
65284
+ }
65285
+ }
65286
+ const o = p.orientation_constraint;
65287
+ level2.lanes.push({
65288
+ v1: level2.vertices[a].id,
65289
+ v2: level2.vertices[b].id,
65290
+ graphIdx,
65291
+ bidirectional,
65292
+ ...o === "forward" || o === "backward" ? { orientation: o } : {},
65293
+ ...num(p.speed_limit) > 0 ? { speedLimit: clamp2(num(p.speed_limit), 0, 20) } : {},
65294
+ ...p.mutex ? { mutex: str60(p.mutex) } : {},
65295
+ ...p.demo_mock_floor_name ? { demoMockFloorName: str60(p.demo_mock_floor_name) } : {},
65296
+ ...p.demo_mock_lift_name ? { demoMockLiftName: str60(p.demo_mock_lift_name) } : {}
65297
+ });
65298
+ });
65299
+ canonicalVertices(level2);
65300
+ rmf.levels.push(level2);
65301
+ }
65302
+ if (!rmf.levels.some((l) => l.lanes.length))
65303
+ warnings.push("The route map has no lanes.");
65304
+ rmf.graphs = [{ idx: graphIdx, name: `Graph ${graphIdx}`, brands: [] }];
65305
+ const f = buildingFrame(rmf);
65306
+ rmf.levels.forEach((l) => l.planFrame = { ...f });
65307
+ rmf.referenceLevel = rmf.levels[0]?.name;
65308
+ return { rmf, warnings };
65309
+ }
65310
+ function rmfSummary(rmf) {
65311
+ if (!rmf)
65312
+ return null;
65313
+ const sum = (f) => rmf.levels.reduce((n, l) => n + f(l), 0);
65314
+ return {
65315
+ source: rmf.source ?? "editor",
65316
+ levels: rmf.levels.length,
65317
+ lanes: sum((l) => l.lanes.length),
65318
+ waypoints: sum((l) => l.vertices.filter((v) => v.name).length),
65319
+ doors: sum((l) => l.doors.length),
65320
+ lifts: rmf.lifts.length,
65321
+ graphs: rmf.graphs.length
65322
+ };
65323
+ }
65324
+
65325
+ // src/services/robot-tracking.service.ts
65326
+ import axios4 from "axios";
65327
+ async function openWithAxios(url, body) {
65328
+ const response = await axios4.post(url, body, {
65329
+ responseType: "stream",
65330
+ // No read timeout: this connection is SUPPOSED to stay open and mostly
65331
+ // silent. A request timeout here would sever a healthy stream on a quiet
65332
+ // robot. The idle watchdog is what decides a stream is dead, because it can
65333
+ // tell silence from a closed socket.
65334
+ timeout: 0,
65335
+ headers: { "Content-Type": "application/json", Accept: "text/event-stream" }
65336
+ });
65337
+ return response.data;
65338
+ }
65339
+ function startRobotTracking(options) {
65340
+ const {
65341
+ credentials,
65342
+ robotSn,
65343
+ onEvent,
65344
+ baseUrl = ROBOT_CLOUD_BASE_URL,
65345
+ idleTimeoutMs = TRACKING_IDLE_TIMEOUT_MS,
65346
+ openStream = openWithAxios,
65347
+ now = Date.now
65348
+ } = options;
65349
+ if (!baseUrl)
65350
+ throw new Error("Robot cloud: ROBOT_CLOUD_BASE_URL is not configured.");
65351
+ let stopped = false;
65352
+ let attempt = 0;
65353
+ let current = null;
65354
+ let watchdog = null;
65355
+ let retry = null;
65356
+ let lastActivityAt = now();
65357
+ let everConnected = false;
65358
+ const parser = createSseParser();
65359
+ function clearTimers() {
65360
+ if (watchdog) {
65361
+ clearInterval(watchdog);
65362
+ watchdog = null;
65363
+ }
65364
+ if (retry) {
65365
+ clearTimeout(retry);
65366
+ retry = null;
65367
+ }
65368
+ }
65369
+ function dropUpstream() {
65370
+ if (!current)
65371
+ return;
65372
+ try {
65373
+ current.destroy();
65374
+ } catch {
65375
+ }
65376
+ current = null;
65377
+ }
65378
+ function lose(reason) {
65379
+ if (stopped)
65380
+ return;
65381
+ onEvent({ type: "lost", reason, at: now() });
65382
+ dropUpstream();
65383
+ scheduleReconnect();
65384
+ }
65385
+ function scheduleReconnect() {
65386
+ if (stopped)
65387
+ return;
65388
+ clearTimers();
65389
+ const delay2 = trackingBackoffMs(attempt++);
65390
+ retry = setTimeout(connect2, delay2);
65391
+ }
65392
+ async function connect2() {
65393
+ if (stopped)
65394
+ return;
65395
+ const body = robotCloudBody(
65396
+ credentials.appid,
65397
+ credentials.secret,
65398
+ ROBOT_CLOUD_PATHS.tracking,
65399
+ { robotSn }
65400
+ );
65401
+ let stream;
65402
+ try {
65403
+ stream = await openStream(
65404
+ `${baseUrl.replace(/\/+$/, "")}${ROBOT_CLOUD_PATHS.tracking}`,
65405
+ body
65406
+ );
65407
+ } catch (error) {
65408
+ lose(error?.message ?? "Could not open the robot's tracking stream.");
65409
+ return;
65410
+ }
65411
+ if (stopped) {
65412
+ try {
65413
+ stream.destroy();
65414
+ } catch {
65415
+ }
65416
+ return;
65417
+ }
65418
+ parser.reset();
65419
+ current = stream;
65420
+ lastActivityAt = now();
65421
+ if (everConnected)
65422
+ onEvent({ type: "reconnected", at: now() });
65423
+ everConnected = true;
65424
+ attempt = 0;
65425
+ stream.on("data", (chunk2) => {
65426
+ if (stopped)
65427
+ return;
65428
+ const { events, sawActivity } = parser.push(chunk2.toString("utf8"));
65429
+ if (sawActivity)
65430
+ lastActivityAt = now();
65431
+ for (const event of events) {
65432
+ const pose = decodeTrackingFrame(event.data);
65433
+ if (pose)
65434
+ onEvent({ type: "pose", pose, at: now() });
65435
+ }
65436
+ });
65437
+ stream.on("error", (error) => lose(error?.message ?? "The tracking stream failed."));
65438
+ stream.on("end", () => lose("The robot cloud closed the tracking stream."));
65439
+ stream.on("close", () => {
65440
+ if (!stopped && current === stream)
65441
+ lose("The tracking stream closed.");
65442
+ });
65443
+ clearTimers();
65444
+ watchdog = setInterval(() => {
65445
+ if (stopped)
65446
+ return;
65447
+ if (now() - lastActivityAt >= idleTimeoutMs) {
65448
+ lose("The robot stopped reporting.");
65449
+ }
65450
+ }, Math.max(1e3, Math.floor(idleTimeoutMs / 3)));
65451
+ }
65452
+ void connect2();
65453
+ return {
65454
+ stop() {
65455
+ if (stopped)
65456
+ return;
65457
+ stopped = true;
65458
+ clearTimers();
65459
+ dropUpstream();
65460
+ }
65461
+ };
65462
+ }
65463
+
65464
+ // src/controllers/robot-fleet.controller.ts
65465
+ import Joi76 from "joi";
65466
+ import { BadRequestError as BadRequestError135, logger as logger108 } from "@7365admin1/node-server-utils";
65467
+
65468
+ // src/services/robot-fault.service.ts
65469
+ import { logger as logger107 } from "@7365admin1/node-server-utils";
65470
+
65471
+ // src/repositories/robot-fault.repo.ts
65472
+ import { ObjectId as ObjectId108 } from "mongodb";
65473
+ import { InternalServerError as InternalServerError50, useAtlas as useAtlas80 } from "@7365admin1/node-server-utils";
65474
+ var toId3 = (v) => v instanceof ObjectId108 ? v : new ObjectId108(String(v));
65475
+ function useRobotFaultRepo() {
65476
+ const db2 = useAtlas80.getDb();
65477
+ if (!db2)
65478
+ throw new InternalServerError50("Unable to connect to server.");
65479
+ const collection = db2.collection(ROBOT_FAULTS_COLLECTION);
65480
+ async function createIndex() {
65481
+ try {
65482
+ await collection.createIndexes([
65483
+ {
65484
+ key: { robotId: 1, code: 1 },
65485
+ name: "one_open_fault_per_robot_code",
65486
+ unique: true,
65487
+ partialFilterExpression: { clearedAt: null }
65488
+ },
65489
+ { key: { clearedAt: 1, since: 1 }, name: "open_faults_by_since" }
65490
+ ]);
65491
+ } catch (error) {
65492
+ throw new InternalServerError50("Failed to create index on robot faults.");
65493
+ }
65494
+ }
65495
+ async function getOpenFaults() {
65496
+ return collection.find({ clearedAt: null }, { projection: { robotId: 1, code: 1, since: 1 } }).toArray();
65497
+ }
65498
+ async function getOpenFault(robotId, code) {
65499
+ return collection.findOne({ robotId: toId3(robotId), code, clearedAt: null });
65500
+ }
65501
+ async function openFault(doc) {
65502
+ const now = /* @__PURE__ */ new Date();
65503
+ try {
65504
+ const res = await collection.insertOne({
65505
+ robotId: toId3(doc.robotId),
65506
+ orgId: doc.orgId ? toId3(doc.orgId) : null,
65507
+ siteId: doc.siteId ? toId3(doc.siteId) : null,
65508
+ code: doc.code,
65509
+ message: doc.message,
65510
+ since: doc.since,
65511
+ clearedAt: null,
65512
+ notifiedAt: null,
65513
+ createdAt: now
65514
+ });
65515
+ return res.insertedId;
65516
+ } catch (error) {
65517
+ if (error?.code === 11e3)
65518
+ return null;
65519
+ throw error;
65520
+ }
65521
+ }
65522
+ async function claimNotify(id) {
65523
+ const res = await collection.updateOne(
65524
+ { _id: toId3(id), clearedAt: null, notifiedAt: null },
65525
+ { $set: { notifiedAt: /* @__PURE__ */ new Date() } }
65526
+ );
65527
+ return res.modifiedCount === 1;
65528
+ }
65529
+ async function claimOfflineAlert(id, cutoff) {
65530
+ const res = await collection.updateOne(
65531
+ { _id: toId3(id), code: "OFFLINE", clearedAt: null, since: { $lte: cutoff }, offlineNotifiedAt: null },
65532
+ { $set: { offlineNotifiedAt: /* @__PURE__ */ new Date() } }
65533
+ );
65534
+ return res.modifiedCount === 1;
65535
+ }
65536
+ async function claimRecoveryAlert(id) {
65537
+ const res = await collection.updateOne(
65538
+ { _id: toId3(id), code: "OFFLINE", offlineNotifiedAt: { $ne: null }, recoveryNotifiedAt: null },
65539
+ { $set: { recoveryNotifiedAt: /* @__PURE__ */ new Date() } }
65540
+ );
65541
+ return res.modifiedCount === 1;
65542
+ }
65543
+ async function findNotifiedOccurrence(robotId, code, since, after) {
65544
+ const filter = {
65545
+ clearedAt: { $gte: after },
65546
+ robotId: toId3(robotId),
65547
+ code,
65548
+ notifiedAt: { $ne: null }
65549
+ };
65550
+ if (since)
65551
+ filter.since = { $gte: new Date(since.getTime() - 1e3), $lte: new Date(since.getTime() + 1e3) };
65552
+ return collection.findOne(filter, { projection: { notifiedAt: 1 } });
65553
+ }
65554
+ async function markNotified(id, at2) {
65555
+ await collection.updateOne({ _id: toId3(id), notifiedAt: null }, { $set: { notifiedAt: at2 } });
65556
+ }
65557
+ async function clearFault(id) {
65558
+ await collection.updateOne(
65559
+ { _id: toId3(id), clearedAt: null },
65560
+ { $set: { clearedAt: /* @__PURE__ */ new Date() } }
65561
+ );
65562
+ }
65563
+ async function listNetworkFaults(q) {
65564
+ const page = Math.max(1, Math.floor(q.page || 1));
65565
+ const limit = Math.min(100, Math.max(1, Math.floor(q.limit || 25)));
65566
+ const [res] = await collection.aggregate(networkFaultsPipeline({ ...q, page, limit })).toArray();
65567
+ const total = res?.total?.[0]?.n ?? 0;
65568
+ const faults = res?.faults?.[0]?.n ?? 0;
65569
+ return { items: res?.items ?? [], page, limit, pages: Math.ceil(total / limit), total, faults };
64472
65570
  }
64473
65571
  async function countNetworkFaults() {
64474
65572
  const [res] = await collection.aggregate(networkFaultCountsPipeline()).toArray();
@@ -64835,8 +65933,11 @@ var floorPlanBodySchema = Joi77.object({
64835
65933
  widthPx: Joi77.number().integer().min(1).max(1e4).required(),
64836
65934
  heightPx: Joi77.number().integer().min(1).max(1e4).required(),
64837
65935
  metersPerPixel: Joi77.number().min(1e-4).max(10).required(),
64838
- tx: Joi77.number().min(-1e3).max(1e3).default(0),
64839
- ty: Joi77.number().min(-1e3).max(1e3).default(0)
65936
+ tx: Joi77.number().min(-1e5).max(1e5).default(0),
65937
+ ty: Joi77.number().min(-1e5).max(1e5).default(0),
65938
+ // No default: an older app re-scaling a plan sends neither, and must not reset a turn it cannot see.
65939
+ yawRad: Joi77.number().min(-10).max(10),
65940
+ space: Joi77.string().valid("world")
64840
65941
  });
64841
65942
  var coord = Joi77.number().min(-1e3).max(1e3).required();
64842
65943
  var point = Joi77.object({ x: coord, y: coord });
@@ -64896,11 +65997,24 @@ var rmfLevel = Joi77.object({
64896
65997
  spawn_robot_type: Joi77.string().trim().max(60).allow(""),
64897
65998
  lift_cabin: Joi77.string().trim().max(60).allow(""),
64898
65999
  merge_radius: Joi77.number().min(0).max(100),
64899
- mutex: Joi77.string().trim().max(60).allow("")
66000
+ mutex: Joi77.string().trim().max(60).allow(""),
66001
+ pickup_dispenser: Joi77.string().trim().max(60).allow(""),
66002
+ dropoff_ingestor: Joi77.string().trim().max(60).allow(""),
66003
+ human_goal_set_name: Joi77.string().trim().max(60).allow("")
64900
66004
  })
64901
66005
  })
64902
66006
  ).max(5e3).default([]),
64903
- walls: Joi77.array().items(Joi77.object(edge)).max(5e3).default([]),
66007
+ walls: Joi77.array().items(
66008
+ Joi77.object({
66009
+ ...edge,
66010
+ // traffic-editor wall look (simulation only); absent = its defaults.
66011
+ textureName: Joi77.string().trim().max(60).allow(""),
66012
+ alpha: Joi77.number().min(0).max(1),
66013
+ textureHeight: Joi77.number().min(0).max(100),
66014
+ textureWidth: Joi77.number().min(0).max(100),
66015
+ textureScale: Joi77.number().min(0).max(100)
66016
+ })
66017
+ ).max(5e3).default([]),
64904
66018
  floors: Joi77.array().items(polygon).max(200).default([]),
64905
66019
  holes: Joi77.array().items(polygon).max(200).default([]),
64906
66020
  doors: Joi77.array().items(
@@ -64909,9 +66023,11 @@ var rmfLevel = Joi77.object({
64909
66023
  name: rmfName.required(),
64910
66024
  type: Joi77.string().valid("hinged", "double_hinged", "sliding", "double_sliding").default("hinged"),
64911
66025
  motionAxis: Joi77.string().valid("start", "end"),
64912
- motionDegrees: Joi77.number().min(0).max(360),
66026
+ // traffic-editor draws |degrees|; files in the wild carry negative ones (rmf_demos hotel).
66027
+ motionDegrees: Joi77.number().min(-360).max(360),
64913
66028
  motionDirection: Joi77.number().valid(1, -1),
64914
- rightLeftRatio: Joi77.number().min(0).max(10)
66029
+ rightLeftRatio: Joi77.number().min(0).max(10),
66030
+ plugin: Joi77.string().trim().max(60).allow("")
64915
66031
  })
64916
66032
  ).max(500).default([]),
64917
66033
  lanes: Joi77.array().items(
@@ -64921,7 +66037,9 @@ var rmfLevel = Joi77.object({
64921
66037
  bidirectional: Joi77.boolean().default(true),
64922
66038
  orientation: Joi77.string().valid("forward", "backward"),
64923
66039
  speedLimit: Joi77.number().min(0).max(20),
64924
- mutex: Joi77.string().trim().max(60).allow("")
66040
+ mutex: Joi77.string().trim().max(60).allow(""),
66041
+ demoMockFloorName: Joi77.string().trim().max(60).allow(""),
66042
+ demoMockLiftName: Joi77.string().trim().max(60).allow("")
64925
66043
  })
64926
66044
  ).max(5e3).default([]),
64927
66045
  measurements: Joi77.array().items(Joi77.object({ ...edge, distanceM: Joi77.number().min(0.01).max(1e4).required() })).max(200).default([]),
@@ -64937,10 +66055,13 @@ var rmfLift = Joi77.object({
64937
66055
  depthM: Joi77.number().min(0.3).max(20).required(),
64938
66056
  referenceFloor: Joi77.string().trim().max(60).allow("").default(""),
64939
66057
  initialFloor: Joi77.string().trim().max(60).allow(""),
66058
+ lowestFloor: Joi77.string().trim().max(60).allow(""),
66059
+ highestFloor: Joi77.string().trim().max(60).allow(""),
66060
+ plugins: Joi77.boolean(),
64940
66061
  doors: Joi77.array().items(
64941
66062
  Joi77.object({
64942
66063
  name: rmfName.required(),
64943
- type: Joi77.string().valid("sliding", "double_sliding").default("double_sliding"),
66064
+ type: Joi77.string().valid("sliding", "double_sliding", "telescope", "double_telescope").default("double_sliding"),
64944
66065
  x: Joi77.number().min(-20).max(20).required(),
64945
66066
  y: Joi77.number().min(-20).max(20).required(),
64946
66067
  widthM: Joi77.number().min(0.3).max(10).required(),
@@ -64964,6 +66085,11 @@ var rmfBuildingSchema = Joi77.object({
64964
66085
  levels: Joi77.array().items(rmfLevel).max(200).unique("floorNo").default([]),
64965
66086
  lifts: Joi77.array().items(rmfLift).max(50).unique("name").default([])
64966
66087
  });
66088
+ var buildingFileImportSchema = Joi77.object({
66089
+ format: Joi77.string().valid("building", "nav").default("building"),
66090
+ text: Joi77.string().min(1).max(19e5).required(),
66091
+ graph: Joi77.number().integer().min(0).max(8).when("format", { is: "nav", then: Joi77.required(), otherwise: Joi77.forbidden() })
66092
+ });
64967
66093
  var buildingMapBodySchema = Joi77.object({
64968
66094
  name: label.required(),
64969
66095
  levels: Joi77.array().items(level).max(200).unique("floorNo").default([]),
@@ -65116,6 +66242,13 @@ function useRobotBuildingMapRepo() {
65116
66242
  "floorPlans.$.updatedAt": at2,
65117
66243
  "floorPlans.$.updatedBy": plan.updatedBy
65118
66244
  };
66245
+ if (plan.yawRad !== void 0)
66246
+ fields["floorPlans.$.yawRad"] = plan.yawRad;
66247
+ const unset = {};
66248
+ if (plan.space === "world")
66249
+ fields["floorPlans.$.space"] = "world";
66250
+ else
66251
+ unset["floorPlans.$.space"] = "";
65119
66252
  if (plan.data) {
65120
66253
  fields["floorPlans.$.data"] = new Binary(plan.data);
65121
66254
  fields["floorPlans.$.mime"] = plan.mime;
@@ -65123,7 +66256,7 @@ function useRobotBuildingMapRepo() {
65123
66256
  }
65124
66257
  const res = existing ? await collection.updateOne(
65125
66258
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": plan.floorNo },
65126
- { $set: { ...fields, updatedAt: at2 }, $inc: { version: 1 } }
66259
+ { $set: { ...fields, updatedAt: at2 }, ...Object.keys(unset).length ? { $unset: unset } : {}, $inc: { version: 1 } }
65127
66260
  ) : await collection.updateOne(
65128
66261
  { _id: id, version, ...NOT_DELETED2, "floorPlans.floorNo": { $ne: plan.floorNo } },
65129
66262
  {
@@ -65137,6 +66270,8 @@ function useRobotBuildingMapRepo() {
65137
66270
  metersPerPixel: plan.metersPerPixel,
65138
66271
  tx: plan.tx,
65139
66272
  ty: plan.ty,
66273
+ yawRad: plan.yawRad ?? 0,
66274
+ ...plan.space === "world" ? { space: "world" } : {},
65140
66275
  data: new Binary(plan.data),
65141
66276
  updatedAt: at2,
65142
66277
  updatedBy: plan.updatedBy
@@ -65240,723 +66375,181 @@ function useRobotLiftSessionRepo() {
65240
66375
  await collection.createIndexes([
65241
66376
  // The queue itself: one lift's waiting and active rows, oldest first.
65242
66377
  { key: { liftKey: 1, status: 1, requestedAt: 1 } },
65243
- // One robot in the car at a time, enforced by the database.
65244
- {
65245
- key: { liftKey: 1 },
65246
- name: "one_active_session_per_lift",
65247
- unique: true,
65248
- partialFilterExpression: { status: "active" }
65249
- },
65250
- // One open request per robot - a robot cannot queue for two lifts.
65251
- {
65252
- key: { robotId: 1 },
65253
- name: "one_open_session_per_robot",
65254
- unique: true,
65255
- partialFilterExpression: { open: true }
65256
- },
65257
- { key: { siteId: 1, requestedAt: -1 } }
65258
- ]);
65259
- } catch (error) {
65260
- throw new InternalServerError51("Failed to create index on robot lift sessions.");
65261
- }
65262
- }
65263
- async function advance(liftKey, now = /* @__PURE__ */ new Date()) {
65264
- await collection.updateMany(
65265
- { liftKey, open: true, expiresAt: { $lt: now } },
65266
- {
65267
- $set: {
65268
- status: "expired",
65269
- open: false,
65270
- closedAt: now,
65271
- closedReason: "timed out",
65272
- updatedAt: now
65273
- }
65274
- }
65275
- );
65276
- const holder = await collection.findOne({ liftKey, status: "active" });
65277
- if (holder)
65278
- return;
65279
- const next = await collection.find({ liftKey, status: "queued", open: true }).sort({ requestedAt: 1, _id: 1 }).limit(1).next();
65280
- if (!next)
65281
- return;
65282
- try {
65283
- await collection.updateOne(
65284
- { _id: next._id, status: "queued", open: true },
65285
- {
65286
- $set: {
65287
- status: "active",
65288
- activeAt: now,
65289
- expiresAt: new Date(now.getTime() + LIFT_LEASE_MS),
65290
- updatedAt: now
65291
- }
65292
- }
65293
- );
65294
- } catch (error) {
65295
- if (!isDuplicateKey(error))
65296
- throw error;
65297
- }
65298
- }
65299
- async function enqueue(value) {
65300
- const now = /* @__PURE__ */ new Date();
65301
- const liftKey = liftQueueKey(String(value.mapId), value.liftName);
65302
- await closeExpiredForRobot(value.robotId, now);
65303
- let insertedId;
65304
- try {
65305
- const res = await collection.insertOne({
65306
- ...value,
65307
- liftKey,
65308
- createdBy: new ObjectId110(value.createdBy),
65309
- status: "queued",
65310
- open: true,
65311
- requestedAt: now,
65312
- activeAt: null,
65313
- expiresAt: new Date(now.getTime() + LIFT_QUEUE_TTL_MS),
65314
- closedAt: null,
65315
- updatedAt: now
65316
- });
65317
- insertedId = res.insertedId;
65318
- } catch (error) {
65319
- if (isDuplicateKey(error)) {
65320
- throw new AppError23("This robot already has a lift request open. Release it first.", 409);
65321
- }
65322
- throw error;
65323
- }
65324
- await advance(liftKey, now);
65325
- return insertedId;
65326
- }
65327
- async function closeExpiredForRobot(robotId, now) {
65328
- const stale = await collection.findOne({ robotId, open: true, expiresAt: { $lt: now } });
65329
- if (stale)
65330
- await advance(stale.liftKey, now);
65331
- }
65332
- async function getSessionById(id) {
65333
- const session = await collection.findOne({ _id: toObjectId16(id, "lift session") });
65334
- if (!session)
65335
- throw new NotFoundError44("Lift session not found.");
65336
- return session;
65337
- }
65338
- async function getQueue(mapId, liftNames) {
65339
- const now = /* @__PURE__ */ new Date();
65340
- const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
65341
- for (const key of keys)
65342
- await advance(key, now);
65343
- return collection.find({ liftKey: { $in: keys }, open: true }).sort({ requestedAt: 1, _id: 1 }).toArray();
65344
- }
65345
- async function getRecent(mapId, liftNames, since) {
65346
- const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
65347
- if (!keys.length)
65348
- return [];
65349
- return collection.find({ liftKey: { $in: keys }, status: { $in: ["released", "expired"] }, closedAt: { $gte: since } }).sort({ closedAt: -1, _id: -1 }).limit(20).toArray();
65350
- }
65351
- async function refresh(id) {
65352
- const now = /* @__PURE__ */ new Date();
65353
- const res = await collection.updateOne(
65354
- { _id: id, status: "active", open: true, expiresAt: { $gte: now } },
65355
- { $set: { expiresAt: new Date(now.getTime() + LIFT_LEASE_MS), updatedAt: now } }
65356
- );
65357
- if (!res.matchedCount) {
65358
- throw new AppError23("This lift session is no longer active.", 409);
65359
- }
65360
- }
65361
- async function release(session, reason = "released") {
65362
- const now = /* @__PURE__ */ new Date();
65363
- await collection.updateOne({ _id: session._id, open: true }, [
65364
- {
65365
- $set: {
65366
- status: { $cond: [{ $eq: ["$status", "active"] }, "released", "cancelled"] },
65367
- open: false,
65368
- closedAt: now,
65369
- closedReason: reason,
65370
- updatedAt: now
65371
- }
65372
- }
65373
- ]);
65374
- await advance(session.liftKey, now);
65375
- }
65376
- async function getOpenForRobot(robotId) {
65377
- const now = /* @__PURE__ */ new Date();
65378
- await closeExpiredForRobot(robotId, now);
65379
- const session = await collection.findOne({ robotId, open: true });
65380
- if (!session)
65381
- return null;
65382
- await advance(session.liftKey, now);
65383
- return collection.findOne({ _id: session._id });
65384
- }
65385
- async function cancelForMap(mapId, keepLiftNames = []) {
65386
- const now = /* @__PURE__ */ new Date();
65387
- await collection.updateMany(
65388
- { mapId, open: true, liftName: { $nin: keepLiftNames } },
65389
- {
65390
- $set: {
65391
- status: "cancelled",
65392
- open: false,
65393
- closedAt: now,
65394
- closedReason: "lift removed from the map",
65395
- updatedAt: now
65396
- }
65397
- }
65398
- );
65399
- }
65400
- return {
65401
- createIndex,
65402
- advance,
65403
- enqueue,
65404
- getSessionById,
65405
- getQueue,
65406
- getRecent,
65407
- refresh,
65408
- release,
65409
- getOpenForRobot,
65410
- cancelForMap
65411
- };
65412
- }
65413
-
65414
- // src/controllers/robot-map.controller.ts
65415
- import Joi78 from "joi";
65416
- import { AppError as AppError24, BadRequestError as BadRequestError137, NotFoundError as NotFoundError45, logger as logger109 } from "@7365admin1/node-server-utils";
65417
-
65418
- // src/utils/rmf-building.util.ts
65419
- var PLAN_W_M2 = 40;
65420
- var PLAN_H_M2 = 26;
65421
- var DEFAULT_PLAN_FRAME = { minX: 0, maxX: PLAN_W_M2, minY: -PLAN_H_M2, maxY: 0 };
65422
- var WELD_M = 0.01;
65423
- var r3 = (v) => Math.round(v * 1e3) / 1e3;
65424
- var clamp2 = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
65425
- function floorLabel(floorNo2) {
65426
- return floorNo2 < 0 ? `B${-floorNo2}` : floorNo2 === 0 ? "G" : `L${floorNo2}`;
65427
- }
65428
- function floorNoFromName(name) {
65429
- if (typeof name !== "string")
65430
- return null;
65431
- const m = /^(L|B)(\d{1,3})$/i.exec(name.trim());
65432
- if (m)
65433
- return m[1].toUpperCase() === "B" ? -Number(m[2]) : Number(m[2]);
65434
- return /^G$/i.test(name.trim()) ? 0 : null;
65435
- }
65436
- function toPlan(f, p) {
65437
- const w = f.maxX - f.minX || 1;
65438
- const h = f.maxY - f.minY || 1;
65439
- return { x: r3((p.x - f.minX) / w * PLAN_W_M2), y: r3((f.maxY - p.y) / h * PLAN_H_M2) };
65440
- }
65441
- function fromPlan(f, p) {
65442
- 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)) };
65443
- }
65444
- function vertexPool(level2) {
65445
- let next = level2.vertices.reduce((n, v) => Math.max(n, Number(/^v(\d+)$/.exec(v.id)?.[1] ?? 0)), 0) + 1;
65446
- const byId = new Map(level2.vertices.map((v) => [v.id, v]));
65447
- function at2(p, extra) {
65448
- const x = r3(p.x);
65449
- const y = r3(p.y);
65450
- const hit = level2.vertices.find((v2) => Math.abs(v2.x - x) < WELD_M && Math.abs(v2.y - y) < WELD_M);
65451
- if (hit) {
65452
- if (extra?.name && !hit.name)
65453
- hit.name = extra.name;
65454
- if (extra?.params && Object.keys(extra.params).length)
65455
- hit.params = { ...hit.params ?? {}, ...extra.params };
65456
- return hit.id;
65457
- }
65458
- const v = { id: `v${next++}`, x, y, ...extra?.name ? { name: extra.name } : {}, ...extra?.params && Object.keys(extra.params).length ? { params: extra.params } : {} };
65459
- level2.vertices.push(v);
65460
- byId.set(v.id, v);
65461
- return v.id;
65462
- }
65463
- return { at: at2, get: (id) => byId.get(id) };
65464
- }
65465
- function emptyLevel(name, floorNo2, elevationM, planFrame) {
65466
- return { name, floorNo: floorNo2, elevationM, planFrame, vertices: [], walls: [], floors: [], holes: [], doors: [], lanes: [], measurements: [], fiducials: [], zones: [] };
65467
- }
65468
- function emptyRmf(source = "editor") {
65469
- return { formatVersion: 1, coordinateSystem: "cartesian_meters", source, graphs: [], levels: [], lifts: [] };
65470
- }
65471
- var collapseDoor = (t) => t === "sliding" || t === "double_sliding" ? "sliding" : "hinged";
65472
- function pruneVertices(level2) {
65473
- const used = /* @__PURE__ */ new Set();
65474
- const add = (...ids2) => ids2.forEach((i) => used.add(i));
65475
- level2.walls.forEach((e) => add(e.v1, e.v2));
65476
- level2.doors.forEach((e) => add(e.v1, e.v2));
65477
- level2.lanes.forEach((e) => add(e.v1, e.v2));
65478
- level2.measurements.forEach((e) => add(e.v1, e.v2));
65479
- [...level2.floors, ...level2.holes, ...level2.zones].forEach((p) => add(...p.vertices));
65480
- level2.vertices = level2.vertices.filter((v) => used.has(v.id) || v.name || v.params && Object.keys(v.params).length);
65481
- }
65482
- function msgParams(params) {
65483
- const out = {};
65484
- for (const p of params ?? []) {
65485
- if (!p?.name)
65486
- continue;
65487
- 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;
65488
- }
65489
- return out;
65490
- }
65491
- var VERTEX_PARAM_KEYS = [
65492
- "is_charger",
65493
- "is_parking_spot",
65494
- "is_holding_point",
65495
- "is_passthrough_point",
65496
- "is_cleaning_zone",
65497
- "dock_name",
65498
- "spawn_robot_name",
65499
- "spawn_robot_type",
65500
- "lift_cabin",
65501
- "merge_radius",
65502
- "mutex"
65503
- ];
65504
- function vertexParams(raw) {
65505
- const out = {};
65506
- for (const k of VERTEX_PARAM_KEYS) {
65507
- const v = raw[k];
65508
- if (v === void 0 || v === "" || v === false)
65509
- continue;
65510
- out[k] = k.startsWith("is_") ? Boolean(v) : k === "merge_radius" ? Number(v) : String(v).slice(0, 60);
65511
- }
65512
- return out;
65513
- }
65514
- var MSG_DOOR_TYPE = { 1: "sliding", 2: "double_sliding", 3: "sliding", 4: "double_sliding", 5: "hinged", 6: "double_hinged" };
65515
- function importFrame(level2) {
65516
- const xs = [];
65517
- const ys = [];
65518
- for (const g of level2.nav_graphs ?? [])
65519
- for (const v of g.vertices ?? [])
65520
- xs.push(v.x), ys.push(v.y);
65521
- for (const d of level2.doors ?? [])
65522
- xs.push(d.v1_x, d.v2_x), ys.push(d.v1_y, d.v2_y);
65523
- if (!xs.length)
65524
- for (const v of level2.wall_graph?.vertices ?? [])
65525
- xs.push(v.x), ys.push(v.y);
65526
- if (!xs.length)
65527
- return { ...DEFAULT_PLAN_FRAME };
65528
- const pad = 3;
65529
- 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) };
65530
- }
65531
- var rot = (x, y, a) => ({ x: x * Math.cos(a) - y * Math.sin(a), y: x * Math.sin(a) + y * Math.cos(a) });
65532
- function rmfFromFleetCore(msg) {
65533
- const rmf = emptyRmf("fleet-core");
65534
- const graphIdx = /* @__PURE__ */ new Map();
65535
- const usedFloors = /* @__PURE__ */ new Set();
65536
- for (const [i, lv] of (msg.levels ?? []).slice(0, 200).entries()) {
65537
- let floorNo2 = floorNoFromName(lv.name) ?? i + 1;
65538
- while (usedFloors.has(floorNo2))
65539
- floorNo2++;
65540
- usedFloors.add(floorNo2);
65541
- const level2 = emptyLevel(String(lv.name).slice(0, 60), floorNo2, Number(lv.elevation ?? 0), importFrame(lv));
65542
- const pool = vertexPool(level2);
65543
- const wg = lv.wall_graph;
65544
- for (const e of (wg?.edges ?? []).slice(0, 5e3)) {
65545
- const a = wg.vertices[e.v1_idx];
65546
- const b = wg.vertices[e.v2_idx];
65547
- if (a && b)
65548
- level2.walls.push({ v1: pool.at(a), v2: pool.at(b) });
65549
- }
65550
- for (const d of (lv.doors ?? []).slice(0, 500)) {
65551
- level2.doors.push({
65552
- name: String(d.name).slice(0, 60),
65553
- v1: pool.at({ x: d.v1_x, y: d.v1_y }),
65554
- v2: pool.at({ x: d.v2_x, y: d.v2_y }),
65555
- type: MSG_DOOR_TYPE[d.door_type] ?? "hinged",
65556
- ...d.motion_range ? { motionDegrees: r3(d.motion_range * 180 / Math.PI) } : {},
65557
- ...d.motion_direction ? { motionDirection: d.motion_direction < 0 ? -1 : 1 } : {}
65558
- });
66378
+ // One robot in the car at a time, enforced by the database.
66379
+ {
66380
+ key: { liftKey: 1 },
66381
+ name: "one_active_session_per_lift",
66382
+ unique: true,
66383
+ partialFilterExpression: { status: "active" }
66384
+ },
66385
+ // One open request per robot - a robot cannot queue for two lifts.
66386
+ {
66387
+ key: { robotId: 1 },
66388
+ name: "one_open_session_per_robot",
66389
+ unique: true,
66390
+ partialFilterExpression: { open: true }
66391
+ },
66392
+ { key: { siteId: 1, requestedAt: -1 } }
66393
+ ]);
66394
+ } catch (error) {
66395
+ throw new InternalServerError51("Failed to create index on robot lift sessions.");
65559
66396
  }
65560
- for (const [gi, g] of (lv.nav_graphs ?? []).entries()) {
65561
- const key = String(g.name ?? gi);
65562
- if (!graphIdx.has(key)) {
65563
- const n = Number(key);
65564
- graphIdx.set(key, Number.isInteger(n) && n >= 0 && n <= 8 ? n : Math.min(8, graphIdx.size));
65565
- }
65566
- const idx = graphIdx.get(key);
65567
- 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)) }));
65568
- for (const e of (g.edges ?? []).slice(0, 5e3)) {
65569
- const a = ids2[e.v1_idx];
65570
- const b = ids2[e.v2_idx];
65571
- if (!a || !b || a === b)
65572
- continue;
65573
- const p = msgParams(e.params);
65574
- level2.lanes.push({
65575
- v1: a,
65576
- v2: b,
65577
- graphIdx: idx,
65578
- bidirectional: (e.edge_type ?? 0) === 0,
65579
- ...Number(p.speed_limit) > 0 ? { speedLimit: Number(p.speed_limit) } : {},
65580
- ...p.mutex ? { mutex: String(p.mutex).slice(0, 60) } : {}
65581
- });
66397
+ }
66398
+ async function advance(liftKey, now = /* @__PURE__ */ new Date()) {
66399
+ await collection.updateMany(
66400
+ { liftKey, open: true, expiresAt: { $lt: now } },
66401
+ {
66402
+ $set: {
66403
+ status: "expired",
66404
+ open: false,
66405
+ closedAt: now,
66406
+ closedReason: "timed out",
66407
+ updatedAt: now
66408
+ }
65582
66409
  }
66410
+ );
66411
+ const holder = await collection.findOne({ liftKey, status: "active" });
66412
+ if (holder)
66413
+ return;
66414
+ const next = await collection.find({ liftKey, status: "queued", open: true }).sort({ requestedAt: 1, _id: 1 }).limit(1).next();
66415
+ if (!next)
66416
+ return;
66417
+ try {
66418
+ await collection.updateOne(
66419
+ { _id: next._id, status: "queued", open: true },
66420
+ {
66421
+ $set: {
66422
+ status: "active",
66423
+ activeAt: now,
66424
+ expiresAt: new Date(now.getTime() + LIFT_LEASE_MS),
66425
+ updatedAt: now
66426
+ }
66427
+ }
66428
+ );
66429
+ } catch (error) {
66430
+ if (!isDuplicateKey(error))
66431
+ throw error;
65583
66432
  }
65584
- rmf.levels.push(level2);
65585
- }
65586
- rmf.graphs = [...new Set(graphIdx.values())].sort((a, b) => a - b).map((idx) => ({ idx, name: `Graph ${idx}`, brands: ["fleet-core"] }));
65587
- rmf.referenceLevel = rmf.levels[0]?.name;
65588
- const levelNames = new Set(rmf.levels.map((l) => l.name));
65589
- for (const l of (msg.lifts ?? []).slice(0, 50)) {
65590
- const yaw = Number(l.ref_yaw ?? 0);
65591
- const doors = (l.doors ?? []).slice(0, 8).map((d) => {
65592
- const a = rot(d.v1_x - l.ref_x, d.v1_y - l.ref_y, -yaw);
65593
- const b = rot(d.v2_x - l.ref_x, d.v2_y - l.ref_y, -yaw);
65594
- return {
65595
- name: String(d.name).slice(0, 60),
65596
- type: d.door_type === 2 || d.door_type === 4 ? "double_sliding" : "sliding",
65597
- x: r3((a.x + b.x) / 2),
65598
- y: r3((a.y + b.y) / 2),
65599
- widthM: r3(Math.hypot(b.x - a.x, b.y - a.y)),
65600
- axisYawRad: r3(Math.atan2(b.y - a.y, b.x - a.x))
65601
- };
65602
- });
65603
- const served = (l.levels ?? []).filter((n) => levelNames.has(n));
65604
- rmf.lifts.push({
65605
- name: String(l.name).slice(0, 60),
65606
- x: r3(l.ref_x),
65607
- y: r3(l.ref_y),
65608
- yawRad: r3(yaw),
65609
- widthM: r3(l.width),
65610
- depthM: r3(l.depth),
65611
- referenceFloor: served[0] ?? rmf.referenceLevel ?? "",
65612
- levelDoors: served.map((level2) => ({ level: level2, doors: doors.map((d) => d.name) })),
65613
- doors
65614
- });
65615
66433
  }
65616
- return rmf;
65617
- }
65618
- function legacyFromRmf(rmf) {
65619
- const levels = [];
65620
- const doors = [];
65621
- for (const lv of rmf.levels) {
65622
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
65623
- const p = (id) => {
65624
- const q = v.get(id);
65625
- return q ? toPlan(lv.planFrame, q) : null;
65626
- };
65627
- const walls = lv.walls.flatMap((w) => {
65628
- const a = p(w.v1);
65629
- const b = p(w.v2);
65630
- return a && b ? [{ start: a, end: b }] : [];
65631
- });
65632
- const zones = lv.zones.flatMap((z5) => {
65633
- const points = z5.vertices.map(p).filter((q) => !!q);
65634
- return points.length >= 3 ? [{ name: z5.name, points: points.slice(0, 200) }] : [];
65635
- });
65636
- levels.push({ floorNo: lv.floorNo, name: lv.name, elevationM: lv.elevationM, walls: walls.slice(0, 2e3), zones: zones.slice(0, 200) });
65637
- for (const d of lv.doors) {
65638
- const a = p(d.v1);
65639
- const b = p(d.v2);
65640
- if (a && b)
65641
- doors.push({ name: d.name, floorNo: lv.floorNo, type: collapseDoor(d.type), start: a, end: b });
66434
+ async function enqueue(value) {
66435
+ const now = /* @__PURE__ */ new Date();
66436
+ const liftKey = liftQueueKey(String(value.mapId), value.liftName);
66437
+ await closeExpiredForRobot(value.robotId, now);
66438
+ let insertedId;
66439
+ try {
66440
+ const res = await collection.insertOne({
66441
+ ...value,
66442
+ liftKey,
66443
+ createdBy: new ObjectId110(value.createdBy),
66444
+ status: "queued",
66445
+ open: true,
66446
+ requestedAt: now,
66447
+ activeAt: null,
66448
+ expiresAt: new Date(now.getTime() + LIFT_QUEUE_TTL_MS),
66449
+ closedAt: null,
66450
+ updatedAt: now
66451
+ });
66452
+ insertedId = res.insertedId;
66453
+ } catch (error) {
66454
+ if (isDuplicateKey(error)) {
66455
+ throw new AppError23("This robot already has a lift request open. Release it first.", 409);
66456
+ }
66457
+ throw error;
65642
66458
  }
66459
+ await advance(liftKey, now);
66460
+ return insertedId;
65643
66461
  }
65644
- const byName = new Map(rmf.levels.map((l) => [l.name, l]));
65645
- const lifts = [];
65646
- for (const l of rmf.lifts) {
65647
- const withDoors = l.levelDoors.filter((x) => x.doors.length).map((x) => byName.get(x.level)?.floorNo);
65648
- let floors = [...new Set(withDoors.filter((n) => typeof n === "number"))];
65649
- if (floors.length < 2)
65650
- floors = rmf.levels.map((x) => x.floorNo);
65651
- if (floors.length < 2)
65652
- continue;
65653
- const ref = byName.get(l.referenceFloor) ?? rmf.levels[0];
65654
- if (!ref)
65655
- continue;
65656
- const c = toPlan(ref.planFrame, l);
65657
- const f = ref.planFrame;
65658
- lifts.push({
65659
- name: l.name,
65660
- x: c.x,
65661
- y: c.y,
65662
- widthM: r3(clamp2(l.widthM / (f.maxX - f.minX || 1) * PLAN_W_M2, 0.5, 10)),
65663
- depthM: r3(clamp2(l.depthM / (f.maxY - f.minY || 1) * PLAN_H_M2, 0.5, 10)),
65664
- floors: floors.sort((a, b) => a - b)
65665
- });
66462
+ async function closeExpiredForRobot(robotId, now) {
66463
+ const stale = await collection.findOne({ robotId, open: true, expiresAt: { $lt: now } });
66464
+ if (stale)
66465
+ await advance(stale.liftKey, now);
65666
66466
  }
65667
- return { levels, doors: doors.slice(0, 500), lifts };
65668
- }
65669
- var defaultCabinDoor = (l) => ({
65670
- name: "door1",
65671
- type: "double_sliding",
65672
- x: r3(l.widthM / 2),
65673
- y: 0,
65674
- widthM: r3(Math.min(1.2, l.depthM * 0.8)),
65675
- axisYawRad: r3(Math.PI / 2)
65676
- });
65677
- function mergeLegacyIntoRmf(prev, legacy) {
65678
- const base = prev ? structuredClone(prev) : emptyRmf("editor");
65679
- const refFrame = base.levels[0]?.planFrame ?? DEFAULT_PLAN_FRAME;
65680
- const legacyFloors = new Map((legacy.levels ?? []).map((l) => [l.floorNo, l]));
65681
- const allFloors = /* @__PURE__ */ new Set([
65682
- ...legacyFloors.keys(),
65683
- ...(legacy.doors ?? []).map((d) => d.floorNo),
65684
- ...(legacy.lifts ?? []).flatMap((l) => l.floors)
65685
- ]);
65686
- for (const floorNo2 of allFloors) {
65687
- if (base.levels.some((l) => l.floorNo === floorNo2))
65688
- continue;
65689
- base.levels.push(emptyLevel(legacyFloors.get(floorNo2)?.name || floorLabel(floorNo2), floorNo2, legacyFloors.get(floorNo2)?.elevationM ?? 0, { ...refFrame }));
66467
+ async function getSessionById(id) {
66468
+ const session = await collection.findOne({ _id: toObjectId16(id, "lift session") });
66469
+ if (!session)
66470
+ throw new NotFoundError44("Lift session not found.");
66471
+ return session;
65690
66472
  }
65691
- base.levels.sort((a, b) => a.floorNo - b.floorNo);
65692
- for (const lv of base.levels) {
65693
- const src = legacyFloors.get(lv.floorNo);
65694
- if (src?.name)
65695
- lv.name = String(src.name).slice(0, 60);
65696
- if (typeof src?.elevationM === "number")
65697
- lv.elevationM = src.elevationM;
65698
- const prevDoors = new Map(lv.doors.map((d) => [d.name, d]));
65699
- lv.walls = [];
65700
- lv.zones = [];
65701
- lv.doors = [];
65702
- const pool = vertexPool(lv);
65703
- const at2 = (p) => pool.at(fromPlan(lv.planFrame, p));
65704
- for (const w of src?.walls ?? [])
65705
- lv.walls.push({ v1: at2(w.start), v2: at2(w.end) });
65706
- for (const z5 of src?.zones ?? [])
65707
- lv.zones.push({ name: z5.name, vertices: z5.points.map(at2) });
65708
- for (const d of (legacy.doors ?? []).filter((x) => x.floorNo === lv.floorNo)) {
65709
- const was = prevDoors.get(d.name);
65710
- const keep = was && collapseDoor(was.type) === d.type;
65711
- lv.doors.push({
65712
- ...keep ? was : {},
65713
- name: d.name,
65714
- v1: at2(d.start),
65715
- v2: at2(d.end),
65716
- type: keep ? was.type : d.type
65717
- });
65718
- }
65719
- pruneVertices(lv);
66473
+ async function getQueue(mapId, liftNames) {
66474
+ const now = /* @__PURE__ */ new Date();
66475
+ const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
66476
+ for (const key of keys)
66477
+ await advance(key, now);
66478
+ return collection.find({ liftKey: { $in: keys }, open: true }).sort({ requestedAt: 1, _id: 1 }).toArray();
65720
66479
  }
65721
- const prevLifts = new Map(base.lifts.map((l) => [l.name, l]));
65722
- const byFloor = new Map(base.levels.map((l) => [l.floorNo, l]));
65723
- base.lifts = (legacy.lifts ?? []).map((l) => {
65724
- const was = prevLifts.get(l.name);
65725
- const ref = was && base.levels.find((x) => x.name === was.referenceFloor) || byFloor.get(l.floors[0]) || base.levels[0];
65726
- const f = ref.planFrame;
65727
- const c = fromPlan(f, l);
65728
- const widthM = r3(l.widthM / PLAN_W_M2 * (f.maxX - f.minX));
65729
- const depthM = r3(l.depthM / PLAN_H_M2 * (f.maxY - f.minY));
65730
- const doors = was?.doors?.length ? was.doors : [defaultCabinDoor({ widthM, depthM })];
65731
- const served = l.floors.map((n) => byFloor.get(n)?.name).filter((n) => !!n);
65732
- const prevLevelDoors = new Map((was?.levelDoors ?? []).map((x) => [x.level, x.doors]));
65733
- return {
65734
- name: l.name,
65735
- x: c.x,
65736
- y: c.y,
65737
- yawRad: was?.yawRad ?? 0,
65738
- widthM,
65739
- depthM,
65740
- referenceFloor: ref.name,
65741
- ...was?.initialFloor && served.includes(was.initialFloor) ? { initialFloor: was.initialFloor } : {},
65742
- doors,
65743
- levelDoors: served.map((level2) => ({ level: level2, doors: prevLevelDoors.get(level2)?.length ? prevLevelDoors.get(level2) : doors.map((d) => d.name) }))
65744
- };
65745
- });
65746
- base.referenceLevel = base.levels.find((l) => l.name === base.referenceLevel)?.name ?? base.levels[0]?.name;
65747
- return base;
65748
- }
65749
- function rmfProblem(rmf) {
65750
- const levelNames = /* @__PURE__ */ new Set();
65751
- const doorNames = /* @__PURE__ */ new Set();
65752
- const graphIdx = new Set(rmf.graphs.map((g) => g.idx));
65753
- for (const lv of rmf.levels) {
65754
- if (levelNames.has(lv.name))
65755
- return `Two floors are both called "${lv.name}".`;
65756
- levelNames.add(lv.name);
65757
- const f = lv.planFrame;
65758
- if (!(f.maxX > f.minX && f.maxY > f.minY))
65759
- return `Floor ${lv.name}: its plan frame is empty.`;
65760
- const ids2 = /* @__PURE__ */ new Set();
65761
- for (const v of lv.vertices) {
65762
- if (ids2.has(v.id))
65763
- return `Floor ${lv.name}: point id "${v.id}" is used twice.`;
65764
- ids2.add(v.id);
65765
- }
65766
- const missing = (id) => !ids2.has(id);
65767
- const edges = [...lv.walls, ...lv.doors, ...lv.lanes, ...lv.measurements];
65768
- if (edges.some((e) => missing(e.v1) || missing(e.v2)))
65769
- return `Floor ${lv.name}: a line ends at a point that does not exist.`;
65770
- if ([...lv.floors, ...lv.holes, ...lv.zones].some((p) => p.vertices.some(missing)))
65771
- return `Floor ${lv.name}: an area uses a point that does not exist.`;
65772
- for (const d of lv.doors) {
65773
- if (doorNames.has(d.name))
65774
- return `Two doors are both called "${d.name}" - door names must be unique in the building.`;
65775
- doorNames.add(d.name);
65776
- }
65777
- if (lv.lanes.some((l) => !graphIdx.has(l.graphIdx)))
65778
- return `Floor ${lv.name}: a lane belongs to a route graph that is not listed.`;
66480
+ async function getRecent(mapId, liftNames, since) {
66481
+ const keys = liftNames.map((name) => liftQueueKey(String(mapId), name));
66482
+ if (!keys.length)
66483
+ return [];
66484
+ return collection.find({ liftKey: { $in: keys }, status: { $in: ["released", "expired"] }, closedAt: { $gte: since } }).sort({ closedAt: -1, _id: -1 }).limit(20).toArray();
65779
66485
  }
65780
- for (const l of rmf.lifts) {
65781
- const cabin = new Set(l.doors.map((d) => d.name));
65782
- if (l.referenceFloor && !levelNames.has(l.referenceFloor))
65783
- return `Lift ${l.name}: its reference floor "${l.referenceFloor}" does not exist.`;
65784
- for (const x of l.levelDoors) {
65785
- if (!levelNames.has(x.level))
65786
- return `Lift ${l.name}: floor "${x.level}" does not exist.`;
65787
- if (x.doors.some((d) => !cabin.has(d)))
65788
- return `Lift ${l.name}: floor ${x.level} opens a cabin door the lift does not have.`;
66486
+ async function refresh(id) {
66487
+ const now = /* @__PURE__ */ new Date();
66488
+ const res = await collection.updateOne(
66489
+ { _id: id, status: "active", open: true, expiresAt: { $gte: now } },
66490
+ { $set: { expiresAt: new Date(now.getTime() + LIFT_LEASE_MS), updatedAt: now } }
66491
+ );
66492
+ if (!res.matchedCount) {
66493
+ throw new AppError23("This lift session is no longer active.", 409);
65789
66494
  }
65790
66495
  }
65791
- return null;
65792
- }
65793
- var P = { str: (v) => [1, v], int: (v) => [2, Math.round(v)], dbl: (v) => [3, v], bool: (v) => [4, v] };
65794
- function toBuildingYaml(name, rmf) {
65795
- const levels = {};
65796
- for (const lv of rmf.levels) {
65797
- const idx = new Map(lv.vertices.map((v, i) => [v.id, i]));
65798
- const edge2 = (v1, v2, params) => [idx.get(v1), idx.get(v2), params];
65799
- levels[lv.name] = {
65800
- elevation: lv.elevationM,
65801
- vertices: lv.vertices.map((v) => {
65802
- const params = {};
65803
- for (const [k, val] of Object.entries(v.params ?? {})) {
65804
- params[k] = typeof val === "boolean" ? P.bool(val) : typeof val === "number" ? P.dbl(val) : P.str(String(val));
66496
+ async function release(session, reason = "released") {
66497
+ const now = /* @__PURE__ */ new Date();
66498
+ await collection.updateOne({ _id: session._id, open: true }, [
66499
+ {
66500
+ $set: {
66501
+ status: { $cond: [{ $eq: ["$status", "active"] }, "released", "cancelled"] },
66502
+ open: false,
66503
+ closedAt: now,
66504
+ closedReason: reason,
66505
+ updatedAt: now
65805
66506
  }
65806
- return [v.x, v.y, 0, v.name ?? "", params];
65807
- }),
65808
- walls: lv.walls.map((w) => edge2(w.v1, w.v2, {})),
65809
- doors: lv.doors.map(
65810
- (d) => edge2(d.v1, d.v2, {
65811
- name: P.str(d.name),
65812
- type: P.str(d.type),
65813
- motion_axis: P.str(d.motionAxis ?? "start"),
65814
- motion_degrees: P.dbl(d.motionDegrees ?? 90),
65815
- motion_direction: P.int(d.motionDirection ?? 1),
65816
- right_left_ratio: P.dbl(d.rightLeftRatio ?? 1)
65817
- })
65818
- ),
65819
- lanes: lv.lanes.map(
65820
- (l) => edge2(l.v1, l.v2, {
65821
- graph_idx: P.int(l.graphIdx),
65822
- bidirectional: P.bool(l.bidirectional),
65823
- orientation: P.str(l.orientation ?? ""),
65824
- ...l.speedLimit ? { speed_limit: P.dbl(l.speedLimit) } : {},
65825
- ...l.mutex ? { mutex: P.str(l.mutex) } : {}
65826
- })
65827
- ),
65828
- measurements: lv.measurements.map((m) => edge2(m.v1, m.v2, { distance: P.dbl(m.distanceM) })),
65829
- floors: lv.floors.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
65830
- holes: lv.holes.map((f) => ({ vertices: f.vertices.map((id) => idx.get(id)), parameters: {} })),
65831
- fiducials: lv.fiducials.map((f) => [f.x, f.y, f.name]),
65832
- layers: {},
65833
- models: []
65834
- };
66507
+ }
66508
+ ]);
66509
+ await advance(session.liftKey, now);
65835
66510
  }
65836
- const elevation = new Map(rmf.levels.map((l) => [l.name, l.elevationM]));
65837
- const lifts = {};
65838
- for (const l of rmf.lifts) {
65839
- const served = l.levelDoors.map((x) => x.level).sort((a, b) => (elevation.get(a) ?? 0) - (elevation.get(b) ?? 0));
65840
- lifts[l.name] = {
65841
- x: l.x,
65842
- y: l.y,
65843
- yaw: l.yawRad,
65844
- width: l.widthM,
65845
- depth: l.depthM,
65846
- reference_floor_name: l.referenceFloor,
65847
- initial_floor_name: l.initialFloor ?? served[0] ?? l.referenceFloor,
65848
- lowest_floor: served[0] ?? l.referenceFloor,
65849
- highest_floor: served[served.length - 1] ?? l.referenceFloor,
65850
- doors: Object.fromEntries(
65851
- 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 }])
65852
- ),
65853
- level_doors: Object.fromEntries(l.levelDoors.map((x) => [x.level, x.doors])),
65854
- plugins: true
65855
- };
66511
+ async function getOpenForRobot(robotId) {
66512
+ const now = /* @__PURE__ */ new Date();
66513
+ await closeExpiredForRobot(robotId, now);
66514
+ const session = await collection.findOne({ robotId, open: true });
66515
+ if (!session)
66516
+ return null;
66517
+ await advance(session.liftKey, now);
66518
+ return collection.findOne({ _id: session._id });
65856
66519
  }
65857
- return JSON.stringify(
65858
- { name, coordinate_system: "cartesian_meters", reference_level_name: rmf.referenceLevel ?? rmf.levels[0]?.name ?? "", graphs: {}, parameters: {}, levels, lifts },
65859
- null,
65860
- 1
65861
- );
65862
- }
65863
- function segmentsIntersect(a, b, c, d) {
65864
- const det = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x);
65865
- if (Math.abs(det) < 0.01)
65866
- return false;
65867
- const t = ((a.x - c.x) * (c.y - d.y) - (a.y - c.y) * (c.x - d.x)) / det;
65868
- const u = -((a.x - b.x) * (a.y - c.y) - (a.y - b.y) * (a.x - c.x)) / det;
65869
- return t >= 0 && t <= 1 && u >= 0 && u <= 1;
65870
- }
65871
- function inLift(p, l) {
65872
- const q = rot(p.x - l.x, p.y - l.y, -l.yawRad);
65873
- return Math.abs(q.x) <= l.widthM / 2 && Math.abs(q.y) <= l.depthM / 2;
65874
- }
65875
- function toNavGraphs(name, rmf) {
65876
- const out = {};
65877
- for (let gi = 0; gi <= 8; gi++) {
65878
- const levels = {};
65879
- const doors = {};
65880
- let empty = true;
65881
- for (const lv of rmf.levels) {
65882
- const v = new Map(lv.vertices.map((x) => [x.id, x]));
65883
- const lanes = lv.lanes.filter((l) => l.graphIdx === gi);
65884
- if (lanes.length)
65885
- empty = false;
65886
- const order = [];
65887
- const mapped = /* @__PURE__ */ new Map();
65888
- for (const l of lanes)
65889
- for (const id of [l.v1, l.v2])
65890
- if (!mapped.has(id))
65891
- mapped.set(id, order.push(id) - 1);
65892
- const lifts2 = rmf.lifts.filter((l) => l.levelDoors.some((x) => x.level === lv.name && x.doors.length));
65893
- const vertices = order.map((id) => {
65894
- const q = v.get(id);
65895
- const lift2 = lifts2.find((l) => inLift(q, l));
65896
- return [q.x, q.y, { name: q.name ?? "", ...q.params ?? {}, ...lift2 ? { lift: lift2.name } : {} }];
65897
- });
65898
- const navLanes = [];
65899
- for (const l of lanes) {
65900
- const a = v.get(l.v1);
65901
- const b = v.get(l.v2);
65902
- const p = {};
65903
- for (const d of lv.doors) {
65904
- const c = v.get(d.v1);
65905
- const e = v.get(d.v2);
65906
- if (c && e && segmentsIntersect(a, b, c, e))
65907
- p.door_name = d.name;
65908
- }
65909
- if (l.orientation)
65910
- p.orientation_constraint = l.orientation;
65911
- if (l.speedLimit && l.speedLimit > 0)
65912
- p.speed_limit = l.speedLimit;
65913
- if (l.mutex)
65914
- p.mutex = l.mutex;
65915
- const endDock = b.params?.dock_name;
65916
- const startDock = a.params?.dock_name;
65917
- const s = mapped.get(l.v1);
65918
- const t = mapped.get(l.v2);
65919
- if (l.bidirectional) {
65920
- const fwd = { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} };
65921
- const back = { ...p, ...endDock ? { undock_name: endDock } : {}, ...startDock ? { dock_name: startDock } : {} };
65922
- if (l.orientation)
65923
- back.orientation_constraint = l.orientation === "forward" ? "backward" : "forward";
65924
- navLanes.push([s, t, fwd], [t, s, back]);
65925
- } else {
65926
- navLanes.push([s, t, { ...p, ...endDock ? { dock_name: endDock } : {}, ...startDock ? { undock_name: startDock } : {} }]);
66520
+ async function cancelForMap(mapId, keepLiftNames = []) {
66521
+ const now = /* @__PURE__ */ new Date();
66522
+ await collection.updateMany(
66523
+ { mapId, open: true, liftName: { $nin: keepLiftNames } },
66524
+ {
66525
+ $set: {
66526
+ status: "cancelled",
66527
+ open: false,
66528
+ closedAt: now,
66529
+ closedReason: "lift removed from the map",
66530
+ updatedAt: now
65927
66531
  }
65928
66532
  }
65929
- levels[lv.name] = { vertices, lanes: navLanes };
65930
- for (const d of lv.doors) {
65931
- const c = v.get(d.v1);
65932
- const e = v.get(d.v2);
65933
- if (c && e)
65934
- doors[d.name] = { endpoints: [[c.x, c.y], [e.x, e.y]], map: lv.name };
65935
- }
65936
- }
65937
- if (empty)
65938
- continue;
65939
- const lifts = Object.fromEntries(rmf.lifts.map((l) => [l.name, { position: [l.x, l.y, l.yawRad], dims: [l.widthM, l.depthM] }]));
65940
- out[gi] = JSON.stringify({ building_name: name, levels, lifts, doors }, null, 1);
66533
+ );
65941
66534
  }
65942
- return out;
65943
- }
65944
- function rmfSummary(rmf) {
65945
- if (!rmf)
65946
- return null;
65947
- const sum = (f) => rmf.levels.reduce((n, l) => n + f(l), 0);
65948
66535
  return {
65949
- source: rmf.source ?? "editor",
65950
- levels: rmf.levels.length,
65951
- lanes: sum((l) => l.lanes.length),
65952
- waypoints: sum((l) => l.vertices.filter((v) => v.name).length),
65953
- doors: sum((l) => l.doors.length),
65954
- lifts: rmf.lifts.length,
65955
- graphs: rmf.graphs.length
66536
+ createIndex,
66537
+ advance,
66538
+ enqueue,
66539
+ getSessionById,
66540
+ getQueue,
66541
+ getRecent,
66542
+ refresh,
66543
+ release,
66544
+ getOpenForRobot,
66545
+ cancelForMap
65956
66546
  };
65957
66547
  }
65958
66548
 
65959
66549
  // src/controllers/robot-map.controller.ts
66550
+ import Joi78 from "joi";
66551
+ import { AppError as AppError24, BadRequestError as BadRequestError137, NotFoundError as NotFoundError45, logger as logger109 } from "@7365admin1/node-server-utils";
66552
+ import { load as loadYaml, CORE_SCHEMA as YAML_CORE_SCHEMA } from "js-yaml";
65960
66553
  function useRobotMapController(deps) {
65961
66554
  const now = () => deps?.now?.() ?? Date.now();
65962
66555
  const robots = () => useRobotRepo();
@@ -66153,6 +66746,32 @@ function useRobotMapController(deps) {
66153
66746
  fail(next, e);
66154
66747
  }
66155
66748
  }
66749
+ async function importBuildingFile(req, res, next) {
66750
+ const { error, value } = buildingFileImportSchema.validate(req.body ?? {});
66751
+ if (error)
66752
+ return fail(next, new BadRequestError137(error.message));
66753
+ try {
66754
+ if (/(^|[\s[{,:-])[&*][A-Za-z0-9_-]+/m.test(value.text.replace(/'[^'\n]*'|"[^"\n]*"/g, "''"))) {
66755
+ throw new BadRequestError137("This file uses YAML anchors or aliases, which building files never contain. Export it again from the traffic editor.");
66756
+ }
66757
+ let doc;
66758
+ try {
66759
+ doc = loadYaml(value.text, { schema: YAML_CORE_SCHEMA, json: true });
66760
+ } catch (e) {
66761
+ throw new BadRequestError137(`This file is not valid YAML: ${String(e?.reason ?? e?.message ?? "unreadable").slice(0, 120)}.`);
66762
+ }
66763
+ const out = value.format === "nav" ? { name: "", ...fromNavGraph(doc, value.graph) } : fromBuildingYaml(doc);
66764
+ const checked = rmfBuildingSchema.validate(out.rmf);
66765
+ if (checked.error)
66766
+ throw new BadRequestError137(`This file cannot be used: ${checked.error.message}`);
66767
+ const problem = rmfProblem(checked.value);
66768
+ if (problem)
66769
+ throw new BadRequestError137(`This file cannot be used: ${problem}`);
66770
+ res.json({ format: value.format, name: out.name, rmf: checked.value, summary: rmfSummary(checked.value), warnings: out.warnings });
66771
+ } catch (e) {
66772
+ fail(next, e instanceof RmfImportError ? new BadRequestError137(e.message) : e);
66773
+ }
66774
+ }
66156
66775
  const floorParam = Joi78.number().integer().min(-20).max(200).required();
66157
66776
  function sniffImage(buf) {
66158
66777
  if (buf.length > 8 && buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
@@ -66188,6 +66807,8 @@ function useRobotMapController(deps) {
66188
66807
  metersPerPixel: value.metersPerPixel,
66189
66808
  tx: value.tx,
66190
66809
  ty: value.ty,
66810
+ yawRad: value.yawRad,
66811
+ space: value.space,
66191
66812
  updatedBy: callerId(req) ?? "",
66192
66813
  ...data ? { data, mime, bytes: data.length } : {}
66193
66814
  });
@@ -66447,6 +67068,7 @@ function useRobotMapController(deps) {
66447
67068
  return {
66448
67069
  getOpenRmfBuilding,
66449
67070
  exportMap,
67071
+ importBuildingFile,
66450
67072
  putFloorPlan,
66451
67073
  getFloorPlan,
66452
67074
  deleteFloorPlan,
@@ -101265,6 +101887,7 @@ export {
101265
101887
  attendanceSchema,
101266
101888
  attendanceSettingsSchema,
101267
101889
  buildSelfServiceEmailContext,
101890
+ buildingFileImportSchema,
101268
101891
  buildingFromRmf,
101269
101892
  buildingInPlanFrame,
101270
101893
  buildingMapBodySchema,
@@ -101518,6 +102141,7 @@ export {
101518
102141
  resolveInviteActor,
101519
102142
  resolveSiteTimezone,
101520
102143
  resolveStaffRole,
102144
+ rmf_building_util_exports as rmfBuilding,
101521
102145
  rmfBuildingSchema,
101522
102146
  robotActionsFor,
101523
102147
  robotBrandFor,