import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString } from "./string-coerce-DKw2K5wM.js";
import { c as isRecord } from "./utils-B5r0V84N.js";
import { m as mergeSsrFPolicies } from "./ssrf-DaCkCIU1.js";
import { r as fetchWithSsrFGuard } from "./fetch-guard-BLLDm71I.js";
import { n as assertOkOrThrowHttpError, r as assertOkOrThrowProviderError } from "./provider-http-errors-BalaoPkp.js";
import { p as resolveProviderHttpRequestConfig } from "./shared-DEeNjizb.js";
import "./string-coerce-runtime-qOd7_06l.js";
import { r as isProviderApiKeyConfigured } from "./provider-auth-CeCp6dqQ.js";
import { n as buildHostnameAllowlistPolicyFromSuffixAllowlist, u as ssrfPolicyFromDangerouslyAllowPrivateNetwork } from "./ssrf-policy-myRWUA-7.js";
import "./ssrf-runtime-YaVY3Tkn.js";
import { o as resolveApiKeyForProvider } from "./provider-auth-runtime-DD1Ac4WT.js";
import "./provider-http-DBvV3EHX.js";
import { a as imageFileExtensionForMimeType, u as toImageDataUrl } from "./image-generation-C8XVQZK1.js";
//#region extensions/fal/image-generation-provider.ts
const DEFAULT_FAL_BASE_URL = "https://fal.run";
const DEFAULT_FAL_IMAGE_MODEL = "fal-ai/flux/dev";
const DEFAULT_FAL_EDIT_SUBPATH = "image-to-image";
const DEFAULT_OUTPUT_FORMAT = "png";
const GPT_IMAGE_EDIT_MAX_INPUT_IMAGES = 10;
const NANO_BANANA_EDIT_MAX_INPUT_IMAGES = 14;
const FAL_OUTPUT_FORMATS = ["png", "jpeg"];
const FAL_SUPPORTED_SIZES = [
	"1024x1024",
	"1024x1536",
	"1536x1024",
	"1024x1792",
	"1792x1024"
];
const FAL_SUPPORTED_ASPECT_RATIOS = [
	"1:1",
	"4:3",
	"3:4",
	"16:9",
	"9:16"
];
const FAL_IMAGE_MALFORMED_RESPONSE = "fal image generation response malformed";
let falFetchGuard = fetchWithSsrFGuard;
function setFalFetchGuardForTesting(impl) {
	falFetchGuard = impl ?? fetchWithSsrFGuard;
}
function matchesTrustedHostSuffix(hostname, trustedSuffix) {
	const normalizedHost = normalizeLowercaseStringOrEmpty(hostname);
	const normalizedSuffix = normalizeLowercaseStringOrEmpty(trustedSuffix);
	return normalizedHost === normalizedSuffix || normalizedHost.endsWith(`.${normalizedSuffix}`);
}
function parseFalImageGenerationResponse(payload) {
	if (!isRecord(payload)) throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);
	const rawImages = payload.images;
	if (rawImages === void 0 || rawImages === null) return {
		images: [],
		prompt: normalizeOptionalString(payload.prompt)
	};
	if (!Array.isArray(rawImages)) throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);
	const images = [];
	for (const entry of rawImages) {
		if (!isRecord(entry)) throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);
		images.push(entry);
	}
	return {
		images,
		prompt: normalizeOptionalString(payload.prompt)
	};
}
function resolveFalNetworkPolicy(params) {
	let parsedBaseUrl;
	try {
		parsedBaseUrl = new URL(params.baseUrl);
	} catch {
		return {};
	}
	const hostSuffix = normalizeLowercaseStringOrEmpty(parsedBaseUrl.hostname);
	if (!hostSuffix || !params.allowPrivateNetwork) return {};
	const trustedHostPolicy = mergeSsrFPolicies(buildHostnameAllowlistPolicyFromSuffixAllowlist([hostSuffix]), ssrfPolicyFromDangerouslyAllowPrivateNetwork(true));
	return {
		apiPolicy: trustedHostPolicy,
		trustedDownloadHostSuffix: hostSuffix,
		trustedDownloadPolicy: trustedHostPolicy
	};
}
function ensureFalModelPath(model, hasInputImages) {
	const trimmed = model?.trim() || DEFAULT_FAL_IMAGE_MODEL;
	if (!hasInputImages) return trimmed;
	if (trimmed.endsWith("/edit") || trimmed.endsWith(`/${DEFAULT_FAL_EDIT_SUBPATH}`) || trimmed.includes("/image-to-image/")) return trimmed;
	if (trimmed.startsWith("openai/gpt-image-") || trimmed.startsWith("fal-ai/nano-banana-")) return `${trimmed}/edit`;
	return `${trimmed}/${DEFAULT_FAL_EDIT_SUBPATH}`;
}
function parseSize(raw) {
	const trimmed = raw?.trim();
	if (!trimmed) return null;
	const match = /^(\d{2,5})x(\d{2,5})$/iu.exec(trimmed);
	if (!match) return null;
	const width = Number.parseInt(match[1] ?? "", 10);
	const height = Number.parseInt(match[2] ?? "", 10);
	if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return null;
	return {
		width,
		height
	};
}
function mapResolutionToEdge(resolution) {
	if (!resolution) return;
	return resolution === "4K" ? 4096 : resolution === "2K" ? 2048 : 1024;
}
function aspectRatioToEnum(aspectRatio) {
	const normalized = aspectRatio?.trim();
	if (!normalized) return;
	if (normalized === "1:1") return "square_hd";
	if (normalized === "4:3") return "landscape_4_3";
	if (normalized === "3:4") return "portrait_4_3";
	if (normalized === "16:9") return "landscape_16_9";
	if (normalized === "9:16") return "portrait_16_9";
}
function aspectRatioToDimensions(aspectRatio, edge) {
	const match = /^(\d+):(\d+)$/u.exec(aspectRatio.trim());
	if (!match) throw new Error(`Invalid fal aspect ratio: ${aspectRatio}`);
	const widthRatio = Number.parseInt(match[1] ?? "", 10);
	const heightRatio = Number.parseInt(match[2] ?? "", 10);
	if (!Number.isFinite(widthRatio) || !Number.isFinite(heightRatio) || widthRatio <= 0 || heightRatio <= 0) throw new Error(`Invalid fal aspect ratio: ${aspectRatio}`);
	if (widthRatio >= heightRatio) return {
		width: edge,
		height: Math.max(1, Math.round(edge * heightRatio / widthRatio))
	};
	return {
		width: Math.max(1, Math.round(edge * widthRatio / heightRatio)),
		height: edge
	};
}
function resolveFalImageSize(params) {
	const parsed = parseSize(params.size);
	if (parsed) return parsed;
	const normalizedAspectRatio = params.aspectRatio?.trim();
	if (normalizedAspectRatio && params.hasInputImages) return aspectRatioToEnum(normalizedAspectRatio) ?? aspectRatioToDimensions(normalizedAspectRatio, 1024);
	const edge = mapResolutionToEdge(params.resolution);
	if (normalizedAspectRatio && edge) return aspectRatioToDimensions(normalizedAspectRatio, edge);
	if (edge) return {
		width: edge,
		height: edge
	};
	if (normalizedAspectRatio) return aspectRatioToEnum(normalizedAspectRatio) ?? aspectRatioToDimensions(normalizedAspectRatio, 1024);
}
async function fetchImageBuffer(url, networkPolicy) {
	const downloadPolicy = (() => {
		const trustedSuffix = networkPolicy?.trustedDownloadHostSuffix;
		const trustedPolicy = networkPolicy?.trustedDownloadPolicy;
		if (!trustedSuffix || !trustedPolicy) return;
		try {
			return matchesTrustedHostSuffix(new URL(url).hostname, trustedSuffix) ? trustedPolicy : void 0;
		} catch {
			return;
		}
	})();
	const { response, release } = await falFetchGuard({
		url,
		policy: downloadPolicy,
		auditContext: "fal-image-download"
	});
	try {
		await assertOkOrThrowProviderError(response, "fal image download failed");
		const mimeType = response.headers.get("content-type")?.trim() || "image/png";
		const arrayBuffer = await response.arrayBuffer();
		return {
			buffer: Buffer.from(arrayBuffer),
			mimeType
		};
	} finally {
		await release();
	}
}
function buildFalImageGenerationProvider() {
	return {
		id: "fal",
		label: "fal",
		defaultModel: DEFAULT_FAL_IMAGE_MODEL,
		models: [DEFAULT_FAL_IMAGE_MODEL, `${DEFAULT_FAL_IMAGE_MODEL}/${DEFAULT_FAL_EDIT_SUBPATH}`],
		isConfigured: ({ agentDir }) => isProviderApiKeyConfigured({
			provider: "fal",
			agentDir
		}),
		capabilities: {
			generate: {
				maxCount: 4,
				supportsSize: true,
				supportsAspectRatio: true,
				supportsResolution: true
			},
			edit: {
				enabled: true,
				maxCount: 4,
				maxInputImages: GPT_IMAGE_EDIT_MAX_INPUT_IMAGES,
				supportsSize: true,
				supportsAspectRatio: true,
				supportsResolution: true
			},
			geometry: {
				sizes: [...FAL_SUPPORTED_SIZES],
				aspectRatios: [...FAL_SUPPORTED_ASPECT_RATIOS],
				resolutions: [
					"1K",
					"2K",
					"4K"
				]
			},
			output: { formats: [...FAL_OUTPUT_FORMATS] }
		},
		async generateImage(req) {
			const auth = await resolveApiKeyForProvider({
				provider: "fal",
				cfg: req.cfg,
				agentDir: req.agentDir,
				store: req.authStore
			});
			if (!auth.apiKey) throw new Error("fal API key missing");
			const inputImageCount = req.inputImages?.length ?? 0;
			const hasInputImages = inputImageCount > 0;
			const imageSize = resolveFalImageSize({
				size: req.size,
				resolution: req.resolution,
				aspectRatio: req.aspectRatio,
				hasInputImages
			});
			const model = ensureFalModelPath(req.model, hasInputImages);
			const isGptImageEditModel = model.startsWith("openai/gpt-image-");
			const isNanoBananaEditModel = model.startsWith("fal-ai/nano-banana-");
			if (hasInputImages && isGptImageEditModel && inputImageCount > GPT_IMAGE_EDIT_MAX_INPUT_IMAGES) throw new Error(`fal GPT Image edit supports at most ${GPT_IMAGE_EDIT_MAX_INPUT_IMAGES} reference images (requested ${inputImageCount})`);
			if (hasInputImages && isNanoBananaEditModel && inputImageCount > NANO_BANANA_EDIT_MAX_INPUT_IMAGES) throw new Error(`fal Nano Banana edit supports at most ${NANO_BANANA_EDIT_MAX_INPUT_IMAGES} reference images (requested ${inputImageCount})`);
			if (hasInputImages && !isGptImageEditModel && !isNanoBananaEditModel) {
				if (inputImageCount > 1) throw new Error("fal flux image generation currently supports at most one reference image");
				if (req.aspectRatio) throw new Error("fal flux image edit endpoint does not support aspectRatio overrides");
			}
			const explicitBaseUrl = req.cfg?.models?.providers?.fal?.baseUrl?.trim();
			const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy } = resolveProviderHttpRequestConfig({
				baseUrl: explicitBaseUrl,
				defaultBaseUrl: DEFAULT_FAL_BASE_URL,
				allowPrivateNetwork: false,
				defaultHeaders: {
					Authorization: `Key ${auth.apiKey}`,
					"Content-Type": "application/json"
				},
				provider: "fal",
				capability: "image",
				transport: "http"
			});
			const networkPolicy = resolveFalNetworkPolicy({
				baseUrl,
				allowPrivateNetwork
			});
			const requestBody = {
				prompt: req.prompt,
				num_images: req.count ?? 1,
				output_format: req.outputFormat ?? DEFAULT_OUTPUT_FORMAT
			};
			if (imageSize !== void 0) if (model.startsWith("fal-ai/nano-banana-") && hasInputImages) {
				if (req.aspectRatio) requestBody.aspect_ratio = req.aspectRatio;
				if (req.resolution) requestBody.resolution = req.resolution;
			} else requestBody.image_size = imageSize;
			if (hasInputImages) {
				const [input] = req.inputImages ?? [];
				if (!input) throw new Error("fal image edit request missing reference image");
				if (isGptImageEditModel || isNanoBananaEditModel) requestBody.image_urls = req.inputImages.map((img) => toImageDataUrl(img));
				else requestBody.image_url = toImageDataUrl(input);
			}
			const { response, release } = await falFetchGuard({
				url: `${baseUrl}/${model}`,
				init: {
					method: "POST",
					headers,
					body: JSON.stringify(requestBody)
				},
				timeoutMs: req.timeoutMs,
				policy: networkPolicy.apiPolicy,
				dispatcherPolicy,
				auditContext: "fal-image-generate"
			});
			try {
				await assertOkOrThrowHttpError(response, "fal image generation failed");
				const payload = parseFalImageGenerationResponse(await response.json());
				const images = [];
				let imageIndex = 0;
				for (const entry of payload.images) {
					const url = normalizeOptionalString(entry.url);
					if (!url) throw new Error(FAL_IMAGE_MALFORMED_RESPONSE);
					const downloaded = await fetchImageBuffer(url, networkPolicy);
					imageIndex += 1;
					images.push({
						buffer: downloaded.buffer,
						mimeType: downloaded.mimeType,
						fileName: `image-${imageIndex}.${imageFileExtensionForMimeType(downloaded.mimeType || normalizeOptionalString(entry.content_type))}`
					});
				}
				if (images.length === 0) throw new Error("fal image generation response missing image data");
				return {
					images,
					model,
					metadata: payload.prompt ? { prompt: payload.prompt } : void 0
				};
			} finally {
				await release();
			}
		}
	};
}
//#endregion
export { setFalFetchGuardForTesting as n, buildFalImageGenerationProvider as t };
