import { AISDKError, InvalidArgumentError, JSONParseError, TypeValidationError } from "../../provider/dist/index.js";
import { toJSONSchema } from "../../../zod/v4/core/json-schema-processors.js";
import { safeParseAsync } from "../../../zod/v4/classic/parse.js";
import { ZodFirstPartyTypeKind } from "../../../zod/v3/types.js";
var { btoa, atob } = globalThis, name = "AI_DownloadError", marker = `vercel.ai.error.${name}`, symbol = Symbol.for(marker), _a, _b, DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {
	constructor({ url: g, statusCode: G, statusText: K, cause: q, message: J = q == null ? `Failed to download ${g}: ${G} ${K}` : `Failed to download ${g}: ${q}` }) {
		super({
			name,
			message: J,
			cause: q
		}), this[_a] = !0, this.url = g, this.statusCode = G, this.statusText = K;
	}
	static isInstance(G) {
		return AISDKError.hasMarker(G, marker);
	}
}, DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
async function readResponseWithSizeLimit({ response: g, url: G, maxBytes: K = DEFAULT_MAX_DOWNLOAD_SIZE }) {
	let q = g.headers.get("content-length");
	if (q != null) {
		let g = parseInt(q, 10);
		if (!isNaN(g) && g > K) throw new DownloadError({
			url: G,
			message: `Download of ${G} exceeded maximum size of ${K} bytes (Content-Length: ${g}).`
		});
	}
	let J = g.body;
	if (J == null) return new Uint8Array();
	let Y = J.getReader(), X = [], Z = 0;
	try {
		for (;;) {
			let { done: g, value: q } = await Y.read();
			if (g) break;
			if (Z += q.length, Z > K) throw new DownloadError({
				url: G,
				message: `Download of ${G} exceeded maximum size of ${K} bytes.`
			});
			X.push(q);
		}
	} finally {
		try {
			await Y.cancel();
		} finally {
			Y.releaseLock();
		}
	}
	let Q = new Uint8Array(Z), $ = 0;
	for (let g of X) Q.set(g, $), $ += g.length;
	return Q;
}
var createIdGenerator = ({ prefix: g, size: K = 16, alphabet: q = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator: J = "-" } = {}) => {
	let Y = () => {
		let g = q.length, G = Array(K);
		for (let J = 0; J < K; J++) G[J] = q[Math.random() * g | 0];
		return G.join("");
	};
	if (g == null) return Y;
	if (q.includes(J)) throw new InvalidArgumentError({
		argument: "separator",
		message: `The separator "${J}" must not be part of the alphabet "${q}".`
	});
	return () => `${g}${J}${Y()}`;
};
createIdGenerator();
function getRuntimeEnvironmentUserAgent(g = globalThis) {
	return g.window ? "runtime/browser" : g.navigator?.userAgent ? `runtime/${g.navigator.userAgent.toLowerCase()}` : g.process?.versions?.node ? `runtime/node.js/${g.process.version.substring(0)}` : g.EdgeRuntime ? "runtime/vercel-edge" : "runtime/unknown";
}
function normalizeHeaders(g) {
	if (g == null) return {};
	let G = {};
	if (g instanceof Headers) g.forEach((g, K) => {
		G[K.toLowerCase()] = g;
	});
	else {
		Array.isArray(g) || (g = Object.entries(g));
		for (let [K, q] of g) q != null && (G[K.toLowerCase()] = q);
	}
	return G;
}
function withUserAgentSuffix(g, ...G) {
	let K = new Headers(normalizeHeaders(g)), q = K.get("user-agent") || "";
	return K.set("user-agent", [q, ...G].filter(Boolean).join(" ")), Object.fromEntries(K.entries());
}
var suspectProtoRx = /"__proto__"\s*:/, suspectConstructorRx = /"constructor"\s*:/;
function _parse(g) {
	let G = JSON.parse(g);
	return typeof G != "object" || !G || suspectProtoRx.test(g) === !1 && suspectConstructorRx.test(g) === !1 ? G : filter(G);
}
function filter(g) {
	let G = [g];
	for (; G.length;) {
		let g = G;
		G = [];
		for (let K of g) {
			if (Object.prototype.hasOwnProperty.call(K, "__proto__") || Object.prototype.hasOwnProperty.call(K, "constructor") && Object.prototype.hasOwnProperty.call(K.constructor, "prototype")) throw SyntaxError("Object contains forbidden prototype property");
			for (let g in K) {
				let q = K[g];
				q && typeof q == "object" && G.push(q);
			}
		}
	}
	return g;
}
function secureJsonParse(g) {
	let { stackTraceLimit: G } = Error;
	try {
		Error.stackTraceLimit = 0;
	} catch {
		return _parse(g);
	}
	try {
		return _parse(g);
	} finally {
		Error.stackTraceLimit = G;
	}
}
function addAdditionalPropertiesToJsonSchema(g) {
	if (g.type === "object" || Array.isArray(g.type) && g.type.includes("object")) {
		g.additionalProperties = !1;
		let { properties: G } = g;
		if (G != null) for (let g of Object.keys(G)) G[g] = visit(G[g]);
	}
	g.items != null && (g.items = Array.isArray(g.items) ? g.items.map(visit) : visit(g.items)), g.anyOf != null && (g.anyOf = g.anyOf.map(visit)), g.allOf != null && (g.allOf = g.allOf.map(visit)), g.oneOf != null && (g.oneOf = g.oneOf.map(visit));
	let { definitions: G } = g;
	if (G != null) for (let g of Object.keys(G)) G[g] = visit(G[g]);
	return g;
}
function visit(g) {
	return typeof g == "boolean" ? g : addAdditionalPropertiesToJsonSchema(g);
}
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"), defaultOptions = {
	name: void 0,
	$refStrategy: "root",
	basePath: ["#"],
	effectStrategy: "input",
	pipeStrategy: "all",
	dateStrategy: "format:date-time",
	mapStrategy: "entries",
	removeAdditionalStrategy: "passthrough",
	allowedAdditionalProperties: !0,
	rejectedAdditionalProperties: !1,
	definitionPath: "definitions",
	strictUnions: !1,
	definitions: {},
	errorMessages: !1,
	patternStrategy: "escape",
	applyRegexFlags: !1,
	emailStrategy: "format:email",
	base64Strategy: "contentEncoding:base64",
	nameStrategy: "ref"
}, getDefaultOptions = (g) => typeof g == "string" ? {
	...defaultOptions,
	name: g
} : {
	...defaultOptions,
	...g
};
function parseAnyDef() {
	return {};
}
function parseArrayDef(g, G) {
	let K = { type: "array" };
	return g.type?._def && g.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny && (K.items = parseDef(g.type._def, {
		...G,
		currentPath: [...G.currentPath, "items"]
	})), g.minLength && (K.minItems = g.minLength.value), g.maxLength && (K.maxItems = g.maxLength.value), g.exactLength && (K.minItems = g.exactLength.value, K.maxItems = g.exactLength.value), K;
}
function parseBigintDef(g) {
	let G = {
		type: "integer",
		format: "int64"
	};
	if (!g.checks) return G;
	for (let K of g.checks) switch (K.kind) {
		case "min":
			K.inclusive ? G.minimum = K.value : G.exclusiveMinimum = K.value;
			break;
		case "max":
			K.inclusive ? G.maximum = K.value : G.exclusiveMaximum = K.value;
			break;
		case "multipleOf":
			G.multipleOf = K.value;
			break;
	}
	return G;
}
function parseBooleanDef() {
	return { type: "boolean" };
}
function parseBrandedDef(g, G) {
	return parseDef(g.type._def, G);
}
var parseCatchDef = (g, G) => parseDef(g.innerType._def, G);
function parseDateDef(g, G, K) {
	let q = K ?? G.dateStrategy;
	if (Array.isArray(q)) return { anyOf: q.map((K, q) => parseDateDef(g, G, K)) };
	switch (q) {
		case "string":
		case "format:date-time": return {
			type: "string",
			format: "date-time"
		};
		case "format:date": return {
			type: "string",
			format: "date"
		};
		case "integer": return integerDateParser(g);
	}
}
var integerDateParser = (g) => {
	let G = {
		type: "integer",
		format: "unix-time"
	};
	for (let K of g.checks) switch (K.kind) {
		case "min":
			G.minimum = K.value;
			break;
		case "max":
			G.maximum = K.value;
			break;
	}
	return G;
};
function parseDefaultDef(g, G) {
	return {
		...parseDef(g.innerType._def, G),
		default: g.defaultValue()
	};
}
function parseEffectsDef(g, G) {
	return G.effectStrategy === "input" ? parseDef(g.schema._def, G) : parseAnyDef();
}
function parseEnumDef(g) {
	return {
		type: "string",
		enum: Array.from(g.values)
	};
}
var isJsonSchema7AllOfType = (g) => "type" in g && g.type === "string" ? !1 : "allOf" in g;
function parseIntersectionDef(g, G) {
	let K = [parseDef(g.left._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"allOf",
			"0"
		]
	}), parseDef(g.right._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"allOf",
			"1"
		]
	})].filter((g) => !!g), q = [];
	return K.forEach((g) => {
		if (isJsonSchema7AllOfType(g)) q.push(...g.allOf);
		else {
			let G = g;
			if ("additionalProperties" in g && g.additionalProperties === !1) {
				let { additionalProperties: K, ...q } = g;
				G = q;
			}
			q.push(G);
		}
	}), q.length ? { allOf: q } : void 0;
}
function parseLiteralDef(g) {
	let G = typeof g.value;
	return G !== "bigint" && G !== "number" && G !== "boolean" && G !== "string" ? { type: Array.isArray(g.value) ? "array" : "object" } : {
		type: G === "bigint" ? "integer" : G,
		const: g.value
	};
}
var emojiRegex = void 0, zodPatterns = {
	cuid: /^[cC][^\s-]{8,}$/,
	cuid2: /^[0-9a-z]+$/,
	ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
	email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
	emoji: () => (emojiRegex === void 0 && (emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u")), emojiRegex),
	uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
	ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
	ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
	ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
	ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
	base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
	base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
	nanoid: /^[a-zA-Z0-9_-]{21}$/,
	jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(g, G) {
	let K = { type: "string" };
	if (g.checks) for (let q of g.checks) switch (q.kind) {
		case "min":
			K.minLength = typeof K.minLength == "number" ? Math.max(K.minLength, q.value) : q.value;
			break;
		case "max":
			K.maxLength = typeof K.maxLength == "number" ? Math.min(K.maxLength, q.value) : q.value;
			break;
		case "email":
			switch (G.emailStrategy) {
				case "format:email":
					addFormat(K, "email", q.message, G);
					break;
				case "format:idn-email":
					addFormat(K, "idn-email", q.message, G);
					break;
				case "pattern:zod":
					addPattern(K, zodPatterns.email, q.message, G);
					break;
			}
			break;
		case "url":
			addFormat(K, "uri", q.message, G);
			break;
		case "uuid":
			addFormat(K, "uuid", q.message, G);
			break;
		case "regex":
			addPattern(K, q.regex, q.message, G);
			break;
		case "cuid":
			addPattern(K, zodPatterns.cuid, q.message, G);
			break;
		case "cuid2":
			addPattern(K, zodPatterns.cuid2, q.message, G);
			break;
		case "startsWith":
			addPattern(K, RegExp(`^${escapeLiteralCheckValue(q.value, G)}`), q.message, G);
			break;
		case "endsWith":
			addPattern(K, RegExp(`${escapeLiteralCheckValue(q.value, G)}$`), q.message, G);
			break;
		case "datetime":
			addFormat(K, "date-time", q.message, G);
			break;
		case "date":
			addFormat(K, "date", q.message, G);
			break;
		case "time":
			addFormat(K, "time", q.message, G);
			break;
		case "duration":
			addFormat(K, "duration", q.message, G);
			break;
		case "length":
			K.minLength = typeof K.minLength == "number" ? Math.max(K.minLength, q.value) : q.value, K.maxLength = typeof K.maxLength == "number" ? Math.min(K.maxLength, q.value) : q.value;
			break;
		case "includes":
			addPattern(K, RegExp(escapeLiteralCheckValue(q.value, G)), q.message, G);
			break;
		case "ip":
			q.version !== "v6" && addFormat(K, "ipv4", q.message, G), q.version !== "v4" && addFormat(K, "ipv6", q.message, G);
			break;
		case "base64url":
			addPattern(K, zodPatterns.base64url, q.message, G);
			break;
		case "jwt":
			addPattern(K, zodPatterns.jwt, q.message, G);
			break;
		case "cidr":
			q.version !== "v6" && addPattern(K, zodPatterns.ipv4Cidr, q.message, G), q.version !== "v4" && addPattern(K, zodPatterns.ipv6Cidr, q.message, G);
			break;
		case "emoji":
			addPattern(K, zodPatterns.emoji(), q.message, G);
			break;
		case "ulid":
			addPattern(K, zodPatterns.ulid, q.message, G);
			break;
		case "base64":
			switch (G.base64Strategy) {
				case "format:binary":
					addFormat(K, "binary", q.message, G);
					break;
				case "contentEncoding:base64":
					K.contentEncoding = "base64";
					break;
				case "pattern:zod":
					addPattern(K, zodPatterns.base64, q.message, G);
					break;
			}
			break;
		case "nanoid": addPattern(K, zodPatterns.nanoid, q.message, G);
		case "toLowerCase":
		case "toUpperCase":
		case "trim": break;
		default:
	}
	return K;
}
function escapeLiteralCheckValue(g, G) {
	return G.patternStrategy === "escape" ? escapeNonAlphaNumeric(g) : g;
}
var ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(g) {
	let G = "";
	for (let K = 0; K < g.length; K++) ALPHA_NUMERIC.has(g[K]) || (G += "\\"), G += g[K];
	return G;
}
function addFormat(g, G, K, q) {
	g.format || g.anyOf?.some((g) => g.format) ? (g.anyOf ||= [], g.format && (g.anyOf.push({ format: g.format }), delete g.format), g.anyOf.push({
		format: G,
		...K && q.errorMessages && { errorMessage: { format: K } }
	})) : g.format = G;
}
function addPattern(g, G, K, q) {
	g.pattern || g.allOf?.some((g) => g.pattern) ? (g.allOf ||= [], g.pattern && (g.allOf.push({ pattern: g.pattern }), delete g.pattern), g.allOf.push({
		pattern: stringifyRegExpWithFlags(G, q),
		...K && q.errorMessages && { errorMessage: { pattern: K } }
	})) : g.pattern = stringifyRegExpWithFlags(G, q);
}
function stringifyRegExpWithFlags(g, G) {
	if (!G.applyRegexFlags || !g.flags) return g.source;
	let K = {
		i: g.flags.includes("i"),
		m: g.flags.includes("m"),
		s: g.flags.includes("s")
	}, q = K.i ? g.source.toLowerCase() : g.source, J = "", Y = !1, X = !1, Z = !1;
	for (let g = 0; g < q.length; g++) {
		if (Y) {
			J += q[g], Y = !1;
			continue;
		}
		if (K.i) {
			if (X) {
				if (q[g].match(/[a-z]/)) {
					Z ? (J += q[g], J += `${q[g - 2]}-${q[g]}`.toUpperCase(), Z = !1) : q[g + 1] === "-" && q[g + 2]?.match(/[a-z]/) ? (J += q[g], Z = !0) : J += `${q[g]}${q[g].toUpperCase()}`;
					continue;
				}
			} else if (q[g].match(/[a-z]/)) {
				J += `[${q[g]}${q[g].toUpperCase()}]`;
				continue;
			}
		}
		if (K.m) {
			if (q[g] === "^") {
				J += "(^|(?<=[\r\n]))";
				continue;
			} else if (q[g] === "$") {
				J += "($|(?=[\r\n]))";
				continue;
			}
		}
		if (K.s && q[g] === ".") {
			J += X ? `${q[g]}\r
` : `[${q[g]}\r
]`;
			continue;
		}
		J += q[g], q[g] === "\\" ? Y = !0 : X && q[g] === "]" ? X = !1 : !X && q[g] === "[" && (X = !0);
	}
	try {
		new RegExp(J);
	} catch {
		return console.warn(`Could not convert regex pattern at ${G.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`), g.source;
	}
	return J;
}
function parseRecordDef(g, G) {
	let K = {
		type: "object",
		additionalProperties: parseDef(g.valueType._def, {
			...G,
			currentPath: [...G.currentPath, "additionalProperties"]
		}) ?? G.allowedAdditionalProperties
	};
	if (g.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && g.keyType._def.checks?.length) {
		let { type: q, ...J } = parseStringDef(g.keyType._def, G);
		return {
			...K,
			propertyNames: J
		};
	} else if (g.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return {
		...K,
		propertyNames: { enum: g.keyType._def.values }
	};
	else if (g.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && g.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && g.keyType._def.type._def.checks?.length) {
		let { type: q, ...J } = parseBrandedDef(g.keyType._def, G);
		return {
			...K,
			propertyNames: J
		};
	}
	return K;
}
function parseMapDef(g, G) {
	return G.mapStrategy === "record" ? parseRecordDef(g, G) : {
		type: "array",
		maxItems: 125,
		items: {
			type: "array",
			items: [parseDef(g.keyType._def, {
				...G,
				currentPath: [
					...G.currentPath,
					"items",
					"items",
					"0"
				]
			}) || parseAnyDef(), parseDef(g.valueType._def, {
				...G,
				currentPath: [
					...G.currentPath,
					"items",
					"items",
					"1"
				]
			}) || parseAnyDef()],
			minItems: 2,
			maxItems: 2
		}
	};
}
function parseNativeEnumDef(g) {
	let G = g.values, K = Object.keys(g.values).filter((g) => typeof G[G[g]] != "number").map((g) => G[g]), q = Array.from(new Set(K.map((g) => typeof g)));
	return {
		type: q.length === 1 ? q[0] === "string" ? "string" : "number" : ["string", "number"],
		enum: K
	};
}
function parseNeverDef() {
	return { not: parseAnyDef() };
}
function parseNullDef() {
	return { type: "null" };
}
var primitiveMappings = {
	ZodString: "string",
	ZodNumber: "number",
	ZodBigInt: "integer",
	ZodBoolean: "boolean",
	ZodNull: "null"
};
function parseUnionDef(g, G) {
	let K = g.options instanceof Map ? Array.from(g.options.values()) : g.options;
	if (K.every((g) => g._def.typeName in primitiveMappings && (!g._def.checks || !g._def.checks.length))) {
		let g = K.reduce((g, G) => {
			let K = primitiveMappings[G._def.typeName];
			return K && !g.includes(K) ? [...g, K] : g;
		}, []);
		return { type: g.length > 1 ? g : g[0] };
	} else if (K.every((g) => g._def.typeName === "ZodLiteral" && !g.description)) {
		let g = K.reduce((g, G) => {
			let K = typeof G._def.value;
			switch (K) {
				case "string":
				case "number":
				case "boolean": return [...g, K];
				case "bigint": return [...g, "integer"];
				case "object": if (G._def.value === null) return [...g, "null"];
				case "symbol":
				case "undefined":
				case "function":
				default: return g;
			}
		}, []);
		if (g.length === K.length) {
			let G = g.filter((g, G, K) => K.indexOf(g) === G);
			return {
				type: G.length > 1 ? G : G[0],
				enum: K.reduce((g, G) => g.includes(G._def.value) ? g : [...g, G._def.value], [])
			};
		}
	} else if (K.every((g) => g._def.typeName === "ZodEnum")) return {
		type: "string",
		enum: K.reduce((g, G) => [...g, ...G._def.values.filter((G) => !g.includes(G))], [])
	};
	return asAnyOf(g, G);
}
var asAnyOf = (g, G) => {
	let K = (g.options instanceof Map ? Array.from(g.options.values()) : g.options).map((g, K) => parseDef(g._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"anyOf",
			`${K}`
		]
	})).filter((g) => !!g && (!G.strictUnions || typeof g == "object" && Object.keys(g).length > 0));
	return K.length ? { anyOf: K } : void 0;
};
function parseNullableDef(g, G) {
	if ([
		"ZodString",
		"ZodNumber",
		"ZodBigInt",
		"ZodBoolean",
		"ZodNull"
	].includes(g.innerType._def.typeName) && (!g.innerType._def.checks || !g.innerType._def.checks.length)) return { type: [primitiveMappings[g.innerType._def.typeName], "null"] };
	let K = parseDef(g.innerType._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"anyOf",
			"0"
		]
	});
	return K && { anyOf: [K, { type: "null" }] };
}
function parseNumberDef(g) {
	let G = { type: "number" };
	if (!g.checks) return G;
	for (let K of g.checks) switch (K.kind) {
		case "int":
			G.type = "integer";
			break;
		case "min":
			K.inclusive ? G.minimum = K.value : G.exclusiveMinimum = K.value;
			break;
		case "max":
			K.inclusive ? G.maximum = K.value : G.exclusiveMaximum = K.value;
			break;
		case "multipleOf":
			G.multipleOf = K.value;
			break;
	}
	return G;
}
function parseObjectDef(g, G) {
	let K = {
		type: "object",
		properties: {}
	}, q = [], J = g.shape();
	for (let g in J) {
		let Y = J[g];
		if (Y === void 0 || Y._def === void 0) continue;
		let X = safeIsOptional(Y), Z = parseDef(Y._def, {
			...G,
			currentPath: [
				...G.currentPath,
				"properties",
				g
			],
			propertyPath: [
				...G.currentPath,
				"properties",
				g
			]
		});
		Z !== void 0 && (K.properties[g] = Z, X || q.push(g));
	}
	q.length && (K.required = q);
	let Y = decideAdditionalProperties(g, G);
	return Y !== void 0 && (K.additionalProperties = Y), K;
}
function decideAdditionalProperties(g, G) {
	if (g.catchall._def.typeName !== "ZodNever") return parseDef(g.catchall._def, {
		...G,
		currentPath: [...G.currentPath, "additionalProperties"]
	});
	switch (g.unknownKeys) {
		case "passthrough": return G.allowedAdditionalProperties;
		case "strict": return G.rejectedAdditionalProperties;
		case "strip": return G.removeAdditionalStrategy === "strict" ? G.allowedAdditionalProperties : G.rejectedAdditionalProperties;
	}
}
function safeIsOptional(g) {
	try {
		return g.isOptional();
	} catch {
		return !0;
	}
}
var parseOptionalDef = (g, G) => {
	if (G.currentPath.toString() === G.propertyPath?.toString()) return parseDef(g.innerType._def, G);
	let K = parseDef(g.innerType._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"anyOf",
			"1"
		]
	});
	return K ? { anyOf: [{ not: parseAnyDef() }, K] } : parseAnyDef();
}, parsePipelineDef = (g, G) => {
	if (G.pipeStrategy === "input") return parseDef(g.in._def, G);
	if (G.pipeStrategy === "output") return parseDef(g.out._def, G);
	let K = parseDef(g.in._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"allOf",
			"0"
		]
	});
	return { allOf: [K, parseDef(g.out._def, {
		...G,
		currentPath: [
			...G.currentPath,
			"allOf",
			K ? "1" : "0"
		]
	})].filter((g) => g !== void 0) };
};
function parsePromiseDef(g, G) {
	return parseDef(g.type._def, G);
}
function parseSetDef(g, G) {
	let K = {
		type: "array",
		uniqueItems: !0,
		items: parseDef(g.valueType._def, {
			...G,
			currentPath: [...G.currentPath, "items"]
		})
	};
	return g.minSize && (K.minItems = g.minSize.value), g.maxSize && (K.maxItems = g.maxSize.value), K;
}
function parseTupleDef(g, G) {
	return g.rest ? {
		type: "array",
		minItems: g.items.length,
		items: g.items.map((g, K) => parseDef(g._def, {
			...G,
			currentPath: [
				...G.currentPath,
				"items",
				`${K}`
			]
		})).reduce((g, G) => G === void 0 ? g : [...g, G], []),
		additionalItems: parseDef(g.rest._def, {
			...G,
			currentPath: [...G.currentPath, "additionalItems"]
		})
	} : {
		type: "array",
		minItems: g.items.length,
		maxItems: g.items.length,
		items: g.items.map((g, K) => parseDef(g._def, {
			...G,
			currentPath: [
				...G.currentPath,
				"items",
				`${K}`
			]
		})).reduce((g, G) => G === void 0 ? g : [...g, G], [])
	};
}
function parseUndefinedDef() {
	return { not: parseAnyDef() };
}
function parseUnknownDef() {
	return parseAnyDef();
}
var parseReadonlyDef = (g, G) => parseDef(g.innerType._def, G), selectParser = (g, G, K) => {
	switch (G) {
		case ZodFirstPartyTypeKind.ZodString: return parseStringDef(g, K);
		case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(g);
		case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(g, K);
		case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(g);
		case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();
		case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(g, K);
		case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();
		case ZodFirstPartyTypeKind.ZodNull: return parseNullDef();
		case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(g, K);
		case ZodFirstPartyTypeKind.ZodUnion:
		case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(g, K);
		case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(g, K);
		case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(g, K);
		case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(g, K);
		case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(g);
		case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(g);
		case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(g);
		case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(g, K);
		case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(g, K);
		case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(g, K);
		case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(g, K);
		case ZodFirstPartyTypeKind.ZodLazy: return () => g.getter()._def;
		case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(g, K);
		case ZodFirstPartyTypeKind.ZodNaN:
		case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();
		case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(g, K);
		case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();
		case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();
		case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(g, K);
		case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(g, K);
		case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(g, K);
		case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(g, K);
		case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(g, K);
		case ZodFirstPartyTypeKind.ZodFunction:
		case ZodFirstPartyTypeKind.ZodVoid:
		case ZodFirstPartyTypeKind.ZodSymbol: return;
		default: return /* @__PURE__ */ ((g) => void 0)(G);
	}
}, getRelativePath = (g, G) => {
	let K = 0;
	for (; K < g.length && K < G.length && g[K] === G[K]; K++);
	return [(g.length - K).toString(), ...G.slice(K)].join("/");
};
function parseDef(g, G, K = !1) {
	let q = G.seen.get(g);
	if (G.override) {
		let J = G.override?.call(G, g, G, q, K);
		if (J !== ignoreOverride) return J;
	}
	if (q && !K) {
		let g = get$ref(q, G);
		if (g !== void 0) return g;
	}
	let J = {
		def: g,
		path: G.currentPath,
		jsonSchema: void 0
	};
	G.seen.set(g, J);
	let Y = selectParser(g, g.typeName, G), X = typeof Y == "function" ? parseDef(Y(), G) : Y;
	if (X && addMeta(g, G, X), G.postProcess) {
		let K = G.postProcess(X, g, G);
		return J.jsonSchema = X, K;
	}
	return J.jsonSchema = X, X;
}
var get$ref = (g, G) => {
	switch (G.$refStrategy) {
		case "root": return { $ref: g.path.join("/") };
		case "relative": return { $ref: getRelativePath(G.currentPath, g.path) };
		case "none":
		case "seen": return g.path.length < G.currentPath.length && g.path.every((g, K) => G.currentPath[K] === g) ? (console.warn(`Recursive reference detected at ${G.currentPath.join("/")}! Defaulting to any`), parseAnyDef()) : G.$refStrategy === "seen" ? parseAnyDef() : void 0;
	}
}, addMeta = (g, G, K) => (g.description && (K.description = g.description), K), getRefs = (g) => {
	let G = getDefaultOptions(g), K = G.name === void 0 ? G.basePath : [
		...G.basePath,
		G.definitionPath,
		G.name
	];
	return {
		...G,
		currentPath: K,
		propertyPath: void 0,
		seen: new Map(Object.entries(G.definitions).map(([g, K]) => [K._def, {
			def: K._def,
			path: [
				...G.basePath,
				G.definitionPath,
				g
			],
			jsonSchema: void 0
		}]))
	};
}, zod3ToJsonSchema = (g, G) => {
	let K = getRefs(G), q = typeof G == "object" && G.definitions ? Object.entries(G.definitions).reduce((g, [G, q]) => ({
		...g,
		[G]: parseDef(q._def, {
			...K,
			currentPath: [
				...K.basePath,
				K.definitionPath,
				G
			]
		}, !0) ?? parseAnyDef()
	}), {}) : void 0, J = typeof G == "string" ? G : G?.nameStrategy === "title" ? void 0 : G?.name, Y = parseDef(g._def, J === void 0 ? K : {
		...K,
		currentPath: [
			...K.basePath,
			K.definitionPath,
			J
		]
	}, !1) ?? parseAnyDef(), X = typeof G == "object" && G.name !== void 0 && G.nameStrategy === "title" ? G.name : void 0;
	X !== void 0 && (Y.title = X);
	let Z = J === void 0 ? q ? {
		...Y,
		[K.definitionPath]: q
	} : Y : {
		$ref: [
			...K.$refStrategy === "relative" ? [] : K.basePath,
			K.definitionPath,
			J
		].join("/"),
		[K.definitionPath]: {
			...q,
			[J]: Y
		}
	};
	return Z.$schema = "http://json-schema.org/draft-07/schema#", Z;
}, schemaSymbol = Symbol.for("vercel.ai.schema");
function lazySchema(g) {
	let G;
	return () => (G ??= g(), G);
}
function jsonSchema(g, { validate: G } = {}) {
	return {
		[schemaSymbol]: !0,
		_type: void 0,
		get jsonSchema() {
			return typeof g == "function" && (g = g()), g;
		},
		validate: G
	};
}
function isSchema(g) {
	return typeof g == "object" && !!g && schemaSymbol in g && g[schemaSymbol] === !0 && "jsonSchema" in g && "validate" in g;
}
function asSchema(g) {
	return g == null ? jsonSchema({
		properties: {},
		additionalProperties: !1
	}) : isSchema(g) ? g : "~standard" in g ? g["~standard"].vendor === "zod" ? zodSchema(g) : standardSchema(g) : g();
}
function standardSchema(g) {
	return jsonSchema(() => addAdditionalPropertiesToJsonSchema(g["~standard"].jsonSchema.input({ target: "draft-07" })), { validate: async (G) => {
		let K = await g["~standard"].validate(G);
		return "value" in K ? {
			success: !0,
			value: K.value
		} : {
			success: !1,
			error: new TypeValidationError({
				value: G,
				cause: K.issues
			})
		};
	} });
}
function zod3Schema(g, G) {
	let K = G?.useReferences ?? !1;
	return jsonSchema(() => zod3ToJsonSchema(g, { $refStrategy: K ? "root" : "none" }), { validate: async (G) => {
		let K = await g.safeParseAsync(G);
		return K.success ? {
			success: !0,
			value: K.data
		} : {
			success: !1,
			error: K.error
		};
	} });
}
function zod4Schema(g, G) {
	let K = G?.useReferences ?? !1;
	return jsonSchema(() => addAdditionalPropertiesToJsonSchema(toJSONSchema(g, {
		target: "draft-7",
		io: "input",
		reused: K ? "ref" : "inline"
	})), { validate: async (G) => {
		let K = await safeParseAsync(g, G);
		return K.success ? {
			success: !0,
			value: K.data
		} : {
			success: !1,
			error: K.error
		};
	} });
}
function isZod4Schema(g) {
	return "_zod" in g;
}
function zodSchema(g, G) {
	return isZod4Schema(g) ? zod4Schema(g, G) : zod3Schema(g, G);
}
async function safeValidateTypes({ value: g, schema: G, context: K }) {
	let J = asSchema(G);
	try {
		if (J.validate == null) return {
			success: !0,
			value: g,
			rawValue: g
		};
		let G = await J.validate(g);
		return G.success ? {
			success: !0,
			value: G.value,
			rawValue: g
		} : {
			success: !1,
			error: TypeValidationError.wrap({
				value: g,
				cause: G.error,
				context: K
			}),
			rawValue: g
		};
	} catch (G) {
		return {
			success: !1,
			error: TypeValidationError.wrap({
				value: g,
				cause: G,
				context: K
			}),
			rawValue: g
		};
	}
}
async function safeParseJSON({ text: g, schema: G }) {
	try {
		let K = secureJsonParse(g);
		return G == null ? {
			success: !0,
			value: K,
			rawValue: K
		} : await safeValidateTypes({
			value: K,
			schema: G
		});
	} catch (G) {
		return {
			success: !1,
			error: JSONParseError.isInstance(G) ? G : new JSONParseError({
				text: g,
				cause: G
			}),
			rawValue: void 0
		};
	}
}
async function resolve(g) {
	return typeof g == "function" && (g = g()), Promise.resolve(g);
}
export { DEFAULT_MAX_DOWNLOAD_SIZE, DownloadError, asSchema, createIdGenerator, getRuntimeEnvironmentUserAgent, jsonSchema, lazySchema, readResponseWithSizeLimit, resolve, safeParseJSON, safeValidateTypes, withUserAgentSuffix, zodSchema };
