import { selectSvgElement as ft } from "./chunk-EXTU4WIE.js";
import { createText as _, getIconSVG as N, registerIconPacks as ht, unknownIcon as gt } from "./chunk-JA3XYJ7Z.js";
import { populateCommonDb as ut } from "./chunk-4BX2VUAB.js";
import { cleanAndMerge as pt, getEdgeId as mt } from "./chunk-S3R3BYOJ.js";
import { setupGraphViewbox as yt, setAccTitle as wt, getAccTitle as kt, setDiagramTitle as xt, getDiagramTitle as bt, getAccDescription as vt, setAccDescription as Et, clear as $t, getConfig as St, defaultConfig_default as At, getConfig2 as J, sanitizeText as Dt } from "./chunk-ABZYJK2D.js";
import { __name as g, log as K } from "./chunk-AGHRB4JF.js";
import { parse as Tt } from "../../../../../../@mermaid-js_parser@0.6.3/node_modules/@mermaid-js/parser/dist/mermaid-parser.core.js";
import Q from "../../../../../../cytoscape@3.33.1/node_modules/cytoscape/dist/cytoscape.esm.js";
import Bt from "../../../../../../../../_virtual/cytoscape-fcose.js";
import "../../../../../../d3-transition@3.0.1_d3-selection@3.0.0/node_modules/d3-transition/src/selection/index.js";
import "../../../../../../d3-zoom@3.0.0/node_modules/d3-zoom/src/transform.js";
import Ct from "../../../../../../d3-selection@3.0.0/node_modules/d3-selection/src/select.js";
var V = {
  L: "left",
  R: "right",
  T: "top",
  B: "bottom"
}, W = {
  L: /* @__PURE__ */ g((e) => `${e},${e / 2} 0,${e} 0,0`, "L"),
  R: /* @__PURE__ */ g((e) => `0,${e / 2} ${e},0 ${e},${e}`, "R"),
  T: /* @__PURE__ */ g((e) => `0,0 ${e},0 ${e / 2},${e}`, "T"),
  B: /* @__PURE__ */ g((e) => `${e / 2},0 ${e},${e} 0,${e}`, "B")
}, X = {
  L: /* @__PURE__ */ g((e, t) => e - t + 2, "L"),
  R: /* @__PURE__ */ g((e, t) => e - 2, "R"),
  T: /* @__PURE__ */ g((e, t) => e - t + 2, "T"),
  B: /* @__PURE__ */ g((e, t) => e - 2, "B")
}, Lt = /* @__PURE__ */ g(function(e) {
  return A(e) ? e === "L" ? "R" : "L" : e === "T" ? "B" : "T";
}, "getOppositeArchitectureDirection"), U = /* @__PURE__ */ g(function(e) {
  const t = e;
  return t === "L" || t === "R" || t === "T" || t === "B";
}, "isArchitectureDirection"), A = /* @__PURE__ */ g(function(e) {
  const t = e;
  return t === "L" || t === "R";
}, "isArchitectureDirectionX"), j = /* @__PURE__ */ g(function(e) {
  const t = e;
  return t === "T" || t === "B";
}, "isArchitectureDirectionY"), Z = /* @__PURE__ */ g(function(e, t) {
  const i = A(e) && j(t), o = j(e) && A(t);
  return i || o;
}, "isArchitectureDirectionXY"), jt = /* @__PURE__ */ g(function(e) {
  const t = e[0], i = e[1], o = A(t) && j(i), r = j(t) && A(i);
  return o || r;
}, "isArchitecturePairXY"), zt = /* @__PURE__ */ g(function(e) {
  return e !== "LL" && e !== "RR" && e !== "TT" && e !== "BB";
}, "isValidArchitectureDirectionPair"), G = /* @__PURE__ */ g(function(e, t) {
  const i = `${e}${t}`;
  return zt(i) ? i : void 0;
}, "getArchitectureDirectionPair"), It = /* @__PURE__ */ g(function([e, t], i) {
  const o = i[0], r = i[1];
  return A(o) ? j(r) ? [e + (o === "L" ? -1 : 1), t + (r === "T" ? 1 : -1)] : [e + (o === "L" ? -1 : 1), t] : A(r) ? [e + (r === "L" ? 1 : -1), t + (o === "T" ? 1 : -1)] : [e, t + (o === "T" ? 1 : -1)];
}, "shiftPositionByArchitectureDirectionPair"), Ft = /* @__PURE__ */ g(function(e) {
  return e === "LT" || e === "TL" ? [1, 1] : e === "BL" || e === "LB" ? [1, -1] : e === "BR" || e === "RB" ? [-1, -1] : [-1, 1];
}, "getArchitectureDirectionXYFactors"), Pt = /* @__PURE__ */ g(function(e, t) {
  return Z(e, t) ? "bend" : A(e) ? "horizontal" : "vertical";
}, "getArchitectureDirectionAlignment"), Rt = /* @__PURE__ */ g(function(e) {
  return e.type === "service";
}, "isArchitectureService"), Xt = /* @__PURE__ */ g(function(e) {
  return e.type === "junction";
}, "isArchitectureJunction"), tt = /* @__PURE__ */ g((e) => e.data(), "edgeData"), F = /* @__PURE__ */ g((e) => e.data(), "nodeData"), Yt = At.architecture, P, et = (P = class {
  constructor() {
    this.nodes = {}, this.groups = {}, this.edges = [], this.registeredIds = {}, this.elements = {}, this.setAccTitle = wt, this.getAccTitle = kt, this.setDiagramTitle = xt, this.getDiagramTitle = bt, this.getAccDescription = vt, this.setAccDescription = Et, this.clear();
  }
  clear() {
    this.nodes = {}, this.groups = {}, this.edges = [], this.registeredIds = {}, this.dataStructures = void 0, this.elements = {}, $t();
  }
  addService({
    id: t,
    icon: i,
    in: o,
    title: r,
    iconText: a
  }) {
    if (this.registeredIds[t] !== void 0)
      throw new Error(
        `The service id [${t}] is already in use by another ${this.registeredIds[t]}`
      );
    if (o !== void 0) {
      if (t === o)
        throw new Error(`The service [${t}] cannot be placed within itself`);
      if (this.registeredIds[o] === void 0)
        throw new Error(
          `The service [${t}]'s parent does not exist. Please make sure the parent is created before this service`
        );
      if (this.registeredIds[o] === "node")
        throw new Error(`The service [${t}]'s parent is not a group`);
    }
    this.registeredIds[t] = "node", this.nodes[t] = {
      id: t,
      type: "service",
      icon: i,
      iconText: a,
      title: r,
      edges: [],
      in: o
    };
  }
  getServices() {
    return Object.values(this.nodes).filter(Rt);
  }
  addJunction({ id: t, in: i }) {
    this.registeredIds[t] = "node", this.nodes[t] = {
      id: t,
      type: "junction",
      edges: [],
      in: i
    };
  }
  getJunctions() {
    return Object.values(this.nodes).filter(Xt);
  }
  getNodes() {
    return Object.values(this.nodes);
  }
  getNode(t) {
    return this.nodes[t] ?? null;
  }
  addGroup({ id: t, icon: i, in: o, title: r }) {
    var a, l, u;
    if (((a = this.registeredIds) == null ? void 0 : a[t]) !== void 0)
      throw new Error(
        `The group id [${t}] is already in use by another ${this.registeredIds[t]}`
      );
    if (o !== void 0) {
      if (t === o)
        throw new Error(`The group [${t}] cannot be placed within itself`);
      if (((l = this.registeredIds) == null ? void 0 : l[o]) === void 0)
        throw new Error(
          `The group [${t}]'s parent does not exist. Please make sure the parent is created before this group`
        );
      if (((u = this.registeredIds) == null ? void 0 : u[o]) === "node")
        throw new Error(`The group [${t}]'s parent is not a group`);
    }
    this.registeredIds[t] = "group", this.groups[t] = {
      id: t,
      icon: i,
      title: r,
      in: o
    };
  }
  getGroups() {
    return Object.values(this.groups);
  }
  addEdge({
    lhsId: t,
    rhsId: i,
    lhsDir: o,
    rhsDir: r,
    lhsInto: a,
    rhsInto: l,
    lhsGroup: u,
    rhsGroup: d,
    title: n
  }) {
    if (!U(o))
      throw new Error(
        `Invalid direction given for left hand side of edge ${t}--${i}. Expected (L,R,T,B) got ${String(o)}`
      );
    if (!U(r))
      throw new Error(
        `Invalid direction given for right hand side of edge ${t}--${i}. Expected (L,R,T,B) got ${String(r)}`
      );
    if (this.nodes[t] === void 0 && this.groups[t] === void 0)
      throw new Error(
        `The left-hand id [${t}] does not yet exist. Please create the service/group before declaring an edge to it.`
      );
    if (this.nodes[i] === void 0 && this.groups[i] === void 0)
      throw new Error(
        `The right-hand id [${i}] does not yet exist. Please create the service/group before declaring an edge to it.`
      );
    const s = this.nodes[t].in, p = this.nodes[i].in;
    if (u && s && p && s == p)
      throw new Error(
        `The left-hand id [${t}] is modified to traverse the group boundary, but the edge does not pass through two groups.`
      );
    if (d && s && p && s == p)
      throw new Error(
        `The right-hand id [${i}] is modified to traverse the group boundary, but the edge does not pass through two groups.`
      );
    const f = {
      lhsId: t,
      lhsDir: o,
      lhsInto: a,
      lhsGroup: u,
      rhsId: i,
      rhsDir: r,
      rhsInto: l,
      rhsGroup: d,
      title: n
    };
    this.edges.push(f), this.nodes[t] && this.nodes[i] && (this.nodes[t].edges.push(this.edges[this.edges.length - 1]), this.nodes[i].edges.push(this.edges[this.edges.length - 1]));
  }
  getEdges() {
    return this.edges;
  }
  /**
   * Returns the current diagram's adjacency list, spatial map, & group alignments.
   * If they have not been created, run the algorithms to generate them.
   * @returns
   */
  getDataStructures() {
    if (this.dataStructures === void 0) {
      const t = {}, i = Object.entries(this.nodes).reduce((d, [n, s]) => (d[n] = s.edges.reduce((p, f) => {
        var m, y;
        const c = (m = this.getNode(f.lhsId)) == null ? void 0 : m.in, h = (y = this.getNode(f.rhsId)) == null ? void 0 : y.in;
        if (c && h && c !== h) {
          const w = Pt(f.lhsDir, f.rhsDir);
          w !== "bend" && (t[c] ?? (t[c] = {}), t[c][h] = w, t[h] ?? (t[h] = {}), t[h][c] = w);
        }
        if (f.lhsId === n) {
          const w = G(f.lhsDir, f.rhsDir);
          w && (p[w] = f.rhsId);
        } else {
          const w = G(f.rhsDir, f.lhsDir);
          w && (p[w] = f.lhsId);
        }
        return p;
      }, {}), d), {}), o = Object.keys(i)[0], r = { [o]: 1 }, a = Object.keys(i).reduce(
        (d, n) => n === o ? d : { ...d, [n]: 1 },
        {}
      ), l = /* @__PURE__ */ g((d) => {
        const n = { [d]: [0, 0] }, s = [d];
        for (; s.length > 0; ) {
          const p = s.shift();
          if (p) {
            r[p] = 1, delete a[p];
            const f = i[p], [c, h] = n[p];
            Object.entries(f).forEach(([m, y]) => {
              r[y] || (n[y] = It(
                [c, h],
                m
              ), s.push(y));
            });
          }
        }
        return n;
      }, "BFS"), u = [l(o)];
      for (; Object.keys(a).length > 0; )
        u.push(l(Object.keys(a)[0]));
      this.dataStructures = {
        adjList: i,
        spatialMaps: u,
        groupAlignments: t
      };
    }
    return this.dataStructures;
  }
  setElementForId(t, i) {
    this.elements[t] = i;
  }
  getElementById(t) {
    return this.elements[t];
  }
  getConfig() {
    return pt({
      ...Yt,
      ...St().architecture
    });
  }
  getConfigField(t) {
    return this.getConfig()[t];
  }
}, g(P, "ArchitectureDB"), P), Ot = /* @__PURE__ */ g((e, t) => {
  ut(e, t), e.groups.map((i) => t.addGroup(i)), e.services.map((i) => t.addService({ ...i, type: "service" })), e.junctions.map((i) => t.addJunction({ ...i, type: "junction" })), e.edges.map((i) => t.addEdge(i));
}, "populateDb"), it = {
  parser: {
    // @ts-expect-error - ArchitectureDB is not assignable to DiagramDB
    yy: void 0
  },
  parse: /* @__PURE__ */ g(async (e) => {
    var o;
    const t = await Tt("architecture", e);
    K.debug(t);
    const i = (o = it.parser) == null ? void 0 : o.yy;
    if (!(i instanceof et))
      throw new Error(
        "parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues."
      );
    Ot(t, i);
  }, "parse")
}, Mt = /* @__PURE__ */ g((e) => `
  .edge {
    stroke-width: ${e.archEdgeWidth};
    stroke: ${e.archEdgeColor};
    fill: none;
  }

  .arrow {
    fill: ${e.archEdgeArrowColor};
  }

  .node-bkg {
    fill: none;
    stroke: ${e.archGroupBorderColor};
    stroke-width: ${e.archGroupBorderWidth};
    stroke-dasharray: 8;
  }
  .node-icon-text {
    display: flex; 
    align-items: center;
  }
  
  .node-icon-text > div {
    color: #fff;
    margin: 1px;
    height: fit-content;
    text-align: center;
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
`, "getStyles"), Nt = Mt, I = /* @__PURE__ */ g((e) => `<g><rect width="80" height="80" style="fill: #087ebf; stroke-width: 0px;"/>${e}</g>`, "wrapIcon"), R = {
  prefix: "mermaid-architecture",
  height: 80,
  width: 80,
  icons: {
    database: {
      body: I(
        '<path id="b" data-name="4" d="m20,57.86c0,3.94,8.95,7.14,20,7.14s20-3.2,20-7.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><path id="c" data-name="3" d="m20,45.95c0,3.94,8.95,7.14,20,7.14s20-3.2,20-7.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><path id="d" data-name="2" d="m20,34.05c0,3.94,8.95,7.14,20,7.14s20-3.2,20-7.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse id="e" data-name="1" cx="40" cy="22.14" rx="20" ry="7.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="20" y1="57.86" x2="20" y2="22.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="60" y1="57.86" x2="60" y2="22.14" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/>'
      )
    },
    server: {
      body: I(
        '<rect x="17.5" y="17.5" width="45" height="45" rx="2" ry="2" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="17.5" y1="32.5" x2="62.5" y2="32.5" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="17.5" y1="47.5" x2="62.5" y2="47.5" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><g><path d="m56.25,25c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: #fff; stroke-width: 0px;"/><path d="m56.25,25c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: none; stroke: #fff; stroke-miterlimit: 10;"/></g><g><path d="m56.25,40c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: #fff; stroke-width: 0px;"/><path d="m56.25,40c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: none; stroke: #fff; stroke-miterlimit: 10;"/></g><g><path d="m56.25,55c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: #fff; stroke-width: 0px;"/><path d="m56.25,55c0,.27-.45.5-1,.5h-10.5c-.55,0-1-.23-1-.5s.45-.5,1-.5h10.5c.55,0,1,.23,1,.5Z" style="fill: none; stroke: #fff; stroke-miterlimit: 10;"/></g><g><circle cx="32.5" cy="25" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="27.5" cy="25" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="22.5" cy="25" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/></g><g><circle cx="32.5" cy="40" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="27.5" cy="40" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="22.5" cy="40" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/></g><g><circle cx="32.5" cy="55" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="27.5" cy="55" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/><circle cx="22.5" cy="55" r=".75" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10;"/></g>'
      )
    },
    disk: {
      body: I(
        '<rect x="20" y="15" width="40" height="50" rx="1" ry="1" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="24" cy="19.17" rx=".8" ry=".83" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="56" cy="19.17" rx=".8" ry=".83" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="24" cy="60.83" rx=".8" ry=".83" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="56" cy="60.83" rx=".8" ry=".83" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="40" cy="33.75" rx="14" ry="14.58" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><ellipse cx="40" cy="33.75" rx="4" ry="4.17" style="fill: #fff; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><path d="m37.51,42.52l-4.83,13.22c-.26.71-1.1,1.02-1.76.64l-4.18-2.42c-.66-.38-.81-1.26-.33-1.84l9.01-10.8c.88-1.05,2.56-.08,2.09,1.2Z" style="fill: #fff; stroke-width: 0px;"/>'
      )
    },
    internet: {
      body: I(
        '<circle cx="40" cy="40" r="22.5" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="40" y1="17.5" x2="40" y2="62.5" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="17.5" y1="40" x2="62.5" y2="40" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><path d="m39.99,17.51c-15.28,11.1-15.28,33.88,0,44.98" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><path d="m40.01,17.51c15.28,11.1,15.28,33.88,0,44.98" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="19.75" y1="30.1" x2="60.25" y2="30.1" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/><line x1="19.75" y1="49.9" x2="60.25" y2="49.9" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/>'
      )
    },
    cloud: {
      body: I(
        '<path d="m65,47.5c0,2.76-2.24,5-5,5H20c-2.76,0-5-2.24-5-5,0-1.87,1.03-3.51,2.56-4.36-.04-.21-.06-.42-.06-.64,0-2.6,2.48-4.74,5.65-4.97,1.65-4.51,6.34-7.76,11.85-7.76.86,0,1.69.08,2.5.23,2.09-1.57,4.69-2.5,7.5-2.5,6.1,0,11.19,4.38,12.28,10.17,2.14.56,3.72,2.51,3.72,4.83,0,.03,0,.07-.01.1,2.29.46,4.01,2.48,4.01,4.9Z" style="fill: none; stroke: #fff; stroke-miterlimit: 10; stroke-width: 2px;"/>'
      )
    },
    unknown: gt,
    blank: {
      body: I("")
    }
  }
}, Gt = /* @__PURE__ */ g(async function(e, t, i) {
  const o = i.getConfigField("padding"), r = i.getConfigField("iconSize"), a = r / 2, l = r / 6, u = l / 2;
  await Promise.all(
    t.edges().map(async (d) => {
      var z, D;
      const {
        source: n,
        sourceDir: s,
        sourceArrow: p,
        sourceGroup: f,
        target: c,
        targetDir: h,
        targetArrow: m,
        targetGroup: y,
        label: w
      } = tt(d);
      let { x: k, y: v } = d[0].sourceEndpoint();
      const { x: E, y: b } = d[0].midpoint();
      let { x, y: $ } = d[0].targetEndpoint();
      const S = o + 4;
      if (f && (A(s) ? k += s === "L" ? -S : S : v += s === "T" ? -S : S + 18), y && (A(h) ? x += h === "L" ? -S : S : $ += h === "T" ? -S : S + 18), !f && ((z = i.getNode(n)) == null ? void 0 : z.type) === "junction" && (A(s) ? k += s === "L" ? a : -a : v += s === "T" ? a : -a), !y && ((D = i.getNode(c)) == null ? void 0 : D.type) === "junction" && (A(h) ? x += h === "L" ? a : -a : $ += h === "T" ? a : -a), d[0]._private.rscratch) {
        const T = e.insert("g");
        if (T.insert("path").attr("d", `M ${k},${v} L ${E},${b} L${x},${$} `).attr("class", "edge").attr("id", mt(n, c, { prefix: "L" })), p) {
          const B = A(s) ? X[s](k, l) : k - u, C = j(s) ? X[s](v, l) : v - u;
          T.insert("polygon").attr("points", W[s](l)).attr("transform", `translate(${B},${C})`).attr("class", "arrow");
        }
        if (m) {
          const B = A(h) ? X[h](x, l) : x - u, C = j(h) ? X[h]($, l) : $ - u;
          T.insert("polygon").attr("points", W[h](l)).attr("transform", `translate(${B},${C})`).attr("class", "arrow");
        }
        if (w) {
          const B = Z(s, h) ? "XY" : A(s) ? "X" : "Y";
          let C = 0;
          B === "X" ? C = Math.abs(k - x) : B === "Y" ? C = Math.abs(v - $) / 1.5 : C = Math.abs(k - x) / 2;
          const L = T.append("g");
          if (await _(
            L,
            w,
            {
              useHtmlLabels: !1,
              width: C,
              classes: "architecture-service-label"
            },
            J()
          ), L.attr("dy", "1em").attr("alignment-baseline", "middle").attr("dominant-baseline", "middle").attr("text-anchor", "middle"), B === "X")
            L.attr("transform", "translate(" + E + ", " + b + ")");
          else if (B === "Y")
            L.attr("transform", "translate(" + E + ", " + b + ") rotate(-90)");
          else if (B === "XY") {
            const Y = G(s, h);
            if (Y && jt(Y)) {
              const q = L.node().getBoundingClientRect(), [O, M] = Ft(Y);
              L.attr("dominant-baseline", "auto").attr("transform", `rotate(${-1 * O * M * 45})`);
              const H = L.node().getBoundingClientRect();
              L.attr(
                "transform",
                `
                translate(${E}, ${b - q.height / 2})
                translate(${O * H.width / 2}, ${M * H.height / 2})
                rotate(${-1 * O * M * 45}, 0, ${q.height / 2})
              `
              );
            }
          }
        }
      }
    })
  );
}, "drawEdges"), _t = /* @__PURE__ */ g(async function(e, t, i) {
  const r = i.getConfigField("padding") * 0.75, a = i.getConfigField("fontSize"), u = i.getConfigField("iconSize") / 2;
  await Promise.all(
    t.nodes().map(async (d) => {
      const n = F(d);
      if (n.type === "group") {
        const { h: s, w: p, x1: f, y1: c } = d.boundingBox(), h = e.append("rect");
        h.attr("id", `group-${n.id}`).attr("x", f + u).attr("y", c + u).attr("width", p).attr("height", s).attr("class", "node-bkg");
        const m = e.append("g");
        let y = f, w = c;
        if (n.icon) {
          const k = m.append("g");
          k.html(
            `<g>${await N(n.icon, { height: r, width: r, fallbackPrefix: R.prefix })}</g>`
          ), k.attr(
            "transform",
            "translate(" + (y + u + 1) + ", " + (w + u + 1) + ")"
          ), y += r, w += a / 2 - 1 - 2;
        }
        if (n.label) {
          const k = m.append("g");
          await _(
            k,
            n.label,
            {
              useHtmlLabels: !1,
              width: p,
              classes: "architecture-service-label"
            },
            J()
          ), k.attr("dy", "1em").attr("alignment-baseline", "middle").attr("dominant-baseline", "start").attr("text-anchor", "start"), k.attr(
            "transform",
            "translate(" + (y + u + 4) + ", " + (w + u + 2) + ")"
          );
        }
        i.setElementForId(n.id, h);
      }
    })
  );
}, "drawGroups"), Jt = /* @__PURE__ */ g(async function(e, t, i) {
  const o = J();
  for (const r of i) {
    const a = t.append("g"), l = e.getConfigField("iconSize");
    if (r.title) {
      const s = a.append("g");
      await _(
        s,
        r.title,
        {
          useHtmlLabels: !1,
          width: l * 1.5,
          classes: "architecture-service-label"
        },
        o
      ), s.attr("dy", "1em").attr("alignment-baseline", "middle").attr("dominant-baseline", "middle").attr("text-anchor", "middle"), s.attr("transform", "translate(" + l / 2 + ", " + l + ")");
    }
    const u = a.append("g");
    if (r.icon)
      u.html(
        `<g>${await N(r.icon, { height: l, width: l, fallbackPrefix: R.prefix })}</g>`
      );
    else if (r.iconText) {
      u.html(
        `<g>${await N("blank", { height: l, width: l, fallbackPrefix: R.prefix })}</g>`
      );
      const f = u.append("g").append("foreignObject").attr("width", l).attr("height", l).append("div").attr("class", "node-icon-text").attr("style", `height: ${l}px;`).append("div").html(Dt(r.iconText, o)), c = parseInt(
        window.getComputedStyle(f.node(), null).getPropertyValue("font-size").replace(/\D/g, "")
      ) ?? 16;
      f.attr("style", `-webkit-line-clamp: ${Math.floor((l - 2) / c)};`);
    } else
      u.append("path").attr("class", "node-bkg").attr("id", "node-" + r.id).attr(
        "d",
        `M0 ${l} v${-l} q0,-5 5,-5 h${l} q5,0 5,5 v${l} H0 Z`
      );
    a.attr("id", `service-${r.id}`).attr("class", "architecture-service");
    const { width: d, height: n } = a.node().getBBox();
    r.width = d, r.height = n, e.setElementForId(r.id, a);
  }
  return 0;
}, "drawServices"), Zt = /* @__PURE__ */ g(function(e, t, i) {
  i.forEach((o) => {
    const r = t.append("g"), a = e.getConfigField("iconSize");
    r.append("g").append("rect").attr("id", "node-" + o.id).attr("fill-opacity", "0").attr("width", a).attr("height", a), r.attr("class", "architecture-junction");
    const { width: u, height: d } = r._groups[0][0].getBBox();
    r.width = u, r.height = d, e.setElementForId(o.id, r);
  });
}, "drawJunctions");
ht([
  {
    name: R.prefix,
    icons: R
  }
]);
Q.use(Bt);
function rt(e, t, i) {
  e.forEach((o) => {
    t.add({
      group: "nodes",
      data: {
        type: "service",
        id: o.id,
        icon: o.icon,
        label: o.title,
        parent: o.in,
        width: i.getConfigField("iconSize"),
        height: i.getConfigField("iconSize")
      },
      classes: "node-service"
    });
  });
}
g(rt, "addServices");
function st(e, t, i) {
  e.forEach((o) => {
    t.add({
      group: "nodes",
      data: {
        type: "junction",
        id: o.id,
        parent: o.in,
        width: i.getConfigField("iconSize"),
        height: i.getConfigField("iconSize")
      },
      classes: "node-junction"
    });
  });
}
g(st, "addJunctions");
function ot(e, t) {
  t.nodes().map((i) => {
    const o = F(i);
    if (o.type === "group")
      return;
    o.x = i.position().x, o.y = i.position().y, e.getElementById(o.id).attr("transform", "translate(" + (o.x || 0) + "," + (o.y || 0) + ")");
  });
}
g(ot, "positionNodes");
function nt(e, t) {
  e.forEach((i) => {
    t.add({
      group: "nodes",
      data: {
        type: "group",
        id: i.id,
        icon: i.icon,
        label: i.title,
        parent: i.in
      },
      classes: "node-group"
    });
  });
}
g(nt, "addGroups");
function ct(e, t) {
  e.forEach((i) => {
    const { lhsId: o, rhsId: r, lhsInto: a, lhsGroup: l, rhsInto: u, lhsDir: d, rhsDir: n, rhsGroup: s, title: p } = i, f = Z(i.lhsDir, i.rhsDir) ? "segments" : "straight", c = {
      id: `${o}-${r}`,
      label: p,
      source: o,
      sourceDir: d,
      sourceArrow: a,
      sourceGroup: l,
      sourceEndpoint: d === "L" ? "0 50%" : d === "R" ? "100% 50%" : d === "T" ? "50% 0" : "50% 100%",
      target: r,
      targetDir: n,
      targetArrow: u,
      targetGroup: s,
      targetEndpoint: n === "L" ? "0 50%" : n === "R" ? "100% 50%" : n === "T" ? "50% 0" : "50% 100%"
    };
    t.add({
      group: "edges",
      data: c,
      classes: f
    });
  });
}
g(ct, "addEdges");
function at(e, t, i) {
  const o = /* @__PURE__ */ g((u, d) => Object.entries(u).reduce(
    (n, [s, p]) => {
      var h;
      let f = 0;
      const c = Object.entries(p);
      if (c.length === 1)
        return n[s] = c[0][1], n;
      for (let m = 0; m < c.length - 1; m++)
        for (let y = m + 1; y < c.length; y++) {
          const [w, k] = c[m], [v, E] = c[y];
          if (((h = i[w]) == null ? void 0 : h[v]) === d)
            n[s] ?? (n[s] = []), n[s] = [...n[s], ...k, ...E];
          else if (w === "default" || v === "default")
            n[s] ?? (n[s] = []), n[s] = [...n[s], ...k, ...E];
          else {
            const x = `${s}-${f++}`;
            n[x] = k;
            const $ = `${s}-${f++}`;
            n[$] = E;
          }
        }
      return n;
    },
    {}
  ), "flattenAlignments"), r = t.map((u) => {
    const d = {}, n = {};
    return Object.entries(u).forEach(([s, [p, f]]) => {
      var h, m, y;
      const c = ((h = e.getNode(s)) == null ? void 0 : h.in) ?? "default";
      d[f] ?? (d[f] = {}), (m = d[f])[c] ?? (m[c] = []), d[f][c].push(s), n[p] ?? (n[p] = {}), (y = n[p])[c] ?? (y[c] = []), n[p][c].push(s);
    }), {
      horiz: Object.values(o(d, "horizontal")).filter(
        (s) => s.length > 1
      ),
      vert: Object.values(o(n, "vertical")).filter(
        (s) => s.length > 1
      )
    };
  }), [a, l] = r.reduce(
    ([u, d], { horiz: n, vert: s }) => [
      [...u, ...n],
      [...d, ...s]
    ],
    [[], []]
  );
  return {
    horizontal: a,
    vertical: l
  };
}
g(at, "getAlignments");
function lt(e, t) {
  const i = [], o = /* @__PURE__ */ g((a) => `${a[0]},${a[1]}`, "posToStr"), r = /* @__PURE__ */ g((a) => a.split(",").map((l) => parseInt(l)), "strToPos");
  return e.forEach((a) => {
    const l = Object.fromEntries(
      Object.entries(a).map(([s, p]) => [o(p), s])
    ), u = [o([0, 0])], d = {}, n = {
      L: [-1, 0],
      R: [1, 0],
      T: [0, 1],
      B: [0, -1]
    };
    for (; u.length > 0; ) {
      const s = u.shift();
      if (s) {
        d[s] = 1;
        const p = l[s];
        if (p) {
          const f = r(s);
          Object.entries(n).forEach(([c, h]) => {
            const m = o([f[0] + h[0], f[1] + h[1]]), y = l[m];
            y && !d[m] && (u.push(m), i.push({
              [V[c]]: y,
              [V[Lt(c)]]: p,
              gap: 1.5 * t.getConfigField("iconSize")
            }));
          });
        }
      }
    }
  }), i;
}
g(lt, "getRelativeConstraints");
function dt(e, t, i, o, r, { spatialMaps: a, groupAlignments: l }) {
  return new Promise((u) => {
    const d = Ct("body").append("div").attr("id", "cy").attr("style", "display:none"), n = Q({
      container: document.getElementById("cy"),
      style: [
        {
          selector: "edge",
          style: {
            "curve-style": "straight",
            label: "data(label)",
            "source-endpoint": "data(sourceEndpoint)",
            "target-endpoint": "data(targetEndpoint)"
          }
        },
        {
          selector: "edge.segments",
          style: {
            "curve-style": "segments",
            "segment-weights": "0",
            "segment-distances": [0.5],
            // @ts-ignore Incorrect library types
            "edge-distances": "endpoints",
            "source-endpoint": "data(sourceEndpoint)",
            "target-endpoint": "data(targetEndpoint)"
          }
        },
        {
          selector: "node",
          style: {
            // @ts-ignore Incorrect library types
            "compound-sizing-wrt-labels": "include"
          }
        },
        {
          selector: "node[label]",
          style: {
            "text-valign": "bottom",
            "text-halign": "center",
            "font-size": `${r.getConfigField("fontSize")}px`
          }
        },
        {
          selector: ".node-service",
          style: {
            label: "data(label)",
            width: "data(width)",
            height: "data(height)"
          }
        },
        {
          selector: ".node-junction",
          style: {
            width: "data(width)",
            height: "data(height)"
          }
        },
        {
          selector: ".node-group",
          style: {
            // @ts-ignore Incorrect library types
            padding: `${r.getConfigField("padding")}px`
          }
        }
      ],
      layout: {
        name: "grid",
        boundingBox: {
          x1: 0,
          x2: 100,
          y1: 0,
          y2: 100
        }
      }
    });
    d.remove(), nt(i, n), rt(e, n, r), st(t, n, r), ct(o, n);
    const s = at(r, a, l), p = lt(a, r), f = n.layout({
      name: "fcose",
      quality: "proof",
      styleEnabled: !1,
      animate: !1,
      nodeDimensionsIncludeLabels: !1,
      // Adjust the edge parameters if it passes through the border of a group
      // Hacky fix for: https://github.com/iVis-at-Bilkent/cytoscape.js-fcose/issues/67
      idealEdgeLength(c) {
        const [h, m] = c.connectedNodes(), { parent: y } = F(h), { parent: w } = F(m);
        return y === w ? 1.5 * r.getConfigField("iconSize") : 0.5 * r.getConfigField("iconSize");
      },
      edgeElasticity(c) {
        const [h, m] = c.connectedNodes(), { parent: y } = F(h), { parent: w } = F(m);
        return y === w ? 0.45 : 1e-3;
      },
      alignmentConstraint: s,
      relativePlacementConstraint: p
    });
    f.one("layoutstop", () => {
      var h;
      function c(m, y, w, k) {
        let v, E;
        const { x: b, y: x } = m, { x: $, y: S } = y;
        E = (k - x + (b - w) * (x - S) / (b - $)) / Math.sqrt(1 + Math.pow((x - S) / (b - $), 2)), v = Math.sqrt(Math.pow(k - x, 2) + Math.pow(w - b, 2) - Math.pow(E, 2));
        const z = Math.sqrt(Math.pow($ - b, 2) + Math.pow(S - x, 2));
        v = v / z;
        let D = ($ - b) * (k - x) - (S - x) * (w - b);
        switch (!0) {
          case D >= 0:
            D = 1;
            break;
          case D < 0:
            D = -1;
            break;
        }
        let T = ($ - b) * (w - b) + (S - x) * (k - x);
        switch (!0) {
          case T >= 0:
            T = 1;
            break;
          case T < 0:
            T = -1;
            break;
        }
        return E = Math.abs(E) * D, v = v * T, {
          distances: E,
          weights: v
        };
      }
      g(c, "getSegmentWeights"), n.startBatch();
      for (const m of Object.values(n.edges()))
        if ((h = m.data) != null && h.call(m)) {
          const { x: y, y: w } = m.source().position(), { x: k, y: v } = m.target().position();
          if (y !== k && w !== v) {
            const E = m.sourceEndpoint(), b = m.targetEndpoint(), { sourceDir: x } = tt(m), [$, S] = j(x) ? [E.x, b.y] : [b.x, E.y], { weights: z, distances: D } = c(E, b, $, S);
            m.style("segment-distances", D), m.style("segment-weights", z);
          }
        }
      n.endBatch(), f.run();
    }), f.run(), n.ready((c) => {
      K.info("Ready", c), u(n);
    });
  });
}
g(dt, "layoutArchitecture");
var qt = /* @__PURE__ */ g(async (e, t, i, o) => {
  const r = o.db, a = r.getServices(), l = r.getJunctions(), u = r.getGroups(), d = r.getEdges(), n = r.getDataStructures(), s = ft(t), p = s.append("g");
  p.attr("class", "architecture-edges");
  const f = s.append("g");
  f.attr("class", "architecture-services");
  const c = s.append("g");
  c.attr("class", "architecture-groups"), await Jt(r, f, a), Zt(r, f, l);
  const h = await dt(a, l, u, d, r, n);
  await Gt(p, h, r), await _t(c, h, r), ot(r, h), yt(void 0, s, r.getConfigField("padding"), r.getConfigField("useMaxWidth"));
}, "draw"), Ht = { draw: qt }, ce = {
  parser: it,
  get db() {
    return new et();
  },
  renderer: Ht,
  styles: Nt
};
export {
  ce as diagram
};
