import { $constructor } from "./core.js";
import { jsonStringifyReplacer } from "./util.js";
var initializer = (e, i) => {
	e.name = "$ZodError", Object.defineProperty(e, "_zod", {
		value: e._zod,
		enumerable: !1
	}), Object.defineProperty(e, "issues", {
		value: i,
		enumerable: !1
	}), e.message = JSON.stringify(i, jsonStringifyReplacer, 2), Object.defineProperty(e, "toString", {
		value: () => e.message,
		enumerable: !1
	});
};
const $ZodError = $constructor("$ZodError", initializer), $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(e, r = (e) => e.message) {
	let i = {}, a = [];
	for (let o of e.issues) o.path.length > 0 ? (i[o.path[0]] = i[o.path[0]] || [], i[o.path[0]].push(r(o))) : a.push(r(o));
	return {
		formErrors: a,
		fieldErrors: i
	};
}
function formatError(e, r = (e) => e.message) {
	let i = { _errors: [] }, a = (e) => {
		for (let o of e.issues) if (o.code === "invalid_union" && o.errors.length) o.errors.map((e) => a({ issues: e }));
		else if (o.code === "invalid_key") a({ issues: o.issues });
		else if (o.code === "invalid_element") a({ issues: o.issues });
		else if (o.path.length === 0) i._errors.push(r(o));
		else {
			let e = i, a = 0;
			for (; a < o.path.length;) {
				let i = o.path[a];
				a === o.path.length - 1 ? (e[i] = e[i] || { _errors: [] }, e[i]._errors.push(r(o))) : e[i] = e[i] || { _errors: [] }, e = e[i], a++;
			}
		}
	};
	return a(e), i;
}
export { $ZodError, $ZodRealError, flattenError, formatError };
