import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
//#region src/tunnel/well-known.ts
init_logger();
const log = createLogger("Tunnel");
let cached = null;
const CACHE_TTL_MS = 5 * 6e4;
function brokerOrigin(brokerUrl) {
	return new URL(brokerUrl.replace(/\/+$/, "").replace(/\/api\/?$/, "") || brokerUrl).origin;
}
/**
* Fetch `/.well-known/tunnel-config` (broker URL, frp endpoints, frpc version).
* Registration secret is never published here — use `XOPC_TUNNEL_REGISTRATION_SECRET`.
*/
async function fetchTunnelWellKnown(brokerUrl) {
	const origin = brokerOrigin(brokerUrl);
	if (cached && cached.origin === origin && Date.now() - cached.fetchedAt < CACHE_TTL_MS) return cached.config;
	const url = `${origin}/.well-known/tunnel-config`;
	const res = await fetch(url, { signal: AbortSignal.timeout(1e4) });
	if (!res.ok) throw new Error(`Tunnel well-known fetch failed: ${res.status} ${res.statusText}`);
	const body = await res.json();
	cached = {
		origin,
		config: body,
		fetchedAt: Date.now()
	};
	log.debug({
		url,
		brokerUrl: body.brokerUrl,
		transport: body.transport?.tls
	}, "Loaded tunnel well-known config");
	return body;
}
async function pingTunnelBroker(brokerUrl) {
	try {
		await fetchTunnelWellKnown(brokerUrl);
		return true;
	} catch {
		return false;
	}
}
function clearTunnelWellKnownCache() {
	cached = null;
}
//#endregion
export { clearTunnelWellKnownCache, fetchTunnelWellKnown, pingTunnelBroker };

//# sourceMappingURL=well-known.js.map