UNPKG

mermaid

Version:

Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.

3,792 lines • 131 kB
import {
  applyLineJumpsToSvg,
  normalizeLineHops
} from "./chunk-5UF2PZMI.mjs";
import {
  clearLayoutRenderState,
  createCommonLayoutRenderer,
  defaultMeasureLayout
} from "./chunk-NZQPWTTU.mjs";
import "./chunk-PWRPXRNR.mjs";
import "./chunk-BW5T7TNM.mjs";
import {
  ease,
  isAxisTaggedRoute
} from "./chunk-236L5HCG.mjs";
import "./chunk-7WTMCWOC.mjs";
import {
  withLineIntersectionOrigin
} from "./chunk-57UP3UTE.mjs";
import "./chunk-46A7OBX7.mjs";
import "./chunk-UIPQR6YN.mjs";
import "./chunk-YMNL5UXF.mjs";
import "./chunk-WJPS3GCF.mjs";
import "./chunk-7CML27B5.mjs";
import "./chunk-DNOZYBWV.mjs";
import "./chunk-VSULCTJ3.mjs";
import "./chunk-L2MXK2W4.mjs";
import {
  log
} from "./chunk-2RP5QIEU.mjs";
import {
  __name
} from "./chunk-42YUCIBL.mjs";

// src/rendering-util/layout-algorithms/layered/failureMode.ts
var throwsOnFailure = false;
function setLayeredThrowsOnFailure(value) {
  throwsOnFailure = value;
}
__name(setLayeredThrowsOnFailure, "setLayeredThrowsOnFailure");
function layeredThrowsOnFailure() {
  return throwsOnFailure;
}
__name(layeredThrowsOnFailure, "layeredThrowsOnFailure");

// src/rendering-util/layout-algorithms/layered/lineHops.ts
var JUMP_RADIUS = 6;
function applyLayeredLineJumps(data, { measure }) {
  const lineHops = normalizeLineHops(data.config?.layered?.lineHops);
  if (lineHops === false) {
    return;
  }
  const edges = data.edges.filter(
    (edge) => Array.isArray(edge.points) && edge.points.length >= 2
  ).map((edge) => ({
    id: edge.id,
    points: edge.points,
    curve: edge.curve,
    cornerRadius: edge.cornerRadius,
    arrowTypeStart: edge.arrowTypeStart,
    arrowTypeEnd: edge.arrowTypeEnd
  }));
  applyLineJumpsToSvg(measure.groups.edgePaths, edges, {
    enabled: true,
    jumpRadius: JUMP_RADIUS,
    jumpStyle: lineHops
  });
}
__name(applyLayeredLineJumps, "applyLayeredLineJumps");

// src/rendering-util/layout-algorithms/layered/layered.ts
var Kind = { Node: 0, Dummy: 1, Label: 2, StartPort: 3, EndPort: 4 };
var NODE_INPUTS = [
  "w",
  "h",
  "kind",
  "pin",
  "hint",
  "key",
  "span"
];
var EDGE_INPUTS = [
  "tail",
  "head",
  "minlen",
  "labelW",
  "labelH",
  "tailDx",
  "headDx",
  "tailFixed",
  "headFixed"
];
function layoutInputs(nodes, edges) {
  const inputs = [];
  for (const n of nodes) for (const f of NODE_INPUTS) inputs.push(n[f]);
  for (const e of edges) for (const f of EDGE_INPUTS) inputs.push(+e[f]);
  return inputs;
}
__name(layoutInputs, "layoutInputs");
function lnode(w, h, kind = Kind.Node) {
  return { w, h, kind, pin: 0, hint: NaN, key: NaN, span: 0, x: 0, y: 0, rank: 0 };
}
__name(lnode, "lnode");
function ledge(tail, head, minlen = 1, labelW = 0, labelH = 0) {
  return {
    tail,
    head,
    minlen,
    labelW,
    labelH,
    tailDx: 0,
    headDx: 0,
    tailFixed: false,
    headFixed: false,
    reversed: false,
    points: [],
    labelX: 0,
    labelY: 0
  };
}
__name(ledge, "ledge");
var MAX_SWEEPS = 24;
var MAX_DUMMIES = 2e4;
var PORT_PITCH = 16;
var MIN_PITCH = 8;
var MIN_SLOPE = 0.125;
var MAX_GAP = 3;
var TRACK_MARGIN = 20;
var TRACK_PITCH = 10;
var TRACK_SPREAD = 14;
var LEVEL_WIDE = 2;
var LEVEL_MARGIN = 28;
var LEVEL_PITCH = 12;
var LEVEL_LEAD = 12;
var LEVEL_CLEAR = 8;
var LEVEL_TOUCH = 4;
var CROSSED_SLOPE = 0.5;
var IN_LINE = 0.5;
var TWIN = 1;
var SNAP = 12;
var BEND_SNAP = 24;
var LEAN_CLEAR = 40;
var MAX_WEIGHED = 400;
var SAMPLES = 16;
var LINE_A = new Float64Array(2 * SAMPLES + 2);
var LINE_B = new Float64Array(2 * SAMPLES + 2);
var End = { Held: 0, Leaves: 1, Arrives: 2 };
function isDummy(kind) {
  return kind === Kind.Dummy || kind === Kind.Label;
}
__name(isDummy, "isDummy");
function gapBetween(other, self, nodeSep, sep) {
  if (other === Kind.Node) return nodeSep / 2 + sep / 2;
  return other === self ? sep : sep / 2;
}
__name(gapBetween, "gapBetween");
function sortRange(list, from, to, key) {
  for (let i = from + 1; i < to; i++) {
    const item = list[i];
    const k = key[item];
    let j = i - 1;
    while (j >= from && (key[list[j]] > k || key[list[j]] === k && list[j] > item)) {
      list[j + 1] = list[j];
      j--;
    }
    list[j + 1] = item;
  }
}
__name(sortRange, "sortRange");
function sortByBary(list, count, bary, pos, right, spare) {
  const before = /* @__PURE__ */ __name((a, b) => bary[a] < bary[b] || bary[a] === bary[b] && (right ? pos[a] > pos[b] : pos[a] < pos[b]), "before");
  const RUN = 8;
  for (let s = 0; s < count; s += RUN) {
    for (let i = s + 1, end = Math.min(count, s + RUN); i < end; i++) {
      const item = list[i];
      let j = i - 1;
      while (j >= s && before(item, list[j])) {
        list[j + 1] = list[j];
        j--;
      }
      list[j + 1] = item;
    }
  }
  let from = list;
  let to = spare;
  for (let width = RUN; width < count; width *= 2) {
    for (let s = 0; s < count; s += 2 * width) {
      const mid = Math.min(count, s + width);
      const end = Math.min(count, s + 2 * width);
      let i = s;
      let j = mid;
      let k = s;
      while (i < mid && j < end) to[k++] = before(from[j], from[i]) ? from[j++] : from[i++];
      while (i < mid) to[k++] = from[i++];
      while (j < end) to[k++] = from[j++];
    }
    const t = from;
    from = to;
    to = t;
  }
  if (from !== list) for (let i = 0; i < count; i++) list[i] = from[i];
}
__name(sortByBary, "sortByBary");
function layered(nodes, edges, opt) {
  const real = nodes.length;
  if (real === 0) return { width: 0, height: 0 };
  const m = edges.length;
  if (real === 1 && m === 0 && nodes[0].kind === Kind.Node) {
    const node = nodes[0];
    node.rank = 0;
    node.x = node.w / 2;
    node.y = node.h / 2;
    return { width: node.w, height: node.h };
  }
  let step = 1;
  if (m > 0) {
    const seen = /* @__PURE__ */ new Set();
    for (const e of edges) {
      const a = Math.min(e.tail, e.head);
      const b = Math.max(e.tail, e.head);
      const key = a * real + b;
      if (e.labelW > 0 || seen.has(key)) {
        step = 2;
        break;
      }
      seen.add(key);
    }
  }
  orient(nodes, edges);
  rank(nodes, edges, step);
  const span = new Int32Array(m);
  let dummies = 0;
  for (let ei = 0; ei < m; ei++) {
    const e = edges[ei];
    span[ei] = Math.abs(nodes[e.head].rank - nodes[e.tail].rank);
    if (span[ei] > 1) dummies += span[ei] - 1;
  }
  const direct = new Uint8Array(m);
  if (dummies > MAX_DUMMIES) {
    const longest = [];
    for (let ei = 0; ei < m; ei++) if (span[ei] > 1) longest.push(ei);
    longest.sort((a, b) => span[b] - span[a] || a - b);
    for (const ei of longest) {
      if (dummies <= MAX_DUMMIES) break;
      direct[ei] = 1;
      dummies -= span[ei] - 1;
    }
  }
  const n = real + dummies;
  const W = new Float64Array(n);
  const H = new Float64Array(n);
  const KIND = new Uint8Array(n);
  const RANK = new Int32Array(n);
  let maxRank = 0;
  for (let i = 0; i < real; i++) {
    const node = nodes[i];
    W[i] = node.w;
    H[i] = node.h;
    KIND[i] = node.kind;
    RANK[i] = node.rank;
    if (node.rank > maxRank) maxRank = node.rank;
  }
  let segments = 0;
  for (let ei = 0; ei < m; ei++) if (!direct[ei]) segments += span[ei];
  const EF = new Int32Array(segments);
  const ET = new Int32Array(segments);
  const EFD = new Float64Array(segments);
  const ETD = new Float64Array(segments);
  const firstDummy = new Int32Array(m).fill(-1);
  const heads = new Uint8Array(maxRank + 1);
  const labelNode = new Int32Array(m).fill(-1);
  let spans = false;
  for (let i = 0; i < real; i++)
    if (nodes[i].span > 0 && nodes[i].kind === Kind.Node) spans = true;
  const EFK = spans ? new Uint8Array(segments) : void 0;
  const ETK = spans ? new Uint8Array(segments) : void 0;
  const firstSeg = new Int32Array(m).fill(-1);
  const lastSeg = new Int32Array(m).fill(-1);
  const KEY = new Float64Array(n).fill(NaN);
  for (let i = 0; i < real; i++) KEY[i] = nodes[i].key;
  let offsets = false;
  {
    let next = real;
    let ce = 0;
    for (let ei = 0; ei < m; ei++) {
      if (direct[ei]) continue;
      const e = edges[ei];
      const a = e.reversed ? e.head : e.tail;
      const b = e.reversed ? e.tail : e.head;
      const aDx = e.reversed ? e.headDx : e.tailDx;
      const bDx = e.reversed ? e.tailDx : e.headDx;
      if (aDx !== 0 || bDx !== 0) offsets = true;
      const ra = RANK[a];
      const rb = RANK[b];
      let labelRank = -1;
      if (e.labelW > 0) {
        labelRank = ra + (rb - ra >> 1);
        if (step === 2 && rb - ra >= 4) {
          if ((labelRank & 1) === 1) labelRank += e.reversed ? 1 : -1;
        } else if (step === 2 && (labelRank & 1) === 0) labelRank += e.reversed ? 1 : -1;
      }
      let prev = a;
      if (rb - ra > 1) firstDummy[ei] = next;
      firstSeg[ei] = ce;
      if (EFK && !(e.reversed ? e.headFixed : e.tailFixed))
        EFK[ce] = e.reversed ? End.Arrives : End.Leaves;
      for (let r = ra + 1; r < rb; r++) {
        const d = next++;
        RANK[d] = r;
        KEY[d] = KEY[a] + (KEY[b] - KEY[a]) * (r - ra) / (rb - ra);
        if (r === labelRank) {
          W[d] = e.labelW;
          H[d] = e.labelH;
          KIND[d] = Kind.Label;
          labelNode[ei] = d;
          heads[r] |= e.reversed ? 2 : 1;
        } else {
          KIND[d] = Kind.Dummy;
        }
        EF[ce] = prev;
        ET[ce] = d;
        EFD[ce] = prev === a ? aDx : 0;
        ce++;
        prev = d;
      }
      EF[ce] = prev;
      ET[ce] = b;
      EFD[ce] = prev === a ? aDx : 0;
      ETD[ce] = bDx;
      if (ETK && !(e.reversed ? e.tailFixed : e.headFixed))
        ETK[ce] = e.reversed ? End.Leaves : End.Arrives;
      lastSeg[ei] = ce;
      ce++;
    }
  }
  let GRP;
  if (opt.groups) {
    const { of, parent } = opt.groups;
    GRP = new Int32Array(n);
    for (let i = 0; i < real; i++) GRP[i] = of[i];
    const depth = /* @__PURE__ */ __name((gr) => {
      let d = 0;
      for (; gr >= 0; gr = parent[gr]) d++;
      return d;
    }, "depth");
    const lca = /* @__PURE__ */ __name((x, y2) => {
      let dx = depth(x);
      let dy = depth(y2);
      for (; dx > dy; dx--) x = parent[x];
      for (; dy > dx; dy--) y2 = parent[y2];
      while (x !== y2) {
        x = parent[x];
        y2 = parent[y2];
      }
      return x;
    }, "lca");
    for (let ei = 0; ei < m; ei++) {
      if (firstDummy[ei] < 0) continue;
      const e = edges[ei];
      const gr = lca(of[e.tail], of[e.head]);
      for (let d = firstDummy[ei], end = d + span[ei] - 1; d < end; d++) GRP[d] = gr;
    }
  }
  const succStart = new Int32Array(n + 1);
  const predStart = new Int32Array(n + 1);
  for (let e = 0; e < segments; e++) {
    succStart[EF[e] + 1]++;
    predStart[ET[e] + 1]++;
  }
  for (let i = 0; i < n; i++) {
    succStart[i + 1] += succStart[i];
    predStart[i + 1] += predStart[i];
  }
  const succE = new Int32Array(segments);
  const predE = new Int32Array(segments);
  {
    const sf = succStart.slice(0, n);
    const pf = predStart.slice(0, n);
    for (let e = 0; e < segments; e++) {
      succE[sf[EF[e]]++] = e;
      predE[pf[ET[e]]++] = e;
    }
  }
  const layerStart = new Int32Array(maxRank + 2);
  for (let i = 0; i < n; i++) layerStart[RANK[i] + 1]++;
  for (let r = 0; r <= maxRank; r++) layerStart[r + 1] += layerStart[r];
  const order = new Int32Array(n);
  const pos = new Int32Array(n);
  {
    const byRank = new Int32Array(n);
    const fill = layerStart.slice(0, maxRank + 1);
    for (let i = 0; i < n; i++) byRank[fill[RANK[i]]++] = i;
    for (let r = 0; r <= maxRank; r++) fill[r] = layerStart[r];
    const visited = new Uint8Array(n);
    const stack = [];
    for (let k = 0; k < n; k++) {
      if (visited[byRank[k]]) continue;
      stack.push(byRank[k]);
      while (stack.length > 0) {
        const v = stack.pop();
        if (visited[v]) continue;
        visited[v] = 1;
        order[fill[RANK[v]]++] = v;
        for (let j = succStart[v + 1] - 1; j >= succStart[v]; j--) {
          const w = ET[succE[j]];
          if (!visited[w]) stack.push(w);
        }
      }
    }
  }
  const sortRank = /* @__PURE__ */ __name((r, key) => {
    const s = layerStart[r];
    const e = layerStart[r + 1];
    if (e - s < 2) return false;
    for (let i = s; i < e; i++) if (Number.isNaN(key(order[i]))) return false;
    const layer = Array.from(order.subarray(s, e));
    const index = /* @__PURE__ */ new Map();
    layer.forEach((v, i) => index.set(v, i));
    layer.sort((a, b) => key(a) - key(b) || index.get(a) - index.get(b));
    order.set(layer, s);
    return true;
  }, "sortRank");
  for (let r = 0; r <= maxRank; r++) sortRank(r, (v) => KEY[v]);
  let pinned = false;
  for (let i = 0; i < real; i++) if (nodes[i].pin !== 0) pinned = true;
  if (pinned) {
    for (let r = 0; r <= maxRank; r++) {
      const layer = Array.from(order.subarray(layerStart[r], layerStart[r + 1]));
      const index = /* @__PURE__ */ new Map();
      layer.forEach((v, i) => index.set(v, i));
      const pinOf = /* @__PURE__ */ __name((v) => v < real ? nodes[v].pin : 0, "pinOf");
      layer.sort((a, b) => pinOf(a) - pinOf(b) || index.get(a) - index.get(b));
      order.set(layer, layerStart[r]);
    }
  }
  const fixed = new Uint8Array(maxRank + 1);
  const hint = /* @__PURE__ */ __name((v) => v < real && (nodes[v].kind === Kind.StartPort || nodes[v].kind === Kind.EndPort) ? nodes[v].hint : NaN, "hint");
  for (const r of [0, maxRank]) if (sortRank(r, hint)) fixed[r] = 1;
  const setPositions = /* @__PURE__ */ __name(() => {
    for (let r = 0; r <= maxRank; r++) {
      const s = layerStart[r];
      for (let i = s, e = layerStart[r + 1]; i < e; i++) pos[order[i]] = i - s;
    }
  }, "setPositions");
  setPositions();
  const g = {
    n,
    real,
    maxRank,
    W,
    KIND,
    RANK,
    EF,
    ET,
    EFD,
    ETD,
    succStart,
    succE,
    predStart,
    predE,
    layerStart,
    order,
    pos,
    offsets,
    fixed,
    GRP,
    groupParent: opt.groups?.parent
  };
  let crossings = 0;
  let declared = 0;
  if (segments > 0 && maxRank > 0) {
    [crossings, declared] = reduceCrossings(g, nodes);
    setPositions();
  }
  if (opt.orderOnly) {
    const at = position(g, opt);
    for (let i = 0; i < real; i++) nodes[i].x = at[i];
    for (let ei = 0; ei < m; ei++) {
      const e = edges[ei];
      const a = e.reversed ? e.head : e.tail;
      const b = e.reversed ? e.tail : e.head;
      const pts = [RANK[a], at[a]];
      if (!direct[ei] && firstDummy[ei] >= 0)
        for (let d = firstDummy[ei], end = d + span[ei] - 1; d < end; d++)
          pts.push(RANK[d], at[d]);
      pts.push(RANK[b], at[b]);
      e.points = pts;
    }
    return { width: 0, height: 0, crossings, declared };
  }
  if (EFK && ETK) spread(g, nodes, EFK, ETK);
  const xs = position(g, opt);
  const empty = emptyRanks(g);
  if (EFK && ETK) {
    const free = freeEnds(g, EFK, ETK);
    alignLabels(g, nodes, xs, free, opt, empty);
    settle(g, nodes, xs, EFK, ETK, free, empty);
    snap(g, xs, empty, opt);
    for (let ei = 0; ei < m; ei++) {
      if (direct[ei]) continue;
      const e = edges[ei];
      const aDx = EFD[firstSeg[ei]];
      const bDx = ETD[lastSeg[ei]];
      e.tailDx = e.reversed ? bDx : aDx;
      e.headDx = e.reversed ? aDx : bDx;
    }
  }
  alignPorts(g, xs, empty);
  const onLine = new Uint8Array(n);
  if (empty && !opt.tracks)
    straighten(g, xs, empty, firstDummy, span, opt.apart ? 0 : opt.edgeSep, onLine);
  if (!opt.tracks) pastLabels(g, xs, firstDummy, span, opt.edgeSep, onLine);
  const pieceStart = new Int32Array(m + 1);
  const pieces = opt.tracks || EFK && !opt.straight ? { from: [], to: [], rank: [], lower: [], track: [], levels: [], wide: [] } : void 0;
  const trackCount = new Int32Array(maxRank + 1);
  if (pieces) {
    for (let ei = 0; ei < m; ei++) {
      pieceStart[ei] = pieces.from.length;
      if (direct[ei]) continue;
      const d0 = firstDummy[ei];
      let twin = false;
      for (let d = d0, end = d0 < 0 ? d0 : d0 + span[ei] - 1; d < end; d++) {
        const bare = empty !== void 0 && empty[RANK[d]] === 1;
        if (!opt.tracks && bare !== (onLine[d] === 1)) twin = true;
      }
      if (twin) continue;
      let x = xs[EF[firstSeg[ei]]] + EFD[firstSeg[ei]];
      let rank2 = RANK[EF[firstSeg[ei]]];
      for (let d = d0, end = d0 < 0 ? d0 : d0 + span[ei] - 1; d < end; d++) {
        if (empty && empty[RANK[d]]) continue;
        pieces.from.push(x);
        pieces.to.push(xs[d]);
        pieces.rank.push(rank2);
        pieces.lower.push(d);
        x = xs[d];
        rank2 = RANK[d];
      }
      pieces.from.push(x);
      pieces.to.push(xs[ET[lastSeg[ei]]] + ETD[lastSeg[ei]]);
      pieces.rank.push(rank2);
      pieces.lower.push(-1);
    }
    pieceStart[m] = pieces.from.length;
  }
  const portOnly = /* @__PURE__ */ __name((r, kind) => {
    let found = false;
    for (let i = layerStart[r]; i < layerStart[r + 1]; i++) {
      const k = KIND[order[i]];
      if (k === kind) found = true;
      else if (k !== Kind.Dummy) return false;
    }
    return found;
  }, "portOnly");
  const startRanks = portOnly(0, Kind.StartPort) ? step : 0;
  const endRanks = portOnly(maxRank, Kind.EndPort) ? step : 0;
  const run2 = new Float64Array(maxRank + 1);
  for (let e = 0; e < segments; e++) {
    const across = Math.abs(xs[EF[e]] + EFD[e] - xs[ET[e]] - ETD[e]);
    if (across > run2[RANK[EF[e]]]) run2[RANK[EF[e]]] = across;
  }
  const bandTop = new Float64Array(maxRank + 1);
  const bandBottom = new Float64Array(maxRank + 1);
  const usual = /* @__PURE__ */ __name((r) => (r < startRanks || r >= maxRank - endRanks ? opt.portSep : opt.rankSep) / step, "usual");
  const gapUnder = new Float64Array(maxRank + 1);
  for (let r = 0; r < maxRank; r++) {
    gapUnder[r] = pieces ? usual(r) : Math.max(usual(r), Math.min(MAX_GAP * opt.rankSep / step, run2[r] * MIN_SLOPE));
  }
  const between = new Uint8Array(maxRank + 1).fill(1);
  for (let i = 0; i < real; i++) between[RANK[i]] = 0;
  for (let r = 1; r < maxRank; r++) {
    if (opt.tracks || !between[r] || heads[r] !== 1 && heads[r] !== 2) continue;
    const shift = Math.min((opt.headRoom ?? 0) / 2, gapUnder[heads[r] === 1 ? r - 1 : r] / 2);
    gapUnder[r - 1] += heads[r] === 1 ? -shift : shift;
    gapUnder[r] += heads[r] === 1 ? shift : -shift;
  }
  const inset = /* @__PURE__ */ __name((d) => KIND[d] === Kind.Dummy && between[RANK[d]] && !opt.tracks ? (bandBottom[RANK[d]] - bandTop[RANK[d]]) / 4 : 0, "inset");
  const margin = opt.tracks ? TRACK_MARGIN : LEVEL_MARGIN;
  const leastPitch = opt.tracks ? TRACK_PITCH : LEVEL_PITCH;
  const mostPitch = opt.tracks ? TRACK_SPREAD : LEVEL_PITCH;
  const below = new Int32Array(maxRank + 1);
  if (pieces) {
    const room = new Float64Array(maxRank + 1);
    for (let r = 0; r < maxRank; r++) {
      if (empty && empty[r]) continue;
      let next = r + 1;
      room[r] = gapUnder[r];
      while (next < maxRank && empty && empty[next]) room[r] += gapUnder[next++];
      below[r] = next;
    }
    for (let k = 0; k < pieces.from.length; k++)
      pieces.wide.push(
        Math.abs(pieces.from[k] - pieces.to[k]) > LEVEL_WIDE * room[pieces.rank[k]] ? 1 : 0
      );
    const tall = new Float64Array(maxRank + 1);
    assignTracks(pieces, trackCount, !opt.tracks, room, tall);
    for (let r = 0; r < maxRank; r++) {
      if (trackCount[r] > 0)
        gapUnder[r] += Math.max(0, 2 * margin + (trackCount[r] - 1) * leastPitch - room[r]);
      else if (tall[r] > 0)
        gapUnder[r] += Math.max(0, Math.min(MAX_GAP * opt.rankSep, tall[r]) - room[r]);
    }
  }
  let y = 0;
  for (let r = 0; r <= maxRank; r++) {
    let h = 0;
    for (let i = layerStart[r]; i < layerStart[r + 1]; i++)
      if (H[order[i]] > h) h = H[order[i]];
    bandTop[r] = y;
    bandBottom[r] = y + h;
    y += h + gapUnder[r];
  }
  const height = y;
  const trackY = /* @__PURE__ */ __name((piece, onTrack = pieces.track[piece]) => {
    const r = pieces.rank[piece];
    const top = bandBottom[r];
    const bottom = bandTop[below[r]];
    const count = opt.tracks ? trackCount[r] : pieces.levels[piece];
    const pitch = count > 1 ? Math.min(mostPitch, (bottom - top - 2 * margin) / (count - 1)) : 0;
    return (top + bottom) / 2 + (onTrack - (count - 1) / 2) * pitch;
  }, "trackY");
  let minX = Infinity;
  let maxX = -Infinity;
  for (let i = 0; i < n; i++) {
    const half = W[i] / 2;
    if (xs[i] - half < minX) minX = xs[i] - half;
    if (xs[i] + half > maxX) maxX = xs[i] + half;
  }
  const arrives = new Uint8Array(maxRank + 1);
  const leaves = new Uint8Array(maxRank + 1);
  for (let i = 0; i < real; i++) {
    if (KIND[i] !== Kind.Node || !EFK) continue;
    if (predStart[i + 1] > predStart[i]) arrives[RANK[i]] = 1;
    if (succStart[i + 1] > succStart[i]) leaves[RANK[i]] = 1;
  }
  for (let i = 0; i < real; i++) {
    const node = nodes[i];
    const r = node.rank;
    node.x = xs[i] - minX;
    if (KIND[i] === Kind.Node && leaves[r] && !arrives[r]) node.y = bandBottom[r] - node.h / 2;
    else if (KIND[i] === Kind.Node && arrives[r] && !leaves[r])
      node.y = bandTop[r] + node.h / 2;
    else node.y = (bandTop[r] + bandBottom[r]) / 2;
  }
  for (let ei = 0; ei < m; ei++) {
    const e = edges[ei];
    const first = nodes[e.reversed ? e.head : e.tail];
    const last = nodes[e.reversed ? e.tail : e.head];
    const pts = [first.x + (e.reversed ? e.headDx : e.tailDx), first.y + first.h / 2];
    const d0 = firstDummy[ei];
    if (pieces && pieceStart[ei + 1] > pieceStart[ei]) {
      for (let k = pieceStart[ei]; k < pieceStart[ei + 1]; k++) {
        if (pieces.track[k] >= 0 && (opt.tracks || pieces.wide[k] === 1)) {
          const across = trackY(k);
          pts.push(pieces.from[k] - minX, across, pieces.to[k] - minX, across);
        } else if (pieces.track[k] > 0) {
          pts.push(pieces.from[k] - minX, trackY(k, pieces.track[k] - 1));
        }
        const d = pieces.lower[k];
        if (d < 0) continue;
        pts.push(xs[d] - minX, bandTop[RANK[d]] + inset(d));
        if (bandBottom[RANK[d]] > bandTop[RANK[d]])
          pts.push(xs[d] - minX, bandBottom[RANK[d]] - inset(d));
      }
    } else if (d0 >= 0) {
      for (let d = d0, end = d0 + span[ei] - 1; d < end; d++) {
        if (onLine[d]) continue;
        const x = xs[d] - minX;
        const top = bandTop[RANK[d]];
        const bottom = bandBottom[RANK[d]];
        pts.push(x, top + inset(d));
        if (bottom > top) pts.push(x, bottom - inset(d));
      }
    }
    pts.push(last.x + (e.reversed ? e.tailDx : e.headDx), last.y - last.h / 2);
    if (e.reversed) {
      for (let i = 0, j = pts.length - 2; i < j; i += 2, j -= 2) {
        const tx = pts[i];
        const ty = pts[i + 1];
        pts[i] = pts[j];
        pts[i + 1] = pts[j + 1];
        pts[j] = tx;
        pts[j + 1] = ty;
      }
    }
    e.points = pts;
    const ln = labelNode[ei];
    if (ln >= 0) {
      e.labelX = xs[ln] - minX;
      e.labelY = (bandTop[RANK[ln]] + bandBottom[RANK[ln]]) / 2;
    } else if (e.labelW > 0) {
      e.labelX = (pts[0] + pts[pts.length - 2]) / 2;
      e.labelY = (pts[1] + pts[pts.length - 1]) / 2;
    }
  }
  return { width: maxX - minX, height };
}
__name(layered, "layered");
function orient(nodes, edges) {
  const n = nodes.length;
  const m = edges.length;
  const start = new Int32Array(n + 1);
  for (let i = 0; i < m; i++) {
    const e = edges[i];
    e.reversed = nodes[e.head].kind === Kind.StartPort || nodes[e.tail].kind === Kind.EndPort;
    if (!e.reversed) start[e.tail + 1]++;
  }
  for (let i = 0; i < n; i++) start[i + 1] += start[i];
  const out = new Int32Array(start[n]);
  {
    const fill = start.slice(0, n);
    for (let i = 0; i < m; i++) if (!edges[i].reversed) out[fill[edges[i].tail]++] = i;
  }
  const state = new Uint8Array(n);
  const cursor = start.slice(0, n);
  const stack = [];
  for (let root = 0; root < n; root++) {
    if (state[root] !== 0) continue;
    stack.push(root);
    state[root] = 1;
    while (stack.length > 0) {
      const v = stack[stack.length - 1];
      if (cursor[v] < start[v + 1]) {
        const e = edges[out[cursor[v]++]];
        const w = e.head;
        if (state[w] === 1) e.reversed = true;
        else if (state[w] === 0) {
          state[w] = 1;
          stack.push(w);
        }
      } else {
        state[v] = 2;
        stack.pop();
      }
    }
  }
}
__name(orient, "orient");
function rank(nodes, edges, step) {
  const n = nodes.length;
  const m = edges.length;
  const from = new Int32Array(m);
  const to = new Int32Array(m);
  const len = new Int32Array(m);
  const outStart = new Int32Array(n + 1);
  const inStart = new Int32Array(n + 1);
  for (let i = 0; i < m; i++) {
    const e = edges[i];
    const a = e.reversed ? e.head : e.tail;
    const b = e.reversed ? e.tail : e.head;
    from[i] = a;
    to[i] = b;
    len[i] = Math.max(1, e.minlen) * step;
    outStart[a + 1]++;
    inStart[b + 1]++;
  }
  for (let i = 0; i < n; i++) {
    outStart[i + 1] += outStart[i];
    inStart[i + 1] += inStart[i];
  }
  const outE = new Int32Array(m);
  const inE = new Int32Array(m);
  {
    const of = outStart.slice(0, n);
    const inf = inStart.slice(0, n);
    for (let i = 0; i < m; i++) {
      outE[of[from[i]]++] = i;
      inE[inf[to[i]]++] = i;
    }
  }
  const r = new Int32Array(n);
  for (let i = 0; i < n; i++) if (nodes[i].kind === Kind.StartPort) r[i] = -step;
  const indeg = new Int32Array(n);
  for (let i = 0; i < n; i++) indeg[i] = inStart[i + 1] - inStart[i];
  const topo = new Int32Array(n);
  let count = 0;
  for (let i = 0; i < n; i++) if (indeg[i] === 0) topo[count++] = i;
  for (let q = 0; q < count; q++) {
    const v = topo[q];
    for (let k = outStart[v]; k < outStart[v + 1]; k++) {
      const ei = outE[k];
      const w = to[ei];
      if (r[v] + len[ei] > r[w]) r[w] = r[v] + len[ei];
      if (--indeg[w] === 0) topo[count++] = w;
    }
  }
  for (let pass = 0; pass < 8; pass++) {
    let changed = false;
    for (let q = count - 1; q >= 0; q--) {
      const v = topo[q];
      const ins = inStart[v + 1] - inStart[v];
      const outs = outStart[v + 1] - outStart[v];
      if (ins === 0 && outs === 0) continue;
      let lo = -Infinity;
      let hi = Infinity;
      for (let k = inStart[v]; k < inStart[v + 1]; k++) {
        const ei = inE[k];
        lo = Math.max(lo, r[from[ei]] + len[ei]);
      }
      for (let k = outStart[v]; k < outStart[v + 1]; k++) {
        const ei = outE[k];
        hi = Math.min(hi, r[to[ei]] - len[ei]);
      }
      let next = r[v];
      if (outs > ins && hi !== Infinity) next = hi;
      else if (ins > outs && lo !== -Infinity) next = lo;
      if (next !== r[v]) {
        r[v] = next;
        changed = true;
      }
    }
    if (!changed) break;
  }
  let min = Infinity;
  let max = -Infinity;
  let startPorts = false;
  for (let i = 0; i < n; i++) {
    const kind = nodes[i].kind;
    if (kind === Kind.StartPort) startPorts = true;
    if (kind === Kind.StartPort || kind === Kind.EndPort) continue;
    if (r[i] < min) min = r[i];
    if (r[i] > max) max = r[i];
  }
  if (min === Infinity) {
    min = 0;
    max = 0;
  }
  for (let i = 0; i < n; i++) {
    if (nodes[i].kind === Kind.StartPort) r[i] = min - step;
    else if (nodes[i].kind === Kind.EndPort) r[i] = max + step;
  }
  if (startPorts) min -= step;
  for (let i = 0; i < n; i++) nodes[i].rank = r[i] - min;
}
__name(rank, "rank");
function sideEnds(g, v, side, span, kinds, ids, room) {
  const start = side === 0 ? g.predStart : g.succStart;
  const list = side === 0 ? g.predE : g.succE;
  const other = side === 0 ? g.EF : g.ET;
  const pos = g.pos;
  for (let k = start[v]; k < start[v + 1]; k++)
    if (kinds[list[k]] !== End.Held) ids.push(list[k]);
  if (ids.length < 2) return 0;
  ids.sort((a, b) => pos[other[a]] - pos[other[b]] || a - b);
  const fill = /* @__PURE__ */ __name((share) => {
    let total2 = 0;
    room[0] = 0;
    for (let k = 1; k < ids.length; k++) {
      const same = kinds[ids[k]] === kinds[ids[k - 1]];
      room[k] = share(same && kinds[ids[k]] === End.Leaves, same);
      total2 += room[k];
    }
    return total2;
  }, "fill");
  let total = fill(() => 1);
  if (span / total < MIN_PITCH) total = fill((leaves) => leaves ? 0.5 : 1);
  if (span / total < MIN_PITCH) total = fill((_leaves, same) => same ? 0 : 1);
  if (total === 0) return 0;
  const pitch = Math.min(PORT_PITCH, span / total);
  for (let k = 1; k < ids.length; k++) room[k] *= pitch;
  return total * pitch;
}
__name(sideEnds, "sideEnds");
function spread(g, nodes, EFK, ETK) {
  const { real, W, EFD, ETD } = g;
  for (let v = 0; v < real; v++) {
    const span = Math.min(nodes[v].span, W[v]);
    if (span <= 0 || nodes[v].kind !== Kind.Node) continue;
    for (let side = 0; side < 2; side++) {
      const ids = [];
      const room = [];
      const total = sideEnds(g, v, side, span, side === 0 ? ETK : EFK, ids, room);
      if (total === 0) continue;
      const dx = side === 0 ? ETD : EFD;
      let at = -total / 2;
      for (let k = 0; k < ids.length; k++) {
        at += room[k];
        dx[ids[k]] = at;
      }
    }
  }
}
__name(spread, "spread");
function follow(g, empty, e, side) {
  if (!empty) return e;
  const { KIND, RANK, EF, ET, succStart, succE, predStart, predE } = g;
  for (let hops = 0; hops < 1e5; hops++) {
    const u = side === 0 ? EF[e] : ET[e];
    if (KIND[u] !== Kind.Dummy || !empty[RANK[u]]) break;
    e = side === 0 ? predE[predStart[u]] : succE[succStart[u]];
  }
  return e;
}
__name(follow, "follow");
function alignPorts(g, xs, empty) {
  const { maxRank, KIND, EF, ET, EFD, ETD, succStart, succE, predStart, predE, layerStart, order } = g;
  for (const [r, kind] of [
    [0, Kind.StartPort],
    [maxRank, Kind.EndPort]
  ]) {
    const s = layerStart[r];
    const end = layerStart[r + 1];
    const to = [];
    for (let i = s; i < end; i++) {
      const v = order[i];
      const start = kind === Kind.StartPort;
      if (KIND[v] !== kind || (start ? succStart[v + 1] - succStart[v] : predStart[v + 1] - predStart[v]) !== 1)
        break;
      const e = follow(
        g,
        empty,
        start ? succE[succStart[v]] : predE[predStart[v]],
        start ? 1 : 0
      );
      const at = start ? xs[ET[e]] + ETD[e] : xs[EF[e]] + EFD[e];
      if (to.length > 0 && at < to[to.length - 1] + TWIN) break;
      to.push(at);
    }
    if (to.length === 0 || to.length !== end - s) continue;
    for (let i = s; i < end; i++) xs[order[i]] = to[i - s];
  }
}
__name(alignPorts, "alignPorts");
function freeEnds(g, EFK, ETK) {
  const free = [new Int32Array(g.n), new Int32Array(g.n)];
  for (let e = 0; e < g.EF.length; e++) {
    if (ETK[e] !== End.Held) free[0][g.ET[e]]++;
    if (EFK[e] !== End.Held) free[1][g.EF[e]]++;
  }
  return free;
}
__name(freeEnds, "freeEnds");
function alignLabels(g, nodes, xs, free, opt, empty) {
  const sep = opt.edgeSep;
  const {
    n,
    real,
    maxRank,
    KIND,
    RANK,
    W,
    EF,
    ET,
    EFD,
    ETD,
    succStart,
    succE,
    predStart,
    predE,
    layerStart,
    order,
    pos
  } = g;
  const placed = /* @__PURE__ */ __name((v) => KIND[v] === Kind.Label || KIND[v] === Kind.Dummy && !(empty !== void 0 && empty[RANK[v]] === 1), "placed");
  const end = /* @__PURE__ */ __name((e, side) => {
    const u = side === 0 ? EF[e] : ET[e];
    const x = side === 0 ? xs[u] + EFD[e] : xs[u] + ETD[e];
    return [x, u < real && nodes[u].kind === Kind.Node ? free[1 - side][u] : 0];
  }, "end");
  const room = /* @__PURE__ */ __name((v) => {
    const s = layerStart[RANK[v]];
    const i = s + pos[v];
    const clear = /* @__PURE__ */ __name((other) => W[other] / 2 + W[v] / 2 + gapBetween(KIND[other], KIND[v], opt.nodeSep, sep), "clear");
    return [
      i > s ? xs[order[i - 1]] + clear(order[i - 1]) : -Infinity,
      i + 1 < layerStart[RANK[v] + 1] ? xs[order[i + 1]] - clear(order[i + 1]) : Infinity
    ];
  }, "room");
  const choose = /* @__PURE__ */ __name((x, up, down, lo, hi) => {
    const upFirst = up[1] !== down[1] ? up[1] < down[1] : Math.abs(up[0] - x) <= Math.abs(down[0] - x);
    const choices = upFirst ? [up[0], down[0]] : [down[0], up[0]];
    return choices.find((choice) => choice >= lo && choice <= hi) ?? Math.max(lo, Math.min(hi, choices[0]));
  }, "choose");
  const done = new Uint8Array(n);
  const chain = [];
  for (let r = 1; r < maxRank; r++) {
    for (let i = layerStart[r]; i < layerStart[r + 1]; i++) {
      if (!placed(order[i]) || done[order[i]]) continue;
      let top = order[i];
      while (isDummy(KIND[EF[predE[predStart[top]]]])) top = EF[predE[predStart[top]]];
      let bottom = top;
      let lo = -Infinity;
      let hi = Infinity;
      chain.length = 0;
      for (let d = top; isDummy(KIND[d]); d = ET[succE[succStart[d]]]) {
        bottom = d;
        if (!placed(d)) continue;
        done[d] = 1;
        chain.push(d);
        const [least, most] = room(d);
        if (least > lo) lo = least;
        if (most < hi) hi = most;
      }
      if (lo <= hi) {
        const x = choose(
          xs[chain[0]],
          end(predE[predStart[top]], 0),
          end(succE[succStart[bottom]], 1),
          lo,
          hi
        );
        for (const d of chain) xs[d] = x;
        continue;
      }
      for (const d of chain) {
        const [least, most] = room(d);
        if (least > most) continue;
        xs[d] = choose(
          xs[d],
          end(follow(g, empty, predE[predStart[d]], 0), 0),
          end(follow(g, empty, succE[succStart[d]], 1), 1),
          least,
          most
        );
      }
    }
  }
}
__name(alignLabels, "alignLabels");
function settle(g, nodes, xs, EFK, ETK, free, empty) {
  const { real, W, EF, ET, EFD, ETD, succStart, succE, predStart, predE, pos } = g;
  const wanted = /* @__PURE__ */ __name((e, side, v, span, again) => {
    if (free[side][v] < 2) return 0;
    e = follow(g, empty, e, side);
    const u = side === 0 ? EF[e] : ET[e];
    const point = side === 0 ? xs[u] + EFD[e] : xs[u] + ETD[e];
    if (again && Math.abs(point - xs[v]) <= span / 2 + IN_LINE)
      return Math.max(-span / 2, Math.min(span / 2, point - xs[v]));
    let middle = point;
    let width = 0;
    if (u < real && nodes[u].kind === Kind.Node && (side === 0 ? EFK : ETK)[e] !== End.Held && free[1 - side][u] >= 2) {
      width = Math.max(0, Math.min(nodes[u].span, W[u]));
      if (width > 0) middle = xs[u];
    }
    const lo = Math.max(xs[v] - span / 2, middle - width / 2);
    const hi = Math.min(xs[v] + span / 2, middle + width / 2);
    if (lo > hi + IN_LINE) {
      const lean = Math.max(0, span / 2 - LEAN_CLEAR);
      return Math.max(-lean, Math.min(lean, point - xs[v]));
    }
    const place = (xs[v] * width + middle * span) / (width + span);
    return Math.max(lo, Math.min(hi, place)) - xs[v];
  }, "wanted");
  const sides = [];
  for (let v = 0; v < real; v++) {
    const span = Math.min(nodes[v].span, W[v]);
    if (span <= 0 || nodes[v].kind !== Kind.Node) continue;
    for (let side = 0; side < 2; side++) {
      const other = side === 0 ? EF : ET;
      const start = side === 0 ? predStart : succStart;
      const list = side === 0 ? predE : succE;
      const ids = [];
      const room = [];
      sideEnds(g, v, side, span, side === 0 ? ETK : EFK, ids, room);
      if (ids.length === 0) continue;
      if (ids.length === 1) room[0] = 0;
      const all = [];
      for (let k = start[v]; k < start[v + 1]; k++) all.push(list[k]);
      all.sort((a, b) => pos[other[a]] - pos[other[b]] || a - b);
      sides.push({ v, side, span, ids, room, all });
    }
  }
  for (let pass = 0, moved = true; moved && pass < 6; pass++) {
    moved = false;
    for (const { v, side, span, ids, room, all } of sides) {
      const kinds = side === 0 ? ETK : EFK;
      const dx = side === 0 ? ETD : EFD;
      let k = 0;
      let lo = -span / 2;
      for (let i = 0; i <= all.length; i++) {
        const held = i < all.length && kinds[all[i]] === End.Held;
        if (i < all.length && !held) continue;
        let size2 = 0;
        for (let j = i - 1; j >= 0 && kinds[all[j]] !== End.Held; j--) size2++;
        const hi = held ? dx[all[i]] - PORT_PITCH : span / 2;
        if (size2 > 0) {
          const sum = [];
          const count = [];
          let before = 0;
          for (let j2 = 0; j2 < size2; j2++) {
            if (j2 > 0) before += room[k + j2];
            sum.push(wanted(ids[k + j2], side, v, span, pass > 0) - before);
            count.push(1);
            let together = j2 > 0 && room[k + j2] === 0;
            while (sum.length > 1 && (together || sum[sum.length - 2] / count[count.length - 2] > sum[sum.length - 1] / count[count.length - 1])) {
              together = false;
              const top = sum.pop();
              const pooled = count.pop();
              sum[sum.length - 1] += top;
              count[count.length - 1] += pooled;
            }
          }
          const total = before;
          let j = 0;
          before = 0;
          for (let b = 0; b < sum.length; b++) {
            const level = hi - total < lo ? (lo + hi - total) / 2 : Math.max(lo, Math.min(hi - total, sum[b] / count[b]));
            for (let c = 0; c < count[b]; c++, j++) {
              if (j > 0) before += room[k + j];
              if (Math.abs(dx[ids[k + j]] - level - before) > 0.01) moved = true;
              dx[ids[k + j]] = level + before;
            }
          }
          k += size2;
        }
        if (held) lo = dx[all[i]] + PORT_PITCH;
      }
    }
  }
}
__name(settle, "settle");
function snap(g, xs, empty, opt) {
  const { n, KIND, RANK, EF, ET, EFD, ETD, layerStart, order, pos } = g;
  const passed = /* @__PURE__ */ __name((u) => empty !== void 0 && KIND[u] === Kind.Dummy && empty[RANK[u]] === 1, "passed");
  const a = [];
  const b = [];
  const da = [];
  const db = [];
  for (let e = 0; e < EF.length; e++) {
    if (passed(EF[e])) continue;
    const f = follow(g, empty, e, 1);
    a.push(EF[e]);
    b.push(ET[f]);
    da.push(EFD[e]);
    db.push(ETD[f]);
  }
  const off = /* @__PURE__ */ __name((k) => xs[b[k]] + db[k] - xs[a[k]] - da[k], "off");
  const block = new Int32Array(n);
  const members = [];
  for (let i = 0; i < n; i++) {
    block[i] = i;
    members.push([i]);
  }
  const join = /* @__PURE__ */ __name((x, y) => {
    let keep = block[x];
    let drop = block[y];
    if (keep === drop) return;
    if (members[keep].length < members[drop].length) [keep, drop] = [drop, keep];
    for (const v of members[drop]) {
      block[v] = keep;
      members[keep].push(v);
    }
    members[drop] = [];
  }, "join");
  const near = [];
  for (let k = 0; k < a.length; k++) {
    const d = Math.abs(off(k));
    if (d < 0.01) join(a[k], b[k]);
    else if (d <= BEND_SNAP) near.push(k);
  }
  if (near.length === 0) return;
  near.sort((x, y) => Math.abs(off(x)) - Math.abs(off(y)) || x - y);
  const gap = /* @__PURE__ */ __name((v) => halfRoom(g, opt, v), "gap");
  const free = /* @__PURE__ */ __name((id, shift) => {
    for (const v of members[id]) {
      const s = layerStart[RANK[v]];
      const end = layerStart[RANK[v] + 1];
      const i = s + pos[v];
      if (i > s && block[order[i - 1]] !== id && xs[v] + shift - xs[order[i - 1]] < gap(v) + gap(order[i - 1]) - 0.01)
        return false;
      if (i + 1 < end && block[order[i + 1]] !== id && xs[order[i + 1]] - xs[v] - shift < gap(v) + gap(order[i + 1]) - 0.01)
        return false;
    }
    return true;
  }, "free");
  for (const k of near) {
    const d = off(k);
    if (Math.abs(d) < 0.01) {
      join(a[k], b[k]);
      continue;
    }
    if (Math.abs(d) > BEND_SNAP || block[a[k]] === block[b[k]]) continue;
    const upper = block[a[k]];
    const lower = block[b[k]];
    const first = members[upper].length <= members[lower].length ? upper : lower;
    for (const id of [first, first === upper ? lower : upper]) {
      const shift = id === upper ? d : -d;
      if (Math.abs(d) > SNAP && !members[id].every((v) => KIND[v] === Kind.Dummy)) continue;
      if (!free(id, shift)) continue;
      for (const v of members[id]) xs[v] += shift;
      join(a[k], b[k]);
      break;
    }
  }
}
__name(snap, "snap");
function emptyRanks(g) {
  const { maxRank, KIND, layerStart, order } = g;
  const empty = new Uint8Array(maxRank + 1);
  let any = false;
  for (let r = 1; r < maxRank; r++) {
    let only = layerStart[r + 1] > layerStart[r];
    for (let i = layerStart[r]; only && i < layerStart[r + 1]; i++)
      if (KIND[order[i]] !== Kind.Dummy) only = false;
    if (only) {
      empty[r] = 1;
      any = true;
    }
  }
  return any ? empty : void 0;
}
__name(emptyRanks, "emptyRanks");
function assignTracks(pieces, trackCount, curved, room, tall) {
  const { from, to, rank: rank2, track, levels, wide } = pieces;
  const total = from.length;
  const byRank = /* @__PURE__ */ new Map();
  for (let k = 0; k < total; k++) {
    track.push(-1);
    levels.push(0);
    if (Math.abs(from[k] - to[k]) < IN_LINE) continue;
    const list = byRank.get(rank2[k]);
    if (list) list.push(k);
    else byRank.set(rank2[k], [k]);
  }
  if (byRank.size === 0) return;
  const LO = new Float64Array(total);
  const HI = new Float64Array(total);
  for (let k = 0; k < total; k++) {
    LO[k] = Math.min(from[k], to[k]);
    HI[k] = Math.max(from[k], to[k]);
  }
  const within = /* @__PURE__ */ __name((x, k) => x >= LO[k] - IN_LINE && x <= HI[k] + IN_LINE ? 1 : 0, "within");
  const mates = /* @__PURE__ */ __name((a, b) => Math.abs(from[a] - from[b]) < IN_LINE || Math.abs(to[a] - to[b]) < IN_LINE, "mates");
  const overlap = /* @__PURE__ */ __name((a, b) => LO[a] < HI[b] - IN_LINE && LO[b] < HI[a] - IN_LINE, "overlap");
  const clash = /* @__PURE__ */ __name((a, b) => overlap(a, b) && !mates(a, b), "clash");
  const meet = /* @__PURE__ */ __name((a, b) => overlap(a, b) || within(to[a], b) + within(from[b], a) + within(to[b], a) + within(from[a], b) > 0, "meet");
  const crossings = /* @__PURE__ */ __name((a, b) => within(to[a], b) + within(from[b], a), "crossings");
  const nearPairs = /* @__PURE__ */ __name((list) => {
    const byLo = list.map((_, i) => i).sort((a, b) => LO[list[a]] - LO[list[b]]);
    const pairs = [];
    for (let x = 0; x < byLo.length; x++) {
      const i = byLo[x];
      const reach = HI[list[i]] + 4 * IN_LINE;
      for (let y = x + 1; y < byLo.length && LO[list[byLo[y]]] <= reach; y++) {
        const j = byLo[y];
        pairs.push(Math.min(i, j), Math.max(i, j));
      }
    }
    return pairs;
  }, "nearPairs");
  const lay = /* @__PURE__ */ __name((list) => {
    list.sort((a, b) => HI[b] - LO[b] - (HI[a] - LO[a]) || LO[a] - LO[b] || a - b);
    const count = list.length;
    const above = [];
    const group = list.map((_, i) => i);
    const find = /* @__PURE__ */ __name((i) => {
      while (group[i] !== i) i = group[i] = group[group[i]];
      return i;
    }, "find");
    const weighed = count <= MAX_WEIGHED;
    const pairs = weighed ? nearPairs(list) : [];
    const clashes = weighed ? list.map(() => []) : [];
    for (let p = 0; p < pairs.length; p += 2) {
      const i = pairs[p];
      const j = pairs[p + 1];
      if (!clash(list[i], list[j])) continue;
      clashes[i].push(j);
      clashes[j].push(i);
    }
    let sequence = list.map((_, i) => i);
    if (weighed) {
      const waiting = new Int32Array(count);
      const after = [];
      for (let i = 0; i < count; i++) {
        above.push([]);
        after.push([]);
      }
      for (let p = 0; p < pairs.length; p += 2) {
        const i = pairs[p];
        const j = pairs[p + 1];
        const a = list[i];
        const b = list[j];
        if (!meet(a, b)) continue;
        group[find(i)] = find(j);
        const ab = crossings(a, b);
        const ba = crossings(b, a);
        if (ab === ba) continue;
        const first2 = ab < ba ? i : j;
        const second = ab < ba ? j : i;
        above[second].push(first2);
        after[first2].push(second);
        waiting[second]++;
      }
      const placed = new Uint8Array(count);
      sequence = [];
      for (let done = 0; done < count; done++) {
        let pick = -1;
        for (let i = 0; i < count; i++) {
          if (placed[i]) continue;
          if (pick < 0 || waiting[i] < waiting[pick]) pick = i;
          if (waiting[i] === 0) break;
        }
        placed[pick] = 1;
        sequence.push(pick);
        for (const j of after[pick]) waiting[j]--;
      }
    }
    const taken = /* @__PURE__ */ new Set();
    const onTrack = [];
    let rows = 0;
    for (const at of sequence) {
      const k = list[at];
      let t = 0;
      for (const i of above[at] ?? []) if (track[list[i]] >= t) t = track[list[i]] + 1;
      if (weighed) {
        taken.clear();
        for (const i of clashes[at]) taken.add(track[list[i]]);
        while (taken.has(t)) t++;
      } else {
        while (onTrack[t]?.some((other) => clash(k, other))) t++;
        (onTrack[t] ??= []).push(k);
      }
      track[k] = t;
      if (t >= rows) rows = t + 1;
    }
    const first = new Int32Array(count).fill(rows);
    const last = new Int32Array(count).fill(-1);
    for (let i = 0; i < count; i++) {
      const root = find(i);
      first[root] = Math.min(first[root], track[list[i]]);
      last[root] = Math.max(last[root], track[list[i]]);
    }
    for (let i = 0; i < count; i++) {
      const root = find(i);
      levels[list[i]] = last[root] - first[root] + 1;
      if (curved) track[list[i]] -= first[root];
    }
    return rows;
  }, "lay");
  const sample = /* @__PURE__ */ __name((k, h, out) => {
    const c = ease(to[k] - from[k], h);
    for (let i = 0; i <= SAMPLES; i++) {
      const t = i / SAMPLES;
      const u = 1 - t;
      out[2 * i] = from[k] + (to[k] - from[k]) * t * t * (3 - 2 * t);
      out[2 * i + 1] = h * (3 * c * t * u * u + 3 * (1 - c) * t * t * u + t * t * t);
    }
  }, "sample");
  const reaches = /* @__PURE__ */ __name((points, line, limit) => {
    const bound = limit * limit * (1 + 1e-9);
    for (let i = 0; i <= SAMPLES; i++) {
      const px = points[2 * i];
      const py = points[2 * i + 1];
      for (let j = 0; j < SAMPLES; j++) {
        const dx = line[2 * j + 2] - line[2 * j];
        const dy = line[2 * j + 3] - line[2 * j + 1];
        const t = Math.max(
          0,
          Math.min(
            1,
            ((px - line[2 * j]) * dx + (py - line[2 * j + 1]) * dy) / (dx * dx + dy * dy || 1)
          )
        );
        const ex = px - line[2 * j] - t * dx;
        const ey = py - line[2 * j + 1] - t * dy;
        if (ex * ex + ey * ey < bound && Math.hypot(ex, ey) < limit) return true;
      }
    }
    return false;
  }, "reaches");
  const near = /* @__PURE__ */ __name((a, b, height, limit) => {
    const h = Math.max(height / 2, height - 2 * LEVEL_LEAD);
    sample(a, h, LINE_A);
    sample(b, h, LINE_B);
    return reaches(LINE_A, LINE_B, limit) || reaches(LINE_B, LINE_A, limit);
  }, "near");
  for (const [r, all] of byRank) {
    if (!curved) {
      trackCount[r] = lay(all);
      continue;
    }
    if (all.length > MAX_WEIGHED) continue;
    const far = all.filter((k) => wide[k] === 1);
    lay(far);
    const level = new Set(far.filter((k) => levels[k] > 1));
    const pairs = nearPairs(all);
    for (let p = 0; p < pairs.length; p += 2) {
      const a = all[pairs[p]];
      const b = all[pairs[p + 1]];
      if (level.has(a) && level.has(b) || !clash(a, b) || from[a] < to[a] !== from[b] < to[b])
        continue;
      if (near(a, b, room[r], wide[a] === 1 || wide[b] === 1 ? LEVEL_CLEAR : LEVEL_TOUCH))
        level.add(a).add(b);
    }
    for (const k of far) {
      track[k] = -1;
      levels[k] = 0;
    }
    if (level.size === 0) continue;
    let crossing = 0;
    let alongside = 0;
    const beside = /* @__PURE__ */ new Set();
    for (let p = 0; p < pairs.length; p += 2) {
      const a = all[pairs[p]];
      const b = all[pairs[p + 1]];
      if (level.has(a) && level.has(b)) {
        if (!overlap(a, b)) continue;
        if (from[a] < to[a] !== from[b] < to[b]) crossing++;
        else if (!mates(a, b)) alongside++;
      } else if ((level.has(a) || level.has(b)) && meet(a, b)) beside.add(a).add(b);
    }
    if (crossing > alongside) {
      for (const k of all)
        if ((HI[k] - LO[k]) * CROSSED_SLOPE > tall[r])
          tall[r] = (HI[k] - LO[k]) * CROSSED_SLOPE;
      continue;
    }
    const members = all.filter((k) => level.has(k) || wide[k] !== 1 && beside.has(k));
    lay(members);
    let most = 0;
    for (const k of members) if (levels[k] > most) most = levels[k];
    trackCount[r] = most;
  }
}
__name(assignTracks, "assignTracks");
function straighten(g, xs, empty, firstDummy, span, sep, onLine) {
  const { maxRank, EF, ET, EFD, ETD, succStart, succE, predStart, predE, layerStart, order } = g;
  const want = new Float64Array(xs.length);
  const from = new Float64Array(xs.length);
  const to = new Float64Array(xs.length);
  for (let ei = 0; ei < firstDummy.length; ei++) {
    const d0 = firstDummy[ei];
    if (d0 < 0) continue;
    const end = d0 + span[ei] - 1;
    const base = g.RANK[d0];
    for (let d = d0; d < end; d++) {
      if (!empty[base + d - d0]) continue;
      let last = d;
      while (last + 1 < end && empty[base + last + 1 - d0]) last++;
      const above = predE[predStart[d]];
      const below = succE[succStart[last]];
      const x0 = xs[EF[above]] + EFD[above];
      const x1 = xs[ET[below]] + ETD[below];
      const steps = last - d + 2;
      for (let k = d; k <= last; k++) {
        want[k] = x0 + (x1 - x0) * (k - d + 1) / steps;
        from[k] = x0;
        to[k] = x1;
      }
      d = last;
    }
  }
  const twins = [];
  for (let r = 1; r < maxRank; r++) {
    if (!empty[r]) continue;
    const s = layerStart[r];
    const end = layerStart[r + 1];
    const row = Array.from(order.subarray(s, end)).sort(
      (a, b) => from[a] - from[b] || to[a] - to[b] || a - b
    );
    for (let i = 0; i < row.length; ) {
      twins.length = 0;
      let j = i;
      for (; j < row.length && Math.abs(from[row[j]] - from[row[i]]) < TWIN && Math.abs(to[row[j]] - to[row[i]]) < TWIN; j++)
        twins.push(row[j]);
      twins.sort((a, b) => g.pos[a] - g.pos[b]);
      for (let k = 0; k < twins.length; k++) {
        const d = twins[k];
        xs[d] = want[d] + (k - (twins.length - 1) / 2) * sep;
        if (twins.length === 1 || sep === 0) onLine[d] = 1;
      }
      i = j;
    }
  }
}
__name(straighten, "straighten");
function pastLabels(g, xs, firstDummy, span, clear, onLine) {
  const {
    maxRank,
    W,
    KIND,
    RANK,
    EF,
    ET,
    EFD,
    ETD,
    succStart,
    succE,
    predStart,
    predE,
    layerStart,
    order
  } = g;
  const labelled = new Uint8Array(maxRank + 1);
  let any = false;
  for (let r = 1; r < maxRank; r++) {
    let labels = false;
    let others = false;
    for (let i = layerStart[r]; i < layerStart[r + 1]; i++) {
      const kind = KIND[order[i]];
      if (kind === Kind.Label) labels = true;
      else if (kind !== Kind.Dummy) others = true;
    }
    if (labels && !others) {
      labelled[r] = 1;
      any = true;
    }
  }
  if (!any) return;
  for (let ei = 0; ei < firstDummy.length; ei++) {
    const d0 = firstDummy[ei];
    if (d0 < 0) continue;
    for (let d = d0, end = d0 + span[ei] - 1; d < end; d++) {
      if (KIND[d] !== Kind.Dummy || !labelled[RANK[d]]) continue;
      let first = d;
      let last = d;
      while (first > d0 && onLine[first - 1]) first--;
      while (last + 1 < end && onLine[last + 1]) last++;
      const above = predE[predStart[first]];
      const below = succE[succStart[last]];
      const from = xs[EF[above]] + EFD[above];
      const to = xs[ET[below]] + ETD[below];
      const lo = Math.min(from, to) - clear;
      const hi = Math.max(from, to) + clear;
      let free = true;
      const r = RANK[d];
      for (let i = layerStart[r]; free && i < layerStart[r + 1]; i++) {
        const label = order[i];
        if (KIND[label] === Kind.Label && xs[label] + W[label] / 2 > lo && xs[label] - W[label] / 2 < hi)
          free = false;
      }
      if (!free) continue;
      onLine[d] = 1;
      const steps = last - first + 2;
      for (let k = first; k <= last; k++) xs[k] = from + (to - from) * (k - first + 1) / steps;
    }
  }
}
__name(pastLabels, "pastLabels");
function reduceCrossings(g, nodes) {
  const {
    n,
    real,
    maxRank,
    W,
    EF,
    ET,
    EFD,
    ETD,
    succStart,
    succE,
    predStart,
    predE,
    layerStart,
    order,
    pos,
    offsets,
    fixed,
    GRP,
    groupParent
  } = g;
  let widest = 0;
  for (let r = 0; r <= maxRank; r++) widest = Math.max(widest, layerStart[r + 1] - layerStart[r]);
  if (widest < 2) return [0, 0];
  const place = offsets ? new Int32Array(EF.length) : void 0;
  const placeIn = new Int32Array(place ? EF.length : 0);
  const places = new Int32Array(place ? n : 0);
  const leaving = place ? succE.slice() : succE;
  const mixed = new Uint8Array(place ? n : 0);
  if (place) {
    const arriving = predE.slice();
    const byOffset = /* @__PURE__ */ __name((list, from, to, dx) => {
      for (let k = from + 1; k < to; k++) {
        if (dx[list[k]] === dx[list[from]]) continue;
        list.subarray(from, to).sort((a, b) => dx[a] - dx[b]);
        return true;
      }
      return false;
    }, "byOffset");
    for (let v = 0; v < n; v++) {
      places[v] = 1;
      if (byOffset(arriving, predStart[v], predStart[v + 1], ETD)) {
        for (let k = predStart[v] + 1; k < predStart[v + 1]; k++) {
          if (ETD[arriving[k]] !== ETD[arriving[k - 1]]) places[v]++;
          placeIn[arriving[k]] = places[v] - 1;
        }
      }
      if (byOffset(leaving, succStart[v], succStart[v + 1], EFD)) mixed[v] = 1;
    }
  }
  let size2 = 1;
  while (size2 < (place ? widest + EF.length : widest)) size2 <<= 1;
  const tree = new Int32Array(2 * size2);
  const targets = new Int32Array(EF.length);
  const count = /* @__PURE__ */ __name(() => {
    let total = 0;
    for (let r = 0; r < maxRank; r++) {
      let southLen = layerStart[r + 2] - layerStart[r + 1];
      if (place) {
        let next = 0;
        for (let i = layerStart[r + 1]; i < layerStart[r + 2]; i++) {
          const v = order[i];
          for (let k = predStart[v]; k < predStart[v + 1]; k++)
            place[predE[k]] = next + placeIn[predE[k]];
          next += places[v];
        }
        southLen = next;
      }
      if (southLen < 2) continue;
      let t = 0;
      for (let i = layerStart[r]; i < layerStart[r + 1]; i++) {
        const v = order[i];
        const from = succStart[v];
        const to = succStart[v + 1];
        const t0 = t;
        for (let k = from; k < to; k++)
          targets[t++] = place ? place[leaving[k]] : pos[ET[succE[k]]];
        const d = t - t0;
        if (d < 2) continue;
        if (place && mixed[v]) {
          for (let a = t0 + 1; a < t; a++) {
            const item = targets[a];
            const dx = EFD[leaving[from + a - t0]];
            let b = a - 1;
            while (b >= t0 && EFD[leaving[from + b - t0]] === dx && targets[b] > item) {
              targets[b + 1] = targets[b];
              b--;
            }
            targets[b + 1] = item;
          }
        } else if (d <= 12) {
          for (let a = t0 + 1; a < t; a++) {
            const item = targets[a];
            let b = a - 1;
            while (b >= t0 && targets[b] > item) {
              targets[b + 1] = targets[b];
              b--;
            }
            targets[b + 1] = item;
          }
        } else {
          targets.subarray(t0, t).sort();
        }
      }
      if (t < 2) continue;
      let leaves = 1;
      while (leaves < southLen) leaves <<= 1;
      tree.fill(0, 0, 2 * leaves);
      for (let k = 0; k < t; k++) {
        let i = targets[k] + leaves;
        tree[i]++;
        while (i > 1) {
          if ((i & 1) === 0) total += tree[i + 1];
          i >>= 1;
          tree[i]++;
        }
      }
    }
    return total;
  }, "count");
  const declared = count();
  const bary = new Float64Array(n);
  const moving = new Int32Array(widest);
  const spare = new Int32Array(widest);
  const groups = groupParent ? groupParent.length : 0;
  const depth = new Int32Array(groups);
  for (let gr = 0; gr < groups; gr++) for (let p = gr; p >= 0; p = groupParent[p]) depth[gr]++;
  const groupSum = new Float64Array(groups);
  const groupCount = new Int32Array(groups);
  const groupFirst = new Int32Array(groups);
  const arrange = /* @__PURE__ */ __name((r, key) => {
    const s = layerStart[r];
    const e = layerStart[r + 1];
    for (let i = s; i < e; i++) {
      for (let gr = GRP[order[i]]; gr >= 0; gr = groupParent[gr]) {
        groupSum[gr] = 0;
        groupCount[gr] = 0;
      }
    }
    for (let i = s; i < e; i++) {
      const v = order[i];
      for (let gr = GRP[v]; gr >= 0; gr = groupParent[gr]) {
        if (groupCount[gr] === 0) groupFirst[gr] = i;
        groupSum[gr] += key[v];
        groupCount[gr]++;
      }
    }
    const value = /* @__PURE__ */ __name((item) => item >= n ? groupSum[item - n] / groupCount[item - n] : key[item], "value");
    const first = /* @__PURE__ */ __name((item) => item >= n ? groupFirst[item - n] : s + pos[item], "first");
    const compare = /* @__PURE__ */ __name((a, b) => {
      let ia = a;
      let ib = b;
      let ca = GRP[a];
      let cb = GRP[b];
      let da = ca < 0 ? 0 : depth[ca];
      let db = cb < 0 ? 0 : depth[cb];
      for (; da > db; da--) {
        ia = n + ca;
        ca = groupParent[ca];
      }
      for (; db > da; db--) {
        ib = n + cb;
        cb = groupParent[cb];
      }
      while (ca !== cb) {
        ia = n + ca;
        ca = groupParent[ca];
        ib = n + cb;
        cb = groupParent[cb];
      }
      return value(ia) - value(ib) || first(ia) - first(ib);
    }, "compare");
    const row = Array.from(order.subarray(s, e)).sort(compare);
    order.set(row, s);
    for (let i = s; i < e; i++) pos[order[i]] = i - s;
  }, "arrange");
  if (GRP) {
    const at2 = new Float64Array(n);
    for (let r = 0; r <= maxRank; r++) {
      for (let i = layerStart[r]; i < layerStart[r + 1]; i++) at2[order[i]] = i - layerStart[r];
      arrange(r, at2);
    }
  }
  let best = GRP ? count() : declared;
  if (best === 0) return [0, declared];
  const bestOrder = order.slice();
  const start = Math.min(best, declared);
  const sweep = /* @__PURE__ */ __name((down, biasRight) => {
    const start2 = down ? predStart : succStart;
    const list = down ? predE : succE;
    const other = down ? EF : ET;
    const otherDx = down ? EFD : ETD;
    for (let step = 1; step <= maxRank; step++) {
      const r = down ? step : maxRank - step;
      if (fixed[r]) continue;
      const s = layerStart[r];
      const e = layerStart[r + 1];
      let movable = 0;
      for (let i = s; i < e; i++) {
        const v = order[i];
        const pin = v < real ? nodes[v].pin : 0;
        if (pin !== 0) {
          bary[v] = pin * 1e9;
          moving[movable++] = v;
          continue;
        }
        const from = start2[v];
        const to = start2[v + 1];
        if (from === to) {
          if (GRP) {
            const across = down ? layerStart[r] - layerStart[r - 1] : layerStart[r + 2] - layerStart[r + 1];
            bary[v] = (i - s) * across / (e - s);
            continue;
          }
          bary[v] = -1;
          continue;
        }
        let sum = 0;
        for (let k2 = from; k2 < to; k2++) {
          const u = other[list[k2]];
          sum += pos[u];
          if (offsets && W[u] > 0) sum += otherDx[list[k2]] / W[u];
        }
        bary[v] = sum / (to - from);
        moving[movable++] = v;
      }
      if (GRP) {
        arrange(r, bary);
        continue;
      }
      if (movable < 2) continue;
      sortByBary(moving, movable, bary, pos, biasRight, spare);
      let k = 0;
      for (let i = s; i < e; i++) if (bary[order[i]] !== -1) order[i] = moving[k++];
      for (let i = s; i < e; i++) pos[order[i]] = i - s;
    }
  }, "sweep");
  const outOfOrder = /* @__PURE__ */ __name(() => {
    let total = 0;
    for (let r = 0; r <= maxRank; r++) {
      for (let i = layerStart[r]; i < layerStart[r + 1]; i++) {
        if (order[i] >= real) continue;
        for (let j = i + 1; j < layerStart[r + 1]; j++) if (order[j] < order[i]) total++;
      }
    }
    return total;
  }, "outOfOrder");
  const settlePositions = /* @__PURE__ */ __name(() => {
    for (let r = 0; r <= maxRank; r++)
      for (let i = layerStart[r]; i < layerStart[r + 1]; i++) pos[order[i]] = i - layerStart[r];
  }, "settlePositions");
  const pinOf = /* @__PURE__ */ __name((v) => v < real ? nodes[v].pin : 0, "pinOf");
  const at = /* @__PURE__ */ __name((e, up) => {
    const u = up ? EF[e] : ET[e];
    return offsets && W[u] > 0 ? pos[u] + (up ? EFD[e] : ETD[e]) / W[u] : pos[u];
  }, "at");
  const between = /* @__PURE__ */ __name((a, b) => {
    let c = 0;
    for (let k = predStart[a]; k < predStart[a + 1]; k++) {
      const x = at(predE[k], true);
      for (let j = predStart[b]; j < predStart[b + 1]; j++) if (x > at(predE[j], true)) c++;
    }
    for (let k = succStart[a]; k < succStart[a + 1]; k++) {
      const x = at(succE[k], false);
      for (let j = succStart[b]; j < succStart[b + 1]; j++) if (x > at(succE[j], false)) c++;
    }
    return c;
  }, "between");
  const transpose = /* @__PURE__ */ __name(() => {
    for (let pass = 0; pass < 8; pass++) {
      let improved = false;
      for (let r = 0; r <= maxRank; r++) {
        if (fixed[r]) continue;
        const s = layerStart[r];
        for (let i = s; i + 1 < layerStart[r + 1]; i++) {
          const a = order[i];
          const b = order[i + 1];
          if (pinOf(a) !== pinOf(b) || GRP && GRP[a] !== GRP[b]) continue;
          if (between(b, a) >= between(a, b)) continue;
          order[i] = b;
          order[i + 1] = a;
          pos[b] = i - s;
          pos[a] = i + 1 - s;
          improved = true;
        }
      }
      if (!improved) break;
    }
  }, "transpose");
  const initial = order.slice();
  const small = n <= 600;
  let chosen = bestOrder;
  let chosenOut = Infinity;
  for (let attempt = 0; attempt < (small ? 2 : 1); attempt++) {
    if (attempt > 0) {
      order.set(initial);
      settlePositions();
    }
    let found = start;
    const foundOrder = initial.slice();
    for (let i = 0, stale = 0; stale < 4 && i < MAX_SWEEPS; i++, stale++) {
      sweep((i + attempt) % 2 === 0, i % 4 >= 2);
      const c = count();
      if (c < found) {
        found = c;
        foundOrder.set(order);
        stale = 0;
        if (c === 0) break;
      }
    }
    order.set(foundOrder);
    if (small && found > 0) {
      settlePositions();
      transpose();
      const c = count();
      if (c < found) {
        found = c;
        foundOrder.set(order);
      }
    }
    const out = small ? outOfOrder() : 0;
    if (attempt === 0 || found < best || found === best && out < chosenOut) {
      best = found;
      chosen = foundOrder;
      chosenOut = out;
    }
  }
  order.set(chosen);
  settlePositions();
  bestOrder.set(chosen);
  if (GRP) best = count();
  if (!small) return [best, declared];
  for (let i = 0; i < real; i++) if (nodes[i].pin !== 0) return [best, declared];
  if (chosenOut === 0 || fixed[0] || fixed[maxRank]) return [best, declared];
  for (let r = 0; r <= maxRank; r++) order.subarray(layerStart[r], layerStart[r + 1]).reverse();
  settlePositions();
  if (count() > best || outOfOrder() >= chosenOut) order.set(bestOrder);
  return [best, declared];
}
__name(reduceCrossings, "reduceCrossings");
function halfRoom(g, opt, v) {
  return g.W[v] / 2 + (g.KIND[v] === Kind.Node ? opt.nodeSep : opt.edgeSep) / 2;
}
__name(halfRoom, "halfRoom");
function position(g, opt) {
  const {
    n,
    maxRank,
    W,
    KIND,
    EF,
    ET,
    EFD,
    ETD,
    succStart,
    succE,
    predStart,
    predE,
    layerStart,
    order,
    pos
  } = g;
  const segments = EF.length;
  const gap = new Float64Array(n);
  for (let i = 0; i < n; i++) gap[i] = halfRoom(g, opt, i);
  const key = new Int32Array(segments);
  for (let e = 0; e < segments; e++) key[e] = pos[ET[e]];
  for (let v = 0; v < n; v++)
    if (succStart[v + 1] - succStart[v] > 1)
      sortRange(succE, succStart[v], succStart[v + 1], key);
  for (let e = 0; e < segments; e++) key[e] = pos[EF[e]];
  for (let v = 0; v < n; v++)
    if (predStart[v + 1] - predStart[v] > 1)
      sortRange(predE, predStart[v], predStart[v + 1], key);
  const conflict = new Uint8Array(segments);
  for (let r = 1; r <= maxRank; r++) {
    const prevLen = layerStart[r] - layerStart[r - 1];
    const s = layerStart[r];
    const end = layerStart[r + 1];
    let k0 = 0;
    let scan = s;
    for (let i = s; i < end; i++) {
      const v = order[i];
      let inner = -1;
      if (isDummy(KIND[v])) {
        const u = EF[predE[predStart[v]]];
        if (isDummy(KIND[u])) inner = u;
      }
      const k1 = inner >= 0 ? pos[inner] : prevLen;
      if (inner >= 0 || i === end - 1) {
        for (let j = scan; j <= i; j++) {
          const w = order[j];
          const wDummy = isDummy(KIND[w]);
          for (let k = predStart[w]; k < predStart[w + 1]; k++) {
            const e = predE[k];
            const up = pos[EF[e]];
            if ((up < k0 || k1 < up) && !(wDummy && isDummy(KIND[EF[e]]))) conflict[e] = 1;
          }
        }
        scan = i + 1;
        k0 = k1;
      }
    }
  }
  const results = [];
  const root = new Int32Array(n);
  const align = new Int32Array(n);
  const shift = new Float64Array(n);
  const eFrom = new Int32Array(n);
  const eTo = new Int32Array(n);
  const eW = new Float64Array(n);
  const indeg = new Int32Array(n);
  const outStart = new Int32Array(n + 1);
  const outE = new Int32Array(n);
  const fill = new Int32Array(n);
  const topo = new Int32Array(n);
  const x = new Float64Array(n);
  for (let variant = 0; variant < 4; variant++) {
    const up = variant < 2;
    const right = (variant & 1) === 1;
    const start = up ? predStart : succStart;
    const list = up ? predE : succE;
    const other = up ? EF : ET;
    const ownDx = up ? ETD : EFD;
    const otherDx = up ? EFD : ETD;
    for (let i = 0; i < n; i++) {
      root[i] = i;
      align[i] = i;
      shift[i] = 0;
      indeg[i] = 0;
      outStart[i + 1] = 0;
      x[i] = 0;
    }
    for (let step = 0; step <= maxRank; step++) {
      const r = up ? step : maxRank - step;
      const s = layerStart[r];
      const end = layerStart[r + 1];
      const adjacent = up ? r - 1 : r + 1;
      const adjacentLast = adjacent >= 0 && adjacent <= maxRank ? layerStart[adjacent + 1] - layerStart[adjacent] - 1 : 0;
      let prevIdx = -1;
      for (let i = right ? end - 1 : s; right ? i >= s : i < end; right ? i-- : i++) {
        const v = order[i];
        const from = start[v];
        const d = start[v + 1] - from;
        if (d === 0) continue;
        const lo = from + (d - 1 >> 1);
        const hi = from + (d >> 1);
        for (let pass = 0; pass < 2; pass++) {
          if (pass === 1 && lo === hi) break;
          const e = list[pass === 0 !== right ? lo : hi];
          const w = other[e];
          const idx = right ? adjacentLast - pos[w] : pos[w];
          if (align[v] === v && prevIdx < idx && conflict[e] === 0) {
            align[w] = v;
            align[v] = root[v] = root[w];
            shift[v] = shift[w] + otherDx[e] - ownDx[e];
            prevIdx = idx;
          }
        }
      }
    }
    let blockEdges = 0;
    for (let r = 0; r <= maxRank; r++) {
      const s = layerStart[r];
      const end = layerStart[r + 1];
      for (let i = s + 1; i < end; i++) {
        const a = right ? order[i] : order[i - 1];
        const b = right ? order[i - 1] : order[i];
        const sep = gap[a] + gap[b];
        eFrom[blockEdges] = root[a];
        eTo[blockEdges] = root[b];
        eW[blockEdges] = right ? sep - shift[a] + shift[b] : sep + shift[a] - shift[b];
        indeg[root[b]]++;
        outStart[root[a] + 1]++;
        blockEdges++;
      }
    }
    for (let i = 0; i < n; i++) outStart[i + 1] += outStart[i];
    for (let i = 0; i < n; i++) fill[i] = outStart[i];
    for (let e = 0; e < blockEdges; e++) outE[fill[eFrom[e]]++] = e;
    let count = 0;
    for (let i = 0; i < n; i++) if (root[i] === i && indeg[i] === 0) topo[count++] = i;
    for (let q = 0; q < count; q++) {
      const v = topo[q];
      for (let k = outStart[v]; k < outStart[v + 1]; k++) {
        const e = outE[k];
        const w = eTo[e];
        if (x[v] + eW[e] > x[w]) x[w] = x[v] + eW[e];
        if (--indeg[w] === 0) topo[count++] = w;
      }
    }
    for (let q = count - 1; q >= 0; q--) {
      const v = topo[q];
      let min = Infinity;
      for (let k = outStart[v]; k < outStart[v + 1]; k++) {
        const e = outE[k];
        const cand = x[eTo[e]] - eW[e];
        if (cand < min) min = cand;
      }
      if (min !== Infinity && min > x[v]) x[v] = min;
    }
    const xs = new Float64Array(n);
    for (let i = 0; i < n; i++) xs[i] = (right ? -x[root[i]] : x[root[i]]) + shift[i];
    results.push(xs);
  }
  let narrowest = 0;
  let bestWidth = Infinity;
  const mins = [];
  const maxs = [];
  for (let k = 0; k < 4; k++) {
    let lo = Infinity;
    let hi = -Infinity;
    const xs = results[k];
    for (let i = 0; i < n; i++) {
      const half = W[i] / 2;
      if (xs[i] - half < lo) lo = xs[i] - half;
      if (xs[i] + half > hi) hi = xs[i] + half;
    }
    mins.push(lo);
    maxs.push(hi);
    if (hi - lo < bestWidth) {
      bestWidth = hi - lo;
      narrowest = k;
    }
  }
  for (let k = 0; k < 4; k++) {
    const delta = (k & 1) === 0 ? mins[narrowest] - mins[k] : maxs[narrowest] - maxs[k];
    if (delta !== 0) {
      const xs = results[k];
      for (let i = 0; i < n; i++) xs[i] += delta;
    }
  }
  const out = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    let a = results[0][i];
    let b = results[1][i];
    let c = results[2][i];
    let d = results[3][i];
    let t;
    if (a > b) {
      t = a;
      a = b;
      b = t;
    }
    if (c > d) {
      t = c;
      c = d;
      d = t;
    }
    if (a > c) {
      t = a;
      a = c;
      c = t;
    }
    if (b > d) {
      t = b;
      b = d;
      d = t;
    }
    if (b > c) {
      t = b;
      b = c;
      c = t;
    }
    out[i] = (b + c) / 2;
  }
  return out;
}
__name(position, "position");

// src/rendering-util/layout-algorithms/layered/compound.ts
var Side = { Top: 0, Right: 1, Bottom: 2, Left: 3 };
var MAX_PORTS = 4e4;
var MAX_ORDERED_PORTS = 400;
var MAX_ORDERED_EDGES = 500;
var FLAT_SLACK = 1.5;
var FLAT_SPARE = 4;
function snapshot(nodes, edges, levels, total) {
  return {
    nodes: nodes.map(({ x, y, w, h }) => ({ x, y, w, h })),
    edges: edges.map(({ route, labelX, labelY }) => ({ route, labelX, labelY })),
    levels: levels.map(({ x, y, ports }) => ({
      x,
      y,
      ports: ports.map(({ px, py }) => ({ px, py }))
    })),
    total
  };
}
__name(snapshot, "snapshot");
function restore(s, nodes, edges, levels) {
  nodes.forEach((c, i) => Object.assign(c, s.nodes[i]));
  edges.forEach((e, i) => Object.assign(e, s.edges[i]));
  levels.forEach((level, i) => {
    const saved = s.levels[i];
    level.x = saved.x;
    level.y = saved.y;
    level.ports.forEach((port, j) => Object.assign(port, saved.ports[j]));
  });
  return s.total;
}
__name(restore, "restore");
var FAN = 24;
var IN_LINE2 = 0.5;
var CURVE_PIECES = 3;
var CORNER_PIECES = 2;
var STEP_PIECES = Math.max(3, CURVE_PIECES, CORNER_PIECES + 1);
var HANDLE = 0.62;
var MAX_INSERT = 128;
var Style = { Curved: 0, Stepped: 1, Linear: 2 };
function styleOf(opt) {
  if (opt.tracks) return Style.Stepped;
  return opt.straight ? Style.Linear : Style.Curved;
}
__name(styleOf, "styleOf");
function routeCrossings(nodes, edges, style = Style.Curved) {
  let size2 = 0;
  for (const e of edges)
    if (e.src !== e.dst && e.route.length > 3) size2 += (e.route.length / 3 - 1) * STEP_PIECES;
  const ax = new Float64Array(size2);
  const ay = new Float64Array(size2);
  const bx = new Float64Array(size2);
  const by = new Float64Array(size2);
  const low = new Float64Array(size2);
  const high = new Float64Array(size2);
  const owner = new Int32Array(size2);
  const ends = new Uint8Array(size2);
  let count = 0;
  let top = Infinity;
  let bottom = -Infinity;
  let fromX = NaN;
  let fromY = NaN;
  let toX = NaN;
  let toY = NaN;
  const add = /* @__PURE__ */ __name((ei, part, x0, y0, x1, y1) => {
    const p = count - 1;
    const on = x0 === toX && y0 === toY && (y1 === y0 && fromY === y0 || x1 === x0 && fromX === x0);
    if (on && owner[p] === ei && ends[p] === part && (x0 - fromX) * (x1 - x0) + (y0 - fromY) * (y1 - y0) > 0) {
      count--;
      x0 = fromX;
      y0 = fromY;
    }
    fromX = x0;
    fromY = y0;
    toX = x1;
    toY = y1;
    ends[count] = part;
    ax[count] = Math.min(x0, x1);
    bx[count] = Math.max(x0, x1);
    ay[count] = x0 <= x1 ? y0 : y1;
    by[count] = x0 <= x1 ? y1 : y0;
    low[count] = Math.min(y0, y1);
    high[count] = Math.max(y0, y1);
    if (low[count] < top) top = low[count];
    if (high[count] > bottom) bottom = high[count];
    owner[count++] = ei;
  }, "add");
  for (let ei = 0; ei < edges.length; ei++) {
    const e = edges[ei];
    if (e.src === e.dst) continue;
    const r = e.route;
    const aligned = /* @__PURE__ */ __name((k) => Math.abs(r[k] - r[k - 3]) < 0.01 || Math.abs(r[k + 1] - r[k - 2]) < 0.01, "aligned");
    const length = /* @__PURE__ */ __name((k) => Math.abs(r[k] - r[k - 3]) + Math.abs(r[k + 1] - r[k - 2]), "length");
    const turns = /* @__PURE__ */ __name((k) => style === Style.Curved && k > 0 && k < r.length - 3 && aligned(k) && aligned(k + 3) && length(k) >= 0.01 && length(k + 3) >= 0.01 && Math.abs(r[k] - r[k - 3]) < 0.01 !== Math.abs(r[k + 3] - r[k]) < 0.01, "turns");
    let atX = r[0];
    let atY = r[1];
    for (let k = 3; k < r.length; k += 3) {
      const part = (k === 3 ? 1 : 0) | (k === r.length - 3 ? 2 : 0);
      const x0 = atX;
      const y0 = atY;
      const x1 = r[k];
      const y1 = r[k + 1];
      atX = x1;
      atY = y1;
      if (aligned(k) || style === Style.Linear) {
        if (!turns(k)) {
          add(ei, part, x0, y0, x1, y1);
          continue;
        }
        const before = turns(k - 3) ? length(k) / 2 : length(k);
        const after = turns(k + 3) ? length(k + 3) / 2 : length(k + 3);
        const ux = (x1 - r[k - 3]) / length(k);
        const uy = (y1 - r[k - 2]) / length(k);
        const vx = (r[k + 3] - x1) / length(k + 3);
        const vy = (r[k + 4] - y1) / length(k + 3);
        const sx = x1 - ux * before;
        const sy = y1 - uy * before;
        add(ei, part, x0, y0, sx, sy);
        const c1x = x1 - ux * before * (1 - HANDLE);
        const c1y = y1 - uy * before * (1 - HANDLE);
        const c2x = x1 + vx * after * (1 - HANDLE);
        const c2y = y1 + vy * after * (1 - HANDLE);
        atX = x1 + vx * after;
        atY = y1 + vy * after;
        const turn = part | (k + 3 === r.length - 3 ? 2 : 0);
        let px2 = sx;
        let py2 = sy;
        for (let i = 1; i <= CORNER_PIECES; i++) {
          const t = i / CORNER_PIECES;
          const u = 1 - t;
          const x = u * u * u * sx + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * atX;
          const y = u * u * u * sy + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * atY;
          add(ei, turn, px2, py2, x, y);
          px2 = x;
          py2 = y;
        }
        continue;
      }
      if (style === Style.Stepped) {
        const down2 = r[k + 2] === 0;
        const mx = down2 ? x0 : (x0 + x1) / 2;
        const my = down2 ? (y0 + y1) / 2 : y0;
        add(ei, part, x0, y0, mx, my);
        add(ei, part, mx, my, down2 ? x1 : mx, down2 ? my : y1);
        add(ei, part, down2 ? x1 : mx, down2 ? my : y1, x1, y1);
        continue;
      }
      const down = r[k + 2] === 0;
      const c = down ? ease(x1 - x0, y1 - y0) : ease(y1 - y0, x1 - x0);
      let px = x0;
      let py = y0;
      for (let i = 1; i <= CURVE_PIECES; i++) {
        const t = i / CURVE_PIECES;
        const u = 1 - t;
        const across = t * t * (3 - 2 * t);
        const along = 3 * c * t * u * u + 3 * (1 - c) * t * t * u + t * t * t;
        const x = x0 + (x1 - x0) * (down ? across : along);
        const y = y0 + (y1 - y0) * (down ? along : across);
        add(ei, part, px, py, x, y);
        px = x;
        py = y;
      }
    }
  }
  const bands = bottom > top ? Math.round(Math.sqrt(count)) : 1;
  const scale = bottom > top ? bands / (bottom - top) : 0;
  const bandOf = /* @__PURE__ */ __name((y) => Math.min(bands - 1, Math.floor((y - top) * scale)), "bandOf");
  const first = new Int32Array(count);
  const bandStart = new Int32Array(bands + 1);
  for (let p = 0; p < count; p++) {
    first[p] = bandOf(low[p]);
    for (let b = first[p], last = bandOf(high[p]); b <= last; b++) bandStart[b + 1]++;
  }
  for (let b = 0; b < bands; b++) bandStart[b + 1] += bandStart[b];
  const fill = bandStart.slice(0, bands);
  const inBand = new Int32Array(bandStart[bands]);
  for (let p = 0; p < count; p++)
    for (let b = first[p], last = bandOf(high[p]); b <= last; b++) inBand[fill[b]++] = p;
  const runs = new Float64Array(edges.length * 8);
  const inLine = /* @__PURE__ */ __name((r, a, b, c) => Math.abs(r[a] - r[b]) < IN_LINE2 && Math.abs(r[a] - r[c]) < IN_LINE2 || Math.abs(r[a + 1] - r[b + 1]) < IN_LINE2 && Math.abs(r[a + 1] - r[c + 1]) < IN_LINE2, "inLine");
  for (let ei = 0; ei < edges.length; ei++) {
    const r = edges[ei].route;
    if (r.length < 6) continue;
    let k = 3;
    while (k + 3 < r.length && inLine(r, 0, k, k + 3)) k += 3;
    const last = r.length - 3;
    let j = last - 3;
    while (j >= 3 && inLine(r, last, j, j - 3)) j -= 3;
    runs.set([r[0], r[1], r[k], r[k + 1], r[j], r[j + 1], r[last], r[last + 1]], ei * 8);
  }
  const onRun = /* @__PURE__ */ __name((ei, end, x, y) => {
    const o = ei * 8 + (end === 1 ? 0 : 4);
    const x0 = runs[o];
    const y0 = runs[o + 1];
    const dx = runs[o + 2] - x0;
    const dy = runs[o + 3] - y0;
    const length = dx * dx + dy * dy;
    const t = length > 0 ? Math.max(0, Math.min(1, ((x - x0) * dx + (y - y0) * dy) / length)) : 0;
    return Math.hypot(x - x0 - t * dx, y - y0 - t * dy) < IN_LINE2;
  }, "onRun");
  let total = 0;
  for (let band = 0; band < bands; band++) {
    const bandEnd = bandStart[band + 1];
    if (bandEnd - bandStart[band] > MAX_INSERT)
      inBand.subarray(bandStart[band], bandEnd).sort((p, q) => ax[p] - ax[q] || p - q);
    else {
      for (let i = bandStart[band] + 1; i < bandEnd; i++) {
        const p = inBand[i];
        let j = i;
        for (; j > bandStart[band] && ax[inBand[j - 1]] > ax[p]; j--)
          inBand[j] = inBand[j - 1];
        inBand[j] = p;
      }
    }
    for (let s = bandStart[band]; s < bandEnd; s++) {
      const p = inBand[s];
      const dx = bx[p] - ax[p];
      const dy = by[p] - ay[p];
      const here = first[p] === band;
      for (let t = s + 1; t < bandEnd; t++) {
        const q = inBand[t];
        if (ax[q] > bx[p]) break;
        if (high[q] < low[p] || low[q] > high[p] || owner[p] === owner[q] || !here && first[q] !== band)
          continue;
        const d1 = dx * (ay[q] - ay[p]) - dy * (ax[q] - ax[p]);
        const d2 = dx * (by[q] - ay[p]) - dy * (bx[q] - ax[p]);
        if (d1 > 0 === d2 > 0) continue;
        const ex = bx[q] - ax[q];
        const ey = by[q] - ay[q];
        const d3 = ex * (ay[p] - ay[q]) - ey * (ax[p] - ax[q]);
        const d4 = ex * (by[p] - ay[q]) - ey * (bx[p] - ax[q]);
        if (d3 > 0 === d4 > 0) continue;
        const ep = edges[owner[p]];
        const eq = edges[owner[q]];
        const at = d3 / (d3 - d4);
        const x = ax[p] + at * dx;
        const y = ay[p] + at * dy;
        const fan = /* @__PURE__ */ __name((v, pe, qe) => (ends[p] & pe) !== 0 && (ends[q] & qe) !== 0 || Math.abs(x - nodes[v].x) < nodes[v].w / 2 + FAN && Math.abs(y - nodes[v].y) < nodes[v].h / 2 + FAN || onRun(owner[p], pe, x, y) && onRun(owner[q], qe, x, y), "fan");
        if (ep.src === eq.src && fan(ep.src, 1, 1)) continue;
        if (ep.src === eq.dst && fan(ep.src, 1, 2)) continue;
        if (ep.dst === eq.src && fan(ep.dst, 2, 1)) continue;
        if (ep.dst === eq.dst && fan(ep.dst, 2, 2)) continue;
        total++;
      }
    }
  }
  return total;
}
__name(routeCrossings, "routeCrossings");
function inheritCrossedDirections(nodes, ends) {
  const ancestors = /* @__PURE__ */ __name((i) => {
    const set = /* @__PURE__ */ new Set();
    for (let p = nodes[i].parent; p >= 0 && !set.has(p); p = nodes[p].parent) set.add(p);
    return set;
  }, "ancestors");
  for (const [src, dst] of ends) {
    if (src < 0 || dst < 0 || src === dst) continue;
    const a = ancestors(src);
    const b = ancestors(dst);
    for (const g of a) if (!b.has(g)) nodes[g].dir = void 0;
    for (const g of b) if (!a.has(g)) nodes[g].dir = void 0;
  }
}
__name(inheritCrossedDirections, "inheritCrossedDirections");
function cnode(w, h, parent = -1) {
  return {
    w,
    h,
    parent,
    isGroup: false,
    dir: void 0,
    padX: 0,
    padTop: 0,
    padBottom: 0,
    minW: 0,
    seq: 0,
    span: 0,
    x: 0,
    y: 0
  };
}
__name(cnode, "cnode");
var START_SIDE = {
  TB: Side.Top,
  BT: Side.Bottom,
  LR: Side.Left,
  RL: Side.Right
};
function startSide(dir) {
  return START_SIDE[dir];
}
__name(startSide, "startSide");
function opposite(side) {
  return side + 2 & 3;
}
__name(opposite, "opposite");
function compoundLayout(nodes, edges, rootDir, opt) {
  const n = nodes.length;
  const levelOf = /* @__PURE__ */ new Map();
  const order = [];
  const makeLevel = /* @__PURE__ */ __name((id, dir) => {
    const level = {
      id,
      dir,
      items: [],
      edges: [],
      ports: [],
      portOf: /* @__PURE__ */ new Map(),
      routes: /* @__PURE__ */ new Map(),
      x: 0,
      y: 0
    };
    levelOf.set(id, level);
    return level;
  }, "makeLevel");
  const root = makeLevel(-1, rootDir);
  const children = [];
  for (let i = 0; i < n; i++) children.push([]);
  const rootItems = [];
  for (let i = 0; i < n; i++) {
    const p = nodes[i].parent;
    if (p >= 0 && p < n && p !== i && nodes[p].isGroup) children[p].push(i);
    else {
      nodes[i].parent = -1;
      rootItems.push(i);
    }
  }
  root.items = rootItems;
  order.push(root);
  const depth = new Int32Array(n);
  const placed = new Uint8Array(n);
  const descend = /* @__PURE__ */ __name((from) => {
    for (let q = from; q < order.length; q++) {
      const level = order[q];
      for (const item of level.items) {
        placed[item] = 1;
        depth[item] = level.id < 0 ? 0 : depth[level.id] + 1;
        if (nodes[item].isGroup) {
          const child = makeLevel(item, nodes[item].dir ?? level.dir);
          child.items = children[item];
          order.push(child);
        }
      }
    }
  }, "descend");
  descend(0);
  for (let i = 0; i < n; i++) {
    if (placed[i]) continue;
    const former = nodes[i].parent;
    children[former] = children[former].filter((c) => c !== i);
    nodes[i].parent = -1;
    root.items.push(i);
    placed[i] = 1;
    depth[i] = 0;
    if (nodes[i].isGroup) {
      const from = order.length;
      const child = makeLevel(i, nodes[i].dir ?? rootDir);
      child.items = children[i];
      order.push(child);
      descend(from);
    }
  }
  for (let q = order.length - 1; q > 0; q--) {
    const level = order[q];
    let seq = Infinity;
    for (const item of level.items) if (nodes[item].seq < seq) seq = nodes[item].seq;
    if (seq !== Infinity) nodes[level.id].seq = seq;
  }
  for (const level of order) level.items.sort((a, b) => nodes[a].seq - nodes[b].seq || a - b);
  let ports = 0;
  for (const e of edges) {
    let a = e.src;
    let b = e.dst;
    let crossed = 0;
    for (; depth[a] > depth[b]; crossed++) a = nodes[a].parent;
    for (; depth[b] > depth[a]; crossed++) b = nodes[b].parent;
    for (; a !== b && nodes[a].parent !== nodes[b].parent; crossed += 2) {
      a = nodes[a].parent;
      b = nodes[b].parent;
    }
    if (a === b) continue;
    if (ports + crossed > MAX_PORTS) {
      e.src = a;
      e.dst = b;
    } else {
      ports += crossed;
    }
  }
  const loops = [];
  const stray = [];
  for (let ei = 0; ei < edges.length; ei++) {
    const e = edges[ei];
    e.route = [];
    if (e.src === e.dst) {
      loops.push(ei);
      continue;
    }
    let a = e.src;
    let b = e.dst;
    const aPath = [];
    const bPath = [];
    while (depth[a] > depth[b]) {
      aPath.push(a);
      a = nodes[a].parent;
    }
    while (depth[b] > depth[a]) {
      bPath.push(b);
      b = nodes[b].parent;
    }
    if (a === b) {
      stray.push(ei);
      continue;
    }
    while (nodes[a].parent !== nodes[b].parent) {
      aPath.push(a);
      bPath.push(b);
      a = nodes[a].parent;
      b = nodes[b].parent;
    }
    levelOf.get(nodes[a].parent).edges.push({ e: ei, a, b });
    for (const [path, out] of [
      [aPath, true],
      [bPath, false]
    ]) {
      for (const inner of path) {
        const level = levelOf.get(nodes[inner].parent);
        const port = {
          e: ei,
          inner,
          out,
          side: Side.Top,
          hint: NaN,
          px: 0,
          py: 0,
          route: []
        };
        level.ports.push(port);
        level.portOf.set(ei * 2 + (out ? 0 : 1), port);
      }
    }
  }
  const local = new Int32Array(n);
  const endpointBelow = /* @__PURE__ */ __name((item, e, out) => (out ? e.src : e.dst) !== item, "endpointBelow");
  const build = /* @__PURE__ */ __name((level, sized) => {
    const vertical = level.dir === "TB" || level.dir === "BT";
    const start = startSide(level.dir);
    const lnodes = [];
    const ledges = [];
    level.items.forEach((item, i) => {
      local[item] = i;
      const node = nodes[item];
      const ln = sized ? lnode(vertical ? node.w : node.h, vertical ? node.h : node.w) : lnode(0, 0);
      ln.span = node.isGroup ? Math.min(node.span, ln.w - 2 * node.padX) : node.span;
      ln.key = keyed ? key[item] : NaN;
      lnodes.push(ln);
    });
    const held = /* @__PURE__ */ __name((item, ei, out) => nodes[item].isGroup && endpointBelow(item, edges[ei], out), "held");
    const offset = /* @__PURE__ */ __name((item, ei, out) => {
      if (!sized || !nodes[item].isGroup || !endpointBelow(item, edges[ei], out)) return 0;
      const port = levelOf.get(item).portOf.get(ei * 2 + (out ? 0 : 1));
      return vertical ? port.px - nodes[item].w / 2 : port.py - nodes[item].h / 2;
    }, "offset");
    for (const le of level.edges) {
      const e = edges[le.e];
      const edge = ledge(local[le.a], local[le.b], e.minlen);
      if (sized) {
        edge.labelW = vertical ? e.labelW : e.labelH;
        edge.labelH = vertical ? e.labelH : e.labelW;
        edge.tailDx = offset(le.a, le.e, true);
        edge.headDx = offset(le.b, le.e, false);
        edge.tailFixed = held(le.a, le.e, true);
        edge.headFixed = held(le.b, le.e, false);
      }
      ledges.push(edge);
    }
    const dummies = new Int32Array(level.ports.length).fill(-1);
    level.ports.forEach((port, i) => {
      if (port.side === start || port.side === opposite(start)) {
        const d = lnodes.length;
        const ln = lnode(0, 0, port.side === start ? Kind.StartPort : Kind.EndPort);
        ln.key = keyed ? key[port.out ? edges[port.e].dst : edges[port.e].src] : NaN;
        ln.hint = Number.isNaN(port.hint) && keyed && farHint ? farHint(level, port) : port.hint;
        lnodes.push(ln);
        dummies[i] = d;
        const edge = port.out ? ledge(local[port.inner], d) : ledge(d, local[port.inner]);
        if (port.out) {
          edge.tailDx = offset(port.inner, port.e, true);
          edge.tailFixed = held(port.inner, port.e, true);
        } else {
          edge.headDx = offset(port.inner, port.e, false);
          edge.headFixed = held(port.inner, port.e, false);
        }
        ledges.push(edge);
      } else {
        lnodes[local[port.inner]].pin = port.side === Side.Top || port.side === Side.Left ? -1 : 1;
      }
    });
    return { lnodes, ledges, dummies };
  }, "build");
  const ordered = ports > 1 && ports <= MAX_ORDERED_PORTS && edges.length <= MAX_ORDERED_EDGES;
  const key = new Float64Array(n).fill(NaN);
  let keyed = false;
  let flatCrossings = 0;
  let farHint;
  let flat = order.length > 1 && ordered;
  for (const level of order) if (level.dir !== rootDir) flat = false;
  if (flat) {
    const vertical = rootDir === "TB" || rootDir === "BT";
    const leaf = new Int32Array(n).fill(-1);
    const group = new Int32Array(n).fill(-1);
    const lnodes = [];
    const of = [];
    const parent = [];
    for (let i = 0; i < n; i++) {
      if (!nodes[i].isGroup) continue;
      group[i] = parent.length;
      parent.push(-1);
    }
    for (let i = 0; i < n; i++) {
      const p = nodes[i].parent;
      if (nodes[i].isGroup) parent[group[i]] = p >= 0 ? group[p] : -1;
      else {
        leaf[i] = lnodes.length;
        lnodes.push(
          lnode(vertical ? nodes[i].w : nodes[i].h, vertical ? nodes[i].h : nodes[i].w)
        );
        of.push(p >= 0 ? group[p] : -1);
      }
    }
    const ledges = [];
    const ledgeOf = new Int32Array(edges.length).fill(-1);
    edges.forEach((e, ei) => {
      if (e.src === e.dst || leaf[e.src] < 0 || leaf[e.dst] < 0) return;
      ledgeOf[ei] = ledges.length;
      ledges.push(
        ledge(
          leaf[e.src],
          leaf[e.dst],
          e.minlen,
          vertical ? e.labelW : e.labelH,
          vertical ? e.labelH : e.labelW
        )
      );
    });
    const flatLayout = layered(lnodes, ledges, {
      ...opt,
      groups: { of: Int32Array.from(of), parent: Int32Array.from(parent) },
      orderOnly: true
    });
    flatCrossings = Math.min(flatLayout.crossings ?? 0, flatLayout.declared ?? 0);
    const sum = new Float64Array(n);
    const count = new Int32Array(n);
    const last = new Int32Array(n).fill(-1);
    for (let i = 0; i < n; i++) {
      if (leaf[i] < 0) continue;
      key[i] = lnodes[leaf[i]].x;
      for (let p = nodes[i].parent; p >= 0; p = nodes[p].parent) {
        sum[p] += key[i];
        count[p]++;
        last[p] = Math.max(last[p], lnodes[leaf[i]].rank);
      }
    }
    for (let i = 0; i < n; i++) if (count[i] > 0) key[i] = sum[i] / count[i];
    farHint = /* @__PURE__ */ __name((level, port) => {
      const le = ledgeOf[port.e];
      if (le < 0 || level.id < 0 || !port.out || port.side !== opposite(startSide(level.dir)))
        return NaN;
      const points = ledges[le].points;
      let inside2 = key[edges[port.e].src];
      let outside = 0;
      for (let k = 0; k < points.length; k += 2) {
        if (points[k] === last[level.id]) inside2 = points[k + 1];
        if (points[k] === last[level.id] + 1) outside = points[k + 1];
      }
      return inside2 + outside * 1e-6;
    }, "farHint");
  }
  const laid = /* @__PURE__ */ new Map();
  const layOut = /* @__PURE__ */ __name((level, lnodes, ledges) => {
    if (!ordered) return { lnodes, ledges, size: layered(lnodes, ledges, opt) };
    const given = layoutInputs(lnodes, ledges);
    let past = laid.get(level.id);
    if (!past) laid.set(level.id, past = []);
    for (const p of past) {
      let same = p.given.length === given.length;
      for (let i = 0; same && i < given.length; i++) same = Object.is(p.given[i], given[i]);
      if (same) return p;
    }
    const done = { given, lnodes, ledges, size: layered(lnodes, ledges, opt) };
    past.push(done);
    return done;
  }, "layOut");
  let total = { width: 0, height: 0 };
  const place = /* @__PURE__ */ __name(() => {
    for (const level of order) {
      for (const port of level.ports) {
        if (nodes[port.inner].isGroup && endpointBelow(port.inner, edges[port.e], port.out)) {
          levelOf.get(port.inner).portOf.get(port.e * 2 + (port.out ? 0 : 1)).side = port.side;
        }
      }
      if (level.edges.length === 0) continue;
      let needed = false;
      for (const le of level.edges) {
        const e = edges[le.e];
        if (nodes[le.a].isGroup && e.src !== le.a || nodes[le.b].isGroup && e.dst !== le.b)
          needed = true;
      }
      if (!needed) continue;
      const { lnodes, ledges } = build(level, false);
      orient(lnodes, ledges);
      rank(lnodes, ledges, 1);
      const start = startSide(level.dir);
      level.edges.forEach((le, i) => {
        const e = edges[le.e];
        const aAbove = !ledges[i].reversed;
        if (nodes[le.a].isGroup && e.src !== le.a) {
          levelOf.get(le.a).portOf.get(le.e * 2).side = aAbove ? opposite(start) : start;
        }
        if (nodes[le.b].isGroup && e.dst !== le.b) {
          levelOf.get(le.b).portOf.get(le.e * 2 + 1).side = aAbove ? start : opposite(start);
        }
      });
    }
    for (let q = order.length - 1; q >= 0; q--) {
      const level = order[q];
      const group = level.id >= 0 ? nodes[level.id] : void 0;
      const vertical = level.dir === "TB" || level.dir === "BT";
      const flip = level.dir === "BT" || level.dir === "RL";
      const built = build(level, true);
      const { lnodes, ledges, size: size2 } = layOut(level, built.lnodes, built.ledges);
      const dummies = built.dummies;
      const contentW = vertical ? size2.width : size2.height;
      const contentH = vertical ? size2.height : size2.width;
      const padX = group ? group.padX : 0;
      const padTop = group ? group.padTop : 0;
      const boxW = Math.max(contentW + 2 * padX, group ? group.minW : 0);
      const boxH = contentH + padTop + (group ? group.padBottom : 0);
      const offX = (boxW - contentW) / 2;
      const offY = padTop;
      const across = /* @__PURE__ */ __name((ly) => flip ? size2.height - ly : ly, "across");
      const tx = /* @__PURE__ */ __name((lx, ly) => offX + (vertical ? lx : across(ly)), "tx");
      const ty = /* @__PURE__ */ __name((lx, ly) => offY + (vertical ? across(ly) : lx), "ty");
      const axis = vertical ? 0 : 1;
      const convert = /* @__PURE__ */ __name((points) => {
        const out = [];
        for (let i = 0; i < points.length; i += 2)
          out.push(tx(points[i], points[i + 1]), ty(points[i], points[i + 1]), axis);
        return out;
      }, "convert");
      level.items.forEach((item, i) => {
        nodes[item].x = tx(lnodes[i].x, lnodes[i].y);
        nodes[item].y = ty(lnodes[i].x, lnodes[i].y);
      });
      level.edges.forEach((le, i) => {
        const edge = ledges[i];
        level.routes.set(le.e, convert(edge.points));
        const e = edges[le.e];
        if (e.labelW > 0) {
          e.labelX = tx(edge.labelX, edge.labelY);
          e.labelY = ty(edge.labelX, edge.labelY);
        }
      });
      let k = level.edges.length;
      level.ports.forEach((port, i) => {
        const item = nodes[port.inner];
        if (dummies[i] >= 0) {
          const route = convert(ledges[k++].points);
          const at = port.out ? route.length - 3 : 0;
          let bx2 = route[at];
          let by2 = route[at + 1];
          if (port.side === Side.Top) by2 = 0;
          else if (port.side === Side.Bottom) by2 = boxH;
          else if (port.side === Side.Left) bx2 = 0;
          else bx2 = boxW;
          if (port.out) route.push(bx2, by2, axis);
          else route.unshift(bx2, by2, axis);
          port.px = bx2;
          port.py = by2;
          port.route = route;
          return;
        }
        let ix = item.x;
        let iy = item.y;
        if (item.isGroup && endpointBelow(port.inner, edges[port.e], port.out)) {
          const inner = levelOf.get(port.inner).portOf.get(port.e * 2 + (port.out ? 0 : 1));
          ix += inner.px - item.w / 2;
          iy += inner.py - item.h / 2;
        } else if (port.side === Side.Top) iy -= item.h / 2;
        else if (port.side === Side.Bottom) iy += item.h / 2;
        else if (port.side === Side.Left) ix -= item.w / 2;
        else ix += item.w / 2;
        let bx = ix;
        let by = iy;
        if (port.side === Side.Top) by = 0;
        else if (port.side === Side.Bottom) by = boxH;
        else if (port.side === Side.Left) bx = 0;
        else bx = boxW;
        const a = port.side === Side.Top || port.side === Side.Bottom ? 0 : 1;
        port.px = bx;
        port.py = by;
        port.route = port.out ? [ix, iy, a, bx, by, a] : [bx, by, a, ix, iy, a];
      });
      if (group) {
        group.w = boxW;
        group.h = boxH;
      } else {
        total = { width: boxW, height: boxH };
      }
    }
    for (const level of order) {
      const ox = level.x;
      const oy = level.y;
      for (const item of level.items) {
        const node = nodes[item];
        node.x += ox;
        node.y += oy;
        if (node.isGroup) {
          const child = levelOf.get(item);
          child.x = node.x - node.w / 2;
          child.y = node.y - node.h / 2;
        }
      }
    }
    const append = /* @__PURE__ */ __name((route, part, ox, oy) => {
      for (let i = 0; i < part.length; i += 3) {
        const x = part[i] + ox;
        const y = part[i + 1] + oy;
        const len = route.length;
        if (len >= 3 && Math.abs(route[len - 3] - x) < 0.01 && Math.abs(route[len - 2] - y) < 0.01)
          continue;
        route.push(x, y, part[i + 2]);
      }
    }, "append");
    for (const level of order) {
      for (const le of level.edges) {
        const e = edges[le.e];
        const route = [];
        const outward = [];
        for (let item = e.src; nodes[item].parent !== level.id; item = nodes[item].parent) {
          outward.push(levelOf.get(nodes[item].parent));
        }
        for (const lv of outward) append(route, lv.portOf.get(le.e * 2).route, lv.x, lv.y);
        append(route, level.routes.get(le.e), level.x, level.y);
        const inward = [];
        for (let item = e.dst; nodes[item].parent !== level.id; item = nodes[item].parent) {
          inward.push(levelOf.get(nodes[item].parent));
        }
        for (let i = inward.length - 1; i >= 0; i--) {
          append(route, inward[i].portOf.get(le.e * 2 + 1).route, inward[i].x, inward[i].y);
        }
        e.route = route;
        if (e.labelW > 0) {
          e.labelX += level.x;
          e.labelY += level.y;
        }
      }
    }
  }, "place");
  const style = styleOf(opt);
  keyed = flat;
  place();
  let crossings = -1;
  if (flat) {
    crossings = routeCrossings(nodes, edges, style);
    if (crossings > flatCrossings * FLAT_SLACK + FLAT_SPARE) {
      const first = snapshot(nodes, edges, order, total);
      keyed = false;
      place();
      const own = routeCrossings(nodes, edges, style);
      if (own >= crossings) {
        keyed = true;
        total = restore(first, nodes, edges, order);
      } else crossings = own;
    }
  }
  if (keyed === flat && ordered) {
    let again = false;
    for (const level of order) {
      if (level.id < 0) continue;
      const box = nodes[level.id];
      const vertical = level.dir === "TB" || level.dir === "BT";
      const end = opposite(startSide(level.dir));
      const seen = [];
      for (const port of level.ports) {
        if (port.side !== end) continue;
        const route = edges[port.e].route;
        const bx = level.x + port.px;
        const by = level.y + port.py;
        let at = -1;
        for (let k = 0; k < route.length && (at < 0 || port.out); k += 3)
          if (Math.abs(route[k] - bx) < 0.01 && Math.abs(route[k + 1] - by) < 0.01) at = k;
        if (at < 0) continue;
        const a = vertical ? 0 : 1;
        let next = port.out ? at + 3 : at - 3;
        while (next >= 0 && next < route.length && Math.abs(route[next + a] - route[at + a]) < IN_LINE2)
          next += port.out ? 3 : -3;
        if (next < 0 || next >= route.length) continue;
        port.hint = route[next + a] - (vertical ? box.x - box.w / 2 : box.y - box.h / 2);
        seen.push([vertical ? port.px : port.py, port.hint]);
      }
      seen.sort((p, q) => p[0] - q[0]);
      for (let i = 1; i < seen.length; i++) if (seen[i - 1][1] > seen[i][1]) again = true;
    }
    if (again) {
      const before = crossings >= 0 ? crossings : routeCrossings(nodes, edges, style);
      const first = before > 0 ? snapshot(nodes, edges, order, total) : void 0;
      if (first) {
        place();
        if (routeCrossings(nodes, edges, style) >= before)
          total = restore(first, nodes, edges, order);
      }
    }
  }
  for (const ei of stray) {
    const e = edges[ei];
    const a = nodes[e.src];
    const b = nodes[e.dst];
    e.route = [a.x, a.y, 0, b.x, b.y, 0];
    e.labelX = (a.x + b.x) / 2;
    e.labelY = (a.y + b.y) / 2;
  }
  for (const ei of loops) {
    const e = edges[ei];
    const node = nodes[e.src];
    e.labelX = node.x + node.w / 2 + 28 + e.labelW / 2;
    e.labelY = node.y;
  }
  return total;
}
__name(compoundLayout, "compoundLayout");

// src/rendering-util/layout-algorithms/layered/index.ts
var PORT_SEP = 20;
var LOOP = 26;
var LOOP_GAP = 6;
var CORNER = 12;
var LABEL_CLEAR = 4;
var LABEL_HOLD = 4;
var TURN_BREAKPOINT = 640;
var TIGHT_NODE = 0.5;
var TIGHT_RANK = 0.75;
var TIGHT_PAD = 0.6;
var MAX_MIN_LEN = 1e3;
var V12_SPACING = {
  nodeSpacing: 50,
  rankSpacing: 50,
  edgeSpacing: 20,
  diagramPadding: 8
};
function layoutSettings(config = {}) {
  return {
    spacing: {
      node: config.nodeSpacing ?? V12_SPACING.nodeSpacing,
      rank: config.rankSpacing ?? V12_SPACING.rankSpacing,
      edge: V12_SPACING.edgeSpacing
    },
    diagramPadding: config.diagramPadding ?? V12_SPACING.diagramPadding
  };
}
__name(layoutSettings, "layoutSettings");
var layered2 = /* @__PURE__ */ __name((graph, ctx) => {
  void ctx;
  check(graph);
  const available = graph.availableWidth;
  const across = tighten(graph, graph.direction);
  if (available === void 0 || !(available > 0) || across.width <= available) return across;
  if (!runsAcross(graph.direction) || available >= TURN_BREAKPOINT) return across;
  const down = tighten(graph, "TB");
  return down.width < across.width ? down : across;
}, "layered");
function runsAcross(dir) {
  return dir === "LR" || dir === "RL";
}
__name(runsAcross, "runsAcross");
function tighten(graph, dir) {
  const loose = run(graph, dir, false);
  const available = graph.availableWidth;
  if (available === void 0 || !(available > 0) || loose.width <= available) return loose;
  const tight = run(graph, dir, true);
  return tight.width < loose.width ? tight : loose;
}
__name(tighten, "tighten");
function finite(value, what) {
  if (!Number.isFinite(value) || value < 0) {
    throw new RangeError(`layout: ${what} must be a finite number >= 0, got ${value}`);
  }
}
__name(finite, "finite");
function check(graph) {
  const ids = /* @__PURE__ */ new Set();
  const add = /* @__PURE__ */ __name((id, what) => {
    if (ids.has(id)) throw new Error(`layout: duplicate ${what} id '${id}'`);
    ids.add(id);
  }, "add");
  for (const n of graph.nodes) {
    add(n.id, "node");
    finite(n.width, `width of node '${n.id}'`);
    finite(n.height, `height of node '${n.id}'`);
    if (n.span !== void 0) finite(n.span, `span of node '${n.id}'`);
  }
  for (const g of graph.groups) {
    add(g.id, "group");
    const { top, right, bottom, left } = g.padding;
    for (const v of [top, right, bottom, left]) finite(v, `padding of group '${g.id}'`);
    if (g.title) {
      finite(g.title.width, `title width of group '${g.id}'`);
      finite(g.title.height, `title height of group '${g.id}'`);
    }
  }
  const edges = /* @__PURE__ */ new Set();
  for (const e of graph.edges) {
    if (edges.has(e.id)) throw new Error(`layout: duplicate edge id '${e.id}'`);
    edges.add(e.id);
    if (!ids.has(e.source))
      throw new Error(`layout: edge '${e.id}' has unknown source '${e.source}'`);
    if (!ids.has(e.target))
      throw new Error(`layout: edge '${e.id}' has unknown target '${e.target}'`);
    finite(e.minLen, `minLen of edge '${e.id}'`);
    if (e.label) {
      finite(e.label.width, `label width of edge '${e.id}'`);
      finite(e.label.height, `label height of edge '${e.id}'`);
    }
  }
  const { node, rank: rank2, edge } = graph.spacing;
  finite(node, "spacing.node");
  finite(rank2, "spacing.rank");
  finite(edge, "spacing.edge");
  if (graph.diagramPadding !== void 0) finite(graph.diagramPadding, "diagramPadding");
  if (graph.headRoom !== void 0) finite(graph.headRoom, "headRoom");
}
__name(check, "check");
function run(graph, rootDir, tight) {
  const padScale = tight ? TIGHT_PAD : 1;
  const nodeCount = graph.nodes.length;
  const index = /* @__PURE__ */ new Map();
  const cnodes = [];
  graph.nodes.forEach((n, i) => {
    index.set(n.id, i);
    const c = cnode(n.width, n.height);
    c.seq = i;
    cnodes.push(c);
  });
  const padTops = [];
  graph.groups.forEach((g, j) => {
    index.set(g.id, nodeCount + j);
    const c = cnode(0, 0);
    c.isGroup = true;
    c.dir = g.direction;
    c.padX = Math.max(g.padding.left, g.padding.right) * padScale;
    const padTop = g.padding.top * padScale;
    padTops.push(padTop);
    c.padTop = padTop + (g.title?.height ?? 0);
    c.padBottom = g.padding.bottom * padScale;
    c.minW = (g.title?.width ?? 0) + 2 * c.padX;
    c.seq = nodeCount + j;
    c.span = Infinity;
    cnodes.push(c);
  });
  const parentOf = /* @__PURE__ */ __name((id) => {
    if (id === void 0) return -1;
    const p = index.get(id);
    return p !== void 0 && p >= nodeCount ? p : -1;
  }, "parentOf");
  graph.nodes.forEach((n, i) => cnodes[i].parent = parentOf(n.parent));
  graph.groups.forEach((g, j) => cnodes[nodeCount + j].parent = parentOf(g.parent));
  const ends = graph.edges.map((e) => [index.get(e.source), index.get(e.target)]);
  inheritCrossedDirections(cnodes, ends);
  const inner = ends.map(([src, dst], k) => {
    const out = holds(cnodes, src, dst);
    if (!out && !holds(cnodes, dst, src)) return void 0;
    const group = out ? src : dst;
    const dir = flowIn(cnodes, group, rootDir);
    const down = !runsAcross(dir);
    const label = graph.edges[k].label;
    const labelLen = label ? down ? label.height : label.width : 0;
    const c = cnodes[group];
    const atTop = down && out === (dir === "TB");
    const band = !down ? c.padX : atTop ? c.padTop : c.padBottom;
    const j = group - nodeCount;
    const title = atTop ? graph.groups[j].title : void 0;
    const skip = title ? padTops[j] / 2 + title.height : 0;
    const titleW = title ? title.width : 0;
    return { group, member: out ? dst : src, out, dir, band, skip, titleW, labelLen };
  });
  for (const edge of inner) {
    if (!edge || edge.labelLen === 0 && edge.skip === 0) continue;
    const c = cnodes[edge.group];
    const room = edge.band + edge.labelLen + (graph.headRoom ?? 0);
    if (runsAcross(edge.dir)) {
      c.minW += 2 * Math.max(0, room - c.padX);
      c.padX = Math.max(c.padX, room);
    } else if (edge.out === (edge.dir === "TB")) c.padTop = Math.max(c.padTop, room);
    else c.padBottom = Math.max(c.padBottom, room);
  }
  const sideways2 = /* @__PURE__ */ __name((i) => {
    let dir;
    const seen = /* @__PURE__ */ new Set();
    for (let p = cnodes[i].parent; p >= 0 && dir === void 0 && !seen.has(p); p = cnodes[p].parent) {
      seen.add(p);
      dir = cnodes[p].dir;
    }
    return runsAcross(dir ?? rootDir);
  }, "sideways");
  graph.nodes.forEach((n, i) => {
    const across = sideways2(i) ? n.height : n.width;
    cnodes[i].span = n.span ?? Math.max(0, across - 2 * CORNER);
  });
  const loopSide = new Uint8Array(cnodes.length);
  const loopCount = new Uint16Array(cnodes.length);
  const loopReach = new Float64Array(cnodes.length);
  const loopSlot = [];
  const cedges = graph.edges.map((e, k) => {
    const [src, dst] = ends[k];
    const labelW = e.label?.width ?? 0;
    const labelH = e.label?.height ?? 0;
    if (src === dst && src < nodeCount) {
      const c = cnodes[src];
      const across = sideways2(src) ? labelH : labelW;
      const grow = LOOP + (across > 0 ? across + LOOP_GAP : 0);
      loopSlot[k] = { index: loopCount[src], reach: loopReach[src] };
      loopCount[src]++;
      loopReach[src] += grow;
      if (sideways2(src)) {
        c.h += 2 * grow;
        loopSide[src] = 2;
      } else {
        c.w += 2 * grow;
        loopSide[src] = 1;
      }
    }
    return {
      src,
      dst,
      minlen: Math.min(MAX_MIN_LEN, Math.max(1, Math.round(e.minLen))),
      labelW,
      labelH,
      route: [],
      labelX: 0,
      labelY: 0
    };
  });
  const routing2 = graph.routing ?? "curved";
  const opt = {
    nodeSep: graph.spacing.node * (tight ? TIGHT_NODE : 1),
    edgeSep: graph.spacing.edge,
    rankSep: graph.spacing.rank * (tight ? TIGHT_RANK : 1),
    portSep: PORT_SEP,
    tracks: routing2 === "stepped",
    straight: routing2 === "straight",
    headRoom: graph.headRoom ?? 0
  };
  const total = compoundLayout(cnodes, cedges, rootDir, opt);
  const pad = graph.diagramPadding ?? 0;
  const nodes = /* @__PURE__ */ new Map();
  graph.nodes.forEach((n, i) => {
    const c = cnodes[i];
    nodes.set(n.id, { x: c.x + pad, y: c.y + pad, width: n.width, height: n.height });
  });
  const groups = /* @__PURE__ */ new Map();
  graph.groups.forEach((g, j) => {
    const c = cnodes[nodeCount + j];
    const x = c.x + pad;
    const y = c.y + pad;
    const top = y - c.h / 2;
    const titleY = top + padTops[j] / 2 + (g.title?.height ?? 0) / 2;
    groups.set(g.id, { x, y, width: c.w, height: c.h, title: { x, y: titleY } });
  });
  const box = /* @__PURE__ */ __name((i) => {
    const c = cnodes[i];
    const size2 = i < nodeCount ? graph.nodes[i] : { width: c.w, height: c.h };
    return { x: c.x + pad, y: c.y + pad, width: size2.width, height: size2.height };
  }, "box");
  const edges = /* @__PURE__ */ new Map();
  const deferred = [];
  graph.edges.forEach((e, k) => {
    const ce = cedges[k];
    const [src, dst] = ends[k];
    if (src === dst) {
      const slot = loopSlot[k] ?? { index: 0, reach: 0 };
      edges.set(
        e.id,
        selfLoop(
          box(src),
          loopSide[src] === 2,
          e.label,
          slot.reach,
          slot.index,
          loopCount[src] || 1
        )
      );
      return;
    }
    if (inner[k]) {
      deferred.push(k);
      return;
    }
    const points = [];
    for (let p = 0; p + 2 < ce.route.length; p += 3) {
      points.push({
        x: ce.route[p] + pad,
        y: ce.route[p + 1] + pad,
        axis: ce.route[p + 2] === 1 ? "h" : "v"
      });
    }
    const model = {
      points,
      ports: {
        source: sideOf(box(src), points[0], flowEnd(rootDir)),
        target: sideOf(box(dst), points[points.length - 1], flowStart(rootDir))
      }
    };
    if (ce.labelW > 0 || ce.labelH > 0) model.label = { x: ce.labelX + pad, y: ce.labelY + pad };
    edges.set(e.id, model);
  });
  for (const k of deferred) {
    const within = inner[k];
    const member = box(within.member);
    const group = box(within.group);
    const label = graph.edges[k].label;
    const taken = endsAt(member, within, edges.values());
    const across = freeAcross(member, within, taken);
    const labelAt = label ? labelAcross(group, within, label, across, taken) : across;
    edges.set(graph.edges[k].id, innerEdge(group, member, within, label, across, labelAt));
  }
  return {
    width: total.width + 2 * pad,
    height: total.height + 2 * pad,
    nodes,
    edges,
    groups,
    direction: rootDir
  };
}
__name(run, "run");
function holds(cnodes, g, i) {
  if (g === i || !cnodes[g].isGroup) return false;
  const seen = /* @__PURE__ */ new Set();
  for (let p = cnodes[i].parent; p >= 0 && !seen.has(p); p = cnodes[p].parent) {
    if (p === g) return true;
    seen.add(p);
  }
  return false;
}
__name(holds, "holds");
function flowIn(cnodes, g, rootDir) {
  const seen = /* @__PURE__ */ new Set();
  for (let p = g; p >= 0 && !seen.has(p); p = cnodes[p].parent) {
    seen.add(p);
    const dir = cnodes[p].dir;
    if (dir) return dir;
  }
  return rootDir;
}
__name(flowIn, "flowIn");
function innerEdge(group, member, { out, dir, band, skip, titleW, labelLen }, label, across, labelAt) {
  const { down, side, face } = innerFace(member, out, dir);
  const centre = down ? group.y : group.x;
  const border = centre + side * (down ? group.height : group.width) / 2;
  const at = /* @__PURE__ */ __name((along) => down ? { x: across, y: along, axis: "v" } : { x: along, y: across, axis: "h" }, "at");
  const underTitle = down && Math.abs(across - group.x) < titleW / 2;
  const edge = underTitle ? border - side * skip : border;
  const [from, to] = out ? [edge, face] : [face, edge];
  const model = {
    points: [at(from), at(to)],
    ports: {
      source: out ? flowStart(dir) : flowEnd(dir),
      target: out ? flowStart(dir) : flowEnd(dir)
    }
  };
  if (label) {
    const along = border - side * (band + labelLen / 2);
    model.label = down ? { x: labelAt, y: along } : { x: along, y: labelAt };
  }
  return model;
}
__name(innerEdge, "innerEdge");
function innerFace(member, out, dir) {
  const down = !runsAcross(dir);
  const sign = dir === "TB" || dir === "LR" ? 1 : -1;
  const side = out ? -sign : sign;
  const face = (down ? member.y : member.x) + side * (down ? member.height : member.width) / 2;
  return { down, side, face };
}
__name(innerFace, "innerFace");
function endsAt(member, { out, dir }, drawn) {
  const { down, face } = innerFace(member, out, dir);
  const centre = down ? member.x : member.y;
  const half = (down ? member.width : member.height) / 2;
  const along = /* @__PURE__ */ __name((p) => down ? p.y : p.x, "along");
  const acrossOf = /* @__PURE__ */ __name((p) => down ? p.x : p.y, "acrossOf");
  const taken = [];
  for (const edge of drawn) {
    for (const p of [edge.points[0], edge.points[edge.points.length - 1]]) {
      if (!p || Math.abs(along(p) - face) > 1 || Math.abs(acrossOf(p) - centre) > half + 1) {
        continue;
      }
      taken.push(acrossOf(p));
    }
  }
  return taken;
}
__name(endsAt, "endsAt");
var gapTo = /* @__PURE__ */ __name((x, taken) => taken.reduce((min, t) => Math.min(min, Math.abs(x - t)), Infinity), "gapTo");
function freeAcross(member, { dir }, taken) {
  const down = !runsAcross(dir);
  const centre = down ? member.x : member.y;
  const half = (down ? member.width : member.height) / 2;
  const gap = /* @__PURE__ */ __name((x) => gapTo(x, taken), "gap");
  if (gap(centre) >= PORT_SEP) return centre;
  const reach = Math.max(0, half - Math.min(CORNER, half / 2));
  let best = centre;
  for (let step = 1; step * PORT_SEP <= reach + 1e-6; step++) {
    for (const x of [centre + step * PORT_SEP, centre - step * PORT_SEP]) {
      if (gap(x) >= PORT_SEP) return x;
      if (gap(x) > gap(best)) best = x;
    }
  }
  for (const x of [centre + reach, centre - reach]) if (gap(x) > gap(best)) best = x;
  return best;
}
__name(freeAcross, "freeAcross");
function labelAcross(group, { dir }, label, across, taken) {
  const down = !runsAcross(dir);
  const half = (down ? label.width : label.height) / 2;
  const clear = half + LABEL_CLEAR;
  const room = (down ? group.width : group.height) / 2 - half;
  const centre = down ? group.x : group.y;
  const [lo, hi] = room >= 0 ? [centre - room, centre + room] : [centre, centre];
  const slide = Math.max(0, half - LABEL_HOLD);
  const fits = /* @__PURE__ */ __name((x) => x >= lo - 1e-6 && x <= hi + 1e-6 && Math.abs(x - across) <= slide + 1e-6, "fits");
  const gap = /* @__PURE__ */ __name((x) => gapTo(x, taken), "gap");
  if (taken.length === 0 || gap(across) >= clear && fits(across)) return across;
  const options = [across, ...taken.flatMap((t) => [t - clear, t + clear])].filter(fits);
  options.sort((a, b) => Math.abs(a - across) - Math.abs(b - across));
  const free = options.find((x) => gap(x) >= clear);
  if (free !== void 0) return free;
  const clamp = /* @__PURE__ */ __name((x) => Math.min(hi, Math.max(lo, x)), "clamp");
  return [clamp(across), ...options].reduce((best, x) => gap(x) > gap(best) ? x : best);
}
__name(labelAcross, "labelAcross");
var FLOW_START = {
  TB: "top",
  BT: "bottom",
  LR: "left",
  RL: "right"
};
var FLOW_END = { TB: "bottom", BT: "top", LR: "right", RL: "left" };
function flowStart(dir) {
  return FLOW_START[dir];
}
__name(flowStart, "flowStart");
function flowEnd(dir) {
  return FLOW_END[dir];
}
__name(flowEnd, "flowEnd");
function sideOf(b, p, fallback) {
  if (!p) return fallback;
  const dx = p.x - b.x;
  const dy = p.y - b.y;
  const rx = b.width > 0 ? Math.abs(dx) / (b.width / 2) : Math.abs(dx);
  const ry = b.height > 0 ? Math.abs(dy) / (b.height / 2) : Math.abs(dy);
  if (rx < 1e-6 && ry < 1e-6) return fallback;
  if (ry >= rx) return dy < 0 ? "top" : "bottom";
  return dx < 0 ? "left" : "right";
}
__name(sideOf, "sideOf");
function selfLoop(b, below, label, reach = 0, index = 0, count = 1) {
  const spread2 = (index + 1) / (count + 1) / 2;
  if (below) {
    const y = b.y + b.height / 2;
    const out2 = y + reach + LOOP;
    const x0 = b.x - b.width * spread2;
    const x1 = b.x + b.width * spread2;
    return {
      points: [
        { x: x0, y, axis: "v" },
        { x: x0, y: out2, axis: "v" },
        { x: x1, y: out2, axis: "h" },
        { x: x1, y, axis: "v" }
      ],
      ...label ? { label: { x: b.x, y: out2 + LOOP_GAP + label.height / 2 } } : {},
      ports: { source: "bottom", target: "bottom" }
    };
  }
  const x = b.x + b.width / 2;
  const out = x + reach + LOOP;
  const y0 = b.y - b.height * spread2;
  const y1 = b.y + b.height * spread2;
  return {
    points: [
      { x, y: y0, axis: "h" },
      { x: out, y: y0, axis: "h" },
      { x: out, y: y1, axis: "v" },
      { x, y: y1, axis: "h" }
    ],
    ...label ? { label: { x: out + LOOP_GAP + label.width / 2, y: b.y } } : {},
    ports: { source: "right", target: "right" }
  };
}
__name(selfLoop, "selfLoop");

// src/rendering-util/layout-algorithms/layered/layoutData.ts
var LABEL_W = 12;
var LABEL_H = 4;
var HEAD_ROOM = 7;
var GROUP_PAD = 20;
var TITLE_GAP = 12;
var DIRS = { TB: "TB", TD: "TB", BT: "BT", LR: "LR", RL: "RL" };
function direction(data) {
  return DIRS[String(data.direction ?? "").toUpperCase()] ?? "TB";
}
__name(direction, "direction");
var sideways = /* @__PURE__ */ __name((dir) => dir === "LR" || dir === "RL", "sideways");
var roundSpan = /* @__PURE__ */ __name((w, h, s) => (s ? h : w) * 0.6, "roundSpan");
var SPANS = new Map([
  ...[
    "circle",
    "circ",
    "doublecircle",
    "double-circle",
    "dbl-circ",
    "ellipse",
    "diamond",
    "diam",
    "decision",
    "question",
    "sm-circ",
    "small-circle",
    "start",
    "fr-circ",
    "framed-circle",
    "stop",
    "f-circ",
    "filled-circle",
    "junction",
    "cross-circ",
    "crossed-circle",
    "summary",
    // State diagram start, end and choice; mindmap cloud and bang.
    "stateStart",
    "stateEnd",
    "choice",
    "cloud",
    "bang"
  ].map((name) => [name, roundSpan]),
  ...["stadium", "terminal", "pill"].map(
    (name) => [name, ((w, h, s) => s ? h * 0.6 : w - h)]
  ),
  ...["hexagon", "hex", "prepare"].map(
    (name) => [name, ((w, h, s) => s ? h * 0.5 : w - h / 2 - 12)]
  )
]);
var size = /* @__PURE__ */ __name((value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0, "size");
var ROUTINGS = /* @__PURE__ */ new Set(["rounded", "curved", "stepped", "straight"]);
function routing(data) {
  const chosen = data.config?.layered?.edgeRouting;
  return chosen && ROUTINGS.has(chosen) ? chosen : "rounded";
}
__name(routing, "routing");
var STEPS = /* @__PURE__ */ new Set(["step", "stepBefore", "stepAfter"]);
function drawnCurve(mode, curve) {
  if (mode === "rounded") {
    return "rounded";
  }
  if (mode === "straight") {
    return "linear";
  }
  if (mode === "stepped") {
    return curve && STEPS.has(curve) ? curve : "step";
  }
  return curve;
}
__name(drawnCurve, "drawnCurve");
function toLayoutGroup(n, data, groupIds) {
  const margin = data.config?.flowchart?.subGraphTitleMargin;
  const titleWidth = size(n.labelBBox?.width);
  const titleHeight = size(n.labelBBox?.height);
  const titled = titleWidth > 0 && titleHeight > 0;
  const group = {
    id: n.id,
    padding: {
      top: titled ? size(margin?.top) + size(margin?.bottom) + TITLE_GAP : GROUP_PAD,
      right: GROUP_PAD,
      bottom: GROUP_PAD,
      left: GROUP_PAD
    }
  };
  if (n.parentId && groupIds.has(n.parentId)) {
    group.parent = n.parentId;
  }
  const dir = n.dir ? DIRS[String(n.dir).toUpperCase()] : void 0;
  if (dir) {
    group.direction = dir;
  }
  if (titled) {
    group.title = { width: titleWidth, height: titleHeight };
  }
  return group;
}
__name(toLayoutGroup, "toLayoutGroup");
function checkNesting(groups) {
  const parentOf = new Map(groups.map((g) => [g.id, g.parent]));
  for (const { id } of groups) {
    const seen = /* @__PURE__ */ new Set([id]);
    for (let p = parentOf.get(id); p !== void 0; p = parentOf.get(p)) {
      if (seen.has(p)) {
        throw new Error(`layered: subgraph '${p}' is nested inside itself`);
      }
      seen.add(p);
    }
  }
}
__name(checkNesting, "checkNesting");
function hasLabel(edge) {
  return typeof edge.label === "string" ? edge.label.trim().length > 0 : Boolean(edge.label);
}
__name(hasLabel, "hasLabel");
function toLayoutGraph(data) {
  const dir = direction(data);
  const flowchart = data.config?.flowchart;
  const { spacing } = layoutSettings({
    nodeSpacing: size(data.nodeSpacing) || size(flowchart?.nodeSpacing) || void 0,
    rankSpacing: size(data.rankSpacing) || size(flowchart?.rankSpacing) || void 0
  });
  const groupIds = new Set(data.nodes.filter((n) => n.isGroup).map((n) => n.id));
  const groups = data.nodes.filter((n) => n.isGroup).map((n) => toLayoutGroup(n, data, groupIds));
  checkNesting(groups);
  const nodes = [];
  const ids = new Set(groupIds);
  for (const n of data.nodes) {
    if (n.isGroup) {
      continue;
    }
    ids.add(n.id);
    const width = size(n.width);
    const height = size(n.height);
    const node = { id: n.id, width, height };
    if (n.parentId && groupIds.has(n.parentId)) {
      node.parent = n.parentId;
    }
    const span = n.shape ? SPANS.get(n.shape) : void 0;
    if (span) {
      node.span = Math.max(0, span(width, height, sideways(dir)));
    }
    nodes.push(node);
  }
  const edges = [];
  for (const e of data.edges) {
    if (e.isLayoutOnly || !e.start || !e.end || !ids.has(e.start) || !ids.has(e.end)) {
      continue;
    }
    const edge = {
      id: e.id,
      source: e.start,
      target: e.end,
      minLen: Math.max(1, Math.round(size(e.minlen) || 1))
    };
    const lw = size(e.width);
    if (hasLabel(e) && lw > 0) {
      edge.label = { width: lw + LABEL_W, height: size(e.height) + LABEL_H };
    }
    edges.push(edge);
  }
  const mode = routing(data);
  return {
    direction: dir,
    nodes,
    edges,
    groups,
    spacing,
    diagramPadding: 0,
    // Rounded corners need the same right-angle tracks as stepped routes.
    routing: mode === "rounded" ? "stepped" : mode,
    headRoom: HEAD_ROOM
  };
}
__name(toLayoutGraph, "toLayoutGraph");
function applyLayoutModel(data, model) {
  const mode = routing(data);
  for (const n of data.nodes) {
    const placed = model.nodes.get(n.id);
    if (placed) {
      n.x = placed.x;
      n.y = placed.y;
      continue;
    }
    const cluster = n.isGroup ? model.groups.get(n.id) : void 0;
    if (cluster) {
      n.x = cluster.x;
      n.y = cluster.y;
      n.width = cluster.width;
      n.height = cluster.height;
    }
  }
  for (const e of data.edges) {
    const routed = model.edges.get(e.id);
    if (!routed) {
      continue;
    }
    e.points = routed.points.map((p) => ({ x: p.x, y: p.y, axis: p.axis }));
    e.curve = drawnCurve(mode, e.curve);
    if (routed.label) {
      e.x = routed.label.x;
      e.y = routed.label.y;
    }
  }
}
__name(applyLayoutModel, "applyLayoutModel");
var hasOutline = /* @__PURE__ */ __name((n) => n !== void 0 && !n.isGroup && typeof n.intersect === "function" && Number.isFinite(n.x) && Number.isFinite(n.y), "hasOutline");
function inside(n, p) {
  const d = Math.hypot(p.x - n.x, p.y - n.y);
  if (d < 1e-6) {
    return true;
  }
  const o = n.intersect(p);
  const r = Math.hypot(o.x - n.x, o.y - n.y);
  return Number.isFinite(r) && d <= r + 1e-6;
}
__name(inside, "inside");
function onOutline(n, end) {
  const onTopOrBottom = Math.abs(Math.abs(end.y - n.y) - size(n.height) / 2) < 0.5;
  const onLeftOrRight = Math.abs(Math.abs(end.x - n.x) - size(n.width) / 2) < 0.5;
  if (!onTopOrBottom && !onLeftOrRight) {
    return end;
  }
  const met = firstMet(n, end, onTopOrBottom);
  if (met) {
    return met;
  }
  if (inside(n, end)) {
    return end;
  }
  const to = onTopOrBottom ? { x: end.x, y: n.y } : { x: n.x, y: end.y };
  if (!inside(n, to)) {
    const o = n.intersect(end);
    return Number.isFinite(o.x) && Number.isFinite(o.y) ? { ...end, x: o.x, y: o.y } : end;
  }
  let outside = 0;
  let within = 1;
  for (let i = 0; i < 40; i++) {
    const t = (outside + within) / 2;
    const p = { x: end.x + (to.x - end.x) * t, y: end.y + (to.y - end.y) * t };
    if (inside(n, p)) {
      within = t;
    } else {
      outside = t;
    }
  }
  return {
    ...end,
    x: end.x + (to.x - end.x) * within,
    y: end.y + (to.y - end.y) * within
  };
}
__name(onOutline, "onOutline");
function firstMet(n, end, onTopOrBottom) {
  const far = onTopOrBottom ? { x: end.x, y: 2 * n.y - end.y } : { x: 2 * n.x - end.x, y: end.y };
  const o = n.intersect(withLineIntersectionOrigin(end, far));
  if (!o || !Number.isFinite(o.x) || !Number.isFinite(o.y)) {
    return void 0;
  }
  if (o === n || o.x === n.x && o.y === n.y) {
    return void 0;
  }
  const onRoute = onTopOrBottom ? Math.abs(o.x - end.x) < 0.5 : Math.abs(o.y - end.y) < 0.5;
  const inBox = Math.abs(o.x - n.x) <= size(n.width) / 2 + 0.5 && Math.abs(o.y - n.y) <= size(n.height) / 2 + 0.5;
  if (!onRoute || !inBox) {
    return void 0;
  }
  return onTopOrBottom ? { ...end, y: o.y } : { ...end, x: o.x };
}
__name(firstMet, "firstMet");
function clipRouteEnds(data) {
  const byId = new Map(data.nodes.map((n) => [n.id, n]));
  for (const e of data.edges) {
    const points = e.points;
    if (!isAxisTaggedRoute(points)) {
      continue;
    }
    const src = byId.get(e.start ?? "");
    const dst = byId.get(e.end ?? "");
    const next = [...points];
    if (hasOutline(src)) {
      next[0] = onOutline(src, next[0]);
    }
    if (hasOutline(dst)) {
      next[next.length - 1] = onOutline(dst, next[next.length - 1]);
    }
    e.points = next;
  }
}
__name(clipRouteEnds, "clipRouteEnds");
function runLayeredLayoutCore(data) {
  const model = layered2(toLayoutGraph(data));
  applyLayoutModel(data, model);
  clipRouteEnds(data);
  return model;
}
__name(runLayeredLayoutCore, "runLayeredLayoutCore");

// src/rendering-util/layout-algorithms/layered/render.ts
var renderLayered = createCommonLayoutRenderer({
  // The engine sizes a subgraph from its title, so the title is measured as it is painted: on
  // one line, not wrapped at `flowchart.wrappingWidth`.
  measureLayout: /* @__PURE__ */ __name((data4Layout, context) => defaultMeasureLayout(data4Layout, context, { unwrapGroupLabels: true }), "measureLayout"),
  runLayoutCore: runLayeredLayoutCore,
  paintOptions: { getNodes: /* @__PURE__ */ __name((data) => paintOrder(data.nodes), "getNodes") },
  // Crossings get hops once every edge is drawn, as the elk layout draws them (#8835).
  afterPaint: applyLayeredLineJumps
});
function paintOrder(nodes) {
  const parentOf = new Map(nodes.filter((n) => n.isGroup).map((n) => [n.id, n.parentId]));
  const depth = /* @__PURE__ */ __name((id) => {
    const seen = /* @__PURE__ */ new Set([id]);
    let d = 0;
    for (let p = parentOf.get(id); p !== void 0 && parentOf.has(p) && !seen.has(p); ) {
      seen.add(p);
      d++;
      p = parentOf.get(p);
    }
    return d;
  }, "depth");
  const groups = nodes.map((n, i) => ({ n, i, d: n.isGroup ? depth(n.id) : 0 })).filter(({ n }) => n.isGroup).sort((a, b) => a.d - b.d || a.i - b.i).map(({ n }) => n);
  return [...groups, ...nodes.filter((n) => !n.isGroup)];
}
__name(paintOrder, "paintOrder");
function copyPlain(value) {
  if (Array.isArray(value)) {
    return value.map(copyPlain);
  }
  if (value !== null && typeof value === "object") {
    const proto = Object.getPrototypeOf(value);
    if (proto === Object.prototype || proto === null) {
      const out = {};
      for (const [key, v] of Object.entries(value)) {
        if (key === "__proto__") {
          continue;
        }
        out[key] = copyPlain(v);
      }
      return out;
    }
  }
  return value;
}
__name(copyPlain, "copyPlain");
function snapshot2(data) {
  const copies = /* @__PURE__ */ new Map();
  for (const item of [...data.nodes, ...data.edges]) {
    copies.set(item, copyPlain({ ...item }));
  }
  return { nodes: [...data.nodes], edges: [...data.edges], copies };
}
__name(snapshot2, "snapshot");
function restore2(data, { nodes, edges, copies }) {
  for (const [item, copy] of copies) {
    const target = item;
    for (const key of Object.keys(target)) {
      if (!(key in copy)) {
        delete target[key];
      }
    }
    Object.assign(target, copyPlain(copy));
  }
  data.nodes = nodes;
  data.edges = edges;
}
__name(restore2, "restore");
async function render(data4Layout, svg, helpers, options) {
  const before = snapshot2(data4Layout);
  try {
    await renderLayered(data4Layout, svg, helpers, options);
  } catch (error) {
    if (layeredThrowsOnFailure()) {
      throw error;
    }
    const reason = error instanceof Error ? error.message : String(error);
    log.warn(`Layered layout failed (${reason}); falling back to dagre.`);
    restore2(data4Layout, before);
    clearLayoutRenderState();
    svg.select("g").selectAll("*").remove();
    svg.attr("data-layout-fallback", "dagre");
    data4Layout.layoutAlgorithm = "dagre";
    const dagre = await import("./dagre-7STDYROV.mjs");
    await dagre.render(data4Layout, svg, helpers, options);
  }
}
__name(render, "render");
export {
  render,
  setLayeredThrowsOnFailure
};