import { TARGET_MODULE_AUTOMATION, TARGET_MODULE_DATABASE } from "../alerts/alertsModel"; import type { NotificationTarget } from "../alerts/alertsModel"; declare module "../alerts/alertsModel" { interface NotificationTarget { application?: string; } } const str = (v: unknown): string => (typeof v === "string" ? v : ""); export type TargetRoute = | { surface: "database"; key: string; viewId?: string } | { surface: "intelligence"; key: string; viewId?: never } | { surface: "automation"; autoId: string; tab: string } | { surface: "map"; routeId: string }; export const OPEN_RETRY_MS = [0, 250, 700, 1500, 2600] as const; /** Retry while the destination loads, stopping after success or cancellation. */ export function retryEmit( emit: () => boolean | void, schedule: (fn: () => void, ms: number) => number = setTimeout as never, ladder: readonly number[] = OPEN_RETRY_MS ): () => void { const timers: number[] = []; let done = false; for (const ms of ladder) { timers.push( schedule(() => { if (done) return; if (emit() === true) done = true; }, ms) ); } return () => { done = true; for (const t of timers) clearTimeout(t as never); }; } export function routeForTarget(t: NotificationTarget | null): TargetRoute | null { if (!t || !str(t.module).trim() || !str(t.id).trim()) return null; if (t.module === "intelligence") { const query = new URLSearchParams({ path: t.id }); if (str(t.tab).trim()) query.set("proposal", t.tab!.trim()); return { surface: "intelligence", key: `intelligence?${query}` }; } if (t.module === TARGET_MODULE_AUTOMATION) return { surface: "automation", autoId: t.id, tab: str(t.tab).trim() || "runs" }; if (t.module === TARGET_MODULE_DATABASE) { const viewId = str(t.tab).trim(); return { surface: "database", key: t.id, ...(viewId ? { viewId } : {}) }; } const application = str(t.application).trim(); // A Routing App address takes precedence over the legacy map destination. if (t.module === "customer_data" && t.tab === "map" && application) { const query = new URLSearchParams({ database: "customer_data", application, route: t.id }); return { surface: "database", key: `app?${query}` }; } if (t.module.startsWith("ut_") && str(t.id).trim()) { const query = new URLSearchParams({ database: t.module, record: t.id }); return { surface: "database", key: `data?${query}` }; } if (t.module === "customer_data" && t.tab === "map") return { surface: "map", routeId: t.id }; return null; }