import { r as E } from "./_baseUniq.js";
import { o as k } from "./_basePickBy.js";
import { t as j } from "./layout.js";
import { t as F } from "./clone.js";
import { t as B } from "./graph.js";
import { n as w, r } from "./chunk-AGHRB4JF.js";
import { b as Y } from "./chunk-ICPOFSXX.js";
import { n as H } from "./chunk-ZZ45TVLE.js";
import { a as _, c as O, i as V, l as U, n as $, t as q, u as z } from "./chunk-5FUZZQ4R.js";
import { a as K, i as Q, n as W, r as Z, t as I } from "./chunk-ENJZ2VHE.js";
function v(e) {
  var t = {
    options: {
      directed: e.isDirected(),
      multigraph: e.isMultigraph(),
      compound: e.isCompound()
    },
    nodes: L(e),
    edges: ee(e)
  };
  return E(e.graph()) || (t.value = F(e.graph())), t;
}
function L(e) {
  return k(e.nodes(), function(t) {
    var n = e.node(t), a = e.parent(t), s = { v: t };
    return E(n) || (s.value = n), E(a) || (s.parent = a), s;
  });
}
function ee(e) {
  return k(e.edges(), function(t) {
    var n = e.edge(t), a = {
      v: t.v,
      w: t.w
    };
    return E(t.name) || (a.name = t.name), E(n) || (a.value = n), a;
  });
}
var c = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map(), A = /* @__PURE__ */ new Map(), ne = /* @__PURE__ */ w(() => {
  p.clear(), A.clear(), c.clear();
}, "clear"), S = /* @__PURE__ */ w((e, t) => {
  const n = p.get(t) || [];
  return r.trace("In isDescendant", t, " ", e, " = ", n.includes(e)), n.includes(e);
}, "isDescendant"), te = /* @__PURE__ */ w((e, t) => {
  const n = p.get(t) || [];
  return r.info("Descendants of ", t, " is ", n), r.info("Edge is ", e), e.v === t || e.w === t ? !1 : n ? n.includes(e.v) || S(e.v, t) || S(e.w, t) || n.includes(e.w) : (r.debug("Tilt, ", t, ",not in descendants"), !1);
}, "edgeInCluster"), J = /* @__PURE__ */ w((e, t, n, a) => {
  r.warn("Copying children of ", e, "root", a, "data", t.node(e), a);
  const s = t.children(e) || [];
  e !== a && s.push(e), r.warn("Copying (nodes) clusterId", e, "nodes", s), s.forEach((o) => {
    if (t.children(o).length > 0) J(o, t, n, a);
    else {
      const d = t.node(o);
      r.info("cp ", o, " to ", a, " with parent ", e), n.setNode(o, d), a !== t.parent(o) && (r.warn("Setting parent", o, t.parent(o)), n.setParent(o, t.parent(o))), e !== a && o !== e ? (r.debug("Setting parent", o, e), n.setParent(o, e)) : (r.info("In copy ", e, "root", a, "data", t.node(e), a), r.debug("Not Setting parent for node=", o, "cluster!==rootId", e !== a, "node!==clusterId", o !== e));
      const l = t.edges(o);
      r.debug("Copying Edges", l), l.forEach((u) => {
        r.info("Edge", u);
        const m = t.edge(u.v, u.w, u.name);
        r.info("Edge data", m, a);
        try {
          te(u, a) ? (r.info("Copying as ", u.v, u.w, m, u.name), n.setEdge(u.v, u.w, m, u.name), r.info("newGraph edges ", n.edges(), n.edge(n.edges()[0]))) : r.info("Skipping copy of edge ", u.v, "-->", u.w, " rootId: ", a, " clusterId:", e);
        } catch (h) {
          r.error(h);
        }
      });
    }
    r.debug("Removing node", o), t.removeNode(o);
  });
}, "copy"), R = /* @__PURE__ */ w((e, t) => {
  const n = t.children(e);
  let a = [...n];
  for (const s of n)
    A.set(s, e), a = [...a, ...R(s, t)];
  return a;
}, "extractDescendants"), ie = /* @__PURE__ */ w((e, t, n) => {
  const a = e.edges().filter((l) => l.v === t || l.w === t), s = e.edges().filter((l) => l.v === n || l.w === n), o = a.map((l) => ({
    v: l.v === t ? n : l.v,
    w: l.w === t ? t : l.w
  })), d = s.map((l) => ({
    v: l.v,
    w: l.w
  }));
  return o.filter((l) => d.some((u) => l.v === u.v && l.w === u.w));
}, "findCommonEdges"), N = /* @__PURE__ */ w((e, t, n) => {
  const a = t.children(e);
  if (r.trace("Searching children of id ", e, a), a.length < 1) return e;
  let s;
  for (const o of a) {
    const d = N(o, t, n), l = ie(t, n, d);
    if (d) if (l.length > 0) s = d;
    else return d;
  }
  return s;
}, "findNonClusterChild"), P = /* @__PURE__ */ w((e) => !c.has(e) || !c.get(e).externalConnections ? e : c.has(e) ? c.get(e).id : e, "getAnchorId"), re = /* @__PURE__ */ w((e, t) => {
  if (!e || t > 10) {
    r.debug("Opting out, no graph ");
    return;
  } else r.debug("Opting in, graph ");
  e.nodes().forEach(function(n) {
    e.children(n).length > 0 && (r.warn("Cluster identified", n, " Replacement id in edges: ", N(n, e, n)), p.set(n, R(n, e)), c.set(n, {
      id: N(n, e, n),
      clusterData: e.node(n)
    }));
  }), e.nodes().forEach(function(n) {
    const a = e.children(n), s = e.edges();
    a.length > 0 ? (r.debug("Cluster identified", n, p), s.forEach((o) => {
      S(o.v, n) ^ S(o.w, n) && (r.warn("Edge: ", o, " leaves cluster ", n), r.warn("Descendants of XXX ", n, ": ", p.get(n)), c.get(n).externalConnections = !0);
    })) : r.debug("Not a cluster ", n, p);
  });
  for (let n of c.keys()) {
    const a = c.get(n).id, s = e.parent(a);
    s !== n && c.has(s) && !c.get(s).externalConnections && (c.get(n).id = s);
  }
  e.edges().forEach(function(n) {
    const a = e.edge(n);
    r.warn("Edge " + n.v + " -> " + n.w + ": " + JSON.stringify(n)), r.warn("Edge " + n.v + " -> " + n.w + ": " + JSON.stringify(e.edge(n)));
    let s = n.v, o = n.w;
    if (r.warn("Fix XXX", c, "ids:", n.v, n.w, "Translating: ", c.get(n.v), " --- ", c.get(n.w)), c.get(n.v) || c.get(n.w)) {
      if (r.warn("Fixing and trying - removing XXX", n.v, n.w, n.name), s = P(n.v), o = P(n.w), e.removeEdge(n.v, n.w, n.name), s !== n.v) {
        const d = e.parent(s);
        c.get(d).externalConnections = !0, a.fromCluster = n.v;
      }
      if (o !== n.w) {
        const d = e.parent(o);
        c.get(d).externalConnections = !0, a.toCluster = n.w;
      }
      r.warn("Fix Replacing with XXX", s, o, n.name), e.setEdge(s, o, a, n.name);
    }
  }), r.warn("Adjusted Graph", v(e)), T(e, 0), r.trace(c);
}, "adjustClustersAndEdges"), T = /* @__PURE__ */ w((e, t) => {
  if (r.warn("extractor - ", t, v(e), e.children("D")), t > 10) {
    r.error("Bailing out");
    return;
  }
  let n = e.nodes(), a = !1;
  for (const s of n) {
    const o = e.children(s);
    a = a || o.length > 0;
  }
  if (!a) {
    r.debug("Done, no node has children", e.nodes());
    return;
  }
  r.debug("Nodes = ", n, t);
  for (const s of n)
    if (r.debug("Extracting node", s, c, c.has(s) && !c.get(s).externalConnections, !e.parent(s), e.node(s), e.children("D"), " Depth ", t), !c.has(s)) r.debug("Not a cluster", s, t);
    else if (!c.get(s).externalConnections && e.children(s) && e.children(s).length > 0) {
      r.warn("Cluster without external connections, without a parent and with children", s, t);
      let o = e.graph().rankdir === "TB" ? "LR" : "TB";
      c.get(s)?.clusterData?.dir && (o = c.get(s).clusterData.dir, r.warn("Fixing dir", c.get(s).clusterData.dir, o));
      const d = new B({
        multigraph: !0,
        compound: !0
      }).setGraph({
        rankdir: o,
        nodesep: 50,
        ranksep: 50,
        marginx: 8,
        marginy: 8
      }).setDefaultEdgeLabel(function() {
        return {};
      });
      r.warn("Old graph before copy", v(e)), J(s, e, d, s), e.setNode(s, {
        clusterNode: !0,
        id: s,
        clusterData: c.get(s).clusterData,
        label: c.get(s).label,
        graph: d
      }), r.warn("New graph after copy node: (", s, ")", v(d)), r.debug("Old graph after copy", v(e));
    } else
      r.warn("Cluster ** ", s, " **not meeting the criteria !externalConnections:", !c.get(s).externalConnections, " no parent: ", !e.parent(s), " children ", e.children(s) && e.children(s).length > 0, e.children("D"), t), r.debug(c);
  n = e.nodes(), r.warn("New list of nodes", n);
  for (const s of n) {
    const o = e.node(s);
    r.warn(" Now next level", s, o), o?.clusterNode && T(o.graph, t + 1);
  }
}, "extractor"), G = /* @__PURE__ */ w((e, t) => {
  if (t.length === 0) return [];
  let n = Object.assign([], t);
  return t.forEach((a) => {
    const s = G(e, e.children(a));
    n = [...n, ...s];
  }), n;
}, "sorter"), se = /* @__PURE__ */ w((e) => G(e, e.children()), "sortNodesByHierarchy"), M = /* @__PURE__ */ w(async (e, t, n, a, s, o) => {
  r.warn("Graph in recursive render:XAX", v(t), s);
  const d = t.graph().rankdir;
  r.trace("Dir in recursive render - dir:", d);
  const l = e.insert("g").attr("class", "root");
  t.nodes() ? r.info("Recursive render XXX", t.nodes()) : r.info("No nodes found for", t), t.edges().length > 0 && r.info("Recursive edges", t.edge(t.edges()[0]));
  const u = l.insert("g").attr("class", "clusters"), m = l.insert("g").attr("class", "edgePaths"), h = l.insert("g").attr("class", "edgeLabels"), y = l.insert("g").attr("class", "nodes");
  await Promise.all(t.nodes().map(async function(f) {
    const i = t.node(f);
    if (s !== void 0) {
      const g = JSON.parse(JSON.stringify(s.clusterData));
      r.trace(`Setting data for parent cluster XXX
 Node.id = `, f, `
 data=`, g.height, `
Parent cluster`, s.height), t.setNode(s.id, g), t.parent(f) || (r.trace("Setting parent", f, s.id), t.setParent(f, s.id, g));
    }
    if (r.info("(Insert) Node XXX" + f + ": " + JSON.stringify(t.node(f))), i?.clusterNode) {
      r.info("Cluster identified XBX", f, i.width, t.node(f));
      const { ranksep: g, nodesep: C } = t.graph();
      i.graph.setGraph({
        ...i.graph.graph(),
        ranksep: g + 25,
        nodesep: C
      });
      const x = await M(y, i.graph, n, a, t.node(f), o), D = x.elem;
      z(i, D), i.diff = x.diff || 0, r.info("New compound node after recursive render XAX", f, "width", i.width, "height", i.height), U(D, i);
    } else t.children(f).length > 0 ? (r.trace("Cluster - the non recursive path XBX", f, i.id, i, i.width, "Graph:", t), r.trace(N(i.id, t)), c.set(i.id, {
      id: N(i.id, t),
      node: i
    })) : (r.trace("Node - the non recursive path XAX", f, y, t.node(f), d), await _(y, t.node(f), {
      config: o,
      dir: d
    }));
  })), await (/* @__PURE__ */ w(async () => {
    const f = t.edges().map(async function(i) {
      const g = t.edge(i.v, i.w, i.name);
      r.info("Edge " + i.v + " -> " + i.w + ": " + JSON.stringify(i)), r.info("Edge " + i.v + " -> " + i.w + ": ", i, " ", JSON.stringify(t.edge(i))), r.info("Fix", c, "ids:", i.v, i.w, "Translating: ", c.get(i.v), c.get(i.w)), await Z(h, g);
    });
    await Promise.all(f);
  }, "processEdges"))(), r.info("Graph before layout:", JSON.stringify(v(t))), r.info("############################################# XXX"), r.info("###                Layout                 ### XXX"), r.info("############################################# XXX"), j(t), r.info("Graph after layout:", JSON.stringify(v(t)));
  let X = 0, { subGraphTitleTotalMargin: b } = H(o);
  return await Promise.all(se(t).map(async function(f) {
    const i = t.node(f);
    if (r.info("Position XBX => " + f + ": (" + i.x, "," + i.y, ") width: ", i.width, " height: ", i.height), i?.clusterNode)
      i.y += b, r.info("A tainted cluster node XBX1", f, i.id, i.width, i.height, i.x, i.y, t.parent(f)), c.get(i.id).node = i, O(i);
    else if (t.children(f).length > 0) {
      r.info("A pure cluster node XBX1", f, i.id, i.x, i.y, i.width, i.height, t.parent(f)), i.height += b, t.node(i.parentId);
      const g = i?.padding / 2 || 0, C = i?.labelBBox?.height || 0, x = C - g || 0;
      r.debug("OffsetY", x, "labelHeight", C, "halfPadding", g), await V(u, i), c.get(i.id).node = i;
    } else {
      const g = t.node(i.parentId);
      i.y += b / 2, r.info("A regular node XBX1 - using the padding", i.id, "parent", i.parentId, i.width, i.height, i.x, i.y, "offsetY", i.offsetY, "parent", g, g?.offsetY, i), O(i);
    }
  })), t.edges().forEach(function(f) {
    const i = t.edge(f);
    r.info("Edge " + f.v + " -> " + f.w + ": " + JSON.stringify(i), i), i.points.forEach((g) => g.y += b / 2), K(i, W(m, i, c, n, t.node(f.v), t.node(f.w), a));
  }), t.nodes().forEach(function(f) {
    const i = t.node(f);
    r.info(f, i.type, i.diff), i.isGroup && (X = i.diff);
  }), r.warn("Returning from recursive render XAX", l, X), {
    elem: l,
    diff: X
  };
}, "recursiveRender"), ve = /* @__PURE__ */ w(async (e, t) => {
  const n = new B({
    multigraph: !0,
    compound: !0
  }).setGraph({
    rankdir: e.direction,
    nodesep: e.config?.nodeSpacing || e.config?.flowchart?.nodeSpacing || e.nodeSpacing,
    ranksep: e.config?.rankSpacing || e.config?.flowchart?.rankSpacing || e.rankSpacing,
    marginx: 8,
    marginy: 8
  }).setDefaultEdgeLabel(function() {
    return {};
  }), a = t.select("g");
  Q(a, e.markers, e.type, e.diagramId), $(), I(), q(), ne(), e.nodes.forEach((o) => {
    n.setNode(o.id, { ...o }), o.parentId && n.setParent(o.id, o.parentId);
  }), r.debug("Edges:", e.edges), e.edges.forEach((o) => {
    if (o.start === o.end) {
      const d = o.start, l = d + "---" + d + "---1", u = d + "---" + d + "---2", m = n.node(d);
      n.setNode(l, {
        domId: l,
        id: l,
        parentId: m.parentId,
        labelStyle: "",
        label: "",
        padding: 0,
        shape: "labelRect",
        style: "",
        width: 10,
        height: 10
      }), n.setParent(l, m.parentId), n.setNode(u, {
        domId: u,
        id: u,
        parentId: m.parentId,
        labelStyle: "",
        padding: 0,
        shape: "labelRect",
        label: "",
        style: "",
        width: 10,
        height: 10
      }), n.setParent(u, m.parentId);
      const h = structuredClone(o), y = structuredClone(o), X = structuredClone(o);
      h.label = "", h.arrowTypeEnd = "none", h.id = d + "-cyclic-special-1", y.arrowTypeStart = "none", y.arrowTypeEnd = "none", y.id = d + "-cyclic-special-mid", X.label = "", m.isGroup && (h.fromCluster = d, X.toCluster = d), X.id = d + "-cyclic-special-2", X.arrowTypeStart = "none", n.setEdge(d, l, h, d + "-cyclic-special-0"), n.setEdge(l, u, y, d + "-cyclic-special-1"), n.setEdge(u, d, X, d + "-cyc<lic-special-2");
    } else n.setEdge(o.start, o.end, { ...o }, o.id);
  }), r.warn("Graph at first:", JSON.stringify(v(n))), re(n), r.warn("Graph after XAX:", JSON.stringify(v(n)));
  const s = Y();
  await M(a, n, e.type, e.diagramId, void 0, s);
}, "render");
export {
  ve as render
};

//# sourceMappingURL=dagre-KV5264BT.js.map