const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
const require_helpers = require('./helpers.cjs');
const require_logger = require('./logger.cjs');
const require_journal = require('./journal.cjs');
const require_router = require('./router.cjs');
const require_fixture_loader = require('./fixture-loader.cjs');
const require_sse_writer = require('./sse-writer.cjs');
const require_interruption = require('./interruption.cjs');
const require_chaos = require('./chaos.cjs');
const require_recorder = require('./recorder.cjs');
const require_responses = require('./responses.cjs');
const require_messages = require('./messages.cjs');
const require_gemini = require('./gemini.cjs');
const require_gemini_embeddings = require('./gemini-embeddings.cjs');
const require_bedrock = require('./bedrock.cjs');
const require_bedrock_converse = require('./bedrock-converse.cjs');
const require_gemini_interactions = require('./gemini-interactions.cjs');
const require_embeddings = require('./embeddings.cjs');
const require_transcription = require('./transcription.cjs');
const require_images = require('./images.cjs');
const require_speech = require('./speech.cjs');
const require_video = require('./video.cjs');
const require_fal_audio = require('./fal-audio.cjs');
const require_fal = require('./fal.cjs');
const require_openrouter_video = require('./openrouter-video.cjs');
const require_veo_video = require('./veo-video.cjs');
const require_grok_video = require('./grok-video.cjs');
const require_elevenlabs_audio = require('./elevenlabs-audio.cjs');
const require_ollama = require('./ollama.cjs');
const require_cohere = require('./cohere.cjs');
const require_search = require('./search.cjs');
const require_rerank = require('./rerank.cjs');
const require_moderation = require('./moderation.cjs');
const require_ws_framing = require('./ws-framing.cjs');
const require_ws_responses = require('./ws-responses.cjs');
const require_ws_realtime = require('./ws-realtime.cjs');
const require_ws_gemini_live = require('./ws-gemini-live.cjs');
const require_metrics = require('./metrics.cjs');
let node_http = require("node:http");
node_http = require_runtime.__toESM(node_http);

//#region src/server.ts
const COMPLETIONS_PATH = "/v1/chat/completions";
const RESPONSES_PATH = "/v1/responses";
const REALTIME_PATH = "/v1/realtime";
const GEMINI_LIVE_PATH = "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
const MESSAGES_PATH = "/v1/messages";
const EMBEDDINGS_PATH = "/v1/embeddings";
const COHERE_CHAT_PATH = "/v2/chat";
const COHERE_EMBED_PATH = "/v2/embed";
const SEARCH_PATH = "/search";
const RERANK_PATH = "/v2/rerank";
const MODERATIONS_PATH = "/v1/moderations";
const IMAGES_PATH = "/v1/images/generations";
const IMAGES_EDIT_PATH = "/v1/images/edits";
const IMAGES_VARIATIONS_PATH = "/v1/images/variations";
const SPEECH_PATH = "/v1/audio/speech";
const TRANSCRIPTIONS_PATH = "/v1/audio/transcriptions";
const TRANSLATIONS_PATH = "/v1/audio/translations";
const VIDEOS_PATH = "/v1/videos";
const GEMINI_PREDICT_RE = /^\/v1beta\/models\/([^:]+):predict$/;
const ELEVENLABS_SOUND_GENERATION_PATH = "/v1/sound-generation";
const ELEVENLABS_TTS_RE = /^\/v1\/text-to-speech\/([^/]+)$/;
const ELEVENLABS_MUSIC_RE = /^\/v1\/music(?:\/(.+))?$/;
const FAL_QUEUE_SUBMIT_RE = /^\/fal\/queue\/submit\/(.+)$/;
const FAL_QUEUE_REQUESTS_RE = /^\/fal\/queue\/requests\/(.+)$/;
const FAL_RUN_RE = /^\/fal\/run\/(.+)$/;
const FAL_PREFIX_RE = /^\/fal(?:\/.*)?$/;
const DEFAULT_CHUNK_SIZE = 20;
const COMPAT_SUFFIXES = [
	"/chat/completions",
	"/embeddings",
	"/responses",
	"/audio/speech",
	"/audio/transcriptions",
	"/audio/translations",
	"/images/generations",
	"/images/edits",
	"/images/variations"
];
/**
* Normalize OpenAI-compatible paths with arbitrary prefixes.
* Strips /openai/ prefix and rewrites paths ending in known suffixes to /v1/<suffix>.
* Skips /v1/ (already standard) and /v2/ (Cohere convention).
*/
function normalizeCompatPath(pathname, logger) {
	if (pathname.startsWith("/openai/")) pathname = pathname.slice(7);
	if (!pathname.startsWith("/v1/") && !pathname.startsWith("/v2/")) {
		for (const suffix of COMPAT_SUFFIXES) if (pathname.endsWith(suffix)) {
			if (logger) logger.debug(`Path normalized: ${pathname} → /v1${suffix}`);
			pathname = "/v1" + suffix;
			break;
		}
	}
	return pathname;
}
const GEMINI_INTERACTIONS_PATH = "/v1beta/interactions";
const GEMINI_PATH_RE = /^\/v1beta\/models\/([^:]+):(generateContent|streamGenerateContent)$/;
const GEMINI_EMBED_RE = /^\/v1beta\/models\/([^:]+):embedContent$/;
const AZURE_DEPLOYMENT_RE = /^\/openai\/deployments\/([^/]+)\/(chat\/completions|embeddings)$/;
const BEDROCK_INVOKE_RE = /^\/model\/([^/]+)\/invoke$/;
const BEDROCK_STREAM_RE = /^\/model\/([^/]+)\/invoke-with-response-stream$/;
const BEDROCK_CONVERSE_RE = /^\/model\/([^/]+)\/converse$/;
const BEDROCK_CONVERSE_STREAM_RE = /^\/model\/([^/]+)\/converse-stream$/;
const VERTEX_AI_RE = /^\/v1\/projects\/[^/]+\/locations\/[^/]+\/publishers\/google\/models\/([^/:]+):(generateContent|streamGenerateContent)$/;
const OLLAMA_CHAT_PATH = "/api/chat";
const OLLAMA_GENERATE_PATH = "/api/generate";
const OLLAMA_EMBEDDINGS_PATH = "/api/embeddings";
const OLLAMA_EMBED_PATH = "/api/embed";
const OLLAMA_TAGS_PATH = "/api/tags";
const OPENROUTER_VIDEOS_PATH = "/api/v1/videos";
const OPENROUTER_VIDEO_MODELS_PATH = "/api/v1/videos/models";
const HEALTH_PATH = "/health";
const READY_PATH = "/ready";
const MODELS_PATH = "/v1/models";
const REQUESTS_PATH = "/v1/_requests";
const DEFAULT_MODELS = [
	"gpt-4",
	"gpt-4o",
	"claude-3-5-sonnet-20241022",
	"gemini-2.0-flash",
	"text-embedding-3-small"
];
const CORS_HEADERS = {
	"Access-Control-Allow-Origin": "*",
	"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
	"Access-Control-Allow-Headers": "*"
};
function setCorsHeaders(res) {
	for (const [key, value] of Object.entries(CORS_HEADERS)) res.setHeader(key, value);
}
function handleOptions(res) {
	setCorsHeaders(res);
	res.writeHead(204);
	res.end();
}
function handleNotFound(res, message) {
	setCorsHeaders(res);
	require_sse_writer.writeErrorResponse(res, 404, JSON.stringify({ error: {
		message,
		type: "not_found"
	} }));
}
const CONTROL_PREFIX = "/__aimock";
/**
* Perform a full fixtures reset: clear the fixtures array, journal, video/fal
* generation state, and the interaction/event-id counters, then zero the
* `aimock_fixtures_loaded` gauge. Shared by `/reset/fixtures` and the
* deprecated `/reset` alias.
*/
function performFixturesReset(fixtures, journal, videoStates, openRouterVideoJobs, veoVideoJobs, grokVideoJobs, defaults) {
	fixtures.length = 0;
	journal.clear();
	videoStates.clear();
	openRouterVideoJobs.clear();
	veoVideoJobs.clear();
	grokVideoJobs.clear();
	require_fal_audio.falJobs.clear();
	require_fal.falQueueStates.clear();
	require_gemini_interactions.resetInteractionCounter();
	require_gemini_interactions.resetEventIdCounter();
	if (defaults.registry) defaults.registry.setGauge("aimock_fixtures_loaded", {}, fixtures.length);
}
/**
* Handle requests under `/__aimock/`. Returns `true` if the request was
* handled, `false` if the path doesn't match the control prefix.
*/
async function handleControlAPI(req, res, pathname, fixtures, journal, videoStates, openRouterVideoJobs, veoVideoJobs, grokVideoJobs, defaults) {
	if (!pathname.startsWith(CONTROL_PREFIX)) return false;
	const subPath = pathname.slice(9);
	setCorsHeaders(res);
	if (subPath === "/health" && req.method === "GET") {
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ status: "ok" }));
		return true;
	}
	if (subPath === "/journal" && req.method === "GET") {
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify(journal.getAll()));
		return true;
	}
	if (subPath === "/fixtures" && req.method === "POST") {
		let raw;
		try {
			raw = await require_helpers.readBody(req);
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			defaults.logger.error(`POST /__aimock/fixtures: failed to read body: ${msg}`);
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ error: `Failed to read request body: ${msg}` }));
			return true;
		}
		let parsed;
		try {
			parsed = JSON.parse(raw);
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			defaults.logger.error(`POST /__aimock/fixtures: invalid JSON: ${msg}`);
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ error: `Invalid JSON: ${msg}` }));
			return true;
		}
		if (!Array.isArray(parsed.fixtures)) {
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ error: "Missing or invalid \"fixtures\" array" }));
			return true;
		}
		const converted = parsed.fixtures.map((e) => require_fixture_loader.entryToFixture(e));
		const errors = require_fixture_loader.validateFixtures(converted).filter((i) => i.severity === "error");
		if (errors.length > 0) {
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({
				error: "Validation failed",
				details: errors
			}));
			return true;
		}
		fixtures.push(...converted);
		if (defaults.registry) defaults.registry.setGauge("aimock_fixtures_loaded", {}, fixtures.length);
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ added: converted.length }));
		return true;
	}
	if (subPath === "/fixtures" && req.method === "DELETE") {
		fixtures.length = 0;
		if (defaults.registry) defaults.registry.setGauge("aimock_fixtures_loaded", {}, fixtures.length);
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ cleared: true }));
		return true;
	}
	if (subPath === "/reset/fixtures" && req.method === "POST") {
		performFixturesReset(fixtures, journal, videoStates, openRouterVideoJobs, veoVideoJobs, grokVideoJobs, defaults);
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ reset: true }));
		return true;
	}
	if (subPath === "/reset/journal" && req.method === "POST") {
		journal.clearEntries();
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ reset: true }));
		return true;
	}
	if (subPath === "/reset" && req.method === "POST") {
		performFixturesReset(fixtures, journal, videoStates, openRouterVideoJobs, veoVideoJobs, grokVideoJobs, defaults);
		const deprecation = "POST /__aimock/reset is deprecated; use POST /__aimock/reset/fixtures (full reset) or POST /__aimock/reset/journal (journal only)";
		defaults.logger.warn("POST /__aimock/reset is deprecated; use /__aimock/reset/fixtures or /__aimock/reset/journal");
		res.writeHead(200, {
			"Content-Type": "application/json",
			Deprecation: "true"
		});
		res.end(JSON.stringify({
			reset: true,
			deprecated: true,
			deprecation
		}));
		return true;
	}
	if (subPath === "/error" && req.method === "POST") {
		let raw;
		try {
			raw = await require_helpers.readBody(req);
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			defaults.logger.error(`POST /__aimock/error: failed to read body: ${msg}`);
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ error: `Failed to read request body: ${msg}` }));
			return true;
		}
		let parsed;
		try {
			parsed = JSON.parse(raw);
		} catch (err) {
			const msg = err instanceof Error ? err.message : String(err);
			defaults.logger.error(`POST /__aimock/error: invalid JSON: ${msg}`);
			res.writeHead(400, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ error: `Invalid JSON: ${msg}` }));
			return true;
		}
		const status = parsed.status ?? 500;
		const errorBody = parsed.body;
		const errorFixture = {
			match: { predicate: () => true },
			response: {
				error: {
					message: errorBody?.message ?? "Injected error",
					type: errorBody?.type ?? "server_error",
					code: errorBody?.code
				},
				status
			}
		};
		fixtures.unshift(errorFixture);
		let consumed = false;
		const original = errorFixture.match.predicate;
		errorFixture.match.predicate = (req) => {
			if (consumed) return false;
			const result = original(req);
			if (result) {
				consumed = true;
				queueMicrotask(() => {
					const idx = fixtures.indexOf(errorFixture);
					if (idx !== -1) fixtures.splice(idx, 1);
				});
			}
			return result;
		};
		res.writeHead(200, { "Content-Type": "application/json" });
		res.end(JSON.stringify({ queued: true }));
		return true;
	}
	handleNotFound(res, `Unknown control endpoint: ${pathname}`);
	return true;
}
async function handleCompletions(req, res, fixtures, journal, defaults, modelFallback, providerKey) {
	setCorsHeaders(res);
	let raw;
	try {
		raw = await require_helpers.readBody(req);
	} catch (err) {
		const msg = err instanceof Error ? err.message : "Failed to read request body";
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body: null,
			response: {
				status: 500,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
			message: `Request body read failed: ${msg}`,
			type: "server_error"
		} }));
		return;
	}
	let body;
	try {
		body = JSON.parse(raw);
		if (modelFallback && !body.model) body.model = modelFallback;
	} catch (parseErr) {
		const detail = parseErr instanceof Error ? parseErr.message : "unknown parse error";
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body: null,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: `Malformed JSON: ${detail}`,
			type: "invalid_request_error",
			param: null,
			code: "invalid_json"
		} }));
		return;
	}
	if (!Array.isArray(body.messages)) {
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body: null,
			response: {
				status: 400,
				fixture: null
			}
		});
		require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
			message: "Missing required parameter: 'messages'",
			type: "invalid_request_error",
			param: null,
			code: null
		} }));
		return;
	}
	const method = req.method ?? "POST";
	const path = req.url ?? COMPLETIONS_PATH;
	const flatHeaders = require_helpers.flattenHeaders(req.headers);
	body._endpointType = "chat";
	body._context = require_helpers.getContext(req);
	const testId = require_helpers.getTestId(req);
	const { fixture, skippedBySequenceOrTurn } = require_router.matchFixtureDiagnostic(fixtures, body, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform, require_router.recordMatchOptions(!!(defaults.record && providerKey), defaults.logger));
	if (fixture) {
		journal.incrementFixtureMatchCount(fixture, fixtures, testId);
		defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
	} else {
		const lastUserMsg = body.messages.filter((m) => m.role === "user").pop();
		const snippet = typeof lastUserMsg?.content === "string" ? lastUserMsg.content.slice(0, 80) : "";
		defaults.logger.debug(`No fixture matched for request (model=${body.model ?? "?"}, msg="${snippet}")`);
	}
	const chaosAction = require_chaos.evaluateChaos(fixture, defaults.chaos, req.headers, defaults.logger);
	const chaosContext = {
		method,
		path,
		headers: flatHeaders,
		body
	};
	if (chaosAction === "drop" || chaosAction === "disconnect") {
		require_chaos.applyChaosAction(chaosAction, res, fixture, journal, chaosContext, fixture ? "fixture" : "proxy", defaults.registry);
		return;
	}
	if (fixture && chaosAction === "malformed") {
		require_chaos.applyChaosAction(chaosAction, res, fixture, journal, chaosContext, "fixture", defaults.registry);
		return;
	}
	if (!fixture) {
		if (require_helpers.resolveStrictMode(defaults.strict, req.headers)) {
			const strictStatus = 503;
			const strictMessage = require_helpers.strictNoMatchMessage(skippedBySequenceOrTurn);
			defaults.logger.error(require_helpers.strictNoMatchLogLine(req.method ?? "POST", req.url ?? COMPLETIONS_PATH, skippedBySequenceOrTurn));
			journal.add({
				method: req.method ?? "POST",
				path: req.url ?? COMPLETIONS_PATH,
				headers: require_helpers.flattenHeaders(req.headers),
				body,
				response: {
					status: strictStatus,
					fixture: null,
					...require_helpers.strictOverrideField(defaults.strict, req.headers)
				}
			});
			require_sse_writer.writeErrorResponse(res, strictStatus, JSON.stringify({ error: {
				message: strictMessage,
				type: "invalid_request_error",
				param: null,
				code: "no_fixture_match"
			} }));
			return;
		}
		if (defaults.record && providerKey) {
			const hookOptions = chaosAction === "malformed" ? {
				beforeWriteResponse: () => {
					require_chaos.applyChaosAction(chaosAction, res, null, journal, chaosContext, "proxy", defaults.registry);
					return true;
				},
				onHookBypassed: (reason) => {
					defaults.logger.warn(`[chaos] malformed bypassed on proxy: upstream returned streaming response (${reason})`);
					defaults.registry?.incrementCounter("aimock_chaos_bypassed_total", {
						action: "malformed",
						source: "proxy",
						reason
					});
				}
			} : void 0;
			const outcome = await require_recorder.proxyAndRecord(req, res, body, providerKey, req.url ?? COMPLETIONS_PATH, fixtures, defaults, raw, hookOptions);
			if (outcome === "handled_by_hook") return;
			if (outcome !== "not_configured") {
				journal.add({
					method: req.method ?? "POST",
					path: req.url ?? COMPLETIONS_PATH,
					headers: require_helpers.flattenHeaders(req.headers),
					body,
					response: {
						status: res.statusCode ?? 200,
						fixture: null,
						source: "proxy"
					}
				});
				return;
			}
		}
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status: 404,
				fixture: null,
				...require_helpers.strictOverrideField(defaults.strict, req.headers)
			}
		});
		require_sse_writer.writeErrorResponse(res, 404, JSON.stringify({ error: {
			message: "No fixture matched",
			type: "invalid_request_error",
			param: null,
			code: "no_fixture_match"
		} }));
		return;
	}
	const response = await require_helpers.resolveResponse(fixture, body);
	const latency = fixture.latency ?? defaults.latency;
	const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);
	const includeUsage = body.stream === true && body.stream_options?.include_usage === true;
	if (require_helpers.isErrorResponse(response)) {
		const status = response.status ?? 500;
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status,
				fixture
			}
		});
		require_sse_writer.writeErrorResponse(res, status, require_helpers.serializeErrorResponse(response), { retryAfter: response.retryAfter });
		return;
	}
	if (require_helpers.isAudioResponse(response)) {
		journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status: 422,
				fixture
			}
		});
		require_sse_writer.writeErrorResponse(res, 422, JSON.stringify({ error: {
			message: "Audio responses are not supported on the chat completions endpoint. Use Gemini generateContent or a dedicated audio endpoint.",
			type: "invalid_request_error"
		} }));
		return;
	}
	if (require_helpers.isContentWithToolCallsResponse(response)) {
		if (response.webSearches?.length) defaults.logger.warn("webSearches in fixture response are not supported for Chat Completions API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, body.model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status: 200,
				fixture
			}
		});
		if (body.stream !== true) {
			const completion = require_helpers.buildContentWithToolCallsCompletion(response.content ?? "", response.toolCalls ?? [], body.model, effReasoning, overrides, body.messages);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(completion));
		} else {
			const chunks = require_helpers.buildContentWithToolCallsChunks(response.content ?? "", response.toolCalls ?? [], body.model, chunkSize, effReasoning, overrides, response.blocks);
			const completionText = (response.content ?? "") + (response.toolCalls ?? []).map((tc) => tc.name + tc.arguments).join("");
			const usageChunk = includeUsage ? require_helpers.buildUsageChunk(chunks[0]?.id ?? "chatcmpl-unknown", overrides?.model ?? body.model, chunks[0]?.created ?? Math.floor(Date.now() / 1e3), overrides?.usage ? {
				prompt_tokens: overrides.usage.prompt_tokens ?? 0,
				completion_tokens: overrides.usage.completion_tokens ?? 0,
				total_tokens: overrides.usage.total_tokens ?? (overrides.usage.prompt_tokens ?? 0) + (overrides.usage.completion_tokens ?? 0)
			} : {
				prompt_tokens: require_helpers.estimatePromptTokens(body.messages),
				completion_tokens: require_helpers.estimateTokens(completionText),
				total_tokens: require_helpers.estimatePromptTokens(body.messages) + require_helpers.estimateTokens(completionText)
			}, overrides?.systemFingerprint) : void 0;
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await require_sse_writer.writeSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick,
				usageChunk,
				recordedTimings: fixture.recordedTimings,
				replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	if (require_helpers.isTextResponse(response)) {
		if (response.webSearches?.length) defaults.logger.warn("webSearches in fixture response are not supported for Chat Completions API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, body.model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status: 200,
				fixture
			}
		});
		if (body.stream !== true) {
			const completion = require_helpers.buildTextCompletion(response.content, body.model, effReasoning, overrides, body.messages);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(completion));
		} else {
			const chunks = require_helpers.buildTextChunks(response.content, body.model, chunkSize, effReasoning, overrides);
			const usageChunk = includeUsage ? require_helpers.buildUsageChunk(chunks[0]?.id ?? "chatcmpl-unknown", overrides?.model ?? body.model, chunks[0]?.created ?? Math.floor(Date.now() / 1e3), overrides?.usage ? {
				prompt_tokens: overrides.usage.prompt_tokens ?? 0,
				completion_tokens: overrides.usage.completion_tokens ?? 0,
				total_tokens: overrides.usage.total_tokens ?? (overrides.usage.prompt_tokens ?? 0) + (overrides.usage.completion_tokens ?? 0)
			} : {
				prompt_tokens: require_helpers.estimatePromptTokens(body.messages),
				completion_tokens: require_helpers.estimateTokens(response.content),
				total_tokens: require_helpers.estimatePromptTokens(body.messages) + require_helpers.estimateTokens(response.content)
			}, overrides?.systemFingerprint) : void 0;
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await require_sse_writer.writeSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick,
				usageChunk,
				recordedTimings: fixture.recordedTimings,
				replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	if (require_helpers.isToolCallResponse(response)) {
		if (response.webSearches?.length) defaults.logger.warn("webSearches in fixture response are not supported for Chat Completions API — ignoring");
		const overrides = require_helpers.extractOverrides(response);
		const effectiveStrict = require_helpers.resolveStrictMode(defaults.strict, req.headers);
		const effReasoning = require_helpers.resolveReasoningForModel(response.reasoning, body.model, effectiveStrict, defaults.logger);
		const journalEntry = journal.add({
			method: req.method ?? "POST",
			path: req.url ?? COMPLETIONS_PATH,
			headers: require_helpers.flattenHeaders(req.headers),
			body,
			response: {
				status: 200,
				fixture
			}
		});
		if (body.stream !== true) {
			const completion = require_helpers.buildToolCallCompletion(response.toolCalls, body.model, effReasoning, overrides, body.messages);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify(completion));
		} else {
			const chunks = require_helpers.buildToolCallChunks(response.toolCalls, body.model, chunkSize, effReasoning, overrides);
			const completionText = response.toolCalls.map((tc) => tc.name + tc.arguments).join("");
			const usageChunk = includeUsage ? require_helpers.buildUsageChunk(chunks[0]?.id ?? "chatcmpl-unknown", overrides?.model ?? body.model, chunks[0]?.created ?? Math.floor(Date.now() / 1e3), overrides?.usage ? {
				prompt_tokens: overrides.usage.prompt_tokens ?? 0,
				completion_tokens: overrides.usage.completion_tokens ?? 0,
				total_tokens: overrides.usage.total_tokens ?? (overrides.usage.prompt_tokens ?? 0) + (overrides.usage.completion_tokens ?? 0)
			} : {
				prompt_tokens: require_helpers.estimatePromptTokens(body.messages),
				completion_tokens: require_helpers.estimateTokens(completionText),
				total_tokens: require_helpers.estimatePromptTokens(body.messages) + require_helpers.estimateTokens(completionText)
			}, overrides?.systemFingerprint) : void 0;
			const interruption = require_interruption.createInterruptionSignal(fixture);
			if (!await require_sse_writer.writeSSEStream(res, chunks, {
				latency,
				streamingProfile: fixture.streamingProfile,
				signal: interruption?.signal,
				onChunkSent: interruption?.tick,
				usageChunk,
				recordedTimings: fixture.recordedTimings,
				replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed
			})) {
				if (!res.writableEnded) res.destroy();
				journalEntry.response.interrupted = true;
				journalEntry.response.interruptReason = interruption?.reason();
			}
			interruption?.cleanup();
		}
		return;
	}
	journal.add({
		method: req.method ?? "POST",
		path: req.url ?? COMPLETIONS_PATH,
		headers: require_helpers.flattenHeaders(req.headers),
		body,
		response: {
			status: 500,
			fixture
		}
	});
	require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
		message: "Fixture response did not match any known type",
		type: "server_error"
	} }));
}
async function createServer(fixtures, options, mounts, serviceFixtures) {
	const host = options?.host ?? "127.0.0.1";
	const port = options?.port ?? 0;
	const logger = new require_logger.Logger(options?.logLevel ?? "silent");
	const registry = options?.metrics ? require_metrics.createMetricsRegistry() : void 0;
	const serverOptions = options ?? {};
	const defaults = {
		latency: serverOptions.latency ?? 0,
		chunkSize: Math.max(1, serverOptions.chunkSize ?? DEFAULT_CHUNK_SIZE),
		replaySpeed: serverOptions.replaySpeed ?? 1,
		logger,
		get chaos() {
			return serverOptions.chaos;
		},
		registry,
		get record() {
			return serverOptions.record;
		},
		get strict() {
			return serverOptions.strict;
		},
		get requestTransform() {
			return serverOptions.requestTransform;
		},
		get falQueue() {
			return serverOptions.falQueue;
		},
		get openRouterVideo() {
			return serverOptions.openRouterVideo;
		},
		get veoVideo() {
			return serverOptions.veoVideo;
		},
		get grokVideo() {
			return serverOptions.grokVideo;
		}
	};
	if (options?.chaos) {
		const chaosRates = [
			{
				name: "dropRate",
				value: options.chaos.dropRate
			},
			{
				name: "malformedRate",
				value: options.chaos.malformedRate
			},
			{
				name: "disconnectRate",
				value: options.chaos.disconnectRate
			}
		];
		for (const { name, value } of chaosRates) if (value !== void 0 && (value < 0 || value > 1)) logger.warn(`Chaos ${name} (${value}) is outside 0-1 range — will be clamped at runtime`);
	}
	for (const { name, config } of [
		{
			name: "falQueue",
			config: options?.falQueue
		},
		{
			name: "openRouterVideo",
			config: options?.openRouterVideo
		},
		{
			name: "veoVideo",
			config: options?.veoVideo
		},
		{
			name: "grokVideo",
			config: options?.grokVideo
		}
	]) {
		if (!config) continue;
		for (const field of ["pollsBeforeInProgress", "pollsBeforeCompleted"]) {
			const value = config[field];
			if (value === void 0) continue;
			if (!Number.isFinite(value)) logger.warn(`${name}.${field} (${value}) is not a finite number — treating as unset`);
			else if (!Number.isInteger(value) || value < 0) logger.warn(`${name}.${field} (${value}) is not a non-negative integer — flooring/clamping to a non-negative integer`);
		}
	}
	{
		const cap = options?.record?.openRouterVideo?.maxContentBytes;
		if (cap !== void 0 && (!Number.isInteger(cap) || cap < 0)) logger.warn(`record.openRouterVideo.maxContentBytes (${cap}) is not a non-negative integer — using the default cap (${require_openrouter_video.OPENROUTER_VIDEO_DEFAULT_MAX_CONTENT_BYTES})`);
	}
	const journal = new require_journal.Journal({
		maxEntries: options?.journalMaxEntries ?? 1e3,
		fixtureCountsMaxTestIds: options?.fixtureCountsMaxTestIds ?? 500
	});
	const videoStates = new require_video.VideoStateMap();
	const openRouterVideoJobs = new require_openrouter_video.OpenRouterVideoJobMap();
	const veoVideoJobs = new require_veo_video.VeoVideoJobMap();
	const grokVideoJobs = new require_grok_video.GrokVideoJobMap();
	if (mounts) for (const { handler } of mounts) {
		if (handler.setJournal) handler.setJournal(journal);
		if (registry && handler.setRegistry) handler.setRegistry(registry);
	}
	if (registry) registry.setGauge("aimock_fixtures_loaded", {}, fixtures.length);
	const server = node_http.createServer((req, res) => {
		handleHttpRequest(req, res).catch((err) => {
			const msg = err instanceof Error ? err.message : "Internal error";
			defaults.logger.warn(`Unhandled request error: ${msg}`);
			if (!res.headersSent) {
				res.writeHead(500, { "Content-Type": "application/json" });
				res.end(JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
			} else if (!res.writableEnded) res.end();
		});
	});
	async function handleHttpRequest(req, res) {
		if (req.method === "OPTIONS") {
			handleOptions(res);
			return;
		}
		const startTime = registry ? process.hrtime.bigint() : 0n;
		const parsedUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
		let pathname = parsedUrl.pathname;
		if (registry) res.on("finish", () => {
			try {
				const normalizedPath = require_metrics.normalizePathLabel(pathname);
				const method = req.method ?? "UNKNOWN";
				const status = String(res.statusCode);
				registry.incrementCounter("aimock_requests_total", {
					method,
					path: normalizedPath,
					status
				});
				const elapsed = Number(process.hrtime.bigint() - startTime) / 1e9;
				registry.observeHistogram("aimock_request_duration_seconds", {
					method,
					path: normalizedPath
				}, elapsed);
			} catch (err) {
				defaults.logger.warn("metrics instrumentation error", err);
			}
		});
		if (pathname.startsWith(CONTROL_PREFIX)) {
			await handleControlAPI(req, res, pathname, fixtures, journal, videoStates, openRouterVideoJobs, veoVideoJobs, grokVideoJobs, defaults);
			return;
		}
		if (mounts) {
			for (const { path: mountPath, handler } of mounts) if (pathname === mountPath || pathname.startsWith(mountPath + "/")) {
				const subPath = pathname.slice(mountPath.length) || "/";
				if (await handler.handleRequest(req, res, subPath)) return;
			}
		}
		if (pathname === OLLAMA_CHAT_PATH && req.method === "POST") {
			try {
				await require_ollama.handleOllama(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === OLLAMA_GENERATE_PATH && req.method === "POST") {
			try {
				await require_ollama.handleOllamaGenerate(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if ((pathname === OLLAMA_EMBEDDINGS_PATH || pathname === OLLAMA_EMBED_PATH) && req.method === "POST") {
			try {
				await require_ollama.handleOllamaEmbeddings(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === OLLAMA_TAGS_PATH && req.method === "GET") {
			setCorsHeaders(res);
			const modelIds = /* @__PURE__ */ new Set();
			for (const f of fixtures) if (f.match.model && typeof f.match.model === "string") modelIds.add(f.match.model);
			const models = (modelIds.size > 0 ? [...modelIds] : DEFAULT_MODELS).map((name) => ({
				name,
				model: name,
				modified_at: (/* @__PURE__ */ new Date()).toISOString(),
				size: 0,
				digest: "",
				details: {}
			}));
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ models }));
			return;
		}
		const openRouterVideoContentMatch = pathname.match(require_metrics.OPENROUTER_VIDEO_CONTENT_RE);
		if (openRouterVideoContentMatch && req.method === "GET") {
			try {
				await require_openrouter_video.handleOpenRouterVideoContent(req, res, openRouterVideoContentMatch[1], journal, defaults, setCorsHeaders, openRouterVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`openrouter-video content: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "GET",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`openrouter-video content: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === OPENROUTER_VIDEO_MODELS_PATH && req.method === "GET") {
			try {
				await require_openrouter_video.handleOpenRouterVideoModels(req, res, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`openrouter-video models: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "GET",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`openrouter-video models: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const openRouterVideoStatusMatch = pathname.match(require_metrics.OPENROUTER_VIDEO_STATUS_RE);
		if (openRouterVideoStatusMatch && req.method === "GET") {
			try {
				await require_openrouter_video.handleOpenRouterVideoStatus(req, res, openRouterVideoStatusMatch[1], fixtures, journal, defaults, setCorsHeaders, openRouterVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`openrouter-video status: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "GET",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`openrouter-video status: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === OPENROUTER_VIDEOS_PATH && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_openrouter_video.handleOpenRouterVideoCreate(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders, openRouterVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`openrouter-video submit: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "POST",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`openrouter-video submit: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		let azureDeploymentId;
		const azureMatch = pathname.match(AZURE_DEPLOYMENT_RE);
		if (azureMatch && req.method === "POST") {
			azureDeploymentId = azureMatch[1];
			pathname = `/v1/${azureMatch[2]}`;
		}
		if (!azureDeploymentId) pathname = normalizeCompatPath(pathname, logger);
		if (pathname === HEALTH_PATH && req.method === "GET") {
			setCorsHeaders(res);
			if (mounts && mounts.length > 0) {
				const services = { llm: {
					status: "ok",
					fixtures: fixtures.length
				} };
				for (const { path: mountPath, handler } of mounts) if (handler.health) {
					const name = mountPath.replace(/^\//, "");
					services[name] = handler.health();
				}
				res.writeHead(200, { "Content-Type": "application/json" });
				res.end(JSON.stringify({
					status: "ok",
					services
				}));
			} else {
				res.writeHead(200, { "Content-Type": "application/json" });
				res.end(JSON.stringify({ status: "ok" }));
			}
			return;
		}
		if (pathname === READY_PATH && req.method === "GET") {
			setCorsHeaders(res);
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify({ status: "ready" }));
			return;
		}
		if (pathname === "/metrics" && req.method === "GET") {
			if (!registry) {
				handleNotFound(res, "Not found");
				return;
			}
			setCorsHeaders(res);
			res.writeHead(200, { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" });
			res.end(registry.serialize());
			return;
		}
		if (pathname === MODELS_PATH && req.method === "GET") {
			setCorsHeaders(res);
			const modelIds = /* @__PURE__ */ new Set();
			for (const f of fixtures) if (f.match.model && typeof f.match.model === "string") modelIds.add(f.match.model);
			const data = (modelIds.size > 0 ? [...modelIds] : DEFAULT_MODELS).map((id) => ({
				id,
				object: "model",
				created: 1686935002,
				owned_by: "aimock"
			}));
			res.writeHead(200, { "Content-Type": "application/json" });
			res.end(JSON.stringify({
				object: "list",
				data
			}));
			return;
		}
		if (pathname === REQUESTS_PATH) {
			setCorsHeaders(res);
			if (req.method === "GET") {
				const limitParam = parsedUrl.searchParams.get("limit");
				let opts;
				if (limitParam) {
					const limit = parseInt(limitParam, 10);
					if (Number.isNaN(limit) || limit <= 0) {
						require_sse_writer.writeErrorResponse(res, 400, JSON.stringify({ error: {
							message: `Invalid limit parameter: "${limitParam}"`,
							type: "invalid_request_error"
						} }));
						return;
					}
					opts = { limit };
				}
				const entries = journal.getAll(opts);
				res.writeHead(200, { "Content-Type": "application/json" });
				res.end(JSON.stringify(entries));
				return;
			}
			if (req.method === "DELETE") {
				journal.clearEntries();
				res.writeHead(204);
				res.end();
				return;
			}
			handleNotFound(res, "Not found");
			return;
		}
		if (pathname === RESPONSES_PATH && req.method === "POST") {
			try {
				await require_responses.handleResponses(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`event: error\ndata: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		if (pathname === MESSAGES_PATH && req.method === "POST") {
			try {
				await require_messages.handleMessages(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`event: error\ndata: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		if (pathname === COHERE_CHAT_PATH && req.method === "POST") {
			try {
				await require_cohere.handleCohere(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`event: error\ndata: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		if (pathname === COHERE_EMBED_PATH && req.method === "POST") {
			try {
				await require_cohere.handleCohereEmbed(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === EMBEDDINGS_PATH && req.method === "POST") {
			try {
				const deploymentId = azureDeploymentId;
				const embeddingsProvider = azureDeploymentId ? "azure" : "openai";
				let raw = await require_helpers.readBody(req);
				if (deploymentId) try {
					const parsed = JSON.parse(raw);
					if (!parsed.model) {
						parsed.model = deploymentId;
						raw = JSON.stringify(parsed);
					}
				} catch (err) {
					if (!(err instanceof SyntaxError)) defaults.logger.error(`Unexpected error in Azure model injection: ${err instanceof Error ? err.message : String(err)}`);
				}
				await require_embeddings.handleEmbeddings(req, res, raw, fixtures, journal, defaults, setCorsHeaders, embeddingsProvider);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === IMAGES_PATH && req.method === "POST") {
			try {
				await require_images.handleImages(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === IMAGES_EDIT_PATH && req.method === "POST") {
			try {
				await require_images.handleImageEdit(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === IMAGES_VARIATIONS_PATH && req.method === "POST") {
			try {
				await require_images.handleImageVariations(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === SPEECH_PATH && req.method === "POST") {
			try {
				await require_speech.handleSpeech(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === TRANSCRIPTIONS_PATH && req.method === "POST") {
			try {
				await require_transcription.handleTranscription(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === TRANSLATIONS_PATH && req.method === "POST") {
			try {
				await require_transcription.handleTranscription(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders, "translation");
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === require_metrics.GROK_VIDEO_SUBMIT_PATH && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_grok_video.handleGrokVideoCreate(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders, grokVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`grok-video submit: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "POST",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`grok-video submit: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === VIDEOS_PATH && req.method === "POST") {
			try {
				await require_video.handleVideoCreate(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders, videoStates);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const grokVideoStatusMatch = pathname.match(require_metrics.GROK_VIDEO_STATUS_RE);
		if (grokVideoStatusMatch && grokVideoStatusMatch[1] !== "generations" && req.method === "GET") {
			try {
				await require_grok_video.handleGrokVideoStatus(req, res, grokVideoStatusMatch[1], fixtures, journal, defaults, setCorsHeaders, grokVideoJobs, videoStates);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`grok-video status: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "GET",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`grok-video status: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const veoPredictMatch = pathname.match(require_metrics.VEO_PREDICT_LRO_RE);
		if (veoPredictMatch && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_veo_video.handleVeoVideoCreate(req, res, await require_helpers.readBody(req), veoPredictMatch[1], fixtures, journal, defaults, setCorsHeaders, veoVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`veo-video submit: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "POST",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`veo-video submit: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const veoOperationMatch = pathname.match(require_metrics.VEO_OPERATION_RE);
		if (veoOperationMatch && req.method === "GET") {
			try {
				await require_veo_video.handleVeoVideoStatus(req, res, veoOperationMatch[1], fixtures, journal, defaults, setCorsHeaders, veoVideoJobs);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				defaults.logger.error(`veo-video status: ${msg}`);
				if (!res.headersSent) {
					try {
						journal.add({
							method: req.method ?? "GET",
							path: req.url ?? pathname,
							headers: require_helpers.flattenHeaders(req.headers),
							body: null,
							response: {
								status: 500,
								fixture: null
							}
						});
					} catch (jErr) {
						defaults.logger.warn(`veo-video status: journal write failed after handler error: ${jErr instanceof Error ? jErr.message : String(jErr)}`);
					}
					require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
						message: msg,
						type: "server_error"
					} }));
				} else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const geminiPredictMatch = pathname.match(GEMINI_PREDICT_RE);
		if (geminiPredictMatch && req.method === "POST") {
			const predictModel = geminiPredictMatch[1];
			try {
				await require_images.handleImages(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders, "gemini", predictModel);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === GEMINI_INTERACTIONS_PATH && req.method === "POST") {
			try {
				await require_gemini_interactions.handleGeminiInteractions(req, res, await require_helpers.readBody(req), fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`data: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		const geminiEmbedMatch = pathname.match(GEMINI_EMBED_RE);
		if (geminiEmbedMatch && req.method === "POST") {
			const embedModel = geminiEmbedMatch[1];
			try {
				await require_gemini_embeddings.handleGeminiEmbedContent(req, res, await require_helpers.readBody(req), embedModel, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const geminiMatch = pathname.match(GEMINI_PATH_RE);
		if (geminiMatch && req.method === "POST") {
			const geminiModel = geminiMatch[1];
			const streaming = geminiMatch[2] === "streamGenerateContent";
			try {
				await require_gemini.handleGemini(req, res, await require_helpers.readBody(req), geminiModel, streaming, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`data: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		const vertexMatch = pathname.match(VERTEX_AI_RE);
		if (vertexMatch && req.method === "POST") {
			const vertexModel = vertexMatch[1];
			const streaming = vertexMatch[2] === "streamGenerateContent";
			try {
				await require_gemini.handleGemini(req, res, await require_helpers.readBody(req), vertexModel, streaming, fixtures, journal, defaults, setCorsHeaders, "vertexai");
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) try {
					res.write(`data: ${JSON.stringify({ error: { message: msg } })}\n\n`);
					res.end();
				} catch (writeErr) {
					logger.debug("Failed to write error recovery response:", writeErr);
				}
			}
			return;
		}
		const bedrockMatch = pathname.match(BEDROCK_INVOKE_RE);
		if (bedrockMatch && req.method === "POST") {
			const bedrockModelId = bedrockMatch[1];
			try {
				await require_bedrock.handleBedrock(req, res, await require_helpers.readBody(req), bedrockModelId, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const bedrockStreamMatch = pathname.match(BEDROCK_STREAM_RE);
		if (bedrockStreamMatch && req.method === "POST") {
			const bedrockModelId = bedrockStreamMatch[1];
			try {
				await require_bedrock.handleBedrockStream(req, res, await require_helpers.readBody(req), bedrockModelId, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const converseMatch = pathname.match(BEDROCK_CONVERSE_RE);
		if (converseMatch && req.method === "POST") {
			const converseModelId = converseMatch[1];
			try {
				await require_bedrock_converse.handleConverse(req, res, await require_helpers.readBody(req), converseModelId, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const converseStreamMatch = pathname.match(BEDROCK_CONVERSE_STREAM_RE);
		if (converseStreamMatch && req.method === "POST") {
			const converseStreamModelId = converseStreamMatch[1];
			try {
				await require_bedrock_converse.handleConverseStream(req, res, await require_helpers.readBody(req), converseStreamModelId, fixtures, journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === SEARCH_PATH && req.method === "POST") {
			try {
				await require_search.handleSearch(req, res, await require_helpers.readBody(req), serviceFixtures?.search ?? [], journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === RERANK_PATH && req.method === "POST") {
			try {
				await require_rerank.handleRerank(req, res, await require_helpers.readBody(req), serviceFixtures?.rerank ?? [], journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === MODERATIONS_PATH && req.method === "POST") {
			try {
				await require_moderation.handleModeration(req, res, await require_helpers.readBody(req), serviceFixtures?.moderation ?? [], journal, defaults, setCorsHeaders);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname === ELEVENLABS_SOUND_GENERATION_PATH && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_elevenlabs_audio.handleElevenLabsAudio(req, res, await require_helpers.readBody(req), fixtures, defaults, journal, "sound-generation");
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const elevenLabsTTSMatch = pathname.match(ELEVENLABS_TTS_RE);
		if (elevenLabsTTSMatch && req.method === "POST") {
			setCorsHeaders(res);
			const voiceId = elevenLabsTTSMatch[1];
			try {
				await require_elevenlabs_audio.handleElevenLabsTTS(req, res, await require_helpers.readBody(req), fixtures, defaults, journal, voiceId);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		const musicMatch = pathname.match(ELEVENLABS_MUSIC_RE);
		if (musicMatch && req.method === "POST") {
			setCorsHeaders(res);
			const musicSubType = musicMatch[1] ?? "music";
			try {
				await require_elevenlabs_audio.handleElevenLabsAudio(req, res, await require_helpers.readBody(req), fixtures, defaults, journal, musicSubType);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		let falBody;
		if (FAL_PREFIX_RE.test(pathname) && req.headers["x-fal-target-host"]) {
			setCorsHeaders(res);
			try {
				falBody = req.method === "POST" || req.method === "PUT" ? await require_helpers.readBody(req) : "";
				const raw = falBody;
				const chaosAction = require_chaos.evaluateChaos(null, defaults.chaos, req.headers, defaults.logger);
				if (chaosAction) {
					require_chaos.applyChaosAction(chaosAction, res, null, journal, {
						method: req.method ?? "GET",
						path: pathname,
						headers: require_helpers.flattenHeaders(req.headers),
						body: {
							model: "",
							messages: []
						}
					}, "fixture", defaults.registry);
					return;
				}
				if (await require_fal.handleFal(req, res, raw, pathname, fixtures, defaults, journal) === "handled") return;
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
				return;
			}
		}
		if (pathname.match(FAL_QUEUE_SUBMIT_RE) && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_fal_audio.handleFalQueue(req, res, falBody ?? await require_helpers.readBody(req), pathname, fixtures, defaults, journal);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname.match(FAL_QUEUE_REQUESTS_RE) && (req.method === "GET" || req.method === "POST" || req.method === "PUT")) {
			setCorsHeaders(res);
			try {
				const raw = req.method === "POST" || req.method === "PUT" ? falBody ?? await require_helpers.readBody(req) : "{}";
				const chaosAction = require_chaos.evaluateChaos(null, defaults.chaos, req.headers, defaults.logger);
				if (chaosAction) {
					require_chaos.applyChaosAction(chaosAction, res, null, journal, {
						method: req.method ?? "GET",
						path: pathname,
						headers: require_helpers.flattenHeaders(req.headers),
						body: {
							model: "",
							messages: []
						}
					}, "fixture", defaults.registry);
					return;
				}
				await require_fal_audio.handleFalQueue(req, res, raw, pathname, fixtures, defaults, journal);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname.match(FAL_RUN_RE) && req.method === "POST") {
			setCorsHeaders(res);
			try {
				await require_fal_audio.handleFalQueue(req, res, falBody ?? await require_helpers.readBody(req), pathname, fixtures, defaults, journal);
			} catch (err) {
				const msg = err instanceof Error ? err.message : "Internal error";
				if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} }));
				else if (!res.writableEnded) res.destroy();
			}
			return;
		}
		if (pathname !== COMPLETIONS_PATH) {
			handleNotFound(res, "Not found");
			return;
		}
		if (req.method !== "POST") {
			handleNotFound(res, "Not found");
			return;
		}
		const completionsProvider = azureDeploymentId ? "azure" : "openai";
		try {
			await handleCompletions(req, res, fixtures, journal, defaults, azureDeploymentId, completionsProvider);
		} catch (err) {
			const msg = err instanceof Error ? err.message : "Internal error";
			if (!res.headersSent) require_sse_writer.writeErrorResponse(res, 500, JSON.stringify({ error: {
				message: msg,
				type: "server_error"
			} }));
			else if (!res.writableEnded) try {
				res.write(`data: ${JSON.stringify({ error: {
					message: msg,
					type: "server_error"
				} })}\n\n`);
				res.end();
			} catch (writeErr) {
				logger.debug("Failed to write error recovery response:", writeErr);
			}
		}
	}
	const activeConnections = /* @__PURE__ */ new Set();
	server.on("upgrade", (req, socket, head) => {
		handleUpgradeRequest(req, socket, head).catch((err) => {
			const msg = err instanceof Error ? err.message : "Internal error";
			defaults.logger.warn(`Unhandled upgrade error: ${msg}`);
			if (!socket.destroyed) socket.destroy();
		});
	});
	async function handleUpgradeRequest(req, socket, head) {
		const parsedUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
		let pathname = parsedUrl.pathname;
		if (mounts) {
			for (const { path: mountPath, handler } of mounts) if ((pathname === mountPath || pathname.startsWith(mountPath + "/")) && handler.handleUpgrade) {
				const subPath = pathname.slice(mountPath.length) || "/";
				if (await handler.handleUpgrade(socket, head, subPath)) return;
			}
		}
		if (!pathname.match(AZURE_DEPLOYMENT_RE)) pathname = normalizeCompatPath(pathname, logger);
		if (pathname !== RESPONSES_PATH && pathname !== REALTIME_PATH && pathname !== GEMINI_LIVE_PATH) {
			socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
			socket.destroy();
			return;
		}
		if (head.length > 0) socket.unshift(head);
		let ws;
		try {
			ws = require_ws_framing.upgradeToWebSocket(req, socket);
		} catch (err) {
			const msg = err instanceof Error ? err.message : "WebSocket upgrade failed";
			logger.error(`WebSocket upgrade error: ${msg}`);
			if (!socket.destroyed) socket.destroy();
			return;
		}
		activeConnections.add(ws);
		ws.on("error", (err) => {
			logger.error(`WebSocket error: ${err.message}`);
			activeConnections.delete(ws);
		});
		ws.on("close", () => {
			activeConnections.delete(ws);
		});
		const wsTestId = require_helpers.getTestId(req);
		if (pathname === RESPONSES_PATH) require_ws_responses.handleWebSocketResponses(ws, fixtures, journal, {
			...defaults,
			model: "gpt-4",
			testId: wsTestId,
			upgradeHeaders: req.headers
		});
		else if (pathname === REALTIME_PATH) {
			const model = parsedUrl.searchParams.get("model") ?? "gpt-realtime-2";
			require_ws_realtime.handleWebSocketRealtime(ws, fixtures, journal, {
				...defaults,
				model,
				testId: wsTestId,
				upgradeHeaders: req.headers
			});
		} else if (pathname === GEMINI_LIVE_PATH) require_ws_gemini_live.handleWebSocketGeminiLive(ws, fixtures, journal, {
			...defaults,
			model: "gemini-2.0-flash",
			testId: wsTestId,
			upgradeHeaders: req.headers
		});
	}
	const originalClose = server.close.bind(server);
	server.close = function(callback) {
		for (const ws of activeConnections) ws.close(1001, "Server shutting down");
		activeConnections.clear();
		videoStates.clear();
		openRouterVideoJobs.clear();
		veoVideoJobs.clear();
		grokVideoJobs.clear();
		originalClose(callback);
		return this;
	};
	return new Promise((resolve, reject) => {
		server.on("error", reject);
		server.listen(port, host, () => {
			const addr = server.address();
			if (!addr || typeof addr === "string") {
				reject(/* @__PURE__ */ new Error("Unexpected address format"));
				return;
			}
			const url = `http://${addr.address}:${addr.port}`;
			if (mounts) {
				for (const { path: mountPath, handler } of mounts) if (handler.setBaseUrl) handler.setBaseUrl(url + mountPath);
			}
			resolve({
				server,
				journal,
				url,
				defaults,
				videoStates,
				openRouterVideoJobs,
				veoVideoJobs,
				grokVideoJobs
			});
		});
	});
}

//#endregion
exports.createServer = createServer;
//# sourceMappingURL=server.cjs.map