import { C as writeJsonArray, x as readJsonArray } from "./session-store-DWxJ5Pof.js";
import path from "path";
import { createHash, createHmac } from "crypto";
//#region src/core/webhooks.ts
function subsPath(dataDir) {
	return path.join(dataDir, ".agentic", "webhooks.json");
}
function failuresPath(dataDir) {
	return path.join(dataDir, ".agentic", "webhook-failures.json");
}
function loadWebhooks(dataDir) {
	return readJsonArray(subsPath(dataDir), "subscriptions");
}
/** A subscription matches an event by exact name, "*", or a "prefix.*" pattern. */
function matchSubscriptions(subs, event) {
	return subs.filter((s) => s.events.some((pat) => {
		if (pat === "*" || pat === event) return true;
		if (pat.endsWith(".*")) return event.startsWith(pat.slice(0, -1));
		return false;
	}));
}
function signPayload(secret, body) {
	return createHmac("sha256", secret).update(body).digest("hex");
}
function loadFailures(dataDir) {
	return readJsonArray(failuresPath(dataDir), "failures");
}
async function deliver(sub, event, payload) {
	const body = JSON.stringify({
		event,
		payload,
		deliveredAt: (/* @__PURE__ */ new Date()).toISOString()
	});
	const headers = {
		"Content-Type": "application/json",
		"X-DXCRM-Event": event
	};
	if (sub.secret) headers["X-DXCRM-Signature"] = `sha256=${signPayload(sub.secret, body)}`;
	try {
		const res = await fetch(sub.url, {
			method: "POST",
			headers,
			body
		});
		if (!res.ok) return {
			ok: false,
			error: `HTTP ${res.status}`
		};
		return { ok: true };
	} catch (err) {
		return {
			ok: false,
			error: err.message
		};
	}
}
/** Emit an event to all matching subscriptions; queue failures for replay. */
async function emitEvent(dataDir, event, payload) {
	const matched = matchSubscriptions(loadWebhooks(dataDir), event);
	if (matched.length === 0) return;
	const failures = loadFailures(dataDir);
	for (const sub of matched) {
		const r = await deliver(sub, event, payload);
		if (!r.ok) failures.push({
			id: `whf_${createHash("sha256").update(`${sub.id}:${event}:${Date.now()}`).digest("hex").slice(0, 10)}`,
			subscriptionId: sub.id,
			url: sub.url,
			...sub.secret ? { secret: sub.secret } : {},
			event,
			payload,
			attempts: 1,
			lastError: r.error ?? "unknown",
			queuedAt: (/* @__PURE__ */ new Date()).toISOString()
		});
	}
	if (failures.length > 0) writeJsonArray(failuresPath(dataDir), "failures", failures);
}
//#endregion
export { emitEvent };

//# sourceMappingURL=webhooks-sWZ8CJtR.js.map