const require_logger = require('./logger-DXu5t4bD.cjs');
const require_fetch = require('./fetch-D5ITc9pG.cjs');
let fs = require("fs");
fs = require_logger.__toESM(fs);
let path = require("path");
path = require_logger.__toESM(path);
let cache_manager = require("cache-manager");
let keyv = require("keyv");
let keyv_file = require("keyv-file");
let crypto = require("crypto");

//#region src/cacheMigration.ts
/**
* Migration sunset date: After this date, skip migration entirely.
* Users who haven't upgraded by then will start with a fresh cache.
*
* Set to 2 months after initial release (December 2025).
* After this date, this entire migration module can be removed.
*
* TODO(2026-02-01): Remove this migration code after sunset date.
*/
const MIGRATION_SUNSET_DATE = /* @__PURE__ */ new Date("2026-02-01T00:00:00Z");
/**
* Check if migration has been sunset (date has passed).
* After sunset, we skip migration entirely - users get a fresh cache.
*/
function isMigrationSunset() {
	return Date.now() >= MIGRATION_SUNSET_DATE.getTime();
}
/**
* Calculate total size of a directory recursively
*/
function getDirSize(dirPath) {
	let totalSize = 0;
	try {
		const entries = fs.default.readdirSync(dirPath, { withFileTypes: true });
		for (const entry of entries) {
			const itemPath = path.default.join(dirPath, entry.name);
			if (entry.isDirectory()) totalSize += getDirSize(itemPath);
			else totalSize += fs.default.statSync(itemPath).size;
		}
	} catch (err) {
		if (err.code !== "ENOENT") require_logger.logger_default.warn(`[Cache Migration] Error calculating directory size: ${err.message}`);
	}
	return totalSize;
}
/**
* Check if sufficient disk space is available for migration
* Returns true if check passes or cannot be performed
*/
function checkDiskSpace(cachePath) {
	try {
		const cacheSize = getDirSize(cachePath);
		if (typeof fs.default.statfsSync === "function") {
			const stats = fs.default.statfsSync(cachePath);
			const availableBytes = stats.bavail * stats.bsize;
			const requiredBytes = cacheSize * 2 + 10 * 1024 * 1024;
			require_logger.logger_default.debug(`[Cache Migration] Disk space check: need ${(requiredBytes / 1024 / 1024).toFixed(2)}MB, have ${(availableBytes / 1024 / 1024).toFixed(2)}MB available`);
			if (availableBytes < requiredBytes) {
				require_logger.logger_default.error(`[Cache Migration] Insufficient disk space for migration. Need ${(requiredBytes / 1024 / 1024).toFixed(0)}MB, have ${(availableBytes / 1024 / 1024).toFixed(0)}MB available.`);
				return false;
			}
			return true;
		} else {
			require_logger.logger_default.debug("[Cache Migration] Disk space check not available on this platform, proceeding");
			return true;
		}
	} catch (err) {
		require_logger.logger_default.warn(`[Cache Migration] Could not check disk space: ${err.message}`);
		return true;
	}
}
/** Maximum number of attempts to acquire the migration lock */
const MAX_LOCK_ATTEMPTS = 3;
/**
* Check if a process with the given PID exists.
* Uses signal 0 which doesn't actually send a signal but checks process existence.
* Note: On Windows, this may throw different error types but the catch block handles it.
*/
function isProcessRunning(pid) {
	try {
		process.kill(pid, 0);
		return true;
	} catch (err) {
		return err.code === "EPERM";
	}
}
/**
* Acquire a migration lock to prevent concurrent migrations.
* Returns file descriptor if lock acquired, null if another process holds the lock.
* Uses atomic file creation with 'wx' flag and includes stale lock detection.
*/
function acquireMigrationLock(cachePath, attempt = 1) {
	if (attempt > MAX_LOCK_ATTEMPTS) {
		require_logger.logger_default.warn(`[Cache Migration] Failed to acquire lock after ${MAX_LOCK_ATTEMPTS} attempts`);
		return null;
	}
	const lockFile = path.default.join(cachePath, ".migration.lock");
	try {
		if (!fs.default.existsSync(cachePath)) fs.default.mkdirSync(cachePath, { recursive: true });
		const fd = fs.default.openSync(lockFile, "wx");
		fs.default.writeSync(fd, process.pid.toString());
		fs.default.fsyncSync(fd);
		require_logger.logger_default.debug(`[Cache Migration] Lock acquired (PID: ${process.pid})`);
		return fd;
	} catch (err) {
		if (err.code === "EEXIST") {
			try {
				const content = fs.default.readFileSync(lockFile, "utf-8");
				const pid = parseInt(content, 10);
				if (!isNaN(pid)) {
					if (isProcessRunning(pid)) {
						require_logger.logger_default.info(`[Cache Migration] Another migration is in progress (PID: ${pid})`);
						return null;
					}
					require_logger.logger_default.warn(`[Cache Migration] Removing stale lock file (PID: ${pid} not found)`);
					try {
						fs.default.unlinkSync(lockFile);
						return acquireMigrationLock(cachePath, attempt + 1);
					} catch (unlinkErr) {
						require_logger.logger_default.error(`[Cache Migration] Failed to remove stale lock: ${unlinkErr.message}`);
						return null;
					}
				}
			} catch (readErr) {
				require_logger.logger_default.warn(`[Cache Migration] Could not read lock file: ${readErr.message}`);
			}
			return null;
		}
		throw err;
	}
}
/**
* Release the migration lock
*/
function releaseMigrationLock(fd, cachePath) {
	if (fd === null) return;
	const lockFile = path.default.join(cachePath, ".migration.lock");
	try {
		fs.default.closeSync(fd);
	} catch (err) {
		require_logger.logger_default.warn(`[Cache Migration] Failed to close lock file: ${err.message}`);
	}
	try {
		fs.default.unlinkSync(lockFile);
		require_logger.logger_default.debug("[Cache Migration] Lock released");
	} catch (err) {
		require_logger.logger_default.warn(`[Cache Migration] Failed to remove lock file: ${err.message}`);
	}
}
/**
* Parse expireTime field, handling the "[object Object]" suffix bug
*/
function parseExpireTime(expireTimeValue) {
	try {
		if (typeof expireTimeValue === "number") return expireTimeValue > 0 ? expireTimeValue : void 0;
		if (typeof expireTimeValue === "string") {
			const cleaned = expireTimeValue.replace(/\[object Object\].*$/, "");
			const timestamp = parseInt(cleaned, 10);
			if (isNaN(timestamp) || timestamp <= 0) return;
			return timestamp;
		}
		return;
	} catch (_err) {
		return;
	}
}
/**
* Read all cache entries from cache-manager-fs-hash format
*/
function readOldCacheEntries(cachePath) {
	const stats = {
		totalFiles: 0,
		successCount: 0,
		failureCount: 0,
		skippedExpired: 0,
		errors: []
	};
	const entries = /* @__PURE__ */ new Map();
	if (!fs.default.existsSync(cachePath)) {
		require_logger.logger_default.info(`[Cache Migration] No old cache directory found at ${cachePath}`);
		return {
			entries,
			stats
		};
	}
	const diskstoreDirs = fs.default.readdirSync(cachePath, { withFileTypes: true }).filter((dirEntry) => dirEntry.isDirectory() && dirEntry.name.startsWith("diskstore-")).map((dirEntry) => dirEntry.name);
	require_logger.logger_default.info(`[Cache Migration] Found ${diskstoreDirs.length} diskstore directories`);
	const shouldLogProgress = diskstoreDirs.length > 100;
	if (shouldLogProgress) require_logger.logger_default.info(`[Cache Migration] Processing large cache, this may take a moment...`);
	const now = Date.now();
	let dirCount = 0;
	for (const dir of diskstoreDirs) {
		const dirPath = path.default.join(cachePath, dir);
		dirCount++;
		if (shouldLogProgress && dirCount % 100 === 0) require_logger.logger_default.info(`[Cache Migration] Processed ${dirCount}/${diskstoreDirs.length} directories...`);
		try {
			const jsonFiles = fs.default.readdirSync(dirPath).filter((f) => f.endsWith(".json"));
			for (const file of jsonFiles) {
				const filePath = path.default.join(dirPath, file);
				stats.totalFiles++;
				if (stats.totalFiles % 1e3 === 0 && stats.totalFiles > 0) require_logger.logger_default.info(`[Cache Migration] Processed ${stats.totalFiles} files...`);
				try {
					const content = fs.default.readFileSync(filePath, "utf-8");
					const oldEntry = JSON.parse(content);
					if (!oldEntry.key || oldEntry.val === void 0) {
						stats.failureCount++;
						stats.errors.push(`Missing required fields in ${filePath}`);
						continue;
					}
					const expireTime = parseExpireTime(oldEntry.expireTime);
					if (expireTime && expireTime <= now) {
						stats.skippedExpired++;
						continue;
					}
					const newEntry = {
						value: oldEntry.val,
						expires: expireTime
					};
					entries.set(oldEntry.key, newEntry);
					stats.successCount++;
				} catch (err) {
					stats.failureCount++;
					stats.errors.push(`Error parsing ${filePath}: ${err.message}`);
				}
			}
		} catch (err) {
			stats.failureCount++;
			stats.errors.push(`Error reading directory ${dirPath}: ${err.message}`);
		}
	}
	return {
		entries,
		stats
	};
}
/**
* Validate that a cache file can be read and has the expected structure.
* Returns the number of entries if valid, throws if invalid.
*/
function validateCacheFile(cachePath, expectedEntryCount) {
	if (!fs.default.existsSync(cachePath)) throw new Error(`Cache file does not exist after write: ${cachePath}`);
	const content = fs.default.readFileSync(cachePath, "utf-8");
	let parsed;
	try {
		parsed = JSON.parse(content);
	} catch (err) {
		throw new Error(`Cache file is not valid JSON: ${err.message}`);
	}
	if (!Array.isArray(parsed.cache)) throw new Error("Cache file has invalid structure: missing or invalid \"cache\" array");
	if (typeof parsed.lastExpire !== "number") throw new Error("Cache file has invalid structure: missing or invalid \"lastExpire\" field");
	if (parsed.cache.length !== expectedEntryCount) throw new Error(`Cache file entry count mismatch: expected ${expectedEntryCount}, got ${parsed.cache.length}`);
	require_logger.logger_default.debug(`[Cache Migration] Validated cache file: ${cachePath} (${expectedEntryCount} entries)`);
}
/**
* Write entries in keyv-file format using atomic write operation.
* Writes to a temp file first, then renames atomically to prevent corruption.
* Validates the written file before returning.
*/
function writeNewCacheFile(entries, newCachePath) {
	const data = {
		cache: Array.from(entries.entries()),
		lastExpire: Date.now()
	};
	const dir = path.default.dirname(newCachePath);
	if (!fs.default.existsSync(dir)) fs.default.mkdirSync(dir, { recursive: true });
	const tempFile = path.default.join(dir, `.cache.${(0, crypto.randomBytes)(8).toString("hex")}.tmp`);
	try {
		let serialized;
		try {
			serialized = JSON.stringify(data);
		} catch (err) {
			throw new Error(`Failed to serialize cache data: ${err.message}`);
		}
		fs.default.writeFileSync(tempFile, serialized, "utf-8");
		fs.default.renameSync(tempFile, newCachePath);
		require_logger.logger_default.debug(`[Cache Migration] Atomically wrote cache file: ${newCachePath}`);
		validateCacheFile(newCachePath, entries.size);
	} catch (err) {
		try {
			if (fs.default.existsSync(tempFile)) fs.default.unlinkSync(tempFile);
		} catch (_cleanupErr) {}
		throw err;
	}
}
/**
* Create a backup of the old cache directory
*/
function createBackup(cachePath) {
	const backupPath = `${cachePath}.backup.${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
	require_logger.logger_default.info(`[Cache Migration] Creating backup at ${backupPath}`);
	if (fs.default.existsSync(cachePath)) fs.default.cpSync(cachePath, backupPath, { recursive: true });
	return backupPath;
}
/**
* Mark migration as complete by creating a marker file
*/
function markMigrationComplete(cacheBasePath, stats) {
	const markerPath = path.default.join(cacheBasePath, ".cache-migrated");
	const metadata = {
		timestamp: (/* @__PURE__ */ new Date()).toISOString(),
		stats,
		version: "4-to-7"
	};
	if (!fs.default.existsSync(cacheBasePath)) fs.default.mkdirSync(cacheBasePath, { recursive: true });
	fs.default.writeFileSync(markerPath, JSON.stringify(metadata, null, 2), "utf-8");
}
/**
* Check if migration has already been completed.
* Uses fast-path: if marker exists AND new cache file exists, skip directory scan.
* Only validates old cache format when inconsistency is suspected.
*/
function isMigrationComplete(cacheBasePath, newCacheFile) {
	const markerPath = path.default.join(cacheBasePath, ".cache-migrated");
	if (!fs.default.existsSync(markerPath)) return false;
	if (newCacheFile && fs.default.existsSync(newCacheFile)) return true;
	if (newCacheFile) {
		if (hasOldCacheFormat(cacheBasePath)) {
			require_logger.logger_default.warn("[Cache Migration] Marker file exists but migration appears incomplete. Old cache format found but new cache missing. Retrying migration...");
			try {
				fs.default.unlinkSync(markerPath);
			} catch (err) {
				require_logger.logger_default.warn(`[Cache Migration] Failed to remove stale marker: ${err.message}`);
			}
			return false;
		}
	}
	return true;
}
/**
* Check if old cache format exists
*/
function hasOldCacheFormat(cachePath) {
	let dirEntries;
	try {
		dirEntries = fs.default.readdirSync(cachePath, { withFileTypes: true });
	} catch (err) {
		if (err.code === "ENOENT") return false;
		throw err;
	}
	return dirEntries.some((dirEntry) => dirEntry.isDirectory() && dirEntry.name.startsWith("diskstore-"));
}
/**
* Clean up old cache directories after successful migration
*/
function cleanupOldCache(cachePath) {
	let dirEntries;
	try {
		dirEntries = fs.default.readdirSync(cachePath, { withFileTypes: true });
	} catch (err) {
		if (err.code === "ENOENT") return;
		throw err;
	}
	const diskstoreDirs = dirEntries.filter((dirEntry) => dirEntry.isDirectory() && dirEntry.name.startsWith("diskstore-")).map((dirEntry) => dirEntry.name);
	require_logger.logger_default.info(`[Cache Migration] Cleaning up ${diskstoreDirs.length} old cache directories`);
	for (const dir of diskstoreDirs) {
		const dirPath = path.default.join(cachePath, dir);
		try {
			fs.default.rmSync(dirPath, {
				recursive: true,
				force: true
			});
		} catch (err) {
			require_logger.logger_default.warn(`[Cache Migration] Failed to remove ${dirPath}: ${err.message}`);
		}
	}
}
/**
* Clean up backup directory after successful migration
* Only deletes if no valuable data was migrated AND no failures occurred
*/
function cleanupBackup(backupPath, stats) {
	if (stats.successCount === 0 && stats.failureCount === 0) {
		require_logger.logger_default.info(`[Cache Migration] No valid entries found (${stats.skippedExpired} expired only). Removing backup to save space.`);
		try {
			fs.default.rmSync(backupPath, {
				recursive: true,
				force: true
			});
			require_logger.logger_default.info(`[Cache Migration] Backup removed: ${backupPath}`);
			return true;
		} catch (err) {
			require_logger.logger_default.warn(`[Cache Migration] Failed to remove backup ${backupPath}: ${err.message}`);
			return false;
		}
	} else if (stats.failureCount > 0) {
		require_logger.logger_default.info(`[Cache Migration] Backup kept at ${backupPath} due to ${stats.failureCount} migration errors. You may want to investigate these failures.`);
		return false;
	} else {
		require_logger.logger_default.info(`[Cache Migration] Backup kept at ${backupPath} (migrated ${stats.successCount} valid entries). You can manually delete this backup if you no longer need it.`);
		return false;
	}
}
/**
* Main migration function
* Migrates cache from cache-manager v4 (cache-manager-fs-hash) to v7 (keyv-file)
*/
function runMigration(cachePath, newCacheFilePath) {
	require_logger.logger_default.info("[Cache Migration] Starting cache migration from v4 to v7");
	const lock = acquireMigrationLock(cachePath);
	if (lock === null) {
		require_logger.logger_default.info("[Cache Migration] Another migration is in progress, skipping");
		return {
			success: true,
			stats: {
				totalFiles: 0,
				successCount: 0,
				failureCount: 0,
				skippedExpired: 0,
				errors: []
			}
		};
	}
	try {
		if (isMigrationComplete(cachePath, newCacheFilePath)) {
			require_logger.logger_default.info("[Cache Migration] Migration already completed, skipping");
			return {
				success: true,
				stats: {
					totalFiles: 0,
					successCount: 0,
					failureCount: 0,
					skippedExpired: 0,
					errors: []
				}
			};
		}
		if (!hasOldCacheFormat(cachePath)) {
			require_logger.logger_default.info("[Cache Migration] No old cache format detected, skipping migration");
			markMigrationComplete(cachePath, {
				totalFiles: 0,
				successCount: 0,
				failureCount: 0,
				skippedExpired: 0,
				errors: []
			});
			return {
				success: true,
				stats: {
					totalFiles: 0,
					successCount: 0,
					failureCount: 0,
					skippedExpired: 0,
					errors: []
				}
			};
		}
		if (!checkDiskSpace(cachePath)) {
			require_logger.logger_default.error("[Cache Migration] Insufficient disk space, aborting migration");
			return {
				success: false,
				stats: {
					totalFiles: 0,
					successCount: 0,
					failureCount: 1,
					skippedExpired: 0,
					errors: ["Insufficient disk space for migration"]
				}
			};
		}
		const backupPath = createBackup(cachePath);
		require_logger.logger_default.info("[Cache Migration] Reading old cache entries");
		const { entries, stats } = readOldCacheEntries(cachePath);
		require_logger.logger_default.info(`[Cache Migration] Read ${stats.successCount} entries (${stats.failureCount} failures, ${stats.skippedExpired} expired)`);
		if (stats.errors.length > 0) {
			require_logger.logger_default.warn(`[Cache Migration] Encountered ${stats.errors.length} errors:`);
			stats.errors.slice(0, 10).forEach((err) => require_logger.logger_default.warn(`  - ${err}`));
			if (stats.errors.length > 10) require_logger.logger_default.warn(`  ... and ${stats.errors.length - 10} more errors`);
		}
		if (entries.size > 0) {
			require_logger.logger_default.info(`[Cache Migration] Writing ${entries.size} entries to new cache file: ${newCacheFilePath}`);
			writeNewCacheFile(entries, newCacheFilePath);
		} else require_logger.logger_default.info("[Cache Migration] No entries to migrate");
		cleanupOldCache(cachePath);
		const backupDeleted = cleanupBackup(backupPath, stats);
		markMigrationComplete(cachePath, stats);
		require_logger.logger_default.info("[Cache Migration] Migration completed successfully");
		return {
			success: true,
			stats,
			backupPath: backupDeleted ? void 0 : backupPath
		};
	} catch (err) {
		require_logger.logger_default.error(`[Cache Migration] Migration failed: ${err.message}`);
		require_logger.logger_default.error(`[Cache Migration] Stack trace: ${err.stack}`);
		return {
			success: false,
			stats: {
				totalFiles: 0,
				successCount: 0,
				failureCount: 1,
				skippedExpired: 0,
				errors: [err.message]
			}
		};
	} finally {
		releaseMigrationLock(lock, cachePath);
	}
}
/**
* Check if migration should be run.
* Returns false if:
* - Migration is already complete (marker + new cache file exist)
* - Migration has been sunset (date passed)
* - No old cache format exists
*/
function shouldRunMigration(cachePath, newCacheFile) {
	if (isMigrationSunset()) return false;
	if (isMigrationComplete(cachePath, newCacheFile)) return false;
	return hasOldCacheFormat(cachePath);
}

//#endregion
//#region src/cache.ts
var cache_exports = /* @__PURE__ */ require_logger.__exportAll({
	clearCache: () => clearCache,
	disableCache: () => disableCache,
	enableCache: () => enableCache,
	fetchWithCache: () => fetchWithCache,
	getCache: () => getCache,
	isCacheEnabled: () => isCacheEnabled
});
let cacheInstance;
let enabled = require_logger.getEnvBool("PROMPTFOO_CACHE_ENABLED", true);
const cacheType = require_logger.getEnvString("PROMPTFOO_CACHE_TYPE") || (require_logger.getEnvString("NODE_ENV") === "test" ? "memory" : "disk");
/** Default cache TTL: 14 days in seconds */
const DEFAULT_CACHE_TTL_SECONDS = 3600 * 24 * 14;
/**
* Get the cache TTL in milliseconds.
* Reads from PROMPTFOO_CACHE_TTL environment variable (in seconds) or uses default.
*/
function getCacheTtlMs() {
	return require_logger.getEnvInt("PROMPTFOO_CACHE_TTL", DEFAULT_CACHE_TTL_SECONDS) * 1e3;
}
function getCache() {
	if (!cacheInstance) {
		let cachePath = "";
		const stores = [];
		let migrationFailed = false;
		if (cacheType === "disk" && enabled) {
			cachePath = require_logger.getEnvString("PROMPTFOO_CACHE_PATH") || path.default.join(require_logger.getConfigDirectoryPath(), "cache");
			if (!fs.default.existsSync(cachePath)) {
				require_logger.logger_default.info(`Creating cache folder at ${cachePath}.`);
				fs.default.mkdirSync(cachePath, { recursive: true });
			}
			const newCacheFile = path.default.join(cachePath, "cache.json");
			if (shouldRunMigration(cachePath, newCacheFile)) {
				require_logger.logger_default.info("[Cache] Migrating cache from v4 to v7...");
				try {
					const result = runMigration(cachePath, newCacheFile);
					if (result.success) {
						require_logger.logger_default.info(`[Cache] Migration completed: ${result.stats.successCount} entries migrated, ${result.stats.skippedExpired} expired`);
						if (result.backupPath) require_logger.logger_default.info(`[Cache] Backup kept at: ${result.backupPath}`);
					} else {
						require_logger.logger_default.error(`[Cache] Migration failed: ${result.stats.errors.join(", ")}. Falling back to memory cache.`);
						migrationFailed = true;
					}
				} catch (err) {
					require_logger.logger_default.error(`[Cache] Migration error: ${err.message}. Falling back to memory cache.`);
					migrationFailed = true;
				}
			}
			if (!migrationFailed) try {
				const keyv$1 = new keyv.Keyv({
					store: new keyv_file.KeyvFile({ filename: newCacheFile }),
					ttl: getCacheTtlMs()
				});
				stores.push(keyv$1);
			} catch (err) {
				require_logger.logger_default.warn(`[Cache] Failed to initialize disk cache: ${err.message}. Using memory cache instead.`);
			}
		}
		cacheInstance = (0, cache_manager.createCache)({
			stores,
			ttl: getCacheTtlMs(),
			refreshThreshold: 0
		});
	}
	return cacheInstance;
}
async function fetchWithCache(url, options = {}, timeout = require_fetch.REQUEST_TIMEOUT_MS, format = "json", bust = false, maxRetries) {
	if (!enabled || bust) {
		const fetchStart = Date.now();
		const resp = await require_fetch.fetchWithRetries(url, options, timeout, maxRetries);
		const fetchLatencyMs$1 = Date.now() - fetchStart;
		const respText = await resp.text();
		try {
			return {
				cached: false,
				data: format === "json" ? JSON.parse(respText) : respText,
				status: resp.status,
				statusText: resp.statusText,
				headers: Object.fromEntries(resp.headers.entries()),
				latencyMs: fetchLatencyMs$1,
				deleteFromCache: async () => {}
			};
		} catch {
			throw new Error(`Error parsing response as JSON: ${respText}`);
		}
	}
	const copy = Object.assign({}, options);
	delete copy.headers;
	const cacheKey = `fetch:v2:${url}:${JSON.stringify(copy)}`;
	const cache = await getCache();
	let cached = true;
	let errorResponse = null;
	let fetchLatencyMs;
	const cachedResponse = await cache.wrap(cacheKey, async () => {
		cached = false;
		const fetchStart = Date.now();
		const response = await require_fetch.fetchWithRetries(url, options, timeout, maxRetries);
		fetchLatencyMs = Date.now() - fetchStart;
		const responseText = await response.text();
		const headers = Object.fromEntries(response.headers.entries());
		try {
			const parsedData = format === "json" ? JSON.parse(responseText) : responseText;
			const data = JSON.stringify({
				data: parsedData,
				status: response.status,
				statusText: response.statusText,
				headers,
				latencyMs: fetchLatencyMs
			});
			if (!response.ok) {
				if (responseText == "") errorResponse = JSON.stringify({
					data: `Empty Response: ${response.status}: ${response.statusText}`,
					status: response.status,
					statusText: response.statusText,
					headers,
					latencyMs: fetchLatencyMs
				});
				else errorResponse = data;
				return;
			}
			if (!data) return;
			if (format === "json" && parsedData?.error) {
				require_logger.logger_default.debug(`Not caching ${url} because it contains an 'error' key: ${parsedData.error}`);
				return data;
			}
			require_logger.logger_default.debug(`Storing ${url} response in cache with latencyMs=${fetchLatencyMs}: ${data}`);
			return data;
		} catch (err) {
			throw new Error(`Error parsing response from ${url}: ${err.message}. Received text: ${responseText}`);
		}
	});
	if (cached && cachedResponse) require_logger.logger_default.debug(`Returning cached response for ${url}: ${cachedResponse}`);
	const parsedResponse = JSON.parse(cachedResponse ?? errorResponse);
	return {
		cached,
		data: parsedResponse.data,
		status: parsedResponse.status,
		statusText: parsedResponse.statusText,
		headers: parsedResponse.headers,
		latencyMs: parsedResponse.latencyMs,
		deleteFromCache: async () => {
			await cache.del(cacheKey);
			require_logger.logger_default.debug(`Evicted from cache: ${cacheKey}`);
		}
	};
}
function enableCache() {
	enabled = true;
}
function disableCache() {
	enabled = false;
}
async function clearCache() {
	return getCache().clear();
}
function isCacheEnabled() {
	return enabled;
}

//#endregion
Object.defineProperty(exports, 'cache_exports', {
  enumerable: true,
  get: function () {
    return cache_exports;
  }
});
Object.defineProperty(exports, 'clearCache', {
  enumerable: true,
  get: function () {
    return clearCache;
  }
});
Object.defineProperty(exports, 'disableCache', {
  enumerable: true,
  get: function () {
    return disableCache;
  }
});
Object.defineProperty(exports, 'enableCache', {
  enumerable: true,
  get: function () {
    return enableCache;
  }
});
Object.defineProperty(exports, 'fetchWithCache', {
  enumerable: true,
  get: function () {
    return fetchWithCache;
  }
});
Object.defineProperty(exports, 'getCache', {
  enumerable: true,
  get: function () {
    return getCache;
  }
});
Object.defineProperty(exports, 'isCacheEnabled', {
  enumerable: true,
  get: function () {
    return isCacheEnabled;
  }
});
//# sourceMappingURL=cache-Cv2r51Z1.cjs.map