import { __name, log } from "./chunk-AGHRB4JF.js";
import { clear, common_default, defaultConfig_default, getAccDescription, getAccTitle, getConfig, getConfig2, getDiagramTitle, setAccDescription, setAccTitle, setDiagramTitle, setupGraphViewbox2 } from "./chunk-ABZYJK2D.js";
import select_default from "../../../../d3-selection/src/select.js";
import "../../../../d3/src/index.js";
import { cleanAndMerge, random, utils_default } from "./chunk-S3R3BYOJ.js";
import { populateCommonDb } from "./chunk-4BX2VUAB.js";
import { parse } from "../../../../@mermaid-js/parser/dist/mermaid-parser.core.js";
import { ImperativeState } from "./chunk-QZHKN3VN.js";
var commitType = {
	NORMAL: 0,
	REVERSE: 1,
	HIGHLIGHT: 2,
	MERGE: 3,
	CHERRY_PICK: 4
}, DEFAULT_GITGRAPH_CONFIG = defaultConfig_default.gitGraph, getConfig3 = /* @__PURE__ */ __name(() => cleanAndMerge({
	...DEFAULT_GITGRAPH_CONFIG,
	...getConfig().gitGraph
}), "getConfig"), state = new ImperativeState(() => {
	let f = getConfig3(), V = f.mainBranchName, H = f.mainBranchOrder;
	return {
		mainBranchName: V,
		commits: /* @__PURE__ */ new Map(),
		head: null,
		branchConfig: /* @__PURE__ */ new Map([[V, {
			name: V,
			order: H
		}]]),
		branches: /* @__PURE__ */ new Map([[V, null]]),
		currBranch: V,
		direction: "LR",
		seq: 0,
		options: {}
	};
});
function getID() {
	return random({ length: 7 });
}
__name(getID, "getID");
function uniqBy(f, V) {
	let H = /* @__PURE__ */ Object.create(null);
	return f.reduce((f, U) => {
		let W = V(U);
		return H[W] || (H[W] = !0, f.push(U)), f;
	}, []);
}
__name(uniqBy, "uniqBy");
var setDirection = /* @__PURE__ */ __name(function(f) {
	state.records.direction = f;
}, "setDirection"), setOptions = /* @__PURE__ */ __name(function(f) {
	log.debug("options str", f), f = f?.trim(), f ||= "{}";
	try {
		state.records.options = JSON.parse(f);
	} catch (f) {
		log.error("error while parsing gitGraph options", f.message);
	}
}, "setOptions"), getOptions = /* @__PURE__ */ __name(function() {
	return state.records.options;
}, "getOptions"), commit = /* @__PURE__ */ __name(function(f) {
	let H = f.msg, W = f.id, G = f.type, K = f.tags;
	log.info("commit", H, W, G, K), log.debug("Entering commit:", H, W, G, K);
	let q = getConfig3();
	W = common_default.sanitizeText(W, q), H = common_default.sanitizeText(H, q), K = K?.map((f) => common_default.sanitizeText(f, q));
	let J = {
		id: W || state.records.seq + "-" + getID(),
		message: H,
		seq: state.records.seq++,
		type: G ?? commitType.NORMAL,
		tags: K ?? [],
		parents: state.records.head == null ? [] : [state.records.head.id],
		branch: state.records.currBranch
	};
	state.records.head = J, log.info("main branch", q.mainBranchName), state.records.commits.has(J.id) && log.warn(`Commit ID ${J.id} already exists`), state.records.commits.set(J.id, J), state.records.branches.set(state.records.currBranch, J.id), log.debug("in pushCommit " + J.id);
}, "commit"), branch = /* @__PURE__ */ __name(function(f) {
	let H = f.name, W = f.order;
	if (H = common_default.sanitizeText(H, getConfig3()), state.records.branches.has(H)) throw Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${H}")`);
	state.records.branches.set(H, state.records.head == null ? null : state.records.head.id), state.records.branchConfig.set(H, {
		name: H,
		order: W
	}), checkout(H), log.debug("in createBranch");
}, "branch"), merge = /* @__PURE__ */ __name((f) => {
	let H = f.branch, W = f.id, G = f.type, K = f.tags, q = getConfig3();
	H = common_default.sanitizeText(H, q), W &&= common_default.sanitizeText(W, q);
	let J = state.records.branches.get(state.records.currBranch), Y = state.records.branches.get(H), X = J ? state.records.commits.get(J) : void 0, Z = Y ? state.records.commits.get(Y) : void 0;
	if (X && Z && X.branch === H) throw Error(`Cannot merge branch '${H}' into itself.`);
	if (state.records.currBranch === H) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"merge\". Cannot merge a branch to itself");
		throw f.hash = {
			text: `merge ${H}`,
			token: `merge ${H}`,
			expected: ["branch abc"]
		}, f;
	}
	if (X === void 0 || !X) {
		let f = /* @__PURE__ */ Error(`Incorrect usage of "merge". Current branch (${state.records.currBranch})has no commits`);
		throw f.hash = {
			text: `merge ${H}`,
			token: `merge ${H}`,
			expected: ["commit"]
		}, f;
	}
	if (!state.records.branches.has(H)) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"merge\". Branch to be merged (" + H + ") does not exist");
		throw f.hash = {
			text: `merge ${H}`,
			token: `merge ${H}`,
			expected: [`branch ${H}`]
		}, f;
	}
	if (Z === void 0 || !Z) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"merge\". Branch to be merged (" + H + ") has no commits");
		throw f.hash = {
			text: `merge ${H}`,
			token: `merge ${H}`,
			expected: ["\"commit\""]
		}, f;
	}
	if (X === Z) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"merge\". Both branches have same head");
		throw f.hash = {
			text: `merge ${H}`,
			token: `merge ${H}`,
			expected: ["branch abc"]
		}, f;
	}
	if (W && state.records.commits.has(W)) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"merge\". Commit with id:" + W + " already exists, use different custom id");
		throw f.hash = {
			text: `merge ${H} ${W} ${G} ${K?.join(" ")}`,
			token: `merge ${H} ${W} ${G} ${K?.join(" ")}`,
			expected: [`merge ${H} ${W}_UNIQUE ${G} ${K?.join(" ")}`]
		}, f;
	}
	let Q = Y || "", $ = {
		id: W || `${state.records.seq}-${getID()}`,
		message: `merged branch ${H} into ${state.records.currBranch}`,
		seq: state.records.seq++,
		parents: state.records.head == null ? [] : [state.records.head.id, Q],
		branch: state.records.currBranch,
		type: commitType.MERGE,
		customType: G,
		customId: !!W,
		tags: K ?? []
	};
	state.records.head = $, state.records.commits.set($.id, $), state.records.branches.set(state.records.currBranch, $.id), log.debug(state.records.branches), log.debug("in mergeBranch");
}, "merge"), cherryPick = /* @__PURE__ */ __name(function(f) {
	let H = f.id, W = f.targetId, G = f.tags, K = f.parent;
	log.debug("Entering cherryPick:", H, W, G);
	let q = getConfig3();
	if (H = common_default.sanitizeText(H, q), W = common_default.sanitizeText(W, q), G = G?.map((f) => common_default.sanitizeText(f, q)), K = common_default.sanitizeText(K, q), !H || !state.records.commits.has(H)) {
		let f = /* @__PURE__ */ Error("Incorrect usage of \"cherryPick\". Source commit id should exist and provided");
		throw f.hash = {
			text: `cherryPick ${H} ${W}`,
			token: `cherryPick ${H} ${W}`,
			expected: ["cherry-pick abc"]
		}, f;
	}
	let J = state.records.commits.get(H);
	if (J === void 0 || !J) throw Error("Incorrect usage of \"cherryPick\". Source commit id should exist and provided");
	if (K && !(Array.isArray(J.parents) && J.parents.includes(K))) throw /* @__PURE__ */ Error("Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.");
	let Y = J.branch;
	if (J.type === commitType.MERGE && !K) throw /* @__PURE__ */ Error("Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.");
	if (!W || !state.records.commits.has(W)) {
		if (Y === state.records.currBranch) {
			let f = /* @__PURE__ */ Error("Incorrect usage of \"cherryPick\". Source commit is already on current branch");
			throw f.hash = {
				text: `cherryPick ${H} ${W}`,
				token: `cherryPick ${H} ${W}`,
				expected: ["cherry-pick abc"]
			}, f;
		}
		let f = state.records.branches.get(state.records.currBranch);
		if (f === void 0 || !f) {
			let f = /* @__PURE__ */ Error(`Incorrect usage of "cherry-pick". Current branch (${state.records.currBranch})has no commits`);
			throw f.hash = {
				text: `cherryPick ${H} ${W}`,
				token: `cherryPick ${H} ${W}`,
				expected: ["cherry-pick abc"]
			}, f;
		}
		let U = state.records.commits.get(f);
		if (U === void 0 || !U) {
			let f = /* @__PURE__ */ Error(`Incorrect usage of "cherry-pick". Current branch (${state.records.currBranch})has no commits`);
			throw f.hash = {
				text: `cherryPick ${H} ${W}`,
				token: `cherryPick ${H} ${W}`,
				expected: ["cherry-pick abc"]
			}, f;
		}
		let q = {
			id: state.records.seq + "-" + getID(),
			message: `cherry-picked ${J?.message} into ${state.records.currBranch}`,
			seq: state.records.seq++,
			parents: state.records.head == null ? [] : [state.records.head.id, J.id],
			branch: state.records.currBranch,
			type: commitType.CHERRY_PICK,
			tags: G ? G.filter(Boolean) : [`cherry-pick:${J.id}${J.type === commitType.MERGE ? `|parent:${K}` : ""}`]
		};
		state.records.head = q, state.records.commits.set(q.id, q), state.records.branches.set(state.records.currBranch, q.id), log.debug(state.records.branches), log.debug("in cherryPick");
	}
}, "cherryPick"), checkout = /* @__PURE__ */ __name(function(f) {
	if (f = common_default.sanitizeText(f, getConfig3()), state.records.branches.has(f)) {
		state.records.currBranch = f;
		let V = state.records.branches.get(state.records.currBranch);
		V === void 0 || !V ? state.records.head = null : state.records.head = state.records.commits.get(V) ?? null;
	} else {
		let V = /* @__PURE__ */ Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${f}")`);
		throw V.hash = {
			text: `checkout ${f}`,
			token: `checkout ${f}`,
			expected: [`branch ${f}`]
		}, V;
	}
}, "checkout");
function upsert(f, V, H) {
	let U = f.indexOf(V);
	U === -1 ? f.push(H) : f.splice(U, 1, H);
}
__name(upsert, "upsert");
function prettyPrintCommitHistory(f) {
	let H = f.reduce((f, V) => f.seq > V.seq ? f : V, f[0]), U = "";
	f.forEach(function(f) {
		f === H ? U += "	*" : U += "	|";
	});
	let W = [
		U,
		H.id,
		H.seq
	];
	for (let f in state.records.branches) state.records.branches.get(f) === H.id && W.push(f);
	if (log.debug(W.join(" ")), H.parents && H.parents.length == 2 && H.parents[0] && H.parents[1]) {
		let V = state.records.commits.get(H.parents[0]);
		upsert(f, H, V), H.parents[1] && f.push(state.records.commits.get(H.parents[1]));
	} else if (H.parents.length == 0) return;
	else if (H.parents[0]) {
		let V = state.records.commits.get(H.parents[0]);
		upsert(f, H, V);
	}
	f = uniqBy(f, (f) => f.id), prettyPrintCommitHistory(f);
}
__name(prettyPrintCommitHistory, "prettyPrintCommitHistory");
var prettyPrint = /* @__PURE__ */ __name(function() {
	log.debug(state.records.commits);
	let f = getCommitsArray()[0];
	prettyPrintCommitHistory([f]);
}, "prettyPrint"), clear2 = /* @__PURE__ */ __name(function() {
	state.reset(), clear();
}, "clear"), getBranchesAsObjArray = /* @__PURE__ */ __name(function() {
	return [...state.records.branchConfig.values()].map((f, V) => f.order !== null && f.order !== void 0 ? f : {
		...f,
		order: parseFloat(`0.${V}`)
	}).sort((f, V) => (f.order ?? 0) - (V.order ?? 0)).map(({ name: f }) => ({ name: f }));
}, "getBranchesAsObjArray"), getBranches = /* @__PURE__ */ __name(function() {
	return state.records.branches;
}, "getBranches"), getCommits = /* @__PURE__ */ __name(function() {
	return state.records.commits;
}, "getCommits"), getCommitsArray = /* @__PURE__ */ __name(function() {
	let f = [...state.records.commits.values()];
	return f.forEach(function(f) {
		log.debug(f.id);
	}), f.sort((f, V) => f.seq - V.seq), f;
}, "getCommitsArray"), db = {
	commitType,
	getConfig: getConfig3,
	setDirection,
	setOptions,
	getOptions,
	commit,
	branch,
	merge,
	cherryPick,
	checkout,
	prettyPrint,
	clear: clear2,
	getBranchesAsObjArray,
	getBranches,
	getCommits,
	getCommitsArray,
	getCurrentBranch: /* @__PURE__ */ __name(function() {
		return state.records.currBranch;
	}, "getCurrentBranch"),
	getDirection: /* @__PURE__ */ __name(function() {
		return state.records.direction;
	}, "getDirection"),
	getHead: /* @__PURE__ */ __name(function() {
		return state.records.head;
	}, "getHead"),
	setAccTitle,
	getAccTitle,
	getAccDescription,
	setAccDescription,
	setDiagramTitle,
	getDiagramTitle
}, populate = /* @__PURE__ */ __name((f, V) => {
	populateCommonDb(f, V), f.dir && V.setDirection(f.dir);
	for (let H of f.statements) parseStatement(H, V);
}, "populate"), parseStatement = /* @__PURE__ */ __name((H, U) => {
	let W = {
		Commit: /* @__PURE__ */ __name((f) => U.commit(parseCommit(f)), "Commit"),
		Branch: /* @__PURE__ */ __name((f) => U.branch(parseBranch(f)), "Branch"),
		Merge: /* @__PURE__ */ __name((f) => U.merge(parseMerge(f)), "Merge"),
		Checkout: /* @__PURE__ */ __name((f) => U.checkout(parseCheckout(f)), "Checkout"),
		CherryPicking: /* @__PURE__ */ __name((f) => U.cherryPick(parseCherryPicking(f)), "CherryPicking")
	}[H.$type];
	W ? W(H) : log.error(`Unknown statement type: ${H.$type}`);
}, "parseStatement"), parseCommit = /* @__PURE__ */ __name((f) => ({
	id: f.id,
	msg: f.message ?? "",
	type: f.type === void 0 ? commitType.NORMAL : commitType[f.type],
	tags: f.tags ?? void 0
}), "parseCommit"), parseBranch = /* @__PURE__ */ __name((f) => ({
	name: f.name,
	order: f.order ?? 0
}), "parseBranch"), parseMerge = /* @__PURE__ */ __name((f) => ({
	branch: f.branch,
	id: f.id ?? "",
	type: f.type === void 0 ? void 0 : commitType[f.type],
	tags: f.tags ?? void 0
}), "parseMerge"), parseCheckout = /* @__PURE__ */ __name((f) => f.branch, "parseCheckout"), parseCherryPicking = /* @__PURE__ */ __name((f) => ({
	id: f.id,
	targetId: "",
	tags: f.tags?.length === 0 ? void 0 : f.tags,
	parent: f.parent
}), "parseCherryPicking"), parser = { parse: /* @__PURE__ */ __name(async (f) => {
	let H = await parse("gitGraph", f);
	log.debug(H), populate(H, db);
}, "parse") }, DEFAULT_GITGRAPH_CONFIG2 = getConfig2()?.gitGraph, LAYOUT_OFFSET = 10, COMMIT_STEP = 40, PX = 4, PY = 2, THEME_COLOR_LIMIT = 8, branchPos = /* @__PURE__ */ new Map(), commitPos = /* @__PURE__ */ new Map(), defaultPos = 30, allCommitsDict = /* @__PURE__ */ new Map(), lanes = [], maxPos = 0, dir = "LR", clear3 = /* @__PURE__ */ __name(() => {
	branchPos.clear(), commitPos.clear(), allCommitsDict.clear(), maxPos = 0, lanes = [], dir = "LR";
}, "clear"), drawText = /* @__PURE__ */ __name((f) => {
	let V = document.createElementNS("http://www.w3.org/2000/svg", "text");
	return (typeof f == "string" ? f.split(/\\n|\n|<br\s*\/?>/gi) : f).forEach((f) => {
		let H = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
		H.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"), H.setAttribute("dy", "1em"), H.setAttribute("x", "0"), H.setAttribute("class", "row"), H.textContent = f.trim(), V.appendChild(H);
	}), V;
}, "drawText"), findClosestParent = /* @__PURE__ */ __name((V) => {
	let H, U, W;
	return dir === "BT" ? (U = /* @__PURE__ */ __name((f, V) => f <= V, "comparisonFunc"), W = Infinity) : (U = /* @__PURE__ */ __name((f, V) => f >= V, "comparisonFunc"), W = 0), V.forEach((f) => {
		let V = dir === "TB" || dir == "BT" ? commitPos.get(f)?.y : commitPos.get(f)?.x;
		V !== void 0 && U(V, W) && (H = f, W = V);
	}), H;
}, "findClosestParent"), findClosestParentBT = /* @__PURE__ */ __name((f) => {
	let V = "", H = Infinity;
	return f.forEach((f) => {
		let U = commitPos.get(f).y;
		U <= H && (V = f, H = U);
	}), V || void 0;
}, "findClosestParentBT"), setParallelBTPos = /* @__PURE__ */ __name((f, V, H) => {
	let U = H, W = H, G = [];
	f.forEach((f) => {
		let H = V.get(f);
		if (!H) throw Error(`Commit not found for key ${f}`);
		H.parents.length ? (U = calculateCommitPosition(H), W = Math.max(U, W)) : G.push(H), setCommitPosition(H, U);
	}), U = W, G.forEach((f) => {
		setRootPosition(f, U, H);
	}), f.forEach((f) => {
		let H = V.get(f);
		if (H?.parents.length) {
			let f = findClosestParentBT(H.parents);
			U = commitPos.get(f).y - COMMIT_STEP, U <= W && (W = U);
			let V = branchPos.get(H.branch).pos, G = U - LAYOUT_OFFSET;
			commitPos.set(H.id, {
				x: V,
				y: G
			});
		}
	});
}, "setParallelBTPos"), findClosestParentPos = /* @__PURE__ */ __name((f) => {
	let V = findClosestParent(f.parents.filter((f) => f !== null));
	if (!V) throw Error(`Closest parent not found for commit ${f.id}`);
	let H = commitPos.get(V)?.y;
	if (H === void 0) throw Error(`Closest parent position not found for commit ${f.id}`);
	return H;
}, "findClosestParentPos"), calculateCommitPosition = /* @__PURE__ */ __name((f) => findClosestParentPos(f) + COMMIT_STEP, "calculateCommitPosition"), setCommitPosition = /* @__PURE__ */ __name((f, V) => {
	let H = branchPos.get(f.branch);
	if (!H) throw Error(`Branch not found for commit ${f.id}`);
	let U = H.pos, W = V + LAYOUT_OFFSET;
	return commitPos.set(f.id, {
		x: U,
		y: W
	}), {
		x: U,
		y: W
	};
}, "setCommitPosition"), setRootPosition = /* @__PURE__ */ __name((f, V, H) => {
	let U = branchPos.get(f.branch);
	if (!U) throw Error(`Branch not found for commit ${f.id}`);
	let W = V + H, G = U.pos;
	commitPos.set(f.id, {
		x: G,
		y: W
	});
}, "setRootPosition"), drawCommitBullet = /* @__PURE__ */ __name((f, V, H, U, W, G) => {
	if (G === commitType.HIGHLIGHT) f.append("rect").attr("x", H.x - 10).attr("y", H.y - 10).attr("width", 20).attr("height", 20).attr("class", `commit ${V.id} commit-highlight${W % THEME_COLOR_LIMIT} ${U}-outer`), f.append("rect").attr("x", H.x - 6).attr("y", H.y - 6).attr("width", 12).attr("height", 12).attr("class", `commit ${V.id} commit${W % THEME_COLOR_LIMIT} ${U}-inner`);
	else if (G === commitType.CHERRY_PICK) f.append("circle").attr("cx", H.x).attr("cy", H.y).attr("r", 10).attr("class", `commit ${V.id} ${U}`), f.append("circle").attr("cx", H.x - 3).attr("cy", H.y + 2).attr("r", 2.75).attr("fill", "#fff").attr("class", `commit ${V.id} ${U}`), f.append("circle").attr("cx", H.x + 3).attr("cy", H.y + 2).attr("r", 2.75).attr("fill", "#fff").attr("class", `commit ${V.id} ${U}`), f.append("line").attr("x1", H.x + 3).attr("y1", H.y + 1).attr("x2", H.x).attr("y2", H.y - 5).attr("stroke", "#fff").attr("class", `commit ${V.id} ${U}`), f.append("line").attr("x1", H.x - 3).attr("y1", H.y + 1).attr("x2", H.x).attr("y2", H.y - 5).attr("stroke", "#fff").attr("class", `commit ${V.id} ${U}`);
	else {
		let K = f.append("circle");
		if (K.attr("cx", H.x), K.attr("cy", H.y), K.attr("r", V.type === commitType.MERGE ? 9 : 10), K.attr("class", `commit ${V.id} commit${W % THEME_COLOR_LIMIT}`), G === commitType.MERGE) {
			let G = f.append("circle");
			G.attr("cx", H.x), G.attr("cy", H.y), G.attr("r", 6), G.attr("class", `commit ${U} ${V.id} commit${W % THEME_COLOR_LIMIT}`);
		}
		G === commitType.REVERSE && f.append("path").attr("d", `M ${H.x - 5},${H.y - 5}L${H.x + 5},${H.y + 5}M${H.x - 5},${H.y + 5}L${H.x + 5},${H.y - 5}`).attr("class", `commit ${U} ${V.id} commit${W % THEME_COLOR_LIMIT}`);
	}
}, "drawCommitBullet"), drawCommitLabel = /* @__PURE__ */ __name((f, V, H, U) => {
	if (V.type !== commitType.CHERRY_PICK && (V.customId && V.type === commitType.MERGE || V.type !== commitType.MERGE) && DEFAULT_GITGRAPH_CONFIG2?.showCommitLabel) {
		let W = f.append("g"), G = W.insert("rect").attr("class", "commit-label-bkg"), K = W.append("text").attr("x", U).attr("y", H.y + 25).attr("class", "commit-label").text(V.id), q = K.node()?.getBBox();
		if (q && (G.attr("x", H.posWithOffset - q.width / 2 - PY).attr("y", H.y + 13.5).attr("width", q.width + 2 * PY).attr("height", q.height + 2 * PY), dir === "TB" || dir === "BT" ? (G.attr("x", H.x - (q.width + 4 * PX + 5)).attr("y", H.y - 12), K.attr("x", H.x - (q.width + 4 * PX)).attr("y", H.y + q.height - 12)) : K.attr("x", H.posWithOffset - q.width / 2), DEFAULT_GITGRAPH_CONFIG2.rotateCommitLabel)) if (dir === "TB" || dir === "BT") K.attr("transform", "rotate(-45, " + H.x + ", " + H.y + ")"), G.attr("transform", "rotate(-45, " + H.x + ", " + H.y + ")");
		else {
			let f = -7.5 - (q.width + 10) / 25 * 9.5, V = 10 + q.width / 25 * 8.5;
			W.attr("transform", "translate(" + f + ", " + V + ") rotate(-45, " + U + ", " + H.y + ")");
		}
	}
}, "drawCommitLabel"), drawCommitTags = /* @__PURE__ */ __name((f, V, H, U) => {
	if (V.tags.length > 0) {
		let W = 0, G = 0, K = 0, q = [];
		for (let U of V.tags.reverse()) {
			let V = f.insert("polygon"), J = f.append("circle"), Y = f.append("text").attr("y", H.y - 16 - W).attr("class", "tag-label").text(U), X = Y.node()?.getBBox();
			if (!X) throw Error("Tag bbox not found");
			G = Math.max(G, X.width), K = Math.max(K, X.height), Y.attr("x", H.posWithOffset - X.width / 2), q.push({
				tag: Y,
				hole: J,
				rect: V,
				yOffset: W
			}), W += 20;
		}
		for (let { tag: f, hole: V, rect: W, yOffset: J } of q) {
			let q = K / 2, Y = H.y - 19.2 - J;
			if (W.attr("class", "tag-label-bkg").attr("points", `
      ${U - G / 2 - PX / 2},${Y + PY}  
      ${U - G / 2 - PX / 2},${Y - PY}
      ${H.posWithOffset - G / 2 - PX},${Y - q - PY}
      ${H.posWithOffset + G / 2 + PX},${Y - q - PY}
      ${H.posWithOffset + G / 2 + PX},${Y + q + PY}
      ${H.posWithOffset - G / 2 - PX},${Y + q + PY}`), V.attr("cy", Y).attr("cx", U - G / 2 + PX / 2).attr("r", 1.5).attr("class", "tag-hole"), dir === "TB" || dir === "BT") {
				let K = U + J;
				W.attr("class", "tag-label-bkg").attr("points", `
        ${H.x},${K + 2}
        ${H.x},${K - 2}
        ${H.x + LAYOUT_OFFSET},${K - q - 2}
        ${H.x + LAYOUT_OFFSET + G + 4},${K - q - 2}
        ${H.x + LAYOUT_OFFSET + G + 4},${K + q + 2}
        ${H.x + LAYOUT_OFFSET},${K + q + 2}`).attr("transform", "translate(12,12) rotate(45, " + H.x + "," + U + ")"), V.attr("cx", H.x + PX / 2).attr("cy", K).attr("transform", "translate(12,12) rotate(45, " + H.x + "," + U + ")"), f.attr("x", H.x + 5).attr("y", K + 3).attr("transform", "translate(14,14) rotate(45, " + H.x + "," + U + ")");
			}
		}
	}
}, "drawCommitTags"), getCommitClassType = /* @__PURE__ */ __name((f) => {
	switch (f.customType ?? f.type) {
		case commitType.NORMAL: return "commit-normal";
		case commitType.REVERSE: return "commit-reverse";
		case commitType.HIGHLIGHT: return "commit-highlight";
		case commitType.MERGE: return "commit-merge";
		case commitType.CHERRY_PICK: return "commit-cherry-pick";
		default: return "commit-normal";
	}
}, "getCommitClassType"), calculatePosition = /* @__PURE__ */ __name((f, V, H, U) => {
	let W = {
		x: 0,
		y: 0
	};
	if (f.parents.length > 0) {
		let H = findClosestParent(f.parents);
		if (H) {
			let G = U.get(H) ?? W;
			return V === "TB" ? G.y + COMMIT_STEP : V === "BT" ? (U.get(f.id) ?? W).y - COMMIT_STEP : G.x + COMMIT_STEP;
		}
	} else if (V === "TB") return defaultPos;
	else if (V === "BT") return (U.get(f.id) ?? W).y - COMMIT_STEP;
	else return 0;
	return 0;
}, "calculatePosition"), getCommitPosition = /* @__PURE__ */ __name((f, V, H) => {
	let U = dir === "BT" && H ? V : V + LAYOUT_OFFSET, W = dir === "TB" || dir === "BT" ? U : branchPos.get(f.branch)?.pos, G = dir === "TB" || dir === "BT" ? branchPos.get(f.branch)?.pos : U;
	if (G === void 0 || W === void 0) throw Error(`Position were undefined for commit ${f.id}`);
	return {
		x: G,
		y: W,
		posWithOffset: U
	};
}, "getCommitPosition"), drawCommits = /* @__PURE__ */ __name((V, H, U) => {
	if (!DEFAULT_GITGRAPH_CONFIG2) throw Error("GitGraph config not found");
	let W = V.append("g").attr("class", "commit-bullets"), G = V.append("g").attr("class", "commit-labels"), K = dir === "TB" || dir === "BT" ? defaultPos : 0, q = [...H.keys()], J = DEFAULT_GITGRAPH_CONFIG2?.parallelCommits ?? !1, Y = /* @__PURE__ */ __name((f, V) => {
		let U = H.get(f)?.seq, W = H.get(V)?.seq;
		return U !== void 0 && W !== void 0 ? U - W : 0;
	}, "sortKeys"), X = q.sort(Y);
	dir === "BT" && (J && setParallelBTPos(X, H, K), X = X.reverse()), X.forEach((f) => {
		let V = H.get(f);
		if (!V) throw Error(`Commit not found for key ${f}`);
		J && (K = calculatePosition(V, dir, K, commitPos));
		let q = getCommitPosition(V, K, J);
		if (U) {
			let f = getCommitClassType(V), H = V.customType ?? V.type;
			drawCommitBullet(W, V, q, f, branchPos.get(V.branch)?.index ?? 0, H), drawCommitLabel(G, V, q, K), drawCommitTags(G, V, q, K);
		}
		dir === "TB" || dir === "BT" ? commitPos.set(V.id, {
			x: q.x,
			y: q.posWithOffset
		}) : commitPos.set(V.id, {
			x: q.posWithOffset,
			y: q.y
		}), K = dir === "BT" && J ? K + COMMIT_STEP : K + COMMIT_STEP + LAYOUT_OFFSET, K > maxPos && (maxPos = K);
	});
}, "drawCommits"), shouldRerouteArrow = /* @__PURE__ */ __name((V, H, U, W, G) => {
	let K = (dir === "TB" || dir === "BT" ? U.x < W.x : U.y < W.y) ? H.branch : V.branch, q = /* @__PURE__ */ __name((f) => f.branch === K, "isOnBranchToGetCurve"), J = /* @__PURE__ */ __name((f) => f.seq > V.seq && f.seq < H.seq, "isBetweenCommits");
	return [...G.values()].some((f) => J(f) && q(f));
}, "shouldRerouteArrow"), findLane = /* @__PURE__ */ __name((f, V, H = 0) => {
	let U = f + Math.abs(f - V) / 2;
	return H > 5 ? U : lanes.every((f) => Math.abs(f - U) >= 10) ? (lanes.push(U), U) : findLane(f, V - Math.abs(f - V) / 5, H + 1);
}, "findLane"), drawArrow = /* @__PURE__ */ __name((f, V, H, U) => {
	let W = commitPos.get(V.id), G = commitPos.get(H.id);
	if (W === void 0 || G === void 0) throw Error(`Commit positions not found for commits ${V.id} and ${H.id}`);
	let K = shouldRerouteArrow(V, H, W, G, U), q = "", J = "", Y = 0, X = 0, Z = branchPos.get(H.branch)?.index;
	H.type === commitType.MERGE && V.id !== H.parents[0] && (Z = branchPos.get(V.branch)?.index);
	let Q;
	if (K) {
		q = "A 10 10, 0, 0, 0,", J = "A 10 10, 0, 0, 1,", Y = 10, X = 10;
		let f = W.y < G.y ? findLane(W.y, G.y) : findLane(G.y, W.y), H = W.x < G.x ? findLane(W.x, G.x) : findLane(G.x, W.x);
		dir === "TB" ? W.x < G.x ? Q = `M ${W.x} ${W.y} L ${H - Y} ${W.y} ${J} ${H} ${W.y + X} L ${H} ${G.y - Y} ${q} ${H + X} ${G.y} L ${G.x} ${G.y}` : (Z = branchPos.get(V.branch)?.index, Q = `M ${W.x} ${W.y} L ${H + Y} ${W.y} ${q} ${H} ${W.y + X} L ${H} ${G.y - Y} ${J} ${H - X} ${G.y} L ${G.x} ${G.y}`) : dir === "BT" ? W.x < G.x ? Q = `M ${W.x} ${W.y} L ${H - Y} ${W.y} ${q} ${H} ${W.y - X} L ${H} ${G.y + Y} ${J} ${H + X} ${G.y} L ${G.x} ${G.y}` : (Z = branchPos.get(V.branch)?.index, Q = `M ${W.x} ${W.y} L ${H + Y} ${W.y} ${J} ${H} ${W.y - X} L ${H} ${G.y + Y} ${q} ${H - X} ${G.y} L ${G.x} ${G.y}`) : W.y < G.y ? Q = `M ${W.x} ${W.y} L ${W.x} ${f - Y} ${q} ${W.x + X} ${f} L ${G.x - Y} ${f} ${J} ${G.x} ${f + X} L ${G.x} ${G.y}` : (Z = branchPos.get(V.branch)?.index, Q = `M ${W.x} ${W.y} L ${W.x} ${f + Y} ${J} ${W.x + X} ${f} L ${G.x - Y} ${f} ${q} ${G.x} ${f - X} L ${G.x} ${G.y}`);
	} else q = "A 20 20, 0, 0, 0,", J = "A 20 20, 0, 0, 1,", Y = 20, X = 20, dir === "TB" ? (W.x < G.x && (Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${W.x} ${G.y - Y} ${q} ${W.x + X} ${G.y} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${G.x - Y} ${W.y} ${J} ${G.x} ${W.y + X} L ${G.x} ${G.y}`), W.x > G.x && (q = "A 20 20, 0, 0, 0,", J = "A 20 20, 0, 0, 1,", Y = 20, X = 20, Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${W.x} ${G.y - Y} ${J} ${W.x - X} ${G.y} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${G.x + Y} ${W.y} ${q} ${G.x} ${W.y + X} L ${G.x} ${G.y}`), W.x === G.x && (Q = `M ${W.x} ${W.y} L ${G.x} ${G.y}`)) : dir === "BT" ? (W.x < G.x && (Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${W.x} ${G.y + Y} ${J} ${W.x + X} ${G.y} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${G.x - Y} ${W.y} ${q} ${G.x} ${W.y - X} L ${G.x} ${G.y}`), W.x > G.x && (q = "A 20 20, 0, 0, 0,", J = "A 20 20, 0, 0, 1,", Y = 20, X = 20, Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${W.x} ${G.y + Y} ${q} ${W.x - X} ${G.y} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${G.x - Y} ${W.y} ${q} ${G.x} ${W.y - X} L ${G.x} ${G.y}`), W.x === G.x && (Q = `M ${W.x} ${W.y} L ${G.x} ${G.y}`)) : (W.y < G.y && (Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${G.x - Y} ${W.y} ${J} ${G.x} ${W.y + X} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${W.x} ${G.y - Y} ${q} ${W.x + X} ${G.y} L ${G.x} ${G.y}`), W.y > G.y && (Q = H.type === commitType.MERGE && V.id !== H.parents[0] ? `M ${W.x} ${W.y} L ${G.x - Y} ${W.y} ${q} ${G.x} ${W.y - X} L ${G.x} ${G.y}` : `M ${W.x} ${W.y} L ${W.x} ${G.y + Y} ${J} ${W.x + X} ${G.y} L ${G.x} ${G.y}`), W.y === G.y && (Q = `M ${W.x} ${W.y} L ${G.x} ${G.y}`));
	if (Q === void 0) throw Error("Line definition not found");
	f.append("path").attr("d", Q).attr("class", "arrow arrow" + Z % THEME_COLOR_LIMIT);
}, "drawArrow"), drawArrows = /* @__PURE__ */ __name((f, V) => {
	let H = f.append("g").attr("class", "commit-arrows");
	[...V.keys()].forEach((f) => {
		let U = V.get(f);
		U.parents && U.parents.length > 0 && U.parents.forEach((f) => {
			drawArrow(H, V.get(f), U, V);
		});
	});
}, "drawArrows"), drawBranches = /* @__PURE__ */ __name((f, V) => {
	let H = f.append("g");
	V.forEach((f, V) => {
		let U = V % THEME_COLOR_LIMIT, W = branchPos.get(f.name)?.pos;
		if (W === void 0) throw Error(`Position not found for branch ${f.name}`);
		let G = H.append("line");
		G.attr("x1", 0), G.attr("y1", W), G.attr("x2", maxPos), G.attr("y2", W), G.attr("class", "branch branch" + U), dir === "TB" ? (G.attr("y1", defaultPos), G.attr("x1", W), G.attr("y2", maxPos), G.attr("x2", W)) : dir === "BT" && (G.attr("y1", maxPos), G.attr("x1", W), G.attr("y2", defaultPos), G.attr("x2", W)), lanes.push(W);
		let K = f.name, q = drawText(K), J = H.insert("rect"), Y = H.insert("g").attr("class", "branchLabel").insert("g").attr("class", "label branch-label" + U);
		Y.node().appendChild(q);
		let X = q.getBBox();
		J.attr("class", "branchLabelBkg label" + U).attr("rx", 4).attr("ry", 4).attr("x", -X.width - 4 - (DEFAULT_GITGRAPH_CONFIG2?.rotateCommitLabel === !0 ? 30 : 0)).attr("y", -X.height / 2 + 8).attr("width", X.width + 18).attr("height", X.height + 4), Y.attr("transform", "translate(" + (-X.width - 14 - (DEFAULT_GITGRAPH_CONFIG2?.rotateCommitLabel === !0 ? 30 : 0)) + ", " + (W - X.height / 2 - 1) + ")"), dir === "TB" ? (J.attr("x", W - X.width / 2 - 10).attr("y", 0), Y.attr("transform", "translate(" + (W - X.width / 2 - 5) + ", 0)")) : dir === "BT" ? (J.attr("x", W - X.width / 2 - 10).attr("y", maxPos), Y.attr("transform", "translate(" + (W - X.width / 2 - 5) + ", " + maxPos + ")")) : J.attr("transform", "translate(-19, " + (W - X.height / 2) + ")");
	});
}, "drawBranches"), setBranchPosition = /* @__PURE__ */ __name(function(f, V, H, U, W) {
	return branchPos.set(f, {
		pos: V,
		index: H
	}), V += 50 + (W ? 40 : 0) + (dir === "TB" || dir === "BT" ? U.width / 2 : 0), V;
}, "setBranchPosition"), diagram = {
	parser,
	db,
	renderer: { draw: /* @__PURE__ */ __name(function(f, H, U, W) {
		if (clear3(), log.debug("in gitgraph renderer", f + "\n", "id:", H, U), !DEFAULT_GITGRAPH_CONFIG2) throw Error("GitGraph config not found");
		let G = DEFAULT_GITGRAPH_CONFIG2.rotateCommitLabel ?? !1, K = W.db;
		allCommitsDict = K.getCommits();
		let q = K.getBranchesAsObjArray();
		dir = K.getDirection();
		let J = select_default(`[id="${H}"]`), Y = 0;
		q.forEach((f, V) => {
			let H = drawText(f.name), U = J.append("g"), W = U.insert("g").attr("class", "branchLabel"), K = W.insert("g").attr("class", "label branch-label");
			K.node()?.appendChild(H);
			let q = H.getBBox();
			Y = setBranchPosition(f.name, Y, V, q, G), K.remove(), W.remove(), U.remove();
		}), drawCommits(J, allCommitsDict, !1), DEFAULT_GITGRAPH_CONFIG2.showBranches && drawBranches(J, q), drawArrows(J, allCommitsDict), drawCommits(J, allCommitsDict, !0), utils_default.insertTitle(J, "gitTitleText", DEFAULT_GITGRAPH_CONFIG2.titleTopMargin ?? 0, K.getDiagramTitle()), setupGraphViewbox2(void 0, J, DEFAULT_GITGRAPH_CONFIG2.diagramPadding, DEFAULT_GITGRAPH_CONFIG2.useMaxWidth);
	}, "draw") },
	styles: /* @__PURE__ */ __name((f) => `
  .commit-id,
  .commit-msg,
  .branch-label {
    fill: lightgrey;
    color: lightgrey;
    font-family: 'trebuchet ms', verdana, arial, sans-serif;
    font-family: var(--mermaid-font-family);
  }
  ${[
		0,
		1,
		2,
		3,
		4,
		5,
		6,
		7
	].map((V) => `
        .branch-label${V} { fill: ${f["gitBranchLabel" + V]}; }
        .commit${V} { stroke: ${f["git" + V]}; fill: ${f["git" + V]}; }
        .commit-highlight${V} { stroke: ${f["gitInv" + V]}; fill: ${f["gitInv" + V]}; }
        .label${V}  { fill: ${f["git" + V]}; }
        .arrow${V} { stroke: ${f["git" + V]}; }
        `).join("\n")}

  .branch {
    stroke-width: 1;
    stroke: ${f.lineColor};
    stroke-dasharray: 2;
  }
  .commit-label { font-size: ${f.commitLabelFontSize}; fill: ${f.commitLabelColor};}
  .commit-label-bkg { font-size: ${f.commitLabelFontSize}; fill: ${f.commitLabelBackground}; opacity: 0.5; }
  .tag-label { font-size: ${f.tagLabelFontSize}; fill: ${f.tagLabelColor};}
  .tag-label-bkg { fill: ${f.tagLabelBackground}; stroke: ${f.tagLabelBorder}; }
  .tag-hole { fill: ${f.textColor}; }

  .commit-merge {
    stroke: ${f.primaryColor};
    fill: ${f.primaryColor};
  }
  .commit-reverse {
    stroke: ${f.primaryColor};
    fill: ${f.primaryColor};
    stroke-width: 3;
  }
  .commit-highlight-outer {
  }
  .commit-highlight-inner {
    stroke: ${f.primaryColor};
    fill: ${f.primaryColor};
  }

  .arrow { stroke-width: 8; stroke-linecap: round; fill: none}
  .gitTitleText {
    text-anchor: middle;
    font-size: 18px;
    fill: ${f.textColor};
  }
`, "getStyles")
};
export { diagram };
