const require_rolldown_runtime = require("./rolldown-runtime-D_mwlA32.cjs");
const require_logger = require("./logger-DuG3amVa.cjs");
const require_fetch = require("./fetch-Hdu2Q-w3.cjs");
const require_accounts = require("./accounts-CibSkI-0.cjs");
let zod = require("zod");
let posthog_node = require("posthog-node");
//#region src/telemetryEvents.ts
/** Closed list of telemetry event names. Shared by telemetry recording and API DTOs. */
const TELEMETRY_EVENTS = [
	"assertion_used",
	"command_used",
	"eval setup",
	"eval_ran",
	"feature_used",
	"funnel",
	"redteam discover",
	"redteam generate",
	"redteam init",
	"redteam poison",
	"redteam report",
	"redteam run",
	"redteam setup",
	"webui_action",
	"webui_api",
	"webui_page_view"
];
const TelemetryPropertyValueSchema = zod.z.union([
	zod.z.string(),
	zod.z.number(),
	zod.z.boolean(),
	zod.z.array(zod.z.string())
]);
zod.z.object({
	event: zod.z.enum(TELEMETRY_EVENTS),
	packageVersion: zod.z.string().optional().prefault(require_fetch.VERSION),
	properties: zod.z.record(zod.z.string(), TelemetryPropertyValueSchema)
});
//#endregion
//#region src/telemetry.ts
var telemetry_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
	Telemetry: () => Telemetry,
	default: () => telemetry
});
let posthogClient = null;
let isShuttingDown = false;
function getPostHogClient() {
	if (require_logger.getEnvBool("PROMPTFOO_DISABLE_TELEMETRY") || require_logger.getEnvBool("IS_TESTING")) return null;
	if (posthogClient === null && "phc_E5n5uHnDo2eREJL1uqX1cIlbkoRby4yFWt3V94HqRRg") try {
		posthogClient = new posthog_node.PostHog(require_fetch.POSTHOG_KEY, {
			host: require_fetch.EVENTS_ENDPOINT,
			fetch: require_fetch.fetchWithProxy,
			flushInterval: 0
		});
	} catch {
		posthogClient = null;
	}
	return posthogClient;
}
const TELEMETRY_TIMEOUT_MS = 1e3;
function getRuntimeMetadata() {
	return {
		nodeVersion: process.version,
		nodeMajor: Number.parseInt(process.versions.node, 10),
		platform: process.platform,
		arch: process.arch
	};
}
var Telemetry = class {
	telemetryDisabledRecorded = false;
	id;
	constructor() {
		this.id = require_accounts.getUserId();
		this.identify();
	}
	getPersonProperties(ciFlag) {
		return {
			...require_accounts.getUserAuthInfo(),
			isRunningInCi: ciFlag
		};
	}
	async identify() {
		if (this.disabled || require_logger.getEnvBool("IS_TESTING")) return;
		const client = getPostHogClient();
		if (client) try {
			const personProperties = this.getPersonProperties(require_logger.isCI());
			client.identify({
				distinctId: this.id,
				properties: personProperties
			});
			client.flush().catch(() => {});
		} catch (error) {
			require_logger.logger.debug(`PostHog identify error: ${error}`);
		}
	}
	get disabled() {
		return require_logger.getEnvBool("PROMPTFOO_DISABLE_TELEMETRY");
	}
	recordTelemetryDisabled() {
		if (!this.telemetryDisabledRecorded) {
			this.sendEvent("feature_used", { feature: "telemetry disabled" });
			this.telemetryDisabledRecorded = true;
		}
	}
	record(eventName, properties) {
		if (this.disabled) this.recordTelemetryDisabled();
		else this.sendEvent(eventName, properties);
	}
	sendEvent(eventName, properties) {
		const ciFlag = require_logger.isCI();
		const personProperties = this.getPersonProperties(ciFlag);
		const propertiesWithMetadata = {
			...properties,
			packageVersion: require_fetch.VERSION,
			isRunningInCi: ciFlag,
			...getRuntimeMetadata()
		};
		const client = getPostHogClient();
		if (client && !require_logger.getEnvBool("IS_TESTING")) try {
			client.capture({
				distinctId: this.id,
				event: eventName,
				properties: {
					...propertiesWithMetadata,
					$set: personProperties
				}
			});
			client.flush().catch(() => {});
		} catch (error) {
			require_logger.logger.debug(`PostHog capture error: ${error}`);
		}
		require_fetch.fetchWithProxy(require_fetch.R_ENDPOINT, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				event: eventName,
				environment: require_logger.getEnvString("NODE_ENV", "development"),
				email: personProperties.email,
				meta: {
					user_id: this.id,
					...propertiesWithMetadata
				}
			})
		}).catch(() => {});
	}
	async shutdown() {
		if (isShuttingDown) return;
		const client = getPostHogClient();
		if (!client) return;
		isShuttingDown = true;
		try {
			await client.shutdown();
		} catch (error) {
			require_logger.logger.debug(`PostHog shutdown error: ${error}`);
		}
	}
	/**
	* This is a separate endpoint to save consent used only for redteam data synthesis for "harmful" plugins.
	*/
	async saveConsent(email, metadata) {
		try {
			const response = await require_fetch.fetchWithTimeout(require_fetch.CONSENT_ENDPOINT, {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({
					email,
					metadata
				})
			}, TELEMETRY_TIMEOUT_MS);
			if (!response.ok) throw new Error(`Failed to save consent: ${response.statusText}`);
		} catch (err) {
			require_logger.logger.debug(`Failed to save consent: ${err.message}`);
		}
	}
};
const telemetry = new Telemetry();
const TELEMETRY_INSTANCE_KEY = Symbol.for("promptfoo.telemetry.instance");
const SHUTDOWN_HANDLER_KEY = Symbol.for("promptfoo.telemetry.shutdownHandler");
process[TELEMETRY_INSTANCE_KEY] = telemetry;
if (!process[SHUTDOWN_HANDLER_KEY]) {
	process[SHUTDOWN_HANDLER_KEY] = true;
	process.once("beforeExit", () => {
		const instance = process[TELEMETRY_INSTANCE_KEY];
		if (instance) instance.shutdown().catch(() => {});
	});
}
//#endregion
Object.defineProperty(exports, "telemetry", {
	enumerable: true,
	get: function() {
		return telemetry;
	}
});
Object.defineProperty(exports, "telemetry_exports", {
	enumerable: true,
	get: function() {
		return telemetry_exports;
	}
});

//# sourceMappingURL=telemetry-rAm0hXxf.cjs.map