import { createRequire } from "node:module";
import { StructureModel, detectInteractiveSession, fromRef, isNode, isRef, isSymbol, loadConfigFile, log, nodeBrand, ref, refs } from "@hey-api/codegen-core";
import { ConfigError, OperationPath, OperationStrategy, applyNaming, buildSymbolIn, childContext, createOperationKey, createSchemaProcessor, createSchemaWalker, deduplicateSchema, definePluginConfig, dependencyFactory, ensureDirSync, escapeComment, findTsConfigPath, getInput, getLogs, getParser, hasOperationDataRequired, hasParameterGroupObjectRequired, isEnvironment, mappers, operationPagination, operationResponsesMap, outputHeaderToPrefix, parseUrl, pathToJsonPointer, pathToName, refToName, requestValidatorLayers, resolveSource, resolveValidatorLayer, satisfies, statusCodeToGroup, toCase, valueToObject, warnOnConflictingDuplicatePlugins } from "@hey-api/shared";
import colors from "ansi-colors";
import path from "node:path";
import { fileURLToPath } from "node:url";
import fs from "node:fs";
import { parseTsconfig } from "get-tsconfig";
import ts from "typescript";
//#region \0rolldown/runtime.js
var __require = /* @__PURE__ */ createRequire(import.meta.url);
//#endregion
//#region src/config/expand.ts
function expandToJobs(configs) {
	const jobs = [];
	let jobIndex = 0;
	for (const config of configs) {
		const inputs = getInput(config);
		const outputs = config.output instanceof Array ? config.output : [config.output];
		if (outputs.length === 1) jobs.push({
			config: {
				...config,
				input: inputs,
				output: outputs[0]
			},
			index: jobIndex++
		});
		else if (outputs.length > 1 && inputs.length !== outputs.length) {
			console.warn(`⚙️ ${colors.yellow("Warning:")} You provided ${colors.cyan(String(inputs.length))} ${colors.cyan(inputs.length === 1 ? "input" : "inputs")} and ${colors.yellow(String(outputs.length))} ${colors.yellow("outputs")}. This will produce identical output in multiple locations. You likely want to provide a single output or the same number of outputs as inputs.`);
			for (const output of outputs) jobs.push({
				config: {
					...config,
					input: inputs,
					output
				},
				index: jobIndex++
			});
		} else if (outputs.length > 1) outputs.forEach((output, index) => {
			jobs.push({
				config: {
					...config,
					input: inputs[index],
					output
				},
				index: jobIndex++
			});
		});
	}
	return jobs;
}
//#endregion
//#region src/config/packages.ts
/**
* Finds and reads the project's package.json file by searching upwards from the config file location,
* or from process.cwd() if no config file is provided.
* This ensures we get the correct dependencies even in monorepo setups.
*
* @param configFilePath - The path to the configuration file (e.g., openapi-ts.config.ts)
* @returns An object containing all project dependencies (dependencies, devDependencies, peerDependencies, optionalDependencies)
*/
const getProjectDependencies = (configFilePath) => {
	let currentDir = configFilePath ? path.dirname(configFilePath) : process.cwd();
	while (currentDir !== path.dirname(currentDir)) {
		const packageJsonPath = path.join(currentDir, "package.json");
		if (fs.existsSync(packageJsonPath)) try {
			const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
			return {
				...packageJson.dependencies,
				...packageJson.devDependencies,
				...packageJson.peerDependencies,
				...packageJson.optionalDependencies
			};
		} catch {}
		const parentDir = path.dirname(currentDir);
		if (parentDir === currentDir) break;
		currentDir = parentDir;
	}
	return {};
};
//#endregion
//#region src/config/output/postprocess.ts
const postProcessors = {
	"biome:check": {
		args: [
			"check",
			"--write",
			"{{path}}"
		],
		command: "biome",
		name: "Biome (Check)"
	},
	"biome:format": {
		args: [
			"format",
			"--write",
			"{{path}}"
		],
		command: "biome",
		name: "Biome (Format)"
	},
	"biome:lint": {
		args: [
			"lint",
			"--write",
			"{{path}}"
		],
		command: "biome",
		name: "Biome (Lint)"
	},
	eslint: {
		args: ["{{path}}", "--fix"],
		command: "eslint",
		name: "ESLint"
	},
	oxfmt: {
		args: ["{{path}}"],
		command: "oxfmt",
		name: "Oxfmt"
	},
	oxlint: {
		args: ["--fix", "{{path}}"],
		command: "oxlint",
		name: "Oxlint"
	},
	prettier: {
		args: [
			"--ignore-unknown",
			"{{path}}",
			"--write",
			"--ignore-path",
			"./.prettierignore"
		],
		command: "prettier",
		name: "Prettier"
	}
};
//#endregion
//#region src/config/output/config.ts
const __filename$1 = fileURLToPath(import.meta.url);
const __dirname$1 = path.dirname(__filename$1);
function getOutput(userConfig) {
	if (userConfig.output instanceof Array) throw new Error("Unexpected array of outputs in user configuration. This should have been expanded already.");
	const userOutput = typeof userConfig.output === "string" ? { path: userConfig.output } : userConfig.output ?? {};
	const legacyPostProcess = resolveLegacyPostProcess(userOutput);
	const output = valueToObject({
		defaultValue: {
			clean: true,
			entryFile: true,
			fileName: {
				case: "preserve",
				name: "{{name}}",
				suffix: ".gen"
			},
			format: null,
			lint: null,
			module: {},
			path: "",
			postProcess: [],
			preferExportAll: false
		},
		mappers: { object: (fields, defaultValue) => ({
			...fields,
			fileName: valueToObject({
				defaultValue: { ...defaultValue.fileName },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: fields.fileName
			}),
			module: valueToObject({
				defaultValue: {
					extension: fields.importFileExtension,
					resolve: fields.resolveModuleName
				},
				mappers: { object: (moduleFields) => ({
					...moduleFields,
					extension: fields.importFileExtension ?? moduleFields.extension,
					resolve: fields.resolveModuleName ?? moduleFields.resolve
				}) },
				value: fields.module
			})
		}) },
		value: userOutput
	});
	output.tsConfig = loadTsConfig(findTsConfigPath(__dirname$1, output.tsConfigPath));
	if (output.module.extension === void 0 && (output.tsConfig?.compilerOptions?.moduleResolution === "nodenext" || output.tsConfig?.compilerOptions?.moduleResolution === "NodeNext" || output.tsConfig?.compilerOptions?.moduleResolution === "node16" || output.tsConfig?.compilerOptions?.moduleResolution === "Node16" || output.tsConfig?.compilerOptions?.module === "nodenext" || output.tsConfig?.compilerOptions?.module === "NodeNext" || output.tsConfig?.compilerOptions?.module === "node16" || output.tsConfig?.compilerOptions?.module === "Node16")) output.module.extension = ".js";
	if (output.module.extension && !output.module.extension.startsWith(".")) output.module.extension = `.${output.module.extension}`;
	output.postProcess = normalizePostProcess(userOutput.postProcess ?? legacyPostProcess);
	output.source = resolveSource(output);
	return output;
}
function resolveLegacyPostProcess(config) {
	const result = [];
	if (config.lint !== void 0) {
		let processor;
		let preset;
		if (config.lint) {
			preset = config.lint === "biome" ? "biome:lint" : config.lint;
			processor = postProcessors[preset];
			if (processor) result.push(processor);
		}
		log.warnDeprecated({
			context: "output",
			field: "lint",
			replacement: `postProcess: [${processor && preset ? `'${preset}'` : ""}]`
		});
	}
	if (config.format !== void 0) {
		let processor;
		let preset;
		if (config.format) {
			preset = config.format === "biome" ? "biome:format" : config.format;
			processor = postProcessors[preset];
			if (processor) result.push(processor);
		}
		log.warnDeprecated({
			context: "output",
			field: "format",
			replacement: `postProcess: [${processor && preset ? `'${preset}'` : ""}]`
		});
	}
	return result;
}
function normalizePostProcess(input) {
	if (!input) return [];
	return input.map((item) => {
		if (typeof item === "string") {
			const preset = postProcessors[item];
			if (!preset) throw new Error(`Unknown post-processor preset: "${item}"`);
			return preset;
		}
		return {
			name: item.name ?? item.command,
			...item
		};
	});
}
function loadTsConfig(configPath) {
	if (!configPath) return null;
	try {
		return parseTsconfig(configPath);
	} catch {
		throw new Error(`Couldn't read tsconfig from path: ${configPath}`);
	}
}
//#endregion
//#region src/plugins/@angular/common/httpRequests/config.ts
function resolveHttpRequests(config, context) {
	let input = config.httpRequests;
	if (typeof input === "string" || typeof input === "function") input = { strategy: input };
	else if (typeof input === "boolean") input = { enabled: input };
	else if (!input) input = {};
	const strategy = input.strategy ?? "flat";
	return context.valueToObject({
		defaultValue: {
			container: "class",
			enabled: true,
			methods: "instance",
			nesting: "operationId",
			nestingDelimiters: /[./]/,
			strategy,
			strategyDefaultTag: "default"
		},
		mappers: { object(value) {
			value.containerName = context.valueToObject({
				defaultValue: strategy === "single" ? {
					casing: "PascalCase",
					name: "HttpRequests"
				} : { casing: "PascalCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.containerName
			});
			value.methodName = context.valueToObject({
				defaultValue: strategy === "flat" ? {
					casing: "camelCase",
					name: "{{name}}Request"
				} : { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.methodName
			});
			value.segmentName = context.valueToObject({
				defaultValue: {
					casing: "PascalCase",
					name: "{{name}}Requests"
				},
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.segmentName
			});
			return value;
		} },
		value: input
	});
}
//#endregion
//#region src/plugins/@angular/common/httpRequests/resolve.ts
function resolvePath$3(plugin) {
	if (plugin.config.httpRequests.nesting === "id") return OperationPath.id();
	if (plugin.config.httpRequests.nesting === "operationId") return OperationPath.fromOperationId({
		delimiters: plugin.config.httpRequests.nestingDelimiters,
		fallback: OperationPath.id()
	});
	return plugin.config.httpRequests.nesting;
}
function resolveHttpRequestsStrategy(plugin) {
	if (plugin.config.httpRequests.strategy === "flat") return OperationStrategy.flat({ path: (operation) => [resolvePath$3(plugin)(operation).join(".")] });
	if (plugin.config.httpRequests.strategy === "single") {
		const root = plugin.config.httpRequests.containerName;
		return OperationStrategy.single({
			path: resolvePath$3(plugin),
			root: typeof root.name === "string" ? root.name : root.name?.("") ?? ""
		});
	}
	if (plugin.config.httpRequests.strategy === "byTags") return OperationStrategy.byTags({
		fallback: plugin.config.httpRequests.strategyDefaultTag,
		path: resolvePath$3(plugin)
	});
	return plugin.config.httpRequests.strategy;
}
//#endregion
//#region src/plugins/@angular/common/httpResources/config.ts
function resolveHttpResources(config, context) {
	let input = config.httpResources;
	if (typeof input === "string" || typeof input === "function") input = { strategy: input };
	else if (typeof input === "boolean") input = { enabled: input };
	else if (!input) input = {};
	const strategy = input.strategy ?? "flat";
	return context.valueToObject({
		defaultValue: {
			container: "class",
			enabled: true,
			methods: "instance",
			nesting: "operationId",
			nestingDelimiters: /[./]/,
			strategy,
			strategyDefaultTag: "default"
		},
		mappers: { object(value) {
			value.containerName = context.valueToObject({
				defaultValue: strategy === "single" ? {
					casing: "PascalCase",
					name: "HttpResources"
				} : { casing: "PascalCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.containerName
			});
			value.methodName = context.valueToObject({
				defaultValue: strategy === "flat" ? {
					casing: "camelCase",
					name: "{{name}}Resource"
				} : { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.methodName
			});
			value.segmentName = context.valueToObject({
				defaultValue: {
					casing: "PascalCase",
					name: "{{name}}Resources"
				},
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.segmentName
			});
			return value;
		} },
		value: input
	});
}
//#endregion
//#region src/plugins/@angular/common/httpResources/resolve.ts
function resolvePath$2(plugin) {
	if (plugin.config.httpResources.nesting === "id") return OperationPath.id();
	if (plugin.config.httpResources.nesting === "operationId") return OperationPath.fromOperationId({
		delimiters: plugin.config.httpResources.nestingDelimiters,
		fallback: OperationPath.id()
	});
	return plugin.config.httpResources.nesting;
}
function resolveHttpResourcesStrategy(plugin) {
	if (plugin.config.httpResources.strategy === "flat") return OperationStrategy.flat({ path: (operation) => [resolvePath$2(plugin)(operation).join(".")] });
	if (plugin.config.httpResources.strategy === "single") {
		const root = plugin.config.httpResources.containerName;
		return OperationStrategy.single({
			path: resolvePath$2(plugin),
			root: typeof root.name === "string" ? root.name : root.name?.("") ?? ""
		});
	}
	if (plugin.config.httpResources.strategy === "byTags") return OperationStrategy.byTags({
		fallback: plugin.config.httpResources.strategyDefaultTag,
		path: resolvePath$2(plugin)
	});
	return plugin.config.httpResources.strategy;
}
//#endregion
//#region src/config/utils.ts
function getTypedConfig(plugin) {
	if ("context" in plugin) return plugin.context.config;
	return plugin.config;
}
//#endregion
//#region src/plugins/@hey-api/client-core/utils.ts
function getClientBaseUrlKey(config) {
	const client = getClientPlugin(config);
	if (client.name === "@hey-api/client-axios" || client.name === "@hey-api/client-nuxt") return "baseURL";
	return "baseUrl";
}
function getClientPlugin(config) {
	for (const name of config.pluginOrder) {
		const plugin = config.plugins[name];
		if (plugin?.tags?.includes("client")) return plugin;
	}
	return {
		config: { name: "" },
		name: ""
	};
}
//#endregion
//#region src/ts-dsl/base.ts
var TsDsl = class {
	analyze(_) {}
	clone() {
		const cloned = Object.create(Object.getPrototypeOf(this));
		Object.assign(cloned, this);
		return cloned;
	}
	exported;
	file;
	get name() {
		return {
			...this._name,
			set: (value) => {
				this._name = ref(value);
				if (isSymbol(value)) value.setNode(this);
			},
			toString: () => this._name ? this.$name(this._name) : ""
		};
	}
	nameSanitizer;
	language = "typescript";
	parent;
	root = false;
	scope = "value";
	structuralChildren;
	structuralParents;
	symbol;
	toAst() {}
	"~brand" = nodeBrand;
	$if(value, ifTrue, ifFalse) {
		if (value) {
			let result;
			try {
				result = ifTrue?.(this, value);
			} catch {}
			if (result === void 0) try {
				result = ifTrue?.(value);
			} catch {}
			if (result === void 0) try {
				result = ifTrue?.();
			} catch {}
			return result ?? this;
		}
		if (ifFalse) {
			let result;
			try {
				result = ifFalse?.(this, value);
			} catch {}
			if (result === void 0) try {
				result = ifFalse?.(value);
			} catch {}
			if (result === void 0) try {
				result = ifFalse?.();
			} catch {}
			return result ?? this;
		}
		return this;
	}
	$maybeId(expr) {
		return typeof expr === "string" ? ts.factory.createIdentifier(expr) : expr;
	}
	$name(name) {
		const value = fromRef(name);
		if (isSymbol(value)) try {
			return value.finalName;
		} catch {
			return value.name;
		}
		return String(value);
	}
	$node(value) {
		if (value === void 0) return;
		if (isRef(value)) value = fromRef(value);
		if (isSymbol(value)) return this.$maybeId(value.finalName);
		if (typeof value === "string") return this.$maybeId(value);
		if (value instanceof Array) return value.map((item) => {
			if (isRef(item)) item = fromRef(item);
			return this.unwrap(item);
		});
		return this.unwrap(value);
	}
	$type(value, args) {
		if (value === void 0) return;
		if (isRef(value)) value = fromRef(value);
		if (isSymbol(value)) return ts.factory.createTypeReferenceNode(value.finalName, args);
		if (typeof value === "string") return ts.factory.createTypeReferenceNode(value, args);
		if (typeof value === "boolean") {
			const literal = value ? ts.factory.createTrue() : ts.factory.createFalse();
			return ts.factory.createLiteralTypeNode(literal);
		}
		if (typeof value === "number") return ts.factory.createLiteralTypeNode(ts.factory.createNumericLiteral(value));
		if (value instanceof Array) return value.map((item) => this.$type(item, args));
		return this.unwrap(value);
	}
	_name;
	/** Unwraps nested nodes into raw TypeScript AST. */
	unwrap(value) {
		return isNode(value) ? value.toAst() : value;
	}
};
var TypeTsDsl = class extends TsDsl {};
//#endregion
//#region src/ts-dsl/expr/id.ts
const Mixed$56 = TsDsl;
var IdTsDsl = class extends Mixed$56 {
	"~dsl" = "IdTsDsl";
	constructor(name) {
		super();
		this.name.set(name);
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		return ts.factory.createIdentifier(this.name.toString());
	}
};
//#endregion
//#region src/ts-dsl/layout/newline.ts
var NewlineTsDsl = class extends TsDsl {
	"~dsl" = "NewlineTsDsl";
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		return this.$node(new IdTsDsl("\n"));
	}
};
//#endregion
//#region src/ts-dsl/mixins/args.ts
/**
* Adds `.arg()` and `.args()` for managing expression arguments in call-like nodes.
*/
function ArgsMixin(Base) {
	class Args extends Base {
		_args = [];
		analyze(ctx) {
			super.analyze(ctx);
			for (const arg of this._args) ctx.analyze(arg);
		}
		arg(arg) {
			if (arg !== void 0) this._args.push(ref(arg));
			return this;
		}
		args(...args) {
			this._args.push(...args.filter((a) => a !== void 0).map((a) => ref(a)));
			return this;
		}
		$args() {
			return this.$node(this._args).map((arg) => this.$node(arg));
		}
	}
	return Args;
}
//#endregion
//#region src/ts-dsl/expr/prefix.ts
const Mixed$55 = TsDsl;
var PrefixTsDsl = class extends Mixed$55 {
	"~dsl" = "PrefixTsDsl";
	_expr;
	_op;
	constructor(expr, op) {
		super();
		this._expr = expr;
		this._op = op;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._expr);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the operand (the expression being prefixed). */
	expr(expr) {
		this._expr = expr;
		return this;
	}
	/** Sets the operator to MinusToken for negation (`-`). */
	neg() {
		this._op = ts.SyntaxKind.MinusToken;
		return this;
	}
	/** Sets the operator to ExclamationToken for logical NOT (`!`). */
	not() {
		this._op = ts.SyntaxKind.ExclamationToken;
		return this;
	}
	/** Sets the operator (e.g., `ts.SyntaxKind.ExclamationToken` for `!`). */
	op(op) {
		this._op = op;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createPrefixUnaryExpression(this._op, this.$node(this._expr));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Prefix unary expression missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._expr) missing.push(".expr()");
		if (!this._op) missing.push("operator (e.g., .not(), .neg())");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/utils/factories.ts
function createFactory(name) {
	let impl;
	const slot = ((...args) => {
		if (!impl) throw new Error(`${name} factory not registered`);
		return impl(...args);
	});
	slot.set = (fn) => {
		impl = fn;
	};
	return slot;
}
const f = {
	as: createFactory("as"),
	attr: createFactory("attr"),
	await: createFactory("await"),
	call: createFactory("call"),
	method: createFactory("method"),
	new: createFactory("new"),
	return: createFactory("return"),
	spread: createFactory("spread"),
	type: {
		expr: createFactory("type.expr"),
		idx: createFactory("type.idx"),
		operator: createFactory("type.operator"),
		query: createFactory("type.query"),
		tupleMember: createFactory("type.tupleMember")
	},
	typeofExpr: createFactory("typeofExpr")
};
//#endregion
//#region src/ts-dsl/mixins/as.ts
function AsMixin(Base) {
	class As extends Base {
		analyze(ctx) {
			super.analyze(ctx);
		}
		as(...args) {
			return f.as(this, ...args);
		}
	}
	return As;
}
//#endregion
//#region src/ts-dsl/expr/literal.ts
const Mixed$54 = AsMixin(TsDsl);
var LiteralTsDsl = class extends Mixed$54 {
	"~dsl" = "LiteralTsDsl";
	value;
	constructor(value) {
		super();
		this.value = value;
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		if (typeof this.value === "boolean") return this.value ? ts.factory.createTrue() : ts.factory.createFalse();
		if (typeof this.value === "number") {
			const expr = ts.factory.createNumericLiteral(Math.abs(this.value));
			return this.value < 0 ? this.$node(new PrefixTsDsl(expr).neg()) : expr;
		}
		if (typeof this.value === "string") return ts.factory.createStringLiteral(this.value, true);
		if (typeof this.value === "bigint") return ts.factory.createBigIntLiteral(this.value.toString());
		if (this.value === null) return ts.factory.createNull();
		throw new Error(`Unsupported literal: ${String(this.value)}`);
	}
};
const regexp = {
	illegalStartCharacters: /^[^$_\p{ID_Start}]+/u,
	number: /^-?\d+(\.\d+)?$/,
	typeScriptIdentifier: /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u
};
const keywords = {
	browserGlobals: [
		"AbortController",
		"AbortSignal",
		"Blob",
		"CustomEvent",
		"document",
		"Event",
		"EventTarget",
		"fetch",
		"File",
		"FileList",
		"FileReader",
		"FormData",
		"Headers",
		"history",
		"location",
		"navigator",
		"Request",
		"Response",
		"TextDecoder",
		"TextEncoder",
		"URL",
		"URLSearchParams",
		"window"
	],
	javaScriptGlobals: [
		"Array",
		"ArrayBuffer",
		"atob",
		"BigInt",
		"Boolean",
		"btoa",
		"clearInterval",
		"clearTimeout",
		"console",
		"crypto",
		"DataView",
		"Date",
		"Error",
		"Function",
		"globalThis",
		"Infinity",
		"Intl",
		"JSON",
		"Map",
		"Math",
		"NaN",
		"Number",
		"Object",
		"performance",
		"Promise",
		"Proxy",
		"queueMicrotask",
		"Reflect",
		"RegExp",
		"Set",
		"setInterval",
		"setTimeout",
		"String",
		"structuredClone",
		"Symbol",
		"WeakMap",
		"WeakSet"
	],
	javaScriptKeywords: [
		"arguments",
		"async",
		"await",
		"break",
		"case",
		"catch",
		"class",
		"const",
		"continue",
		"debugger",
		"default",
		"delete",
		"do",
		"else",
		"enum",
		"eval",
		"export",
		"extends",
		"false",
		"finally",
		"for",
		"from",
		"function",
		"if",
		"implements",
		"import",
		"in",
		"instanceof",
		"interface",
		"let",
		"new",
		"null",
		"package",
		"private",
		"protected",
		"public",
		"return",
		"static",
		"super",
		"switch",
		"this",
		"throw",
		"true",
		"try",
		"typeof",
		"var",
		"void",
		"while",
		"with",
		"yield"
	],
	nodeGlobals: [
		"__dirname",
		"__filename",
		"Buffer",
		"exports",
		"global",
		"module",
		"process",
		"require"
	],
	typeScriptKeywords: [
		"any",
		"as",
		"bigint",
		"boolean",
		"namespace",
		"never",
		"null",
		"number",
		"string",
		"symbol",
		"type",
		"undefined",
		"unknown",
		"void"
	]
};
//#endregion
//#region src/ts-dsl/utils/reserved.ts
var ReservedList = class {
	_array;
	_set;
	constructor(values) {
		this._array = values;
		this._set = new Set(values);
	}
	get "~values"() {
		return this._set;
	}
	/**
	* Updates the reserved list with new values.
	*
	* @param values New reserved values or a function that receives the previous
	* reserved values and returns the new ones.
	*/
	set(values) {
		const vals = typeof values === "function" ? values(this._array) : values;
		this._array = vals;
		this._set = new Set(vals);
	}
};
/**
* Reserved names for identifiers. These names will not be used
* for variables, functions, classes, or other identifiers in generated code.
*/
const reserved = {
	runtime: new ReservedList([
		...keywords.browserGlobals,
		...keywords.javaScriptGlobals,
		...keywords.javaScriptKeywords,
		...keywords.nodeGlobals,
		...keywords.typeScriptKeywords
	]),
	type: new ReservedList([...keywords.javaScriptKeywords, ...keywords.typeScriptKeywords])
};
//#endregion
//#region src/ts-dsl/utils/name.ts
const safeAccessorName = (name) => {
	regexp.number.lastIndex = 0;
	if (regexp.number.test(name)) return name.startsWith("-") ? `'${name}'` : name;
	regexp.typeScriptIdentifier.lastIndex = 0;
	if (regexp.typeScriptIdentifier.test(name)) return name;
	return `'${name}'`;
};
const safeMemberName = (name) => {
	regexp.typeScriptIdentifier.lastIndex = 0;
	if (regexp.typeScriptIdentifier.test(name)) return new IdTsDsl(name);
	return new LiteralTsDsl(name);
};
const safePropName = (name) => {
	regexp.number.lastIndex = 0;
	if (regexp.number.test(name)) return name.startsWith("-") ? new LiteralTsDsl(name) : new LiteralTsDsl(Number(name));
	regexp.typeScriptIdentifier.lastIndex = 0;
	if (regexp.typeScriptIdentifier.test(name)) return new IdTsDsl(name);
	return new LiteralTsDsl(name);
};
const validTypeScriptChar = /^[\u200c\u200d\p{ID_Continue}]$/u;
const safeName = (name, reserved) => {
	let sanitized = "";
	let index;
	const first = name[0] ?? "";
	regexp.illegalStartCharacters.lastIndex = 0;
	if (regexp.illegalStartCharacters.test(first)) if (validTypeScriptChar.test(first)) {
		sanitized += "_";
		index = 0;
	} else {
		sanitized += "_";
		index = 1;
	}
	else {
		sanitized += first;
		index = 1;
	}
	while (index < name.length) {
		const char = name[index] ?? "";
		sanitized += validTypeScriptChar.test(char) ? char : "_";
		index += 1;
	}
	if (reserved["~values"].has(sanitized)) sanitized = `${sanitized}_`;
	return sanitized || "_";
};
const safeRuntimeName = (name) => safeName(name, reserved.runtime);
const safeTypeName = (name) => safeName(name, reserved.type);
//#endregion
//#region src/ts-dsl/decl/decorator.ts
const Mixed$53 = ArgsMixin(TsDsl);
var DecoratorTsDsl = class extends Mixed$53 {
	"~dsl" = "DecoratorTsDsl";
	nameSanitizer = safeRuntimeName;
	constructor(name, ...args) {
		super();
		this.name.set(name);
		this.args(...args);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
	}
	toAst() {
		const target = this.$node(this.name);
		const args = this.$args();
		return ts.factory.createDecorator(args.length ? ts.factory.createCallExpression(target, void 0, args) : target);
	}
};
//#endregion
//#region src/ts-dsl/mixins/decorator.ts
function DecoratorMixin(Base) {
	class Decorator extends Base {
		decorators = [];
		analyze(ctx) {
			super.analyze(ctx);
			for (const decorator of this.decorators) ctx.analyze(decorator);
		}
		decorator(name, ...args) {
			this.decorators.push(new DecoratorTsDsl(name, ...args));
			return this;
		}
		$decorators() {
			return this.$node(this.decorators);
		}
	}
	return Decorator;
}
//#endregion
//#region src/ts-dsl/utils/context.ts
function accessChainToNode(accessChain) {
	let result;
	accessChain.forEach((node, index) => {
		if (index === 0) result = node;
		else result = result.attr(node.name);
	});
	return result;
}
function getAccessChainForNode(node) {
	const accessChain = structuralToAccessChain([...getStructuralChainForNode(node, /* @__PURE__ */ new Set())]);
	if (!accessChain.length) return [node.clone()];
	return accessChain.map((node) => node.clone());
}
function getScope(node) {
	return node.scope ?? "value";
}
function getStructuralChainForNode(node, visited) {
	if (visited.has(node)) return [];
	visited.add(node);
	if (isStopNode(node)) return [];
	if (node.structuralParents) for (const [parent] of node.structuralParents) {
		if (getScope(parent) !== getScope(node)) continue;
		const chain = getStructuralChainForNode(parent, visited);
		if (chain.length) return [...chain, node];
	}
	if (!node.root) return [];
	return [node];
}
function isAccessorNode(node) {
	return node["~dsl"] === "FieldTsDsl" || node["~dsl"] === "GetterTsDsl" || node["~dsl"] === "MethodTsDsl";
}
function isStopNode(node) {
	return node["~dsl"] === "FuncTsDsl" || node["~dsl"] === "TemplateTsDsl";
}
/**
* Fold a structural chain to an access chain by removing
* non-accessor nodes.
*/
function structuralToAccessChain(structuralChain) {
	const accessChain = [];
	structuralChain.forEach((node, index) => {
		if (index === 0) accessChain.push(node);
		else if (isAccessorNode(node)) accessChain.push(node);
	});
	return accessChain;
}
function transformAccessChain(accessChain, options = {}) {
	return accessChain.map((node, index) => {
		const transformedNode = options.transform?.(node, index, accessChain);
		if (transformedNode) return transformedNode;
		const accessNode = node.toAccessNode?.(node, options, {
			chain: accessChain,
			index,
			isLeaf: index === accessChain.length - 1,
			isRoot: index === 0,
			length: accessChain.length
		});
		if (accessNode) return accessNode;
		if (index === 0) {
			if (node["~dsl"] === "ClassTsDsl") {
				const nextNode = accessChain[index + 1];
				if (nextNode && isAccessorNode(nextNode)) {
					if (nextNode.hasModifier("static")) return $(node.name);
				}
				return $.new(node.name).args();
			}
			return $(node.name);
		}
		return node;
	});
}
var TsDslContext = class {
	/**
	* Build an expression for accessing the node.
	*
	* @param node - The node or symbol to build access for
	* @param options - Access options
	* @returns Expression for accessing the node
	*
	* @example
	* ```ts
	* ctx.access(node); // → Expression for accessing the node
	* ```
	*/
	access(node, options) {
		const n = isSymbol(node) ? node.node : node;
		if (!n) throw new Error(`Symbol ${node.name} is not resolved to a node.`);
		return accessChainToNode(transformAccessChain(getAccessChainForNode(n), options));
	}
	/**
	* Build an example.
	*
	* @param node - The node to generate an example for
	* @param options - Example options
	* @returns Full example string
	*
	* @example
	* ```ts
	* ctx.example(node, { moduleName: 'my-sdk' }); // → Full example string
	* ```
	*/
	example(node, options, astOptions) {
		if (astOptions) return TypeScriptRenderer.astToString(astOptions);
		options ||= {};
		const accessChain = getAccessChainForNode(node);
		if (options.importName) accessChain[0].name.set(options.importName);
		const importNode = $(accessChain[0].name.toString());
		const finalChain = transformAccessChain(accessChain, { context: "example" });
		const setupNode = options.importSetup ? typeof options.importSetup === "function" ? options.importSetup({
			$,
			node: importNode
		}) : options.importSetup : finalChain[0];
		const setupName = options.setupName;
		let payload = typeof options.payload === "function" ? options.payload({ $ }) : options.payload;
		payload = payload instanceof Array ? payload : payload ? [payload] : [];
		let nodes = [];
		if (setupName) nodes = [$.const(setupName).assign(setupNode), $.await(accessChainToNode([$(setupName), ...finalChain.slice(1)]).call(...payload))];
		else nodes = [$.await(accessChainToNode([setupNode, ...finalChain.slice(1)]).call(...payload))];
		const localName = importNode.name.toString();
		return TypeScriptRenderer.astToString({
			imports: [[{
				imports: !options.importKind || options.importKind === "named" ? [{
					isTypeOnly: false,
					localName,
					sourceName: localName
				}] : [],
				isTypeOnly: false,
				kind: options.importKind ?? "named",
				localName: options.importKind !== "named" ? localName : void 0,
				modulePath: options.moduleName ?? "your-package"
			}]],
			nodes,
			trailingNewline: false
		});
	}
};
const ctx = new TsDslContext();
//#endregion
//#region src/ts-dsl/layout/doc.ts
var DocTsDsl = class extends TsDsl {
	"~dsl" = "DocTsDsl";
	_lines = [];
	constructor(lines, fn) {
		super();
		if (lines) this.add(lines);
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	add(lines) {
		this._lines.push(lines);
		return this;
	}
	apply(node) {
		const lines = this._lines.reduce((lines, line) => {
			if (typeof line === "function") line = line(ctx);
			for (const l of typeof line === "string" ? [line] : line) if (l || l === "") lines.push(l);
			return lines;
		}, []);
		if (!lines.length) return node;
		const jsdocTexts = lines.map((line) => ts.factory.createJSDocText(`${line}\n`));
		const jsdoc = ts.factory.createJSDocComment(ts.factory.createNodeArray(jsdocTexts), void 0);
		const cleanedJsdoc = ts.createPrinter().printNode(ts.EmitHint.Unspecified, jsdoc, node.getSourceFile?.() ?? ts.createSourceFile("", "", ts.ScriptTarget.Latest)).replace("/*", "").replace("*  */", "");
		ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, cleanedJsdoc, true);
		return node;
	}
	toAst() {
		return this.$node(new IdTsDsl(""));
	}
};
//#endregion
//#region src/ts-dsl/mixins/doc.ts
function DocMixin(Base) {
	class Doc extends Base {
		_doc;
		analyze(ctx) {
			super.analyze(ctx);
		}
		doc(lines, fn) {
			this._doc = new DocTsDsl(lines, fn);
			return this;
		}
		$docs(node) {
			return this._doc ? this._doc.apply(node) : node;
		}
	}
	return Doc;
}
//#endregion
//#region src/ts-dsl/mixins/modifiers.ts
function modifierToKind(modifier) {
	switch (modifier) {
		case "abstract": return ts.SyntaxKind.AbstractKeyword;
		case "async": return ts.SyntaxKind.AsyncKeyword;
		case "const": return ts.SyntaxKind.ConstKeyword;
		case "declare": return ts.SyntaxKind.DeclareKeyword;
		case "default": return ts.SyntaxKind.DefaultKeyword;
		case "export": return ts.SyntaxKind.ExportKeyword;
		case "override": return ts.SyntaxKind.OverrideKeyword;
		case "private": return ts.SyntaxKind.PrivateKeyword;
		case "protected": return ts.SyntaxKind.ProtectedKeyword;
		case "public": return ts.SyntaxKind.PublicKeyword;
		case "readonly": return ts.SyntaxKind.ReadonlyKeyword;
		case "static": return ts.SyntaxKind.StaticKeyword;
	}
}
function ModifiersMixin(Base) {
	class Modifiers extends Base {
		modifiers = [];
		analyze(ctx) {
			super.analyze(ctx);
		}
		hasModifier(modifier) {
			const kind = modifierToKind(modifier);
			return Boolean(this.modifiers.find((mod) => mod.kind === kind));
		}
		_m(modifier, condition) {
			if (condition) {
				const kind = modifierToKind(modifier);
				this.modifiers.push(ts.factory.createModifier(kind));
			}
			return this;
		}
	}
	return Modifiers;
}
/**
* Mixin that adds an `abstract` modifier to a node.
*/
function AbstractMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Abstract extends Mixed {
		abstract(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("abstract", cond);
		}
	}
	return Abstract;
}
/**
* Mixin that adds an `async` modifier to a node.
*/
function AsyncMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Async extends Mixed {
		async(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("async", cond);
		}
	}
	return Async;
}
/**
* Mixin that adds a `const` modifier to a node.
*/
function ConstMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Const extends Mixed {
		const(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("const", cond);
		}
	}
	return Const;
}
/**
* Mixin that adds a `default` modifier to a node.
*/
function DefaultMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Default extends Mixed {
		/**
		* Adds the `default` keyword modifier if the condition is true.
		*
		* @param condition - Whether to add the modifier (default: true).
		* @returns The target object for chaining.
		*/
		default(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("default", cond);
		}
	}
	return Default;
}
/**
* Mixin that adds an `export` modifier to a node.
*/
function ExportMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Export extends Mixed {
		/**
		* Adds the `export` keyword modifier if the condition is true.
		*
		* @param condition - Whether to add the modifier (default: true).
		* @returns The target object for chaining.
		*/
		export(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			this.exported = cond;
			if (this.symbol) this.symbol.setExported(cond);
			return this._m("export", cond);
		}
	}
	return Export;
}
/**
* Mixin that adds a `private` modifier to a node.
*/
function PrivateMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Private extends Mixed {
		private(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("private", cond);
		}
	}
	return Private;
}
/**
* Mixin that adds a `protected` modifier to a node.
*/
function ProtectedMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Protected extends Mixed {
		protected(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("protected", cond);
		}
	}
	return Protected;
}
/**
* Mixin that adds a `public` modifier to a node.
*/
function PublicMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Public extends Mixed {
		public(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("public", cond);
		}
	}
	return Public;
}
/**
* Mixin that adds a `readonly` modifier to a node.
*/
function ReadonlyMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Readonly extends Mixed {
		readonly(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("readonly", cond);
		}
	}
	return Readonly;
}
/**
* Mixin that adds a `static` modifier to a node.
*/
function StaticMixin(Base) {
	const Mixed = ModifiersMixin(Base);
	class Static extends Mixed {
		static(condition) {
			const cond = !arguments.length ? true : Boolean(condition);
			return this._m("static", cond);
		}
	}
	return Static;
}
//#endregion
//#region src/ts-dsl/type/param.ts
const Mixed$52 = TsDsl;
var TypeParamTsDsl = class extends Mixed$52 {
	"~dsl" = "TypeParamTsDsl";
	scope = "type";
	constraint;
	defaultValue;
	constructor(name, fn) {
		super();
		if (name) this.name.set(name);
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this.constraint);
		ctx.analyze(this.defaultValue);
	}
	/** Sets the parameter default value. */
	default(value) {
		this.defaultValue = ref(value);
		return this;
	}
	extends(constraint) {
		this.constraint = ref(constraint);
		return this;
	}
	toAst() {
		if (!this.name.toString()) throw new Error("Missing type name");
		return ts.factory.createTypeParameterDeclaration(void 0, this.$node(this.name), this.$type(this.constraint), this.$type(this.defaultValue));
	}
};
//#endregion
//#region src/ts-dsl/mixins/type-params.ts
function TypeParamsMixin(Base) {
	class TypeParams extends Base {
		_generics = [];
		analyze(ctx) {
			super.analyze(ctx);
			for (const g of this._generics) ctx.analyze(g);
		}
		generic(...args) {
			const g = new TypeParamTsDsl(...args);
			this._generics.push(g);
			return this;
		}
		generics(...args) {
			for (let arg of args) {
				if (typeof arg === "string" || typeof arg === "number" || isSymbol(arg) || isRef(arg)) arg = new TypeParamTsDsl(arg);
				this._generics.push(arg);
			}
			return this;
		}
		$generics() {
			return this.$node(this._generics);
		}
	}
	return TypeParams;
}
//#endregion
//#region src/ts-dsl/mixins/optional.ts
function OptionalMixin(Base) {
	class Optional extends Base {
		_optional;
		analyze(ctx) {
			super.analyze(ctx);
		}
		optional(condition) {
			this._optional = !arguments.length ? true : Boolean(condition);
			return this;
		}
		required(condition) {
			this._optional = !arguments.length ? false : !condition;
			return this;
		}
	}
	return Optional;
}
//#endregion
//#region src/ts-dsl/mixins/value.ts
function ValueMixin(Base) {
	class Value extends Base {
		value;
		analyze(ctx) {
			super.analyze(ctx);
			ctx.analyze(this.value);
		}
		assign(expr) {
			this.value = expr;
			return this;
		}
		$value() {
			return this.$node(this.value);
		}
	}
	return Value;
}
//#endregion
//#region src/ts-dsl/token.ts
var TokenTsDsl = class extends TsDsl {
	"~dsl" = "TokenTsDsl";
	_kind;
	/** Sets the token kind */
	kind(kind) {
		this._kind = kind;
		return this;
	}
	/** Creates `-` */
	minus() {
		return this.kind(ts.SyntaxKind.MinusToken);
	}
	/** Creates `?` (optional) */
	optional() {
		return this.kind(ts.SyntaxKind.QuestionToken);
	}
	/** Creates `+` */
	plus() {
		return this.kind(ts.SyntaxKind.PlusToken);
	}
	/** Creates `?.` (optional chaining token) */
	questionDot() {
		return this.kind(ts.SyntaxKind.QuestionDotToken);
	}
	/** Creates `readonly` */
	readonly() {
		return this.kind(ts.SyntaxKind.ReadonlyKeyword);
	}
	/** Creates `...` (spread / rest) */
	spread() {
		return this.kind(ts.SyntaxKind.DotDotDotToken);
	}
	toAst() {
		this.$validate();
		return ts.factory.createToken(this._kind);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Token missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._kind) missing.push(".kind()");
		return missing;
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
};
//#endregion
//#region src/ts-dsl/mixins/type-args.ts
function TypeArgsMixin(Base) {
	class TypeArgs extends Base {
		_generics = [];
		analyze(ctx) {
			super.analyze(ctx);
			for (const g of this._generics) ctx.analyze(g);
		}
		generic(arg) {
			this._generics.push(ref(arg));
			return this;
		}
		generics(...args) {
			this._generics.push(...args.map((a) => ref(a)));
			return this;
		}
		$generics() {
			return this.$type(this._generics);
		}
	}
	return TypeArgs;
}
//#endregion
//#region src/ts-dsl/mixins/type-expr.ts
function TypeExprMixin(Base) {
	class TypeExpr extends Base {
		analyze(ctx) {
			super.analyze(ctx);
		}
		idx(...args) {
			return f.type.idx(this, ...args);
		}
		keyof() {
			return f.type.operator().keyof(this);
		}
		readonly() {
			return f.type.operator().readonly(this);
		}
		returnType(...args) {
			return f.type.expr("ReturnType").generic(f.type.query(this, ...args));
		}
		typeofExpr(...args) {
			return f.typeofExpr(this, ...args);
		}
		typeofType(...args) {
			return f.type.query(this, ...args);
		}
		unique() {
			return f.type.operator().unique(this);
		}
	}
	return TypeExpr;
}
//#endregion
//#region src/ts-dsl/type/attr.ts
const Mixed$51 = TypeExprMixin(TsDsl);
var TypeAttrTsDsl = class extends Mixed$51 {
	"~dsl" = "TypeAttrTsDsl";
	scope = "type";
	_base;
	_right;
	constructor(base, right) {
		super();
		if (right) {
			this.base(base);
			this.right(right);
		} else {
			this.base();
			this.right(base);
		}
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._base);
		ctx.analyze(this._right);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	base(base) {
		if (isRef(base)) this._base = base;
		else this._base = base ? ref(base) : void 0;
		return this;
	}
	right(right) {
		this._right = ref(right);
		return this;
	}
	toAst() {
		this.$validate();
		const left = this.$node(this._base);
		if (!ts.isEntityName(left)) throw new Error("TypeAttrTsDsl: base must be an EntityName");
		return ts.factory.createQualifiedName(left, this.$node(this._right));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Type attribute missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._base) missing.push(".base()");
		if (!this._right) missing.push(".right()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/expr.ts
const Mixed$50 = TypeArgsMixin(TypeExprMixin(TsDsl));
var TypeExprTsDsl = class extends Mixed$50 {
	"~dsl" = "TypeExprTsDsl";
	scope = "type";
	_exprInput;
	constructor(name, fn) {
		super();
		if (typeof name === "function") name(this);
		else {
			this._exprInput = name ? ref(name) : void 0;
			fn?.(this);
		}
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._exprInput);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Accesses a nested type (e.g., `Foo.Bar`). */
	attr(right) {
		this._exprInput = isNode(right) ? ref(right.base(this._exprInput)) : ref(new TypeAttrTsDsl(this._exprInput, right));
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createTypeReferenceNode(this.$type(this._exprInput), this.$generics());
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Type expression missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._exprInput) missing.push("name or .attr()");
		return missing;
	}
};
f.type.expr.set((...args) => new TypeExprTsDsl(...args));
//#endregion
//#region src/ts-dsl/decl/field.ts
const Mixed$49 = DecoratorMixin(DocMixin(OptionalMixin(PrivateMixin(ProtectedMixin(PublicMixin(ReadonlyMixin(StaticMixin(ValueMixin(TsDsl)))))))));
var FieldTsDsl = class extends Mixed$49 {
	"~dsl" = "FieldTsDsl";
	nameSanitizer = safeAccessorName;
	_type;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this._type);
	}
	/** Sets the field type. */
	type(type) {
		this._type = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type);
		return this;
	}
	toAst() {
		const node = ts.factory.createPropertyDeclaration([...this.$decorators(), ...this.modifiers], this.$node(this.name), this._optional ? this.$node(new TokenTsDsl().optional()) : void 0, this.$type(this._type), this.$value());
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/stmt/stmt.ts
const Mixed$48 = TsDsl;
var StmtTsDsl = class extends Mixed$48 {
	"~dsl" = "StmtTsDsl";
	_inner;
	constructor(inner) {
		super();
		this._inner = inner;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._inner);
	}
	toAst() {
		const node = this.$node(this._inner);
		return ts.isStatement(node) ? node : ts.factory.createExpressionStatement(node);
	}
};
//#endregion
//#region src/ts-dsl/mixins/do.ts
/**
* Adds `.do()` for appending statements or expressions to a body.
*/
function DoMixin(Base) {
	class Do extends Base {
		_do = [];
		analyze(ctx) {
			super.analyze(ctx);
			ctx.pushScope();
			try {
				for (const item of this._do) ctx.analyze(item);
			} finally {
				ctx.popScope();
			}
		}
		do(...items) {
			this._do.push(...items);
			return this;
		}
		$do() {
			return this.$node(this._do.map((item) => new StmtTsDsl(item)));
		}
	}
	return Do;
}
//#endregion
//#region src/ts-dsl/decl/pattern.ts
const Mixed$47 = TsDsl;
/**
* Builds binding patterns (e.g., `{ foo, bar }`, `[a, b, ...rest]`).
*/
var PatternTsDsl = class extends Mixed$47 {
	"~dsl" = "PatternTsDsl";
	pattern;
	_spread;
	analyze(ctx) {
		super.analyze(ctx);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Defines an array pattern (e.g., `[a, b, c]`). */
	array(...props) {
		this.pattern = {
			kind: "array",
			values: props[0] instanceof Array ? [...props[0]] : props
		};
		return this;
	}
	/** Defines an object pattern (e.g., `{ a, b: alias }`). */
	object(...props) {
		const entries = {};
		for (const p of props) if (typeof p === "string") entries[p] = p;
		else if (p instanceof Array) for (const n of p) entries[n] = n;
		else Object.assign(entries, p);
		this.pattern = {
			kind: "object",
			values: entries
		};
		return this;
	}
	/** Adds a spread element (e.g., `...rest`, `...options`, `...args`). */
	spread(name) {
		this._spread = name;
		return this;
	}
	toAst() {
		this.$validate();
		if (this.pattern.kind === "object") {
			const elements = Object.entries(this.pattern.values).map(([key, alias]) => key === alias ? ts.factory.createBindingElement(void 0, void 0, key, void 0) : ts.factory.createBindingElement(void 0, key, alias, void 0));
			const spread = this.createSpread();
			if (spread) elements.push(spread);
			return ts.factory.createObjectBindingPattern(elements);
		}
		if (this.pattern.kind === "array") {
			const elements = this.pattern.values.map((p) => ts.factory.createBindingElement(void 0, void 0, p, void 0));
			const spread = this.createSpread();
			if (spread) elements.push(spread);
			return ts.factory.createArrayBindingPattern(elements);
		}
		throw new Error("PatternTsDsl requires object() or array() pattern");
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Binding pattern missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this.pattern) missing.push(".array() or .object()");
		return missing;
	}
	createSpread() {
		return this._spread ? ts.factory.createBindingElement(this.$node(new TokenTsDsl().spread()), void 0, this.$node(new IdTsDsl(this._spread))) : void 0;
	}
};
//#endregion
//#region src/ts-dsl/mixins/pattern.ts
/**
* Mixin providing `.array()`, `.object()`, and `.spread()` methods for defining destructuring patterns.
*/
function PatternMixin(Base) {
	class Pattern extends Base {
		pattern;
		analyze(ctx) {
			super.analyze(ctx);
			ctx.analyze(this.pattern);
		}
		array(...props) {
			(this.pattern ??= new PatternTsDsl()).array(...props);
			return this;
		}
		object(...props) {
			(this.pattern ??= new PatternTsDsl()).object(...props);
			return this;
		}
		/** Adds a spread element (e.g., `...args`, `...options`) to the pattern. */
		spread(name) {
			(this.pattern ??= new PatternTsDsl()).spread(name);
			return this;
		}
		/** Renders the pattern into a `BindingName`. */
		$pattern() {
			if (!this.pattern) return;
			return this.$node(this.pattern);
		}
	}
	return Pattern;
}
//#endregion
//#region src/ts-dsl/decl/param.ts
const Mixed$46 = DecoratorMixin(OptionalMixin(PatternMixin(ValueMixin(TsDsl))));
var ParamTsDsl = class extends Mixed$46 {
	"~dsl" = "ParamTsDsl";
	_type;
	constructor(name, fn) {
		super();
		if (typeof name === "function") name(this);
		else {
			this.name.set(name);
			fn?.(this);
		}
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the parameter type. */
	type(node) {
		this._type = node instanceof TypeTsDsl ? node : new TypeExprTsDsl(node);
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createParameterDeclaration(this.$decorators(), void 0, this.$pattern() ?? this.name.toString(), this._optional ? this.$node(new TokenTsDsl().optional()) : void 0, this.$type(this._type), this.$value());
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Parameter missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this.$pattern() && !this.name.toString()) missing.push("name or pattern (.array()/.object())");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/mixins/param.ts
function ParamMixin(Base) {
	class Param extends Base {
		_params = [];
		analyze(ctx) {
			super.analyze(ctx);
			for (const param of this._params) ctx.analyze(param);
		}
		param(name, fn) {
			const p = new ParamTsDsl(name, fn);
			this._params.push(p);
			return this;
		}
		params(...params) {
			this._params.push(...params);
			return this;
		}
		$params() {
			return this.$node(this._params);
		}
	}
	return Param;
}
//#endregion
//#region src/ts-dsl/mixins/layout.ts
function LayoutMixin(Base) {
	class Layout extends Base {
		static DEFAULT_THRESHOLD = 3;
		layout;
		analyze(ctx) {
			super.analyze(ctx);
		}
		auto(threshold = Layout.DEFAULT_THRESHOLD) {
			this.layout = threshold;
			return this;
		}
		inline() {
			this.layout = false;
			return this;
		}
		pretty() {
			this.layout = true;
			return this;
		}
		$multiline(count) {
			if (this.layout === void 0) this.layout = Layout.DEFAULT_THRESHOLD;
			if (count === 0) return false;
			return typeof this.layout === "number" ? count >= this.layout : this.layout;
		}
	}
	return Layout;
}
//#endregion
//#region src/ts-dsl/stmt/block.ts
const Mixed$45 = DoMixin(LayoutMixin(TsDsl));
var BlockTsDsl = class extends Mixed$45 {
	"~dsl" = "BlockTsDsl";
	constructor(...items) {
		super();
		this.do(...items);
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		const statements = this.$do();
		return ts.factory.createBlock(statements, this.$multiline(statements.length));
	}
};
//#endregion
//#region src/ts-dsl/decl/init.ts
const Mixed$44 = DecoratorMixin(DoMixin(DocMixin(ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(TsDsl)))))));
var InitTsDsl = class extends Mixed$44 {
	"~dsl" = "InitTsDsl";
	constructor(fn) {
		super();
		fn?.(this);
	}
	analyze(ctx) {
		ctx.pushScope();
		try {
			super.analyze(ctx);
		} finally {
			ctx.popScope();
		}
	}
	toAst() {
		const node = ts.factory.createConstructorDeclaration([...this.$decorators(), ...this.modifiers], this.$params(), this.$node(new BlockTsDsl(...this._do).pretty()));
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/mixins/type-returns.ts
function TypeReturnsMixin(Base) {
	class TypeReturns extends Base {
		_returns;
		analyze(ctx) {
			super.analyze(ctx);
			ctx.analyze(this._returns);
		}
		returns(type) {
			this._returns = type instanceof TypeTsDsl ? type : new TypeExprTsDsl(type);
			return this;
		}
		$returns() {
			return this.$type(this._returns);
		}
	}
	return TypeReturns;
}
//#endregion
//#region src/ts-dsl/decl/method.ts
const Mixed$43 = AbstractMixin(AsyncMixin(DecoratorMixin(DoMixin(DocMixin(OptionalMixin(ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(StaticMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl)))))))))))));
var MethodTsDsl = class extends Mixed$43 {
	"~dsl" = "MethodTsDsl";
	nameSanitizer = safeAccessorName;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn?.(this);
	}
	analyze(ctx) {
		ctx.analyze(this.name);
		ctx.pushScope();
		try {
			super.analyze(ctx);
		} finally {
			ctx.popScope();
		}
	}
	toAst() {
		const node = ts.factory.createMethodDeclaration([...this.$decorators(), ...this.modifiers], void 0, this.$node(this.name), this._optional ? this.$node(new TokenTsDsl().optional()) : void 0, this.$generics(), this.$params(), this.$returns(), this.$node(new BlockTsDsl(...this._do).pretty()));
		return this.$docs(node);
	}
};
f.method.set((...args) => new MethodTsDsl(...args));
//#endregion
//#region src/ts-dsl/decl/class.ts
const Mixed$42 = AbstractMixin(DecoratorMixin(DefaultMixin(DocMixin(ExportMixin(TypeParamsMixin(TsDsl))))));
var ClassTsDsl = class extends Mixed$42 {
	"~dsl" = "ClassTsDsl";
	nameSanitizer = safeRuntimeName;
	baseClass;
	body = [];
	constructor(name) {
		super();
		this.name.set(name);
		if (isSymbol(name)) name.setKind("class");
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.baseClass);
		ctx.analyze(this.name);
		ctx.pushScope();
		try {
			for (const item of this.body) ctx.analyze(item);
		} finally {
			ctx.popScope();
		}
	}
	/** Returns true if the class has any members. */
	get hasBody() {
		return Boolean(this.body.length);
	}
	/** Adds one or more class members (fields, methods, etc.). */
	do(...items) {
		this.body.push(...items);
		return this;
	}
	/** Records a base class to extend from. */
	extends(base) {
		this.baseClass = base ? ref(base) : void 0;
		return this;
	}
	/** Adds a class field. */
	field(name, fn) {
		const f = new FieldTsDsl(name, fn);
		this.body.push(f);
		return this;
	}
	/** Adds a class constructor. */
	init(fn) {
		const i = typeof fn === "function" ? new InitTsDsl(fn) : fn || new InitTsDsl();
		this.body.push(i);
		return this;
	}
	/** Adds a class method. */
	method(name, fn) {
		const m = new MethodTsDsl(name, fn);
		this.body.push(m);
		return this;
	}
	/** Inserts an empty line between members for formatting. */
	newline() {
		this.body.push(new NewlineTsDsl());
		return this;
	}
	toAst() {
		const body = this.$node(this.body);
		const node = ts.factory.createClassDeclaration([...this.$decorators(), ...this.modifiers], this.$node(this.name), this.$generics(), this._heritage(), body);
		return this.$docs(node);
	}
	/** Builds heritage clauses (extends). */
	_heritage() {
		const node = this.$node(this.baseClass);
		if (!node) return [];
		return [ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [ts.factory.createExpressionWithTypeArguments(node, void 0)])];
	}
};
//#endregion
//#region src/ts-dsl/decl/member.ts
const Mixed$41 = DocMixin(TsDsl);
var EnumMemberTsDsl = class extends Mixed$41 {
	"~dsl" = "EnumMemberTsDsl";
	_value;
	constructor(name, value) {
		super();
		this.name.set(name);
		if (typeof value === "function") value(this);
		else this.value(value);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._value);
	}
	/** Sets the enum member value. */
	value(value) {
		this._value = value;
		return this;
	}
	toAst() {
		const node = ts.factory.createEnumMember(this.$node(safeMemberName(this.name.toString())), this.$node(this._value));
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/decl/enum.ts
const Mixed$40 = ConstMixin(DocMixin(ExportMixin(TsDsl)));
var EnumTsDsl = class extends Mixed$40 {
	"~dsl" = "EnumTsDsl";
	nameSanitizer = safeRuntimeName;
	_members = [];
	constructor(name, fn) {
		super();
		this.name.set(name);
		if (isSymbol(name)) name.setKind("enum");
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.pushScope();
		try {
			for (const member of this._members) ctx.analyze(member);
		} finally {
			ctx.popScope();
		}
	}
	/** Adds an enum member. */
	member(name, value) {
		const m = new EnumMemberTsDsl(name, value);
		this._members.push(m);
		return this;
	}
	/** Adds multiple enum members. */
	members(...members) {
		this._members.push(...members);
		return this;
	}
	toAst() {
		const node = ts.factory.createEnumDeclaration(this.modifiers, this.$node(this.name), this.$node(this._members));
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/decl/func.ts
const Mixed$39 = AbstractMixin(AsMixin(AsyncMixin(DecoratorMixin(DoMixin(DocMixin(ExportMixin(ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(StaticMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl))))))))))))));
var ImplFuncTsDsl = class extends Mixed$39 {
	"~dsl" = "FuncTsDsl";
	nameSanitizer = safeRuntimeName;
	mode;
	constructor(name, fn) {
		super();
		if (typeof name === "function") {
			this.mode = "arrow";
			name(this);
		} else if (name) {
			this.mode = "decl";
			this.name.set(name);
			if (isSymbol(name)) name.setKind("function");
			fn?.(this);
		}
	}
	analyze(ctx) {
		ctx.pushScope();
		try {
			super.analyze(ctx);
			ctx.analyze(this.name);
		} finally {
			ctx.popScope();
		}
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Switches the function to an arrow function form. */
	arrow() {
		this.mode = "arrow";
		return this;
	}
	/** Switches the function to a function declaration form. */
	decl() {
		this.mode = "decl";
		return this;
	}
	/** Switches the function to a function expression form. */
	expr() {
		this.mode = "expr";
		return this;
	}
	toAst() {
		this.$validate();
		const body = this.$node(new BlockTsDsl(...this._do).pretty());
		if (this.mode === "decl") {
			const node = ts.factory.createFunctionDeclaration([...this.$decorators(), ...this.modifiers], void 0, this.$node(this.name), this.$generics(), this.$params(), this.$returns(), body);
			return this.$docs(node);
		}
		if (this.mode === "expr") {
			const node = ts.factory.createFunctionExpression(this.modifiers, void 0, this.$node(this.name), this.$generics(), this.$params(), this.$returns(), body);
			return this.$docs(node);
		}
		const node = ts.factory.createArrowFunction(this.modifiers, this.$generics(), this.$params(), this.$returns(), void 0, body.statements.length === 1 && ts.isReturnStatement(body.statements[0]) && body.statements[0].expression ? body.statements[0].expression : body);
		return this.$docs(node);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Function ${this.mode} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (this.mode === "decl" && !this.name.toString()) missing.push("name");
		return missing;
	}
};
const FuncTsDsl = ImplFuncTsDsl;
//#endregion
//#region src/ts-dsl/decl/getter.ts
const Mixed$38 = AbstractMixin(AsyncMixin(DecoratorMixin(DoMixin(DocMixin(ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(StaticMixin(TypeReturnsMixin(TsDsl)))))))))));
var GetterTsDsl = class extends Mixed$38 {
	"~dsl" = "GetterTsDsl";
	nameSanitizer = safeAccessorName;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn?.(this);
	}
	analyze(ctx) {
		ctx.analyze(this.name);
		ctx.pushScope();
		try {
			super.analyze(ctx);
		} finally {
			ctx.popScope();
		}
	}
	toAst() {
		const node = ts.factory.createGetAccessorDeclaration([...this.$decorators(), ...this.modifiers], this.$node(this.name), this.$params(), this.$returns(), this.$node(new BlockTsDsl(...this._do).pretty()));
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/decl/setter.ts
const Mixed$37 = AbstractMixin(AsyncMixin(DecoratorMixin(DoMixin(DocMixin(ParamMixin(PrivateMixin(ProtectedMixin(PublicMixin(StaticMixin(TsDsl))))))))));
var SetterTsDsl = class extends Mixed$37 {
	"~dsl" = "SetterTsDsl";
	nameSanitizer = safeAccessorName;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn?.(this);
	}
	analyze(ctx) {
		ctx.analyze(this.name);
		ctx.pushScope();
		try {
			super.analyze(ctx);
		} finally {
			ctx.popScope();
		}
	}
	toAst() {
		const node = ts.factory.createSetAccessorDeclaration([...this.$decorators(), ...this.modifiers], this.$node(this.name), this.$params(), this.$node(new BlockTsDsl(...this._do).pretty()));
		return this.$docs(node);
	}
};
//#endregion
//#region src/ts-dsl/mixins/expr.ts
function ExprMixin(Base) {
	class Expr extends Base {
		analyze(ctx) {
			super.analyze(ctx);
		}
		attr(...args) {
			return f.attr(this, ...args);
		}
		await() {
			return f.await(this);
		}
		call(...args) {
			return f.call(this, ...args);
		}
		return() {
			return f.return(this);
		}
	}
	return Expr;
}
//#endregion
//#region src/ts-dsl/mixins/spread.ts
function SpreadMixin(Base) {
	class Spread extends Base {
		analyze(ctx) {
			super.analyze(ctx);
		}
		spread() {
			return f.spread(this);
		}
	}
	return Spread;
}
//#endregion
//#region src/ts-dsl/expr/array.ts
const Mixed$36 = AsMixin(ExprMixin(LayoutMixin(SpreadMixin(TsDsl))));
var ArrayTsDsl = class extends Mixed$36 {
	"~dsl" = "ArrayTsDsl";
	_elements = [];
	constructor(...exprs) {
		super();
		this.elements(...exprs);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const item of this._elements) ctx.analyze(item);
	}
	/** Adds a single array element. */
	element(expr) {
		const node = typeof expr === "string" || typeof expr === "number" || typeof expr === "boolean" ? new LiteralTsDsl(expr) : expr;
		this._elements.push(node);
		return this;
	}
	/** Adds multiple array elements. */
	elements(...exprs) {
		for (const expr of exprs) this.element(expr);
		return this;
	}
	toAst() {
		return ts.factory.createArrayLiteralExpression(this._elements.map((item) => this.$node(item)), this.$multiline(this._elements.length));
	}
};
//#endregion
//#region src/ts-dsl/expr/as.ts
const Mixed$35 = AsMixin(ExprMixin(TsDsl));
var AsTsDsl = class extends Mixed$35 {
	"~dsl" = "AsTsDsl";
	expr;
	type;
	constructor(expr, type) {
		super();
		this.expr = ref(expr);
		this.type = ref(type);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.expr);
		ctx.analyze(this.type);
	}
	toAst() {
		return ts.factory.createAsExpression(this.$node(this.expr), this.$type(this.type));
	}
};
f.as.set((...args) => new AsTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/binary.ts
const Mixed$34 = AsMixin(ExprMixin(TsDsl));
var BinaryTsDsl = class extends Mixed$34 {
	"~dsl" = "BinaryTsDsl";
	_base;
	_expr;
	_op;
	constructor(base, op, expr) {
		super();
		this._base = ref(base);
		this._op = op;
		if (expr) this._expr = ref(expr);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._base);
		ctx.analyze(this._expr);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Logical AND — `this && expr` */
	and(expr) {
		return this.opAndExpr("&&", expr);
	}
	/** Creates an assignment expression (e.g., `this = expr`). */
	assign(expr) {
		return this.opAndExpr("=", expr);
	}
	/** Nullish coalescing — `this ?? expr` */
	coalesce(expr) {
		return this.opAndExpr("??", expr);
	}
	/** Division — `this / expr` */
	div(expr) {
		return this.opAndExpr("/", expr);
	}
	/** Strict equality — `this === expr` */
	eq(expr) {
		return this.opAndExpr("===", expr);
	}
	/** Greater than — `this > expr` */
	gt(expr) {
		return this.opAndExpr(">", expr);
	}
	/** Greater than or equal — `this >= expr` */
	gte(expr) {
		return this.opAndExpr(">=", expr);
	}
	/** Loose equality — `this == expr` */
	looseEq(expr) {
		return this.opAndExpr("==", expr);
	}
	/** Loose inequality — `this != expr` */
	looseNeq(expr) {
		return this.opAndExpr("!=", expr);
	}
	/** Less than — `this < expr` */
	lt(expr) {
		return this.opAndExpr("<", expr);
	}
	/** Less than or equal — `this <= expr` */
	lte(expr) {
		return this.opAndExpr("<=", expr);
	}
	/** Subtraction — `this - expr` */
	minus(expr) {
		return this.opAndExpr("-", expr);
	}
	/** Strict inequality — `this !== expr` */
	neq(expr) {
		return this.opAndExpr("!==", expr);
	}
	/** Nullish assignment — `this ??= expr` */
	nullishAssign(expr) {
		return this.opAndExpr("??=", expr);
	}
	/** Logical OR — `this || expr` */
	or(expr) {
		return this.opAndExpr("||", expr);
	}
	/** Addition — `this + expr` */
	plus(expr) {
		return this.opAndExpr("+", expr);
	}
	/** Multiplication — `this * expr` */
	times(expr) {
		return this.opAndExpr("*", expr);
	}
	toAst() {
		this.$validate();
		const base = this.$node(this._base);
		const operator = typeof this._op === "string" ? this.opToToken(this._op) : this._op;
		return ts.factory.createBinaryExpression(base, operator, this.$node(this._expr));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Binary expression missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._op) missing.push("operator (e.g., .eq(), .plus())");
		if (!this._expr) missing.push("right-hand expression");
		return missing;
	}
	/** Sets the binary operator and right-hand operand for this expression. */
	opAndExpr(op, expr) {
		this._expr = ref(expr);
		this._op = op;
		return this;
	}
	opToToken(op) {
		const token = {
			"!=": ts.SyntaxKind.ExclamationEqualsToken,
			"!==": ts.SyntaxKind.ExclamationEqualsEqualsToken,
			"&&": ts.SyntaxKind.AmpersandAmpersandToken,
			"*": ts.SyntaxKind.AsteriskToken,
			"+": ts.SyntaxKind.PlusToken,
			"-": ts.SyntaxKind.MinusToken,
			"/": ts.SyntaxKind.SlashToken,
			"<": ts.SyntaxKind.LessThanToken,
			"<=": ts.SyntaxKind.LessThanEqualsToken,
			"=": ts.SyntaxKind.EqualsToken,
			"==": ts.SyntaxKind.EqualsEqualsToken,
			"===": ts.SyntaxKind.EqualsEqualsEqualsToken,
			">": ts.SyntaxKind.GreaterThanToken,
			">=": ts.SyntaxKind.GreaterThanEqualsToken,
			"??": ts.SyntaxKind.QuestionQuestionToken,
			"??=": ts.SyntaxKind.QuestionQuestionEqualsToken,
			"||": ts.SyntaxKind.BarBarToken
		}[op];
		if (!token) throw new Error(`Unsupported operator: ${op}`);
		return token;
	}
};
//#endregion
//#region src/ts-dsl/mixins/operator.ts
function OperatorMixin(Base) {
	class Operator extends Base {
		analyze(ctx) {
			super.analyze(ctx);
		}
		and(expr) {
			return new BinaryTsDsl(this).and(expr);
		}
		assign(expr) {
			return new BinaryTsDsl(this, "=", expr);
		}
		coalesce(expr) {
			return new BinaryTsDsl(this).coalesce(expr);
		}
		div(expr) {
			return new BinaryTsDsl(this).div(expr);
		}
		eq(expr) {
			return new BinaryTsDsl(this).eq(expr);
		}
		gt(expr) {
			return new BinaryTsDsl(this).gt(expr);
		}
		gte(expr) {
			return new BinaryTsDsl(this).gte(expr);
		}
		looseEq(expr) {
			return new BinaryTsDsl(this).looseEq(expr);
		}
		looseNeq(expr) {
			return new BinaryTsDsl(this).looseNeq(expr);
		}
		lt(expr) {
			return new BinaryTsDsl(this).lt(expr);
		}
		lte(expr) {
			return new BinaryTsDsl(this).lte(expr);
		}
		minus(expr) {
			return new BinaryTsDsl(this).minus(expr);
		}
		neq(expr) {
			return new BinaryTsDsl(this).neq(expr);
		}
		nullishAssign(expr) {
			return new BinaryTsDsl(this).nullishAssign(expr);
		}
		or(expr) {
			return new BinaryTsDsl(this).or(expr);
		}
		plus(expr) {
			return new BinaryTsDsl(this).plus(expr);
		}
		times(expr) {
			return new BinaryTsDsl(this).times(expr);
		}
	}
	return Operator;
}
//#endregion
//#region src/ts-dsl/expr/attr.ts
const Mixed$33 = AsMixin(ExprMixin(OperatorMixin(OptionalMixin(SpreadMixin(TsDsl)))));
var AttrTsDsl = class extends Mixed$33 {
	"~dsl" = "AttrTsDsl";
	_computed = false;
	_left;
	constructor(left, right) {
		super();
		this._left = ref(left);
		this.name.set(right);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._left);
		ctx.analyze(this.name);
	}
	/** Use computed property access (e.g., `obj[expr]`)? */
	computed(condition) {
		this._computed = condition ?? true;
		return this;
	}
	toAst() {
		const left = this.$node(this._left);
		regexp.typeScriptIdentifier.lastIndex = 0;
		if (this._computed || !regexp.typeScriptIdentifier.test(this.name.toString())) {
			const right = fromRef(this.name);
			let value = isSymbol(right) ? right.finalName : right;
			if (typeof value === "string") {
				if (value.startsWith("'") && value.endsWith("'") || value.startsWith("\"") && value.endsWith("\"")) value = value.slice(1, -1);
			}
			if (this._optional) return ts.factory.createElementAccessChain(left, this.$node(new TokenTsDsl().questionDot()), this.$node(this._computed ? this.name : new LiteralTsDsl(value)));
			return ts.factory.createElementAccessExpression(left, this.$node(this._computed ? this.name : new LiteralTsDsl(value)));
		}
		if (this._optional) return ts.factory.createPropertyAccessChain(left, this.$node(new TokenTsDsl().questionDot()), this.$node(this.name));
		return ts.factory.createPropertyAccessExpression(left, this.$node(this.name));
	}
};
f.attr.set((...args) => new AttrTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/await.ts
const Mixed$32 = ExprMixin(TsDsl);
var AwaitTsDsl = class extends Mixed$32 {
	"~dsl" = "AwaitTsDsl";
	_awaitExpr;
	constructor(expr) {
		super();
		this._awaitExpr = ref(expr);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._awaitExpr);
	}
	toAst() {
		return ts.factory.createAwaitExpression(this.$node(this._awaitExpr));
	}
};
f.await.set((...args) => new AwaitTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/call.ts
const Mixed$31 = ArgsMixin(AsMixin(ExprMixin(SpreadMixin(TypeArgsMixin(TsDsl)))));
var CallTsDsl = class extends Mixed$31 {
	"~dsl" = "CallTsDsl";
	_callee;
	constructor(callee, ...args) {
		super();
		this._callee = ref(callee);
		this.args(...args);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._callee);
	}
	toAst() {
		return ts.factory.createCallExpression(this.$node(this._callee), this.$generics(), this.$args());
	}
};
f.call.set((...args) => new CallTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/expr.ts
const Mixed$30 = AsMixin(ExprMixin(OperatorMixin(SpreadMixin(TypeExprMixin(TsDsl)))));
var ExprTsDsl = class extends Mixed$30 {
	"~dsl" = "ExprTsDsl";
	_exprInput;
	constructor(id) {
		super();
		this._exprInput = ref(id);
		if (typeof id === "string" || isSymbol(id)) this.name.set(id);
		else if (isNode(id)) this.name.set(id.name);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._exprInput);
	}
	toAst() {
		return this.$node(this._exprInput);
	}
};
//#endregion
//#region src/ts-dsl/layout/hint.ts
var HintTsDsl = class extends TsDsl {
	"~dsl" = "HintTsDsl";
	_lines = [];
	constructor(lines, fn) {
		super();
		if (lines) this.add(lines);
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	add(lines) {
		this._lines.push(lines);
		return this;
	}
	apply(node) {
		const lines = this._lines.reduce((lines, line) => {
			if (typeof line === "function") line = line(ctx);
			for (const l of typeof line === "string" ? [line] : line) if (l || l === "") lines.push(l);
			return lines;
		}, []);
		if (!lines.length) return node;
		for (const line of lines) ts.addSyntheticLeadingComment(node, ts.SyntaxKind.SingleLineCommentTrivia, ` ${line}`, false);
		return node;
	}
	toAst() {
		return this.$node(new IdTsDsl(""));
	}
};
//#endregion
//#region src/ts-dsl/mixins/hint.ts
function HintMixin(Base) {
	class Hint extends Base {
		_hint;
		analyze(ctx) {
			super.analyze(ctx);
		}
		hint(lines, fn) {
			this._hint = new HintTsDsl(lines, fn);
			return this;
		}
		$hint(node) {
			return this._hint ? this._hint.apply(node) : node;
		}
	}
	return Hint;
}
//#endregion
//#region src/ts-dsl/expr/prop.ts
const Mixed$29 = DocMixin(TsDsl);
var ObjectPropTsDsl = class extends Mixed$29 {
	"~dsl" = "ObjectPropTsDsl";
	_value;
	_meta;
	constructor(meta) {
		super();
		this._meta = meta;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._value);
	}
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	get kind() {
		return this._meta.kind;
	}
	get propName() {
		return this._meta.name;
	}
	value(value) {
		this._value = ref(value);
		return this;
	}
	toAst() {
		this.$validate();
		const node = this.$node(this._value);
		if (this._meta.kind === "spread") {
			if (ts.isStatement(node)) throw new Error("Invalid spread: object spread must be an expression, not a statement.");
			const result = ts.factory.createSpreadAssignment(node);
			return this.$docs(result);
		}
		if (this._meta.kind === "getter") {
			const getter = new GetterTsDsl(this._meta.name).do(node);
			const result = this.$node(getter);
			return this.$docs(result);
		}
		if (this._meta.kind === "setter") {
			const setter = new SetterTsDsl(this._meta.name).do(node);
			const result = this.$node(setter);
			return this.$docs(result);
		}
		if (this._meta.kind === "method") return this.$docs(node);
		if (ts.isIdentifier(node) && node.text === this._meta.name) {
			const result = ts.factory.createShorthandPropertyAssignment(this._meta.name);
			return this.$docs(result);
		}
		if (ts.isStatement(node)) throw new Error("Invalid property: object property value must be an expression, not a statement.");
		const result = ts.factory.createPropertyAssignment(this._meta.kind === "computed" ? ts.factory.createComputedPropertyName(this.$node(new IdTsDsl(this._meta.name))) : this.$node(safePropName(this._meta.name)), node);
		return this.$docs(result);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Object property${this._meta.name ? ` "${this._meta.name}"` : ""} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._value) missing.push(".value()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/expr/object.ts
const Mixed$28 = AsMixin(ExprMixin(HintMixin(LayoutMixin(TsDsl))));
var ObjectTsDsl = class extends Mixed$28 {
	"~dsl" = "ObjectTsDsl";
	_props = /* @__PURE__ */ new Map();
	_spreadCounter = 0;
	constructor(...props) {
		super();
		if (props.length === 1 && typeof props[0] === "function") props[0](this);
		else this.props(...props);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const prop of this._props.values()) ctx.analyze(prop);
	}
	/** Returns composite key for the property. */
	_propKey(prop) {
		if (prop.kind === "spread") return `spread:${this._spreadCounter++}`;
		return `${prop.kind}:${prop.propName}`;
	}
	/** Adds a computed property (e.g., `{ [expr]: value }`), or removes if null. */
	computed(name, expr) {
		if (expr === null) this._props.delete(`computed:${name}`);
		else this._props.set(`computed:${name}`, new ObjectPropTsDsl({
			kind: "computed",
			name
		}).value(expr));
		return this;
	}
	/** Adds a getter property (e.g., `{ get foo() { ... } }`), or removes if null. */
	getter(name, stmt) {
		if (stmt === null) this._props.delete(`getter:${name}`);
		else this._props.set(`getter:${name}`, new ObjectPropTsDsl({
			kind: "getter",
			name
		}).value(stmt));
		return this;
	}
	/** Returns true if object has at least one property or spread. */
	hasProps() {
		return this._props.size > 0;
	}
	/** Returns true if object has no properties or spreads. */
	get isEmpty() {
		return this._props.size === 0;
	}
	/** Adds a method property (e.g., `{ foo() { ... } }`), or removes if null. */
	method(name, fn) {
		if (fn === null) this._props.delete(`method:${name}`);
		else this._props.set(`method:${name}`, new ObjectPropTsDsl({
			kind: "method",
			name
		}).value(f.method(name, fn)));
		return this;
	}
	/** Adds a property assignment, or removes if null. */
	prop(name, expr) {
		if (expr === null) this._props.delete(`prop:${name}`);
		else this._props.set(`prop:${name}`, new ObjectPropTsDsl({
			kind: "prop",
			name
		}).value(expr));
		return this;
	}
	/** Adds multiple properties. */
	props(...props) {
		for (const prop of props) this._props.set(this._propKey(prop), prop);
		return this;
	}
	/** Adds a setter property (e.g., `{ set foo(v) { ... } }`), or removes if null. */
	setter(name, stmt) {
		if (stmt === null) this._props.delete(`setter:${name}`);
		else this._props.set(`setter:${name}`, new ObjectPropTsDsl({
			kind: "setter",
			name
		}).value(stmt));
		return this;
	}
	/** Adds a spread property (e.g., `{ ...options }`). */
	spread(expr) {
		const key = `spread:${this._spreadCounter++}`;
		this._props.set(key, new ObjectPropTsDsl({ kind: "spread" }).value(expr));
		return this;
	}
	toAst() {
		const props = [...this._props.values()];
		const node = ts.factory.createObjectLiteralExpression(this.$node(props), this.$multiline(props.length));
		return this.$hint(node);
	}
};
//#endregion
//#region src/ts-dsl/expr/from-value.ts
const fromValue$1 = (input, options) => {
	if (isNode(input)) return input;
	if (input === null || typeof input === "number" || typeof input === "boolean" || typeof input === "string" || typeof input === "bigint") return new LiteralTsDsl(input);
	if (input instanceof Array) {
		const arr = new ArrayTsDsl(...input.map((v) => fromValue$1(v, options)));
		if (options?.layout === "pretty") arr.pretty();
		return arr;
	}
	if (typeof input === "object") {
		const obj = new ObjectTsDsl();
		for (const [key, val] of Object.entries(input)) {
			const expr = fromValue$1(val, options);
			obj.prop(key, expr);
		}
		if (options?.layout === "pretty") obj.pretty();
		return obj;
	}
	throw new Error(`$.fromValue(): Unsupported input type ${String(input)}`);
};
//#endregion
//#region src/ts-dsl/expr/new.ts
const Mixed$27 = ArgsMixin(AsMixin(ExprMixin(SpreadMixin(TypeArgsMixin(TsDsl)))));
var NewTsDsl = class extends Mixed$27 {
	"~dsl" = "NewTsDsl";
	_newExpr;
	constructor(expr, ...args) {
		super();
		this._newExpr = ref(expr);
		this.args(...args);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._newExpr);
	}
	toAst() {
		return ts.factory.createNewExpression(this.$node(this._newExpr), this.$generics(), this.$args());
	}
};
f.new.set((...args) => new NewTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/postfix.ts
const Mixed$26 = TsDsl;
var PostfixTsDsl = class extends Mixed$26 {
	"~dsl" = "PostfixTsDsl";
	_expr;
	_op;
	constructor(expr, op) {
		super();
		this._expr = expr;
		this._op = op;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._expr);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the operator to MinusMinusToken for decrement (`--`). */
	dec() {
		this._op = ts.SyntaxKind.MinusMinusToken;
		return this;
	}
	/** Sets the operand (the expression being postfixed). */
	expr(expr) {
		this._expr = expr;
		return this;
	}
	/** Sets the operator to PlusPlusToken for increment (`++`). */
	inc() {
		this._op = ts.SyntaxKind.PlusPlusToken;
		return this;
	}
	/** Sets the operator (e.g., `ts.SyntaxKind.PlusPlusToken` for `++`). */
	op(op) {
		this._op = op;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createPostfixUnaryExpression(this.$node(this._expr), this._op);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Postfix unary expression missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._expr) missing.push(".expr()");
		if (!this._op) missing.push("operator (e.g., .inc(), .dec())");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/expr/regexp.ts
const Mixed$25 = TsDsl;
var RegExpTsDsl = class extends Mixed$25 {
	"~dsl" = "RegExpTsDsl";
	pattern;
	flags;
	constructor(pattern, flags) {
		super();
		this.pattern = pattern;
		this.flags = flags;
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		const literal = `/${(this.pattern.startsWith("/") && this.pattern.endsWith("/") ? this.pattern.slice(1, -1) : this.pattern).replace(/(?<!\\)\//g, "\\/")}/${this.flags ?? ""}`;
		return ts.factory.createRegularExpressionLiteral(literal);
	}
};
//#endregion
//#region src/ts-dsl/expr/spread.ts
const Mixed$24 = TsDsl;
var SpreadTsDsl = class extends Mixed$24 {
	"~dsl" = "SpreadTsDsl";
	_expr;
	constructor(expr) {
		super();
		this._expr = ref(expr);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._expr);
	}
	toAst() {
		return ts.factory.createSpreadElement(this.$node(this._expr));
	}
};
f.spread.set((...args) => new SpreadTsDsl(...args));
//#endregion
//#region src/ts-dsl/expr/template.ts
const Mixed$23 = TsDsl;
var TemplateTsDsl = class extends Mixed$23 {
	"~dsl" = "TemplateTsDsl";
	parts = [];
	constructor(value) {
		super();
		if (value !== void 0) this.add(value);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const part of this.parts) ctx.analyze(part);
	}
	add(value) {
		this.parts.push(ref(value));
		return this;
	}
	toAst() {
		const parts = this.$node(this.parts.map((p) => {
			const part = fromRef(p);
			return isSymbol(part) ? part.finalName : part;
		}));
		const normalized = [];
		for (let index = 0; index < parts.length; index++) {
			const current = parts[index];
			if (typeof current === "string") {
				let merged = current;
				while (index + 1 < parts.length && typeof parts[index + 1] === "string") {
					merged += parts[index + 1];
					index++;
				}
				normalized.push(merged);
			} else if (typeof current === "number") normalized.push(String(current));
			else normalized.push(current);
		}
		if (!normalized.length || typeof normalized[0] !== "string") normalized.unshift("");
		if (normalized.length === 1 && typeof normalized[0] === "string") return ts.factory.createNoSubstitutionTemplateLiteral(normalized[0]);
		if (normalized.length === 2 && typeof normalized[0] === "string" && typeof normalized[1] !== "string") return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(normalized[0]), [ts.factory.createTemplateSpan(normalized[1], ts.factory.createTemplateTail(""))]);
		const head = ts.factory.createTemplateHead(normalized.shift());
		const spans = [];
		while (normalized.length) {
			const expr = normalized.shift();
			const next = typeof normalized[0] === "string" ? normalized.shift() : "";
			const isLast = !normalized.length;
			spans.push(ts.factory.createTemplateSpan(expr, isLast ? ts.factory.createTemplateTail(next) : ts.factory.createTemplateMiddle(next)));
		}
		return ts.factory.createTemplateExpression(head, spans);
	}
};
//#endregion
//#region src/ts-dsl/expr/ternary.ts
const Mixed$22 = TsDsl;
var TernaryTsDsl = class extends Mixed$22 {
	"~dsl" = "TernaryTsDsl";
	_condition;
	_then;
	_else;
	constructor(condition) {
		super();
		if (condition) this.condition(condition);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._condition);
		ctx.analyze(this._then);
		ctx.analyze(this._else);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	condition(condition) {
		this._condition = condition;
		return this;
	}
	do(expr) {
		this._then = expr;
		return this;
	}
	otherwise(expr) {
		this._else = expr;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createConditionalExpression(this.$node(this._condition), void 0, this.$node(this._then), void 0, this.$node(this._else));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Ternary expression missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._condition) missing.push(".condition()");
		if (!this._then) missing.push(".do()");
		if (!this._else) missing.push(".otherwise()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/expr/typeof.ts
const Mixed$21 = OperatorMixin(TsDsl);
var TypeOfExprTsDsl = class extends Mixed$21 {
	"~dsl" = "TypeOfExprTsDsl";
	_expr;
	constructor(expr) {
		super();
		this._expr = expr;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._expr);
	}
	toAst() {
		return ts.factory.createTypeOfExpression(this.$node(this._expr));
	}
};
f.typeofExpr.set((...args) => new TypeOfExprTsDsl(...args));
//#endregion
//#region src/ts-dsl/layout/note.ts
var NoteTsDsl = class extends TsDsl {
	"~dsl" = "NoteTsDsl";
	_lines = [];
	constructor(lines, fn) {
		super();
		if (lines) this.add(lines);
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	add(lines) {
		this._lines.push(lines);
		return this;
	}
	apply(node) {
		const lines = this._lines.reduce((lines, line) => {
			if (typeof line === "function") line = line(ctx);
			for (const l of typeof line === "string" ? [line] : line) if (l || l === "") lines.push(l);
			return lines;
		}, []);
		if (!lines.length) return node;
		ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, `\n${lines.join("\n")}\n`, true);
		return node;
	}
	toAst() {
		return this.$node(new IdTsDsl(""));
	}
};
//#endregion
//#region src/ts-dsl/stmt/for.ts
const Mixed$20 = DoMixin(LayoutMixin(TsDsl));
var ImplForTsDsl = class extends Mixed$20 {
	"~dsl" = "ForTsDsl";
	_await;
	_condition;
	_iterableOrUpdate;
	_mode = "for";
	_variableOrInit;
	constructor(variableOrInit, modeOrCondition, iterableOrUpdate) {
		super();
		this._iterableOrUpdate = iterableOrUpdate;
		this._variableOrInit = variableOrInit;
		if (typeof modeOrCondition === "string") this._mode = modeOrCondition ?? "for";
		else this._condition = modeOrCondition;
	}
	analyze(ctx) {
		ctx.analyze(this._condition);
		ctx.analyze(this._iterableOrUpdate);
		ctx.analyze(this._variableOrInit);
		ctx.pushScope();
		try {
			super.analyze(ctx);
		} finally {
			ctx.popScope();
		}
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Enables async iteration (`for await...of`). Can only be called on for...of. */
	await() {
		this._await = true;
		this.of();
		return this;
	}
	/** Sets the condition (e.g., `i < n`). */
	condition(condition) {
		this._condition = condition;
		return this;
	}
	/** Sets the iteration variable (e.g., `$.const('item')`). */
	each(variable) {
		this._variableOrInit = variable;
		return this;
	}
	/** Sets the object to iterate over and switches to for...in. */
	in(iterable) {
		this._mode = "in";
		if (iterable !== void 0) this.iterable(iterable);
		return this;
	}
	/** Sets the initialization (e.g., `let i = 0`). */
	init(init) {
		this._variableOrInit = init;
		return this;
	}
	/** Sets the iterable to iterate over. */
	iterable(iterable) {
		this._iterableOrUpdate = iterable;
		return this;
	}
	/** Sets the iterable to iterate over and switches to for...of. */
	of(iterable) {
		this._mode = "of";
		if (iterable !== void 0) this.iterable(iterable);
		return this;
	}
	/** Sets the update expression (e.g., `i++`). */
	update(update) {
		this._iterableOrUpdate = update;
		return this;
	}
	toAst() {
		this.$validate();
		const body = this.$node(new BlockTsDsl(...this._do).pretty());
		if (this._mode === "of") return ts.factory.createForOfStatement(this._await ? ts.factory.createToken(ts.SyntaxKind.AwaitKeyword) : void 0, this.$node(this._variableOrInit).declarationList, this.$node(this._iterableOrUpdate), body);
		if (this._mode === "in") return ts.factory.createForInStatement(this.$node(this._variableOrInit).declarationList, this.$node(this._iterableOrUpdate), body);
		const init = this.$node(this._variableOrInit);
		return ts.factory.createForStatement(init && ts.isVariableStatement(init) ? init.declarationList : init, this.$node(this._condition), this.$node(this._iterableOrUpdate), body);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`For${this._mode === "for" ? "" : `...${this._mode}`} statement missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (this._mode !== "for") {
			if (!this._variableOrInit) missing.push(".each()");
			if (!this._iterableOrUpdate) missing.push(".iterable()");
		}
		return missing;
	}
};
const ForTsDsl = ImplForTsDsl;
//#endregion
//#region src/ts-dsl/stmt/if.ts
const Mixed$19 = DoMixin(TsDsl);
var IfTsDsl = class extends Mixed$19 {
	"~dsl" = "IfTsDsl";
	_condition;
	_else;
	constructor(condition) {
		super();
		if (condition) this.condition(condition);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._condition);
		if (this._else) {
			ctx.pushScope();
			try {
				for (const stmt of this._else) ctx.analyze(stmt);
			} finally {
				ctx.popScope();
			}
		}
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	condition(condition) {
		this._condition = condition;
		return this;
	}
	otherwise(...items) {
		this._else = items;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createIfStatement(this.$node(this._condition), this.$node(new BlockTsDsl(...this._do).pretty()), this._else ? this.$node(new BlockTsDsl(...this._else).pretty()) : void 0);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`If statement missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._condition) missing.push(".condition()");
		if (!this._do.length) missing.push(".do()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/stmt/return.ts
const Mixed$18 = TsDsl;
var ReturnTsDsl = class extends Mixed$18 {
	"~dsl" = "ReturnTsDsl";
	_returnExpr;
	constructor(expr) {
		super();
		if (expr) this._returnExpr = ref(expr);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._returnExpr);
	}
	toAst() {
		return ts.factory.createReturnStatement(this.$node(this._returnExpr));
	}
};
f.return.set((...args) => new ReturnTsDsl(...args));
//#endregion
//#region src/ts-dsl/stmt/throw.ts
const Mixed$17 = TsDsl;
var ThrowTsDsl = class extends Mixed$17 {
	"~dsl" = "ThrowTsDsl";
	error;
	msg;
	useNew;
	constructor(error, useNew = true) {
		super();
		this.error = error;
		this.useNew = useNew;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.error);
		ctx.analyze(this.msg);
	}
	message(value) {
		this.msg = value;
		return this;
	}
	toAst() {
		const errorNode = this.$node(this.error);
		const messageNode = this.$node(this.msg ? [this.msg] : []).map((expr) => typeof expr === "string" ? this.$node(new LiteralTsDsl(expr)) : expr);
		if (this.useNew) return ts.factory.createThrowStatement(ts.factory.createNewExpression(errorNode, void 0, messageNode));
		const args = messageNode.length ? [ts.factory.createCallExpression(errorNode, void 0, messageNode)] : [errorNode];
		return ts.factory.createThrowStatement(args[0]);
	}
};
//#endregion
//#region src/ts-dsl/stmt/try.ts
const Mixed$16 = TsDsl;
var TryTsDsl = class extends Mixed$16 {
	"~dsl" = "TryTsDsl";
	_catch;
	_catchArg;
	_finally;
	_try;
	constructor(...tryBlock) {
		super();
		this.try(...tryBlock);
	}
	analyze(ctx) {
		super.analyze(ctx);
		if (this._try) {
			ctx.pushScope();
			try {
				for (const stmt of this._try) ctx.analyze(stmt);
			} finally {
				ctx.popScope();
			}
		}
		if (this._catch || this._catchArg) {
			ctx.pushScope();
			try {
				ctx.analyze(this._catchArg);
				if (this._catch) for (const stmt of this._catch) ctx.analyze(stmt);
			} finally {
				ctx.popScope();
			}
		}
		if (this._finally) {
			ctx.pushScope();
			try {
				for (const stmt of this._finally) ctx.analyze(stmt);
			} finally {
				ctx.popScope();
			}
		}
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	catch(...items) {
		this._catch = items;
		return this;
	}
	catchArg(arg) {
		this._catchArg = arg;
		return this;
	}
	finally(...items) {
		this._finally = items;
		return this;
	}
	try(...items) {
		this._try = items;
		return this;
	}
	toAst() {
		this.$validate();
		const catchParam = this._catchArg ? this.$node(this._catchArg) : void 0;
		return ts.factory.createTryStatement(this.$node(new BlockTsDsl(...this._try).pretty()), ts.factory.createCatchClause(catchParam ? ts.factory.createVariableDeclaration(catchParam) : void 0, this.$node(new BlockTsDsl(...this._catch ?? []).pretty())), this._finally ? this.$node(new BlockTsDsl(...this._finally).pretty()) : void 0);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Try statement missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._try || !this._try.length) missing.push(".try()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/stmt/var.ts
const Mixed$15 = DefaultMixin(DocMixin(ExportMixin(HintMixin(PatternMixin(ValueMixin(TsDsl))))));
var VarTsDsl = class extends Mixed$15 {
	"~dsl" = "VarTsDsl";
	nameSanitizer = safeRuntimeName;
	kind = ts.NodeFlags.None;
	_type;
	constructor(name) {
		super();
		if (name) this.name.set(name);
		if (isSymbol(name)) name.setKind("var");
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	const() {
		this.kind = ts.NodeFlags.Const;
		return this;
	}
	let() {
		this.kind = ts.NodeFlags.Let;
		return this;
	}
	/** Sets the variable type. */
	type(node) {
		this._type = node instanceof TypeTsDsl ? node : new TypeExprTsDsl(node);
		return this;
	}
	var() {
		this.kind = ts.NodeFlags.None;
		return this;
	}
	toAst() {
		this.$validate();
		const node = ts.factory.createVariableStatement(this.modifiers, ts.factory.createVariableDeclarationList([ts.factory.createVariableDeclaration(this.$pattern() ?? this.$node(this.name), void 0, this.$type(this._type), this.$value())], this.kind));
		return this.$docs(this.$hint(node));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Variable declaration missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this.$pattern() && !this.name.toString()) missing.push("name or pattern (.array()/.object())");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/alias.ts
const Mixed$14 = DocMixin(ExportMixin(TypeParamsMixin(TsDsl)));
var TypeAliasTsDsl = class extends Mixed$14 {
	"~dsl" = "TypeAliasTsDsl";
	nameSanitizer = safeTypeName;
	scope = "type";
	value;
	constructor(name, fn) {
		super();
		this.name.set(name);
		if (isSymbol(name)) name.setKind("type");
		fn?.(this);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this.value);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the type expression on the right-hand side of `= ...`. */
	type(node) {
		this.value = node;
		return this;
	}
	toAst() {
		this.$validate();
		const node = ts.factory.createTypeAliasDeclaration(this.modifiers, this.$node(this.name), this.$generics(), this.$type(this.value));
		return this.$docs(node);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		const name = this.name.toString();
		throw new Error(`Type alias${name ? ` "${name}"` : ""} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this.value) missing.push(".​type()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/and.ts
const Mixed$13 = TsDsl;
var TypeAndTsDsl = class extends Mixed$13 {
	"~dsl" = "TypeAndTsDsl";
	scope = "type";
	_types = [];
	constructor(...nodes) {
		super();
		this.types(...nodes);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const type of this._types) ctx.analyze(type);
	}
	types(...nodes) {
		this._types.push(...nodes.map((n) => ref(n)));
		return this;
	}
	toAst() {
		const flat = [];
		for (const node of this._types) {
			const type = this.$type(node);
			if (ts.isIntersectionTypeNode(type)) flat.push(...type.types);
			else flat.push(type);
		}
		return ts.factory.createIntersectionTypeNode(flat);
	}
};
//#endregion
//#region src/ts-dsl/type/literal.ts
const Mixed$12 = TsDsl;
var TypeLiteralTsDsl = class extends Mixed$12 {
	"~dsl" = "TypeLiteralTsDsl";
	scope = "type";
	value;
	constructor(value) {
		super();
		this.value = value;
	}
	analyze(ctx) {
		super.analyze(ctx);
	}
	toAst() {
		return ts.factory.createLiteralTypeNode(this.$node(new LiteralTsDsl(this.value)));
	}
};
//#endregion
//#region src/ts-dsl/type/idx-sig.ts
const Mixed$11 = DocMixin(ReadonlyMixin(TsDsl));
var TypeIdxSigTsDsl = class extends Mixed$11 {
	"~dsl" = "TypeIdxSigTsDsl";
	scope = "type";
	_key;
	_type;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn?.(this);
	}
	/** Element kind. */
	get kind() {
		return "idxSig";
	}
	/** Index signature parameter name. */
	get propName() {
		return this.name.toString();
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._key);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the key type: `[name: T]` */
	key(type) {
		this._key = type;
		return this;
	}
	/** Sets the property type. */
	type(type) {
		this._type = type;
		return this;
	}
	toAst() {
		this.$validate();
		const node = ts.factory.createIndexSignature(this.modifiers, [ts.factory.createParameterDeclaration(void 0, void 0, this.$node(this.name), void 0, this.$type(this._key))], this.$type(this._type));
		return this.$docs(node);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		const name = this.name.toString();
		throw new Error(`Index signature${name ? ` "${name}"` : ""} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._key) missing.push(".key()");
		if (!this._type) missing.push(".​type()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/prop.ts
const Mixed$10 = DocMixin(OptionalMixin(ReadonlyMixin(TsDsl)));
var TypePropTsDsl = class extends Mixed$10 {
	"~dsl" = "TypePropTsDsl";
	scope = "type";
	_type;
	constructor(name, fn) {
		super();
		this.name.set(name);
		fn(this);
	}
	/** Element kind. */
	get kind() {
		return "prop";
	}
	/** Property name. */
	get propName() {
		return this.name.toString();
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the property type. */
	type(type) {
		this._type = ref(type);
		return this;
	}
	toAst() {
		this.$validate();
		const name = this.name.toString();
		const node = ts.factory.createPropertySignature(this.modifiers, this.$node(safePropName(name)), this._optional ? this.$node(new TokenTsDsl().optional()) : void 0, this.$type(this._type));
		return this.$docs(node);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		const name = this.name.toString();
		throw new Error(`Type property${name ? ` "${name}"` : ""} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._type) missing.push(".​type()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/object.ts
const Mixed$9 = TsDsl;
var TypeObjectTsDsl = class extends Mixed$9 {
	"~dsl" = "TypeObjectTsDsl";
	scope = "type";
	_props = /* @__PURE__ */ new Map();
	analyze(ctx) {
		super.analyze(ctx);
		for (const prop of this._props.values()) ctx.analyze(prop);
	}
	/** Returns true if object has at least one property or index signature. */
	hasProps() {
		return this._props.size > 0;
	}
	/** Adds an index signature to the object type, or removes if fn is null. */
	idxSig(name, fn) {
		const key = `idxSig:${name}`;
		if (fn === null) this._props.delete(key);
		else this._props.set(key, new TypeIdxSigTsDsl(name, fn));
		return this;
	}
	/** Returns true if object has no properties or index signatures. */
	get isEmpty() {
		return this._props.size === 0;
	}
	/** Adds a property signature, or removes if fn is null. */
	prop(name, fn) {
		const key = `prop:${name}`;
		if (fn === null) this._props.delete(key);
		else this._props.set(key, new TypePropTsDsl(name, fn));
		return this;
	}
	/** Adds multiple properties/index signatures. */
	props(...members) {
		for (const member of members) this._props.set(`${member.kind}:${member.propName}`, member);
		return this;
	}
	toAst() {
		return ts.factory.createTypeLiteralNode(this.$node([...this._props.values()]));
	}
};
//#endregion
//#region src/ts-dsl/type/tuple.ts
const Mixed$8 = TsDsl;
var TypeTupleTsDsl = class extends Mixed$8 {
	"~dsl" = "TypeTupleTsDsl";
	scope = "type";
	_elements = [];
	constructor(...nodes) {
		super();
		this.elements(...nodes);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const type of this._elements) ctx.analyze(type);
	}
	elements(...types) {
		this._elements.push(...types);
		return this;
	}
	toAst() {
		return ts.factory.createTupleTypeNode(this._elements.map((t) => this.$type(t)));
	}
};
//#endregion
//#region src/ts-dsl/type/from-value.ts
const fromValue = (input) => {
	if (isNode(input)) return input;
	if (input === null) return new TypeLiteralTsDsl(input);
	if (typeof input === "number" || typeof input === "boolean" || typeof input === "string" || typeof input === "bigint") return new TypeLiteralTsDsl(input);
	if (input instanceof Array) return new TypeTupleTsDsl(...input.map((v) => fromValue(v)));
	if (typeof input === "object") {
		const obj = new TypeObjectTsDsl();
		for (const [key, val] of Object.entries(input)) {
			const type = fromValue(val);
			obj.prop(key, (p) => p.type(type));
		}
		return obj;
	}
	throw new Error(`$.type.fromValue(): Unsupported input type ${String(input)}`);
};
//#endregion
//#region src/ts-dsl/type/func.ts
const Mixed$7 = DocMixin(ParamMixin(TypeParamsMixin(TypeReturnsMixin(TsDsl))));
var TypeFuncTsDsl = class extends Mixed$7 {
	"~dsl" = "TypeFuncTsDsl";
	scope = "type";
	analyze(ctx) {
		super.analyze(ctx);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	toAst() {
		this.$validate();
		const node = ts.factory.createFunctionTypeNode(this.$generics(), this.$params(), this.$returns());
		return this.$docs(node);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Function type missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (this.$returns() === void 0) missing.push(".returns()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/idx.ts
const Mixed$6 = TypeExprMixin(TsDsl);
var TypeIdxTsDsl = class extends Mixed$6 {
	"~dsl" = "TypeIdxTsDsl";
	scope = "type";
	_base;
	_index;
	constructor(base, index) {
		super();
		this.base(base);
		this.index(index);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._base);
		ctx.analyze(this._index);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	base(base) {
		this._base = base;
		return this;
	}
	index(index) {
		this._index = index;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createIndexedAccessTypeNode(this.$type(this._base), this.$type(this._index));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Indexed access type missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (this._base === void 0) missing.push(".base()");
		if (this._index === void 0) missing.push(".index()");
		return missing;
	}
};
f.type.idx.set((...args) => new TypeIdxTsDsl(...args));
//#endregion
//#region src/ts-dsl/type/mapped.ts
const Mixed$5 = TsDsl;
var TypeMappedTsDsl = class extends Mixed$5 {
	"~dsl" = "TypeMappedTsDsl";
	scope = "type";
	questionToken;
	readonlyToken;
	_key;
	_type;
	constructor(name) {
		super();
		if (name) this.name.set(name);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.questionToken);
		ctx.analyze(this.readonlyToken);
		ctx.analyze(this._key);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	/** Sets the key constraint: `[K in Constraint]` */
	key(type) {
		this._key = type;
		return this;
	}
	/** Removes `readonly` from the mapped members (`[K in X]-readonly`). */
	mutable() {
		this.readonlyToken = new TokenTsDsl().minus();
		return this;
	}
	/** Makes `[K in X]?:` optional. */
	optional() {
		this.questionToken = new TokenTsDsl().optional();
		return this;
	}
	/** Makes `[K in X]` readonly */
	readonly() {
		this.readonlyToken = new TokenTsDsl().readonly();
		return this;
	}
	/** Removes `?` from the mapped members (`[K in X]-?:`). */
	required() {
		this.questionToken = new TokenTsDsl().minus();
		return this;
	}
	/** Sets the mapped value type: `[K in X]: ValueType` */
	type(type) {
		this._type = type;
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createMappedTypeNode(this.$node(this.readonlyToken), ts.factory.createTypeParameterDeclaration(void 0, this.$node(this.name), this.$type(this._key), void 0), void 0, this.$node(this.questionToken), this.$type(this._type), void 0);
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		const name = this.name.toString();
		throw new Error(`Mapped type${name ? ` "${name}"` : ""} missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._key) missing.push(".key()");
		if (!this._type) missing.push(".​type()");
		return missing;
	}
};
//#endregion
//#region src/ts-dsl/type/operator.ts
const Mixed$4 = TsDsl;
/**
* Builds a TypeScript `TypeOperatorNode`, such as:
*
* - `keyof T`
* - `readonly U`
* - `unique V`
*
* This DSL provides both a generic `.operator()` API and convenient
* shorthand methods (`.keyof()`, `.readonly()`, `.unique()`).
*
* The node will throw during render if required fields are missing.
*/
var TypeOperatorTsDsl = class extends Mixed$4 {
	"~dsl" = "TypeOperatorTsDsl";
	scope = "type";
	_op;
	_type;
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._type);
	}
	/** Shorthand: builds `keyof T`. */
	keyof(type) {
		this.operator(ts.SyntaxKind.KeyOfKeyword);
		this.type(type);
		return this;
	}
	/** Sets the operator explicitly. */
	operator(op) {
		this._op = op;
		return this;
	}
	/** Shorthand: builds `readonly T`. */
	readonly(type) {
		this.operator(ts.SyntaxKind.ReadonlyKeyword);
		this.type(type);
		return this;
	}
	/** Sets the target type of the operator. */
	type(type) {
		this._type = type;
		return this;
	}
	/** Shorthand: builds `unique T`. */
	unique(type) {
		this.operator(ts.SyntaxKind.UniqueKeyword);
		this.type(type);
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createTypeOperatorNode(this._op, this.$type(this._type));
	}
	/** Throws if required fields are not set. */
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Type operator missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._op) missing.push(".operator()");
		if (!this._type) missing.push(".​type()");
		return missing;
	}
};
f.type.operator.set((...args) => new TypeOperatorTsDsl(...args));
//#endregion
//#region src/ts-dsl/type/or.ts
const Mixed$3 = TsDsl;
var TypeOrTsDsl = class extends Mixed$3 {
	"~dsl" = "TypeOrTsDsl";
	scope = "type";
	_types = [];
	constructor(...nodes) {
		super();
		this.types(...nodes);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const type of this._types) ctx.analyze(type);
	}
	types(...nodes) {
		this._types.push(...nodes.map((n) => ref(n)));
		return this;
	}
	toAst() {
		const flat = [];
		for (const node of this._types) {
			const type = this.$type(node);
			if (ts.isUnionTypeNode(type)) flat.push(...type.types);
			else flat.push(type);
		}
		return ts.factory.createUnionTypeNode(flat);
	}
};
//#endregion
//#region src/ts-dsl/type/query.ts
const Mixed$2 = TypeExprMixin(TsDsl);
var TypeQueryTsDsl = class extends Mixed$2 {
	"~dsl" = "TypeQueryTsDsl";
	scope = "type";
	_expr;
	constructor(expr) {
		super();
		this._expr = ref(expr);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this._expr);
	}
	toAst() {
		const expr = this.$node(this._expr);
		return ts.factory.createTypeQueryNode(expr);
	}
};
f.type.query.set((...args) => new TypeQueryTsDsl(...args));
//#endregion
//#region src/ts-dsl/type/template.ts
const Mixed$1 = TsDsl;
var TypeTemplateTsDsl = class extends Mixed$1 {
	"~dsl" = "TypeTemplateTsDsl";
	scope = "type";
	parts = [];
	constructor(value) {
		super();
		if (value !== void 0) this.add(value);
	}
	analyze(ctx) {
		super.analyze(ctx);
		for (const part of this.parts) ctx.analyze(part);
	}
	/** Adds a raw string segment or embedded type expression. */
	add(part) {
		this.parts.push(part);
		return this;
	}
	toAst() {
		const parts = this.$node(this.parts);
		const normalized = [];
		for (let index = 0; index < parts.length; index++) {
			const current = parts[index];
			if (typeof current === "string") {
				let merged = current;
				while (index + 1 < parts.length && typeof parts[index + 1] === "string") {
					merged += parts[index + 1];
					index++;
				}
				normalized.push(merged);
			} else normalized.push(current);
		}
		if (!normalized.length || typeof normalized[0] !== "string") normalized.unshift("");
		if (normalized.length === 1 && typeof normalized[0] === "string") return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(normalized[0]), []);
		if (normalized.length === 2 && typeof normalized[0] === "string" && typeof normalized[1] !== "string") return ts.factory.createTemplateLiteralType(ts.factory.createTemplateHead(normalized[0]), [ts.factory.createTemplateLiteralTypeSpan(normalized[1], ts.factory.createTemplateTail(""))]);
		const head = ts.factory.createTemplateHead(normalized.shift());
		const spans = [];
		while (normalized.length) {
			const type = normalized.shift();
			const next = typeof normalized[0] === "string" ? normalized.shift() : "";
			const isLast = !normalized.length;
			spans.push(ts.factory.createTemplateLiteralTypeSpan(type, isLast ? ts.factory.createTemplateTail(next) : ts.factory.createTemplateMiddle(next)));
		}
		return ts.factory.createTemplateLiteralType(head, spans);
	}
};
//#endregion
//#region src/ts-dsl/type/tuple-member.ts
const Mixed = OptionalMixin(TsDsl);
var TypeTupleMemberTsDsl = class extends Mixed {
	"~dsl" = "TypeTupleMemberTsDsl";
	scope = "type";
	_type;
	constructor(name) {
		super();
		this.name.set(name);
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.name);
		ctx.analyze(this._type);
	}
	/** Returns true when all required builder calls are present. */
	get isValid() {
		return !this.missingRequiredCalls().length;
	}
	type(node) {
		this._type = ref(node);
		return this;
	}
	toAst() {
		this.$validate();
		return ts.factory.createNamedTupleMember(void 0, this.$node(this.name), this._optional ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : void 0, this.$type(this._type));
	}
	$validate() {
		const missing = this.missingRequiredCalls();
		if (!missing.length) return;
		throw new Error(`Tuple member missing ${missing.join(" and ")}`);
	}
	missingRequiredCalls() {
		const missing = [];
		if (!this._type) missing.push(".​type()");
		return missing;
	}
};
f.type.tupleMember.set((name) => new TypeTupleMemberTsDsl(name));
//#endregion
//#region src/ts-dsl/utils/lazy.ts
var LazyTsDsl = class extends TsDsl {
	"~dsl" = "LazyTsDsl";
	_thunk;
	constructor(thunk) {
		super();
		this._thunk = thunk;
	}
	analyze(ctx) {
		super.analyze(ctx);
		ctx.analyze(this.toResult());
	}
	toResult() {
		return this._thunk(ctx);
	}
	toAst() {
		return this.toResult().toAst();
	}
};
//#endregion
//#region src/ts-dsl/utils/render-utils.ts
const printer = ts.createPrinter({
	newLine: ts.NewLineKind.LineFeed,
	removeComments: false
});
const blankFile = ts.createSourceFile("", "", ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS);
/** Print a TypeScript node to a string. */
function astToString(node) {
	const result = printer.printNode(ts.EmitHint.Unspecified, node, blankFile);
	try {
		/**
		* TypeScript Compiler API escapes unicode characters by default and there
		* is no way to disable this behavior
		* {@link https://github.com/microsoft/TypeScript/issues/36174}
		*/
		return result.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
	} catch {
		return result;
	}
}
function moduleSortKey({ file, fromFile, preferFileExtension, root }) {
	const filePath = file.finalPath.split(path.sep).join("/");
	let modulePath = fromFile.finalPath.split(path.sep).join("/");
	if (fromFile.external && !path.isAbsolute(modulePath)) return [
		0,
		0,
		modulePath
	];
	if (!modulePath.startsWith(root.split(path.sep).join("/"))) return [
		1,
		0,
		modulePath
	];
	const rel = path.relative(path.dirname(filePath), path.dirname(modulePath)).split(path.sep).join("/");
	let parentCount;
	if (!rel.startsWith("..")) {
		modulePath = `./${rel ? `${rel}/` : ""}${fromFile.name}${fromFile.extension ?? ""}`;
		parentCount = 0;
	} else {
		modulePath = `${rel}/${fromFile.name}${fromFile.extension ?? ""}`;
		parentCount = rel.split(path.sep).filter((segment) => segment === "..").length;
	}
	if (modulePath.endsWith(".ts")) modulePath = modulePath.slice(0, -3);
	if (preferFileExtension) modulePath += preferFileExtension;
	else if (modulePath.endsWith("/index")) modulePath = modulePath.slice(0, -6);
	return [
		2,
		parentCount,
		modulePath
	];
}
//#endregion
//#region src/ts-dsl/utils/render.ts
function headerToLines(header) {
	if (!header) return [];
	const lines = [];
	if (typeof header === "string") {
		lines.push(...header.split(/\r?\n/));
		return lines;
	}
	for (const line of header) lines.push(...line.split(/\r?\n/));
	return lines;
}
var TypeScriptRenderer = class TypeScriptRenderer {
	/**
	* Function to generate a file header.
	*
	* @private
	*/
	_header;
	/**
	* Options for module specifier resolution.
	*
	* @private
	*/
	_module;
	/**
	* Whether `export * from 'module'` should be used when possible instead of named exports.
	*
	* @private
	*/
	_preferExportAll;
	constructor(args = {}) {
		this._header = args.header;
		this._module = args.module;
		this._preferExportAll = args.preferExportAll ?? false;
	}
	render(ctx) {
		const header = typeof this._header === "function" ? this._header(ctx) : this._header;
		return TypeScriptRenderer.astToString({
			exports: this.getExports(ctx),
			exportsOptions: { preferExportAll: this._preferExportAll },
			header,
			imports: this.getImports(ctx),
			nodes: ctx.file.nodes
		});
	}
	supports(ctx) {
		return ctx.file.language === "typescript";
	}
	static astToString(args) {
		let text = "";
		for (const header of headerToLines(args.header)) text += `${header}\n`;
		let imports = "";
		for (const group of args.imports ?? []) {
			if (imports) imports += "\n";
			for (const imp of group) imports += `${astToString(TypeScriptRenderer.toImportAst(imp))}\n`;
		}
		text = `${text}${text && imports ? "\n" : ""}${imports}`;
		let nodes = "";
		for (const node of args.nodes ?? []) {
			if (nodes) nodes += "\n";
			nodes += `${astToString(node.toAst())}\n`;
		}
		text = `${text}${text && nodes ? "\n" : ""}${nodes}`;
		let exports = "";
		for (const group of args.exports ?? []) {
			if (!exports && nodes || exports) exports += "\n";
			for (const exp of group) exports += `${astToString(TypeScriptRenderer.toExportAst(exp, args.exportsOptions))}\n`;
		}
		text = `${text}${text && exports ? "\n" : ""}${exports}`;
		if (args.trailingNewline === false && text.endsWith("\n")) text = text.slice(0, -1);
		return text;
	}
	static toExportAst(group, options) {
		const specifiers = group.exports.map((exp) => {
			return ts.factory.createExportSpecifier(exp.isTypeOnly, exp.sourceName !== exp.exportedName ? $.id(exp.sourceName).toAst() : void 0, $.id(exp.exportedName).toAst());
		});
		const exportClause = group.namespaceExport ? ts.factory.createNamespaceExport($.id(group.namespaceExport).toAst()) : (!group.canExportAll || !options?.preferExportAll) && specifiers.length ? ts.factory.createNamedExports(specifiers) : void 0;
		return ts.factory.createExportDeclaration(void 0, group.isTypeOnly, exportClause, $.literal(group.modulePath).toAst());
	}
	static toImportAst(group) {
		const specifiers = group.imports.map((imp) => {
			return ts.factory.createImportSpecifier(imp.isTypeOnly, imp.sourceName !== imp.localName ? $.id(imp.sourceName).toAst() : void 0, $.id(imp.localName).toAst());
		});
		const importClause = ts.factory.createImportClause(group.isTypeOnly, group.kind === "default" ? $.id(group.localName ?? "").toAst() : void 0, group.kind === "namespace" ? ts.factory.createNamespaceImport($.id(group.localName ?? "").toAst()) : specifiers.length ? ts.factory.createNamedImports(specifiers) : void 0);
		return ts.factory.createImportDeclaration(void 0, importClause, $.literal(group.modulePath).toAst());
	}
	getExports(ctx) {
		const groups = /* @__PURE__ */ new Map();
		for (const exp of ctx.file.exports) {
			const sortKey = moduleSortKey({
				file: ctx.file,
				fromFile: exp.from,
				preferFileExtension: this._module?.extension || "",
				root: ctx.project.root
			});
			const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2];
			const [groupIndex] = sortKey;
			if (!groups.has(groupIndex)) groups.set(groupIndex, /* @__PURE__ */ new Map());
			const moduleMap = groups.get(groupIndex);
			if (!moduleMap.has(modulePath)) moduleMap.set(modulePath, {
				group: {
					canExportAll: exp.canExportAll,
					exports: exp.exports,
					isTypeOnly: exp.isTypeOnly,
					modulePath,
					namespaceExport: exp.namespaceExport
				},
				sortKey
			});
		}
		return Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([, moduleMap]) => {
			const entries = Array.from(moduleMap.values());
			entries.sort((a, b) => {
				const d = a.sortKey[1] - b.sortKey[1];
				return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath);
			});
			return entries.map((e) => {
				const group = e.group;
				if (group.namespaceExport) group.exports = [];
				else {
					if (!group.exports.find((exp) => !exp.isTypeOnly)) {
						group.isTypeOnly = true;
						for (const exp of group.exports) exp.isTypeOnly = false;
					}
					group.exports.sort((a, b) => a.exportedName.localeCompare(b.exportedName));
				}
				return group;
			});
		});
	}
	getImports(ctx) {
		const groups = /* @__PURE__ */ new Map();
		for (const imp of ctx.file.imports) {
			const sortKey = moduleSortKey({
				file: ctx.file,
				fromFile: imp.from,
				preferFileExtension: this._module?.extension || "",
				root: ctx.project.root
			});
			const modulePath = this._module?.resolve?.(sortKey[2], ctx) ?? sortKey[2];
			const [groupIndex] = sortKey;
			if (!groups.has(groupIndex)) groups.set(groupIndex, /* @__PURE__ */ new Map());
			const moduleMap = groups.get(groupIndex);
			if (!moduleMap.has(modulePath)) moduleMap.set(modulePath, {
				group: {
					imports: [],
					isTypeOnly: false,
					kind: imp.kind,
					modulePath
				},
				sortKey
			});
			const group = moduleMap.get(modulePath).group;
			if (imp.kind !== "named") {
				group.isTypeOnly = imp.isTypeOnly;
				group.kind = imp.kind;
				group.localName = imp.localName;
			} else group.imports.push(...imp.imports);
		}
		return Array.from(groups.entries()).sort((a, b) => a[0] - b[0]).map(([, moduleMap]) => {
			const entries = Array.from(moduleMap.values());
			entries.sort((a, b) => {
				const d = a.sortKey[1] - b.sortKey[1];
				return d !== 0 ? d : a.group.modulePath.localeCompare(b.group.modulePath);
			});
			return entries.map((e) => {
				const group = e.group;
				if (group.kind === "namespace") group.imports = [];
				else {
					if (!group.imports.find((imp) => !imp.isTypeOnly)) {
						group.isTypeOnly = true;
						for (const imp of group.imports) imp.isTypeOnly = false;
					}
					group.imports.sort((a, b) => a.localName.localeCompare(b.localName));
				}
				return group;
			});
		});
	}
};
//#endregion
//#region src/ts-dsl/index.ts
const tsDsl = {
	array: (...args) => new ArrayTsDsl(...args),
	as: (...args) => new AsTsDsl(...args),
	attr: (...args) => new AttrTsDsl(...args),
	await: (...args) => new AwaitTsDsl(...args),
	binary: (...args) => new BinaryTsDsl(...args),
	block: (...args) => new BlockTsDsl(...args),
	call: (...args) => new CallTsDsl(...args),
	class: (...args) => new ClassTsDsl(...args),
	const: (...args) => new VarTsDsl(...args).const(),
	dec: (...args) => new PostfixTsDsl(...args).dec(),
	decorator: (...args) => new DecoratorTsDsl(...args),
	doc: (...args) => new DocTsDsl(...args),
	enum: (...args) => new EnumTsDsl(...args),
	expr: (...args) => new ExprTsDsl(...args),
	field: (...args) => new FieldTsDsl(...args),
	for: ((...args) => new ForTsDsl(...args)),
	fromValue: (...args) => fromValue$1(...args),
	func: ((nameOrFn, fn) => {
		if (nameOrFn === void 0) return new FuncTsDsl();
		if (typeof nameOrFn !== "string" || fn === void 0) return new FuncTsDsl(nameOrFn);
		return new FuncTsDsl(nameOrFn, fn);
	}),
	getter: (...args) => new GetterTsDsl(...args),
	hint: (...args) => new HintTsDsl(...args),
	id: (...args) => new IdTsDsl(...args),
	if: (...args) => new IfTsDsl(...args),
	inc: (...args) => new PostfixTsDsl(...args).inc(),
	init: (...args) => new InitTsDsl(...args),
	lazy: (...args) => new LazyTsDsl(...args),
	let: (...args) => new VarTsDsl(...args).let(),
	literal: (...args) => new LiteralTsDsl(...args),
	member: (...args) => new EnumMemberTsDsl(...args),
	method: (...args) => new MethodTsDsl(...args),
	neg: (...args) => new PrefixTsDsl(...args).neg(),
	new: (...args) => new NewTsDsl(...args),
	newline: (...args) => new NewlineTsDsl(...args),
	not: (...args) => new PrefixTsDsl(...args).not(),
	note: (...args) => new NoteTsDsl(...args),
	object: (...args) => new ObjectTsDsl(...args),
	param: (...args) => new ParamTsDsl(...args),
	pattern: (...args) => new PatternTsDsl(...args),
	prefix: (...args) => new PrefixTsDsl(...args),
	prop: (...args) => new ObjectPropTsDsl(...args),
	regexp: (...args) => new RegExpTsDsl(...args),
	return: (...args) => new ReturnTsDsl(...args),
	setter: (...args) => new SetterTsDsl(...args),
	spread: (...args) => new SpreadTsDsl(...args),
	stmt: (...args) => new StmtTsDsl(...args),
	template: (...args) => new TemplateTsDsl(...args),
	ternary: (...args) => new TernaryTsDsl(...args),
	throw: (...args) => new ThrowTsDsl(...args),
	token: (...args) => new TokenTsDsl(...args),
	try: (...args) => new TryTsDsl(...args),
	type: Object.assign((...args) => new TypeExprTsDsl(...args), {
		alias: (...args) => new TypeAliasTsDsl(...args),
		and: (...args) => new TypeAndTsDsl(...args),
		attr: (...args) => new TypeAttrTsDsl(...args),
		expr: (...args) => new TypeExprTsDsl(...args),
		fromValue: (...args) => fromValue(...args),
		func: (...args) => new TypeFuncTsDsl(...args),
		idx: (...args) => new TypeIdxTsDsl(...args),
		literal: (...args) => new TypeLiteralTsDsl(...args),
		mapped: (...args) => new TypeMappedTsDsl(...args),
		object: (...args) => new TypeObjectTsDsl(...args),
		operator: (...args) => new TypeOperatorTsDsl(...args),
		or: (...args) => new TypeOrTsDsl(...args),
		param: (...args) => new TypeParamTsDsl(...args),
		query: (...args) => new TypeQueryTsDsl(...args),
		template: (...args) => new TypeTemplateTsDsl(...args),
		tuple: (...args) => new TypeTupleTsDsl(...args),
		tupleMember: (...args) => new TypeTupleMemberTsDsl(...args)
	}),
	typeofExpr: (...args) => new TypeOfExprTsDsl(...args),
	var: (...args) => new VarTsDsl(...args)
};
const $ = Object.assign((...args) => new ExprTsDsl(...args), tsDsl);
//#endregion
//#region src/plugins/@hey-api/sdk/shared/class.ts
const createRegistryClass = ({ plugin, sdkSymbol, symbol }) => {
	const symbolDefaultKey = plugin.symbol("defaultKey");
	const symbolInstances = plugin.symbol("instances");
	return $.class(symbol).generic("T").field(symbolDefaultKey, (f) => f.private().readonly().assign($.literal("default"))).newline().field(symbolInstances, (f) => f.private().readonly().type($.type("Map").generics("string", "T")).assign($.new("Map"))).newline().method("get", (m) => m.returns("T").param("key", (p) => p.type("string").optional()).do($.const("instance").assign($("this").attr(symbolInstances).attr("get").call($("key").coalesce($("this").attr(symbolDefaultKey)))), $.if($.not("instance")).do($.throw("Error").message($.template("No SDK client found. Create one with \"new ").add(sdkSymbol).add("()\" to fix this error."))), $.return("instance"))).newline().method("set", (m) => m.returns("void").param("value", (p) => p.type("T")).param("key", (p) => p.type("string").optional()).do($("this").attr(symbolInstances).attr("set").call($("key").coalesce($("this").attr(symbolDefaultKey)), "value")));
};
const createClientClass = ({ plugin, symbol }) => {
	const symClient = plugin.querySymbol({ category: "client" });
	const optionalClient = Boolean(plugin.config.client && symClient);
	const symbolClient = plugin.external("client.Client");
	return $.class(symbol).field("client", (f) => f.protected().type(symbolClient)).newline().init((i) => i.param("args", (p) => p.optional(optionalClient).type($.type.object().prop("client", (p) => p.optional(optionalClient).type(symbolClient)))).do($("this").attr("client").assign($("args").attr("client").optional(optionalClient).$if(optionalClient, (a) => a.coalesce(symClient)))));
};
//#endregion
//#region src/plugins/@hey-api/sdk/shared/constants.ts
const nuxtTypeComposable = "TComposable";
const nuxtTypeDefault = "DefaultT";
const nuxtTypeResponse = "ResT";
//#endregion
//#region src/plugins/@hey-api/sdk/shared/auth.ts
const securitySchemeObjectToAuthObject = ({ securitySchemeObject }) => {
	if (securitySchemeObject.type === "openIdConnect") return {
		scheme: "bearer",
		type: "http"
	};
	if (securitySchemeObject.type === "oauth2") {
		if (securitySchemeObject.flows.password || securitySchemeObject.flows.authorizationCode || securitySchemeObject.flows.clientCredentials || securitySchemeObject.flows.implicit) return {
			scheme: "bearer",
			type: "http"
		};
		return;
	}
	if (securitySchemeObject.type === "apiKey") {
		if (securitySchemeObject.in === "header") return {
			name: securitySchemeObject.name,
			type: "apiKey"
		};
		if (securitySchemeObject.in === "query" || securitySchemeObject.in == "cookie") return {
			in: securitySchemeObject.in,
			name: securitySchemeObject.name,
			type: "apiKey"
		};
		return;
	}
	if (securitySchemeObject.type === "http") {
		const scheme = securitySchemeObject.scheme.toLowerCase();
		if (scheme === "bearer" || scheme === "basic") return {
			scheme,
			type: "http"
		};
		return;
	}
};
const operationAuth = ({ operation, plugin }) => {
	if (!operation.security || !plugin.config.auth) return [];
	const auth = [];
	for (const securitySchemeObject of operation.security) {
		const authObject = securitySchemeObjectToAuthObject({ securitySchemeObject });
		if (authObject) auth.push(authObject);
		else if (securitySchemeObject.type !== "mutualTLS") console.warn(`❗️ SDK warning: unsupported security scheme. Please open an issue if you'd like it added https://github.com/hey-api/openapi-ts/issues\n${JSON.stringify(securitySchemeObject, null, 2)}`);
	}
	return auth;
};
//#endregion
//#region src/plugins/@hey-api/sdk/shared/signature.ts
/**
* Collects and resolves all operation parameters for flattened SDK signatures.
* - Prefixes all conflicting names with their location (e.g., path_foo, query_foo)
* - Returns a flat map of resolved parameter names to their metadata
*/
function getSignatureParameters({ operation }) {
	const locations = [
		"header",
		"path",
		"query"
	];
	const nameToLocations = {};
	const addParameter = (name, location) => {
		if (!nameToLocations[name]) nameToLocations[name] = /* @__PURE__ */ new Set();
		nameToLocations[name].add(location);
	};
	for (const location of locations) {
		const parameters = operation.parameters?.[location];
		if (parameters) for (const key in parameters) {
			const parameter = parameters[key];
			addParameter(parameter.name, location);
		}
	}
	if (operation.body) if (!operation.body.schema.logicalOperator && operation.body.schema.type === "object" && operation.body.schema.properties) {
		const properties = operation.body.schema.properties;
		for (const key in properties) addParameter(key, "body");
	} else if (operation.body.schema.$ref) addParameter(toCase(refToName(operation.body.schema.$ref), "camelCase"), "body");
	else addParameter("body", "body");
	const conflicts = /* @__PURE__ */ new Set();
	for (const name in nameToLocations) if (nameToLocations[name].size > 1) conflicts.add(name);
	const signatureParameters = {};
	const fields = [];
	for (const location of locations) {
		const parameters = operation.parameters?.[location];
		if (parameters) for (const key in parameters) {
			const parameter = parameters[key];
			const originalName = parameter.name;
			const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName;
			const signatureParameter = {
				isRequired: parameter.required ?? false,
				name,
				schema: parameter.schema
			};
			if (name !== originalName) signatureParameter.originalName = originalName;
			signatureParameters[name] = signatureParameter;
			fields.push({
				in: location === "header" ? "headers" : location,
				key: name,
				...name !== originalName ? { map: originalName } : {}
			});
		}
	}
	if (operation.body) {
		const location = "body";
		if (!operation.body.schema.logicalOperator && operation.body.schema.type === "object" && operation.body.schema.properties) {
			const properties = operation.body.schema.properties;
			for (const originalName in properties) {
				const property = properties[originalName];
				const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName;
				const signatureParameter = {
					isRequired: operation.body.schema.required?.includes(originalName) ?? false,
					name,
					schema: property
				};
				if (name !== originalName) signatureParameter.originalName = originalName;
				signatureParameters[name] = signatureParameter;
				fields.push({
					in: location,
					key: name,
					...name !== originalName ? { map: originalName } : {}
				});
			}
		} else if (operation.body.schema.$ref) {
			const originalName = toCase(refToName(operation.body.schema.$ref), "camelCase");
			const name = conflicts.has(originalName) ? `${location}_${originalName}` : originalName;
			const signatureParameter = {
				isRequired: operation.body.required ?? false,
				name,
				schema: operation.body.schema
			};
			if (name !== originalName) signatureParameter.originalName = originalName;
			signatureParameters[name] = signatureParameter;
			fields.push({
				key: name,
				map: "body"
			});
		} else {
			signatureParameters.body = {
				isRequired: operation.body.required ?? false,
				name: "body",
				schema: operation.body.schema
			};
			fields.push({
				key: "body",
				map: "body"
			});
		}
	}
	if (!Object.keys(signatureParameters).length) return;
	return {
		fields,
		parameters: signatureParameters
	};
}
//#endregion
//#region src/plugins/@hey-api/sdk/shared/validator.ts
function createRequestValidator({ plugin, ...args }) {
	if (!plugin.config.validator.request) return;
	const validator = plugin.getPluginOrThrow(plugin.config.validator.request);
	if (!validator.api.createRequestValidator) return;
	return validator.api.createRequestValidator({
		...args,
		plugin: validator
	});
}
function createResponseValidator({ operation, plugin }) {
	if (!plugin.config.validator.response) return;
	const validator = plugin.getPluginOrThrow(plugin.config.validator.response);
	if (!validator.api.createResponseValidator) return;
	return validator.api.createResponseValidator({
		operation,
		plugin: validator
	});
}
//#endregion
//#region src/plugins/@hey-api/sdk/shared/operation.ts
/** TODO: needs complete refactor */
const operationOptionsType = ({ isDataAllowed = true, operation, plugin, throwOnError }) => {
	const isNuxtClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-nuxt";
	const symbolDataType = isDataAllowed ? plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "typescript"
	}) : void 0;
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	if (isNuxtClient) {
		const symbolResponseType = plugin.querySymbol({
			category: "type",
			resource: "operation",
			resourceId: operation.id,
			role: "response"
		});
		return $.type(symbolOptions).generic(nuxtTypeComposable).generic(isDataAllowed ? symbolDataType ?? "unknown" : "never").generic(symbolResponseType ?? "unknown").generic(nuxtTypeDefault);
	}
	if (hasOperationSse({ operation })) {
		const symbolResponseType = plugin.querySymbol({
			category: "type",
			resource: "operation",
			resourceId: operation.id,
			role: "response"
		});
		return $.type(symbolOptions).generic(isDataAllowed ? symbolDataType ?? "unknown" : "never").generic(throwOnError !== void 0 ? throwOnError : "boolean").generic(symbolResponseType ?? "unknown");
	}
	if (throwOnError) return $.type(symbolOptions).generic(isDataAllowed ? symbolDataType ?? "unknown" : "never").generic(throwOnError);
	return $.type(symbolOptions).$if(!isDataAllowed || symbolDataType, (t) => t.generic(isDataAllowed ? symbolDataType : "never"));
};
function operationParameters({ isRequiredOptions, operation, plugin }) {
	const result = {
		argNames: [],
		fields: [],
		parameters: []
	};
	const pluginTypeScript = plugin.getPluginOrThrow("@hey-api/typescript");
	const isNuxtClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-nuxt";
	if (plugin.config.paramsStructure === "flat") {
		const signature = getSignatureParameters({
			operation,
			plugin
		});
		const flatParams = $.type.object();
		if (signature) {
			let isParametersRequired = false;
			for (const key in signature.parameters) {
				const parameter = signature.parameters[key];
				if (parameter.isRequired) isParametersRequired = true;
				flatParams.prop(parameter.name, (p) => p.required(parameter.isRequired).type(pluginTypeScript.api.schemaToType(pluginTypeScript, parameter.schema)));
			}
			result.argNames.push("parameters");
			for (const field of signature.fields) result.fields.push(field);
			result.parameters.push($.param("parameters", (p) => p.required(isParametersRequired).type(flatParams)));
		}
	}
	result.parameters.push($.param("options", (p) => p.required(isRequiredOptions).type(operationOptionsType({
		isDataAllowed: plugin.config.paramsStructure === "grouped",
		operation,
		plugin,
		throwOnError: isNuxtClient ? void 0 : "ThrowOnError"
	}))));
	return result;
}
/**
* Infers `responseType` value from provided response content type. This is
* an adapted version of `getParseAs()` from the Fetch API client.
*
* From Axios documentation:
* `responseType` indicates the type of data that the server will respond with
* options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
* browser only: 'blob'
*/
const getResponseType = (contentType) => {
	if (!contentType) return;
	const cleanContent = contentType.split(";")[0]?.trim();
	if (!cleanContent) return;
	if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
	if ([
		"application/",
		"audio/",
		"image/",
		"video/"
	].some((type) => cleanContent.startsWith(type))) return "blob";
	if (cleanContent.startsWith("text/")) return "text";
};
function operationStatements({ isRequiredOptions, opParameters, operation, plugin }) {
	const client = getClientPlugin(getTypedConfig(plugin));
	const isNuxtClient = client.name === "@hey-api/client-nuxt";
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: isNuxtClient ? "response" : "responses"
	});
	const symbolErrorType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: isNuxtClient ? "error" : "errors"
	});
	const reqOptions = $.object();
	if (operation.body) {
		const isBinaryFormat = operation.body.schema?.format === "binary";
		switch (operation.body.type) {
			case "form-data": {
				const symbol = plugin.external("client.formDataBodySerializer");
				reqOptions.spread(symbol);
				break;
			}
			case "json":
				if (isBinaryFormat) reqOptions.prop("bodySerializer", $.literal(null));
				break;
			case "text":
			case "octet-stream":
				reqOptions.prop("bodySerializer", $.literal(null));
				break;
			case "url-search-params": {
				const symbol = plugin.external("client.urlSearchParamsBodySerializer");
				reqOptions.spread(symbol);
				break;
			}
			default:
				if (isBinaryFormat) reqOptions.prop("bodySerializer", $.literal(null));
				break;
		}
	}
	const paramSerializers = $.object();
	for (const name in operation.parameters?.query) {
		const parameter = operation.parameters.query[name];
		if (parameter.schema.type === "array" || parameter.schema.type === "tuple") {
			if (parameter.style !== "form" || !parameter.explode) paramSerializers.prop(parameter.name, $.object().prop("array", $.object().$if(parameter.explode === false, (o) => o.prop("explode", $.literal(parameter.explode))).$if(parameter.style !== "form", (o) => o.prop("style", $.literal(parameter.style)))));
		} else if (parameter.schema.type === "object") {
			if (parameter.style !== "deepObject" || !parameter.explode) paramSerializers.prop(parameter.name, $.object().prop("object", $.object().$if(parameter.explode === false, (o) => o.prop("explode", $.literal(parameter.explode))).$if(parameter.style !== "deepObject", (o) => o.prop("style", $.literal(parameter.style)))));
		}
	}
	if (paramSerializers.hasProps()) reqOptions.prop("querySerializer", $.object().prop("parameters", paramSerializers));
	const requestValidator = createRequestValidator({
		operation,
		plugin
	});
	const responseValidator = createResponseValidator({
		operation,
		plugin
	});
	if (requestValidator) reqOptions.prop("requestValidator", requestValidator.arrow());
	if (plugin.config.transformer) {
		const query = {
			category: "transform",
			resource: "operation",
			resourceId: operation.id,
			role: "response"
		};
		if (plugin.isSymbolRegistered(query)) {
			const ref = plugin.referenceSymbol(query);
			reqOptions.prop("responseTransformer", $(ref));
		}
	}
	let hasServerSentEvents = false;
	let responseTypeValue;
	for (const statusCode in operation.responses) {
		const response = operation.responses[statusCode];
		if (!responseTypeValue && client.name === "@hey-api/client-axios") {
			if (statusCodeToGroup({ statusCode }) === "2XX") {
				responseTypeValue = getResponseType(response.mediaType);
				if (responseTypeValue) reqOptions.prop("responseType", $.literal(responseTypeValue));
			}
		}
		if (response.mediaType === "text/event-stream") hasServerSentEvents = true;
	}
	if (responseValidator) reqOptions.prop("responseValidator", responseValidator.arrow());
	if (plugin.config.responseStyle === "data") reqOptions.prop("responseStyle", $.literal(plugin.config.responseStyle));
	const auth = operationAuth({
		context: plugin.context,
		operation,
		plugin
	});
	if (auth.length) reqOptions.prop("security", $.fromValue(auth));
	reqOptions.prop("url", $.literal(operation.path));
	reqOptions.spread("options");
	const statements = [];
	const hasParams = opParameters.argNames.length;
	if (hasParams) {
		const args = [];
		const config = [];
		for (const argName of opParameters.argNames) args.push($(argName));
		for (const field of opParameters.fields) {
			const shape = $.object();
			if ("in" in field) shape.prop("in", $.literal(field.in));
			if ("key" in field) {
				if (field.key) shape.prop("key", $.literal(field.key));
				if (field.map) shape.prop("map", $.literal(field.map));
			}
			config.push(shape);
		}
		const symbol = plugin.external("client.buildClientParams");
		statements.push($.const("params").assign($(symbol).call($.array(...args), $.array($.object().prop("args", $.array(...config))))));
		reqOptions.spread("params");
	}
	if (operation.body) {
		const parameterContentType = operation.parameters?.header?.["content-type"];
		if (!Boolean(parameterContentType?.required)) {
			const headers = $.object().pretty().prop(parameterContentType?.name ?? "Content-Type", $.literal(operation.body.type === "form-data" ? null : operation.body.mediaType)).spread($("options").attr("headers").required(isRequiredOptions));
			if (hasParams) headers.spread($("params").attr("headers"));
			reqOptions.prop("headers", headers);
		}
	}
	const symbolClient = plugin.config.client ? plugin.querySymbol({ category: "client" }) : void 0;
	let clientExpression;
	const optionsClient = $("options").attr("client").required(isRequiredOptions);
	if (isInstance(plugin)) clientExpression = optionsClient.coalesce($("this").attr("client"));
	else if (symbolClient) clientExpression = optionsClient.coalesce(symbolClient);
	else clientExpression = optionsClient;
	let functionName = hasServerSentEvents ? clientExpression.attr("sse") : clientExpression;
	functionName = functionName.attr(operation.method);
	statements.push($.return(functionName.call(reqOptions).$if(isNuxtClient, (f) => f.generic(nuxtTypeComposable).generic($.type.or(symbolResponseType ?? "unknown", nuxtTypeDefault)).generic(symbolErrorType ?? "unknown").generic(nuxtTypeDefault), (f) => f.generic(symbolResponseType ?? "unknown").generic(symbolErrorType ?? "unknown").generic("ThrowOnError")).$if(plugin.config.responseStyle === "data", (f) => f.generic($.type.literal(plugin.config.responseStyle)))));
	return statements;
}
//#endregion
//#region src/plugins/@hey-api/sdk/v1/node.ts
const source$2 = globalThis.Symbol("@hey-api/sdk");
function isInstance(plugin) {
	const config = plugin.config.operations;
	return config.container === "class" && config.methods === "instance" && config.strategy !== "flat";
}
function attachComment$1(args) {
	const { node, operation, plugin } = args;
	return node.$if(plugin.config.comments && createOperationComment(operation), (n, v) => n.doc(v));
}
function createShellMeta$1(node) {
	return {
		category: "utility",
		resource: "class",
		resourceId: node.getPath().join("."),
		tool: "sdk"
	};
}
function createFnSymbol(plugin, item) {
	const { operation, path, tags } = item.data;
	const name = item.location[item.location.length - 1];
	return plugin.symbol(applyNaming(name, plugin.config.operations.methodName), { meta: {
		category: "sdk",
		path,
		resource: "operation",
		resourceId: operation.id,
		tags,
		tool: "sdk"
	} });
}
function childToNode(resource, plugin) {
	const refChild = plugin.referenceSymbol(createShellMeta$1(resource));
	const memberNameStr = toCase(refChild.name, plugin.config.operations.methodName.casing ?? "camelCase");
	const memberName = plugin.symbol(memberNameStr);
	if (isInstance(plugin)) {
		const privateName = plugin.symbol(`_${memberNameStr}`);
		return [$.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g.returns(refChild).do($("this").attr(privateName).nullishAssign($.new(refChild).args($.object().prop("client", $("this").attr("client")))).return()))];
	}
	if (plugin.isSymbolRegistered(refChild.id)) return [$.field(memberName, (f) => f.static().assign($(refChild)))];
	return [$.getter(memberName, (g) => g.public().static().do($.return(refChild)))];
}
function createShell$1(plugin) {
	const isAngularClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-angular";
	return { define: (node) => {
		const symbol = plugin.symbol(applyNaming(node.name, node.isRoot ? plugin.config.operations.containerName : plugin.config.operations.segmentName), { meta: createShellMeta$1(node) });
		const c = $.class(symbol).export().$if(isInstance(plugin), (c) => c.extends(plugin.referenceSymbol({
			category: "utility",
			resource: "class",
			resourceId: "HeyApiClient",
			tool: "sdk"
		}))).$if(isAngularClient && node.isRoot, (c) => c.decorator(plugin.external("@angular/core.Injectable"), $.object().prop("providedIn", $.literal("root"))));
		const dependencies = [];
		if (node.isRoot && isInstance(plugin)) enrichRootClass({
			dependencies,
			node: c,
			plugin,
			symbol
		});
		return {
			dependencies,
			node: c
		};
	} };
}
function enrichRootClass(args) {
	const { dependencies, node, plugin, symbol } = args;
	const symbolClient = plugin.symbol("HeyApiClient", { meta: {
		category: "utility",
		resource: "class",
		resourceId: "HeyApiClient",
		tool: "sdk"
	} });
	dependencies.push(createClientClass({
		plugin,
		symbol: symbolClient
	}));
	const symbolRegistry = plugin.symbol("HeyApiRegistry", { meta: {
		category: "utility",
		resource: "class",
		resourceId: "HeyApiRegistry",
		tool: "sdk"
	} });
	dependencies.push(createRegistryClass({
		plugin,
		sdkSymbol: symbol,
		symbol: symbolRegistry
	}));
	const isClientRequired = !plugin.config.client || !plugin.querySymbol({ category: "client" });
	const registry = plugin.symbol("__registry");
	node.toAccessNode = (node, options) => {
		if (options.context) return;
		return $(node.name).attr(registry).attr("get").call();
	};
	node.do($.field(registry, (f) => f.public().static().readonly().assign($.new(symbolRegistry).generic(symbol))), $.newline(), $.init((i) => i.param("args", (p) => p.required(isClientRequired).type($.type.object().prop("client", (p) => p.required(isClientRequired).type(plugin.external("client.Client"))).prop("key", (p) => p.optional().type("string")))).do($("super").call("args"), $(symbol).attr(registry).attr("set").call("this", $("args").attr("key").required(isClientRequired)))));
}
function exampleIntent(node, operation, plugin) {
	const config = plugin.config.examples;
	if (!config.enabled) return;
	plugin.intent({ async run(context) {
		const { payload } = config;
		let example = ctx.example(node, {
			...config,
			payload: (ctx) => typeof payload === "function" ? payload(operation, ctx) : payload
		});
		if (config.transform) example = await config.transform(example, operation);
		if (example) context.setExample(operation, {
			lang: config.language,
			source: example
		});
	} });
}
function implementFn(args) {
	const { node, operation, plugin } = args;
	const client = getClientPlugin(getTypedConfig(plugin));
	const isNuxtClient = client.name === "@hey-api/client-nuxt";
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const opParameters = operationParameters({
		isRequiredOptions,
		operation,
		plugin
	});
	const statements = operationStatements({
		isRequiredOptions,
		opParameters,
		operation,
		plugin
	});
	return node.$if(isNuxtClient, (m) => m.generic(nuxtTypeComposable, (t) => t.extends(plugin.external("client.Composable")).default($.type.literal("$fetch"))).generic(nuxtTypeDefault, (t) => t.$if(plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response"
	}), (t, s) => t.extends(s).default(s), (t) => t.default("undefined"))), (m) => m.generic("ThrowOnError", (t) => t.extends("boolean").default(("throwOnError" in client.config ? client.config.throwOnError : false) ?? false))).params(...opParameters.parameters).do(...statements);
}
function toNode$2(model, plugin) {
	if (model.virtual) {
		const nodes = [];
		for (const item of model.itemsFrom(source$2)) {
			const { operation } = item.data;
			let node = $.const(createFnSymbol(plugin, item)).export().assign(implementFn({
				node: $.func(),
				operation,
				plugin
			}));
			node = attachComment$1({
				node,
				operation,
				plugin
			});
			nodes.push(node);
			exampleIntent(node, operation, plugin);
		}
		return { nodes };
	}
	if (!model.shell) return { nodes: [] };
	const nodes = [];
	const isAngularClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-angular";
	const shell = model.shell.define(model);
	const node = shell.node;
	let index = 0;
	for (const item of model.itemsFrom(source$2)) {
		const { operation } = item.data;
		if (node["~dsl"] === "VarTsDsl") {} else {
			if (index > 0 || node.hasBody) node.newline();
			const method = implementFn({
				node: $.method(createFnSymbol(plugin, item), (m) => attachComment$1({
					node: m,
					operation,
					plugin
				}).public().static(!isAngularClient && !isInstance(plugin))),
				operation,
				plugin
			});
			node.do(method);
			exampleIntent(method, operation, plugin);
		}
		index += 1;
	}
	for (const child of model.children.values()) if (node["~dsl"] === "VarTsDsl") {} else {
		if (node.hasBody) node.newline();
		node.do(...childToNode(child, plugin));
	}
	nodes.push(node);
	return {
		dependencies: shell.dependencies,
		nodes
	};
}
//#endregion
//#region src/plugins/shared/utils/operation.ts
function createOperationComment(operation) {
	const comments = [];
	if (operation.summary) comments.push(escapeComment(operation.summary));
	if (operation.description) {
		if (comments.length) comments.push("");
		comments.push(escapeComment(operation.description));
	}
	if (operation.deprecated) {
		if (comments.length) comments.push("");
		comments.push("@deprecated");
	}
	return comments.length ? comments : void 0;
}
/**
* TODO: replace with plugin logic...
*
* @deprecated this needs to be refactored
*/
function isOperationOptionsRequired({ context, operation }) {
	const config = getTypedConfig(context);
	const isNuxtClient = getClientPlugin(config).name === "@hey-api/client-nuxt";
	const plugin = config.plugins["@hey-api/sdk"];
	if (plugin) {
		if (!plugin.config.client && !isInstance(plugin)) return true;
		if (plugin.config.paramsStructure === "flat") return false;
	}
	return isNuxtClient || hasOperationDataRequired(operation);
}
function hasOperationSse({ operation }) {
	for (const statusCode in operation.responses) if (operation.responses[statusCode].mediaType === "text/event-stream") return true;
	return false;
}
//#endregion
//#region src/plugins/@angular/common/shared/node.ts
const source$1 = globalThis.Symbol("@angular/common");
function attachComment(args) {
	const { node, operation, plugin } = args;
	return node.$if(plugin.config.comments && createOperationComment(operation), (n, v) => n.doc(v));
}
function createHttpRequestFnMeta(operation) {
	return {
		category: "utility",
		resource: "operation",
		resourceId: operation.id,
		role: "request",
		tool: "angular"
	};
}
function createHttpRequestShellMeta(node) {
	return {
		category: "utility",
		resource: "shell",
		resourceId: node.getPath().join("."),
		role: "request",
		tool: "angular"
	};
}
function createHttpResourceFnMeta(operation) {
	return {
		category: "utility",
		resource: "operation",
		resourceId: operation.id,
		role: "resource",
		tool: "angular"
	};
}
function createHttpResourceShellMeta(node) {
	return {
		category: "utility",
		resource: "shell",
		resourceId: node.getPath().join("."),
		role: "resource",
		tool: "angular"
	};
}
function createHttpRequestFnSymbol(plugin, item) {
	const { operation } = item.data;
	const name = item.location[item.location.length - 1];
	return plugin.symbol(applyNaming(name, plugin.config.httpRequests.methodName), { meta: createHttpRequestFnMeta(operation) });
}
function createHttpResourceFnSymbol(plugin, item) {
	const { operation } = item.data;
	const name = item.location[item.location.length - 1];
	return plugin.symbol(applyNaming(name, plugin.config.httpResources.methodName), { meta: createHttpResourceFnMeta(operation) });
}
function childToHttpRequestNode(resource, plugin) {
	const refChild = plugin.referenceSymbol(createHttpRequestShellMeta(resource));
	const memberNameStr = toCase(refChild.name, "camelCase");
	const memberName = plugin.symbol(memberNameStr);
	const privateName = plugin.symbol(`_${memberNameStr}`);
	return [$.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g.returns(refChild).do($("this").attr(privateName).nullishAssign($.new(refChild).args()).return()))];
}
function childToHttpResourceNode(resource, plugin) {
	const refChild = plugin.referenceSymbol(createHttpResourceShellMeta(resource));
	const memberNameStr = toCase(refChild.name, "camelCase");
	const memberName = plugin.symbol(memberNameStr);
	const privateName = plugin.symbol(`_${memberNameStr}`);
	return [$.field(privateName, (f) => f.private().optional().type(refChild)), $.getter(memberName, (g) => g.returns(refChild).do($("this").attr(privateName).nullishAssign($.new(refChild).args()).return()))];
}
function createHttpRequestShell(plugin) {
	const isAngularClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-angular";
	const symbolInjectable = plugin.external("@angular/core.Injectable");
	return { define: (node) => {
		const symbol = plugin.symbol(applyNaming(node.name, node.isRoot ? plugin.config.httpRequests.containerName : plugin.config.httpRequests.segmentName), { meta: createHttpRequestShellMeta(node) });
		return {
			dependencies: [],
			node: $.class(symbol).export().$if(isAngularClient && node.isRoot, (c) => c.decorator(symbolInjectable, $.object().prop("providedIn", $.literal("root"))))
		};
	} };
}
function createHttpResourceShell(plugin) {
	const isAngularClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-angular";
	const symbolInjectable = plugin.external("@angular/core.Injectable");
	return { define: (node) => {
		const symbol = plugin.symbol(applyNaming(node.name, node.isRoot ? plugin.config.httpResources.containerName : plugin.config.httpResources.segmentName), { meta: createHttpResourceShellMeta(node) });
		return {
			dependencies: [],
			node: $.class(symbol).export().$if(isAngularClient && node.isRoot, (c) => c.decorator(symbolInjectable, $.object().prop("providedIn", $.literal("root"))))
		};
	} };
}
function implementHttpRequestFn(args) {
	const { node, operation, plugin } = args;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const symbolHttpRequest = plugin.external("@angular/common/http.HttpRequest");
	const symbolClient = plugin.querySymbol({ category: "client" });
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const symbolDataType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "typescript"
	});
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response"
	});
	return node.param("options", (p) => p.required(isRequiredOptions).type($.type(symbolOptions).generic(symbolDataType ?? "unknown").generic("ThrowOnError"))).generic("ThrowOnError", (g) => g.extends("boolean").default(false)).returns($.type(symbolHttpRequest).generic(symbolResponseType ?? "unknown")).do($.return($("options").attr("client").optional().$if(symbolClient, (c, s) => c.coalesce(s)).attr("requestOptions").call($.object().prop("responseStyle", $.literal("data")).prop("method", $.literal(operation.method.toUpperCase())).prop("url", $.literal(operation.path)).spread("options")).generic(symbolResponseType ?? "unknown").generic("ThrowOnError")));
}
function implementHttpResourceFn(args) {
	const { node, operation, plugin } = args;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const symbolHttpResource = plugin.external("@angular/common/http.httpResource");
	const symbolInject = plugin.external("@angular/core.inject");
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const symbolDataType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "typescript"
	});
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response"
	});
	return node.param("options", (p) => p.required(isRequiredOptions).type($.type.func().returns($.type.or($.type(symbolOptions).generic(symbolDataType ?? "unknown").generic("ThrowOnError"), $.type("undefined"))))).generic("ThrowOnError", (g) => g.extends("boolean").default(false)).do($.return($(symbolHttpResource).call($.func().do($.const("opts").assign($.ternary("options").do($("options").call()).otherwise($.id("undefined"))), $.return($.ternary("opts").do($.lazy((ctx) => ctx.access(plugin.referenceSymbol(createHttpRequestFnMeta(operation)), { transform: (node, index) => index === 0 ? node["~dsl"] === "ClassTsDsl" ? $(symbolInject).call($(node.name)) : $(node.name) : node }).call("opts"))).otherwise($.id("undefined"))))).generic(symbolResponseType ?? "unknown")));
}
function toHttpRequestNode(model, plugin) {
	if (model.virtual) {
		const nodes = [];
		for (const item of model.itemsFrom(source$1)) {
			const { operation } = item.data;
			let node = $.const(createHttpRequestFnSymbol(plugin, item)).export().assign(implementHttpRequestFn({
				node: $.func(),
				operation,
				plugin
			}));
			node = attachComment({
				node,
				operation,
				plugin
			});
			nodes.push(node);
		}
		return { nodes };
	}
	if (!model.shell) return { nodes: [] };
	const nodes = [];
	const shell = model.shell.define(model);
	const node = shell.node;
	let index = 0;
	for (const item of model.itemsFrom(source$1)) {
		const { operation } = item.data;
		if (index > 0 || node.hasBody) node.newline();
		node.do(implementHttpRequestFn({
			node: $.method(createHttpRequestFnSymbol(plugin, item), (m) => attachComment({
				node: m,
				operation,
				plugin
			}).public()),
			operation,
			plugin
		}));
		index += 1;
	}
	for (const child of model.children.values()) {
		if (node.hasBody) node.newline();
		node.do(...childToHttpRequestNode(child, plugin));
	}
	nodes.push(node);
	return {
		dependencies: shell.dependencies,
		nodes
	};
}
function toHttpResourceNode(model, plugin) {
	if (model.virtual) {
		const nodes = [];
		for (const item of model.itemsFrom(source$1)) {
			const { operation } = item.data;
			let node = $.const(createHttpResourceFnSymbol(plugin, item)).export().assign(implementHttpResourceFn({
				node: $.func(),
				operation,
				plugin
			}));
			node = attachComment({
				node,
				operation,
				plugin
			});
			nodes.push(node);
		}
		return { nodes };
	}
	if (!model.shell) return { nodes: [] };
	const nodes = [];
	const shell = model.shell.define(model);
	const node = shell.node;
	let index = 0;
	for (const item of model.itemsFrom(source$1)) {
		const { operation } = item.data;
		if (index > 0 || node.hasBody) node.newline();
		node.do(implementHttpResourceFn({
			node: $.method(createHttpResourceFnSymbol(plugin, item), (m) => attachComment({
				node: m,
				operation,
				plugin
			}).public()),
			operation,
			plugin
		}));
		index += 1;
	}
	for (const child of model.children.values()) {
		if (node.hasBody) node.newline();
		node.do(...childToHttpResourceNode(child, plugin));
	}
	nodes.push(node);
	return {
		dependencies: shell.dependencies,
		nodes
	};
}
//#endregion
//#region src/plugins/@angular/common/plugin.ts
const handler$13 = ({ plugin }) => {
	plugin.symbol("HttpRequest", {
		external: "@angular/common/http",
		kind: "type"
	});
	plugin.symbol("inject", { external: "@angular/core" });
	plugin.symbol("Injectable", { external: "@angular/core" });
	plugin.symbol("httpResource", { external: "@angular/common/http" });
	const httpRequestStructure = new StructureModel();
	const httpResourceStructure = new StructureModel();
	if (plugin.config.httpRequests.enabled) {
		const shell = createHttpRequestShell(plugin);
		const strategy = resolveHttpRequestsStrategy(plugin);
		plugin.forEach("operation", ({ operation }) => {
			httpRequestStructure.insert({
				data: { operation },
				locations: strategy(operation).map((path) => ({
					path,
					shell
				})),
				source: source$1
			});
		}, { order: "declarations" });
	}
	if (plugin.config.httpResources.enabled) {
		const shell = createHttpResourceShell(plugin);
		const strategy = resolveHttpResourcesStrategy(plugin);
		plugin.forEach("operation", ({ operation }) => {
			httpResourceStructure.insert({
				data: { operation },
				locations: strategy(operation).map((path) => ({
					path,
					shell
				})),
				source: source$1
			});
		}, { order: "declarations" });
	}
	const allDependencies = [];
	const allNodes = [];
	for (const node of httpRequestStructure.walk()) {
		const { dependencies, nodes } = toHttpRequestNode(node, plugin);
		allDependencies.push(...dependencies ?? []);
		allNodes.push(...nodes);
	}
	for (const node of httpResourceStructure.walk()) {
		const { dependencies, nodes } = toHttpResourceNode(node, plugin);
		allDependencies.push(...dependencies ?? []);
		allNodes.push(...nodes);
	}
	const uniqueDependencies = /* @__PURE__ */ new Map();
	for (const dep of allDependencies) if (dep.symbol) uniqueDependencies.set(dep.symbol.id, dep);
	for (const dep of uniqueDependencies.values()) plugin.node(dep);
	for (const node of allNodes) plugin.node(node);
};
//#endregion
//#region src/plugins/@angular/common/config.ts
const defaultConfig$26 = {
	config: {
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/client-angular", "@hey-api/sdk"],
	handler: handler$13,
	name: "@angular/common",
	resolveConfig: (plugin, context) => {
		plugin.config.httpRequests = resolveHttpRequests(plugin.config, context);
		plugin.config.httpResources = resolveHttpResources(plugin.config, context);
	}
};
definePluginConfig(defaultConfig$26);
//#endregion
//#region src/plugins/@faker-js/faker/api.ts
var Api$4 = class {
	toNode(_schema) {}
	toNodeRef(_schema) {}
};
//#endregion
//#region src/plugins/@faker-js/faker/config.ts
const defaultConfig$25 = {
	api: new Api$4(),
	config: {
		case: "camelCase",
		includeInEntry: false
	},
	handler: () => {},
	name: "@faker-js/faker",
	resolveConfig: (plugin, context) => {
		plugin.config.definitions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "v{{name}}"
			},
			mappers,
			value: plugin.config.definitions
		});
	},
	tags: ["mocker"]
};
definePluginConfig(defaultConfig$25);
//#endregion
//#region src/plugins/@hey-api/client-core/config.ts
const clientDefaultConfig = {
	baseUrl: true,
	bundle: true,
	includeInEntry: false
};
const clientDefaultMeta = {
	dependencies: ["@hey-api/typescript"],
	tags: ["client"]
};
//#endregion
//#region src/generate/client.ts
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Returns paths to client bundle files based on execution context
*/
function getClientBundlePaths(pluginName) {
	const clientName = pluginName.slice(16);
	if (isEnvironment("development")) {
		const pluginsDir = path.resolve(__dirname, "..", "plugins", "@hey-api");
		return {
			clientPath: path.resolve(pluginsDir, `client-${clientName}`, "bundle"),
			corePath: path.resolve(pluginsDir, "client-core", "bundle")
		};
	}
	return {
		clientPath: path.resolve(__dirname, "clients", clientName),
		corePath: path.resolve(__dirname, "clients", "core")
	};
}
/**
* Returns absolute path to the client folder. This is hard-coded for now.
*/
function clientFolderAbsolutePath(config) {
	const client = getClientPlugin(config);
	if ("bundle" in client.config && client.config.bundle) {
		const renamed = config._FRAGILE_CLIENT_BUNDLE_RENAMED;
		return path.resolve(config.output.path, "client", `${renamed?.get("index") ?? "index"}.ts`);
	}
	return client.name;
}
/**
* Recursively copies files and directories.
* This is a PnP-compatible alternative to fs.cpSync that works with Yarn PnP's
* virtualized filesystem.
*/
function copyRecursivePnP(src, dest) {
	if (fs.statSync(src).isDirectory()) {
		if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
		const files = fs.readdirSync(src);
		for (const file of files) copyRecursivePnP(path.join(src, file), path.join(dest, file));
	} else {
		const content = fs.readFileSync(src);
		fs.writeFileSync(dest, content);
	}
}
function renameFile({ filePath, project, renamed }) {
	const extension = path.extname(filePath);
	const name = path.basename(filePath, extension);
	const renamedName = project.fileName?.(name) || name;
	if (renamedName !== name) {
		const outputPath = path.dirname(filePath);
		fs.renameSync(filePath, path.resolve(outputPath, `${renamedName}${extension}`));
		renamed.set(name, renamedName);
	}
}
function replaceImports({ filePath, header, module, renamed }) {
	let content = fs.readFileSync(filePath, "utf8");
	if (isEnvironment("development")) {
		content = content.replace(/from\s+['"]\.\.\/\.\.\/client-core\/bundle\//g, "from '../core/");
		content = content.replace(/from\s+['"]\.\.\/\.\.\/client-core\/bundle['"]/g, "from '../core'");
	}
	content = content.replace(/from\s+['"](\.\.?\/[^'"]*?)['"]/g, (match, importPath) => {
		const importIndex = match.indexOf(importPath);
		const extension = path.extname(importPath);
		const fileName = path.basename(importPath, extension);
		const importDir = path.dirname(importPath);
		const replacedName = (renamed.get(fileName) ?? fileName) + (module.extension ? module.extension : extension);
		return match.slice(0, importIndex) + [importDir, replacedName].filter(Boolean).join("/") + match.slice(importIndex + importPath.length);
	});
	content = `${header ?? ""}${content}`;
	fs.writeFileSync(filePath, content, "utf8");
}
/**
* Creates a `client` folder containing the same modules as the client package.
*/
function generateClientBundle({ header, module, outputPath, plugin, project }) {
	const renamed = /* @__PURE__ */ new Map();
	const headerPrefix = outputHeaderToPrefix({
		defaultValue: ["// This file is auto-generated by @hey-api/openapi-ts"],
		header,
		project
	});
	if (plugin.name.startsWith("@hey-api/client-")) {
		const { clientPath, corePath } = getClientBundlePaths(plugin.name);
		const coreOutputPath = path.resolve(outputPath, "core");
		ensureDirSync(coreOutputPath);
		copyRecursivePnP(corePath, coreOutputPath);
		const clientOutputPath = path.resolve(outputPath, "client");
		ensureDirSync(clientOutputPath);
		copyRecursivePnP(clientPath, clientOutputPath);
		if (project) {
			const copiedCoreFiles = fs.readdirSync(coreOutputPath);
			for (const file of copiedCoreFiles) renameFile({
				filePath: path.resolve(coreOutputPath, file),
				project,
				renamed
			});
			const copiedClientFiles = fs.readdirSync(clientOutputPath);
			for (const file of copiedClientFiles) renameFile({
				filePath: path.resolve(clientOutputPath, file),
				project,
				renamed
			});
		}
		const coreFiles = fs.readdirSync(coreOutputPath);
		for (const file of coreFiles) replaceImports({
			filePath: path.resolve(coreOutputPath, file),
			header: headerPrefix,
			module,
			renamed
		});
		const clientFiles = fs.readdirSync(clientOutputPath);
		for (const file of clientFiles) replaceImports({
			filePath: path.resolve(clientOutputPath, file),
			header: headerPrefix,
			module,
			renamed
		});
		return renamed;
	}
	const clientSrcPath = path.isAbsolute(plugin.name) ? path.dirname(plugin.name) : void 0;
	if (clientSrcPath) {
		const dirPath = path.resolve(outputPath, "client");
		ensureDirSync(dirPath);
		copyRecursivePnP(clientSrcPath, dirPath);
		return;
	}
	const clientModulePathComponents = path.normalize(__require.resolve(plugin.name)).split(path.sep);
	const clientDistPath = clientModulePathComponents.slice(0, clientModulePathComponents.indexOf("dist") + 1).join(path.sep);
	const distFiles = [
		clientModulePathComponents[clientModulePathComponents.length - 1],
		"index.d.mts",
		"index.d.cts"
	];
	const dirPath = path.resolve(outputPath, "client");
	ensureDirSync(dirPath);
	for (const file of distFiles) fs.copyFileSync(path.resolve(clientDistPath, file), path.resolve(dirPath, file));
}
//#endregion
//#region src/plugins/@hey-api/client-core/client.ts
function resolveRuntimeConfigPath({ outputPath, runtimeConfigPath }) {
	const isAbsolutePath = path.isAbsolute(runtimeConfigPath);
	if (!(isAbsolutePath || /^\.\.?\//.test(runtimeConfigPath))) return runtimeConfigPath;
	const absoluteInputPath = isAbsolutePath ? runtimeConfigPath : path.resolve(process.cwd(), runtimeConfigPath);
	const relative = path.relative(outputPath, absoluteInputPath).split(path.sep).join("/");
	return relative.startsWith(".") ? relative : `./${relative}`;
}
function resolveBaseUrlString({ plugin }) {
	const { baseUrl } = plugin.config;
	if (baseUrl === false) return;
	if (typeof baseUrl === "string") return baseUrl;
	const { servers } = plugin.context.ir;
	if (!servers) return;
	return servers[typeof baseUrl === "number" ? baseUrl : 0]?.url;
}
const createClient = ({ plugin }) => {
	const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin));
	const symbolCreateClient = plugin.symbol("createClient", { external: clientModule });
	const symbolCreateConfig = plugin.symbol("createConfig", { external: clientModule });
	const symbolClientOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client",
		role: "options"
	});
	const { runtimeConfigPath } = plugin.config;
	const symbolCreateClientConfig = runtimeConfigPath ? plugin.symbol("createClientConfig", { external: resolveRuntimeConfigPath({
		outputPath: getTypedConfig(plugin).output.path,
		runtimeConfigPath
	}) }) : void 0;
	const defaultVals = $.object();
	const resolvedBaseUrl = resolveBaseUrlString({ plugin });
	if (resolvedBaseUrl) {
		const url = parseUrl(resolvedBaseUrl);
		if (url.protocol && url.host && !resolvedBaseUrl.includes("{")) defaultVals.prop(getClientBaseUrlKey(getTypedConfig(plugin)), $.literal(resolvedBaseUrl));
		else if (resolvedBaseUrl !== "/" && resolvedBaseUrl.startsWith("/")) {
			const baseUrl = resolvedBaseUrl.endsWith("/") ? resolvedBaseUrl.slice(0, -1) : resolvedBaseUrl;
			defaultVals.prop(getClientBaseUrlKey(getTypedConfig(plugin)), $.literal(baseUrl));
		}
	}
	if ("throwOnError" in plugin.config && plugin.config.throwOnError) defaultVals.prop("throwOnError", $.literal(true));
	const createConfigParameters = [$(symbolCreateConfig).call(defaultVals.hasProps() ? defaultVals : void 0).generic(symbolClientOptions)];
	const symbolClient = plugin.symbol("client", { meta: { category: "client" } });
	const statement = $.const(symbolClient).export().assign($(symbolCreateClient).$if(symbolCreateClientConfig, (c, s) => c.call($(s).call(...createConfigParameters)), (c) => c.call(...createConfigParameters)));
	plugin.node(statement);
};
//#endregion
//#region src/plugins/@hey-api/client-core/createClientConfig.ts
function createClientConfigType({ plugin }) {
	const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin));
	const symbolClientOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client",
		role: "options"
	});
	const symbolConfig = plugin.symbol("Config", {
		external: clientModule,
		kind: "type"
	});
	const symbolDefaultClientOptions = plugin.symbol("ClientOptions", {
		external: clientModule,
		kind: "type"
	});
	const symbolCreateClientConfig = plugin.symbol("CreateClientConfig");
	const typeCreateClientConfig = $.type.alias(symbolCreateClientConfig).export().doc([
		"The `createClientConfig()` function will be called on client initialization",
		"and the returned object will become the client's initial configuration.",
		"",
		"You may want to initialize your client this way instead of calling",
		"`setConfig()`. This is useful for example if you're using Next.js",
		"to ensure your client always has the correct values."
	]).generic("T", (g) => g.extends(symbolDefaultClientOptions).default(symbolClientOptions)).type($.type.func().param("override", (p) => p.optional().type($.type(symbolConfig).generic($.type.and(symbolDefaultClientOptions, "T")))).returns($.type(symbolConfig).generic($.type.and($.type("Required").generic(symbolDefaultClientOptions), "T"))));
	plugin.node(typeCreateClientConfig);
}
//#endregion
//#region src/plugins/@hey-api/client-core/plugin.ts
function clientPluginHandler({ plugin }) {
	createClientConfigType({ plugin });
	createClient({ plugin });
}
//#endregion
//#region src/plugins/@hey-api/client-angular/config.ts
const defaultConfig$24 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-angular"
};
definePluginConfig(defaultConfig$24);
//#endregion
//#region src/plugins/@hey-api/client-axios/config.ts
const defaultConfig$23 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-axios"
};
definePluginConfig(defaultConfig$23);
//#endregion
//#region src/plugins/@hey-api/client-fetch/config.ts
const defaultConfig$22 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-fetch"
};
definePluginConfig(defaultConfig$22);
//#endregion
//#region src/plugins/@hey-api/client-ky/config.ts
const defaultConfig$21 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-ky"
};
definePluginConfig(defaultConfig$21);
//#endregion
//#region src/plugins/@hey-api/client-next/config.ts
const defaultConfig$20 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-next"
};
definePluginConfig(defaultConfig$20);
//#endregion
//#region src/plugins/@hey-api/client-nuxt/config.ts
const defaultConfig$19 = {
	...clientDefaultMeta,
	config: clientDefaultConfig,
	handler: clientPluginHandler,
	name: "@hey-api/client-nuxt"
};
definePluginConfig(defaultConfig$19);
//#endregion
//#region src/plugins/@hey-api/client-ofetch/config.ts
const defaultConfig$18 = {
	...clientDefaultMeta,
	config: {
		...clientDefaultConfig,
		throwOnError: false
	},
	handler: clientPluginHandler,
	name: "@hey-api/client-ofetch"
};
definePluginConfig(defaultConfig$18);
//#endregion
//#region src/plugins/@hey-api/schemas/plugin.ts
function stripSchema({ plugin, schema }) {
	if (plugin.config.type === "form") {
		if (schema.description) delete schema.description;
		if (schema["x-enum-descriptions"]) delete schema["x-enum-descriptions"];
		if (schema["x-enum-varnames"]) delete schema["x-enum-varnames"];
		if (schema["x-enumNames"]) delete schema["x-enumNames"];
		if (schema.title) delete schema.title;
	}
}
function schemaToJsonSchemaDraft_04({ context, plugin, schema: _schema }) {
	if (Array.isArray(_schema)) return _schema.map((item) => schemaToJsonSchemaDraft_04({
		context,
		plugin,
		schema: item
	}));
	const schema = structuredClone(_schema);
	if (schema.$ref) return schema;
	stripSchema({
		plugin,
		schema
	});
	if (schema.additionalProperties && typeof schema.additionalProperties !== "boolean") schema.additionalProperties = schemaToJsonSchemaDraft_04({
		context,
		plugin,
		schema: schema.additionalProperties
	});
	if (schema.allOf) schema.allOf = schema.allOf.map((item) => schemaToJsonSchemaDraft_04({
		context,
		plugin,
		schema: item
	}));
	if (schema.items) schema.items = schemaToJsonSchemaDraft_04({
		context,
		plugin,
		schema: schema.items
	});
	if (schema.properties) for (const name in schema.properties) {
		const property = schema.properties[name];
		if (typeof property !== "boolean") schema.properties[name] = schemaToJsonSchemaDraft_04({
			context,
			plugin,
			schema: property
		});
	}
	return schema;
}
function schemaToJsonSchemaDraft_05({ context, plugin, schema: _schema }) {
	if (Array.isArray(_schema)) return _schema.map((item) => schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: item
	}));
	const schema = structuredClone(_schema);
	if ("$ref" in schema) return schema;
	stripSchema({
		plugin,
		schema
	});
	if (schema.additionalProperties && typeof schema.additionalProperties !== "boolean") schema.additionalProperties = schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: schema.additionalProperties
	});
	if (schema.allOf) schema.allOf = schema.allOf.map((item) => schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: item
	}));
	if (schema.anyOf) schema.anyOf = schema.anyOf.map((item) => schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: item
	}));
	if (schema.items) schema.items = schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: schema.items
	});
	if (schema.oneOf) schema.oneOf = schema.oneOf.map((item) => schemaToJsonSchemaDraft_05({
		context,
		plugin,
		schema: item
	}));
	if (schema.properties) for (const name in schema.properties) {
		const property = schema.properties[name];
		if (typeof property !== "boolean") schema.properties[name] = schemaToJsonSchemaDraft_05({
			context,
			plugin,
			schema: property
		});
	}
	return schema;
}
function schemaToJsonSchema2020_12({ context, plugin, schema: _schema }) {
	if (Array.isArray(_schema)) return _schema.map((item) => schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: item
	}));
	const schema = structuredClone(_schema);
	stripSchema({
		plugin,
		schema
	});
	if (schema.additionalProperties && typeof schema.additionalProperties !== "boolean") schema.additionalProperties = schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: schema.additionalProperties
	});
	if (schema.allOf) schema.allOf = schema.allOf.map((item) => schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: item
	}));
	if (schema.anyOf) schema.anyOf = schema.anyOf.map((item) => schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: item
	}));
	if (schema.items) schema.items = schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: schema.items
	});
	if (schema.oneOf) schema.oneOf = schema.oneOf.map((item) => schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: item
	}));
	if (schema.prefixItems) schema.prefixItems = schema.prefixItems.map((item) => schemaToJsonSchema2020_12({
		context,
		plugin,
		schema: item
	}));
	if (schema.properties) for (const name in schema.properties) {
		const property = schema.properties[name];
		if (typeof property !== "boolean") schema.properties[name] = schemaToJsonSchema2020_12({
			context,
			plugin,
			schema: property
		});
	}
	return schema;
}
function schemaName({ name, plugin, schema }) {
	let customName = "";
	if (plugin.config.nameBuilder) if (typeof plugin.config.nameBuilder === "function") customName = plugin.config.nameBuilder(name, schema);
	else customName = plugin.config.nameBuilder.replace("{{name}}", name);
	if (!customName) customName = `${name}Schema`;
	return customName;
}
function schemasV2_0_X({ context, plugin }) {
	if (!context.spec.definitions) return;
	for (const name in context.spec.definitions) {
		const schema = context.spec.definitions[name];
		const symbol = plugin.symbol(schemaName({
			name,
			plugin,
			schema
		}), { meta: {
			category: "schema",
			resource: "definition",
			resourceId: name,
			tool: "json-schema"
		} });
		const obj = schemaToJsonSchemaDraft_04({
			context,
			plugin,
			schema
		});
		const statement = $.const(symbol).export().assign($($.fromValue(obj, { layout: "pretty" })).as("const"));
		plugin.node(statement);
	}
}
function schemasV3_0_X({ context, plugin }) {
	if (!context.spec.components) return;
	for (const name in context.spec.components.schemas) {
		const schema = context.spec.components.schemas[name];
		const symbol = plugin.symbol(schemaName({
			name,
			plugin,
			schema
		}), { meta: {
			category: "schema",
			resource: "definition",
			resourceId: name,
			tool: "json-schema"
		} });
		const obj = schemaToJsonSchemaDraft_05({
			context,
			plugin,
			schema
		});
		const statement = $.const(symbol).export().assign($($.fromValue(obj, { layout: "pretty" })).as("const"));
		plugin.node(statement);
	}
}
function schemasV3_1_X({ context, plugin }) {
	if (!context.spec.components) return;
	for (const name in context.spec.components.schemas) {
		const schema = context.spec.components.schemas[name];
		const symbol = plugin.symbol(schemaName({
			name,
			plugin,
			schema
		}), { meta: {
			category: "schema",
			resource: "definition",
			resourceId: name,
			tool: "json-schema"
		} });
		const obj = schemaToJsonSchema2020_12({
			context,
			plugin,
			schema
		});
		const statement = $.const(symbol).export().assign($($.fromValue(obj, { layout: "pretty" })).as("const"));
		plugin.node(statement);
	}
}
const handler$12 = ({ plugin }) => {
	if ("swagger" in plugin.context.spec) {
		schemasV2_0_X({
			context: plugin.context,
			plugin
		});
		return;
	}
	if (satisfies(plugin.context.spec.openapi, ">=3.0.0 <3.1.0")) {
		schemasV3_0_X({
			context: plugin.context,
			plugin
		});
		return;
	}
	if (satisfies(plugin.context.spec.openapi, ">=3.1.0")) {
		schemasV3_1_X({
			context: plugin.context,
			plugin
		});
		return;
	}
	throw new Error("Unsupported OpenAPI specification");
};
//#endregion
//#region src/plugins/@hey-api/schemas/config.ts
const defaultConfig$17 = {
	config: {
		includeInEntry: false,
		nameBuilder: (name) => `${name}Schema`,
		type: "json"
	},
	handler: handler$12,
	name: "@hey-api/schemas"
};
definePluginConfig(defaultConfig$17);
//#endregion
//#region src/plugins/@hey-api/sdk/examples/config.ts
function resolveExamples(config, context) {
	return context.valueToObject({
		defaultValue: {
			enabled: Boolean(config.examples),
			language: "JavaScript"
		},
		mappers: { boolean: (enabled) => ({ enabled }) },
		value: config.examples
	});
}
//#endregion
//#region src/plugins/@hey-api/sdk/operations/config.ts
function resolveOperations(config, context) {
	if (config.asClass !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "asClass",
		replacement: ["operations: { strategy: \"byTags\" }", "operations: { strategy: \"single\" }"]
	});
	if (config.classNameBuilder !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "classNameBuilder",
		replacement: "operations: { containerName: \"...\" }"
	});
	if (config.classStructure !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "classStructure",
		replacement: ["operations: { nesting: \"operationId\" }", "operations: { nesting: \"id\" }"]
	});
	if (config.instance !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "instance",
		replacement: `operations: { strategy: "single", containerName: "${config.instance || "Name"}", methods: "instance" }`
	});
	if (config.methodNameBuilder !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "methodNameBuilder",
		replacement: "operations: { methodName: \"...\" }"
	});
	if (config.operationId !== void 0) log.warnDeprecated({
		context: "@hey-api/sdk",
		field: "operationId",
		replacement: ["operations: { nesting: \"operationId\" }", "operations: { nesting: \"id\" }"]
	});
	const legacy = mapLegacyToConfig(config);
	return normalizeConfig$1(config.operations, legacy, context);
}
function normalizeConfig$1(input, legacy, context) {
	if (!input || typeof input === "string" || typeof input === "function") input = { strategy: input };
	const strategy = legacy.strategy ?? input.strategy ?? "flat";
	const methods = strategy === "single" ? "instance" : "static";
	return context.valueToObject({
		defaultValue: {
			container: "class",
			methods,
			nesting: "operationId",
			nestingDelimiters: /[./]/,
			strategy,
			strategyDefaultTag: "default"
		},
		mappers: { object(value) {
			value.containerName = context.valueToObject({
				defaultValue: strategy === "single" ? {
					casing: "PascalCase",
					name: "Sdk"
				} : { casing: "PascalCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.containerName
			});
			value.methodName = context.valueToObject({
				defaultValue: { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.methodName
			});
			value.segmentName = context.valueToObject({
				defaultValue: { casing: "PascalCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.segmentName
			});
			return value;
		} },
		value: {
			...legacy,
			...input
		}
	});
}
function mapLegacyToConfig(config) {
	let strategy;
	if (config.instance) strategy = "single";
	else if (config.asClass) strategy = "byTags";
	else if (config.instance === false || config.asClass === false) strategy = "flat";
	let containerName;
	let segmentName;
	if (config.instance) {
		let name = typeof config.instance === "string" ? config.instance : "Sdk";
		segmentName = { casing: "PascalCase" };
		if (config.classNameBuilder) {
			segmentName.name = config.classNameBuilder;
			if (typeof config.classNameBuilder === "string") name = config.classNameBuilder.replace("{{name}}", name);
			else name = config.classNameBuilder(name);
		}
		containerName = {
			casing: "PascalCase",
			name
		};
	} else if (config.classNameBuilder) {
		containerName = {
			casing: "PascalCase",
			name: config.classNameBuilder
		};
		segmentName = { ...containerName };
	} else if (config.asClass) {
		containerName = { casing: "PascalCase" };
		segmentName = { ...containerName };
	}
	let methods;
	if (config.instance) methods = "instance";
	else if (config.asClass) methods = "static";
	let nesting;
	if (config.classStructure === "off" || config.operationId === false) nesting = "id";
	else if (config.classStructure === "auto") nesting = "operationId";
	let methodName;
	if (config.methodNameBuilder) methodName = {
		casing: "camelCase",
		name: config.methodNameBuilder
	};
	return {
		containerName,
		methodName,
		methods,
		nesting,
		segmentName,
		strategy
	};
}
//#endregion
//#region src/plugins/@hey-api/sdk/operations/resolve.ts
function resolvePath$1(plugin) {
	if (plugin.config.operations.nesting === "id") return OperationPath.id();
	if (plugin.config.operations.nesting === "operationId") return OperationPath.fromOperationId({
		delimiters: plugin.config.operations.nestingDelimiters,
		fallback: OperationPath.id()
	});
	return plugin.config.operations.nesting;
}
function resolveStrategy$1(plugin) {
	if (plugin.config.operations.strategy === "flat") return OperationStrategy.flat({ path: (operation) => [resolvePath$1(plugin)(operation).join(".")] });
	if (plugin.config.operations.strategy === "single") {
		const root = plugin.config.operations.containerName;
		return OperationStrategy.single({
			path: resolvePath$1(plugin),
			root: typeof root.name === "string" ? root.name : root.name?.("") ?? ""
		});
	}
	if (plugin.config.operations.strategy === "byTags") return OperationStrategy.byTags({
		fallback: plugin.config.operations.strategyDefaultTag,
		path: resolvePath$1(plugin)
	});
	return plugin.config.operations.strategy;
}
//#endregion
//#region src/plugins/@hey-api/sdk/shared/typeOptions.ts
const createTypeOptions = ({ plugin }) => {
	const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin));
	const client = getClientPlugin(getTypedConfig(plugin));
	const isNuxtClient = client.name === "@hey-api/client-nuxt";
	const symbolTDataShape = plugin.symbol("TDataShape", {
		external: clientModule,
		kind: "type"
	});
	const symbolClient = plugin.symbol("Client", {
		external: clientModule,
		kind: "type",
		meta: {
			resource: "client.Client",
			tool: client.name
		}
	});
	const symbolClientOptions = plugin.symbol("Options", {
		external: clientModule,
		kind: "type"
	});
	const symbolOptions = plugin.symbol("Options", { meta: {
		category: "type",
		resource: "client-options",
		tool: "sdk"
	} });
	const typeOptions = $.type.alias(symbolOptions).export().$if(isNuxtClient, (t) => t.generic("TComposable", (g) => g.extends(plugin.external("client.Composable")).default($.type.literal("$fetch"))).generic("TData", (g) => g.extends(symbolTDataShape).default(symbolTDataShape)).generic(nuxtTypeResponse, (g) => g.default("unknown")).generic(nuxtTypeDefault, (g) => g.default("undefined")), (t) => t.generic("TData", (g) => g.extends(symbolTDataShape).default(symbolTDataShape)).generic("ThrowOnError", (g) => g.extends("boolean").default("boolean")).generic("TResponse", (g) => g.default("unknown"))).type($.type.and($.type(symbolClientOptions).$if(isNuxtClient, (t) => t.generic("TComposable").generic("TData").generic(nuxtTypeResponse).generic(nuxtTypeDefault), (t) => t.generic("TData").generic("ThrowOnError").generic("TResponse")), $.type.object().prop("client", (p) => p.doc([
		"You can provide a client instance returned by `createClient()` instead of",
		"individual options. This might be also useful if you want to implement a",
		"custom client."
	]).required(!plugin.config.client && !isInstance(plugin)).type(symbolClient)).prop("meta", (p) => p.doc(["You can pass arbitrary values through the `meta` object. This can be", "used to access values that aren't defined as part of the SDK function."]).optional().type($.type("Record").generics("string", "unknown")))));
	plugin.node(typeOptions);
};
//#endregion
//#region src/plugins/@hey-api/sdk/v1/plugin.ts
const handlerV1$3 = ({ plugin }) => {
	const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin));
	const client = getClientPlugin(getTypedConfig(plugin));
	const isAngularClient = client.name === "@hey-api/client-angular";
	const isNuxtClient = client.name === "@hey-api/client-nuxt";
	plugin.symbol("formDataBodySerializer", {
		external: clientModule,
		meta: {
			resource: "client.formDataBodySerializer",
			tool: client.name
		}
	});
	plugin.symbol("urlSearchParamsBodySerializer", {
		external: clientModule,
		meta: {
			resource: "client.urlSearchParamsBodySerializer",
			tool: client.name
		}
	});
	plugin.symbol("buildClientParams", {
		external: clientModule,
		meta: {
			resource: "client.buildClientParams",
			tool: client.name
		}
	});
	if (isNuxtClient) plugin.symbol("Composable", {
		external: clientModule,
		kind: "type",
		meta: {
			resource: "client.Composable",
			tool: client.name
		}
	});
	if (isAngularClient) plugin.symbol("Injectable", { external: "@angular/core" });
	createTypeOptions({ plugin });
	const structure = new StructureModel();
	const shell = createShell$1(plugin);
	const strategy = resolveStrategy$1(plugin);
	plugin.forEach("operation", (event) => {
		structure.insert({
			data: {
				operation: event.operation,
				path: event._path,
				tags: event.tags
			},
			locations: strategy(event.operation).map((path) => ({
				path,
				shell
			})),
			source: source$2
		});
	}, { order: "declarations" });
	const allDependencies = [];
	const allNodes = [];
	for (const node of structure.walk()) {
		const { dependencies, nodes } = toNode$2(node, plugin);
		allDependencies.push(...dependencies ?? []);
		allNodes.push(...nodes);
	}
	const uniqueDependencies = /* @__PURE__ */ new Map();
	for (const dep of allDependencies) if (dep.symbol) uniqueDependencies.set(dep.symbol.id, dep);
	for (const dep of uniqueDependencies.values()) plugin.node(dep);
	for (const node of allNodes) plugin.node(node);
};
//#endregion
//#region src/plugins/@hey-api/sdk/plugin.ts
const handler$11 = (args) => handlerV1$3(args);
//#endregion
//#region src/plugins/@hey-api/sdk/config.ts
const transformerInferWarn = "You set `transformer: true` but no transformer plugin was found in your plugins. Add a transformer plugin like `@hey-api/transformers` to enable this feature. The transformer option has been disabled.";
const validatorInferWarn$1 = "You set `validator: true` but no validator plugin was found in your plugins. Add a validator plugin like `zod` to enable this feature. The validator option has been disabled.";
const defaultConfig$16 = {
	config: {
		auth: true,
		client: true,
		comments: true,
		includeInEntry: true,
		paramsStructure: "grouped",
		responseStyle: "fields",
		transformer: false,
		validator: false,
		response: "body"
	},
	dependencies: ["@hey-api/typescript"],
	handler: handler$11,
	name: "@hey-api/sdk",
	resolveConfig: (plugin, context) => {
		if (plugin.config.client) {
			if (typeof plugin.config.client === "boolean") plugin.config.client = context.pluginByTag("client", { defaultPlugin: "@hey-api/client-fetch" });
			plugin.dependencies.add(plugin.config.client);
		} else plugin.config.client = false;
		if (plugin.config.transformer) if (typeof plugin.config.transformer === "boolean") try {
			plugin.config.transformer = context.pluginByTag("transformer");
			plugin.dependencies.add(plugin.config.transformer);
		} catch {
			log.warn(transformerInferWarn);
			plugin.config.transformer = false;
		}
		else plugin.dependencies.add(plugin.config.transformer);
		else plugin.config.transformer = false;
		if (typeof plugin.config.validator !== "object") plugin.config.validator = {
			request: plugin.config.validator,
			response: plugin.config.validator
		};
		if (plugin.config.validator.request) if (typeof plugin.config.validator.request === "boolean") try {
			plugin.config.validator.request = context.pluginByTag("validator");
			plugin.dependencies.add(plugin.config.validator.request);
		} catch {
			log.warn(validatorInferWarn$1);
			plugin.config.validator.request = false;
		}
		else plugin.dependencies.add(plugin.config.validator.request);
		else plugin.config.validator.request = false;
		if (plugin.config.validator.response) if (typeof plugin.config.validator.response === "boolean") try {
			plugin.config.validator.response = context.pluginByTag("validator");
			plugin.dependencies.add(plugin.config.validator.response);
		} catch {
			log.warn(validatorInferWarn$1);
			plugin.config.validator.response = false;
		}
		else plugin.dependencies.add(plugin.config.validator.response);
		else plugin.config.validator.response = false;
		plugin.config.examples = resolveExamples(plugin.config, context);
		plugin.config.operations = resolveOperations(plugin.config, context);
	}
};
definePluginConfig(defaultConfig$16);
//#endregion
//#region src/plugins/@hey-api/transformers/expressions.ts
const bigIntExpressions = ({ dataExpression, schema }) => {
	if (schema.type !== "integer" || schema.format !== "int64") return;
	const bigIntCallExpression = dataExpression !== void 0 ? $("BigInt").call($(dataExpression).attr("toString").call()) : void 0;
	if (bigIntCallExpression) {
		if (typeof dataExpression === "string") return [$.return(bigIntCallExpression)];
		if (dataExpression) return [$(dataExpression).assign(bigIntCallExpression)];
	}
};
const dateExpressions = ({ dataExpression, schema }) => {
	if (schema.type !== "string" || !(schema.format === "date" || schema.format === "date-time")) return;
	if (typeof dataExpression === "string") return [$.return($.new("Date").arg(dataExpression))];
	if (dataExpression) return [$(dataExpression).assign($.new("Date").arg(dataExpression))];
};
//#endregion
//#region src/plugins/@hey-api/transformers/plugin.ts
const dataVariableName = "data";
const buildingSymbols = /* @__PURE__ */ new Set();
function isNodeReturnStatement(node) {
	return node["~dsl"] === "ReturnTsDsl";
}
function schemaResponseTransformerNodes({ plugin, schema }) {
	const nodes = processSchemaType({
		dataExpression: $(dataVariableName),
		plugin,
		schema
	});
	if (nodes.length) {
		const last = nodes[nodes.length - 1];
		if (!isNodeReturnStatement(last)) nodes.push($.return(dataVariableName));
	}
	return nodes;
}
function processSchemaType({ dataExpression, plugin, schema }) {
	if (schema.$ref) {
		const query = {
			category: "transform",
			resource: "definition",
			resourceId: schema.$ref
		};
		const symbol = plugin.querySymbol(query) ?? plugin.symbol(applyNaming(refToName(schema.$ref), {
			case: "camelCase",
			name: "{{name}}SchemaResponseTransformer"
		}), { meta: query });
		if (!symbol.node && !buildingSymbols.has(symbol.id)) {
			buildingSymbols.add(symbol.id);
			try {
				const nodes = schemaResponseTransformerNodes({
					plugin,
					schema: plugin.context.resolveIrRef(schema.$ref)
				});
				if (nodes.length) {
					const node = $.const(symbol).assign($.func().param(dataVariableName, (p) => p.type("any")).do(...nodes));
					plugin.node(node);
				}
			} finally {
				buildingSymbols.delete(symbol.id);
			}
		}
		if (symbol.node || buildingSymbols.has(symbol.id)) {
			const callExpression = $(plugin.referenceSymbol(query)).call(dataExpression);
			if (dataExpression) {
				if (typeof dataExpression === "string" && dataExpression === "item") return [$.return(callExpression)];
				return [typeof dataExpression === "string" ? callExpression : $(dataExpression).assign(callExpression)];
			}
		}
		return [];
	}
	if (schema.type === "array") {
		if (!dataExpression || typeof dataExpression === "string") return [];
		const nodes = !schema.items ? [] : processSchemaType({
			dataExpression: "item",
			plugin,
			schema: schema.items?.[0] ? schema.items[0] : {
				...schema,
				type: void 0
			}
		});
		if (!nodes.length) return [];
		const mapCallbackStatements = nodes;
		if (!mapCallbackStatements.some((stmt) => isNodeReturnStatement(stmt))) mapCallbackStatements.push($.return("item"));
		return [$(dataExpression).assign($(dataExpression).attr("map").call($.func().param("item", (p) => p.type("any")).do(...mapCallbackStatements)))];
	}
	if (schema.type === "object") {
		let nodes = [];
		const required = schema.required ?? [];
		for (const name in schema.properties) {
			const property = schema.properties[name];
			const propertyAccessExpression = $(dataExpression || dataVariableName).attr(name);
			const propertyNodes = processSchemaType({
				dataExpression: propertyAccessExpression,
				plugin,
				schema: property
			});
			if (!propertyNodes.length) continue;
			const noNullableTypesInSchema = !property.items?.find((x) => x.type === "null");
			if (required.includes(name) && noNullableTypesInSchema) nodes = nodes.concat(propertyNodes);
			else nodes.push($.if(propertyAccessExpression).do(...propertyNodes));
		}
		if (schema.additionalProperties && dataExpression) {
			const entryValueNodes = processSchemaType({
				dataExpression: $(dataExpression).attr("key").computed(),
				plugin,
				schema: schema.additionalProperties
			});
			if (entryValueNodes.length) {
				const properties = Object.keys(schema.properties ?? {});
				nodes.push($.for($.const("key")).of($("Object").attr("keys").call(dataExpression)).$if(properties.length, (f) => f.do($.if($.not($.array(...properties).attr("includes").call("key"))).do(...entryValueNodes)), (f) => f.do(...entryValueNodes)));
			}
		}
		return nodes;
	}
	if (schema.items) {
		if (schema.items.length === 1) return processSchemaType({
			dataExpression: "item",
			plugin,
			schema: schema.items[0]
		});
		let arrayNodes = [];
		if (schema.logicalOperator === "and" || schema.items.length === 2 && schema.items.find((item) => item.type === "null" || item.type === "void")) {
			for (const item of schema.items) {
				const nodes = processSchemaType({
					dataExpression: dataExpression || "item",
					plugin,
					schema: item
				});
				if (nodes.length) if (dataExpression) arrayNodes = arrayNodes.concat(nodes);
				else arrayNodes.push($.if("item").do(...nodes), $.return("item"));
			}
			return arrayNodes;
		}
		if (schema.type !== "enum") {
			const hasSimpleTypes = (schema.items ?? []).every((item) => [
				"boolean",
				"integer",
				"null",
				"number",
				"string"
			].includes(item.type));
			const isProcessable = (schema.items ?? []).every((item) => {
				if (item.$ref) return true;
				if (item.logicalOperator === "and" && item.items) return true;
				return false;
			});
			if (!hasSimpleTypes && !isProcessable) console.warn(`❗️ Transformers warning: schema ${JSON.stringify(schema)} is too complex and won't be currently processed. This will likely produce an incomplete transformer which is not what you want. Please open an issue if you'd like this improved https://github.com/hey-api/openapi-ts/issues`);
		}
	}
	for (const transformer of plugin.config.transformers) {
		const t = transformer({
			$,
			config: plugin.config,
			dataExpression,
			plugin,
			schema
		});
		if (t) return t;
	}
	return [];
}
const handler$10 = ({ plugin }) => {
	plugin.forEach("operation", ({ operation }) => {
		const { response } = operationResponsesMap(operation);
		if (!response) return;
		const isNullableUnion = response.items?.length === 2 && response.items.some((item) => item.type === "null" || item.type === "void");
		if (response.items && response.items.length > 1 && response.logicalOperator !== "and" && !isNullableUnion) {
			if (plugin.context.config.logs.level === "debug") console.warn(`❗️ Transformers warning: route ${createOperationKey(operation)} has ${response.items.length} non-void success responses. This is currently not handled and we will not generate a response transformer. Please open an issue if you'd like this feature https://github.com/hey-api/openapi-ts/issues`);
			return;
		}
		const symbolResponse = plugin.querySymbol({
			category: "type",
			resource: "operation",
			resourceId: operation.id,
			role: "response"
		});
		if (!symbolResponse) return;
		const nodes = schemaResponseTransformerNodes({
			plugin,
			schema: response
		});
		if (!nodes.length) return;
		let finalNodes = nodes;
		if (isNullableUnion && nodes.length >= 2) {
			const lastNode = nodes[nodes.length - 1];
			if (isNodeReturnStatement(lastNode)) {
				const transformNodes = nodes.slice(0, -1);
				finalNodes = [$.if($(dataVariableName)).do(...transformNodes), lastNode];
			}
		}
		const symbol = plugin.symbol(applyNaming(operation.id, {
			case: "camelCase",
			name: "{{name}}ResponseTransformer"
		}), { meta: {
			category: "transform",
			resource: "operation",
			resourceId: operation.id,
			role: "response"
		} });
		const value = $.const(symbol).export().assign($.func().async().param(dataVariableName, (p) => p.type("any")).returns($.type("Promise").generic(symbolResponse)).do(...finalNodes));
		plugin.node(value);
	}, { order: "declarations" });
};
//#endregion
//#region src/plugins/@hey-api/transformers/config.ts
const defaultConfig$15 = {
	config: {
		bigInt: true,
		dates: true,
		includeInEntry: false,
		transformers: [],
		typeTransformers: []
	},
	dependencies: ["@hey-api/typescript"],
	handler: handler$10,
	name: "@hey-api/transformers",
	resolveConfig: (plugin) => {
		if (!plugin.config.transformers) plugin.config.transformers = [];
		if (plugin.config.dates) plugin.config.transformers = [...plugin.config.transformers, dateExpressions];
		if (plugin.config.bigInt) plugin.config.transformers = [...plugin.config.transformers, bigIntExpressions];
	},
	tags: ["transformer"]
};
definePluginConfig(defaultConfig$15);
//#endregion
//#region src/plugins/shared/utils/schema.ts
const createSchemaComment = (schema) => {
	const comments = [];
	if (schema.title) comments.push(escapeComment(schema.title));
	if (schema.description) {
		if (comments.length) comments.push("");
		comments.push(escapeComment(schema.description));
	}
	if (schema.deprecated) {
		if (comments.length) comments.push("");
		comments.push("@deprecated");
	}
	return comments.length ? comments : void 0;
};
//#endregion
//#region src/plugins/@hey-api/typescript/shared/export.ts
function resolveEnumKey({ baseName, duplicateAttempt, plugin }) {
	let key = toCase(baseName, plugin.config.enums.case, { stripLeadingSeparators: false });
	regexp.number.lastIndex = 0;
	if (regexp.number.test(key) && plugin.config.enums.enabled && (plugin.config.enums.mode === "typescript" || plugin.config.enums.mode === "typescript-const")) key = `_${key}`;
	if (duplicateAttempt > 0) {
		const nameConflictResolver = plugin.context.config.output?.nameConflictResolver;
		if (nameConflictResolver) {
			const resolvedName = nameConflictResolver({
				attempt: duplicateAttempt,
				baseName: key
			});
			if (resolvedName !== null) key = resolvedName;
			else key = `${key}${duplicateAttempt + 1}`;
		} else key = `${key}${duplicateAttempt + 1}`;
	}
	return key;
}
function buildEnumExport({ enumData, name, plugin, resourceId, schema }) {
	if (!enumData || enumData.mode === "type") return false;
	const mode = enumData.mode;
	const items = enumData.items;
	const duplicateCounts = {};
	const itemsWithAttempts = items.map((item, index) => {
		const candidateKey = toCase(item.key, plugin.config.enums.case, { stripLeadingSeparators: false });
		regexp.number.lastIndex = 0;
		const baseKey = regexp.number.test(candidateKey) && plugin.config.enums.enabled && (plugin.config.enums.mode === "typescript" || plugin.config.enums.mode === "typescript-const") ? `_${candidateKey}` : candidateKey;
		const duplicateAttempt = duplicateCounts[baseKey] ?? 0;
		duplicateCounts[baseKey] = duplicateAttempt + 1;
		return {
			duplicateAttempt,
			index,
			item
		};
	});
	if (mode === "javascript") {
		const filteredItems = plugin.config.enums.constantsIgnoreNull && items.some((item) => item.schema.const === null) ? items.filter((item) => item.schema.const !== null) : items;
		const symbolObject = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "utility",
				resource: "definition",
				resourceId,
				tool: "typescript"
			},
			name,
			naming: plugin.config.definitions,
			plugin,
			schema
		}));
		const objectNode = $.const(symbolObject).export().$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)).assign($.object(...itemsWithAttempts.filter(({ item }) => filteredItems.includes(item)).map(({ duplicateAttempt, item }) => $.prop({
			kind: "prop",
			name: resolveEnumKey({
				baseName: item.key,
				duplicateAttempt,
				plugin
			})
		}).$if(plugin.config.comments && createSchemaComment(item.schema), (p, v) => p.doc(v)).value($.fromValue(item.schema.const)))).as("const"));
		plugin.node(objectNode);
		const symbol = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				resource: "definition",
				resourceId,
				tool: "typescript"
			},
			name,
			naming: plugin.config.definitions,
			plugin,
			schema
		}));
		const node = $.type.alias(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (t, v) => t.doc(v)).type($.type(symbolObject).idx($.type(symbolObject).typeofType().keyof()).typeofType());
		plugin.node(node);
		return true;
	}
	if (mode === "typescript" || mode === "typescript-const") {
		if (items.some((item) => typeof item.schema.const !== "number" && typeof item.schema.const !== "string")) return false;
		const symbol = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				resource: "definition",
				resourceId,
				tool: "typescript"
			},
			name,
			naming: plugin.config.definitions,
			plugin,
			schema
		}));
		const enumNode = $.enum(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (e, v) => e.doc(v)).const(mode === "typescript-const").members(...itemsWithAttempts.map(({ duplicateAttempt, item }) => $.member(resolveEnumKey({
			baseName: item.key,
			duplicateAttempt,
			plugin
		})).$if(plugin.config.comments && createSchemaComment(item.schema), (m, v) => m.doc(v)).value($.fromValue(item.schema.const))));
		plugin.node(enumNode);
		return true;
	}
	return false;
}
function exportAst$3({ final, meta, naming, namingAnchor, path, plugin, schema, tags }) {
	const $ref = meta.resourceId || pathToJsonPointer(path);
	const name = pathToName(path, { anchor: namingAnchor });
	if (buildEnumExport({
		enumData: final.enumData,
		name,
		plugin,
		resourceId: $ref,
		schema
	})) return;
	const symbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			resource: "definition",
			resourceId: $ref,
			tags,
			tool: "typescript"
		},
		name,
		naming,
		plugin,
		schema
	}));
	const node = $.type.alias(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (t, v) => t.doc(v)).type(final.type);
	plugin.node(node);
}
//#endregion
//#region src/plugins/@hey-api/typescript/shared/meta.ts
/**
* Creates default metadata from a schema.
*/
function defaultMeta$2(schema) {
	return {
		default: schema.default,
		readonly: schema.accessScope === "read"
	};
}
/**
* Composes metadata from child results.
*
* @param children - Results from walking child schemas
* @param overrides - Explicit overrides (e.g., from parent schema)
*/
function composeMeta$2(children, overrides) {
	return {
		default: overrides?.default,
		readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly)
	};
}
/**
* Merges parent schema metadata with composed child metadata.
*
* @param parent - The parent schema
* @param children - Results from walking child schemas
*/
function inheritMeta$2(parent, children) {
	return composeMeta$2(children, {
		default: parent.default,
		readonly: parent.accessScope === "read"
	});
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/array.ts
function baseNode$69(ctx) {
	const { plugin, schema, walk } = ctx;
	if (!schema.items) return $.type("Array").generic($.type(plugin.config.topType));
	const dedupedSchema = deduplicateSchema({
		detectFormat: true,
		schema
	});
	if (!dedupedSchema.items) return $.type("Array").generic($.type(plugin.config.topType));
	const itemResults = dedupedSchema.items.map((item) => walk(item, {
		path: ref([]),
		plugin
	}));
	if (itemResults.length === 1) return $.type("Array").generic(itemResults[0].type);
	return dedupedSchema.logicalOperator === "and" ? $.type("Array").generic($.type.and(...itemResults.map((r) => r.type))) : $.type("Array").generic($.type.or(...itemResults.map((r) => r.type)));
}
function arrayResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function arrayToAst$3({ plugin, schema, walk, walkerCtx }) {
	const ctx = {
		$,
		nodes: { base: baseNode$69 },
		plugin,
		schema,
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.array;
	return resolver?.(ctx) ?? arrayResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/boolean.ts
function baseNode$68() {
	return $.type("boolean");
}
function constNode$19(ctx) {
	const { schema } = ctx;
	if (schema.const !== void 0) return $.type.fromValue(schema.const);
}
function booleanResolver$4(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return constResult;
	return ctx.nodes.base(ctx);
}
function booleanToAst$3({ plugin, schema }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$68,
			const: constNode$19
		},
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.boolean;
	return resolver?.(ctx) ?? booleanResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/enum.ts
function buildEnumData(plugin, schema) {
	if (!plugin.config.enums.enabled) return;
	const items = schema.items ?? [];
	const mode = plugin.config.enums.mode;
	return {
		items: items.map((item, index) => {
			let key;
			if (item.title) key = item.title;
			else if (typeof item.const === "number" || typeof item.const === "string") key = `${item.const}`;
			else if (typeof item.const === "boolean") key = item.const ? "true" : "false";
			else if (item.const === null) key = "null";
			else key = `${index}`;
			return {
				key,
				schema: item
			};
		}),
		mode
	};
}
function itemsNode$4(ctx) {
	const { schema } = ctx;
	const items = schema.items ?? [];
	const enumMembers = [];
	let isNullable = false;
	for (const item of items) if (item.type === "string" && typeof item.const === "string") enumMembers.push($.type.literal(item.const));
	else if (item.type === "number" && typeof item.const === "number") enumMembers.push($.type.literal(item.const));
	else if (item.type === "boolean" && typeof item.const === "boolean") enumMembers.push($.type.literal(item.const));
	else if (item.type === "null" || item.const === null) isNullable = true;
	return {
		enumMembers,
		isNullable
	};
}
function baseNode$67(ctx) {
	const { schema } = ctx;
	const items = schema.items ?? [];
	if (!items.length) return $.type("never");
	const literalTypes = items.filter((item) => item.const !== void 0).map((item) => $.type.fromValue(item.const));
	return literalTypes.length ? $.type.or(...literalTypes) : $.type("string");
}
function enumResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function enumToAst$3({ plugin, schema }) {
	const enumData = buildEnumData(plugin, schema);
	const ctx = {
		$,
		nodes: {
			base: baseNode$67,
			items: itemsNode$4
		},
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.enum;
	return {
		enumData,
		type: resolver?.(ctx) ?? enumResolver$4(ctx)
	};
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/intersection.ts
function baseNode$66(ctx) {
	const { childResults } = ctx;
	if (childResults.length === 1) return childResults[0].type;
	return $.type.and(...childResults.map((r) => r.type));
}
function intersectionResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function intersectionToAst$3({ childResults, parentSchema, plugin, schemas }) {
	const ctx = {
		$,
		childResults,
		nodes: { base: baseNode$66 },
		parentSchema,
		plugin,
		schemas
	};
	const resolver = plugin.config["~resolvers"]?.intersection;
	return resolver?.(ctx) ?? intersectionResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/never.ts
function baseNode$65() {
	return $.type("never");
}
function neverResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function neverToAst$3({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$65 },
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.never;
	return resolver?.(ctx) ?? neverResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/null.ts
function baseNode$64() {
	return $.type.literal(null);
}
function nullResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function nullToAst$4({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$64 },
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.null;
	return resolver?.(ctx) ?? nullResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/number.ts
function constNode$18(ctx) {
	const { schema } = ctx;
	if (schema.const !== void 0) return $.type.fromValue(schema.const);
}
function baseNode$63(ctx) {
	const { plugin, schema } = ctx;
	if (schema.type === "integer" && schema.format === "int64") {
		if (plugin.getPlugin("@hey-api/transformers")?.config.bigInt) return $.type("bigint");
	}
	return $.type("number");
}
function numberResolver$4(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return constResult;
	return ctx.nodes.base(ctx);
}
function numberToAst({ plugin, schema }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$63,
			const: constNode$18
		},
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.number;
	return resolver?.(ctx) ?? numberResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/object.ts
function shapeNode$4(ctx) {
	const { schema, walk, walkerCtx } = ctx;
	const shape = $.type.object();
	const required = schema.required ?? [];
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const propertyResult = walk(property, {
			path: ref([]),
			plugin: walkerCtx.plugin
		});
		const isRequired = required.includes(name);
		shape.prop(name, (p) => p.$if(walkerCtx.plugin.config.comments && createSchemaComment(property), (p, v) => p.doc(v)).readonly(property.accessScope === "read").required(isRequired).type(propertyResult.type));
	}
	return shape;
}
function baseNode$62(ctx) {
	const { schema, walk, walkerCtx } = ctx;
	const shape = shapeNode$4(ctx);
	const required = schema.required ?? [];
	let indexSchemas = [];
	let hasOptionalProperties = false;
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isRequired = required.includes(name);
		indexSchemas.push(property);
		if (!isRequired) hasOptionalProperties = true;
	}
	if (schema.patternProperties) for (const pattern in schema.patternProperties) {
		const ir = schema.patternProperties[pattern];
		indexSchemas.unshift(ir);
	}
	const hasPatterns = schema.patternProperties && Object.keys(schema.patternProperties).length;
	const addPropsRaw = schema.additionalProperties;
	const addPropsObj = addPropsRaw !== false && addPropsRaw ? addPropsRaw : void 0;
	if (hasPatterns || addPropsObj && (addPropsObj.type !== "never" || !indexSchemas.length)) {
		const addProps = addPropsObj;
		if (addProps && addProps.type !== "never") if (addProps.type === "unknown") indexSchemas = [addProps, ...schema.patternProperties ? Object.values(schema.patternProperties) : []];
		else indexSchemas.unshift(addProps);
		else if (!hasPatterns && !indexSchemas.length && addProps && addProps.type === "never") indexSchemas = [addProps];
		if (hasOptionalProperties && addProps?.type !== "unknown") indexSchemas.push({ type: "undefined" });
		if (indexSchemas.length) {
			const indexType = walk(indexSchemas.length === 1 ? indexSchemas[0] : deduplicateSchema({ schema: {
				items: indexSchemas,
				logicalOperator: "or"
			} }), {
				path: ref([]),
				plugin: walkerCtx.plugin
			}).type;
			if (schema.propertyNames?.$ref) {
				const propertyNamesResult = walk({ $ref: schema.propertyNames.$ref }, {
					path: ref([]),
					plugin: walkerCtx.plugin
				});
				return $.type.mapped("key").key(propertyNamesResult.type).optional().type(indexType);
			}
			shape.idxSig("key", (i) => i.key("string").type(indexType));
		}
	}
	return shape;
}
function objectResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function objectToAst$4({ plugin, schema, walk, walkerCtx }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$62,
			shape: shapeNode$4
		},
		plugin,
		schema,
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.object;
	return resolver?.(ctx) ?? objectResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/string.ts
function constNode$17(ctx) {
	const { schema } = ctx;
	if (schema.const !== void 0) return $.type.fromValue(schema.const);
}
function formatNode$4(ctx) {
	const { plugin, schema } = ctx;
	const { format } = schema;
	if (!format) return;
	if (format === "binary") return $.type.or($.type("Blob"), $.type("File"));
	if (format === "date-time" || format === "date") {
		if (plugin.getPlugin("@hey-api/transformers")?.config.dates) return $.type("Date");
	}
	if (format === "typeid" && typeof schema.example === "string") {
		const parts = String(schema.example).split("_");
		parts.pop();
		const typeidBase = parts.join("_");
		const typeidQuery = {
			category: "type",
			resource: "type-id",
			resourceId: typeidBase,
			tool: "typescript"
		};
		if (!plugin.querySymbol(typeidQuery)) {
			const containerQuery = {
				category: "type",
				resource: "type-id",
				tool: "typescript",
				variant: "container"
			};
			if (!plugin.querySymbol(containerQuery)) {
				const symbolTypeId = plugin.symbol("TypeID", { meta: containerQuery });
				const nodeTypeId = $.type.alias(symbolTypeId).export().generic("T", (g) => g.extends("string")).type($.type.template().add($.type("T")).add("_").add($.type("string")));
				plugin.node(nodeTypeId);
			}
			const refSymbol = plugin.referenceSymbol(containerQuery);
			const symbolTypeName = plugin.symbol(toCase(`${typeidBase}_id`, plugin.config.case), { meta: typeidQuery });
			const node = $.type.alias(symbolTypeName).export().type($.type(refSymbol).generic($.type.literal(typeidBase)));
			plugin.node(node);
		}
		return $.type(plugin.referenceSymbol(typeidQuery));
	}
}
function baseNode$61(ctx) {
	return $.type("string");
}
function stringResolver$4(ctx) {
	if (ctx.schema.const !== void 0) {
		const constResult = ctx.nodes.const(ctx);
		if (constResult) return constResult;
	}
	const formatResult = ctx.nodes.format(ctx);
	if (formatResult) return formatResult;
	return ctx.nodes.base(ctx);
}
function stringToAst$1({ plugin, schema }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$61,
			const: constNode$17,
			format: formatNode$4
		},
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.string;
	return resolver?.(ctx) ?? stringResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/tuple.ts
function baseNode$60(ctx) {
	const { plugin, schema, walk } = ctx;
	const itemTypes = [];
	if (schema.items) schema.items.forEach((item) => {
		const result = walk(item, {
			path: ref([]),
			plugin
		});
		itemTypes.push(result.type);
	});
	return $.type.tuple(...itemTypes);
}
function constNode$16(ctx) {
	const { schema } = ctx;
	if (!schema.const || !Array.isArray(schema.const)) return;
	const itemTypes = schema.const.map((value) => $.type.fromValue(value));
	return $.type.tuple(...itemTypes);
}
function tupleResolver$4(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return constResult;
	return ctx.nodes.base(ctx);
}
function tupleToAst$3({ plugin, schema, walk, walkerCtx }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$60,
			const: constNode$16
		},
		plugin,
		schema,
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.tuple;
	return resolver?.(ctx) ?? tupleResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/undefined.ts
function baseNode$59() {
	return $.type("undefined");
}
function undefinedResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function undefinedToAst$3({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$59 },
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.undefined;
	return resolver?.(ctx) ?? undefinedResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/union.ts
function baseNode$58(ctx) {
	const { childResults } = ctx;
	if (childResults.length === 1) return childResults[0].type;
	return $.type.or(...childResults.map((r) => r.type));
}
function unionResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function unionToAst$3({ childResults, parentSchema, plugin, schemas }) {
	const ctx = {
		$,
		childResults,
		nodes: { base: baseNode$58 },
		parentSchema,
		plugin,
		schemas
	};
	const resolver = plugin.config["~resolvers"]?.union;
	return resolver?.(ctx) ?? unionResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/unknown.ts
function baseNode$57(ctx) {
	return $.type(ctx.plugin.config.topType);
}
function unknownResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function unknownToAst$3({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$57 },
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.unknown;
	return resolver?.(ctx) ?? unknownResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/toAst/void.ts
function baseNode$56() {
	return $.type("void");
}
function voidResolver$4(ctx) {
	return ctx.nodes.base(ctx);
}
function voidToAst$3({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$56 },
		plugin,
		schema
	};
	const resolver = plugin.config["~resolvers"]?.void;
	return resolver?.(ctx) ?? voidResolver$4(ctx);
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/walker.ts
function createVisitor$4(config = {}) {
	const { schemaExtractor } = config;
	return {
		applyModifiers(result) {
			return {
				enumData: result.enumData,
				type: result.type
			};
		},
		array(schema, ctx, walk) {
			const type = arrayToAst$3({
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		boolean(schema, ctx) {
			const type = booleanToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		enum(schema, ctx) {
			const { enumData, type } = enumToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				enumData,
				meta: defaultMeta$2(schema),
				type
			};
		},
		integer(schema, ctx) {
			const type = numberToAst({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		intercept(schema, ctx, walk) {
			if (schemaExtractor && !schema.$ref) {
				const extracted = schemaExtractor({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(fromRef(ctx.path))
					},
					naming: ctx.plugin.config.definitions,
					path: fromRef(ctx.path),
					plugin: ctx.plugin,
					schema
				});
				if (extracted !== schema) return walk(extracted, ctx);
			}
			const transformersPlugin = ctx.plugin.getPlugin("@hey-api/transformers");
			if (transformersPlugin?.config.typeTransformers) for (const typeTransformer of transformersPlugin.config.typeTransformers) {
				const typeNode = typeTransformer({
					$,
					plugin: transformersPlugin,
					schema
				});
				if (typeNode) return {
					meta: defaultMeta$2(schema),
					type: typeNode
				};
			}
		},
		intersection(items, schemas, parentSchema, ctx) {
			const type = intersectionToAst$3({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				meta: inheritMeta$2(parentSchema, items),
				type
			};
		},
		never(schema, ctx) {
			const type = neverToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		null(schema, ctx) {
			const type = nullToAst$4({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		number(schema, ctx) {
			const type = numberToAst({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		object(schema, ctx, walk) {
			const type = objectToAst$4({
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		postProcess(result) {
			return result;
		},
		reference($ref, schema, ctx) {
			const symbol = ctx.plugin.referenceSymbol({
				category: "type",
				resource: "definition",
				resourceId: $ref
			});
			if (schema.omit && schema.omit.length) {
				const omittedKeys = schema.omit.length === 1 ? $.type.literal(schema.omit[0]) : $.type.or(...schema.omit.map((key) => $.type.literal(key)));
				return {
					meta: defaultMeta$2(schema),
					type: $.type("Omit").generics($.type(symbol), omittedKeys)
				};
			}
			return {
				meta: defaultMeta$2(schema),
				type: $.type(symbol)
			};
		},
		string(schema, ctx) {
			const type = stringToAst$1({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		tuple(schema, ctx, walk) {
			const type = tupleToAst$3({
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		undefined(schema, ctx) {
			const type = undefinedToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		union(items, schemas, parentSchema, ctx) {
			const type = unionToAst$3({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				meta: inheritMeta$2(parentSchema, items),
				type
			};
		},
		unknown(schema, ctx) {
			const type = unknownToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		},
		void(schema, ctx) {
			const type = voidToAst$3({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$2(schema),
				type
			};
		}
	};
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/processor.ts
function createProcessor$4(plugin) {
	const processor = createSchemaProcessor();
	const extractorHooks = [plugin.config["~hooks"]?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract];
	function extractor(ctx) {
		if (processor.hasEmitted(ctx.path)) return ctx.schema;
		for (const hook of extractorHooks) if (typeof hook === "boolean" ? hook : hook?.(ctx) ?? false) {
			process({
				namingAnchor: processor.context.anchor,
				tags: processor.context.tags,
				...ctx
			});
			return { $ref: pathToJsonPointer(ctx.path) };
		}
		return ctx.schema;
	}
	function process(ctx) {
		if (!processor.markEmitted(ctx.path)) return;
		const shouldExport = ctx.export !== false;
		return processor.withContext({
			anchor: ctx.namingAnchor,
			tags: ctx.tags
		}, () => {
			const visitor = createVisitor$4({ schemaExtractor: extractor });
			const result = createSchemaWalker(visitor)(ctx.schema, {
				path: ref(ctx.path),
				plugin
			});
			const final = visitor.applyModifiers(result, {
				path: ref(ctx.path),
				plugin
			});
			if (shouldExport) {
				exportAst$3({
					...ctx,
					final,
					plugin
				});
				return;
			}
			return final;
		});
	}
	return { process };
}
//#endregion
//#region src/plugins/@hey-api/typescript/api.ts
var Api$3 = class {
	schemaToType(plugin, schema) {
		const result = createProcessor$4(plugin).process({
			export: false,
			meta: {
				resource: "definition",
				resourceId: ""
			},
			naming: plugin.config.definitions,
			path: [],
			plugin,
			schema
		});
		if (!result) return $.type(plugin.config.topType);
		return result.type;
	}
};
//#endregion
//#region src/plugins/@hey-api/typescript/shared/clientOptions.ts
const serverToBaseUrlType = ({ server }) => {
	const url = parseUrl(server.url);
	if (url.protocol && url.host) return $.type.literal(server.url);
	return $.type.template().add(url.protocol || $.type("string")).add("://").add(url.host || $.type("string")).add(url.port ? `:${url.port}` : "").add(url.path || "");
};
const createClientOptions = ({ nodeIndex, plugin, servers }) => {
	const client = getClientPlugin(getTypedConfig(plugin));
	const types = servers.map((server) => serverToBaseUrlType({ server }));
	if (!servers.length) types.push($.type("string"));
	else if (!("strictBaseUrl" in client.config && client.config.strictBaseUrl)) types.push($.type.and($.type("string"), $.type.object()));
	const symbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			resource: "client",
			role: "options",
			tool: "typescript"
		},
		name: "ClientOptions",
		naming: { case: plugin.config.case },
		plugin
	}));
	const node = $.type.alias(symbol).export().type($.type.object().prop(getClientBaseUrlKey(getTypedConfig(plugin)), (p) => p.type($.type.or(...types))));
	plugin.node(node, nodeIndex);
};
//#endregion
//#region src/plugins/@hey-api/typescript/shared/operation.ts
const irParametersToIrSchema = ({ parameters }) => {
	const irSchema = { type: "object" };
	if (parameters) {
		const properties = {};
		const required = [];
		for (const key in parameters) {
			const parameter = parameters[key];
			properties[parameter.name] = deduplicateSchema({
				detectFormat: false,
				schema: parameter.schema
			});
			if (parameter.required) required.push(parameter.name);
		}
		irSchema.properties = properties;
		if (required.length) irSchema.required = required;
	}
	return irSchema;
};
const operationToType = ({ operation, path, plugin, tags }) => {
	const processor = createProcessor$4(plugin);
	const data = {
		properties: {
			body: operation.body?.schema ?? { type: "never" },
			...operation.parameters?.header ? { headers: irParametersToIrSchema({ parameters: operation.parameters.header }) } : {},
			path: operation.parameters?.path ? irParametersToIrSchema({ parameters: operation.parameters.path }) : { type: "never" },
			query: operation.parameters?.query ? irParametersToIrSchema({ parameters: operation.parameters.query }) : { type: "never" },
			url: {
				const: operation.path,
				type: "string"
			}
		},
		type: "object"
	};
	const dataRequired = [];
	if (operation.body?.required) dataRequired.push("body");
	if (data.properties.headers?.required) dataRequired.push("headers");
	if (data.properties.path.required) dataRequired.push("path");
	if (data.properties.query.required) dataRequired.push("query");
	dataRequired.push("url");
	if (dataRequired.length) data.required = dataRequired;
	const dataResult = processor.process({
		export: false,
		meta: {
			resource: "operation",
			resourceId: operation.id
		},
		naming: plugin.config.definitions,
		path: [
			...path,
			operation.id,
			"data"
		],
		plugin,
		schema: data
	});
	const dataSymbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			resource: "operation",
			resourceId: operation.id,
			role: "data",
			tags,
			tool: "typescript"
		},
		name: operation.id,
		naming: plugin.config.requests,
		operation,
		plugin
	}));
	const dataNode = $.type.alias(dataSymbol).export().type(dataResult?.type ?? $.type("never"));
	plugin.node(dataNode);
	const { error, errors, response, responses } = operationResponsesMap(operation);
	if (errors) {
		const errorsResult = processor.process({
			export: false,
			meta: {
				resource: "operation",
				resourceId: operation.id
			},
			naming: plugin.config.definitions,
			path: [
				...path,
				operation.id,
				"errors"
			],
			plugin,
			schema: errors
		});
		const errorsSymbol = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				path,
				resource: "operation",
				resourceId: operation.id,
				role: "errors",
				tags,
				tool: "typescript"
			},
			name: operation.id,
			naming: plugin.config.errors,
			operation,
			plugin
		}));
		const errorsNode = $.type.alias(errorsSymbol).export().type(errorsResult?.type ?? $.type("never"));
		plugin.node(errorsNode);
		if (error) {
			const errorSymbol = plugin.registerSymbol(buildSymbolIn({
				meta: {
					category: "type",
					path,
					resource: "operation",
					resourceId: operation.id,
					role: "error",
					tags,
					tool: "typescript"
				},
				name: operation.id,
				naming: {
					case: plugin.config.errors.case,
					name: plugin.config.errors.error
				},
				operation,
				plugin
			}));
			const errorNode = $.type.alias(errorSymbol).export().type($.type(errorsSymbol).idx($.type(errorsSymbol).keyof()));
			plugin.node(errorNode);
		}
	}
	if (responses) {
		const responsesResult = processor.process({
			export: false,
			meta: {
				resource: "operation",
				resourceId: operation.id
			},
			naming: plugin.config.definitions,
			path: [
				...path,
				operation.id,
				"responses"
			],
			plugin,
			schema: responses
		});
		const responsesSymbol = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				path,
				resource: "operation",
				resourceId: operation.id,
				role: "responses",
				tags,
				tool: "typescript"
			},
			name: operation.id,
			naming: plugin.config.responses,
			operation,
			plugin
		}));
		const responsesNode = $.type.alias(responsesSymbol).export().type(responsesResult?.type ?? $.type("never"));
		plugin.node(responsesNode);
		if (response) {
			const responseSymbol = plugin.registerSymbol(buildSymbolIn({
				meta: {
					category: "type",
					path,
					resource: "operation",
					resourceId: operation.id,
					role: "response",
					tags,
					tool: "typescript"
				},
				name: operation.id,
				naming: {
					case: plugin.config.responses.case,
					name: plugin.config.responses.response
				},
				operation,
				plugin
			}));
			const responseNode = $.type.alias(responseSymbol).export().type($.type(responsesSymbol).idx($.type(responsesSymbol).keyof()));
			plugin.node(responseNode);
		}
	}
};
//#endregion
//#region src/plugins/@hey-api/typescript/shared/webhook.ts
function webhookToType({ operation, path, plugin, tags }) {
	const processor = createProcessor$4(plugin);
	let symbolWebhookPayload;
	if (operation.body) {
		symbolWebhookPayload = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				path,
				resource: "webhook",
				resourceId: operation.id,
				role: "payload",
				tags,
				tool: "typescript"
			},
			name: operation.id,
			naming: {
				case: plugin.config.webhooks.case,
				name: plugin.config.webhooks.payload
			},
			operation,
			plugin
		}));
		const payloadResult = processor.process({
			export: false,
			meta: {
				resource: "webhook",
				resourceId: operation.id
			},
			naming: plugin.config.definitions,
			path: [
				...path,
				operation.id,
				"payload"
			],
			plugin,
			schema: operation.body.schema
		});
		const payloadNode = $.type.alias(symbolWebhookPayload).export().$if(plugin.config.comments && createSchemaComment(operation.body.schema), (t, v) => t.doc(v)).type(payloadResult?.type ?? $.type("never"));
		plugin.node(payloadNode);
	}
	const requestType = $.type.object().prop("body", (p) => p.required(Boolean(symbolWebhookPayload)).type(symbolWebhookPayload ? $.type(symbolWebhookPayload) : $.type("never"))).prop("key", (p) => p.required(true).type($.type.literal(operation.path))).prop("path", (p) => p.required(false).type($.type("never"))).prop("query", (p) => p.required(false).type($.type("never")));
	const symbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			resource: "webhook",
			resourceId: operation.id,
			role: "data",
			tags,
			tool: "typescript"
		},
		name: operation.id,
		naming: plugin.config.webhooks,
		operation,
		plugin
	}));
	const node = $.type.alias(symbol).export().type(requestType);
	plugin.node(node);
	return symbol;
}
//#endregion
//#region src/plugins/@hey-api/typescript/v1/plugin.ts
const handlerV1$2 = ({ plugin }) => {
	const nodeClientIndex = plugin.node(null);
	const nodeWebhooksIndex = plugin.node(null);
	const servers = [];
	const webhooks = [];
	const processor = createProcessor$4(plugin);
	plugin.forEach("operation", "parameter", "requestBody", "schema", "server", "webhook", (event) => {
		switch (event.type) {
			case "operation":
				operationToType({
					operation: event.operation,
					path: event._path,
					plugin,
					tags: event.tags
				});
				break;
			case "parameter":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.parameter.schema,
					tags: event.tags
				});
				break;
			case "requestBody":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.requestBody.schema,
					tags: event.tags
				});
				break;
			case "schema":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.schema,
					tags: event.tags
				});
				break;
			case "server":
				servers.push(event.server);
				break;
			case "webhook":
				webhooks.push(webhookToType({
					operation: event.operation,
					path: event._path,
					plugin,
					tags: event.tags
				}));
				break;
		}
	}, { order: "declarations" });
	createClientOptions({
		nodeIndex: nodeClientIndex,
		plugin,
		servers
	});
	if (webhooks.length) {
		const symbol = plugin.registerSymbol(buildSymbolIn({
			meta: {
				category: "type",
				resource: "webhook",
				tool: "typescript",
				variant: "container"
			},
			name: "Webhooks",
			naming: { case: plugin.config.case },
			plugin
		}));
		const node = $.type.alias(symbol).export().type($.type.or(...webhooks));
		plugin.node(node, nodeWebhooksIndex);
	}
};
//#endregion
//#region src/plugins/@hey-api/typescript/plugin.ts
const handler$9 = (args) => handlerV1$2(args);
//#endregion
//#region src/plugins/@hey-api/typescript/config.ts
const defaultConfig$14 = {
	api: new Api$3(),
	config: {
		case: "PascalCase",
		comments: true,
		includeInEntry: true,
		topType: "unknown"
	},
	handler: handler$9,
	name: "@hey-api/typescript",
	resolveConfig: (plugin, context) => {
		plugin.config.definitions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				name: "{{name}}"
			},
			mappers: {
				function: (name) => ({ name }),
				string: (name) => ({ name })
			},
			value: plugin.config.definitions
		});
		plugin.config.enums = context.valueToObject({
			defaultValue: {
				case: "SCREAMING_SNAKE_CASE",
				constantsIgnoreNull: false,
				enabled: Boolean(plugin.config.enums),
				mode: "javascript"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				string: (mode) => ({ mode })
			},
			value: plugin.config.enums
		});
		plugin.config.errors = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				error: "{{name}}Error",
				name: "{{name}}Errors"
			},
			mappers: {
				function: (name) => ({ name }),
				string: (name) => ({ name })
			},
			value: plugin.config.errors
		});
		plugin.config.requests = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				name: "{{name}}Data"
			},
			mappers: {
				function: (name) => ({ name }),
				string: (name) => ({ name })
			},
			value: plugin.config.requests
		});
		plugin.config.responses = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				name: "{{name}}Responses",
				response: "{{name}}Response"
			},
			mappers: {
				function: (name) => ({ name }),
				string: (name) => ({ name })
			},
			value: plugin.config.responses
		});
		plugin.config.webhooks = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				name: "{{name}}WebhookRequest",
				payload: "{{name}}WebhookPayload"
			},
			mappers: {
				function: (name) => ({ name }),
				string: (name) => ({ name })
			},
			value: plugin.config.webhooks
		});
	}
};
definePluginConfig(defaultConfig$14);
//#endregion
//#region src/plugins/@pinia/colada/meta.ts
const handleMeta$1 = (plugin, operation, configPath) => {
	const metaFn = plugin.config[configPath].meta;
	if (!metaFn) return;
	const metaObject = metaFn(operation);
	if (!Object.keys(metaObject).length) return;
	return $.fromValue(metaObject);
};
//#endregion
//#region src/plugins/@pinia/colada/useType.ts
const useTypeData$1 = ({ operation, plugin }) => {
	return operationOptionsType({
		operation,
		plugin: plugin.getPluginOrThrow("@hey-api/sdk")
	});
};
const useTypeError$1 = ({ operation, plugin }) => {
	const client = getClientPlugin(getTypedConfig(plugin));
	const symbolError = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "error"
	}) || "Error";
	if (client.name === "@hey-api/client-axios") {
		const symbol = plugin.external("axios.AxiosError");
		return $.type(symbol).generic(symbolError);
	}
	return $.type(symbolError);
};
const useTypeResponse$1 = ({ operation, plugin }) => {
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response"
	});
	return $.type(symbolResponseType ?? "unknown");
};
//#endregion
//#region src/plugins/@pinia/colada/utils.ts
const getPublicTypeData = ({ isNuxtClient, operation, plugin }) => {
	const typeData = useTypeData$1({
		operation,
		plugin
	});
	return isNuxtClient ? $.type("Omit").generic(typeData).generic("composable") : typeData;
};
//#endregion
//#region src/plugins/@pinia/colada/mutationOptions.ts
const createMutationOptions$1 = ({ operation, plugin }) => {
	const symbolMutationOptionsType = plugin.external(`${plugin.name}.UseMutationOptions`);
	const isNuxtClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-nuxt";
	const typeData = getPublicTypeData({
		isNuxtClient,
		operation,
		plugin
	});
	const options = plugin.symbol("options");
	const fnOptions = plugin.symbol("vars");
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().pretty().spread(options).spread(fnOptions).prop("throwOnError", $.literal(true))).await());
	const statements = [];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const mutationOpts = $.object().pretty().prop("mutation", $.func().async().param(fnOptions, (p) => p.$if(isNuxtClient, (f) => f.type($.type("Partial").generic(typeData)))).do(...statements)).$if(handleMeta$1(plugin, operation, "mutationOptions"), (o, v) => o.prop("meta", v));
	const symbolMutationOptions = plugin.symbol(applyNaming(operation.id, plugin.config.mutationOptions));
	const statement = $.const(symbolMutationOptions).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param(options, (p) => p.optional().type($.type("Partial").generic(typeData))).returns($.type(symbolMutationOptionsType).generic(useTypeResponse$1({
		operation,
		plugin
	})).generic(typeData).generic(useTypeError$1({
		operation,
		plugin
	}))).do($.return(mutationOpts)));
	plugin.node(statement);
};
//#endregion
//#region src/plugins/@pinia/colada/queryKey.ts
const TOptionsType$1 = "TOptions";
const createQueryKeyFunction$1 = ({ plugin }) => {
	const symbolCreateQueryKey = plugin.symbol(applyNaming("createQueryKey", { case: plugin.config.case }), { meta: {
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	} });
	const symbolQueryKeyType = plugin.referenceSymbol({
		category: "type",
		resource: "QueryKey",
		tool: plugin.name
	});
	const symbolJsonValue = plugin.external(`${plugin.name}._JSONValue`);
	const returnType = $.type(symbolQueryKeyType).generic(TOptionsType$1).idx(0);
	const baseUrlKey = getClientBaseUrlKey(getTypedConfig(plugin));
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const symbolClient = plugin.querySymbol({ category: "client" });
	const clientModule = clientFolderAbsolutePath(getTypedConfig(plugin));
	const symbolSerializeQueryValue = plugin.symbol("serializeQueryKeyValue", { external: clientModule });
	const fn = $.const(symbolCreateQueryKey).assign($.func().param("id", (p) => p.type("string")).param("options", (p) => p.optional().type(TOptionsType$1)).param("tags", (p) => p.optional().type("ReadonlyArray<string>")).returns($.type.tuple(returnType)).generic(TOptionsType$1, (g) => g.extends(symbolOptions)).do($.const("params").type(returnType).assign($.object().prop("_id", "id").prop(baseUrlKey, $("options").attr(baseUrlKey).optional().or($("options").attr("client").optional().$if(symbolClient, (a, v) => a.coalesce(v)).attr("getConfig").call().attr(baseUrlKey))).as(returnType)), $.if("tags").do($("params").attr("tags").assign($("tags").as("unknown").as(symbolJsonValue))), $.if($("options").attr("body").optional().neq($.id("undefined"))).do($.const("normalizedBody").assign($(symbolSerializeQueryValue).call($("options").attr("body"))), $.if($("normalizedBody").neq($.id("undefined"))).do($("params").attr("body").assign("normalizedBody"))), $.if($("options").attr("path").optional()).do($("params").attr("path").assign($("options").attr("path"))), $.if($("options").attr("query").optional().neq($.id("undefined"))).do($.const("normalizedQuery").assign($(symbolSerializeQueryValue).call($("options").attr("query"))), $.if($("normalizedQuery").neq($.id("undefined"))).do($("params").attr("query").assign("normalizedQuery"))), $.return($.array($("params")))));
	plugin.node(fn);
};
const createQueryKeyLiteral$1 = ({ id, operation, plugin }) => {
	const config = plugin.config.queryKeys;
	let tagsExpression;
	if (config.tags && operation.tags && operation.tags.length) tagsExpression = $.array(...operation.tags.map((tag) => $.literal(tag)));
	return $(plugin.referenceSymbol({
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	})).call($.literal(id), "options", tagsExpression);
};
const createQueryKeyType$1 = ({ plugin }) => {
	const symbolJsonValue = plugin.external(`${plugin.name}._JSONValue`);
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const symbolQueryKeyType = plugin.symbol("QueryKey", { meta: {
		category: "type",
		resource: "QueryKey",
		tool: plugin.name
	} });
	const queryKeyType = $.type.alias(symbolQueryKeyType).export().generic(TOptionsType$1, (g) => g.extends($.type(symbolOptions))).type($.type.tuple($.type.and($.type(`Pick<${TOptionsType$1}, 'path'>`), $.type.object().prop("_id", (p) => p.type("string")).prop(getClientBaseUrlKey(getTypedConfig(plugin)), (p) => p.optional().type(symbolJsonValue)).prop("body", (p) => p.optional().type(symbolJsonValue)).prop("query", (p) => p.optional().type(symbolJsonValue)).prop("tags", (p) => p.optional().type(symbolJsonValue)))));
	plugin.node(queryKeyType);
};
const queryKeyStatement$1 = ({ operation, plugin, symbol }) => {
	const isNuxtClient = getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-nuxt";
	return $.const(symbol).export().assign($.func().param("options", (p) => p.required(hasOperationDataRequired(operation)).type(getPublicTypeData({
		isNuxtClient,
		operation,
		plugin
	}))).do(createQueryKeyLiteral$1({
		id: operation.id,
		operation,
		plugin
	}).return()));
};
//#endregion
//#region src/plugins/@pinia/colada/queryOptions.ts
const optionsParamName$2 = "options";
const fnOptions = "context";
const createQueryOptions$1 = ({ operation, plugin }) => {
	if (hasOperationSse({ operation })) return;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	if (!plugin.querySymbol({
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	})) {
		createQueryKeyType$1({ plugin });
		createQueryKeyFunction$1({ plugin });
	}
	let keyExpression;
	if (plugin.config.queryKeys.enabled) {
		const symbolQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.queryKeys));
		const node = queryKeyStatement$1({
			operation,
			plugin,
			symbol: symbolQueryKey
		});
		plugin.node(node);
		keyExpression = $(symbolQueryKey).call(optionsParamName$2);
	} else {
		const symbolCreateQueryKey = plugin.referenceSymbol({
			category: "utility",
			resource: "createQueryKey",
			tool: plugin.name
		});
		let tagsExpr;
		if (plugin.config.queryKeys.tags && operation.tags && operation.tags.length) tagsExpr = $.array(...operation.tags.map((t) => $.literal(t)));
		keyExpression = $(symbolCreateQueryKey).call($.literal(operation.id), optionsParamName$2, tagsExpr);
	}
	const typeData = getPublicTypeData({
		isNuxtClient: getClientPlugin(getTypedConfig(plugin)).name === "@hey-api/client-nuxt",
		operation,
		plugin
	});
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().spread(optionsParamName$2).spread(fnOptions).prop("throwOnError", $.literal(true))).await());
	const statements = [];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const queryOpts = $.object().pretty().prop("key", keyExpression).prop("query", $.func().async().param(fnOptions).do(...statements)).$if(handleMeta$1(plugin, operation, "queryOptions"), (o, v) => o.prop("meta", v));
	const symbolQueryOptionsFn = plugin.symbol(applyNaming(operation.id, plugin.config.queryOptions), { meta: {
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "queryOptions",
		tool: plugin.name
	} });
	const symbolDefineQueryOptions = plugin.external(`${plugin.name}.defineQueryOptions`);
	const statement = $.const(symbolQueryOptionsFn).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($(symbolDefineQueryOptions).call($.func().param(optionsParamName$2, (p) => p.required(isRequiredOptions).type(typeData)).do($.return(queryOpts))).generics(typeData, useTypeResponse$1({
		operation,
		plugin
	}), useTypeError$1({
		operation,
		plugin
	})));
	plugin.node(statement);
};
//#endregion
//#region src/plugins/@pinia/colada/v0/plugin.ts
const handlerV0 = ({ plugin }) => {
	plugin.symbol("defineQueryOptions", { external: plugin.name });
	plugin.symbol("UseMutationOptions", {
		external: plugin.name,
		kind: "type"
	});
	plugin.symbol("UseQueryOptions", {
		external: plugin.name,
		kind: "type"
	});
	plugin.symbol("_JSONValue", {
		external: plugin.name,
		kind: "type"
	});
	plugin.symbol("AxiosError", {
		external: "axios",
		kind: "type"
	});
	plugin.forEach("operation", ({ operation }) => {
		if (plugin.hooks.operation.isQuery(operation)) {
			if (plugin.config.queryOptions.enabled) createQueryOptions$1({
				operation,
				plugin
			});
		}
		if (plugin.hooks.operation.isMutation(operation)) {
			if (plugin.config.mutationOptions.enabled) createMutationOptions$1({
				operation,
				plugin
			});
		}
	}, { order: "declarations" });
};
//#endregion
//#region src/plugins/@pinia/colada/plugin.ts
const handler$8 = (args) => handlerV0(args);
//#endregion
//#region src/plugins/@pinia/colada/config.ts
const defaultConfig$13 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/typescript", "@hey-api/sdk"],
	handler: handler$8,
	name: "@pinia/colada",
	resolveConfig: (plugin, context) => {
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}Query"
			},
			mappers,
			value: plugin.config.queryOptions
		});
	}
};
definePluginConfig(defaultConfig$13);
//#endregion
//#region src/plugins/@tanstack/query-core/shared/useType.ts
const useTypeData = ({ operation, plugin }) => {
	return operationOptionsType({
		operation,
		plugin: plugin.getPluginOrThrow("@hey-api/sdk")
	});
};
const useTypeError = ({ operation, plugin }) => {
	const client = getClientPlugin(getTypedConfig(plugin));
	const symbolError = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "error"
	}) || plugin.external(`${plugin.name}.DefaultError`);
	if (client.name === "@hey-api/client-axios") {
		const symbol = plugin.external("axios.AxiosError");
		return $.type(symbol).generic(symbolError);
	}
	return $.type(symbolError);
};
const useTypeResponse = ({ operation, plugin }) => {
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response"
	});
	return $.type(symbolResponseType ?? "unknown");
};
//#endregion
//#region src/plugins/@tanstack/query-core/queryKey.ts
const TOptionsType = "TOptions";
const createQueryKeyFunction = ({ plugin }) => {
	const symbolCreateQueryKey = plugin.symbol(applyNaming("createQueryKey", { case: plugin.config.case }), { meta: {
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	} });
	const symbolQueryKeyType = plugin.referenceSymbol({
		category: "type",
		resource: "QueryKey",
		tool: plugin.name
	});
	const baseUrlKey = getClientBaseUrlKey(getTypedConfig(plugin));
	const symbolClient = plugin.querySymbol({ category: "client" });
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const returnType = $.type(symbolQueryKeyType).generic(TOptionsType).idx(0);
	const fn = $.const(symbolCreateQueryKey).assign($.func().param("id", (p) => p.type("string")).param("options", (p) => p.optional().type(TOptionsType)).param("infinite", (p) => p.optional().type("boolean")).param("tags", (p) => p.optional().type("ReadonlyArray<string>")).generic(TOptionsType, (g) => g.extends(symbolOptions)).returns($.type.tuple(returnType)).do($.const("params").type(returnType).assign($.object().prop("_id", "id").prop(baseUrlKey, $("options").attr(baseUrlKey).optional().or($("options").attr("client").optional().$if(symbolClient, (a, v) => a.coalesce(v)).attr("getConfig").call().attr(baseUrlKey))).as(returnType)), $.if("infinite").do($("params").attr("_infinite").assign("infinite")), $.if("tags").do($("params").attr("tags").assign("tags")), $.if($("options").attr("body").optional()).do($("params").attr("body").assign($("options").attr("body"))), $.if($("options").attr("headers").optional()).do($("params").attr("headers").assign($("options").attr("headers"))), $.if($("options").attr("path").optional()).do($("params").attr("path").assign($("options").attr("path"))), $.if($("options").attr("query").optional()).do($("params").attr("query").assign($("options").attr("query"))), $.return($.array().element($("params")))));
	plugin.node(fn);
};
const createQueryKeyLiteral = ({ id, isInfinite, operation, plugin }) => {
	const config = isInfinite ? plugin.config.infiniteQueryKeys : plugin.config.queryKeys;
	let tagsArray;
	if (config.tags && operation.tags && operation.tags.length) tagsArray = $.array().elements(...operation.tags);
	return $(plugin.referenceSymbol({
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	})).call($.literal(id), "options", isInfinite || tagsArray ? $.literal(Boolean(isInfinite)) : void 0, tagsArray);
};
const createQueryKeyType = ({ plugin }) => {
	const symbolOptions = plugin.referenceSymbol({
		category: "type",
		resource: "client-options",
		tool: "sdk"
	});
	const symbolQueryKeyType = plugin.symbol("QueryKey", { meta: {
		category: "type",
		resource: "QueryKey",
		tool: plugin.name
	} });
	const queryKeyType = $.type.alias(symbolQueryKeyType).export().generic(TOptionsType, (g) => g.extends(symbolOptions)).type($.type.tuple($.type.and($.type(`Pick<${TOptionsType}, '${getClientBaseUrlKey(getTypedConfig(plugin))}' | 'body' | 'headers' | 'path' | 'query'>`), $.type.object().prop("_id", (p) => p.type("string")).prop("_infinite", (p) => p.optional().type("boolean")).prop("tags", (p) => p.optional().type("ReadonlyArray<string>")))));
	plugin.node(queryKeyType);
};
const queryKeyStatement = ({ isInfinite, operation, plugin, symbol, typeQueryKey }) => {
	const typeData = useTypeData({
		operation,
		plugin
	});
	return $.const(symbol).export().assign($.func().param("options", (p) => p.required(hasOperationDataRequired(operation)).type(typeData)).$if(isInfinite && typeQueryKey, (f, v) => f.returns(v)).do(createQueryKeyLiteral({
		id: operation.id,
		isInfinite,
		operation,
		plugin
	}).return()));
};
//#endregion
//#region src/plugins/@tanstack/query-core/shared/meta.ts
const handleMeta = (plugin, operation, configPath) => {
	const metaFn = plugin.config[configPath].meta;
	if (!metaFn) return;
	const metaObject = metaFn(operation);
	if (!Object.keys(metaObject).length) return;
	return $.fromValue(metaObject);
};
//#endregion
//#region src/plugins/@tanstack/query-core/v5/infiniteQueryOptions.ts
function createInfiniteParamsFunction({ plugin }) {
	const symbolCreateInfiniteParams = plugin.symbol(applyNaming("createInfiniteParams", { case: plugin.config.case }), { meta: {
		category: "utility",
		resource: "createInfiniteParams",
		tool: plugin.name
	} });
	const fn = $.const(symbolCreateInfiniteParams).assign($.func().generic("K", (g) => g.extends($.type("Pick").generics($.type("QueryKey").generic("Options").idx(0), $.type.or($.type.literal("body"), $.type.literal("headers"), $.type.literal("path"), $.type.literal("query"))))).param("queryKey", (p) => p.type("QueryKey<Options>")).param("page", (p) => p.type("K")).do($.const("params").assign($.object().spread($("queryKey").attr(0))), $.if($("page").attr("body")).do($("params").attr("body").assign($.object().pretty().spread($("queryKey").attr(0).attr("body").as("any")).spread($("page").attr("body").as("any")))), $.if($("page").attr("headers")).do($("params").attr("headers").assign($.object().pretty().spread($("queryKey").attr(0).attr("headers")).spread($("page").attr("headers")))), $.if($("page").attr("path")).do($("params").attr("path").assign($.object().pretty().spread($("queryKey").attr(0).attr("path").as("any")).spread($("page").attr("path").as("any")))), $.if($("page").attr("query")).do($("params").attr("query").assign($.object().pretty().spread($("queryKey").attr(0).attr("query").as("any")).spread($("page").attr("query").as("any")))), $.return($("params").as("unknown").as($("page").typeofType()))));
	plugin.node(fn);
}
function createInfiniteQueryOptions({ operation, plugin }) {
	const pagination = operationPagination({
		context: plugin.context,
		operation
	});
	if (!pagination) return;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	if (!plugin.querySymbol({
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	})) {
		createQueryKeyType({ plugin });
		createQueryKeyFunction({ plugin });
	}
	if (!plugin.querySymbol({
		category: "utility",
		resource: "createInfiniteParams",
		tool: plugin.name
	})) createInfiniteParamsFunction({ plugin });
	const symbolInfiniteQueryOptions = plugin.external(`${plugin.name}.infiniteQueryOptions`);
	const symbolInfiniteDataType = plugin.external(`${plugin.name}.InfiniteData`);
	const typeData = useTypeData({
		operation,
		plugin
	});
	const typeResponse = useTypeResponse({
		operation,
		plugin
	});
	const symbolQueryKeyType = plugin.referenceSymbol({
		category: "type",
		resource: "QueryKey",
		tool: plugin.name
	});
	const typeQueryKey = $.type(symbolQueryKeyType).generic(typeData);
	const typePageObjectParam = $.type("Pick").generics(typeQueryKey.idx(0), $.type.or($.type.literal("body"), $.type.literal("headers"), $.type.literal("path"), $.type.literal("query")));
	const pluginTypeScript = plugin.getPluginOrThrow("@hey-api/typescript");
	const type = pluginTypeScript.api.schemaToType(pluginTypeScript, pagination.schema);
	const symbolInfiniteQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.infiniteQueryKeys));
	const node = queryKeyStatement({
		isInfinite: true,
		operation,
		plugin,
		symbol: symbolInfiniteQueryKey,
		typeQueryKey
	});
	plugin.node(node);
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().spread("options").spread("params").prop("signal", $("signal")).prop("throwOnError", $.literal(true))).await());
	const symbolCreateInfiniteParams = plugin.referenceSymbol({
		category: "utility",
		resource: "createInfiniteParams",
		tool: plugin.name
	});
	const statements = [$.const("page").type(typePageObjectParam).hint("@ts-ignore").assign($.ternary($("pageParam").typeofExpr().eq($.literal("object"))).do("pageParam").otherwise($.object().pretty().prop(pagination.in, $.object().pretty().prop(pagination.name, $("pageParam"))))), $.const("params").assign($(symbolCreateInfiniteParams).call("queryKey", "page"))];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const symbolInfiniteQueryOptionsFn = plugin.symbol(applyNaming(operation.id, plugin.config.infiniteQueryOptions));
	const statement = $.const(symbolInfiniteQueryOptionsFn).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param("options", (p) => p.required(isRequiredOptions).type(typeData)).do($.return($(symbolInfiniteQueryOptions).call($.object().pretty().hint("@ts-ignore").prop("queryFn", $.func().async().param((p) => p.object("pageParam", "queryKey", "signal")).do(...statements)).prop("queryKey", $(symbolInfiniteQueryKey).call("options")).$if(handleMeta(plugin, operation, "infiniteQueryOptions"), (o, v) => o.prop("meta", v))).generics(typeResponse, useTypeError({
		operation,
		plugin
	}), $.type(symbolInfiniteDataType).generic(typeResponse), typeQueryKey, $.type.or(type, typePageObjectParam)))));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/mutationOptions.ts
function createMutationOptions({ operation, plugin }) {
	if (hasOperationSse({ operation })) return;
	const symbolMutationOptionsType = plugin.external(`${plugin.name}.MutationOptions`);
	const typeData = useTypeData({
		operation,
		plugin
	});
	const mutationType = $.type(symbolMutationOptionsType).generic(useTypeResponse({
		operation,
		plugin
	})).generic(useTypeError({
		operation,
		plugin
	})).generic(typeData);
	const fnOptions = "fnOptions";
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().spread("options").spread(fnOptions).prop("throwOnError", $.literal(true))).await());
	const statements = [];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const mutationOptionsFn = "mutationOptions";
	const symbolMutationOptions = plugin.symbol(applyNaming(operation.id, plugin.config.mutationOptions), { meta: {
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "mutationOptions",
		tool: plugin.name
	} });
	const statement = $.const(symbolMutationOptions).export(plugin.config.mutationOptions.exported).$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param("options", (p) => p.optional().type($.type("Partial").generic(typeData))).returns(mutationType).do($.const(mutationOptionsFn).type(mutationType).assign($.object().pretty().prop("mutationFn", $.func().async().param(fnOptions).do(...statements)).$if(handleMeta(plugin, operation, "mutationOptions"), (c, v) => c.prop("meta", v))), $(mutationOptionsFn).return()));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/queryOptions.ts
const optionsParamName$1 = "options";
function createQueryOptions({ operation, plugin }) {
	if (hasOperationSse({ operation })) return;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	if (!plugin.querySymbol({
		category: "utility",
		resource: "createQueryKey",
		tool: plugin.name
	})) {
		createQueryKeyType({ plugin });
		createQueryKeyFunction({ plugin });
	}
	const symbolQueryOptions = plugin.external(`${plugin.name}.queryOptions`);
	const symbolQueryKey = plugin.symbol(applyNaming(operation.id, plugin.config.queryKeys));
	const node = queryKeyStatement({
		isInfinite: false,
		operation,
		plugin,
		symbol: symbolQueryKey
	});
	plugin.node(node);
	const typeResponse = useTypeResponse({
		operation,
		plugin
	});
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().spread(optionsParamName$1).spread($("queryKey").attr(0)).prop("signal", $("signal")).prop("throwOnError", $.literal(true))).await());
	const statements = [];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const queryOptionsObj = $.object().pretty().prop("queryFn", $.func().async().param((p) => p.object("queryKey", "signal")).do(...statements)).prop("queryKey", $(symbolQueryKey).call(optionsParamName$1)).$if(handleMeta(plugin, operation, "queryOptions"), (o, v) => o.prop("meta", v));
	const symbolQueryOptionsFn = plugin.symbol(applyNaming(operation.id, plugin.config.queryOptions), { meta: {
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "queryOptions",
		tool: plugin.name
	} });
	const statement = $.const(symbolQueryOptionsFn).export(plugin.config.queryOptions.exported).$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param(optionsParamName$1, (p) => p.required(isRequiredOptions).type(useTypeData({
		operation,
		plugin
	}))).do($(symbolQueryOptions).call(queryOptionsObj).generics(typeResponse, useTypeError({
		operation,
		plugin
	}), typeResponse, $(symbolQueryKey).returnType()).return()));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/setQueryData.ts
function createSetQueryData({ operation, plugin }) {
	if (hasOperationSse({ operation })) return;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const symbolQueryOptionsFn = plugin.referenceSymbol({
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "queryOptions",
		tool: plugin.name
	});
	const symbolQueryClient = plugin.referenceSymbol({ resource: `${plugin.name}.QueryClient` });
	const typeData = useTypeData({
		operation,
		plugin
	});
	const typeResponse = useTypeResponse({
		operation,
		plugin
	});
	const responseOrUndefined = $.type.or(typeResponse, $.type("undefined"));
	const updaterType = $.type.or(typeResponse, $.type("undefined"), $.type.func().param("old", (p) => p.type(responseOrUndefined)).returns(responseOrUndefined));
	const symbolSetQueryData = plugin.symbol(applyNaming(operation.id, plugin.config.setQueryData), { meta: {
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "setQueryData",
		tool: plugin.name
	} });
	const queryClientParam = "queryClient";
	const optionsParam = "options";
	const updaterParam = "updater";
	const optionsType = isRequiredOptions ? typeData : $.type.or(typeData, $.type("undefined"));
	const statement = $.const(symbolSetQueryData).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param(queryClientParam, (p) => p.type($.type(symbolQueryClient))).param(optionsParam, (p) => p.type(optionsType)).param(updaterParam, (p) => p.type(updaterType)).do($(queryClientParam).attr("setQueryData").call($(symbolQueryOptionsFn).call(optionsParam).attr("queryKey"), $(updaterParam)).return()));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/useMutation.ts
const mutationOptionsParamName = "mutationOptions";
function createUseMutation({ operation, plugin }) {
	if (!("useMutation" in plugin.config)) return;
	const symbolUseMutationFn = plugin.symbol(applyNaming(operation.id, plugin.config.useMutation));
	const symbolUseMutation = plugin.external(`${plugin.name}.useMutation`);
	const typeData = useTypeData({
		operation,
		plugin
	});
	const symbolMutationOptionsType = plugin.external(`${plugin.name}.MutationOptions`);
	const mutationType = $.type(symbolMutationOptionsType).generic(useTypeResponse({
		operation,
		plugin
	})).generic(useTypeError({
		operation,
		plugin
	})).generic(typeData);
	const symbolMutationOptionsFn = plugin.referenceSymbol({
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "mutationOptions",
		tool: plugin.name
	});
	const func = $.func().param(mutationOptionsParamName, (p) => p.optional().type($.type("Partial").generic($.type("Omit", (t) => t.generics(mutationType, $.type.literal("mutationFn"))))));
	func.do($(symbolUseMutation).call($.object().spread($(symbolMutationOptionsFn).call()).spread(mutationOptionsParamName)).return());
	const statement = $.const(symbolUseMutationFn).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign(func);
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/useQuery.ts
const optionsParamName = "options";
function createUseQuery({ operation, plugin }) {
	if (hasOperationSse({ operation })) return;
	if (!("useQuery" in plugin.config)) return;
	const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useQuery));
	const symbolUseQuery = plugin.external(`${plugin.name}.useQuery`);
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const typeData = useTypeData({
		operation,
		plugin
	});
	const symbolQueryOptionsFn = plugin.referenceSymbol({
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "queryOptions",
		tool: plugin.name
	});
	const statement = $.const(symbolUseQueryFn).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().param(optionsParamName, (p) => p.required(isRequiredOptions).type(typeData)).do($(symbolUseQuery).call($(symbolQueryOptionsFn).call(optionsParamName)).return()));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/useSetQueryData.ts
function createUseSetQueryData({ operation, plugin }) {
	if (hasOperationSse({ operation })) return;
	if (!("useSetQueryData" in plugin.config)) return;
	const isRequiredOptions = isOperationOptionsRequired({
		context: plugin.context,
		operation
	});
	const symbolUseQueryClient = plugin.external(`${plugin.name}.useQueryClient`);
	const symbolQueryOptionsFn = plugin.referenceSymbol({
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "queryOptions",
		tool: plugin.name
	});
	const typeData = useTypeData({
		operation,
		plugin
	});
	const typeResponse = useTypeResponse({
		operation,
		plugin
	});
	const responseOrUndefined = $.type.or(typeResponse, $.type("undefined"));
	const updaterType = $.type.or(typeResponse, $.type("undefined"), $.type.func().param("old", (p) => p.type(responseOrUndefined)).returns(responseOrUndefined));
	const symbolUseSetQueryData = plugin.symbol(applyNaming(operation.id, plugin.config.useSetQueryData), { meta: {
		category: "hook",
		resource: "operation",
		resourceId: operation.id,
		role: "useSetQueryData",
		tool: plugin.name
	} });
	const queryClientVar = "queryClient";
	const optionsParam = "options";
	const updaterParam = "updater";
	const optionsType = isRequiredOptions ? typeData : $.type.or(typeData, $.type("undefined"));
	const statement = $.const(symbolUseSetQueryData).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().do($.const(queryClientVar).assign($(symbolUseQueryClient).call()), $.return($.func().param(optionsParam, (p) => p.type(optionsType)).param(updaterParam, (p) => p.type(updaterType)).do($(queryClientVar).attr("setQueryData").call($(symbolQueryOptionsFn).call(optionsParam).attr("queryKey"), $(updaterParam)).return()))));
	plugin.node(statement);
}
//#endregion
//#region src/plugins/@tanstack/query-core/v5/plugin.ts
const handlerV5 = ({ plugin }) => {
	plugin.symbol("DefaultError", {
		external: plugin.name,
		kind: "type"
	});
	plugin.symbol("InfiniteData", {
		external: plugin.name,
		kind: "type"
	});
	const mutationsType = plugin.name === "@tanstack/angular-query-experimental" || plugin.name === "@tanstack/svelte-query" || plugin.name === "@tanstack/solid-query" ? "MutationOptions" : "UseMutationOptions";
	plugin.symbol(mutationsType, {
		external: plugin.name,
		kind: "type",
		meta: { resource: `${plugin.name}.MutationOptions` }
	});
	plugin.symbol("infiniteQueryOptions", { external: plugin.name });
	plugin.symbol("QueryClient", {
		external: plugin.name,
		kind: "type",
		meta: { resource: `${plugin.name}.QueryClient` }
	});
	plugin.symbol("queryOptions", { external: plugin.name });
	plugin.symbol("useMutation", { external: plugin.name });
	plugin.symbol("useQuery", { external: plugin.name });
	plugin.symbol("useQueryClient", { external: plugin.name });
	plugin.symbol("AxiosError", {
		external: "axios",
		kind: "type"
	});
	plugin.forEach("operation", ({ operation }) => {
		if (plugin.hooks.operation.isQuery(operation)) {
			if (plugin.config.queryOptions.enabled) createQueryOptions({
				operation,
				plugin
			});
			if (plugin.config.infiniteQueryOptions.enabled) createInfiniteQueryOptions({
				operation,
				plugin
			});
			if (plugin.config.setQueryData.enabled) createSetQueryData({
				operation,
				plugin
			});
			if ("useQuery" in plugin.config && plugin.config.useQuery.enabled) createUseQuery({
				operation,
				plugin
			});
			if ("useSetQueryData" in plugin.config && plugin.config.useSetQueryData.enabled) createUseSetQueryData({
				operation,
				plugin
			});
		}
		if (plugin.hooks.operation.isMutation(operation)) {
			if (plugin.config.mutationOptions.enabled) createMutationOptions({
				operation,
				plugin
			});
			if ("useMutation" in plugin.config && plugin.config.useMutation.enabled) createUseMutation({
				operation,
				plugin
			});
		}
	}, { order: "declarations" });
};
//#endregion
//#region src/plugins/@tanstack/query-core/plugin.ts
const handler$7 = (args) => handlerV5(args);
//#endregion
//#region src/plugins/@tanstack/angular-query-experimental/config.ts
const defaultConfig$12 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/angular-query-experimental",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
	}
};
definePluginConfig(defaultConfig$12);
//#endregion
//#region src/plugins/@tanstack/preact-query/config.ts
const defaultConfig$11 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/preact-query",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
		plugin.config.useMutation = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}Mutation"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useMutation
		});
		plugin.config.useQuery = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}Query"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useQuery
		});
		plugin.config.useSetQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useSetQueryData
		});
		if (plugin.config.useMutation.enabled) {
			if (!plugin.config.mutationOptions.enabled) {
				plugin.config.mutationOptions.enabled = true;
				plugin.config.mutationOptions.exported = false;
			}
		}
		if (plugin.config.useQuery.enabled) {
			if (!plugin.config.queryOptions.enabled) {
				plugin.config.queryOptions.enabled = true;
				plugin.config.queryOptions.exported = false;
			}
		}
	}
};
definePluginConfig(defaultConfig$11);
//#endregion
//#region src/plugins/@tanstack/react-query/config.ts
const defaultConfig$10 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/react-query",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
		plugin.config.useMutation = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}Mutation"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useMutation
		});
		plugin.config.useQuery = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}Query"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useQuery
		});
		plugin.config.useSetQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "use{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useSetQueryData
		});
		if (plugin.config.useMutation.enabled) {
			if (!plugin.config.mutationOptions.enabled) {
				plugin.config.mutationOptions.enabled = true;
				plugin.config.mutationOptions.exported = false;
			}
		}
		if (plugin.config.useQuery.enabled) {
			if (!plugin.config.queryOptions.enabled) {
				plugin.config.queryOptions.enabled = true;
				plugin.config.queryOptions.exported = false;
			}
		}
	}
};
definePluginConfig(defaultConfig$10);
//#endregion
//#region src/plugins/@tanstack/solid-query/config.ts
const defaultConfig$9 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/solid-query",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
	}
};
definePluginConfig(defaultConfig$9);
//#endregion
//#region src/plugins/@tanstack/svelte-query/config.ts
const defaultConfig$8 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/svelte-query",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
	}
};
definePluginConfig(defaultConfig$8);
//#endregion
//#region src/plugins/@tanstack/vue-query/config.ts
const defaultConfig$7 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$7,
	name: "@tanstack/vue-query",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.setQueryData = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: false,
				name: "{{name}}SetQueryData"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.setQueryData
		});
	}
};
definePluginConfig(defaultConfig$7);
//#endregion
//#region src/plugins/arktype/v2/api.ts
function createRequestValidatorV2({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "arktype"
	});
	if (!symbol) return;
	const dataParameterName = "data";
	return $.func().async().param(dataParameterName).do($(symbol).attr("parseAsync").call(dataParameterName).await().return());
}
function createResponseValidatorV2({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: "arktype"
	});
	if (!symbol) return;
	const dataParameterName = "data";
	return $.func().async().param(dataParameterName).do($(symbol).attr("parseAsync").call(dataParameterName).await().return());
}
//#endregion
//#region src/plugins/arktype/api.ts
var Api$2 = class {
	createRequestValidator(args) {
		return createRequestValidatorV2(args);
	}
	createResponseValidator(args) {
		return createResponseValidatorV2(args);
	}
};
//#endregion
//#region src/plugins/arktype/constants.ts
const identifiers$2 = {
	keywords: {
		false: "false",
		true: "true"
	},
	number: {
		Infinity: "Infinity",
		NaN: "NaN",
		NegativeInfinity: "NegativeInfinity",
		epoch: "epoch",
		integer: "integer",
		safe: "safe"
	},
	primitives: {
		bigint: "bigint",
		boolean: "boolean",
		keywords: "keywords",
		null: "null",
		number: "number",
		string: "string",
		symbol: "symbol",
		undefined: "undefined",
		unit: "unit"
	},
	string: {
		NFC: "NFC",
		NFD: "NFD",
		NFKC: "NFKC",
		NFKD: "NFKD",
		alpha: "alpha",
		alphanumeric: "alphanumeric",
		base64: "base64",
		capitalize: "capitalize",
		creditCard: "creditCard",
		date: "date",
		digits: "digits",
		email: "email",
		epoch: "epoch",
		hex: "hex",
		integer: "integer",
		ip: "ip",
		iso: "iso",
		json: "json",
		lower: "lower",
		normalize: "normalize",
		numeric: "numeric",
		parse: "parse",
		preformatted: "preformatted",
		regex: "regex",
		semver: "semver",
		trim: "trim",
		upper: "upper",
		url: "url",
		uuid: "uuid",
		v1: "v1",
		v2: "v2",
		v3: "v3",
		v4: "v4",
		v5: "v5",
		v6: "v6",
		v7: "v7",
		v8: "v8"
	},
	type: {
		$: "$",
		allows: "allows",
		and: "and",
		array: "array",
		as: "as",
		assert: "assert",
		brand: "brand",
		configure: "configure",
		default: "default",
		describe: "describe",
		description: "description",
		equals: "equals",
		exclude: "exclude",
		expression: "expression",
		extends: "extends",
		extract: "extract",
		filter: "filter",
		from: "from",
		ifEquals: "ifEquals",
		ifExtends: "ifExtends",
		infer: "infer",
		inferIn: "inferIn",
		intersect: "intersect",
		json: "json",
		meta: "meta",
		narrow: "narrow",
		onDeepUndeclaredKey: "onDeepUndeclaredKey",
		onUndeclaredKey: "onUndeclaredKey",
		optional: "optional",
		or: "or",
		overlaps: "overlaps",
		pipe: "pipe",
		select: "select",
		to: "to",
		toJsonSchema: "toJsonSchema"
	}
};
//#endregion
//#region src/plugins/arktype/shared/export.ts
function exportAst$2({ ast, plugin, schema, symbol, typeInferSymbol }) {
	const type = plugin.external("arktype.type");
	const statement = $.const(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)).assign($(type).call(ast.def ? $.literal(ast.def) : ast.expression));
	plugin.node(statement);
	if (typeInferSymbol) {
		const inferType = $.type.alias(typeInferSymbol).export().type($.type(symbol).attr(identifiers$2.type.infer).typeofType());
		plugin.node(inferType);
	}
}
//#endregion
//#region src/plugins/arktype/v2/toAst/null.ts
const nullToAst$3 = (_args) => {
	const result = {};
	result.def = identifiers$2.primitives.null;
	return result;
};
//#endregion
//#region src/plugins/arktype/v2/toAst/object.ts
function objectToAst$3({ plugin, schema, state }) {
	const result = {};
	const shape = $.object().pretty();
	const required = schema.required ?? [];
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isRequired = required.includes(name);
		const propertyAst = irSchemaToAst({
			optional: !isRequired,
			plugin,
			schema: property,
			state: {
				...state,
				path: ref([
					...fromRef(state.path),
					"properties",
					name
				])
			}
		});
		if (propertyAst.hasLazyExpression) result.hasLazyExpression = true;
		shape.prop(isRequired ? name : `${name}?`, propertyAst.expression);
	}
	if (schema.additionalProperties && (!schema.properties || !Object.keys(schema.properties).length)) {
		const additionalAst = irSchemaToAst({
			plugin,
			schema: schema.additionalProperties,
			state: {
				...state,
				path: ref([...fromRef(state.path), "additionalProperties"])
			}
		});
		result.expression = $("TODO").attr("record").call($("TODO").attr("string").call(), additionalAst.expression);
		if (additionalAst.hasLazyExpression) result.hasLazyExpression = true;
		return result;
	}
	result.expression = shape;
	if (result.hasLazyExpression) return {
		...result,
		typeName: "TODO"
	};
	return result;
}
//#endregion
//#region src/plugins/arktype/v2/toAst/string.ts
const stringToAst = ({ schema }) => {
	const result = {};
	if (typeof schema.const === "string") {
		result.def = schema.const;
		return result;
	}
	let def = identifiers$2.primitives.string;
	if (schema.format) switch (schema.format) {
		case "date":
		case "date-time":
		case "time":
			def = `${def}.${identifiers$2.string.date}.${identifiers$2.string.iso}`;
			break;
		case "email":
			def = `${def}.${identifiers$2.string.email}`;
			break;
		case "ipv4":
			def = `${def}.${identifiers$2.string.ip}.${identifiers$2.string.v4}`;
			break;
		case "ipv6":
			def = `${def}.${identifiers$2.string.ip}.${identifiers$2.string.v6}`;
			break;
		case "uri":
			def = `${def}.${identifiers$2.string.url}`;
			break;
		case "uuid":
			def = `${def}.${identifiers$2.string.uuid}`;
			break;
	}
	if (schema.minLength === schema.maxLength && schema.minLength !== void 0) def = `${schema.minLength} <= ${def} <= ${schema.maxLength}`;
	else if (schema.maxLength !== void 0) {
		def = `${def} <= ${schema.maxLength}`;
		if (schema.minLength !== void 0) def = `${schema.minLength} <= ${def}`;
	} else if (schema.minLength !== void 0) def = `${def} >= ${schema.minLength}`;
	if (schema.pattern) def = `/${schema.pattern}/`;
	result.def = def;
	return result;
};
//#endregion
//#region src/plugins/arktype/v2/toAst/index.ts
function irSchemaWithTypeToAst({ schema, ...args }) {
	switch (schema.type) {
		case "null": return nullToAst$3({
			...args,
			schema
		});
		case "object": return objectToAst$3({
			...args,
			schema
		});
		case "string": return stringToAst({
			...args,
			schema
		});
	}
	return {
		def: "",
		expression: $(args.plugin.external("arktype.type")).call($.object().prop("name", $.literal("string")).prop("platform", $.literal("'android' | 'ios'")).prop("versions?", $.literal("(number | string)[]"))),
		hasLazyExpression: false
	};
}
//#endregion
//#region src/plugins/arktype/v2/plugin.ts
function irSchemaToAst({ plugin, schema, schemaExtractor, state }) {
	if (schemaExtractor && !schema.$ref) {
		const extracted = schemaExtractor({
			meta: {
				resource: "definition",
				resourceId: pathToJsonPointer(fromRef(state.path))
			},
			path: fromRef(state.path),
			schema
		});
		if (extracted !== schema) schema = extracted;
	}
	let ast = {};
	if (schema.$ref) {
		const query = {
			category: "schema",
			resource: "definition",
			resourceId: schema.$ref,
			tool: "arktype"
		};
		const refSymbol = plugin.referenceSymbol(query);
		if (plugin.isSymbolRegistered(query)) {
			const ref = $(refSymbol);
			ast.expression = ref;
		} else {
			const lazyExpression = $("TODO").attr("TODO").call($.func().returns("any").do($.return(refSymbol)));
			ast.expression = lazyExpression;
			ast.hasLazyExpression = true;
			state.hasLazyExpression["~ref"] = true;
		}
	} else if (schema.type) {
		const typeAst = irSchemaWithTypeToAst({
			plugin,
			schema,
			state
		});
		ast.def = typeAst.def;
		ast.expression = typeAst.expression;
		ast.hasLazyExpression = typeAst.hasLazyExpression;
		if (plugin.config.metadata && schema.description) {}
	} else if (schema.items) {
		schema = deduplicateSchema({ schema });
		if (schema.items) {} else ast = irSchemaToAst({
			plugin,
			schema,
			state
		});
	} else {
		const typeAst = irSchemaWithTypeToAst({
			plugin,
			schema: { type: "unknown" },
			state
		});
		ast.def = typeAst.def;
		ast.expression = typeAst.expression;
	}
	if (!ast.expression) {
		const typeAst = irSchemaWithTypeToAst({
			plugin,
			schema: { type: "unknown" },
			state
		});
		ast.expression = typeAst.expression;
	}
	return ast;
}
function handleComponent({ plugin, schema, state }) {
	const $ref = pathToJsonPointer(fromRef(state.path));
	const ast = irSchemaToAst({
		plugin,
		schema,
		state
	});
	const baseName = refToName($ref);
	exportAst$2({
		ast,
		plugin,
		schema,
		symbol: plugin.symbol(applyNaming(baseName, plugin.config.definitions), { meta: {
			category: "schema",
			path: fromRef(state.path),
			resource: "definition",
			resourceId: $ref,
			tags: fromRef(state.tags),
			tool: "arktype"
		} }),
		typeInferSymbol: plugin.config.definitions.types.infer.enabled ? plugin.symbol(applyNaming(baseName, plugin.config.definitions.types.infer), { meta: {
			category: "type",
			path: fromRef(state.path),
			resource: "definition",
			resourceId: $ref,
			tool: "arktype",
			variant: "infer"
		} }) : void 0
	});
}
const handlerV2$1 = ({ plugin }) => {
	plugin.symbol("type", { external: "arktype" });
	plugin.forEach("operation", "parameter", "requestBody", "schema", "webhook", (event) => {
		const state = refs({
			hasLazyExpression: false,
			path: event._path,
			tags: event.tags
		});
		switch (event.type) {
			case "parameter":
				handleComponent({
					plugin,
					schema: event.parameter.schema,
					state
				});
				break;
			case "requestBody":
				handleComponent({
					plugin,
					schema: event.requestBody.schema,
					state
				});
				break;
			case "schema":
				handleComponent({
					plugin,
					schema: event.schema,
					state
				});
				break;
		}
	});
};
//#endregion
//#region src/plugins/arktype/plugin.ts
const handler$6 = (args) => handlerV2$1(args);
//#endregion
//#region src/plugins/arktype/config.ts
const defaultConfig$6 = {
	api: new Api$2(),
	config: {
		case: "PascalCase",
		comments: true,
		includeInEntry: false,
		metadata: false
	},
	handler: handler$6,
	name: "arktype",
	resolveConfig: (plugin, context) => {
		plugin.config.types = context.valueToObject({
			defaultValue: { infer: {
				case: "PascalCase",
				enabled: false
			} },
			mappers: { object: (fields, defaultValue) => ({
				...fields,
				infer: context.valueToObject({
					defaultValue: {
						...defaultValue.infer,
						enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
					},
					mappers,
					value: fields.infer
				})
			}) },
			value: plugin.config.types
		});
		plugin.config.definitions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				enabled: true,
				name: "{{name}}",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.definitions
		});
		plugin.config.requests = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				enabled: true,
				name: "{{name}}Data",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}Data"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.requests
		});
		plugin.config.responses = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				enabled: true,
				name: "{{name}}Response",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}Response"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.responses
		});
		plugin.config.webhooks = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "PascalCase",
				enabled: true,
				name: "{{name}}WebhookRequest",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}WebhookRequest"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.webhooks
		});
	},
	tags: ["validator"]
};
definePluginConfig(defaultConfig$6);
//#endregion
//#region src/plugins/fastify/plugin.ts
const operationToRouteHandler = ({ operation, plugin }) => {
	const type = $.type.object();
	const symbolDataType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "typescript"
	});
	if (symbolDataType) {
		if (operation.body) type.prop("Body", (p) => p.required(operation.body.required).type($.type(symbolDataType).idx($.type.literal("body"))));
		if (operation.parameters) {
			if (operation.parameters.header) type.prop("Headers", (p) => p.required(hasParameterGroupObjectRequired(operation.parameters.header)).type($.type(symbolDataType).idx($.type.literal("headers"))));
			if (operation.parameters.path) type.prop("Params", (p) => p.required(hasParameterGroupObjectRequired(operation.parameters.path)).type($.type(symbolDataType).idx($.type.literal("path"))));
			if (operation.parameters.query) type.prop("Querystring", (p) => p.required(hasParameterGroupObjectRequired(operation.parameters.query)).type($.type(symbolDataType).idx($.type.literal("query"))));
		}
	}
	const { errors, responses } = operationResponsesMap(operation);
	let errorsTypeReference;
	const symbolErrorType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "errors"
	});
	if (symbolErrorType && errors && errors.properties) {
		const keys = Object.keys(errors.properties);
		if (keys.length) {
			if (!keys.includes("default")) errorsTypeReference = $.type(symbolErrorType);
			else if (keys.length > 1) errorsTypeReference = $.type("Omit", (t) => t.generics($.type(symbolErrorType), $.type.literal("default")));
		}
	}
	let responsesTypeReference = void 0;
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "responses"
	});
	if (symbolResponseType && responses && responses.properties) {
		const keys = Object.keys(responses.properties);
		if (keys.length) {
			if (!keys.includes("default")) responsesTypeReference = $.type(symbolResponseType);
			else if (keys.length > 1) responsesTypeReference = $.type("Omit", (t) => t.generics($.type(symbolResponseType), $.type.literal("default")));
		}
	}
	const replyTypes = [errorsTypeReference, responsesTypeReference].filter((t) => t !== void 0);
	if (replyTypes.length) type.prop("Reply", (p) => p.type($.type.and(...replyTypes)));
	if (type.isEmpty) return;
	const symbolRouteHandler = plugin.referenceSymbol({
		category: "type",
		resource: "route-handler",
		tool: "fastify"
	});
	return {
		name: operation.id,
		type: $.type(symbolRouteHandler, (t) => t.generic(type))
	};
};
const handler$5 = ({ plugin }) => {
	plugin.symbol("RouteHandler", {
		external: "fastify",
		kind: "type",
		meta: {
			category: "type",
			resource: "route-handler",
			tool: "fastify"
		}
	});
	const symbolRouteHandlers = plugin.symbol("RouteHandlers");
	const type = $.type.object();
	plugin.forEach("operation", ({ operation }) => {
		const routeHandler = operationToRouteHandler({
			operation,
			plugin
		});
		if (routeHandler) type.prop(routeHandler.name, (p) => p.type(routeHandler.type));
	}, { order: "declarations" });
	const node = $.type.alias(symbolRouteHandlers).export().type(type);
	plugin.node(node);
};
//#endregion
//#region src/plugins/fastify/config.ts
const defaultConfig$5 = {
	config: { includeInEntry: false },
	dependencies: ["@hey-api/typescript"],
	handler: handler$5,
	name: "fastify"
};
definePluginConfig(defaultConfig$5);
//#endregion
//#region src/plugins/nestjs/plugin.ts
const operationToMethod = ({ operation, plugin }) => {
	const funcType = $.type.func();
	const symbolDataType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "data",
		tool: "typescript"
	});
	if (symbolDataType) {
		const params = [];
		if (operation.parameters?.path) params.push({
			isRequired: hasParameterGroupObjectRequired(operation.parameters.path),
			key: "path"
		});
		if (operation.parameters?.query) params.push({
			isRequired: hasParameterGroupObjectRequired(operation.parameters.query),
			key: "query"
		});
		if (operation.body) params.push({
			isRequired: operation.body.required ?? false,
			key: "body"
		});
		if (operation.parameters?.header) params.push({
			isRequired: hasParameterGroupObjectRequired(operation.parameters.header),
			key: "headers"
		});
		params.sort((a, b) => a.isRequired === b.isRequired ? 0 : a.isRequired ? -1 : 1);
		for (const param of params) funcType.param(param.key, (p) => p.required(param.isRequired).type($.type(symbolDataType).idx($.type.literal(param.key))));
	}
	const { responses } = operationResponsesMap(operation);
	const symbolResponseType = plugin.querySymbol({
		category: "type",
		resource: "operation",
		resourceId: operation.id,
		role: "response",
		tool: "typescript"
	});
	if (symbolResponseType && responses) funcType.returns($.type("Promise", (t) => t.generic($.type(symbolResponseType))));
	else funcType.returns($.type("Promise", (t) => t.generic($.type("void"))));
	return {
		name: operation.id,
		type: funcType
	};
};
const emitTypeAlias = ({ methods, plugin, typeName }) => {
	const symbol = plugin.symbol(typeName);
	const type = $.type.object();
	for (const method of methods) type.prop(method.name, (p) => p.type(method.type));
	plugin.node($.type.alias(symbol).export().type(type));
};
const handler$4 = ({ plugin }) => {
	const operationsByTag = /* @__PURE__ */ new Map();
	plugin.forEach("operation", ({ operation, tags }) => {
		const tag = tags?.[0] ?? "default";
		if (!operationsByTag.has(tag)) operationsByTag.set(tag, []);
		const method = operationToMethod({
			operation,
			plugin
		});
		operationsByTag.get(tag).push(method);
	}, { order: "declarations" });
	for (const [tag, methods] of operationsByTag) emitTypeAlias({
		methods,
		plugin,
		typeName: `${toCase(tag, "PascalCase")}ControllerMethods`
	});
};
//#endregion
//#region src/plugins/nestjs/config.ts
const defaultConfig$4 = {
	config: { includeInEntry: false },
	dependencies: ["@hey-api/typescript"],
	handler: handler$4,
	name: "nestjs"
};
definePluginConfig(defaultConfig$4);
//#endregion
//#region src/plugins/orpc/contracts/config.ts
function resolveContracts(config, context) {
	return normalizeConfig(config.contracts, context);
}
function normalizeConfig(input, context) {
	if (!input || typeof input === "string" || typeof input === "function") input = { strategy: input };
	const strategy = input.strategy ?? "single";
	return context.valueToObject({
		defaultValue: {
			container: "object",
			nesting: "operationId",
			nestingDelimiters: /[./]/,
			strategy,
			strategyDefaultTag: "default"
		},
		mappers: { object(value) {
			value.containerName = context.valueToObject({
				defaultValue: strategy === "single" ? {
					casing: "camelCase",
					name: "contract"
				} : { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.containerName
			});
			value.contractName = context.valueToObject({
				defaultValue: { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.contractName
			});
			value.segmentName = context.valueToObject({
				defaultValue: { casing: "camelCase" },
				mappers: {
					function: (name) => ({ name }),
					string: (name) => ({ name })
				},
				value: value.segmentName
			});
			return value;
		} },
		value: input
	});
}
//#endregion
//#region src/plugins/orpc/shared/operation.ts
function hasInput(operation) {
	const hasPathParams = Boolean(operation.parameters?.path && Object.keys(operation.parameters.path).length);
	const hasQueryParams = Boolean(operation.parameters?.query && Object.keys(operation.parameters.query).length);
	const hasHeaderParams = Boolean(operation.parameters?.header && Object.keys(operation.parameters.header).length);
	const hasBody = Boolean(operation.body);
	return hasPathParams || hasQueryParams || hasHeaderParams || hasBody;
}
function getSuccessResponse(operation) {
	if (operation.responses) for (const [statusCode, response] of Object.entries(operation.responses)) {
		const statusCodeNumber = Number.parseInt(statusCode, 10);
		if (statusCodeNumber >= 200 && statusCodeNumber <= 399 && response?.mediaType && response?.schema) return {
			hasOutput: true,
			statusCode: statusCodeNumber
		};
	}
	return {
		hasOutput: false,
		statusCode: void 0
	};
}
function getTags(operation, defaultTag) {
	return operation.tags && operation.tags.length ? [...operation.tags] : [defaultTag];
}
//#endregion
//#region src/plugins/orpc/contracts/node.ts
const source = globalThis.Symbol("orpc");
function createShellMeta(node) {
	return {
		category: "contract",
		resource: "container",
		resourceId: node.getPath().join("."),
		tool: "orpc"
	};
}
function createContractSymbol(plugin, item) {
	const { operation, path, tags } = item.data;
	const name = item.location[item.location.length - 1];
	return plugin.symbol(applyNaming(name, plugin.config.contracts.contractName), { meta: {
		category: "contract",
		path,
		resource: "operation",
		resourceId: operation.id,
		role: "contract",
		tags,
		tool: plugin.name
	} });
}
function createContractExpression(plugin, operation) {
	const successResponse = getSuccessResponse(operation);
	const tags = getTags(operation, plugin.config.contracts.strategyDefaultTag);
	let expression = $(plugin.external("@orpc/contract.oc")).attr("route").call($.object().$if(operation.deprecated, (o, v) => o.prop("deprecated", $.literal(v))).$if(operation.description, (o, v) => o.prop("description", $.literal(v))).prop("inputStructure", $.literal("detailed")).prop("method", $.literal(operation.method.toUpperCase())).$if(operation.operationId, (o, v) => o.prop("operationId", $.literal(v))).prop("path", $.literal(operation.path)).$if(successResponse.hasOutput && successResponse.statusCode !== 200 && successResponse.statusCode, (o, v) => o.prop("successStatus", $.literal(v))).$if(operation.summary, (o, v) => o.prop("summary", $.literal(v))).$if(Boolean(tags.length) && tags, (o, v) => o.prop("tags", $.fromValue(v))));
	if (hasInput(operation) && plugin.config.validator.input) {
		const validator = plugin.getPluginOrThrow(plugin.config.validator.input);
		if ("createRequestSchema" in validator.api) {
			const requestSchema = validator.api.createRequestSchema({
				layers: {
					body: { whenEmpty: "omit" },
					headers: { whenEmpty: "omit" },
					path: {
						as: "params",
						whenEmpty: "omit"
					},
					query: { whenEmpty: "omit" }
				},
				operation,
				plugin: validator
			});
			if (requestSchema) expression = expression.attr("input").call(requestSchema);
		}
	}
	if (successResponse.hasOutput && plugin.config.validator.output) expression = expression.attr("output").call(plugin.referenceSymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: plugin.config.validator.output
	}));
	return expression;
}
function buildContainerObject(node, plugin, symbols) {
	const obj = $.object();
	for (const item of node.itemsFrom(source)) {
		const { operation } = item.data;
		const contractSymbol = symbols.get(operation.id);
		const name = item.location[item.location.length - 1];
		const propName = applyNaming(name, plugin.config.contracts.contractName);
		obj.prop(propName, contractSymbol);
	}
	for (const child of node.children.values()) if (child.shell) {
		const childSymbol = child.shell.define(child).node.symbol;
		if (childSymbol) {
			const propName = applyNaming(child.name, plugin.config.contracts.segmentName);
			obj.prop(propName, childSymbol);
		}
	}
	return obj;
}
function createShell(plugin) {
	const cache = /* @__PURE__ */ new Map();
	return { define: (node) => {
		const resourceId = node.getPath().join(".");
		const cached = cache.get(resourceId);
		if (cached) return {
			dependencies: [],
			node: cached
		};
		const symbol = plugin.symbol(applyNaming(node.name, node.isRoot ? plugin.config.contracts.containerName : plugin.config.contracts.segmentName), { meta: createShellMeta(node) });
		const o = $.const(symbol).export().assign($.object());
		cache.set(resourceId, o);
		return {
			dependencies: [],
			node: o
		};
	} };
}
function toNode$1(model, plugin) {
	if (model.virtual) {
		const nodes = [];
		const symbols = /* @__PURE__ */ new Map();
		for (const item of model.itemsFrom(source)) {
			const { operation } = item.data;
			const contractSymbol = createContractSymbol(plugin, item);
			const expression = createContractExpression(plugin, operation);
			const node = $.const(contractSymbol).export().$if(createOperationComment(operation), (n, v) => n.doc(v)).assign(expression);
			nodes.push(node);
			symbols.set(operation.id, contractSymbol);
		}
		return {
			nodes,
			symbols
		};
	}
	if (!model.shell) return { nodes: [] };
	const nodes = [];
	const symbols = /* @__PURE__ */ new Map();
	for (const item of model.itemsFrom(source)) {
		const { operation } = item.data;
		const contractSymbol = createContractSymbol(plugin, item);
		const expression = createContractExpression(plugin, operation);
		const node = $.const(contractSymbol).export().$if(createOperationComment(operation), (n, v) => n.doc(v)).assign(expression);
		nodes.push(node);
		symbols.set(operation.id, contractSymbol);
	}
	const containerSymbol = model.shell.define(model).node.symbol;
	const obj = buildContainerObject(model, plugin, symbols);
	const containerNode = $.const(containerSymbol).export().assign(obj.pretty());
	nodes.push(containerNode);
	return {
		nodes,
		symbols
	};
}
//#endregion
//#region src/plugins/orpc/contracts/resolve.ts
function resolvePath(plugin) {
	if (plugin.config.contracts.nesting === "id") return OperationPath.id();
	if (plugin.config.contracts.nesting === "operationId") return OperationPath.fromOperationId({
		delimiters: plugin.config.contracts.nestingDelimiters,
		fallback: OperationPath.id()
	});
	return plugin.config.contracts.nesting;
}
function resolveStrategy(plugin) {
	if (plugin.config.contracts.strategy === "flat") return OperationStrategy.flat({ path: (operation) => [resolvePath(plugin)(operation).join(".")] });
	if (plugin.config.contracts.strategy === "single") {
		const root = plugin.config.contracts.containerName;
		return OperationStrategy.single({
			path: resolvePath(plugin),
			root: typeof root.name === "string" ? root.name : root.name?.("") ?? ""
		});
	}
	if (plugin.config.contracts.strategy === "byTags") return OperationStrategy.byTags({
		fallback: plugin.config.contracts.strategyDefaultTag,
		path: resolvePath(plugin)
	});
	return plugin.config.contracts.strategy;
}
//#endregion
//#region src/plugins/orpc/v1/plugin.ts
const handlerV1$1 = ({ plugin }) => {
	plugin.symbol("oc", { external: "@orpc/contract" });
	const structure = new StructureModel();
	const shell = createShell(plugin);
	const strategy = resolveStrategy(plugin);
	plugin.forEach("operation", (event) => {
		structure.insert({
			data: {
				operation: event.operation,
				path: event._path,
				tags: event.tags
			},
			locations: strategy(event.operation).map((path) => ({
				path,
				shell
			})),
			source
		});
	}, { order: "declarations" });
	const allNodes = [];
	for (const node of structure.walk()) {
		const { nodes } = toNode$1(node, plugin);
		allNodes.push(...nodes);
	}
	for (const node of allNodes) plugin.node(node);
};
//#endregion
//#region src/plugins/orpc/plugin.ts
const handler$3 = (args) => handlerV1$1(args);
//#endregion
//#region src/plugins/orpc/config.ts
const validatorInferWarn = "You set `validator: true` but no validator plugin was found in your plugins. Add a validator plugin like `zod` to enable this feature. The validator option has been disabled.";
const defaultConfig$3 = {
	config: { includeInEntry: false },
	handler: handler$3,
	name: "orpc",
	resolveConfig: (plugin, context) => {
		if (typeof plugin.config.validator !== "object") plugin.config.validator = {
			input: plugin.config.validator,
			output: plugin.config.validator
		};
		if (plugin.config.validator.input || plugin.config.validator.input === void 0) if (typeof plugin.config.validator.input === "boolean" || plugin.config.validator.input === void 0) try {
			plugin.config.validator.input = context.pluginByTag("validator");
			plugin.dependencies.add(plugin.config.validator.input);
		} catch {
			if (plugin.config.validator.input !== void 0) log.warn(validatorInferWarn);
			plugin.config.validator.input = false;
		}
		else plugin.dependencies.add(plugin.config.validator.input);
		else plugin.config.validator.input = false;
		if (plugin.config.validator.output || plugin.config.validator.output === void 0) if (typeof plugin.config.validator.output === "boolean" || plugin.config.validator.output === void 0) try {
			plugin.config.validator.output = context.pluginByTag("validator");
			plugin.dependencies.add(plugin.config.validator.output);
		} catch {
			if (plugin.config.validator.output !== void 0) log.warn(validatorInferWarn);
			plugin.config.validator.output = false;
		}
		else plugin.dependencies.add(plugin.config.validator.output);
		else plugin.config.validator.output = false;
		plugin.config.contracts = resolveContracts(plugin.config, context);
	}
};
definePluginConfig(defaultConfig$3);
//#endregion
//#region src/plugins/swr/v2/useSwr.ts
const createUseSwr = ({ operation, plugin }) => {
	if (hasOperationSse({ operation })) return;
	const symbolUseSwr = plugin.external("swr.useSWR");
	const symbolUseQueryFn = plugin.symbol(applyNaming(operation.id, plugin.config.useSwr));
	const awaitSdkFn = $.lazy((ctx) => ctx.access(plugin.referenceSymbol({
		category: "sdk",
		resource: "operation",
		resourceId: operation.id
	})).call($.object().prop("throwOnError", $.literal(true))).await());
	const statements = [];
	if (plugin.getPluginOrThrow("@hey-api/sdk").config.responseStyle === "data") statements.push($.return(awaitSdkFn));
	else statements.push($.const().object("data").assign(awaitSdkFn), $.return("data"));
	const statement = $.const(symbolUseQueryFn).export().$if(plugin.config.comments && createOperationComment(operation), (c, v) => c.doc(v)).assign($.func().do($(symbolUseSwr).call($.literal(operation.path), $.func().async().do(...statements)).return()));
	plugin.node(statement);
};
//#endregion
//#region src/plugins/swr/v2/plugin.ts
const handlerV2 = ({ plugin }) => {
	plugin.symbol("useSWR", {
		external: "swr",
		importKind: "default",
		kind: "function"
	});
	plugin.forEach("operation", ({ operation }) => {
		if (plugin.hooks.operation.isQuery(operation)) {
			if (plugin.config.useSwr.enabled) createUseSwr({
				operation,
				plugin
			});
		}
	}, { order: "declarations" });
};
//#endregion
//#region src/plugins/swr/plugin.ts
const handler$2 = (args) => handlerV2(args);
//#endregion
//#region src/plugins/swr/config.ts
const defaultConfig$2 = {
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false
	},
	dependencies: ["@hey-api/sdk", "@hey-api/typescript"],
	handler: handler$2,
	name: "swr",
	resolveConfig: (plugin, context) => {
		plugin.config.infiniteQueryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteQueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.infiniteQueryKeys
		});
		plugin.config.infiniteQueryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}InfiniteOptions"
			},
			mappers,
			value: plugin.config.infiniteQueryOptions
		});
		plugin.config.mutationOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}Mutation"
			},
			mappers,
			value: plugin.config.mutationOptions
		});
		plugin.config.queryKeys = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "{{name}}QueryKey",
				tags: false
			},
			mappers,
			value: plugin.config.queryKeys
		});
		plugin.config.queryOptions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				exported: true,
				name: "{{name}}Options"
			},
			mappers,
			value: plugin.config.queryOptions
		});
		plugin.config.useSwr = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "use{{name}}"
			},
			mappers: {
				boolean: (enabled) => ({ enabled }),
				function: (name) => ({
					enabled: true,
					name
				}),
				object: (fields) => ({
					enabled: true,
					...fields
				}),
				string: (name) => ({
					enabled: true,
					name
				})
			},
			value: plugin.config.useSwr
		});
		if (plugin.config.useSwr.enabled) {
			if (!plugin.config.queryOptions.enabled) {
				plugin.config.queryOptions.enabled = true;
				plugin.config.queryOptions.exported = false;
			}
		}
	}
};
definePluginConfig(defaultConfig$2);
//#endregion
//#region src/plugins/valibot/v1/constants.ts
const identifiers$1 = {
	actions: {
		args: "args",
		base64: "base64",
		bic: "bic",
		brand: "brand",
		bytes: "bytes",
		check: "check",
		checkItems: "checkItems",
		creditCard: "creditCard",
		cuid2: "cuid2",
		decimal: "decimal",
		description: "description",
		digits: "digits",
		email: "email",
		emoji: "emoji",
		empty: "empty",
		endsWith: "endsWith",
		entries: "entries",
		everyItem: "everyItem",
		excludes: "excludes",
		filterItems: "filterItems",
		findItem: "findItem",
		finite: "finite",
		flavor: "flavor",
		graphemes: "graphemes",
		gtValue: "gtValue",
		hash: "hash",
		hexColor: "hexColor",
		hexadecimal: "hexadecimal",
		imei: "imei",
		includes: "includes",
		integer: "integer",
		ip: "ip",
		ipv4: "ipv4",
		ipv6: "ipv6",
		isoDate: "isoDate",
		isoDateTime: "isoDateTime",
		isoTime: "isoTime",
		isoTimeSecond: "isoTimeSecond",
		isoTimestamp: "isoTimestamp",
		isoWeek: "isoWeek",
		length: "length",
		ltValue: "ltValue",
		mac: "mac",
		mac48: "mac48",
		mac64: "mac64",
		mapItems: "mapItems",
		maxBytes: "maxBytes",
		maxEntries: "maxEntries",
		maxGraphemes: "maxGraphemes",
		maxLength: "maxLength",
		maxSize: "maxSize",
		maxValue: "maxValue",
		maxWords: "maxWords",
		metadata: "metadata",
		mimeType: "mimeType",
		minBytes: "minBytes",
		minEntries: "minEntries",
		minGraphemes: "minGraphemes",
		minLength: "minLength",
		minSize: "minSize",
		minValue: "minValue",
		minWords: "minWords",
		multipleOf: "multipleOf",
		nanoid: "nanoid",
		nonEmpty: "nonEmpty",
		normalize: "normalize",
		notBytes: "notBytes",
		notEntries: "notEntries",
		notGraphemes: "notGraphemes",
		notLength: "notLength",
		notSize: "notSize",
		notValue: "notValue",
		notValues: "notValues",
		notWords: "notWords",
		octal: "octal",
		parseJson: "parseJson",
		partialCheck: "partialCheck",
		rawCheck: "rawCheck",
		rawTransform: "rawTransform",
		readonly: "readonly",
		reduceItems: "reduceItems",
		regex: "regex",
		returns: "returns",
		rfcEmail: "rfcEmail",
		safeInteger: "safeInteger",
		size: "size",
		slug: "slug",
		someItem: "someItem",
		sortItems: "sortItems",
		startsWith: "startsWith",
		stringifyJson: "stringifyJson",
		title: "title",
		toLowerCase: "toLowerCase",
		toMaxValue: "toMaxValue",
		toMinValue: "toMinValue",
		toUpperCase: "toUpperCase",
		transform: "transform",
		trim: "trim",
		trimEnd: "trimEnd",
		trimStart: "trimStart",
		ulid: "ulid",
		url: "url",
		uuid: "uuid",
		value: "value",
		values: "values",
		words: "words"
	},
	async: {
		argsAsync: "argsAsync",
		arrayAsync: "arrayAsync",
		awaitAsync: "awaitAsync",
		checkAsync: "checkAsync",
		checkItemsAsync: "checkItemsAsync",
		customAsync: "customAsync",
		exactOptionalAsync: "exactOptionalAsync",
		fallbackAsync: "fallbackAsync",
		forwardAsync: "forwardAsync",
		getDefaultsAsync: "getDefaultsAsync",
		getFallbacksAsync: "getFallbacksAsync",
		intersectAsync: "intersectAsync",
		lazyAsync: "lazyAsync",
		looseObjectAsync: "looseObjectAsync",
		looseTupleAsync: "looseTupleAsync",
		mapAsync: "mapAsync",
		nonNullableAsync: "nonNullableAsync",
		nonNullishAsync: "nonNullishAsync",
		nonOptionalAsync: "nonOptionalAsync",
		nullableAsync: "nullableAsync",
		nullishAsync: "nullishAsync",
		objectAsync: "objectAsync",
		objectWithRestAsync: "objectWithRestAsync",
		optionalAsync: "optionalAsync",
		parseAsync: "parseAsync",
		parserAsync: "parserAsync",
		partialAsync: "partialAsync",
		partialCheckAsync: "partialCheckAsync",
		pipeAsync: "pipeAsync",
		rawCheckAsync: "rawCheckAsync",
		rawTransformAsync: "rawTransformAsync",
		recordAsync: "recordAsync",
		requiredAsync: "requiredAsync",
		returnsAsync: "returnsAsync",
		safeParseAsync: "safeParseAsync",
		safeParserAsync: "safeParserAsync",
		setAsync: "setAsync",
		strictObjectAsync: "strictObjectAsync",
		strictTupleAsync: "strictTupleAsync",
		transformAsync: "transformAsync",
		tupleAsync: "tupleAsync",
		tupleWithRestAsync: "tupleWithRestAsync",
		undefinedableAsync: "undefinedableAsync",
		unionAsync: "unionAsync",
		variantAsync: "variantAsync"
	},
	methods: {
		assert: "assert",
		config: "config",
		fallback: "fallback",
		flatten: "flatten",
		forward: "forward",
		getDefault: "getDefault",
		getDefaults: "getDefaults",
		getDescription: "getDescription",
		getFallback: "getFallback",
		getFallbacks: "getFallbacks",
		getMetadata: "getMetadata",
		getTitle: "getTitle",
		is: "is",
		keyof: "keyof",
		message: "message",
		omit: "omit",
		parse: "parse",
		parser: "parser",
		partial: "partial",
		pick: "pick",
		pipe: "pipe",
		required: "required",
		safeParse: "safeParse",
		safeParser: "safeParser",
		summarize: "summarize",
		unwrap: "unwrap"
	},
	schemas: {
		any: "any",
		array: "array",
		bigInt: "bigint",
		blob: "blob",
		boolean: "boolean",
		custom: "custom",
		date: "date",
		enum: "enum",
		exactOptional: "exactOptional",
		file: "file",
		function: "function",
		instance: "instance",
		intersect: "intersect",
		lazy: "lazy",
		literal: "literal",
		looseObject: "looseObject",
		looseTuple: "looseTuple",
		map: "map",
		nan: "nan",
		never: "never",
		nonNullable: "nonNullable",
		nonNullish: "nonNullish",
		nonOptional: "nonOptional",
		null: "null",
		nullable: "nullable",
		nullish: "nullish",
		number: "number",
		object: "object",
		objectWithRest: "objectWithRest",
		optional: "optional",
		picklist: "picklist",
		promise: "promise",
		record: "record",
		set: "set",
		strictObject: "strictObject",
		strictTuple: "strictTuple",
		string: "string",
		symbol: "symbol",
		tuple: "tuple",
		tupleWithRest: "tupleWithRest",
		undefined: "undefined",
		undefinedable: "undefinedable",
		union: "union",
		unknown: "unknown",
		variant: "variant",
		void: "void"
	},
	storages: {},
	types: { GenericSchema: "GenericSchema" },
	utils: {}
};
//#endregion
//#region src/plugins/valibot/shared/pipes.ts
function push(target, result) {
	if (result === void 0) return target;
	if (result instanceof Array) target.push(...result);
	else target.push(result);
	return target;
}
function toNode(pipes, plugin) {
	if (!(pipes instanceof Array)) return pipes;
	if (!pipes.length) return $(plugin.external("valibot.v")).attr(identifiers$1.schemas.unknown).call();
	if (pipes.length === 1) return pipes[0];
	return $(plugin.external("valibot.v")).attr(identifiers$1.methods.pipe).call(...pipes);
}
/**
* Functions for working with pipes.
*/
const pipes = {
	push,
	toNode
};
/**
* Convenience function for converting pipes to a node.
*
* Re-exported for backward compatibility.
*/
function pipesToNode(pipes, plugin) {
	return toNode(pipes, plugin);
}
//#endregion
//#region src/plugins/valibot/shared/export.ts
function exportAst$1({ final, meta, naming, namingAnchor, path, plugin, schema, tags }) {
	const v = plugin.external("valibot.v");
	const name = pathToName(path, { anchor: namingAnchor });
	const symbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "schema",
			path,
			tags,
			tool: "valibot",
			...meta
		},
		name,
		naming,
		plugin,
		schema
	}));
	const statement = $.const(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)).$if(final.typeName, (c) => c.type($.type(v).attr(final.typeName))).assign(pipesToNode(final.pipes, plugin));
	plugin.node(statement);
	return symbol;
}
//#endregion
//#region src/plugins/valibot/shared/operation-schema.ts
function buildOperationSchema$1(operation) {
	const requiredProperties = /* @__PURE__ */ new Set();
	const schema = {
		properties: {
			body: { type: "never" },
			path: { type: "never" },
			query: { type: "never" }
		},
		type: "object"
	};
	if (operation.parameters) for (const location of [
		"header",
		"path",
		"query"
	]) {
		const params = operation.parameters[location];
		if (!params) continue;
		const properties = {};
		const required = [];
		const propKey = location === "header" ? "headers" : location;
		for (const key in params) {
			const parameter = params[key];
			properties[parameter.name] = parameter.schema;
			if (parameter.required) {
				required.push(parameter.name);
				requiredProperties.add(propKey);
			}
		}
		if (Object.keys(properties).length) schema.properties[propKey] = {
			properties,
			required,
			type: "object"
		};
	}
	if (operation.body) {
		schema.properties.body = operation.body.schema;
		if (operation.body.required) requiredProperties.add("body");
	}
	schema.required = [...requiredProperties];
	return {
		required: schema.required,
		schema
	};
}
//#endregion
//#region src/plugins/valibot/shared/validator.ts
function getDefaultRequestValidatorLayers$1(operation) {
	const { schema } = buildOperationSchema$1(operation);
	return {
		body: {
			as: "body",
			optional: !schema.required?.includes("body"),
			whenEmpty: "strict"
		},
		headers: {
			as: "headers",
			optional: !schema.required?.includes("headers"),
			whenEmpty: "omit"
		},
		path: {
			as: "path",
			optional: !schema.required?.includes("path"),
			whenEmpty: "strict"
		},
		query: {
			as: "query",
			optional: !schema.required?.includes("query"),
			whenEmpty: "strict"
		}
	};
}
//#endregion
//#region src/plugins/valibot/v1/api.ts
function emptyNode$3(ctx) {
	const { v } = ctx.symbols;
	if (ctx.layer.whenEmpty === "omit") throw new Error(`Cannot create empty schema for layer "${ctx.layer.as}" with whenEmpty: 'omit'`);
	if (ctx.layer.whenEmpty === "strict") return $(v).attr(identifiers$1.schemas.never).call();
	return $(v).attr(identifiers$1.schemas.object).call($.object());
}
function optionalNode$3(ctx) {
	if (!ctx.layer.optional) return ctx.schema;
	const v = ctx.symbols.v;
	return $(v).attr(identifiers$1.schemas.optional).call(ctx.schema);
}
function compositeNode$3(ctx) {
	const { v } = ctx.symbols;
	const obj = $.object();
	const defaultValues = getDefaultRequestValidatorLayers$1(ctx.operation);
	for (const key of requestValidatorLayers) {
		const layer = resolveValidatorLayer(ctx.layers, key, defaultValues);
		const layerSchema = ctx.plugin.querySymbol({
			category: "schema",
			resource: "operation",
			resourceId: ctx.operation.id,
			role: `request-${key}`,
			tool: "valibot"
		});
		if (layerSchema) {
			obj.prop(layer.as, ctx.nodes.optional({
				...ctx,
				layer,
				schema: $(layerSchema)
			}));
			continue;
		}
		if (layer.whenEmpty === "omit") continue;
		const empty = ctx.nodes.empty({
			...ctx,
			layer
		});
		obj.prop(layer.as, ctx.nodes.optional({
			...ctx,
			layer,
			schema: empty
		}));
	}
	if (obj.isEmpty) return;
	return $(v).attr(identifiers$1.schemas.object).call(obj);
}
function requestValidatorResolver$3(ctx) {
	const { schema, v } = ctx.symbols;
	return $(v).attr(identifiers$1.async.parseAsync).call(schema, "data").await().return();
}
function responseValidatorResolver$3(ctx) {
	const { schema, v } = ctx.symbols;
	return $(v).attr(identifiers$1.async.parseAsync).call(schema, "data").await().return();
}
function runRequestResolver$3(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.request, requestValidatorResolver$3];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function runResponseResolver$3(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.response, responseValidatorResolver$3];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function createRequestSchemaContext$3(ctx) {
	const { plugin } = ctx;
	const v = plugin.external("valibot.v");
	return {
		...ctx,
		$,
		nodes: {
			composite: compositeNode$3,
			empty: emptyNode$3,
			optional: optionalNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		symbols: {
			schema: $(""),
			v
		}
	};
}
function createRequestSchemaV1(ctx) {
	const { operation, plugin } = ctx;
	const baseCtx = createRequestSchemaContext$3(ctx);
	const schema = baseCtx.nodes.composite(baseCtx);
	if (!schema) return;
	if (!plugin.config.requests.shouldExtract({ operation })) return schema;
	return exportAst$1({
		final: { pipes: [schema] },
		meta: {
			resource: "operation",
			resourceId: operation.id,
			role: "data"
		},
		naming: plugin.config.requests,
		namingAnchor: operation.id,
		path: [],
		plugin,
		schema: {}
	});
}
function createRequestValidatorV1(ctx) {
	const symbolOrSchema = createRequestSchemaV1(ctx);
	if (!symbolOrSchema) return;
	const baseCtx = createRequestSchemaContext$3(ctx);
	return runRequestResolver$3({
		...baseCtx,
		symbols: {
			...baseCtx.symbols,
			schema: symbolOrSchema
		}
	});
}
function createResponseValidatorV1({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: "valibot"
	});
	if (!symbol) return;
	const v = plugin.external("valibot.v");
	return runResponseResolver$3({
		$,
		operation,
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		symbols: {
			schema: symbol,
			v
		}
	});
}
//#endregion
//#region src/plugins/valibot/api.ts
var Api$1 = class {
	createRequestSchema(ctx) {
		const { plugin } = ctx;
		if (!plugin.config.requests.enabled) return;
		return createRequestSchemaV1(ctx);
	}
	createRequestValidator(args) {
		const { plugin } = args;
		if (!plugin.config.requests.enabled) return;
		return createRequestValidatorV1(args);
	}
	createResponseValidator(args) {
		return createResponseValidatorV1(args);
	}
};
//#endregion
//#region src/plugins/valibot/shared/operation.ts
function irOperationToAst$1({ operation, path, plugin, processor, tags }) {
	if (plugin.config.requests.enabled) {
		const { schema } = buildOperationSchema$1(operation);
		if (schema.properties?.body && schema.properties.body.type !== "never") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-body"
			},
			naming: plugin.config.requests.body,
			namingAnchor: operation.id,
			path: [...path, "body"],
			plugin,
			schema: schema.properties.body,
			tags
		});
		if (schema.properties?.headers && schema.properties.headers.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-headers"
			},
			naming: plugin.config.requests.headers,
			namingAnchor: operation.id,
			path: [...path, "headers"],
			plugin,
			schema: schema.properties.headers,
			tags
		});
		if (schema.properties?.path && schema.properties.path.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-path"
			},
			naming: plugin.config.requests.path,
			namingAnchor: operation.id,
			path: [...path, "path"],
			plugin,
			schema: schema.properties.path,
			tags
		});
		if (schema.properties?.query && schema.properties.query.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-query"
			},
			naming: plugin.config.requests.query,
			namingAnchor: operation.id,
			path: [...path, "query"],
			plugin,
			schema: schema.properties.query,
			tags
		});
	}
	if (plugin.config.responses.enabled) {
		if (operation.responses) {
			const { response } = operationResponsesMap(operation);
			if (response) processor.process({
				meta: {
					resource: "operation",
					resourceId: operation.id,
					role: "responses"
				},
				naming: plugin.config.responses,
				namingAnchor: operation.id,
				path: [...path, "responses"],
				plugin,
				schema: response,
				tags
			});
		}
	}
}
//#endregion
//#region src/plugins/valibot/shared/webhook.ts
function irWebhookToAst$1({ operation, path, plugin, processor, tags }) {
	if (plugin.config.webhooks.enabled) {
		const { schema } = buildOperationSchema$1(operation);
		processor.process({
			meta: {
				resource: "webhook",
				resourceId: operation.id,
				role: "data"
			},
			naming: plugin.config.webhooks,
			namingAnchor: operation.id,
			path,
			plugin,
			schema,
			tags
		});
	}
}
//#endregion
//#region src/plugins/shared/utils/coerce.ts
const shouldCoerceToBigInt = (format) => format === "int64" || format === "uint64";
const maybeBigInt = (value, format) => {
	if (!shouldCoerceToBigInt(format)) return $.fromValue(value);
	if (typeof value === "string") {
		if (value.endsWith("n")) value = value.slice(0, -1);
		return $("BigInt").call($.fromValue(value));
	}
	if (typeof value === "number") return $("BigInt").call($.fromValue(value));
	return $.fromValue(value);
};
//#endregion
//#region src/plugins/valibot/shared/meta.ts
/**
* Creates default metadata from a schema.
*/
function defaultMeta$1(schema) {
	return {
		default: schema.default,
		format: schema.format,
		hasLazy: false,
		nullable: false,
		readonly: schema.accessScope === "read"
	};
}
/**
* Composes metadata from child results.
*
* @param children - Results from walking child schemas
* @param overrides - Explicit overrides (e.g., from parent schema)
*/
function composeMeta$1(children, overrides) {
	return {
		default: overrides?.default,
		format: overrides?.format,
		hasLazy: overrides?.hasLazy ?? children.some((c) => c.meta.hasLazy),
		nullable: overrides?.nullable ?? children.some((c) => c.meta.nullable),
		readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly)
	};
}
/**
* Merges parent schema metadata with composed child metadata.
*
* @param parent - The parent schema
* @param children - Results from walking child schemas
*/
function inheritMeta$1(parent, children) {
	return composeMeta$1(children, {
		default: parent.default,
		format: parent.format,
		nullable: false,
		readonly: parent.accessScope === "read"
	});
}
//#endregion
//#region src/plugins/valibot/v1/toAst/unknown.ts
function baseNode$55(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.unknown).call();
}
function unknownResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function unknownToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$55 },
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema: schema ?? { type: "unknown" },
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.unknown;
	const node = resolver?.(ctx) ?? unknownResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/toAst/array.ts
function baseNode$54(ctx) {
	const { plugin, symbols } = ctx;
	const { v } = symbols;
	const arrayFn = $(v).attr(identifiers$1.schemas.array);
	let { schema: normalizedSchema } = ctx;
	if (normalizedSchema.items) normalizedSchema = deduplicateSchema({ schema: normalizedSchema });
	if (!normalizedSchema.items) return arrayFn.call(unknownToPipes({ plugin }));
	const childResults = [];
	const { applyModifiers, pipes, walk, walkerCtx } = ctx;
	for (let i = 0; i < normalizedSchema.items.length; i++) {
		const item = normalizedSchema.items[i];
		const result = walk(item, childContext(walkerCtx, "items", i));
		childResults.push(result);
	}
	if (childResults.length === 1) {
		const itemNode = pipes.toNode(applyModifiers(childResults[0]).pipes, plugin);
		return arrayFn.call(itemNode);
	}
	return arrayFn.call(unknownToPipes({ plugin }));
}
function lengthNode$7(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.minItems === schema.maxItems && schema.minItems !== void 0) return $(v).attr(identifiers$1.actions.length).call($.fromValue(schema.minItems));
}
function maxLengthNode$7(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.maxItems === void 0) return;
	return $(v).attr(identifiers$1.actions.maxLength).call($.fromValue(schema.maxItems));
}
function minLengthNode$7(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.minItems === void 0) return;
	return $(v).attr(identifiers$1.actions.minLength).call($.fromValue(schema.minItems));
}
function arrayResolver$3(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	if (baseResult) ctx.pipes.push(ctx.pipes.current, baseResult);
	const lengthResult = ctx.nodes.length(ctx);
	if (lengthResult) ctx.pipes.push(ctx.pipes.current, lengthResult);
	else {
		const minLengthResult = ctx.nodes.minLength(ctx);
		if (minLengthResult) ctx.pipes.push(ctx.pipes.current, minLengthResult);
		const maxLengthResult = ctx.nodes.maxLength(ctx);
		if (maxLengthResult) ctx.pipes.push(ctx.pipes.current, maxLengthResult);
	}
	return ctx.pipes.current;
}
function arrayToPipes(ctx) {
	const { plugin, schema, walk, walkerCtx } = ctx;
	const childResults = [];
	if (schema.items) {
		const normalizedSchema = deduplicateSchema({ schema });
		for (let i = 0; i < normalizedSchema.items.length; i++) {
			const item = normalizedSchema.items[i];
			const result = walk(item, childContext(walkerCtx, "items", i));
			childResults.push(result);
		}
	}
	const resolverCtx = {
		$,
		applyModifiers: ctx.applyModifiers,
		nodes: {
			base: baseNode$54,
			length: lengthNode$7,
			maxLength: maxLengthNode$7,
			minLength: minLengthNode$7
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.array;
	const node = resolver?.(resolverCtx) ?? arrayResolver$3(resolverCtx);
	return {
		childResults,
		pipes: [resolverCtx.pipes.toNode(node, plugin)]
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/boolean.ts
function baseNode$53(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.boolean).call();
}
function constNode$15(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (typeof schema.const !== "boolean") return;
	return $(v).attr(identifiers$1.schemas.literal).call($.literal(schema.const));
}
function booleanResolver$3(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return ctx.pipes.push(ctx.pipes.current, constResult);
	const baseResult = ctx.nodes.base(ctx);
	if (baseResult) ctx.pipes.push(ctx.pipes.current, baseResult);
	return ctx.pipes.current;
}
function booleanToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$53,
			const: constNode$15
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.boolean;
	const node = resolver?.(ctx) ?? booleanResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/toAst/enum.ts
function itemsNode$3(ctx) {
	const { schema } = ctx;
	const enumMembers = [];
	let isNullable = false;
	for (const item of schema.items ?? []) if (item.type === "string" && typeof item.const === "string") enumMembers.push($.literal(item.const));
	else if (item.type === "null" || item.const === null) isNullable = true;
	return {
		enumMembers,
		isNullable
	};
}
function baseNode$52(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	const { enumMembers } = ctx.nodes.items(ctx);
	return $(v).attr(identifiers$1.schemas.picklist).call($.array(...enumMembers));
}
function enumResolver$3(ctx) {
	const { enumMembers } = ctx.nodes.items(ctx);
	if (!enumMembers.length) return ctx.pipes.current;
	const baseExpression = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, baseExpression);
	return ctx.pipes.current;
}
function enumToPipes({ plugin, schema }) {
	const v = plugin.external("valibot.v");
	const { enumMembers, isNullable } = itemsNode$3({
		$,
		nodes: {
			base: baseNode$52,
			items: itemsNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v }
	});
	if (!enumMembers.length) return {
		isNullable,
		pipe: unknownToPipes({ plugin })
	};
	const ctx = {
		$,
		nodes: {
			base: baseNode$52,
			items: itemsNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v }
	};
	const resolver = plugin.config["~resolvers"]?.enum;
	const node = resolver?.(ctx) ?? enumResolver$3(ctx);
	return {
		isNullable,
		pipe: ctx.pipes.toNode(node, plugin)
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/intersection.ts
function baseNode$51(ctx) {
	const { applyModifiers, childResults, plugin, symbols } = ctx;
	const { v } = symbols;
	if (!childResults.length) return $(v).attr(identifiers$1.schemas.any).call();
	if (childResults.length === 1) return applyModifiers(childResults[0]).pipes;
	const itemNodes = childResults.map((item) => pipesToNode(item.pipes, plugin));
	return $(v).attr(identifiers$1.schemas.intersect).call($.array(...itemNodes));
}
function intersectionResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	if (base) ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function intersectionToPipes(ctx) {
	const { applyModifiers, childResults, parentSchema, plugin } = ctx;
	const resolverCtx = {
		$,
		applyModifiers,
		childResults,
		nodes: { base: baseNode$51 },
		parentSchema,
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema: parentSchema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.intersection;
	const node = resolver?.(resolverCtx) ?? intersectionResolver$3(resolverCtx);
	return {
		childResults,
		pipes: [resolverCtx.pipes.toNode(node, plugin)]
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/never.ts
function baseNode$50(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.never).call();
}
function neverResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function neverToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$50 },
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.never;
	const node = resolver?.(ctx) ?? neverResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/toAst/null.ts
function baseNode$49(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.null).call();
}
function nullResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function nullToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$49 },
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.null;
	const node = resolver?.(ctx) ?? nullResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/shared/utils/formats.ts
const rangeErrors = (format, range) => ({
	maxError: `Invalid value: Expected ${format} to be <= ${range[1]}`,
	minError: `Invalid value: Expected ${format} to be >= ${range[0]}`
});
const integerRange = {
	int16: [-32768, 32767],
	int32: [-2147483648, 2147483647],
	int64: ["-9223372036854775808", "9223372036854775807"],
	int8: [-128, 127],
	uint16: [0, 65535],
	uint32: [0, 4294967295],
	uint64: ["0", "18446744073709551615"],
	uint8: [0, 255]
};
const getIntegerLimit = (format) => {
	if (!format) return;
	const range = integerRange[format];
	if (!range) return;
	const errors = rangeErrors(format, range);
	return {
		maxValue: range[1],
		minValue: range[0],
		...errors
	};
};
//#endregion
//#region src/plugins/valibot/v1/toAst/number.ts
function baseNode$48(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (ctx.utils.shouldCoerceToBigInt(schema.format)) return [$(v).attr(identifiers$1.schemas.union).call($.array($(v).attr(identifiers$1.schemas.number).call(), $(v).attr(identifiers$1.schemas.string).call(), $(v).attr(identifiers$1.schemas.bigInt).call())), $(v).attr(identifiers$1.actions.transform).call($.func().param("x").do($("BigInt").call("x").return()))];
	const result = [];
	result.push($(v).attr(identifiers$1.schemas.number).call());
	if (schema.type === "integer") result.push($(v).attr(identifiers$1.actions.integer).call());
	return result;
}
function constNode$14(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.const === void 0) return;
	return $(v).attr(identifiers$1.schemas.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format));
}
function maxNode$3(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.exclusiveMaximum !== void 0) return $(v).attr(identifiers$1.actions.ltValue).call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format));
	if (schema.maximum !== void 0) return $(v).attr(identifiers$1.actions.maxValue).call(ctx.utils.maybeBigInt(schema.maximum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return $(v).attr(identifiers$1.actions.maxValue).call(ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.literal(limit.maxError));
}
function minNode$3(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.exclusiveMinimum !== void 0) return $(v).attr(identifiers$1.actions.gtValue).call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format));
	if (schema.minimum !== void 0) return $(v).attr(identifiers$1.actions.minValue).call(ctx.utils.maybeBigInt(schema.minimum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return $(v).attr(identifiers$1.actions.minValue).call(ctx.utils.maybeBigInt(limit.minValue, schema.format), $.literal(limit.minError));
}
function numberResolver$3(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return ctx.pipes.push(ctx.pipes.current, constResult);
	const baseResult = ctx.nodes.base(ctx);
	if (baseResult) ctx.pipes.push(ctx.pipes.current, baseResult);
	const minResult = ctx.nodes.min(ctx);
	if (minResult) ctx.pipes.push(ctx.pipes.current, minResult);
	const maxResult = ctx.nodes.max(ctx);
	if (maxResult) ctx.pipes.push(ctx.pipes.current, maxResult);
	return ctx.pipes.current;
}
function numberToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: {
			base: baseNode$48,
			const: constNode$14,
			max: maxNode$3,
			min: minNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") },
		utils: {
			getIntegerLimit,
			maybeBigInt,
			shouldCoerceToBigInt
		}
	};
	const resolver = plugin.config["~resolvers"]?.number;
	const node = resolver?.(ctx) ?? numberResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/toAst/object.ts
function additionalPropertiesNode$3(ctx) {
	const { pipes, schema } = ctx;
	if (!schema.additionalProperties || !schema.additionalProperties.type) return;
	if (schema.additionalProperties.type === "never") return null;
	const additionalResult = ctx.walk(schema.additionalProperties, childContext(ctx.walkerCtx, "additionalProperties"));
	ctx._childResults.push(additionalResult);
	return pipes.toNode(additionalResult.pipes, ctx.plugin);
}
function baseNode$47(ctx) {
	const { v } = ctx.symbols;
	const additional = ctx.nodes.additionalProperties(ctx);
	const shape = ctx.nodes.shape(ctx);
	if (additional === null) return $(v).attr(identifiers$1.schemas.strictObject).call(shape);
	if (additional) {
		if (shape.isEmpty) return $(v).attr(identifiers$1.schemas.record).call($(v).attr(identifiers$1.schemas.string).call(), additional);
		return $(v).attr(identifiers$1.schemas.objectWithRest).call(shape, additional);
	}
	return $(v).attr(identifiers$1.schemas.object).call(shape);
}
function objectResolver$3(ctx) {
	return ctx.nodes.base(ctx);
}
function shapeNode$3(ctx) {
	const { pipes, schema } = ctx;
	const shape = $.object().pretty();
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isOptional = !schema.required?.includes(name);
		const propertyResult = ctx.walk(property, childContext(ctx.walkerCtx, "properties", name));
		ctx._childResults.push(propertyResult);
		const finalExpr = ctx.applyModifiers(propertyResult, { optional: isOptional });
		shape.prop(name, pipes.toNode(finalExpr.pipes, ctx.plugin));
	}
	return shape;
}
function objectToPipes(ctx) {
	const { applyModifiers, plugin, schema, walk, walkerCtx } = ctx;
	const childResults = [];
	const resolverCtx = {
		$,
		_childResults: childResults,
		applyModifiers,
		nodes: {
			additionalProperties: additionalPropertiesNode$3,
			base: baseNode$47,
			shape: shapeNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.object;
	const node = resolver?.(resolverCtx) ?? objectResolver$3(resolverCtx);
	return {
		childResults,
		pipes: [resolverCtx.pipes.toNode(node, plugin)]
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/string.ts
function baseNode$46(ctx) {
	const { v } = ctx.symbols;
	return $(v).attr(identifiers$1.schemas.string).call();
}
function constNode$13(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (typeof schema.const !== "string") return;
	return $(v).attr(identifiers$1.schemas.literal).call($.literal(schema.const));
}
function formatNode$3(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	switch (schema.format) {
		case "date": return $(v).attr(identifiers$1.actions.isoDate).call();
		case "date-time": return $(v).attr(identifiers$1.actions.isoTimestamp).call();
		case "email": return $(v).attr(identifiers$1.actions.email).call();
		case "ipv4":
		case "ipv6": return $(v).attr(identifiers$1.actions.ip).call();
		case "time": return $(v).attr(identifiers$1.actions.isoTimeSecond).call();
		case "uri": return $(v).attr(identifiers$1.actions.url).call();
		case "uuid": return $(v).attr(identifiers$1.actions.uuid).call();
	}
}
function lengthNode$6(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.minLength === void 0 || schema.minLength !== schema.maxLength) return;
	return $(v).attr(identifiers$1.actions.length).call($.literal(schema.minLength));
}
function maxLengthNode$6(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.maxLength === void 0) return;
	return $(v).attr(identifiers$1.actions.maxLength).call($.literal(schema.maxLength));
}
function minLengthNode$6(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (schema.minLength === void 0) return;
	return $(v).attr(identifiers$1.actions.minLength).call($.literal(schema.minLength));
}
function patternNode$3(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (!schema.pattern) return;
	const flags = /\\[pP]\{/.test(schema.pattern) ? "u" : void 0;
	return $(v).attr(identifiers$1.actions.regex).call($.regexp(schema.pattern, flags));
}
function stringResolver$3(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) return ctx.pipes.push(ctx.pipes.current, constNode);
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.pipes.push(ctx.pipes.current, baseNode);
	const formatNode = ctx.nodes.format(ctx);
	if (formatNode) ctx.pipes.push(ctx.pipes.current, formatNode);
	const lengthNode = ctx.nodes.length(ctx);
	if (lengthNode) ctx.pipes.push(ctx.pipes.current, lengthNode);
	else {
		const minLengthNode = ctx.nodes.minLength(ctx);
		if (minLengthNode) ctx.pipes.push(ctx.pipes.current, minLengthNode);
		const maxLengthNode = ctx.nodes.maxLength(ctx);
		if (maxLengthNode) ctx.pipes.push(ctx.pipes.current, maxLengthNode);
	}
	const patternNode = ctx.nodes.pattern(ctx);
	if (patternNode) ctx.pipes.push(ctx.pipes.current, patternNode);
	return ctx.pipes.current;
}
function stringToPipes({ plugin, schema }) {
	if (shouldCoerceToBigInt(schema.format)) return numberToPipes({
		plugin,
		schema: {
			...schema,
			type: "number"
		}
	});
	const ctx = {
		$,
		nodes: {
			base: baseNode$46,
			const: constNode$13,
			format: formatNode$3,
			length: lengthNode$6,
			maxLength: maxLengthNode$6,
			minLength: minLengthNode$6,
			pattern: patternNode$3
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.string;
	const node = resolver?.(ctx) ?? stringResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/toAst/tuple.ts
function baseNode$45(ctx) {
	const { applyModifiers, pipes, plugin, schema, symbols, walk, walkerCtx } = ctx;
	if (!schema.items) return unknownToPipes({ plugin });
	const { v } = symbols;
	const childResults = [];
	for (let i = 0; i < schema.items.length; i++) {
		const item = schema.items[i];
		const result = walk(item, childContext(walkerCtx, "items", i));
		childResults.push(result);
	}
	const tupleElements = childResults.map((r) => pipes.toNode(applyModifiers(r).pipes, plugin));
	return $(v).attr(identifiers$1.schemas.tuple).call($.array(...tupleElements));
}
function constNode$12(ctx) {
	const { schema, symbols } = ctx;
	const { v } = symbols;
	if (!schema.const || !Array.isArray(schema.const)) return;
	const tupleElements = schema.const.map((value) => $(v).attr(identifiers$1.schemas.literal).call($.fromValue(value)));
	return $(v).attr(identifiers$1.schemas.tuple).call($.array(...tupleElements));
}
function tupleResolver$3(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) return ctx.pipes.push(ctx.pipes.current, constResult);
	const baseResult = ctx.nodes.base(ctx);
	if (baseResult) ctx.pipes.push(ctx.pipes.current, baseResult);
	return ctx.pipes.current;
}
function tupleToPipes(ctx) {
	const { plugin, schema, walk, walkerCtx } = ctx;
	const childResults = [];
	if (schema.items) for (let i = 0; i < schema.items.length; i++) {
		const item = schema.items[i];
		const result = walk(item, childContext(walkerCtx, "items", i));
		childResults.push(result);
	}
	const resolverCtx = {
		$,
		applyModifiers: ctx.applyModifiers,
		nodes: {
			base: baseNode$45,
			const: constNode$12
		},
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.tuple;
	const node = resolver?.(resolverCtx) ?? tupleResolver$3(resolverCtx);
	return {
		childResults,
		pipes: [resolverCtx.pipes.toNode(node, plugin)]
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/undefined.ts
function baseNode$44(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.undefined).call();
}
function undefinedResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function undefinedToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$44 },
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.undefined;
	const node = resolver?.(ctx) ?? undefinedResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/shared/discriminated-union.ts
function hasIntersectionDiscriminatorBranches({ items, parentSchema, schemas }) {
	const discriminatorKey = parentSchema.discriminator?.propertyName;
	if (!discriminatorKey) return false;
	for (let index = 0; index < schemas.length; index++) {
		const schema = schemas[index];
		if (schema.type === "null" || schema.const === null) continue;
		if (schema.logicalOperator !== "and" || !schema.items || schema.items.length !== 2) continue;
		const item = items[index];
		const discriminatedValue = schema.items[0].properties?.[discriminatorKey]?.const;
		if (item.meta.hasLazy || discriminatedValue !== void 0) return true;
	}
	return false;
}
//#endregion
//#region src/plugins/valibot/v1/toAst/union.ts
function baseNode$43(ctx) {
	const { childResults, parentSchema, plugin, schemas, symbols } = ctx;
	const { v } = symbols;
	const nonNullItems = [];
	childResults.forEach((item, index) => {
		const schema = schemas[index];
		if (schema.type !== "null" && schema.const !== null) nonNullItems.push(item);
	});
	if (!nonNullItems.length) return $(v).attr(identifiers$1.schemas.null).call();
	if (nonNullItems.length === 1) return nonNullItems[0].pipes;
	const itemNodes = nonNullItems.map((i) => pipesToNode(i.pipes, plugin));
	const hasIntersectionBranch = hasIntersectionDiscriminatorBranches({
		items: childResults,
		parentSchema,
		schemas
	});
	const discriminatorKey = parentSchema.discriminator?.propertyName;
	if (discriminatorKey && !hasIntersectionBranch) return $(v).attr(identifiers$1.schemas.variant).call($.literal(discriminatorKey), $.array(...itemNodes));
	return $(v).attr(identifiers$1.schemas.union).call($.array(...itemNodes));
}
function unionResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	if (base) ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function unionToPipes(ctx) {
	const { applyModifiers, childResults, parentSchema, plugin, schemas } = ctx;
	const resolverCtx = {
		$,
		applyModifiers,
		childResults,
		nodes: { base: baseNode$43 },
		parentSchema,
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.union;
	const node = resolver?.(resolverCtx) ?? unionResolver$3(resolverCtx);
	return {
		childResults,
		pipes: [resolverCtx.pipes.toNode(node, plugin)]
	};
}
//#endregion
//#region src/plugins/valibot/v1/toAst/void.ts
function baseNode$42(ctx) {
	const { symbols } = ctx;
	const { v } = symbols;
	return $(v).attr(identifiers$1.schemas.void).call();
}
function voidResolver$3(ctx) {
	const base = ctx.nodes.base(ctx);
	ctx.pipes.push(ctx.pipes.current, base);
	return ctx.pipes.current;
}
function voidToPipes({ plugin, schema }) {
	const ctx = {
		$,
		nodes: { base: baseNode$42 },
		pipes: {
			...pipes,
			current: []
		},
		plugin,
		schema,
		symbols: { v: plugin.external("valibot.v") }
	};
	const resolver = plugin.config["~resolvers"]?.void;
	const node = resolver?.(ctx) ?? voidResolver$3(ctx);
	return ctx.pipes.toNode(node, plugin);
}
//#endregion
//#region src/plugins/valibot/v1/walker.ts
function getDefaultValue$3(meta) {
	return meta.format ? maybeBigInt(meta.default, meta.format) : $.fromValue(meta.default);
}
function createVisitor$3(config = {}) {
	const { schemaExtractor } = config;
	return {
		applyModifiers(result, ctx, options = {}) {
			const { optional } = options;
			const v = ctx.plugin.external("valibot.v");
			const pipes = [...result.pipes];
			if (result.meta.readonly) pipes.push($(v).attr(identifiers$1.actions.readonly).call());
			const needsDefault = result.meta.default !== void 0;
			const needsOptional = optional || needsDefault;
			const needsNullable = result.meta.nullable;
			const innerNode = pipesToNode(pipes, ctx.plugin);
			let finalPipes;
			if (needsOptional && needsNullable) if (needsDefault) finalPipes = [$(v).attr(identifiers$1.schemas.nullish).call(innerNode, getDefaultValue$3(result.meta))];
			else finalPipes = [$(v).attr(identifiers$1.schemas.nullish).call(innerNode)];
			else if (needsOptional) if (needsDefault) finalPipes = [$(v).attr(identifiers$1.schemas.optional).call(innerNode, getDefaultValue$3(result.meta))];
			else finalPipes = [$(v).attr(identifiers$1.schemas.optional).call(innerNode)];
			else if (needsNullable) finalPipes = [$(v).attr(identifiers$1.schemas.nullable).call(innerNode)];
			else finalPipes = pipes;
			return {
				pipes: finalPipes,
				typeName: result.meta.hasLazy ? identifiers$1.types.GenericSchema : void 0
			};
		},
		array(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, pipes } = arrayToPipes({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: inheritMeta$1(schema, childResults),
				pipes
			};
		},
		boolean(schema, ctx) {
			const pipe = booleanToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$1(schema),
				pipes: [pipe]
			};
		},
		enum(schema, ctx) {
			const { isNullable, pipe } = enumToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: isNullable
				},
				pipes: [pipe]
			};
		},
		integer(schema, ctx) {
			const pipe = numberToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$1(schema),
				pipes: [pipe]
			};
		},
		intercept(schema, ctx, walk) {
			if (schemaExtractor && !schema.$ref) {
				const extracted = schemaExtractor({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(fromRef(ctx.path))
					},
					naming: ctx.plugin.config.definitions,
					path: fromRef(ctx.path),
					plugin: ctx.plugin,
					schema
				});
				if (extracted !== schema) return walk(extracted, ctx);
			}
			if (schema.symbolRef) return {
				meta: defaultMeta$1(schema),
				pipes: [$(schema.symbolRef)]
			};
		},
		intersection(items, schemas, parentSchema, ctx) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { pipes } = intersectionToPipes({
				applyModifiers,
				childResults: items,
				parentSchema,
				plugin: ctx.plugin
			});
			return {
				meta: composeMeta$1(items, { default: parentSchema.default }),
				pipes
			};
		},
		never(schema, ctx) {
			const pipe = neverToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: false,
					readonly: false
				},
				pipes: [pipe]
			};
		},
		null(schema, ctx) {
			const pipe = nullToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: false,
					readonly: false
				},
				pipes: [pipe]
			};
		},
		number(schema, ctx) {
			const pipe = numberToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$1(schema),
				pipes: [pipe]
			};
		},
		object(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, pipes } = objectToPipes({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: inheritMeta$1(schema, childResults),
				pipes
			};
		},
		postProcess(result, schema, ctx) {
			const metadata = ctx.plugin.config.metadata;
			if (!metadata) return result;
			const node = $.object();
			if (typeof metadata === "function") metadata({
				$,
				node,
				schema
			});
			else if (schema.description) node.prop("description", $.literal(schema.description));
			if (node.isEmpty) return result;
			const metadataExpr = $(ctx.plugin.external("valibot.v")).attr(identifiers$1.actions.metadata).call(node);
			return {
				meta: result.meta,
				pipes: [...result.pipes, metadataExpr]
			};
		},
		reference($ref, schema, ctx) {
			const v = ctx.plugin.external("valibot.v");
			const query = {
				category: "schema",
				resource: "definition",
				resourceId: $ref,
				tool: "valibot"
			};
			const refSymbol = ctx.plugin.referenceSymbol(query);
			if (ctx.plugin.isSymbolRegistered(query)) return {
				meta: defaultMeta$1(schema),
				pipes: [$(refSymbol)]
			};
			return {
				meta: {
					...defaultMeta$1(schema),
					hasLazy: true
				},
				pipes: [$(v).attr(identifiers$1.schemas.lazy).call($.func().do($(refSymbol).return()))]
			};
		},
		string(schema, ctx) {
			const pipe = stringToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: defaultMeta$1(schema),
				pipes: [pipe]
			};
		},
		tuple(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, pipes } = tupleToPipes({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				meta: inheritMeta$1(schema, childResults),
				pipes
			};
		},
		undefined(schema, ctx) {
			const pipe = undefinedToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: false,
					readonly: false
				},
				pipes: [pipe]
			};
		},
		union(items, schemas, parentSchema, ctx) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const hasNull = schemas.some((s) => s.type === "null") || items.some((i) => i.meta.nullable);
			const { pipes } = unionToPipes({
				applyModifiers,
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				meta: composeMeta$1(items, {
					default: parentSchema.default,
					nullable: hasNull
				}),
				pipes
			};
		},
		unknown(schema, ctx) {
			const pipe = unknownToPipes({ plugin: ctx.plugin });
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: false,
					readonly: false
				},
				pipes: [pipe]
			};
		},
		void(schema, ctx) {
			const pipe = voidToPipes({
				plugin: ctx.plugin,
				schema
			});
			return {
				meta: {
					...defaultMeta$1(schema),
					nullable: false,
					readonly: false
				},
				pipes: [pipe]
			};
		}
	};
}
//#endregion
//#region src/plugins/valibot/v1/processor.ts
function createProcessor$3(plugin) {
	const processor = createSchemaProcessor();
	const extractorHooks = [plugin.config["~hooks"]?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract];
	function extractor(ctx) {
		if (processor.hasEmitted(ctx.path)) return ctx.schema;
		for (const hook of extractorHooks) if (typeof hook === "boolean" ? hook : hook?.(ctx) ?? false) {
			process({
				namingAnchor: processor.context.anchor,
				tags: processor.context.tags,
				...ctx
			});
			return { $ref: pathToJsonPointer(ctx.path) };
		}
		return ctx.schema;
	}
	function process(ctx) {
		if (!processor.markEmitted(ctx.path)) return;
		const shouldExport = ctx.export !== false;
		return processor.withContext({
			anchor: ctx.namingAnchor,
			tags: ctx.tags
		}, () => {
			const visitor = createVisitor$3({ schemaExtractor: extractor });
			const result = createSchemaWalker(visitor)(ctx.schema, {
				path: ref(ctx.path),
				plugin
			});
			const final = visitor.applyModifiers(result, {
				path: ref(ctx.path),
				plugin
			});
			if (shouldExport) {
				exportAst$1({
					...ctx,
					final,
					plugin
				});
				return;
			}
			return final;
		});
	}
	return { process };
}
//#endregion
//#region src/plugins/valibot/v1/plugin.ts
const handlerV1 = ({ plugin }) => {
	plugin.symbol("v", {
		external: "valibot",
		importKind: "namespace"
	});
	const processor = createProcessor$3(plugin);
	plugin.forEach("operation", "parameter", "requestBody", "schema", "webhook", (event) => {
		switch (event.type) {
			case "operation":
				irOperationToAst$1({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
			case "parameter":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.parameter.schema,
					tags: event.tags
				});
				break;
			case "requestBody":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.requestBody.schema,
					tags: event.tags
				});
				break;
			case "schema":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.schema,
					tags: event.tags
				});
				break;
			case "webhook":
				irWebhookToAst$1({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
		}
	});
};
//#endregion
//#region src/plugins/valibot/plugin.ts
const handler$1 = (args) => handlerV1(args);
//#endregion
//#region src/plugins/valibot/config.ts
const defaultConfig$1 = {
	api: new Api$1(),
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false,
		metadata: false
	},
	handler: handler$1,
	name: "valibot",
	resolveConfig: (plugin, context) => {
		plugin.config.definitions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "v{{name}}"
			},
			mappers,
			value: plugin.config.definitions
		});
		plugin.config.requests = context.valueToObject({
			defaultValue: {
				body: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "v{{name}}Body"
				},
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				headers: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "v{{name}}Headers"
				},
				name: "v{{name}}Data",
				path: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "v{{name}}Path"
				},
				query: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "v{{name}}Query"
				},
				shouldExtract: () => false
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					body: context.valueToObject({
						defaultValue: defaultValue.body,
						mappers,
						value: fields.body
					}),
					headers: context.valueToObject({
						defaultValue: defaultValue.headers,
						mappers,
						value: fields.headers
					}),
					path: context.valueToObject({
						defaultValue: defaultValue.path,
						mappers,
						value: fields.path
					}),
					query: context.valueToObject({
						defaultValue: defaultValue.query,
						mappers,
						value: fields.query
					}),
					shouldExtract: fields.shouldExtract !== void 0 ? typeof fields.shouldExtract === "function" ? fields.shouldExtract : () => Boolean(fields.shouldExtract) : defaultValue.shouldExtract
				})
			},
			value: plugin.config.requests
		});
		plugin.config.responses = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "v{{name}}Response"
			},
			mappers,
			value: plugin.config.responses
		});
		plugin.config.webhooks = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "v{{name}}WebhookRequest"
			},
			mappers,
			value: plugin.config.webhooks
		});
	},
	tags: ["validator"]
};
definePluginConfig(defaultConfig$1);
//#endregion
//#region src/plugins/zod/constants.ts
const identifiers = {
	AnyZodObject: "AnyZodObject",
	ZodMiniOptional: "ZodMiniOptional",
	ZodOptional: "ZodOptional",
	ZodTypeAny: "ZodTypeAny",
	_default: "_default",
	and: "and",
	array: "array",
	bigint: "bigint",
	boolean: "boolean",
	check: "check",
	coerce: "coerce",
	date: "date",
	datetime: "datetime",
	default: "default",
	describe: "describe",
	discriminatedUnion: "discriminatedUnion",
	email: "email",
	enum: "enum",
	extend: "extend",
	globalRegistry: "globalRegistry",
	gt: "gt",
	gte: "gte",
	guid: "guid",
	infer: "infer",
	input: "input",
	int: "int",
	intersection: "intersection",
	ip: "ip",
	ipv4: "ipv4",
	ipv6: "ipv6",
	iso: "iso",
	lazy: "lazy",
	length: "length",
	literal: "literal",
	lt: "lt",
	lte: "lte",
	max: "max",
	maxLength: "maxLength",
	maximum: "maximum",
	min: "min",
	minLength: "minLength",
	minimum: "minimum",
	never: "never",
	null: "null",
	nullable: "nullable",
	nullish: "nullish",
	number: "number",
	object: "object",
	optional: "optional",
	output: "output",
	parseAsync: "parseAsync",
	readonly: "readonly",
	record: "record",
	regex: "regex",
	register: "register",
	string: "string",
	time: "time",
	tuple: "tuple",
	undefined: "undefined",
	union: "union",
	unknown: "unknown",
	url: "url",
	uuid: "uuid",
	void: "void"
};
//#endregion
//#region src/plugins/zod/shared/export.ts
function exportAst({ final, meta, naming, namingAnchor, path, plugin, schema, tags }) {
	const z = plugin.external("zod.z");
	const name = pathToName(path, { anchor: namingAnchor });
	const symbol = plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "schema",
			path,
			tags,
			tool: "zod",
			...meta
		},
		name,
		naming,
		plugin,
		schema
	}));
	const statement = $.const(symbol).export().$if(plugin.config.comments && createSchemaComment(schema), (c, v) => c.doc(v)).$if(final.typeName, (c) => c.type($.type(z).attr(final.typeName))).assign(final.expression);
	plugin.node(statement);
	const typeInferSymbol = naming.types.infer.enabled ? plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			tags,
			tool: "zod",
			variant: "infer",
			...meta
		},
		name,
		naming: naming.types.infer,
		plugin,
		schema
	})) : void 0;
	if (typeInferSymbol) {
		const inferType = $.type.alias(typeInferSymbol).export().type($.type(z).attr(identifiers.infer).generic($(symbol).typeofType()));
		plugin.node(inferType);
	}
	const typeInputSymbol = naming.types.input.enabled ? plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			tags,
			tool: "zod",
			variant: "input",
			...meta
		},
		name,
		naming: naming.types.input,
		plugin,
		schema
	})) : void 0;
	if (typeInputSymbol) {
		const inputType = $.type.alias(typeInputSymbol).export().type($.type(z).attr(identifiers.input).generic($(symbol).typeofType()));
		plugin.node(inputType);
	}
	const typeOutputSymbol = naming.types.output.enabled ? plugin.registerSymbol(buildSymbolIn({
		meta: {
			category: "type",
			path,
			tags,
			tool: "zod",
			variant: "output",
			...meta
		},
		name,
		naming: naming.types.output,
		plugin,
		schema
	})) : void 0;
	if (typeOutputSymbol) {
		const outputType = $.type.alias(typeOutputSymbol).export().type($.type(z).attr(identifiers.output).generic($(symbol).typeofType()));
		plugin.node(outputType);
	}
	return symbol;
}
//#endregion
//#region src/plugins/zod/shared/operation-schema.ts
function buildOperationSchema(operation) {
	const requiredProperties = /* @__PURE__ */ new Set();
	const schema = {
		properties: {
			body: { type: "never" },
			path: { type: "never" },
			query: { type: "never" }
		},
		type: "object"
	};
	if (operation.parameters) for (const location of [
		"header",
		"path",
		"query"
	]) {
		const params = operation.parameters[location];
		if (!params) continue;
		const properties = {};
		const required = [];
		const propKey = location === "header" ? "headers" : location;
		for (const key in params) {
			const parameter = params[key];
			properties[parameter.name] = parameter.schema;
			if (parameter.required) {
				required.push(parameter.name);
				requiredProperties.add(propKey);
			}
		}
		if (Object.keys(properties).length) schema.properties[propKey] = {
			properties,
			required,
			type: "object"
		};
	}
	if (operation.body) {
		schema.properties.body = operation.body.schema;
		if (operation.body.required) requiredProperties.add("body");
	}
	schema.required = [...requiredProperties];
	return {
		required: schema.required,
		schema
	};
}
//#endregion
//#region src/plugins/zod/shared/validator.ts
function getDefaultRequestValidatorLayers(operation) {
	const { schema } = buildOperationSchema(operation);
	return {
		body: {
			as: "body",
			optional: !schema.required?.includes("body"),
			whenEmpty: "strict"
		},
		headers: {
			as: "headers",
			optional: !schema.required?.includes("headers"),
			whenEmpty: "omit"
		},
		path: {
			as: "path",
			optional: !schema.required?.includes("path"),
			whenEmpty: "strict"
		},
		query: {
			as: "query",
			optional: !schema.required?.includes("query"),
			whenEmpty: "strict"
		}
	};
}
//#endregion
//#region src/plugins/zod/mini/api.ts
function emptyNode$2(ctx) {
	const { z } = ctx.symbols;
	if (ctx.layer.whenEmpty === "omit") throw new Error(`Cannot create empty schema for layer "${ctx.layer.as}" with whenEmpty: 'omit'`);
	if (ctx.layer.whenEmpty === "strict") return $(z).attr(identifiers.never).call();
	return $(z).attr(identifiers.object).call($.object());
}
function optionalNode$2(ctx) {
	if (!ctx.layer.optional) return ctx.schema;
	const { z } = ctx.symbols;
	return $(z).attr(identifiers.optional).call(ctx.schema);
}
function compositeNode$2(ctx) {
	const { z } = ctx.symbols;
	const obj = $.object();
	const defaultValues = getDefaultRequestValidatorLayers(ctx.operation);
	for (const key of requestValidatorLayers) {
		const layer = resolveValidatorLayer(ctx.layers, key, defaultValues);
		const layerSchema = ctx.plugin.querySymbol({
			category: "schema",
			resource: "operation",
			resourceId: ctx.operation.id,
			role: `request-${key}`,
			tool: "zod"
		});
		if (layerSchema) {
			obj.prop(layer.as, ctx.nodes.optional({
				...ctx,
				layer,
				schema: $(layerSchema)
			}));
			continue;
		}
		if (layer.whenEmpty === "omit") continue;
		const empty = ctx.nodes.empty({
			...ctx,
			layer
		});
		obj.prop(layer.as, ctx.nodes.optional({
			...ctx,
			layer,
			schema: empty
		}));
	}
	if (obj.isEmpty) return;
	return $(z).attr(identifiers.object).call(obj);
}
function requestValidatorResolver$2(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function responseValidatorResolver$2(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function runRequestResolver$2(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.request, requestValidatorResolver$2];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function runResponseResolver$2(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.response, responseValidatorResolver$2];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function createRequestSchemaContext$2(ctx) {
	const { plugin } = ctx;
	const z = plugin.external("zod.z");
	return {
		...ctx,
		$,
		chain: { current: $(z) },
		nodes: {
			composite: compositeNode$2,
			empty: emptyNode$2,
			optional: optionalNode$2
		},
		symbols: {
			schema: $(""),
			z
		}
	};
}
function createRequestSchemaMini(ctx) {
	const { operation, plugin } = ctx;
	const baseCtx = createRequestSchemaContext$2(ctx);
	const schema = baseCtx.nodes.composite(baseCtx);
	if (!schema) return;
	if (!plugin.config.requests.shouldExtract({ operation })) return schema;
	return exportAst({
		final: { expression: schema },
		meta: {
			resource: "operation",
			resourceId: operation.id,
			role: "data"
		},
		naming: plugin.config.requests,
		namingAnchor: operation.id,
		path: [],
		plugin,
		schema: {}
	});
}
function createRequestValidatorMini(ctx) {
	const symbolOrSchema = createRequestSchemaMini(ctx);
	if (!symbolOrSchema) return;
	const baseCtx = createRequestSchemaContext$2(ctx);
	return runRequestResolver$2({
		...baseCtx,
		symbols: {
			...baseCtx.symbols,
			schema: symbolOrSchema
		}
	});
}
function createResponseValidatorMini({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: "zod"
	});
	if (!symbol) return;
	const z = plugin.external("zod.z");
	return runResponseResolver$2({
		$,
		chain: { current: $(z) },
		operation,
		plugin,
		symbols: {
			schema: symbol,
			z
		}
	});
}
//#endregion
//#region src/plugins/zod/v3/api.ts
function emptyNode$1(ctx) {
	const { z } = ctx.symbols;
	if (ctx.layer.whenEmpty === "omit") throw new Error(`Cannot create empty schema for layer "${ctx.layer.as}" with whenEmpty: 'omit'`);
	if (ctx.layer.whenEmpty === "strict") return $(z).attr(identifiers.never).call();
	return $(z).attr(identifiers.object).call($.object());
}
function optionalNode$1(ctx) {
	if (!ctx.layer.optional) return ctx.schema;
	return $(ctx.schema).attr(identifiers.optional).call();
}
function compositeNode$1(ctx) {
	const { z } = ctx.symbols;
	const obj = $.object();
	const defaultValues = getDefaultRequestValidatorLayers(ctx.operation);
	for (const key of requestValidatorLayers) {
		const layer = resolveValidatorLayer(ctx.layers, key, defaultValues);
		const layerSchema = ctx.plugin.querySymbol({
			category: "schema",
			resource: "operation",
			resourceId: ctx.operation.id,
			role: `request-${key}`,
			tool: "zod"
		});
		if (layerSchema) {
			obj.prop(layer.as, ctx.nodes.optional({
				...ctx,
				layer,
				schema: $(layerSchema)
			}));
			continue;
		}
		if (layer.whenEmpty === "omit") continue;
		const empty = ctx.nodes.empty({
			...ctx,
			layer
		});
		obj.prop(layer.as, ctx.nodes.optional({
			...ctx,
			layer,
			schema: empty
		}));
	}
	if (obj.isEmpty) return;
	return $(z).attr(identifiers.object).call(obj);
}
function requestValidatorResolver$1(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function responseValidatorResolver$1(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function runRequestResolver$1(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.request, requestValidatorResolver$1];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function runResponseResolver$1(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.response, responseValidatorResolver$1];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function createRequestSchemaContext$1(ctx) {
	const { plugin } = ctx;
	const z = plugin.external("zod.z");
	return {
		...ctx,
		$,
		chain: { current: $(z) },
		nodes: {
			composite: compositeNode$1,
			empty: emptyNode$1,
			optional: optionalNode$1
		},
		symbols: {
			schema: $(""),
			z
		}
	};
}
function createRequestSchemaV3(ctx) {
	const { operation, plugin } = ctx;
	const baseCtx = createRequestSchemaContext$1(ctx);
	const schema = baseCtx.nodes.composite(baseCtx);
	if (!schema) return;
	if (!plugin.config.requests.shouldExtract({ operation })) return schema;
	return exportAst({
		final: { expression: schema },
		meta: {
			resource: "operation",
			resourceId: operation.id,
			role: "data"
		},
		naming: plugin.config.requests,
		namingAnchor: operation.id,
		path: [],
		plugin,
		schema: {}
	});
}
function createRequestValidatorV3(ctx) {
	const symbolOrSchema = createRequestSchemaV3(ctx);
	if (!symbolOrSchema) return;
	const baseCtx = createRequestSchemaContext$1(ctx);
	return runRequestResolver$1({
		...baseCtx,
		symbols: {
			...baseCtx.symbols,
			schema: symbolOrSchema
		}
	});
}
function createResponseValidatorV3({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: "zod"
	});
	if (!symbol) return;
	const z = plugin.external("zod.z");
	return runResponseResolver$1({
		$,
		chain: { current: $(z) },
		operation,
		plugin,
		symbols: {
			schema: symbol,
			z
		}
	});
}
//#endregion
//#region src/plugins/zod/v4/api.ts
function emptyNode(ctx) {
	const { z } = ctx.symbols;
	if (ctx.layer.whenEmpty === "omit") throw new Error(`Cannot create empty schema for layer "${ctx.layer.as}" with whenEmpty: 'omit'`);
	if (ctx.layer.whenEmpty === "strict") return $(z).attr(identifiers.never).call();
	return $(z).attr(identifiers.object).call($.object());
}
function optionalNode(ctx) {
	if (!ctx.layer.optional) return ctx.schema;
	return $(ctx.schema).attr(identifiers.optional).call();
}
function compositeNode(ctx) {
	const { z } = ctx.symbols;
	const obj = $.object();
	const defaultValues = getDefaultRequestValidatorLayers(ctx.operation);
	for (const key of requestValidatorLayers) {
		const layer = resolveValidatorLayer(ctx.layers, key, defaultValues);
		const layerSchema = ctx.plugin.querySymbol({
			category: "schema",
			resource: "operation",
			resourceId: ctx.operation.id,
			role: `request-${key}`,
			tool: "zod"
		});
		if (layerSchema) {
			obj.prop(layer.as, ctx.nodes.optional({
				...ctx,
				layer,
				schema: $(layerSchema)
			}));
			continue;
		}
		if (layer.whenEmpty === "omit") continue;
		const empty = ctx.nodes.empty({
			...ctx,
			layer
		});
		obj.prop(layer.as, ctx.nodes.optional({
			...ctx,
			layer,
			schema: empty
		}));
	}
	if (obj.isEmpty) return;
	return $(z).attr(identifiers.object).call(obj);
}
function requestValidatorResolver(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function responseValidatorResolver(ctx) {
	const { schema } = ctx.symbols;
	return $(schema).attr(identifiers.parseAsync).call("data").await().return();
}
function runRequestResolver(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.request, requestValidatorResolver];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function runResponseResolver(ctx) {
	const validator = ctx.plugin.config["~resolvers"]?.validator;
	const candidates = [typeof validator === "function" ? validator : validator?.response, responseValidatorResolver];
	for (const candidate of candidates) {
		const statements = candidate?.(ctx);
		if (statements === null) return;
		if (statements !== void 0) return $.func().async().param("data").do(...statements instanceof Array ? statements : [statements]);
	}
}
function createRequestSchemaContext(ctx) {
	const { plugin } = ctx;
	const z = plugin.external("zod.z");
	return {
		...ctx,
		$,
		chain: { current: $(z) },
		nodes: {
			composite: compositeNode,
			empty: emptyNode,
			optional: optionalNode
		},
		symbols: {
			schema: $(""),
			z
		}
	};
}
function createRequestSchemaV4(ctx) {
	const { operation, plugin } = ctx;
	const baseCtx = createRequestSchemaContext(ctx);
	const schema = baseCtx.nodes.composite(baseCtx);
	if (!schema) return;
	if (!plugin.config.requests.shouldExtract({ operation })) return schema;
	return exportAst({
		final: { expression: schema },
		meta: {
			resource: "operation",
			resourceId: operation.id,
			role: "data"
		},
		naming: plugin.config.requests,
		namingAnchor: operation.id,
		path: [],
		plugin,
		schema: {}
	});
}
function createRequestValidatorV4(ctx) {
	const symbolOrSchema = createRequestSchemaV4(ctx);
	if (!symbolOrSchema) return;
	const baseCtx = createRequestSchemaContext(ctx);
	return runRequestResolver({
		...baseCtx,
		symbols: {
			...baseCtx.symbols,
			schema: symbolOrSchema
		}
	});
}
function createResponseValidatorV4({ operation, plugin }) {
	const symbol = plugin.querySymbol({
		category: "schema",
		resource: "operation",
		resourceId: operation.id,
		role: "responses",
		tool: "zod"
	});
	if (!symbol) return;
	const z = plugin.external("zod.z");
	return runResponseResolver({
		$,
		chain: { current: $(z) },
		operation,
		plugin,
		symbols: {
			schema: symbol,
			z
		}
	});
}
//#endregion
//#region src/plugins/zod/api.ts
var Api = class {
	createRequestSchema(ctx) {
		const { plugin } = ctx;
		if (!plugin.config.requests.enabled) return;
		switch (plugin.config.compatibilityVersion) {
			case 3: return createRequestSchemaV3(ctx);
			case "mini": return createRequestSchemaMini(ctx);
			default: return createRequestSchemaV4(ctx);
		}
	}
	createRequestValidator(ctx) {
		const { plugin } = ctx;
		if (!plugin.config.requests.enabled) return;
		switch (plugin.config.compatibilityVersion) {
			case 3: return createRequestValidatorV3(ctx);
			case "mini": return createRequestValidatorMini(ctx);
			default: return createRequestValidatorV4(ctx);
		}
	}
	createResponseValidator(ctx) {
		const { plugin } = ctx;
		switch (plugin.config.compatibilityVersion) {
			case 3: return createResponseValidatorV3(ctx);
			case "mini": return createResponseValidatorMini(ctx);
			default: return createResponseValidatorV4(ctx);
		}
	}
};
//#endregion
//#region src/plugins/zod/shared/module.ts
function getZodModule({ plugin }) {
	const version = plugin.package.getVersion("zod");
	if (version) {
		if (plugin.package.satisfies(version, "<4.0.0")) switch (plugin.config.compatibilityVersion) {
			case 3:
			default: return "zod";
			case 4: return "zod/v4";
			case "mini": return "zod/v4-mini";
		}
	}
	switch (plugin.config.compatibilityVersion) {
		case 3: return "zod/v3";
		case 4:
		default: return "zod";
		case "mini": return "zod/mini";
	}
}
//#endregion
//#region src/plugins/zod/shared/operation.ts
function irOperationToAst({ operation, path, plugin, processor, tags }) {
	if (plugin.config.requests.enabled) {
		const { schema } = buildOperationSchema(operation);
		if (schema.properties?.body && schema.properties.body.type !== "never") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-body"
			},
			naming: plugin.config.requests.body,
			namingAnchor: operation.id,
			path: [...path, "body"],
			plugin,
			schema: schema.properties.body,
			tags
		});
		if (schema.properties?.headers && schema.properties.headers.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-headers"
			},
			naming: plugin.config.requests.headers,
			namingAnchor: operation.id,
			path: [...path, "headers"],
			plugin,
			schema: schema.properties.headers,
			tags
		});
		if (schema.properties?.path && schema.properties.path.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-path"
			},
			naming: plugin.config.requests.path,
			namingAnchor: operation.id,
			path: [...path, "path"],
			plugin,
			schema: schema.properties.path,
			tags
		});
		if (schema.properties?.query && schema.properties.query.type === "object") processor.process({
			meta: {
				resource: "operation",
				resourceId: operation.id,
				role: "request-query"
			},
			naming: plugin.config.requests.query,
			namingAnchor: operation.id,
			path: [...path, "query"],
			plugin,
			schema: schema.properties.query,
			tags
		});
	}
	if (plugin.config.responses.enabled) {
		if (operation.responses) {
			const { response } = operationResponsesMap(operation);
			if (response) processor.process({
				meta: {
					resource: "operation",
					resourceId: operation.id,
					role: "responses"
				},
				naming: plugin.config.responses,
				namingAnchor: operation.id,
				path: [...path, "responses"],
				plugin,
				schema: response,
				tags
			});
		}
	}
}
//#endregion
//#region src/plugins/zod/shared/webhook.ts
function irWebhookToAst({ operation, path, plugin, processor, tags }) {
	if (plugin.config.webhooks.enabled) {
		const { schema } = buildOperationSchema(operation);
		processor.process({
			meta: {
				resource: "webhook",
				resourceId: operation.id,
				role: "data"
			},
			naming: plugin.config.webhooks,
			namingAnchor: operation.id,
			path,
			plugin,
			schema,
			tags
		});
	}
}
//#endregion
//#region src/plugins/zod/shared/meta.ts
/**
* Creates default metadata from a schema.
*/
function defaultMeta(schema) {
	return {
		default: schema.default,
		format: schema.format,
		hasLazy: false,
		isIntersection: false,
		isLazy: false,
		isObject: false,
		nullable: false,
		readonly: schema.accessScope === "read"
	};
}
/**
* Composes metadata from child results.
*
* @param children - Results from walking child schemas
* @param overrides - Explicit overrides (e.g., from parent schema)
*/
function composeMeta(children, overrides) {
	return {
		default: overrides?.default,
		format: overrides?.format,
		hasLazy: overrides?.hasLazy ?? children.some((c) => c.meta.hasLazy),
		isIntersection: overrides?.isIntersection ?? false,
		isLazy: overrides?.isLazy ?? children.some((c) => c.meta.isLazy),
		isObject: overrides?.isObject ?? children.some((c) => c.meta.isObject),
		nullable: overrides?.nullable ?? children.some((c) => c.meta.nullable),
		readonly: overrides?.readonly ?? children.some((c) => c.meta.readonly)
	};
}
/**
* Merges parent schema metadata with composed child metadata.
*
* @param parent - The parent schema
* @param children - Results from walking child schemas
*/
function inheritMeta(parent, children) {
	return composeMeta(children, {
		default: parent.default,
		format: parent.format,
		nullable: false,
		readonly: parent.accessScope === "read"
	});
}
//#endregion
//#region src/plugins/zod/mini/toAst/unknown.ts
function baseNode$41(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.unknown).call();
}
function unknownResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unknownToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$41 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.unknown;
	return resolver?.(ctx) ?? unknownResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/array.ts
function baseNode$40(ctx) {
	const { applyModifiers, childResults, plugin, schema, symbols } = ctx;
	const { z } = symbols;
	const arrayFn = $(z).attr(identifiers.array);
	let normalizedSchema = schema;
	if (normalizedSchema.items) normalizedSchema = deduplicateSchema({ schema: normalizedSchema });
	if (!normalizedSchema.items) return arrayFn.call(unknownToAst$2({
		plugin,
		schema: { type: "unknown" }
	}));
	if (childResults.length === 1) {
		const itemNode = applyModifiers(childResults[0], { optional: false }).expression;
		return arrayFn.call(itemNode);
	}
	if (childResults.length > 1) {
		const itemExpressions = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
		if (normalizedSchema.logicalOperator === "and") return arrayFn.call($(z).attr(identifiers.intersection).call(...itemExpressions));
		else return arrayFn.call($(z).attr(identifiers.union).call($.array(...itemExpressions)));
	}
	return arrayFn.call(unknownToAst$2({
		plugin,
		schema: { type: "unknown" }
	}));
}
function lengthNode$5(ctx) {
	const { schema } = ctx;
	if (schema.minItems === schema.maxItems && schema.minItems !== void 0) return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems));
}
function maxLengthNode$5(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.maxItems === void 0) return;
	return $(z).attr(identifiers.maxLength).call($.fromValue(schema.maxItems));
}
function minLengthNode$5(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.minItems === void 0) return;
	return $(z).attr(identifiers.minLength).call($.fromValue(schema.minItems));
}
function arrayResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	const lengthResult = ctx.nodes.length(ctx);
	if (lengthResult) ctx.chain.current = lengthResult;
	else {
		const minLengthResult = ctx.nodes.minLength(ctx);
		const maxLengthResult = ctx.nodes.maxLength(ctx);
		if (minLengthResult && maxLengthResult) ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(minLengthResult, maxLengthResult);
		else if (minLengthResult) ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(minLengthResult);
		else if (maxLengthResult) ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(maxLengthResult);
	}
	return ctx.chain.current;
}
function arrayToAst$2({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	let schemaCopy = schema;
	const z = plugin.external("zod.z");
	if (schemaCopy.items) {
		schemaCopy = deduplicateSchema({ schema: schemaCopy });
		schemaCopy.items.forEach((item, index) => {
			const itemResult = walk(item, childContext(walkerCtx, "items", index));
			childResults.push(itemResult);
		});
	}
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$40,
			length: lengthNode$5,
			maxLength: maxLengthNode$5,
			minLength: minLengthNode$5
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.array;
	return {
		childResults,
		expression: resolver?.(ctx) ?? arrayResolver$2(ctx)
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/boolean.ts
function baseNode$39(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.boolean).call();
}
function constNode$11(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "boolean") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function booleanResolver$2(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function booleanToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$39,
			const: constNode$11
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.boolean;
	return resolver?.(ctx) ?? booleanResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/enum.ts
function itemsNode$2(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	const enumMembers = [];
	const literalMembers = [];
	let isNullable = false;
	let allStrings = true;
	for (const item of schema.items ?? []) if (item.type === "string" && typeof item.const === "string") {
		const literal = $.literal(item.const);
		enumMembers.push(literal);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if ((item.type === "number" || item.type === "integer") && typeof item.const === "number") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "boolean" && typeof item.const === "boolean") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "null" || item.const === null) isNullable = true;
	return {
		allStrings,
		enumMembers,
		isNullable,
		literalMembers
	};
}
function baseNode$38(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx);
	if (allStrings && enumMembers.length) return $(z).attr(identifiers.enum).call($.array(...enumMembers));
	if (literalMembers.length === 1) return literalMembers[0];
	return $(z).attr(identifiers.union).call($.array(...literalMembers));
}
function enumResolver$2(ctx) {
	const { literalMembers } = ctx.nodes.items(ctx);
	if (!literalMembers.length) return ctx.chain.current;
	const baseExpression = ctx.nodes.base(ctx);
	ctx.chain.current = baseExpression;
	return ctx.chain.current;
}
function enumToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$38,
			items: itemsNode$2
		},
		plugin,
		schema,
		symbols: { z }
	};
	const { literalMembers } = itemsNode$2(ctx);
	if (!literalMembers.length) return unknownToAst$2({
		plugin,
		schema: { type: "unknown" }
	});
	const resolver = plugin.config["~resolvers"]?.enum;
	return resolver?.(ctx) ?? enumResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/intersection.ts
function baseNode$37(ctx) {
	const { childResults, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.never).call();
	let expression = childResults[0].expression;
	childResults.slice(1).forEach((item) => {
		expression = $(z).attr(identifiers.intersection).call(expression, item.meta.hasLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression);
	});
	return expression;
}
function intersectionResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function intersectionToAst$2({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$37 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.intersection;
	return {
		childResults,
		expression: resolver?.(ctx) ?? intersectionResolver$2(ctx)
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/never.ts
function baseNode$36(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.never).call();
}
function neverResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function neverToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$36 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.never;
	return resolver?.(ctx) ?? neverResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/null.ts
function baseNode$35(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.null).call();
}
function nullResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function nullToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$35 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.null;
	return resolver?.(ctx) ?? nullResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/number.ts
function baseNode$34(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (ctx.utils.shouldCoerceToBigInt(schema.format)) return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call();
	let chain = $(z).attr(identifiers.number).call();
	if (schema.type === "integer") chain = $(z).attr(identifiers.int).call();
	return chain;
}
function constNode$10(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.const === void 0) return;
	return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format));
}
function maxNode$2(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.exclusiveMaximum !== void 0) return $(z).attr(identifiers.lt).call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format));
	if (schema.maximum !== void 0) return $(z).attr(identifiers.lte).call(ctx.utils.maybeBigInt(schema.maximum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return $(z).attr(identifiers.maximum).call(ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop("error", $.literal(limit.maxError)));
}
function minNode$2(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.exclusiveMinimum !== void 0) return $(z).attr(identifiers.gt).call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format));
	if (schema.minimum !== void 0) return $(z).attr(identifiers.gte).call(ctx.utils.maybeBigInt(schema.minimum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return $(z).attr(identifiers.minimum).call(ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop("error", $.literal(limit.minError)));
}
function numberResolver$2(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const checks = [];
	const minNode = ctx.nodes.min(ctx);
	if (minNode) checks.push(minNode);
	const maxNode = ctx.nodes.max(ctx);
	if (maxNode) checks.push(maxNode);
	if (checks.length) ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(...checks);
	return ctx.chain.current;
}
function numberToNode$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$34,
			const: constNode$10,
			max: maxNode$2,
			min: minNode$2
		},
		plugin,
		schema,
		symbols: { z },
		utils: {
			getIntegerLimit,
			maybeBigInt,
			shouldCoerceToBigInt
		}
	};
	const resolver = plugin.config["~resolvers"]?.number;
	return resolver?.(ctx) ?? numberResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/object.ts
function additionalPropertiesNode$2(ctx) {
	const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx;
	if (!schema.additionalProperties || schema.properties && Object.keys(schema.properties).length) return;
	const additionalResult = walk(schema.additionalProperties, childContext(walkerCtx, "additionalProperties"));
	_childResults.push(additionalResult);
	return applyModifiers(additionalResult, {}).expression;
}
function baseNode$33(ctx) {
	const { nodes, symbols } = ctx;
	const { z } = symbols;
	const additional = nodes.additionalProperties(ctx);
	const shape = nodes.shape(ctx);
	if (additional) return $(z).attr(identifiers.record).call($(z).attr(identifiers.string).call(), additional);
	return $(z).attr(identifiers.object).call(shape);
}
function objectResolver$2(ctx) {
	return ctx.nodes.base(ctx);
}
function shapeNode$2(ctx) {
	const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx;
	const shape = $.object().pretty();
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isOptional = !schema.required?.includes(name);
		const propertyResult = walk(property, childContext(walkerCtx, "properties", name));
		_childResults.push(propertyResult);
		const finalExpr = applyModifiers(propertyResult, { optional: isOptional });
		shape.prop(name, finalExpr.expression);
	}
	return shape;
}
function objectToAst$2(options) {
	const { applyModifiers, plugin, schema, walk, walkerCtx } = options;
	const childResults = [];
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		_childResults: childResults,
		applyModifiers,
		chain: { current: $(z) },
		nodes: {
			additionalProperties: additionalPropertiesNode$2,
			base: baseNode$33,
			shape: shapeNode$2
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.object;
	return {
		childResults,
		expression: resolver?.(ctx) ?? objectResolver$2(ctx)
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/string.ts
function baseNode$32(ctx) {
	const { z } = ctx.symbols;
	return $(z).attr(identifiers.string).call();
}
function constNode$9(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "string") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function formatNode$2(ctx) {
	const { plugin, schema, symbols } = ctx;
	const { z } = symbols;
	switch (schema.format) {
		case "date": return $(z).attr(identifiers.iso).attr(identifiers.date).call();
		case "date-time": {
			const obj = $.object().$if(plugin.config.dates.offset, (o) => o.prop("offset", $.literal(true))).$if(plugin.config.dates.local, (o) => o.prop("local", $.literal(true)));
			return $(z).attr(identifiers.iso).attr(identifiers.datetime).call(obj.hasProps() ? obj : void 0);
		}
		case "email": return $(z).attr(identifiers.email).call();
		case "guid": return $(z).attr(identifiers.guid).call();
		case "ipv4": return $(z).attr(identifiers.ipv4).call();
		case "ipv6": return $(z).attr(identifiers.ipv6).call();
		case "time": return $(z).attr(identifiers.iso).attr(identifiers.time).call();
		case "uri": return $(z).attr(identifiers.url).call();
		case "uuid": return $(z).attr(identifiers.uuid).call();
	}
}
function lengthNode$4(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.minLength === void 0 || schema.minLength !== schema.maxLength) return;
	return $(z).attr(identifiers.length).call($.literal(schema.minLength));
}
function maxLengthNode$4(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.maxLength === void 0) return;
	return $(z).attr(identifiers.maxLength).call($.literal(schema.maxLength));
}
function minLengthNode$4(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.minLength === void 0) return;
	return $(z).attr(identifiers.minLength).call($.literal(schema.minLength));
}
function patternNode$2(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (!schema.pattern) return;
	const flags = /\\[pP]\{/.test(schema.pattern) ? "u" : void 0;
	return $(z).attr(identifiers.regex).call($.regexp(schema.pattern, flags));
}
function stringResolver$2(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const formatNode = ctx.nodes.format(ctx);
	if (formatNode) ctx.chain.current = formatNode;
	const checks = [];
	const lengthNode = ctx.nodes.length(ctx);
	if (lengthNode) checks.push(lengthNode);
	else {
		const minLengthNode = ctx.nodes.minLength(ctx);
		if (minLengthNode) checks.push(minLengthNode);
		const maxLengthNode = ctx.nodes.maxLength(ctx);
		if (maxLengthNode) checks.push(maxLengthNode);
	}
	const patternNode = ctx.nodes.pattern(ctx);
	if (patternNode) checks.push(patternNode);
	if (checks.length) ctx.chain.current = ctx.chain.current.attr(identifiers.check).call(...checks);
	return ctx.chain.current;
}
function stringToNode$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$32,
			const: constNode$9,
			format: formatNode$2,
			length: lengthNode$4,
			maxLength: maxLengthNode$4,
			minLength: minLengthNode$4,
			pattern: patternNode$2
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.string;
	return resolver?.(ctx) ?? stringResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/toAst/tuple.ts
function baseNode$31(ctx) {
	const { applyModifiers, childResults, symbols } = ctx;
	const { z } = symbols;
	const tupleFn = $(z).attr(identifiers.tuple);
	if (!childResults.length) return tupleFn.call($.array());
	const tupleElements = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
	return tupleFn.call($.array(...tupleElements));
}
function constNode$8(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (!schema.const || !Array.isArray(schema.const)) return;
	const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)));
	return $(z).attr(identifiers.tuple).call($.array(...tupleElements));
}
function tupleResolver$2(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function tupleToAst$2({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	const z = plugin.external("zod.z");
	if (schema.items) schema.items.forEach((item, index) => {
		const itemResult = walk(item, childContext(walkerCtx, "items", index));
		childResults.push(itemResult);
	});
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$31,
			const: constNode$8
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.tuple;
	return {
		childResults,
		expression: resolver?.(ctx) ?? tupleResolver$2(ctx)
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/undefined.ts
function baseNode$30(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.undefined).call();
}
function undefinedResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function undefinedToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$30 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.undefined;
	return resolver?.(ctx) ?? undefinedResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/shared/discriminated-union.ts
function tryBuildDiscriminatedUnion({ items, parentSchema, plugin, schemas }) {
	const discriminatorKey = parentSchema.discriminator?.propertyName;
	if (!discriminatorKey) return null;
	const members = [];
	for (let index = 0; index < schemas.length; index++) {
		const schema = schemas[index];
		if (schema.type === "null" || schema.const === null) continue;
		if (schema.logicalOperator !== "and" || !schema.items || schema.items.length !== 2) return null;
		const refPart = schema.items[1];
		const discriminatedValue = schema.items[0].properties?.[discriminatorKey]?.const;
		if (discriminatedValue === void 0 || items[index].meta.hasLazy) return null;
		let refExpression;
		if (refPart.symbolRef) {
			if (refPart.symbolRef.meta?.isIntersection) return null;
			refExpression = $(refPart.symbolRef);
		} else if (refPart.$ref) {
			const query = {
				category: "schema",
				resource: "definition",
				resourceId: refPart.$ref,
				tool: "zod"
			};
			if ((plugin.querySymbol(query)?.meta)?.isIntersection) return null;
			refExpression = $(plugin.referenceSymbol(query));
		} else return null;
		members.push({
			discriminatedValue,
			refExpression
		});
	}
	if (!members.length) return null;
	return {
		discriminatorKey,
		members
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/union.ts
function baseNode$29(ctx) {
	const { childResults, parentSchema, plugin, schemas, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.null).call();
	const nonNullItems = [];
	childResults.forEach((result, index) => {
		const schema = schemas[index];
		if (schema.type !== "null" && schema.const !== null) nonNullItems.push(result);
	});
	if (!nonNullItems.length) return $(z).attr(identifiers.null).call();
	if (nonNullItems.length === 1) return nonNullItems[0].expression;
	const discriminatedExpression = tryBuildDiscriminatedUnion({
		items: childResults,
		parentSchema,
		plugin,
		schemas
	});
	if (discriminatedExpression) {
		const unionMembers = discriminatedExpression.members.map((member) => $(z).attr(identifiers.extend).call(member.refExpression, $.object().prop(discriminatedExpression.discriminatorKey, $(z).attr(identifiers.literal).call($.fromValue(member.discriminatedValue)))));
		return $(z).attr(identifiers.discriminatedUnion).call($.literal(discriminatedExpression.discriminatorKey), $.array().pretty().elements(...unionMembers));
	}
	return $(z).attr(identifiers.union).call($.array().pretty().elements(...nonNullItems.map((item) => item.expression)));
}
function unionResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unionToAst$2({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$29 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.union;
	return {
		childResults,
		expression: resolver?.(ctx) ?? unionResolver$2(ctx)
	};
}
//#endregion
//#region src/plugins/zod/mini/toAst/void.ts
function baseNode$28(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.void).call();
}
function voidResolver$2(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function voidToAst$2({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$28 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.void;
	return resolver?.(ctx) ?? voidResolver$2(ctx);
}
//#endregion
//#region src/plugins/zod/mini/walker.ts
function getDefaultValue$2(meta) {
	return meta.format ? maybeBigInt(meta.default, meta.format) : $.fromValue(meta.default);
}
function createVisitor$2(config = {}) {
	const { schemaExtractor } = config;
	return {
		applyModifiers(result, ctx, options = {}) {
			const { optional } = options;
			const z = ctx.plugin.external("zod.z");
			let expression = result.expression;
			if (result.meta.readonly) expression = $(z).attr(identifiers.readonly).call(expression);
			const needsDefault = result.meta.default !== void 0;
			const needsNullable = result.meta.nullable;
			if (optional && needsNullable) expression = $(z).attr(identifiers.nullish).call(expression);
			else if (optional) expression = $(z).attr(identifiers.optional).call(expression);
			else if (needsNullable) expression = $(z).attr(identifiers.nullable).call(expression);
			if (needsDefault) expression = $(z).attr(identifiers._default).call(expression, getDefaultValue$2(result.meta));
			return { expression };
		},
		array(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = arrayToAst$2({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		boolean(schema, ctx) {
			return {
				expression: booleanToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		enum(schema, ctx) {
			const expression = enumToAst$2({
				plugin: ctx.plugin,
				schema
			});
			const hasNull = schema.items?.some((item) => item.type === "null" || item.const === null) ?? false;
			return {
				expression,
				meta: {
					...defaultMeta(schema),
					nullable: hasNull
				}
			};
		},
		integer(schema, ctx) {
			return {
				expression: numberToNode$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		intercept(schema, ctx, walk) {
			if (schemaExtractor && !schema.$ref) {
				const extracted = schemaExtractor({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(fromRef(ctx.path))
					},
					naming: ctx.plugin.config.definitions,
					path: fromRef(ctx.path),
					plugin: ctx.plugin,
					schema
				});
				if (extracted !== schema) return walk(extracted, ctx);
			}
			if (schema.symbolRef) return {
				expression: $(schema.symbolRef),
				meta: defaultMeta(schema)
			};
		},
		intersection(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const { expression } = intersectionToAst$2({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: true,
					isLazy: false,
					nullable: items.some((i) => i.meta.nullable),
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		never(schema, ctx) {
			return {
				expression: neverToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		null(schema, ctx) {
			return {
				expression: nullToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		number(schema, ctx) {
			return {
				expression: numberToNode$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		object(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = objectToAst$2({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		postProcess(result, schema, ctx) {
			const { metadata } = ctx.plugin.config;
			if (!metadata) return result;
			const node = $.object();
			if (metadata === true) {
				if (!schema.description) return result;
				node.pretty().prop("description", $.literal(schema.description));
			} else metadata({
				$,
				node,
				schema
			});
			if (node.isEmpty) return result;
			const z = ctx.plugin.external("zod.z");
			return {
				...result,
				expression: result.expression.attr(identifiers.register).call($(z).attr(identifiers.globalRegistry), node)
			};
		},
		reference($ref, schema, ctx) {
			const z = ctx.plugin.external("zod.z");
			const query = {
				category: "schema",
				resource: "definition",
				resourceId: $ref,
				tool: "zod"
			};
			const refSymbol = ctx.plugin.referenceSymbol(query);
			if (ctx.plugin.isSymbolRegistered(query)) return {
				expression: $(refSymbol),
				meta: defaultMeta(schema)
			};
			return {
				expression: $(z).attr(identifiers.lazy).call($.func().returns("any").do($(refSymbol).return())),
				meta: {
					...defaultMeta(schema),
					hasLazy: true,
					isLazy: true
				}
			};
		},
		string(schema, ctx) {
			if (shouldCoerceToBigInt(schema.format)) return {
				expression: numberToNode$2({
					plugin: ctx.plugin,
					schema: {
						...schema,
						type: "number"
					}
				}),
				meta: defaultMeta(schema)
			};
			return {
				expression: stringToNode$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		tuple(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = tupleToAst$2({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		undefined(schema, ctx) {
			return {
				expression: undefinedToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		union(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const hasNull = schemas.some((s) => s.type === "null") || items.some((i) => i.meta.nullable);
			const { expression } = unionToAst$2({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: false,
					isLazy: false,
					nullable: hasNull,
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		unknown(schema, ctx) {
			return {
				expression: unknownToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		void(schema, ctx) {
			return {
				expression: voidToAst$2({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		}
	};
}
//#endregion
//#region src/plugins/zod/mini/processor.ts
function createProcessor$2(plugin) {
	const processor = createSchemaProcessor();
	const extractorHooks = [plugin.config["~hooks"]?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract];
	function extractor(ctx) {
		if (processor.hasEmitted(ctx.path)) return ctx.schema;
		for (const hook of extractorHooks) if (typeof hook === "boolean" ? hook : hook?.(ctx) ?? false) {
			process({
				namingAnchor: processor.context.anchor,
				tags: processor.context.tags,
				...ctx
			});
			return { $ref: pathToJsonPointer(ctx.path) };
		}
		return ctx.schema;
	}
	function process(ctx) {
		if (!processor.markEmitted(ctx.path)) return;
		const shouldExport = ctx.export !== false;
		return processor.withContext({
			anchor: ctx.namingAnchor,
			tags: ctx.tags
		}, () => {
			const visitor = createVisitor$2({ schemaExtractor: extractor });
			const result = createSchemaWalker(visitor)(ctx.schema, {
				path: ref(ctx.path),
				plugin
			});
			const final = visitor.applyModifiers(result, {
				path: ref(ctx.path),
				plugin
			});
			if (shouldExport) {
				exportAst({
					...ctx,
					final,
					meta: result.meta.isIntersection ? {
						...ctx.meta,
						isIntersection: true
					} : ctx.meta,
					plugin
				});
				return;
			}
			return final;
		});
	}
	return { process };
}
//#endregion
//#region src/plugins/zod/mini/plugin.ts
const handlerMini = ({ plugin }) => {
	plugin.symbol("z", {
		external: getZodModule({ plugin }),
		importKind: "namespace",
		meta: { resource: "zod.z" }
	});
	const processor = createProcessor$2(plugin);
	plugin.forEach("operation", "parameter", "requestBody", "schema", "webhook", (event) => {
		switch (event.type) {
			case "operation":
				irOperationToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
			case "parameter":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.parameter.schema,
					tags: event.tags
				});
				break;
			case "requestBody":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.requestBody.schema,
					tags: event.tags
				});
				break;
			case "schema":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.schema,
					tags: event.tags
				});
				break;
			case "webhook":
				irWebhookToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
		}
	});
};
//#endregion
//#region src/plugins/zod/v3/toAst/unknown.ts
function baseNode$27(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.unknown).call();
}
function unknownResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unknownToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$27 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.unknown;
	return resolver?.(ctx) ?? unknownResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/array.ts
function baseNode$26(ctx) {
	const { applyModifiers, childResults, plugin, schema, symbols } = ctx;
	const { z } = symbols;
	const arrayFn = $(z).attr(identifiers.array);
	let normalizedSchema = schema;
	if (normalizedSchema.items) normalizedSchema = deduplicateSchema({ schema: normalizedSchema });
	if (!normalizedSchema.items) return arrayFn.call(unknownToAst$1({
		plugin,
		schema: { type: "unknown" }
	}));
	if (childResults.length === 1) {
		const itemNode = applyModifiers(childResults[0], { optional: false }).expression;
		return arrayFn.call(itemNode);
	}
	if (childResults.length > 1) {
		const itemExpressions = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
		const firstSchema = normalizedSchema.items[0];
		if (normalizedSchema.logicalOperator === "and") {
			let intersectionExpression;
			if (firstSchema?.logicalOperator === "or" || firstSchema?.type && firstSchema.type !== "object") intersectionExpression = $(z).attr(identifiers.intersection).call(...itemExpressions);
			else {
				intersectionExpression = itemExpressions[0];
				for (let i = 1; i < itemExpressions.length; i++) intersectionExpression = intersectionExpression.attr(identifiers.and).call(itemExpressions[i]);
			}
			return arrayFn.call(intersectionExpression);
		} else return arrayFn.call($(z).attr(identifiers.union).call($.array(...itemExpressions)));
	}
	return arrayFn.call(unknownToAst$1({
		plugin,
		schema: { type: "unknown" }
	}));
}
function lengthNode$3(ctx) {
	const { schema } = ctx;
	if (schema.minItems === schema.maxItems && schema.minItems !== void 0) return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems));
}
function maxLengthNode$3(ctx) {
	const { schema } = ctx;
	if (schema.maxItems === void 0) return;
	return ctx.chain.current.attr(identifiers.max).call($.fromValue(schema.maxItems));
}
function minLengthNode$3(ctx) {
	const { schema } = ctx;
	if (schema.minItems === void 0) return;
	return ctx.chain.current.attr(identifiers.min).call($.fromValue(schema.minItems));
}
function arrayResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	const lengthResult = ctx.nodes.length(ctx);
	if (lengthResult) ctx.chain.current = lengthResult;
	else {
		const minLengthResult = ctx.nodes.minLength(ctx);
		if (minLengthResult) ctx.chain.current = minLengthResult;
		const maxLengthResult = ctx.nodes.maxLength(ctx);
		if (maxLengthResult) ctx.chain.current = maxLengthResult;
	}
	return ctx.chain.current;
}
function arrayToAst$1({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	let schemaCopy = schema;
	const z = plugin.external("zod.z");
	if (schemaCopy.items) {
		schemaCopy = deduplicateSchema({ schema: schemaCopy });
		schemaCopy.items.forEach((item, index) => {
			const itemResult = walk(item, childContext(walkerCtx, "items", index));
			childResults.push(itemResult);
		});
	}
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$26,
			length: lengthNode$3,
			maxLength: maxLengthNode$3,
			minLength: minLengthNode$3
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.array;
	return {
		childResults,
		expression: resolver?.(ctx) ?? arrayResolver$1(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v3/toAst/boolean.ts
function baseNode$25(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.boolean).call();
}
function constNode$7(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "boolean") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function booleanResolver$1(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function booleanToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$25,
			const: constNode$7
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.boolean;
	return resolver?.(ctx) ?? booleanResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/enum.ts
function itemsNode$1(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	const enumMembers = [];
	const literalMembers = [];
	let isNullable = false;
	let allStrings = true;
	for (const item of schema.items ?? []) if (item.type === "string" && typeof item.const === "string") {
		const literal = $.literal(item.const);
		enumMembers.push(literal);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if ((item.type === "number" || item.type === "integer") && typeof item.const === "number") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "boolean" && typeof item.const === "boolean") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "null" || item.const === null) isNullable = true;
	return {
		allStrings,
		enumMembers,
		isNullable,
		literalMembers
	};
}
function baseNode$24(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx);
	if (allStrings && enumMembers.length) return $(z).attr(identifiers.enum).call($.array(...enumMembers));
	else if (literalMembers.length === 1) return literalMembers[0];
	else return $(z).attr(identifiers.union).call($.array(...literalMembers));
}
function enumResolver$1(ctx) {
	const { literalMembers } = ctx.nodes.items(ctx);
	if (!literalMembers.length) return ctx.chain.current;
	const baseExpression = ctx.nodes.base(ctx);
	ctx.chain.current = baseExpression;
	return ctx.chain.current;
}
function enumToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$24,
			items: itemsNode$1
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.enum;
	return resolver?.(ctx) ?? enumResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/intersection.ts
function baseNode$23(ctx) {
	const { childResults, schemas, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.never).call();
	const firstSchema = schemas[0];
	if (firstSchema?.logicalOperator === "or" || firstSchema?.type && firstSchema.type !== "object") return $(z).attr(identifiers.intersection).call(...childResults.map((result) => result.expression));
	let expression = childResults[0].expression;
	childResults.slice(1).forEach((item) => {
		expression = expression.attr(identifiers.and).call(item.meta.hasLazy && !item.meta.isLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression);
	});
	return expression;
}
function intersectionResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function intersectionToAst$1({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$23 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.intersection;
	return {
		childResults,
		expression: resolver?.(ctx) ?? intersectionResolver$1(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v3/toAst/never.ts
function baseNode$22(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.never).call();
}
function neverResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function neverToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$22 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.never;
	return resolver?.(ctx) ?? neverResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/null.ts
function baseNode$21(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.null).call();
}
function nullResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function nullToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$21 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.null;
	return resolver?.(ctx) ?? nullResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/number.ts
function baseNode$20(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (ctx.utils.shouldCoerceToBigInt(schema.format)) return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call();
	let chain = $(z).attr(identifiers.number).call();
	if (schema.type === "integer") chain = chain.attr(identifiers.int).call();
	return chain;
}
function constNode$6(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.const === void 0) return;
	return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format));
}
function maxNode$1(ctx) {
	const { chain, schema } = ctx;
	if (schema.exclusiveMaximum !== void 0) return chain.current.attr(identifiers.lt).call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format));
	if (schema.maximum !== void 0) return chain.current.attr(identifiers.lte).call(ctx.utils.maybeBigInt(schema.maximum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return chain.current.attr(identifiers.max).call(ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop("message", $.literal(limit.maxError)));
}
function minNode$1(ctx) {
	const { chain, schema } = ctx;
	if (schema.exclusiveMinimum !== void 0) return chain.current.attr(identifiers.gt).call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format));
	if (schema.minimum !== void 0) return chain.current.attr(identifiers.gte).call(ctx.utils.maybeBigInt(schema.minimum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return chain.current.attr(identifiers.min).call(ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop("message", $.literal(limit.minError)));
}
function numberResolver$1(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const minNode = ctx.nodes.min(ctx);
	if (minNode) ctx.chain.current = minNode;
	const maxNode = ctx.nodes.max(ctx);
	if (maxNode) ctx.chain.current = maxNode;
	return ctx.chain.current;
}
function numberToNode$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$20,
			const: constNode$6,
			max: maxNode$1,
			min: minNode$1
		},
		plugin,
		schema,
		symbols: { z },
		utils: {
			getIntegerLimit,
			maybeBigInt,
			shouldCoerceToBigInt
		}
	};
	const resolver = plugin.config["~resolvers"]?.number;
	return resolver?.(ctx) ?? numberResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/object.ts
function additionalPropertiesNode$1(ctx) {
	const { applyModifiers, schema, walk, walkerCtx } = ctx;
	if (!schema.additionalProperties || schema.properties && Object.keys(schema.properties).length) return;
	const additionalResult = walk(schema.additionalProperties, childContext(walkerCtx, "additionalProperties"));
	ctx._childResults.push(additionalResult);
	return applyModifiers(additionalResult, {}).expression;
}
function baseNode$19(ctx) {
	const { nodes, symbols } = ctx;
	const { z } = symbols;
	const additional = nodes.additionalProperties(ctx);
	const shape = nodes.shape(ctx);
	if (additional) return $(z).attr(identifiers.record).call(additional);
	return $(z).attr(identifiers.object).call(shape);
}
function objectResolver$1(ctx) {
	return ctx.nodes.base(ctx);
}
function shapeNode$1(ctx) {
	const { applyModifiers, schema, walk, walkerCtx } = ctx;
	const shape = $.object().pretty();
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isOptional = !schema.required?.includes(name);
		const propertyResult = walk(property, childContext(walkerCtx, "properties", name));
		ctx._childResults.push(propertyResult);
		const finalExpr = applyModifiers(propertyResult, { optional: isOptional });
		shape.prop(name, finalExpr.expression);
	}
	return shape;
}
function objectToAst$1(options) {
	const { applyModifiers, plugin, schema, walk, walkerCtx } = options;
	const childResults = [];
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		_childResults: childResults,
		applyModifiers,
		chain: { current: $(z) },
		nodes: {
			additionalProperties: additionalPropertiesNode$1,
			base: baseNode$19,
			shape: shapeNode$1
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.object;
	return {
		childResults,
		expression: resolver?.(ctx) ?? objectResolver$1(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v3/toAst/string.ts
function baseNode$18(ctx) {
	const { z } = ctx.symbols;
	return $(z).attr(identifiers.string).call();
}
function constNode$5(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "string") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function formatNode$1(ctx) {
	const { chain, plugin, schema } = ctx;
	switch (schema.format) {
		case "date": return chain.current.attr(identifiers.date).call();
		case "date-time": {
			const obj = $.object().$if(plugin.config.dates.offset, (o) => o.prop("offset", $.literal(true))).$if(plugin.config.dates.local, (o) => o.prop("local", $.literal(true)));
			return chain.current.attr(identifiers.datetime).call(obj.hasProps() ? obj : void 0);
		}
		case "email": return chain.current.attr(identifiers.email).call();
		case "ipv4":
		case "ipv6": return chain.current.attr(identifiers.ip).call();
		case "time": return chain.current.attr(identifiers.time).call();
		case "uri": return chain.current.attr(identifiers.url).call();
		case "uuid": return chain.current.attr(identifiers.uuid).call();
	}
}
function lengthNode$2(ctx) {
	const { chain, schema } = ctx;
	if (schema.minLength === void 0 || schema.minLength !== schema.maxLength) return;
	return chain.current.attr(identifiers.length).call($.literal(schema.minLength));
}
function maxLengthNode$2(ctx) {
	const { chain, schema } = ctx;
	if (schema.maxLength === void 0) return;
	return chain.current.attr(identifiers.max).call($.literal(schema.maxLength));
}
function minLengthNode$2(ctx) {
	const { chain, schema } = ctx;
	if (schema.minLength === void 0) return;
	return chain.current.attr(identifiers.min).call($.literal(schema.minLength));
}
function patternNode$1(ctx) {
	const { chain, schema } = ctx;
	if (!schema.pattern) return;
	const flags = /\\[pP]\{/.test(schema.pattern) ? "u" : void 0;
	return chain.current.attr(identifiers.regex).call($.regexp(schema.pattern, flags));
}
function stringResolver$1(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const formatNode = ctx.nodes.format(ctx);
	if (formatNode) ctx.chain.current = formatNode;
	const lengthNode = ctx.nodes.length(ctx);
	if (lengthNode) ctx.chain.current = lengthNode;
	else {
		const minLengthNode = ctx.nodes.minLength(ctx);
		if (minLengthNode) ctx.chain.current = minLengthNode;
		const maxLengthNode = ctx.nodes.maxLength(ctx);
		if (maxLengthNode) ctx.chain.current = maxLengthNode;
	}
	const patternNode = ctx.nodes.pattern(ctx);
	if (patternNode) ctx.chain.current = patternNode;
	return ctx.chain.current;
}
function stringToNode$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$18,
			const: constNode$5,
			format: formatNode$1,
			length: lengthNode$2,
			maxLength: maxLengthNode$2,
			minLength: minLengthNode$2,
			pattern: patternNode$1
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.string;
	return resolver?.(ctx) ?? stringResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/tuple.ts
function baseNode$17(ctx) {
	const { applyModifiers, childResults, symbols } = ctx;
	const { z } = symbols;
	const tupleFn = $(z).attr(identifiers.tuple);
	if (!childResults.length) return tupleFn.call($.array());
	const tupleElements = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
	return tupleFn.call($.array(...tupleElements));
}
function constNode$4(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (!schema.const || !Array.isArray(schema.const)) return;
	const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)));
	return $(z).attr(identifiers.tuple).call($.array(...tupleElements));
}
function tupleResolver$1(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function tupleToAst$1({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	const z = plugin.external("zod.z");
	if (schema.items) schema.items.forEach((item, index) => {
		const itemResult = walk(item, childContext(walkerCtx, "items", index));
		childResults.push(itemResult);
	});
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$17,
			const: constNode$4
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.tuple;
	return {
		childResults,
		expression: resolver?.(ctx) ?? tupleResolver$1(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v3/toAst/undefined.ts
function baseNode$16(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.undefined).call();
}
function undefinedResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function undefinedToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$16 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.undefined;
	return resolver?.(ctx) ?? undefinedResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/toAst/union.ts
function baseNode$15(ctx) {
	const { childResults, parentSchema, plugin, schemas, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.null).call();
	const nonNullItems = [];
	childResults.forEach((result, index) => {
		const schema = schemas[index];
		if (schema.type !== "null" && schema.const !== null) nonNullItems.push(result);
	});
	if (!nonNullItems.length) return $(z).attr(identifiers.null).call();
	if (nonNullItems.length === 1) return nonNullItems[0].expression;
	const discriminatedExpression = tryBuildDiscriminatedUnion({
		items: childResults,
		parentSchema,
		plugin,
		schemas
	});
	if (discriminatedExpression) {
		const unionMembers = discriminatedExpression.members.map((member) => member.refExpression.attr(identifiers.extend).call($.object().prop(discriminatedExpression.discriminatorKey, $(z).attr(identifiers.literal).call($.fromValue(member.discriminatedValue)))));
		return $(z).attr(identifiers.discriminatedUnion).call($.literal(discriminatedExpression.discriminatorKey), $.array().pretty().elements(...unionMembers));
	}
	return $(z).attr(identifiers.union).call($.array().pretty().elements(...nonNullItems.map((item) => item.expression)));
}
function unionResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unionToAst$1({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$15 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.union;
	return {
		childResults,
		expression: resolver?.(ctx) ?? unionResolver$1(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v3/toAst/void.ts
function baseNode$14(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.void).call();
}
function voidResolver$1(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function voidToAst$1({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$14 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.void;
	return resolver?.(ctx) ?? voidResolver$1(ctx);
}
//#endregion
//#region src/plugins/zod/v3/walker.ts
function getDefaultValue$1(meta) {
	return meta.format ? maybeBigInt(meta.default, meta.format) : $.fromValue(meta.default);
}
function createVisitor$1(config = {}) {
	const { schemaExtractor } = config;
	return {
		applyModifiers(result, ctx, options = {}) {
			const { optional } = options;
			let expression = result.expression;
			if (result.meta.readonly) expression = expression.attr(identifiers.readonly).call();
			const needsDefault = result.meta.default !== void 0;
			const needsNullable = result.meta.nullable;
			if (optional && needsNullable) expression = expression.attr(identifiers.nullish).call();
			else if (optional) expression = expression.attr(identifiers.optional).call();
			else if (needsNullable) expression = expression.attr(identifiers.nullable).call();
			if (needsDefault) expression = expression.attr(identifiers.default).call(getDefaultValue$1(result.meta));
			return {
				expression,
				typeName: result.meta.hasLazy ? result.meta.isObject ? identifiers.AnyZodObject : identifiers.ZodTypeAny : void 0
			};
		},
		array(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = arrayToAst$1({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		boolean(schema, ctx) {
			return {
				expression: booleanToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		enum(schema, ctx) {
			const expression = enumToAst$1({
				plugin: ctx.plugin,
				schema
			});
			const hasNull = schema.items?.some((item) => item.type === "null" || item.const === null) ?? false;
			return {
				expression,
				meta: {
					...defaultMeta(schema),
					nullable: hasNull
				}
			};
		},
		integer(schema, ctx) {
			return {
				expression: numberToNode$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		intercept(schema, ctx, walk) {
			if (schemaExtractor && !schema.$ref) {
				const extracted = schemaExtractor({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(fromRef(ctx.path))
					},
					naming: ctx.plugin.config.definitions,
					path: fromRef(ctx.path),
					plugin: ctx.plugin,
					schema
				});
				if (extracted !== schema) return walk(extracted, ctx);
			}
			if (schema.symbolRef) return {
				expression: $(schema.symbolRef),
				meta: defaultMeta(schema)
			};
		},
		intersection(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const { expression } = intersectionToAst$1({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: true,
					isLazy: false,
					nullable: items.some((i) => i.meta.nullable),
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		never(schema, ctx) {
			return {
				expression: neverToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		null(schema, ctx) {
			return {
				expression: nullToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		number(schema, ctx) {
			return {
				expression: numberToNode$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		object(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = objectToAst$1({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: {
					...inheritMeta(schema, childResults),
					isObject: true
				}
			};
		},
		postProcess(result, schema, ctx) {
			if (ctx.plugin.config.metadata && schema.description) return {
				...result,
				expression: result.expression.attr(identifiers.describe).call($.literal(schema.description))
			};
			return result;
		},
		reference($ref, schema, ctx) {
			const z = ctx.plugin.external("zod.z");
			const query = {
				category: "schema",
				resource: "definition",
				resourceId: $ref,
				tool: "zod"
			};
			const refSymbol = ctx.plugin.referenceSymbol(query);
			if (ctx.plugin.isSymbolRegistered(query)) return {
				expression: $(refSymbol),
				meta: defaultMeta(schema)
			};
			return {
				expression: $(z).attr(identifiers.lazy).call($.func().do($(refSymbol).return())),
				meta: {
					...defaultMeta(schema),
					hasLazy: true,
					isLazy: true
				}
			};
		},
		string(schema, ctx) {
			if (shouldCoerceToBigInt(schema.format)) return {
				expression: numberToNode$1({
					plugin: ctx.plugin,
					schema: {
						...schema,
						type: "number"
					}
				}),
				meta: defaultMeta(schema)
			};
			return {
				expression: stringToNode$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		tuple(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = tupleToAst$1({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		undefined(schema, ctx) {
			return {
				expression: undefinedToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		union(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const hasNull = schemas.some((s) => s.type === "null") || items.some((i) => i.meta.nullable);
			const { expression } = unionToAst$1({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: false,
					isLazy: false,
					nullable: hasNull,
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		unknown(schema, ctx) {
			return {
				expression: unknownToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		void(schema, ctx) {
			return {
				expression: voidToAst$1({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		}
	};
}
//#endregion
//#region src/plugins/zod/v3/processor.ts
function createProcessor$1(plugin) {
	const processor = createSchemaProcessor();
	const extractorHooks = [plugin.config["~hooks"]?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract];
	function extractor(ctx) {
		if (processor.hasEmitted(ctx.path)) return ctx.schema;
		for (const hook of extractorHooks) if (typeof hook === "boolean" ? hook : hook?.(ctx) ?? false) {
			process({
				namingAnchor: processor.context.anchor,
				tags: processor.context.tags,
				...ctx
			});
			return { $ref: pathToJsonPointer(ctx.path) };
		}
		return ctx.schema;
	}
	function process(ctx) {
		if (!processor.markEmitted(ctx.path)) return;
		const shouldExport = ctx.export !== false;
		return processor.withContext({
			anchor: ctx.namingAnchor,
			tags: ctx.tags
		}, () => {
			const visitor = createVisitor$1({ schemaExtractor: extractor });
			const result = createSchemaWalker(visitor)(ctx.schema, {
				path: ref(ctx.path),
				plugin
			});
			const final = visitor.applyModifiers(result, {
				path: ref(ctx.path),
				plugin
			});
			if (shouldExport) {
				exportAst({
					...ctx,
					final,
					meta: result.meta.isIntersection ? {
						...ctx.meta,
						isIntersection: true
					} : ctx.meta,
					plugin
				});
				return;
			}
			return final;
		});
	}
	return { process };
}
//#endregion
//#region src/plugins/zod/v3/plugin.ts
const handlerV3 = ({ plugin }) => {
	plugin.symbol("z", {
		external: getZodModule({ plugin }),
		meta: { resource: "zod.z" }
	});
	const processor = createProcessor$1(plugin);
	plugin.forEach("operation", "parameter", "requestBody", "schema", "webhook", (event) => {
		switch (event.type) {
			case "operation":
				irOperationToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
			case "parameter":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.parameter.schema,
					tags: event.tags
				});
				break;
			case "requestBody":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.requestBody.schema,
					tags: event.tags
				});
				break;
			case "schema":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.schema,
					tags: event.tags
				});
				break;
			case "webhook":
				irWebhookToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
		}
	});
};
//#endregion
//#region src/plugins/zod/v4/toAst/unknown.ts
function baseNode$13(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.unknown).call();
}
function unknownResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unknownToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$13 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.unknown;
	return resolver?.(ctx) ?? unknownResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/array.ts
function baseNode$12(ctx) {
	const { applyModifiers, childResults, plugin, schema, symbols } = ctx;
	const { z } = symbols;
	const arrayFn = $(z).attr(identifiers.array);
	let normalizedSchema = schema;
	if (normalizedSchema.items) normalizedSchema = deduplicateSchema({ schema: normalizedSchema });
	if (!normalizedSchema.items) return arrayFn.call(unknownToAst({
		plugin,
		schema: { type: "unknown" }
	}));
	if (childResults.length === 1) {
		const itemNode = applyModifiers(childResults[0], { optional: false }).expression;
		return arrayFn.call(itemNode);
	}
	if (childResults.length > 1) {
		const itemExpressions = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
		const firstSchema = normalizedSchema.items[0];
		if (normalizedSchema.logicalOperator === "and") {
			let intersectionExpression;
			if (firstSchema?.logicalOperator === "or" || firstSchema?.type && firstSchema.type !== "object") intersectionExpression = $(z).attr(identifiers.intersection).call(...itemExpressions);
			else {
				intersectionExpression = itemExpressions[0];
				for (let i = 1; i < itemExpressions.length; i++) intersectionExpression = intersectionExpression.attr(identifiers.and).call(itemExpressions[i]);
			}
			return arrayFn.call(intersectionExpression);
		} else return arrayFn.call($(z).attr(identifiers.union).call($.array(...itemExpressions)));
	}
	return arrayFn.call(unknownToAst({
		plugin,
		schema: { type: "unknown" }
	}));
}
function lengthNode$1(ctx) {
	const { schema } = ctx;
	if (schema.minItems === schema.maxItems && schema.minItems !== void 0) return ctx.chain.current.attr(identifiers.length).call($.fromValue(schema.minItems));
}
function maxLengthNode$1(ctx) {
	const { schema } = ctx;
	if (schema.maxItems === void 0) return;
	return ctx.chain.current.attr(identifiers.max).call($.fromValue(schema.maxItems));
}
function minLengthNode$1(ctx) {
	const { schema } = ctx;
	if (schema.minItems === void 0) return;
	return ctx.chain.current.attr(identifiers.min).call($.fromValue(schema.minItems));
}
function arrayResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	const lengthResult = ctx.nodes.length(ctx);
	if (lengthResult) ctx.chain.current = lengthResult;
	else {
		const minLengthResult = ctx.nodes.minLength(ctx);
		if (minLengthResult) ctx.chain.current = minLengthResult;
		const maxLengthResult = ctx.nodes.maxLength(ctx);
		if (maxLengthResult) ctx.chain.current = maxLengthResult;
	}
	return ctx.chain.current;
}
function arrayToAst({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	let schemaCopy = schema;
	const z = plugin.external("zod.z");
	if (schemaCopy.items) {
		schemaCopy = deduplicateSchema({ schema: schemaCopy });
		schemaCopy.items.forEach((item, index) => {
			const itemResult = walk(item, childContext(walkerCtx, "items", index));
			childResults.push(itemResult);
		});
	}
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$12,
			length: lengthNode$1,
			maxLength: maxLengthNode$1,
			minLength: minLengthNode$1
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.array;
	return {
		childResults,
		expression: resolver?.(ctx) ?? arrayResolver(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v4/toAst/boolean.ts
function baseNode$11(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.boolean).call();
}
function constNode$3(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "boolean") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function booleanResolver(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function booleanToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$11,
			const: constNode$3
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.boolean;
	return resolver?.(ctx) ?? booleanResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/enum.ts
function itemsNode(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	const enumMembers = [];
	const literalMembers = [];
	let isNullable = false;
	let allStrings = true;
	for (const item of schema.items ?? []) if (item.type === "string" && typeof item.const === "string") {
		const literal = $.literal(item.const);
		enumMembers.push(literal);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if ((item.type === "number" || item.type === "integer") && typeof item.const === "number") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "boolean" && typeof item.const === "boolean") {
		allStrings = false;
		const literal = $.literal(item.const);
		literalMembers.push($(z).attr(identifiers.literal).call(literal));
	} else if (item.type === "null" || item.const === null) isNullable = true;
	return {
		allStrings,
		enumMembers,
		isNullable,
		literalMembers
	};
}
function baseNode$10(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	const { allStrings, enumMembers, literalMembers } = ctx.nodes.items(ctx);
	if (allStrings && enumMembers.length) return $(z).attr(identifiers.enum).call($.array(...enumMembers));
	if (literalMembers.length === 1) return literalMembers[0];
	return $(z).attr(identifiers.union).call($.array(...literalMembers));
}
function enumResolver(ctx) {
	const { literalMembers } = ctx.nodes.items(ctx);
	if (!literalMembers.length) return ctx.chain.current;
	const baseExpression = ctx.nodes.base(ctx);
	ctx.chain.current = baseExpression;
	return ctx.chain.current;
}
function enumToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$10,
			items: itemsNode
		},
		plugin,
		schema,
		symbols: { z }
	};
	const { literalMembers } = itemsNode(ctx);
	if (!literalMembers.length) return unknownToAst({
		plugin,
		schema: { type: "unknown" }
	});
	const resolver = plugin.config["~resolvers"]?.enum;
	return resolver?.(ctx) ?? enumResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/intersection.ts
function baseNode$9(ctx) {
	const { childResults, schemas, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.never).call();
	const firstSchema = schemas[0];
	if (firstSchema?.logicalOperator === "or" || firstSchema?.type && firstSchema.type !== "object") return $(z).attr(identifiers.intersection).call(...childResults.map((result) => result.expression));
	let expression = childResults[0].expression;
	childResults.slice(1).forEach((item) => {
		expression = expression.attr(identifiers.and).call(item.meta.hasLazy ? $(z).attr(identifiers.lazy).call($.func().do(item.expression.return())) : item.expression);
	});
	return expression;
}
function intersectionResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function intersectionToAst({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$9 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.intersection;
	return {
		childResults,
		expression: resolver?.(ctx) ?? intersectionResolver(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v4/toAst/never.ts
function baseNode$8(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.never).call();
}
function neverResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function neverToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$8 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.never;
	return resolver?.(ctx) ?? neverResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/null.ts
function baseNode$7(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.null).call();
}
function nullResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function nullToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$7 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.null;
	return resolver?.(ctx) ?? nullResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/number.ts
function baseNode$6(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (ctx.utils.shouldCoerceToBigInt(schema.format)) return $(z).attr(identifiers.coerce).attr(identifiers.bigint).call();
	let chain = $(z).attr(identifiers.number).call();
	if (schema.type === "integer") chain = $(z).attr(identifiers.int).call();
	return chain;
}
function constNode$2(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (schema.const === void 0) return;
	return $(z).attr(identifiers.literal).call(ctx.utils.maybeBigInt(schema.const, schema.format));
}
function maxNode(ctx) {
	const { chain, schema } = ctx;
	if (schema.exclusiveMaximum !== void 0) return chain.current.attr(identifiers.lt).call(ctx.utils.maybeBigInt(schema.exclusiveMaximum, schema.format));
	if (schema.maximum !== void 0) return chain.current.attr(identifiers.lte).call(ctx.utils.maybeBigInt(schema.maximum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return chain.current.attr(identifiers.max).call(ctx.utils.maybeBigInt(limit.maxValue, schema.format), $.object().prop("error", $.literal(limit.maxError)));
}
function minNode(ctx) {
	const { chain, schema } = ctx;
	if (schema.exclusiveMinimum !== void 0) return chain.current.attr(identifiers.gt).call(ctx.utils.maybeBigInt(schema.exclusiveMinimum, schema.format));
	if (schema.minimum !== void 0) return chain.current.attr(identifiers.gte).call(ctx.utils.maybeBigInt(schema.minimum, schema.format));
	const limit = ctx.utils.getIntegerLimit(schema.format);
	if (limit) return chain.current.attr(identifiers.min).call(ctx.utils.maybeBigInt(limit.minValue, schema.format), $.object().prop("error", $.literal(limit.minError)));
}
function numberResolver(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const minNode = ctx.nodes.min(ctx);
	if (minNode) ctx.chain.current = minNode;
	const maxNode = ctx.nodes.max(ctx);
	if (maxNode) ctx.chain.current = maxNode;
	return ctx.chain.current;
}
function numberToNode({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$6,
			const: constNode$2,
			max: maxNode,
			min: minNode
		},
		plugin,
		schema,
		symbols: { z },
		utils: {
			getIntegerLimit,
			maybeBigInt,
			shouldCoerceToBigInt
		}
	};
	const resolver = plugin.config["~resolvers"]?.number;
	return resolver?.(ctx) ?? numberResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/object.ts
function additionalPropertiesNode(ctx) {
	const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx;
	if (!schema.additionalProperties || schema.properties && Object.keys(schema.properties).length) return;
	const additionalResult = walk(schema.additionalProperties, childContext(walkerCtx, "additionalProperties"));
	_childResults.push(additionalResult);
	return applyModifiers(additionalResult, {}).expression;
}
function baseNode$5(ctx) {
	const { nodes, symbols } = ctx;
	const { z } = symbols;
	const additional = nodes.additionalProperties(ctx);
	const shape = nodes.shape(ctx);
	if (additional) return $(z).attr(identifiers.record).call($(z).attr(identifiers.string).call(), additional);
	return $(z).attr(identifiers.object).call(shape);
}
function objectResolver(ctx) {
	return ctx.nodes.base(ctx);
}
function shapeNode(ctx) {
	const { _childResults, applyModifiers, schema, walk, walkerCtx } = ctx;
	const shape = $.object().pretty();
	for (const name in schema.properties) {
		const property = schema.properties[name];
		const isOptional = !schema.required?.includes(name);
		const propertyResult = walk(property, childContext(walkerCtx, "properties", name));
		_childResults.push(propertyResult);
		const finalExpr = applyModifiers(propertyResult, { optional: isOptional });
		shape.prop(name, finalExpr.expression);
	}
	return shape;
}
function objectToAst(options) {
	const { applyModifiers, plugin, schema, walk, walkerCtx } = options;
	const childResults = [];
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		_childResults: childResults,
		applyModifiers,
		chain: { current: $(z) },
		nodes: {
			additionalProperties: additionalPropertiesNode,
			base: baseNode$5,
			shape: shapeNode
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.object;
	return {
		childResults,
		expression: resolver?.(ctx) ?? objectResolver(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v4/toAst/string.ts
function baseNode$4(ctx) {
	const { z } = ctx.symbols;
	return $(z).attr(identifiers.string).call();
}
function constNode$1(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (typeof schema.const !== "string") return;
	return $(z).attr(identifiers.literal).call($.literal(schema.const));
}
function formatNode(ctx) {
	const { plugin, schema, symbols } = ctx;
	const { z } = symbols;
	switch (schema.format) {
		case "date": return $(z).attr(identifiers.iso).attr(identifiers.date).call();
		case "date-time": {
			const obj = $.object().$if(plugin.config.dates.offset, (o) => o.prop("offset", $.literal(true))).$if(plugin.config.dates.local, (o) => o.prop("local", $.literal(true)));
			return $(z).attr(identifiers.iso).attr(identifiers.datetime).call(obj.hasProps() ? obj : void 0);
		}
		case "email": return $(z).attr(identifiers.email).call();
		case "guid": return $(z).attr(identifiers.guid).call();
		case "ipv4": return $(z).attr(identifiers.ipv4).call();
		case "ipv6": return $(z).attr(identifiers.ipv6).call();
		case "time": return $(z).attr(identifiers.iso).attr(identifiers.time).call();
		case "uri": return $(z).attr(identifiers.url).call();
		case "uuid": return $(z).attr(identifiers.uuid).call();
	}
}
function lengthNode(ctx) {
	const { chain, schema } = ctx;
	if (schema.minLength === void 0 || schema.minLength !== schema.maxLength) return;
	return chain.current.attr(identifiers.length).call($.literal(schema.minLength));
}
function maxLengthNode(ctx) {
	const { chain, schema } = ctx;
	if (schema.maxLength === void 0) return;
	return chain.current.attr(identifiers.max).call($.literal(schema.maxLength));
}
function minLengthNode(ctx) {
	const { chain, schema } = ctx;
	if (schema.minLength === void 0) return;
	return chain.current.attr(identifiers.min).call($.literal(schema.minLength));
}
function patternNode(ctx) {
	const { chain, schema } = ctx;
	if (!schema.pattern) return;
	const flags = /\\[pP]\{/.test(schema.pattern) ? "u" : void 0;
	return chain.current.attr(identifiers.regex).call($.regexp(schema.pattern, flags));
}
function stringResolver(ctx) {
	const constNode = ctx.nodes.const(ctx);
	if (constNode) {
		ctx.chain.current = constNode;
		return ctx.chain.current;
	}
	const baseNode = ctx.nodes.base(ctx);
	if (baseNode) ctx.chain.current = baseNode;
	const formatNode = ctx.nodes.format(ctx);
	if (formatNode) ctx.chain.current = formatNode;
	const lengthNode = ctx.nodes.length(ctx);
	if (lengthNode) ctx.chain.current = lengthNode;
	else {
		const minLengthNode = ctx.nodes.minLength(ctx);
		if (minLengthNode) ctx.chain.current = minLengthNode;
		const maxLengthNode = ctx.nodes.maxLength(ctx);
		if (maxLengthNode) ctx.chain.current = maxLengthNode;
	}
	const patternNode = ctx.nodes.pattern(ctx);
	if (patternNode) ctx.chain.current = patternNode;
	return ctx.chain.current;
}
function stringToNode({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: {
			base: baseNode$4,
			const: constNode$1,
			format: formatNode,
			length: lengthNode,
			maxLength: maxLengthNode,
			minLength: minLengthNode,
			pattern: patternNode
		},
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.string;
	return resolver?.(ctx) ?? stringResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/tuple.ts
function baseNode$3(ctx) {
	const { applyModifiers, childResults, symbols } = ctx;
	const { z } = symbols;
	const tupleFn = $(z).attr(identifiers.tuple);
	if (!childResults.length) return tupleFn.call($.array());
	const tupleElements = childResults.map((result) => applyModifiers(result, { optional: false }).expression);
	return tupleFn.call($.array(...tupleElements));
}
function constNode(ctx) {
	const { schema, symbols } = ctx;
	const { z } = symbols;
	if (!schema.const || !Array.isArray(schema.const)) return;
	const tupleElements = schema.const.map((value) => $(z).attr(identifiers.literal).call($.fromValue(value)));
	return $(z).attr(identifiers.tuple).call($.array(...tupleElements));
}
function tupleResolver(ctx) {
	const constResult = ctx.nodes.const(ctx);
	if (constResult) {
		ctx.chain.current = constResult;
		return ctx.chain.current;
	}
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function tupleToAst({ applyModifiers, plugin, schema, walk, walkerCtx }) {
	const childResults = [];
	const z = plugin.external("zod.z");
	if (schema.items) schema.items.forEach((item, index) => {
		const itemResult = walk(item, childContext(walkerCtx, "items", index));
		childResults.push(itemResult);
	});
	const ctx = {
		$,
		applyModifiers,
		chain: { current: $(z) },
		childResults,
		nodes: {
			base: baseNode$3,
			const: constNode
		},
		plugin,
		schema,
		symbols: { z },
		walk,
		walkerCtx
	};
	const resolver = plugin.config["~resolvers"]?.tuple;
	return {
		childResults,
		expression: resolver?.(ctx) ?? tupleResolver(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v4/toAst/undefined.ts
function baseNode$2(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.undefined).call();
}
function undefinedResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function undefinedToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode$2 },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.undefined;
	return resolver?.(ctx) ?? undefinedResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/toAst/union.ts
function baseNode$1(ctx) {
	const { childResults, parentSchema, plugin, schemas, symbols } = ctx;
	const { z } = symbols;
	if (!childResults.length) return $(z).attr(identifiers.null).call();
	const nonNullItems = [];
	childResults.forEach((result, index) => {
		const schema = schemas[index];
		if (schema.type !== "null" && schema.const !== null) nonNullItems.push(result);
	});
	let expression;
	if (!nonNullItems.length) expression = $(z).attr(identifiers.null).call();
	else if (nonNullItems.length === 1) expression = nonNullItems[0].expression;
	else {
		const discriminatedExpression = tryBuildDiscriminatedUnion({
			items: childResults,
			parentSchema,
			plugin,
			schemas
		});
		if (discriminatedExpression) {
			const unionMembers = discriminatedExpression.members.map((member) => member.refExpression.attr(identifiers.extend).call($.object().prop(discriminatedExpression.discriminatorKey, $(z).attr(identifiers.literal).call($.fromValue(member.discriminatedValue)))));
			expression = $(z).attr(identifiers.discriminatedUnion).call($.literal(discriminatedExpression.discriminatorKey), $.array().pretty().elements(...unionMembers));
		} else expression = $(z).attr(identifiers.union).call($.array().pretty().elements(...nonNullItems.map((item) => item.expression)));
	}
	return expression;
}
function unionResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function unionToAst({ childResults, parentSchema, plugin, schemas }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		childResults,
		nodes: { base: baseNode$1 },
		parentSchema,
		plugin,
		schema: parentSchema,
		schemas,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.union;
	return {
		childResults,
		expression: resolver?.(ctx) ?? unionResolver(ctx)
	};
}
//#endregion
//#region src/plugins/zod/v4/toAst/void.ts
function baseNode(ctx) {
	const { symbols } = ctx;
	const { z } = symbols;
	return $(z).attr(identifiers.void).call();
}
function voidResolver(ctx) {
	const baseResult = ctx.nodes.base(ctx);
	ctx.chain.current = baseResult;
	return ctx.chain.current;
}
function voidToAst({ plugin, schema }) {
	const z = plugin.external("zod.z");
	const ctx = {
		$,
		chain: { current: $(z) },
		nodes: { base: baseNode },
		plugin,
		schema,
		symbols: { z }
	};
	const resolver = plugin.config["~resolvers"]?.void;
	return resolver?.(ctx) ?? voidResolver(ctx);
}
//#endregion
//#region src/plugins/zod/v4/walker.ts
function getDefaultValue(meta) {
	return meta.format ? maybeBigInt(meta.default, meta.format) : $.fromValue(meta.default);
}
function createVisitor(config = {}) {
	const { schemaExtractor } = config;
	return {
		applyModifiers(result, ctx, options = {}) {
			const { optional } = options;
			let expression = result.expression;
			if (result.meta.readonly) expression = expression.attr(identifiers.readonly).call();
			const needsDefault = result.meta.default !== void 0;
			const needsNullable = result.meta.nullable;
			if (optional && needsNullable) expression = expression.attr(identifiers.nullish).call();
			else if (optional) expression = expression.attr(identifiers.optional).call();
			else if (needsNullable) expression = expression.attr(identifiers.nullable).call();
			if (needsDefault) expression = expression.attr(identifiers.default).call(getDefaultValue(result.meta));
			return { expression };
		},
		array(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = arrayToAst({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		boolean(schema, ctx) {
			return {
				expression: booleanToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		enum(schema, ctx) {
			const expression = enumToAst({
				plugin: ctx.plugin,
				schema
			});
			const hasNull = schema.items?.some((item) => item.type === "null" || item.const === null) ?? false;
			return {
				expression,
				meta: {
					...defaultMeta(schema),
					nullable: hasNull
				}
			};
		},
		integer(schema, ctx) {
			return {
				expression: numberToNode({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		intercept(schema, ctx, walk) {
			if (schemaExtractor && !schema.$ref) {
				const extracted = schemaExtractor({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(fromRef(ctx.path))
					},
					naming: ctx.plugin.config.definitions,
					path: fromRef(ctx.path),
					plugin: ctx.plugin,
					schema
				});
				if (extracted !== schema) return walk(extracted, ctx);
			}
			if (schema.symbolRef) return {
				expression: $(schema.symbolRef),
				meta: defaultMeta(schema)
			};
		},
		intersection(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const { expression } = intersectionToAst({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: true,
					isLazy: false,
					nullable: items.some((i) => i.meta.nullable),
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		never(schema, ctx) {
			return {
				expression: neverToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		null(schema, ctx) {
			return {
				expression: nullToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		number(schema, ctx) {
			return {
				expression: numberToNode({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					format: schema.format
				}
			};
		},
		object(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = objectToAst({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		postProcess(result, schema, ctx) {
			const { metadata } = ctx.plugin.config;
			if (!metadata) return result;
			const node = $.object();
			if (metadata === true) {
				if (!schema.description) return result;
				node.pretty().prop("description", $.literal(schema.description));
			} else metadata({
				$,
				node,
				schema
			});
			if (node.isEmpty) return result;
			const z = ctx.plugin.external("zod.z");
			return {
				...result,
				expression: result.expression.attr(identifiers.register).call($(z).attr(identifiers.globalRegistry), node)
			};
		},
		reference($ref, schema, ctx) {
			const z = ctx.plugin.external("zod.z");
			const query = {
				category: "schema",
				resource: "definition",
				resourceId: $ref,
				tool: "zod"
			};
			const refSymbol = ctx.plugin.referenceSymbol(query);
			if (ctx.plugin.isSymbolRegistered(query)) return {
				expression: $(refSymbol),
				meta: defaultMeta(schema)
			};
			return {
				expression: $(z).attr(identifiers.lazy).call($.func().returns("any").do($(refSymbol).return())),
				meta: {
					...defaultMeta(schema),
					hasLazy: true,
					isLazy: true
				}
			};
		},
		string(schema, ctx) {
			if (shouldCoerceToBigInt(schema.format)) return {
				expression: numberToNode({
					plugin: ctx.plugin,
					schema: {
						...schema,
						type: "number"
					}
				}),
				meta: defaultMeta(schema)
			};
			return {
				expression: stringToNode({
					plugin: ctx.plugin,
					schema
				}),
				meta: defaultMeta(schema)
			};
		},
		tuple(schema, ctx, walk) {
			const applyModifiers = (result, opts) => this.applyModifiers(result, ctx, opts);
			const { childResults, expression } = tupleToAst({
				applyModifiers,
				plugin: ctx.plugin,
				schema,
				walk,
				walkerCtx: ctx
			});
			return {
				expression,
				meta: inheritMeta(schema, childResults)
			};
		},
		undefined(schema, ctx) {
			return {
				expression: undefinedToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		union(items, schemas, parentSchema, ctx) {
			const hasAnyLazy = items.some((item) => item.meta.hasLazy);
			const hasNull = schemas.some((s) => s.type === "null") || items.some((i) => i.meta.nullable);
			const { expression } = unionToAst({
				childResults: items,
				parentSchema,
				plugin: ctx.plugin,
				schemas
			});
			return {
				expression,
				meta: {
					default: parentSchema.default,
					format: parentSchema.format,
					hasLazy: hasAnyLazy,
					isIntersection: false,
					isLazy: false,
					nullable: hasNull,
					readonly: items.some((i) => i.meta.readonly)
				}
			};
		},
		unknown(schema, ctx) {
			return {
				expression: unknownToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		},
		void(schema, ctx) {
			return {
				expression: voidToAst({
					plugin: ctx.plugin,
					schema
				}),
				meta: {
					...defaultMeta(schema),
					nullable: false,
					readonly: false
				}
			};
		}
	};
}
//#endregion
//#region src/plugins/zod/v4/processor.ts
function createProcessor(plugin) {
	const processor = createSchemaProcessor();
	const extractorHooks = [plugin.config["~hooks"]?.schemas?.shouldExtract, plugin.context.config.parser.hooks.schemas?.shouldExtract];
	function extractor(ctx) {
		if (processor.hasEmitted(ctx.path)) return ctx.schema;
		for (const hook of extractorHooks) if (typeof hook === "boolean" ? hook : hook?.(ctx) ?? false) {
			process({
				namingAnchor: processor.context.anchor,
				tags: processor.context.tags,
				...ctx
			});
			return { $ref: pathToJsonPointer(ctx.path) };
		}
		return ctx.schema;
	}
	function process(ctx) {
		if (!processor.markEmitted(ctx.path)) return;
		const shouldExport = ctx.export !== false;
		return processor.withContext({
			anchor: ctx.namingAnchor,
			tags: ctx.tags
		}, () => {
			const visitor = createVisitor({ schemaExtractor: extractor });
			const result = createSchemaWalker(visitor)(ctx.schema, {
				path: ref(ctx.path),
				plugin
			});
			const final = visitor.applyModifiers(result, {
				path: ref(ctx.path),
				plugin
			});
			if (shouldExport) {
				exportAst({
					...ctx,
					final,
					meta: result.meta.isIntersection ? {
						...ctx.meta,
						isIntersection: true
					} : ctx.meta,
					plugin
				});
				return;
			}
			return final;
		});
	}
	return { process };
}
//#endregion
//#region src/plugins/zod/v4/plugin.ts
const handlerV4 = ({ plugin }) => {
	plugin.symbol("z", {
		external: getZodModule({ plugin }),
		importKind: "namespace",
		meta: { resource: "zod.z" }
	});
	const processor = createProcessor(plugin);
	plugin.forEach("operation", "parameter", "requestBody", "schema", "webhook", (event) => {
		switch (event.type) {
			case "operation":
				irOperationToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
			case "parameter":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.parameter.schema,
					tags: event.tags
				});
				break;
			case "requestBody":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.requestBody.schema,
					tags: event.tags
				});
				break;
			case "schema":
				processor.process({
					meta: {
						resource: "definition",
						resourceId: pathToJsonPointer(event._path)
					},
					naming: plugin.config.definitions,
					path: event._path,
					plugin,
					schema: event.schema,
					tags: event.tags
				});
				break;
			case "webhook":
				irWebhookToAst({
					operation: event.operation,
					path: event._path,
					plugin,
					processor,
					tags: event.tags
				});
				break;
		}
	});
};
//#endregion
//#region src/plugins/zod/plugin.ts
const handler = (args) => {
	const { plugin } = args;
	switch (plugin.config.compatibilityVersion) {
		case 3: return handlerV3(args);
		case "mini": return handlerMini(args);
		default: return handlerV4(args);
	}
};
//#endregion
//#region src/plugins/zod/config.ts
const defaultConfig = {
	api: new Api(),
	config: {
		case: "camelCase",
		comments: true,
		includeInEntry: false,
		metadata: false
	},
	handler,
	name: "zod",
	resolveConfig: (plugin, context) => {
		const packageName = "zod";
		const version = context.package.getVersion(packageName);
		const inferCompatibleVersion = () => {
			if (version && (version.major === 4 || version.major === 3)) return version.major;
			return 4;
		};
		const ensureCompatibleVersion = (compatibilityVersion) => {
			if (!compatibilityVersion) return inferCompatibleVersion();
			if (!version) return compatibilityVersion;
			if (compatibilityVersion === 4 || compatibilityVersion === 3 || compatibilityVersion === "mini") {
				if (!context.package.satisfies(version, ">=3.25.0 <5.0.0")) {
					const compatibleVersion = inferCompatibleVersion();
					console.warn(`🔌 ${colors.yellow("Warning:")} Installed ${colors.cyan(packageName)} ${colors.cyan(`v${version.version}`)} does not support compatibility version ${colors.yellow(String(compatibilityVersion))}, using ${colors.yellow(String(compatibleVersion))}.`);
					return compatibleVersion;
				}
			}
			return compatibilityVersion;
		};
		plugin.config.compatibilityVersion = ensureCompatibleVersion(plugin.config.compatibilityVersion);
		plugin.config.dates = context.valueToObject({
			defaultValue: {
				local: false,
				offset: false
			},
			value: plugin.config.dates
		});
		plugin.config.types = context.valueToObject({
			defaultValue: {
				infer: {
					case: "PascalCase",
					enabled: false
				},
				input: {
					case: "PascalCase",
					enabled: false
				},
				output: {
					case: "PascalCase",
					enabled: false
				}
			},
			mappers: { object: (fields, defaultValue) => ({
				...fields,
				infer: context.valueToObject({
					defaultValue: {
						...defaultValue.infer,
						enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
					},
					mappers,
					value: fields.infer
				}),
				input: context.valueToObject({
					defaultValue: {
						...defaultValue.input,
						enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
					},
					mappers,
					value: fields.input
				}),
				output: context.valueToObject({
					defaultValue: {
						...defaultValue.output,
						enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
					},
					mappers,
					value: fields.output
				})
			}) },
			value: plugin.config.types
		});
		plugin.config.definitions = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "z{{name}}",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}ZodType"
					},
					input: {
						...plugin.config.types.input,
						name: "{{name}}ZodInput"
					},
					output: {
						...plugin.config.types.output,
						name: "{{name}}ZodOutput"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							}),
							input: context.valueToObject({
								defaultValue: {
									...defaultValue.input,
									enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
								},
								mappers,
								value: fields.input
							}),
							output: context.valueToObject({
								defaultValue: {
									...defaultValue.output,
									enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
								},
								mappers,
								value: fields.output
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.definitions
		});
		plugin.config.requests = context.valueToObject({
			defaultValue: {
				body: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "z{{name}}Body",
					types: {
						...plugin.config.types,
						infer: {
							...plugin.config.types.infer,
							name: "{{name}}BodyZodType"
						},
						input: {
							...plugin.config.types.input,
							name: "{{name}}BodyZodInput"
						},
						output: {
							...plugin.config.types.output,
							name: "{{name}}BodyZodOutput"
						}
					}
				},
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				headers: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "z{{name}}Headers",
					types: {
						...plugin.config.types,
						infer: {
							...plugin.config.types.infer,
							name: "{{name}}HeadersZodType"
						},
						input: {
							...plugin.config.types.input,
							name: "{{name}}HeadersZodInput"
						},
						output: {
							...plugin.config.types.output,
							name: "{{name}}HeadersZodOutput"
						}
					}
				},
				name: "z{{name}}Data",
				path: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "z{{name}}Path",
					types: {
						...plugin.config.types,
						infer: {
							...plugin.config.types.infer,
							name: "{{name}}PathZodType"
						},
						input: {
							...plugin.config.types.input,
							name: "{{name}}PathZodInput"
						},
						output: {
							...plugin.config.types.output,
							name: "{{name}}PathZodOutput"
						}
					}
				},
				query: {
					case: plugin.config.case ?? "camelCase",
					enabled: true,
					name: "z{{name}}Query",
					types: {
						...plugin.config.types,
						infer: {
							...plugin.config.types.infer,
							name: "{{name}}QueryZodType"
						},
						input: {
							...plugin.config.types.input,
							name: "{{name}}QueryZodInput"
						},
						output: {
							...plugin.config.types.output,
							name: "{{name}}QueryZodOutput"
						}
					}
				},
				shouldExtract: () => false,
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}DataZodType"
					},
					input: {
						...plugin.config.types.input,
						name: "{{name}}DataZodInput"
					},
					output: {
						...plugin.config.types.output,
						name: "{{name}}DataZodOutput"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					body: context.valueToObject({
						defaultValue: defaultValue.body,
						mappers: {
							...mappers,
							object: (fields, defaultValue) => ({
								...fields,
								types: context.valueToObject({
									defaultValue: defaultValue.types,
									mappers: { object: (fields, defaultValue) => ({
										...fields,
										infer: context.valueToObject({
											defaultValue: {
												...defaultValue.infer,
												enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
											},
											mappers,
											value: fields.infer
										}),
										input: context.valueToObject({
											defaultValue: {
												...defaultValue.input,
												enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
											},
											mappers,
											value: fields.input
										}),
										output: context.valueToObject({
											defaultValue: {
												...defaultValue.output,
												enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
											},
											mappers,
											value: fields.output
										})
									}) },
									value: fields.types
								})
							})
						},
						value: fields.body
					}),
					headers: context.valueToObject({
						defaultValue: defaultValue.headers,
						mappers: {
							...mappers,
							object: (fields, defaultValue) => ({
								...fields,
								types: context.valueToObject({
									defaultValue: defaultValue.types,
									mappers: { object: (fields, defaultValue) => ({
										...fields,
										infer: context.valueToObject({
											defaultValue: {
												...defaultValue.infer,
												enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
											},
											mappers,
											value: fields.infer
										}),
										input: context.valueToObject({
											defaultValue: {
												...defaultValue.input,
												enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
											},
											mappers,
											value: fields.input
										}),
										output: context.valueToObject({
											defaultValue: {
												...defaultValue.output,
												enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
											},
											mappers,
											value: fields.output
										})
									}) },
									value: fields.types
								})
							})
						},
						value: fields.headers
					}),
					path: context.valueToObject({
						defaultValue: defaultValue.path,
						mappers: {
							...mappers,
							object: (fields, defaultValue) => ({
								...fields,
								types: context.valueToObject({
									defaultValue: defaultValue.types,
									mappers: { object: (fields, defaultValue) => ({
										...fields,
										infer: context.valueToObject({
											defaultValue: {
												...defaultValue.infer,
												enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
											},
											mappers,
											value: fields.infer
										}),
										input: context.valueToObject({
											defaultValue: {
												...defaultValue.input,
												enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
											},
											mappers,
											value: fields.input
										}),
										output: context.valueToObject({
											defaultValue: {
												...defaultValue.output,
												enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
											},
											mappers,
											value: fields.output
										})
									}) },
									value: fields.types
								})
							})
						},
						value: fields.path
					}),
					query: context.valueToObject({
						defaultValue: defaultValue.query,
						mappers: {
							...mappers,
							object: (fields, defaultValue) => ({
								...fields,
								types: context.valueToObject({
									defaultValue: defaultValue.types,
									mappers: { object: (fields, defaultValue) => ({
										...fields,
										infer: context.valueToObject({
											defaultValue: {
												...defaultValue.infer,
												enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
											},
											mappers,
											value: fields.infer
										}),
										input: context.valueToObject({
											defaultValue: {
												...defaultValue.input,
												enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
											},
											mappers,
											value: fields.input
										}),
										output: context.valueToObject({
											defaultValue: {
												...defaultValue.output,
												enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
											},
											mappers,
											value: fields.output
										})
									}) },
									value: fields.types
								})
							})
						},
						value: fields.query
					}),
					shouldExtract: fields.shouldExtract !== void 0 ? typeof fields.shouldExtract === "function" ? fields.shouldExtract : () => Boolean(fields.shouldExtract) : defaultValue.shouldExtract,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							}),
							input: context.valueToObject({
								defaultValue: {
									...defaultValue.input,
									enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
								},
								mappers,
								value: fields.input
							}),
							output: context.valueToObject({
								defaultValue: {
									...defaultValue.output,
									enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
								},
								mappers,
								value: fields.output
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.requests
		});
		plugin.config.responses = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "z{{name}}Response",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}ResponseZodType"
					},
					input: {
						...plugin.config.types.input,
						name: "{{name}}ResponseZodInput"
					},
					output: {
						...plugin.config.types.output,
						name: "{{name}}ResponseZodOutput"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							}),
							input: context.valueToObject({
								defaultValue: {
									...defaultValue.input,
									enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
								},
								mappers,
								value: fields.input
							}),
							output: context.valueToObject({
								defaultValue: {
									...defaultValue.output,
									enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
								},
								mappers,
								value: fields.output
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.responses
		});
		plugin.config.webhooks = context.valueToObject({
			defaultValue: {
				case: plugin.config.case ?? "camelCase",
				enabled: true,
				name: "z{{name}}WebhookRequest",
				types: {
					...plugin.config.types,
					infer: {
						...plugin.config.types.infer,
						name: "{{name}}WebhookRequestZodType"
					},
					input: {
						...plugin.config.types.input,
						name: "{{name}}WebhookRequestZodInput"
					},
					output: {
						...plugin.config.types.output,
						name: "{{name}}WebhookRequestZodOutput"
					}
				}
			},
			mappers: {
				...mappers,
				object: (fields, defaultValue) => ({
					...fields,
					types: context.valueToObject({
						defaultValue: defaultValue.types,
						mappers: { object: (fields, defaultValue) => ({
							...fields,
							infer: context.valueToObject({
								defaultValue: {
									...defaultValue.infer,
									enabled: fields.infer !== void 0 ? Boolean(fields.infer) : defaultValue.infer.enabled
								},
								mappers,
								value: fields.infer
							}),
							input: context.valueToObject({
								defaultValue: {
									...defaultValue.input,
									enabled: fields.input !== void 0 ? Boolean(fields.input) : defaultValue.input.enabled
								},
								mappers,
								value: fields.input
							}),
							output: context.valueToObject({
								defaultValue: {
									...defaultValue.output,
									enabled: fields.output !== void 0 ? Boolean(fields.output) : defaultValue.output.enabled
								},
								mappers,
								value: fields.output
							})
						}) },
						value: fields.types
					})
				})
			},
			value: plugin.config.webhooks
		});
	},
	tags: ["validator"]
};
definePluginConfig(defaultConfig);
//#endregion
//#region src/plugins/config.ts
const defaultPluginConfigs = {
	"@angular/common": defaultConfig$26,
	"@faker-js/faker": defaultConfig$25,
	"@hey-api/client-angular": defaultConfig$24,
	"@hey-api/client-axios": defaultConfig$23,
	"@hey-api/client-fetch": defaultConfig$22,
	"@hey-api/client-ky": defaultConfig$21,
	"@hey-api/client-next": defaultConfig$20,
	"@hey-api/client-nuxt": defaultConfig$19,
	"@hey-api/client-ofetch": defaultConfig$18,
	"@hey-api/schemas": defaultConfig$17,
	"@hey-api/sdk": defaultConfig$16,
	"@hey-api/transformers": defaultConfig$15,
	"@hey-api/typescript": defaultConfig$14,
	"@pinia/colada": defaultConfig$13,
	"@tanstack/angular-query-experimental": defaultConfig$12,
	"@tanstack/preact-query": defaultConfig$11,
	"@tanstack/react-query": defaultConfig$10,
	"@tanstack/solid-query": defaultConfig$9,
	"@tanstack/svelte-query": defaultConfig$8,
	"@tanstack/vue-query": defaultConfig$7,
	arktype: defaultConfig$6,
	fastify: defaultConfig$5,
	nestjs: defaultConfig$4,
	orpc: defaultConfig$3,
	swr: defaultConfig$2,
	valibot: defaultConfig$1,
	zod: defaultConfig
};
//#endregion
//#region src/config/plugins.ts
/**
* Default plugins used to generate artifacts if plugins aren't specified.
*/
const defaultPlugins = ["@hey-api/typescript", "@hey-api/sdk"];
function getPluginsConfig({ dependencies, userPlugins, userPluginsConfig }) {
	const circularReferenceTracker = /* @__PURE__ */ new Set();
	const pluginOrder = /* @__PURE__ */ new Set();
	const plugins = {};
	const dfs = (name) => {
		if (circularReferenceTracker.has(name)) throw new Error(`Circular reference detected at '${name}'`);
		if (pluginOrder.has(name)) return;
		circularReferenceTracker.add(name);
		const defaultPlugin = defaultPluginConfigs[name];
		const userPlugin = userPluginsConfig[name];
		if (!defaultPlugin && !userPlugin) throw new Error(`unknown plugin dependency "${name}" - do you need to register a custom plugin with this name?`);
		const plugin = {
			...defaultPlugin,
			...userPlugin,
			config: {
				...defaultPlugin?.config,
				...userPlugin?.config
			},
			dependencies: new Set([...defaultPlugin?.dependencies || [], ...userPlugin?.dependencies || []])
		};
		if (plugin.resolveConfig) {
			const context = {
				package: dependencyFactory(dependencies),
				pluginByTag: (tag, props = {}) => {
					const { defaultPlugin, errorMessage } = props;
					for (const userPlugin of userPlugins) {
						const defaultConfig = defaultPluginConfigs[userPlugin] || userPluginsConfig[userPlugin];
						if (defaultConfig && defaultConfig.tags?.includes(tag) && userPlugin !== name) return userPlugin;
					}
					if (defaultPlugin) {
						const defaultConfig = defaultPluginConfigs[defaultPlugin] || userPluginsConfig[defaultPlugin];
						if (defaultConfig && defaultConfig.tags?.includes(tag) && defaultPlugin !== name) return defaultPlugin;
					}
					throw new Error(errorMessage || `missing plugin - no plugin with tag "${tag}" found`);
				},
				valueToObject
			};
			plugin.resolveConfig(plugin, context);
		}
		for (const dependency of plugin.dependencies) dfs(dependency);
		circularReferenceTracker.delete(name);
		pluginOrder.add(name);
		plugins[name] = plugin;
	};
	for (const name of userPlugins) dfs(name);
	return {
		pluginOrder: Array.from(pluginOrder),
		plugins
	};
}
function isPluginClient(plugin) {
	if (typeof plugin === "string") return plugin.startsWith("@hey-api/client");
	return plugin.name.startsWith("@hey-api/client") || plugin.tags && plugin.tags.includes("client");
}
function getPlugins({ dependencies, userConfig }) {
	const userPluginsConfig = {};
	let definedPlugins = defaultPlugins;
	if (userConfig.plugins) {
		userConfig.plugins = userConfig.plugins.filter((plugin) => typeof plugin === "string" && plugin || typeof plugin !== "string" && plugin.name);
		if (userConfig.plugins.length === 1 && isPluginClient(userConfig.plugins[0])) definedPlugins = [...defaultPlugins, ...userConfig.plugins];
		else definedPlugins = userConfig.plugins;
	}
	warnOnConflictingDuplicatePlugins(definedPlugins);
	return getPluginsConfig({
		dependencies,
		userPlugins: definedPlugins.map((plugin) => {
			if (typeof plugin === "string") return plugin;
			const pluginName = plugin.name;
			if (pluginName) if (plugin.handler) userPluginsConfig[pluginName] = plugin;
			else {
				userPluginsConfig[pluginName] = { config: { ...plugin } };
				delete userPluginsConfig[pluginName].config.name;
			}
			return pluginName;
		}).filter(Boolean),
		userPluginsConfig
	});
}
//#endregion
//#region src/config/resolve.ts
function resolveConfig(validated, dependencies) {
	const logs = getLogs(validated.job.config.logs);
	const input = getInput(validated.job.config);
	const output = getOutput(validated.job.config);
	const parser = getParser(validated.job.config);
	output.path = path.resolve(process.cwd(), output.path);
	let plugins;
	try {
		plugins = getPlugins({
			dependencies,
			userConfig: validated.job.config
		});
	} catch (error) {
		if (error instanceof ConfigError) validated.errors.push(error);
		plugins = {
			pluginOrder: [],
			plugins: {}
		};
	}
	const config = {
		configFile: validated.job.config.configFile ?? "",
		dryRun: validated.job.config.dryRun ?? false,
		input,
		interactive: validated.job.config.interactive ?? detectInteractiveSession(),
		logs,
		output,
		parser,
		pluginOrder: plugins.pluginOrder,
		plugins: plugins.plugins
	};
	if (logs.level === "debug") {
		const jobPrefix = colors.gray(`[Job ${validated.job.index}] `);
		console.warn(`${jobPrefix}${colors.cyan("config:")}`, config);
	}
	return {
		config,
		errors: validated.errors,
		index: validated.job.index
	};
}
//#endregion
//#region src/config/validate.ts
function validateJobs(jobs) {
	return jobs.map((job) => {
		const errors = [];
		const { config } = job;
		if (!getInput(config).length) errors.push(new ConfigError("missing input - which OpenAPI specification should we use to generate your output?"));
		if (!getOutput(config).path) errors.push(new ConfigError("missing output - where should we generate your output?"));
		return {
			errors,
			job
		};
	});
}
//#endregion
//#region src/config/init.ts
/**
* @internal
*/
async function resolveJobs({ logger, userConfigs }) {
	const configs = [];
	let dependencies = {};
	const eventLoad = logger.timeEvent("load");
	for (const userConfig of userConfigs) {
		let configFile;
		if (userConfig.configFile) {
			const parts = userConfig.configFile.split(".");
			configFile = parts.slice(0, parts.length - 1).join(".");
		}
		const loaded = await loadConfigFile({
			configFile,
			logger,
			name: "openapi-ts",
			userConfig
		});
		if (!Object.keys(dependencies).length) dependencies = getProjectDependencies(loaded.foundConfig ? loaded.configFile : void 0);
		configs.push(...loaded.configs);
	}
	eventLoad.timeEnd();
	const eventBuild = logger.timeEvent("build");
	const resolvedJobs = validateJobs(expandToJobs(configs)).map((validated) => resolveConfig(validated, dependencies));
	eventBuild.timeEnd();
	return {
		dependencies,
		jobs: resolvedJobs,
		results: resolvedJobs
	};
}
//#endregion
export { postProcessors as _, clientDefaultConfig as a, TypeScriptRenderer as c, reserved as d, keywords as f, getTypedConfig as g, getClientPlugin as h, generateClientBundle as i, TsDslContext as l, TsDsl as m, defaultPlugins as n, clientDefaultMeta as o, regexp as p, clientPluginHandler as r, $ as s, resolveJobs as t, ctx as u };

//# sourceMappingURL=init-EigcXVTH.mjs.map